signature.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. import { describe, expect, test } from "bun:test"
  2. import { Effect, Schema } from "effect"
  3. import { CodeMode } from "../src/index.js"
  4. import { Tool, inputTypeScript, jsonSchemaToTypeScript, outputTypeScript } from "../src/tool.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. [" /**", ' * @default ["a","b"]', " * @minItems 2", " * @maxItems 5", " */", " tags?: Array<string>"].join("\n"),
  116. )
  117. })
  118. test("skips an unserializable default rather than emitting a broken tag", () => {
  119. const pretty = jsonSchemaToTypeScript(
  120. { type: "object", properties: { size: { type: "number", default: 1n } } },
  121. true,
  122. )
  123. expect(pretty).toBe(["{", " size?: number", "}"].join("\n"))
  124. })
  125. test("neutralizes */ inside descriptions so nothing closes the comment early", () => {
  126. const pretty = jsonSchemaToTypeScript(
  127. { type: "object", properties: { note: { type: "string", description: "Ends */ early" } } },
  128. true,
  129. )
  130. expect(pretty).toContain(" /** Ends * / early */")
  131. expect(pretty).not.toContain("Ends */")
  132. })
  133. test("multiline descriptions become *-prefixed blocks with blank edges trimmed", () => {
  134. const pretty = jsonSchemaToTypeScript(
  135. {
  136. type: "object",
  137. properties: { query: { type: "string", description: "\nFirst line\n\nSecond line\n" } },
  138. },
  139. true,
  140. )
  141. expect(pretty).toBe(
  142. ["{", " /**", " * First line", " *", " * Second line", " */", " query?: string", "}"].join("\n"),
  143. )
  144. })
  145. test("stays total on cyclic $refs and pathological nesting in both modes", () => {
  146. const cyclic = {
  147. $ref: "#/$defs/Node",
  148. $defs: { Node: { type: "object", properties: { child: { $ref: "#/$defs/Node" }, name: { type: "string" } } } },
  149. } as const
  150. expect(jsonSchemaToTypeScript(cyclic)).toBe("{ child?: Node; name?: string }")
  151. expect(jsonSchemaToTypeScript(cyclic, true)).toContain("child?: Node")
  152. let deep: Record<string, unknown> = { type: "string" }
  153. for (let level = 0; level < 12; level += 1) deep = { type: "object", properties: { next: deep } }
  154. for (const pretty of [false, true]) {
  155. const rendered = jsonSchemaToTypeScript(deep, pretty)
  156. expect(rendered).toContain("unknown")
  157. expect(rendered).toContain("next?:")
  158. }
  159. })
  160. })
  161. describe("non-identifier property names render as quoted keys", () => {
  162. // MCP-style schemas routinely carry property names that are not bare TS identifiers
  163. // (`foo-bar`, `@type`, dotted names); the rendered signature must quote them so the
  164. // model sees a valid TypeScript object type. Bare identifiers stay unquoted.
  165. const rawSchema = {
  166. type: "object",
  167. properties: {
  168. "foo-bar": { type: "string" },
  169. "@type": { type: "string" },
  170. "x.y": { type: "number", description: "Dotted name" },
  171. "123": { type: "number" },
  172. plain: { type: "boolean" },
  173. },
  174. required: ["@type"],
  175. } as const
  176. test("compact rendering quotes non-identifier keys and leaves identifiers bare", () => {
  177. expect(jsonSchemaToTypeScript(rawSchema)).toBe(
  178. '{ "123"?: number; "foo-bar"?: string; "@type": string; "x.y"?: number; plain?: boolean }',
  179. )
  180. })
  181. test("pretty rendering quotes non-identifier keys and keeps their JSDoc", () => {
  182. expect(jsonSchemaToTypeScript(rawSchema, true)).toBe(
  183. [
  184. "{",
  185. ' "123"?: number',
  186. ' "foo-bar"?: string',
  187. ' "@type": string',
  188. " /** Dotted name */",
  189. ' "x.y"?: number',
  190. " plain?: boolean",
  191. "}",
  192. ].join("\n"),
  193. )
  194. })
  195. test("JSON Schema input and output signatures of a tool both quote", () => {
  196. const tool = Tool.make({
  197. description: "Adapter tool with awkward field names",
  198. input: rawSchema,
  199. output: { type: "object", properties: { "content-type": { type: "string" } }, required: ["content-type"] } as const,
  200. run: () => Effect.succeed({ "content-type": "text/plain" }),
  201. })
  202. expect(inputTypeScript(tool)).toContain('"foo-bar"?: string')
  203. expect(outputTypeScript(tool)).toBe('{ "content-type": string }')
  204. expect(outputTypeScript(tool, true)).toBe(["{", ' "content-type": string', "}"].join("\n"))
  205. })
  206. test("Effect Schema structs with non-identifier field names quote too", () => {
  207. const tool = Tool.make({
  208. description: "Schema tool with awkward field names",
  209. input: Schema.Struct({ "foo-bar": Schema.String, plain: Schema.optionalKey(Schema.Number) }),
  210. run: () => Effect.succeed(null),
  211. })
  212. expect(inputTypeScript(tool)).toBe('{ "foo-bar": string; plain?: number }')
  213. expect(inputTypeScript(tool, true)).toBe(["{", ' "foo-bar": string', " plain?: number", "}"].join("\n"))
  214. })
  215. })
  216. describe("union schemas render every alternative", () => {
  217. test("anyOf with a number branch keeps sibling alternatives", () => {
  218. const schema = {
  219. anyOf: [{ type: "string" }, { type: "number" }],
  220. } as const
  221. expect(jsonSchemaToTypeScript(schema)).toBe("string | number")
  222. expect(jsonSchemaToTypeScript(schema, true)).toBe("string | number")
  223. })
  224. test("nullable numeric unions keep null", () => {
  225. const schema = {
  226. oneOf: [{ type: "number" }, { type: "null" }],
  227. } as const
  228. expect(jsonSchemaToTypeScript(schema)).toBe("number | null")
  229. expect(jsonSchemaToTypeScript(schema, true)).toBe("number | null")
  230. })
  231. test("tool input and output signatures preserve numeric unions", () => {
  232. const tool = Tool.make({
  233. description: "Tool with numeric unions",
  234. input: {
  235. type: "object",
  236. properties: {
  237. value: { anyOf: [{ type: "string" }, { type: "number" }] },
  238. },
  239. } as const,
  240. output: { anyOf: [{ type: "number" }, { type: "boolean" }] } as const,
  241. run: () => Effect.succeed(1),
  242. })
  243. expect(inputTypeScript(tool)).toBe("{ value?: string | number }")
  244. expect(outputTypeScript(tool)).toBe("number | boolean")
  245. })
  246. })
  247. describe("pretty signatures in search results", () => {
  248. const runtime = CodeMode.make({ tools: { github: { list_issues: listIssues }, orders: { lookup: lookupOrder } } })
  249. const search = async (query: string) => {
  250. const result = await Effect.runPromise(runtime.execute(
  251. `return await tools.$codemode.search({ query: ${JSON.stringify(query)} })`,
  252. ))
  253. expect(result.ok).toBe(true)
  254. if (!result.ok) throw new Error("search failed")
  255. return result.value as { items: Array<{ path: string; signature: string }>; total: number }
  256. }
  257. test("a raw JSON Schema (MCP-style) tool's result signature carries field JSDoc and tags", async () => {
  258. const { items } = await search("list issues repository")
  259. const item = items.find(({ path }) => path === "tools.github.list_issues")!
  260. expect(item.signature).toBe(
  261. [
  262. "tools.github.list_issues(input: {",
  263. " /** Repository owner */",
  264. " owner: string",
  265. " /** Cursor from the previous response's pageInfo */",
  266. " after?: string",
  267. " /**",
  268. " * Results per page",
  269. " * @default 30",
  270. " */",
  271. " perPage?: number",
  272. " /**",
  273. " * Filter by labels",
  274. " * @minItems 1",
  275. " * @maxItems 10",
  276. " */",
  277. " labels?: Array<string>",
  278. ' state?: "open" | "closed"',
  279. "}): Promise<unknown>",
  280. ].join("\n"),
  281. )
  282. })
  283. test("an annotated Effect Schema tool's result signature carries field JSDoc (exact-path lookup too)", async () => {
  284. for (const query of ["look up order", "tools.orders.lookup"]) {
  285. const { items } = await search(query)
  286. const item = items.find(({ path }) => path === "tools.orders.lookup")!
  287. expect(item.signature).toBe(
  288. [
  289. "tools.orders.lookup(input: {",
  290. " /** Order identifier */",
  291. " id: string",
  292. " verbose?: boolean",
  293. "}): Promise<{",
  294. " /** Current order status */",
  295. " status: string",
  296. "}>",
  297. ].join("\n"),
  298. )
  299. }
  300. })
  301. test("the inline catalog line for the same tool stays single-line compact", () => {
  302. const instructions = runtime.instructions()
  303. expect(instructions).toContain(
  304. ' - tools.github.list_issues(input: { owner: string; after?: string; perPage?: number; labels?: Array<string>; state?: "open" | "closed" }): Promise<unknown> // List issues in a repository',
  305. )
  306. expect(instructions).toContain(
  307. " - tools.orders.lookup(input: { id: string; verbose?: boolean }): Promise<{ status: string }> // Look up an order",
  308. )
  309. expect(instructions).not.toContain("/**")
  310. })
  311. })