json-schema.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. import { describe, expect, it } from "vitest";
  2. import { modelInputMessageJsonSchema } from "@zcode/contracts";
  3. import { validateJsonSchemaValue } from "../src/tool/json-schema.js";
  4. describe("tool JSON schema validator", () => {
  5. it("accepts base64-only video message blocks and rejects URL fields", () => {
  6. const message = {
  7. role: "user",
  8. content: [
  9. {
  10. type: "video",
  11. mediaType: "video/mp4",
  12. dataUrl: "data:video/mp4;base64,dmlkZW8=",
  13. source: { id: "video-1", kind: "inline" },
  14. },
  15. ],
  16. };
  17. expect(validateJsonSchemaValue(message, modelInputMessageJsonSchema).valid).toBe(true);
  18. expect(
  19. validateJsonSchemaValue(
  20. {
  21. ...message,
  22. content: [{ ...message.content[0], url: "https://example.test/video.mp4" }],
  23. },
  24. modelInputMessageJsonSchema,
  25. ).valid,
  26. ).toBe(false);
  27. });
  28. it("accepts blockIndex on assistant text and reasoning blocks and still rejects unknown fields", () => {
  29. const message = {
  30. role: "assistant",
  31. content: [
  32. { type: "reasoning", text: "think", providerOptions: {}, blockIndex: 0 },
  33. { type: "text", text: "answer", blockIndex: 1 },
  34. ],
  35. toolCalls: [{ id: "call-1", name: "Read", input: {}, blockIndex: 2 }],
  36. };
  37. expect(validateJsonSchemaValue(message, modelInputMessageJsonSchema).valid).toBe(true);
  38. for (const block of [
  39. { type: "text", text: "answer", blockIndex: -1 },
  40. { type: "text", text: "answer", blockIndex: 1.5 },
  41. { type: "text", text: "answer", order: 1 },
  42. { type: "reasoning", text: "think", order: 1 },
  43. ]) {
  44. expect(
  45. validateJsonSchemaValue({ ...message, content: [block] }, modelInputMessageJsonSchema)
  46. .valid,
  47. ).toBe(false);
  48. }
  49. });
  50. it("validates object properties, required fields, and additionalProperties", () => {
  51. const schema = {
  52. type: "object",
  53. properties: {
  54. status: { enum: ["ok", "failed"] },
  55. count: { type: "integer", minimum: 0 },
  56. },
  57. required: ["status", "count"],
  58. additionalProperties: false,
  59. };
  60. expect(validateJsonSchemaValue({ status: "ok", count: 2 }, schema).valid).toBe(true);
  61. const invalid = validateJsonSchemaValue({ status: "maybe", extra: true }, schema);
  62. expect(invalid.valid).toBe(false);
  63. expect(invalid.errors).toEqual(
  64. expect.arrayContaining([
  65. "$.count is required",
  66. '$.status must be one of "ok", "failed"',
  67. "$.extra is not allowed",
  68. ]),
  69. );
  70. expect(invalid.issues).toEqual([
  71. {
  72. code: "invalid_value",
  73. values: ["ok", "failed"],
  74. path: ["status"],
  75. message: 'Invalid option: expected one of "ok"|"failed"',
  76. },
  77. {
  78. expected: "number",
  79. code: "invalid_type",
  80. path: ["count"],
  81. message: "Invalid input: expected number, received undefined",
  82. },
  83. {
  84. code: "unrecognized_keys",
  85. keys: ["extra"],
  86. path: [],
  87. message: 'Unrecognized key: "extra"',
  88. },
  89. ]);
  90. });
  91. it("validates oneOf variants and array item schemas", () => {
  92. const schema = {
  93. oneOf: [
  94. { type: "string" },
  95. {
  96. type: "object",
  97. properties: {
  98. values: {
  99. type: "array",
  100. items: { type: "integer" },
  101. },
  102. },
  103. required: ["values"],
  104. additionalProperties: false,
  105. },
  106. ],
  107. };
  108. expect(validateJsonSchemaValue("plain", schema).valid).toBe(true);
  109. expect(validateJsonSchemaValue({ values: [1, 2, 3] }, schema).valid).toBe(true);
  110. const invalid = validateJsonSchemaValue({ values: [1, "bad"] }, schema);
  111. expect(invalid.errors).toContain("$ must match exactly one oneOf schema, matched 0");
  112. expect(invalid.issues).toEqual([
  113. {
  114. code: "invalid_union",
  115. errors: [
  116. [
  117. {
  118. expected: "string",
  119. code: "invalid_type",
  120. path: [],
  121. message: "Invalid input: expected string, received object",
  122. },
  123. ],
  124. [
  125. {
  126. expected: "number",
  127. code: "invalid_type",
  128. path: ["values", 1],
  129. message: "Invalid input: expected number, received string",
  130. },
  131. ],
  132. ],
  133. path: [],
  134. message: "Invalid input",
  135. },
  136. ]);
  137. });
  138. it("validates anyOf variants when at least one branch matches", () => {
  139. // 工具契约的 union 与 nullable 字段生成 anyOf(00-tool-change-chain.md「工具 JSON Schema 生成」)。
  140. const schema = {
  141. type: "object",
  142. properties: {
  143. limit: { anyOf: [{ type: "integer", minimum: 1 }, { type: "null" }] },
  144. // 两个分支都匹配时,anyOf 通过,oneOf 不通过。
  145. label: { anyOf: [{ type: "string" }, { type: "string", minLength: 1 }] },
  146. },
  147. additionalProperties: false,
  148. };
  149. expect(validateJsonSchemaValue({ limit: 3, label: "x" }, schema).valid).toBe(true);
  150. expect(validateJsonSchemaValue({ limit: null }, schema).valid).toBe(true);
  151. const invalid = validateJsonSchemaValue({ limit: "many" }, schema);
  152. expect(invalid.errors).toEqual(["$.limit must match at least one anyOf schema"]);
  153. expect(invalid.issues).toEqual([
  154. {
  155. code: "invalid_union",
  156. errors: [
  157. [
  158. {
  159. expected: "number",
  160. code: "invalid_type",
  161. path: [],
  162. message: "Invalid input: expected number, received string",
  163. },
  164. ],
  165. [
  166. {
  167. expected: "null",
  168. code: "invalid_type",
  169. path: [],
  170. message: "Invalid input: expected null, received string",
  171. },
  172. ],
  173. ],
  174. path: ["limit"],
  175. message: "Invalid input",
  176. },
  177. ]);
  178. });
  179. it.each(["anyOf", "oneOf"])("checks sibling keywords next to %s", (keyword) => {
  180. // MCP schema 常把“至少给一个”的约束写成 union,旁边仍有 required / additionalProperties。
  181. const schema = {
  182. type: "object",
  183. properties: {
  184. count: { type: "integer" },
  185. a: { type: "string" },
  186. b: { type: "string" },
  187. },
  188. required: ["count"],
  189. additionalProperties: false,
  190. [keyword]: [{ required: ["a"] }, { required: ["b"] }],
  191. };
  192. expect(validateJsonSchemaValue({ count: 1, a: "x" }, schema).valid).toBe(true);
  193. const invalid = validateJsonSchemaValue({ a: "x", extra: 1 }, schema);
  194. expect(invalid.errors).toEqual(["$.count is required", "$.extra is not allowed"]);
  195. expect(invalid.issues.map((issue) => [issue.code, issue.path])).toEqual([
  196. ["invalid_type", ["count"]],
  197. ["unrecognized_keys", []],
  198. ]);
  199. });
  200. it("checks anyOf and oneOf on the same node independently", () => {
  201. // MCP schema 可以在同一节点同时写 anyOf 与 oneOf,两个约束都要满足。
  202. const schema = {
  203. type: "object",
  204. properties: { mode: { type: "string" } },
  205. anyOf: [{ required: ["mode"] }],
  206. oneOf: [
  207. { properties: { mode: { const: "read" } } },
  208. { properties: { mode: { const: "write" } } },
  209. { properties: { mode: { enum: ["write", "sync"] } } },
  210. ],
  211. };
  212. expect(validateJsonSchemaValue({ mode: "read" }, schema).valid).toBe(true);
  213. expect(validateJsonSchemaValue({ mode: "sync" }, schema).valid).toBe(true);
  214. expect(validateJsonSchemaValue({ mode: "delete" }, schema).errors).toEqual([
  215. "$ must match exactly one oneOf schema, matched 0",
  216. ]);
  217. expect(validateJsonSchemaValue({ mode: "write" }, schema).errors).toEqual([
  218. "$ must match exactly one oneOf schema, matched 2",
  219. ]);
  220. // 缺 mode 时 oneOf 三个分支都匹配(properties 不要求字段存在),所以两个约束各报一次。
  221. const missing = validateJsonSchemaValue({}, schema);
  222. expect(missing.errors).toEqual([
  223. "$ must match at least one anyOf schema",
  224. "$ must match exactly one oneOf schema, matched 3",
  225. ]);
  226. expect(missing.issues.map((issue) => [issue.code, issue.path])).toEqual([
  227. ["invalid_union", []],
  228. ["invalid_union", []],
  229. ]);
  230. });
  231. it("emits source-compatible integer and multi-type issues", () => {
  232. expect(validateJsonSchemaValue(1.5, { type: "integer" }).issues).toEqual([
  233. {
  234. expected: "int",
  235. format: "safeint",
  236. code: "invalid_type",
  237. path: [],
  238. message: "Invalid input: expected int, received number",
  239. },
  240. ]);
  241. expect(validateJsonSchemaValue(true, { type: ["string", "number"] }).issues).toEqual([
  242. {
  243. code: "invalid_union",
  244. errors: [
  245. [
  246. {
  247. expected: "string",
  248. code: "invalid_type",
  249. path: [],
  250. message: "Invalid input: expected string, received boolean",
  251. },
  252. ],
  253. [
  254. {
  255. expected: "number",
  256. code: "invalid_type",
  257. path: [],
  258. message: "Invalid input: expected number, received boolean",
  259. },
  260. ],
  261. ],
  262. path: [],
  263. message: "Invalid input",
  264. },
  265. ]);
  266. });
  267. it("does not duplicate type issues after enum or const value constraints fail", () => {
  268. const invalid = validateJsonSchemaValue(
  269. {
  270. mode: 7,
  271. },
  272. {
  273. type: "object",
  274. properties: {
  275. mode: { type: "string", enum: ["fast", "safe"] },
  276. literal: { type: "string", const: "fixed" },
  277. },
  278. required: ["mode", "literal"],
  279. additionalProperties: false,
  280. },
  281. );
  282. expect(invalid.errors).toEqual([
  283. "$.literal is required",
  284. '$.mode must be one of "fast", "safe"',
  285. "$.mode must be string",
  286. ]);
  287. expect(invalid.issues).toEqual([
  288. {
  289. code: "invalid_value",
  290. values: ["fast", "safe"],
  291. path: ["mode"],
  292. message: 'Invalid option: expected one of "fast"|"safe"',
  293. },
  294. {
  295. code: "invalid_value",
  296. values: ["fixed"],
  297. path: ["literal"],
  298. message: 'Invalid input: expected "fixed"',
  299. },
  300. ]);
  301. });
  302. it("emits source-compatible upper-bound issues for every supported value origin", () => {
  303. const invalid = validateJsonSchemaValue(
  304. {
  305. count: 3,
  306. label: "long",
  307. values: [1, 2],
  308. },
  309. {
  310. type: "object",
  311. properties: {
  312. count: { type: "number", maximum: 2 },
  313. label: { type: "string", maxLength: 3 },
  314. values: { type: "array", maxItems: 1 },
  315. },
  316. required: ["count", "label", "values"],
  317. additionalProperties: false,
  318. },
  319. );
  320. expect(invalid.issues).toEqual([
  321. {
  322. origin: "number",
  323. code: "too_big",
  324. maximum: 2,
  325. inclusive: true,
  326. path: ["count"],
  327. message: "Too big: expected number to be <=2",
  328. },
  329. {
  330. origin: "string",
  331. code: "too_big",
  332. maximum: 3,
  333. inclusive: true,
  334. path: ["label"],
  335. message: "Too big: expected string to have <=3 characters",
  336. },
  337. {
  338. origin: "array",
  339. code: "too_big",
  340. maximum: 1,
  341. inclusive: true,
  342. path: ["values"],
  343. message: "Too big: expected array to have <=1 items",
  344. },
  345. ]);
  346. });
  347. });