Skip to content

Commit 7c7e4ad

Browse files
committed
fix: drop unresolved union members in zod schemas
This change enables the strictUnions option in zod-to-json-schema so that any union members that cannot be resolved are excluded from the resulting JSON Schema anyOf array. Previously, a schema like this: **Before** ```ts import { zodToJsonSchema } from "zod-to-json-schema"; import { z } from "zod"; console.dir( zodToJsonSchema( z.union([ z .string() .base64() .transform((v) => Uint8Array.from(atob(v), (v) => v.charCodeAt(0))), z.instanceof(ReadableStream<Uint8Array>), z.instanceof(Blob), z.instanceof(ArrayBuffer), z.instanceof(Uint8Array), ]) ), { depth: null } ); ``` Prints: ```js { anyOf: [ { type: "string", contentEncoding: "base64" }, {}, {}, {}, {} ], $schema: "http://json-schema.org/draft-07/schema#", } ``` **After** ```ts import { zodToJsonSchema } from "zod-to-json-schema"; import { z } from "zod"; console.dir( zodToJsonSchema( z.union([ z .string() .base64() .transform((v) => Uint8Array.from(atob(v), (v) => v.charCodeAt(0))), z.instanceof(ReadableStream<Uint8Array>), z.instanceof(Blob), z.instanceof(ArrayBuffer), z.instanceof(Uint8Array), ]), { strictUnions: true }, // 👈 ), { depth: null } ); ``` Prints: ```js { anyOf: [ { type: "string", contentEncoding: "base64" } ], $schema: "http://json-schema.org/draft-07/schema#", } ``` --- I picked this example in particular because I have modelled file uploads using a permissive schema that accepts streams, byte arrays / blobs and base64-encoded strings. In the context of MCP, base64 would be most applicable so I wanted to drop the other union members that couldn't be represented in JSON Schema.
1 parent 423b62b commit 7c7e4ad

File tree

1 file changed

+3
-1
lines changed

1 file changed

+3
-1
lines changed

src/server/mcp.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,9 @@ export class McpServer {
108108
name,
109109
description: tool.description,
110110
inputSchema: tool.inputSchema
111-
? (zodToJsonSchema(tool.inputSchema) as Tool["inputSchema"])
111+
? (zodToJsonSchema(tool.inputSchema, {
112+
strictUnions: true,
113+
}) as Tool["inputSchema"])
112114
: EMPTY_OBJECT_JSON_SCHEMA,
113115
};
114116
},

0 commit comments

Comments
 (0)