signature.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. import { describe, expect, test } from "bun:test"
  2. import { Effect, Schema } from "effect"
  3. import { CodeMode, Tool } from "../src/index.js"
  4. import { inputTypeScript, jsonSchemaToTypeScript, outputTypeScript } from "../src/tool-schema.js"
  5. // A raw JSON Schema tool in the shape an MCP adapter produces: render-only input schema
  6. // whose property descriptions and constraints must surface as JSDoc in pretty signatures.
  7. const listIssues = Tool.make({
  8. description: "List issues in a repository",
  9. input: {
  10. type: "object",
  11. properties: {
  12. owner: { type: "string", description: "Repository owner" },
  13. after: { type: "string", description: "Cursor from the previous response's pageInfo" },
  14. perPage: { type: "number", description: "Results per page", default: 30 },
  15. labels: { type: "array", items: { type: "string" }, description: "Filter by labels", minItems: 1, maxItems: 10 },
  16. state: { type: "string", enum: ["open", "closed"] },
  17. },
  18. required: ["owner"],
  19. },
  20. run: () => Effect.succeed("[]"),
  21. })
  22. // An Effect Schema tool whose field annotations must flow through the emitted JSON Schema.
  23. const lookupOrder = Tool.make({
  24. description: "Look up an order",
  25. input: Schema.Struct({
  26. id: Schema.String.annotate({ description: "Order identifier" }),
  27. verbose: Schema.optionalKey(Schema.Boolean),
  28. }),
  29. output: Schema.Struct({
  30. status: Schema.String.annotate({ description: "Current order status" }),
  31. }),
  32. run: () => Effect.succeed({ status: "open" }),
  33. })
  34. describe("pretty signature rendering", () => {
  35. test("described fields get JSDoc comments; undescribed and untagged fields get none", () => {
  36. expect(inputTypeScript(listIssues, true)).toBe(
  37. [
  38. "{",
  39. " /** Repository owner */",
  40. " owner: string,",
  41. " /** Cursor from the previous response's pageInfo */",
  42. " after?: string,",
  43. " /**",
  44. " * Results per page",
  45. " * @default 30",
  46. " */",
  47. " perPage?: number,",
  48. " /**",
  49. " * Filter by labels",
  50. " * @minItems 1",
  51. " * @maxItems 10",
  52. " */",
  53. " labels?: Array<string>,",
  54. ' state?: "open" | "closed",',
  55. "}",
  56. ].join("\n"),
  57. )
  58. })
  59. test("compact mode output is unchanged by the pretty machinery", () => {
  60. expect(inputTypeScript(listIssues)).toBe(
  61. '{ owner: string; after?: string; perPage?: number; labels?: Array<string>; state?: "open" | "closed" }',
  62. )
  63. expect(inputTypeScript(lookupOrder)).toBe("{ id: string; verbose?: boolean }")
  64. expect(outputTypeScript(lookupOrder)).toBe("{ status: string }")
  65. })
  66. test("nested objects recurse with increasing indent and their own JSDoc", () => {
  67. const pretty = jsonSchemaToTypeScript(
  68. {
  69. type: "object",
  70. properties: {
  71. filter: {
  72. type: "object",
  73. description: "Search filter",
  74. properties: { state: { type: "string", description: "Issue state" } },
  75. },
  76. },
  77. },
  78. true,
  79. )
  80. expect(pretty).toBe(
  81. [
  82. "{",
  83. " /** Search filter */",
  84. " filter?: {",
  85. " /** Issue state */",
  86. " state?: string,",
  87. " },",
  88. "}",
  89. ].join("\n"),
  90. )
  91. })
  92. test("Effect Schema annotations become JSDoc on input and output fields", () => {
  93. expect(inputTypeScript(lookupOrder, true)).toBe(
  94. ["{", " /** Order identifier */", " id: string,", " verbose?: boolean,", "}"].join("\n"),
  95. )
  96. expect(outputTypeScript(lookupOrder, true)).toBe(
  97. ["{", " /** Current order status */", " status: string,", "}"].join("\n"),
  98. )
  99. })
  100. test("constraints TypeScript cannot express surface as JSDoc tags", () => {
  101. const pretty = jsonSchemaToTypeScript(
  102. {
  103. type: "object",
  104. properties: {
  105. legacy: { type: "string", deprecated: true },
  106. homepage: { type: "string", format: "uri" },
  107. tags: { type: "array", items: { type: "string" }, minItems: 2, maxItems: 5, default: ["a", "b"] },
  108. },
  109. },
  110. true,
  111. )
  112. expect(pretty).toContain(" /** @deprecated */\n legacy?: string")
  113. expect(pretty).toContain(" /** @format uri */\n homepage?: string")
  114. expect(pretty).toContain(
  115. [
  116. " /**",
  117. ' * @default ["a","b"]',
  118. " * @minItems 2",
  119. " * @maxItems 5",
  120. " */",
  121. " tags?: Array<string>",
  122. ].join("\n"),
  123. )
  124. })
  125. test("skips an unserializable default rather than emitting a broken tag", () => {
  126. const pretty = jsonSchemaToTypeScript(
  127. { type: "object", properties: { size: { type: "number", default: 1n } } },
  128. true,
  129. )
  130. expect(pretty).toBe(["{", " size?: number,", "}"].join("\n"))
  131. })
  132. test("neutralizes */ inside descriptions so nothing closes the comment early", () => {
  133. const pretty = jsonSchemaToTypeScript(
  134. { type: "object", properties: { note: { type: "string", description: "Ends */ early" } } },
  135. true,
  136. )
  137. expect(pretty).toContain(" /** Ends * / early */")
  138. expect(pretty).not.toContain("Ends */")
  139. })
  140. test("multiline descriptions become *-prefixed blocks with blank edges trimmed", () => {
  141. const pretty = jsonSchemaToTypeScript(
  142. {
  143. type: "object",
  144. properties: { query: { type: "string", description: "\nFirst line\n\nSecond line\n" } },
  145. },
  146. true,
  147. )
  148. expect(pretty).toBe(
  149. ["{", " /**", " * First line", " *", " * Second line", " */", " query?: string,", "}"].join("\n"),
  150. )
  151. })
  152. test("stays total on cyclic $refs and pathological nesting in both modes", () => {
  153. const cyclic = {
  154. $ref: "#/$defs/Node",
  155. $defs: { Node: { type: "object", properties: { child: { $ref: "#/$defs/Node" }, name: { type: "string" } } } },
  156. } as const
  157. expect(jsonSchemaToTypeScript(cyclic)).toBe("{ child?: unknown; name?: string }")
  158. expect(jsonSchemaToTypeScript(cyclic, true)).toContain("child?: unknown")
  159. let deep: Record<string, unknown> = { type: "string" }
  160. for (let level = 0; level < 12; level += 1) deep = { type: "object", properties: { next: deep } }
  161. for (const pretty of [false, true]) {
  162. const rendered = jsonSchemaToTypeScript(deep, pretty)
  163. expect(rendered).toContain("unknown")
  164. expect(rendered).toContain("next?:")
  165. }
  166. })
  167. test("intersects ref and union siblings instead of discarding them", () => {
  168. expect(
  169. jsonSchemaToTypeScript({
  170. $ref: "#/$defs/User",
  171. properties: { active: { type: "boolean" } },
  172. required: ["active"],
  173. $defs: {
  174. User: { type: "object", properties: { id: { type: "string" } }, required: ["id"] },
  175. },
  176. }),
  177. ).toBe("{ id: string } & { active: boolean }")
  178. expect(
  179. jsonSchemaToTypeScript({
  180. type: "object",
  181. properties: { common: { type: "boolean" } },
  182. required: ["common"],
  183. anyOf: [
  184. { type: "object", properties: { name: { type: "string" } }, required: ["name"] },
  185. { type: "object", properties: { count: { type: "number" } }, required: ["count"] },
  186. ],
  187. }),
  188. ).toBe("({ name: string } | { count: number }) & { common: boolean }")
  189. expect(jsonSchemaToTypeScript({ $ref: "https://example.com/schema.json" })).toBe("unknown")
  190. expect(
  191. jsonSchemaToTypeScript({
  192. $ref: "#/$defs/User/properties/id",
  193. $defs: { User: { type: "object" }, id: { type: "string" } },
  194. }),
  195. ).toBe("unknown")
  196. expect(
  197. jsonSchemaToTypeScript({
  198. type: ["object", "null"],
  199. properties: { name: { type: "string" } },
  200. }),
  201. ).toBe("{ name?: string } | null")
  202. })
  203. })
  204. describe("non-identifier property names render as quoted keys", () => {
  205. // MCP-style schemas routinely carry property names that are not bare TS identifiers
  206. // (`foo-bar`, `@type`, dotted names); the rendered signature must quote them so the
  207. // model sees a valid TypeScript object type. Bare identifiers stay unquoted.
  208. const rawSchema = {
  209. type: "object",
  210. properties: {
  211. "foo-bar": { type: "string" },
  212. "@type": { type: "string" },
  213. "x.y": { type: "number", description: "Dotted name" },
  214. "123": { type: "number" },
  215. plain: { type: "boolean" },
  216. },
  217. required: ["@type"],
  218. } as const
  219. test("compact rendering quotes non-identifier keys and leaves identifiers bare", () => {
  220. expect(jsonSchemaToTypeScript(rawSchema)).toBe(
  221. '{ "123"?: number; "foo-bar"?: string; "@type": string; "x.y"?: number; plain?: boolean }',
  222. )
  223. })
  224. test("pretty rendering quotes non-identifier keys and keeps their JSDoc", () => {
  225. expect(jsonSchemaToTypeScript(rawSchema, true)).toBe(
  226. [
  227. "{",
  228. ' "123"?: number,',
  229. ' "foo-bar"?: string,',
  230. ' "@type": string,',
  231. " /** Dotted name */",
  232. ' "x.y"?: number,',
  233. " plain?: boolean,",
  234. "}",
  235. ].join("\n"),
  236. )
  237. })
  238. test("JSON Schema input and output signatures of a tool both quote", () => {
  239. const tool = Tool.make({
  240. description: "Adapter tool with awkward field names",
  241. input: rawSchema,
  242. output: {
  243. type: "object",
  244. properties: { "content-type": { type: "string" } },
  245. required: ["content-type"],
  246. } as const,
  247. run: () => Effect.succeed({ "content-type": "text/plain" }),
  248. })
  249. expect(inputTypeScript(tool)).toContain('"foo-bar"?: string')
  250. expect(outputTypeScript(tool)).toBe('{ "content-type": string }')
  251. expect(outputTypeScript(tool, true)).toBe(["{", ' "content-type": string,', "}"].join("\n"))
  252. })
  253. test("Effect Schema structs with non-identifier field names quote too", () => {
  254. const tool = Tool.make({
  255. description: "Schema tool with awkward field names",
  256. input: Schema.Struct({ "foo-bar": Schema.String, plain: Schema.optionalKey(Schema.Number) }),
  257. run: () => Effect.succeed(null),
  258. })
  259. expect(inputTypeScript(tool)).toBe('{ "foo-bar": string; plain?: number }')
  260. expect(inputTypeScript(tool, true)).toBe(["{", ' "foo-bar": string,', " plain?: number,", "}"].join("\n"))
  261. })
  262. })
  263. describe("union schemas render every alternative", () => {
  264. test("anyOf with a number branch keeps sibling alternatives", () => {
  265. const schema = {
  266. anyOf: [{ type: "string" }, { type: "number" }],
  267. } as const
  268. expect(jsonSchemaToTypeScript(schema)).toBe("string | number")
  269. expect(jsonSchemaToTypeScript(schema, true)).toBe("string | number")
  270. })
  271. test("nullable numeric unions keep null", () => {
  272. const schema = {
  273. oneOf: [{ type: "number" }, { type: "null" }],
  274. } as const
  275. expect(jsonSchemaToTypeScript(schema)).toBe("number | null")
  276. expect(jsonSchemaToTypeScript(schema, true)).toBe("number | null")
  277. })
  278. test("tool input and output signatures preserve numeric unions", () => {
  279. const tool = Tool.make({
  280. description: "Tool with numeric unions",
  281. input: {
  282. type: "object",
  283. properties: {
  284. value: { anyOf: [{ type: "string" }, { type: "number" }] },
  285. },
  286. } as const,
  287. output: { anyOf: [{ type: "number" }, { type: "boolean" }] } as const,
  288. run: () => Effect.succeed(1),
  289. })
  290. expect(inputTypeScript(tool)).toBe("{ value?: string | number }")
  291. expect(outputTypeScript(tool)).toBe("number | boolean")
  292. })
  293. test("allOf renders intersections with parenthesized union members", () => {
  294. const schema = {
  295. allOf: [{ type: "object", properties: { id: { type: "string" } } }, { type: ["string", "null"] }],
  296. } as const
  297. expect(jsonSchemaToTypeScript(schema)).toBe("{ id?: string } & (string | null)")
  298. })
  299. test("allOf does not discard an unresolved constraint", () => {
  300. expect(jsonSchemaToTypeScript({ allOf: [{ type: "string" }, { $ref: "https://example.com/external.json" }] })).toBe(
  301. "unknown",
  302. )
  303. expect(
  304. jsonSchemaToTypeScript({
  305. allOf: [{ type: "string" }, { allOf: [{ $ref: "https://example.com/external.json" }] }],
  306. }),
  307. ).toBe("unknown")
  308. expect(
  309. jsonSchemaToTypeScript({
  310. type: "string",
  311. allOf: [{ $ref: "#/$defs/Constraint" }],
  312. $defs: { Constraint: { description: "TypeScript-neutral constraint" } },
  313. }),
  314. ).toBe("string")
  315. })
  316. })
  317. describe("JSDoc signatures in catalogs and search results", () => {
  318. const runtime = CodeMode.make({ tools: { github: { list_issues: listIssues }, orders: { lookup: lookupOrder } } })
  319. const search = async (query: string) => {
  320. const result = await Effect.runPromise(
  321. runtime.execute(`return await tools.$codemode.search({ query: ${JSON.stringify(query)} })`),
  322. )
  323. expect(result.ok).toBe(true)
  324. if (!result.ok) throw new Error("search failed")
  325. return result.value as { items: Array<{ path: string; signature: string }>; remaining: number }
  326. }
  327. test("a raw JSON Schema (MCP-style) tool's result signature carries field JSDoc and tags", async () => {
  328. const { items } = await search("list issues repository")
  329. const item = items.find(({ path }) => path === "tools.github.list_issues")!
  330. expect(item.signature).toBe(
  331. [
  332. "tools.github.list_issues(input: {",
  333. " /** Repository owner */",
  334. " owner: string,",
  335. " /** Cursor from the previous response's pageInfo */",
  336. " after?: string,",
  337. " /**",
  338. " * Results per page",
  339. " * @default 30",
  340. " */",
  341. " perPage?: number,",
  342. " /**",
  343. " * Filter by labels",
  344. " * @minItems 1",
  345. " * @maxItems 10",
  346. " */",
  347. " labels?: Array<string>,",
  348. ' state?: "open" | "closed",',
  349. "}): Promise<unknown>",
  350. ].join("\n"),
  351. )
  352. })
  353. test("an annotated Effect Schema tool's result signature carries field JSDoc (exact-path lookup too)", async () => {
  354. for (const query of ["look up order", "tools.orders.lookup"]) {
  355. const { items } = await search(query)
  356. const item = items.find(({ path }) => path === "tools.orders.lookup")!
  357. expect(item.signature).toBe(
  358. [
  359. "tools.orders.lookup(input: {",
  360. " /** Order identifier */",
  361. " id: string,",
  362. " verbose?: boolean,",
  363. "}): Promise<{",
  364. " /** Current order status */",
  365. " status: string,",
  366. "}>",
  367. ].join("\n"),
  368. )
  369. }
  370. })
  371. test("the inline catalog uses the same JSDoc signatures", async () => {
  372. const instructions = runtime.instructions()
  373. const github = (await search("list issues repository")).items.find(
  374. ({ path }) => path === "tools.github.list_issues",
  375. )!
  376. const orders = (await search("look up order")).items.find(({ path }) => path === "tools.orders.lookup")!
  377. expect(instructions).toContain(` - ${github.signature} // List issues in a repository`)
  378. expect(instructions).toContain(` - ${orders.signature} // Look up an order`)
  379. expect(instructions).toContain("/** Repository owner */")
  380. })
  381. })
  382. describe("non-identifier tool paths", () => {
  383. const resolveLibrary = Tool.make({
  384. description: "Resolve a Context7 library ID",
  385. input: {
  386. type: "object",
  387. properties: {
  388. query: { type: "string" },
  389. libraryName: { type: "string" },
  390. },
  391. required: ["query", "libraryName"],
  392. } as const,
  393. run: () => Effect.succeed("/reactjs/react.dev"),
  394. })
  395. const runtime = CodeMode.make({ tools: { context7: { "resolve-library-id": resolveLibrary } } })
  396. test("inline catalog uses bracket notation for dashed tool names", () => {
  397. const instructions = runtime.instructions()
  398. expect(instructions).toContain(
  399. 'tools.context7["resolve-library-id"](input: {\n query: string,\n libraryName: string,\n}): Promise<unknown>',
  400. )
  401. expect(instructions).toContain("Do not infer or normalize tool names")
  402. expect(instructions).toContain("bracket notation and quotes are part of the path")
  403. expect(instructions).not.toContain("tools.context7.resolve-library-id")
  404. expect(instructions).not.toContain("tools.context7.resolve_library_id")
  405. })
  406. test("search results return callable bracket-notation paths and signatures", async () => {
  407. const result = await Effect.runPromise(
  408. runtime.execute(`return await tools.$codemode.search({ query: "resolve library" })`),
  409. )
  410. expect(result.ok).toBe(true)
  411. if (!result.ok) throw new Error("search failed")
  412. const value = result.value as { items: Array<{ path: string; signature: string }> }
  413. expect(value.items[0]?.path).toBe('tools.context7["resolve-library-id"]')
  414. expect(value.items[0]?.signature).toContain('tools.context7["resolve-library-id"](input: {')
  415. })
  416. })