From 7c7e4ad0aec7370754c9ebef4934e056c07e3e08 Mon Sep 17 00:00:00 2001 From: Georges Haidar Date: Sun, 16 Feb 2025 19:23:29 +0000 Subject: [PATCH] fix: drop unresolved union members in zod schemas MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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), 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), 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. --- src/server/mcp.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/server/mcp.ts b/src/server/mcp.ts index d71eecb5b..8f4a909ce 100644 --- a/src/server/mcp.ts +++ b/src/server/mcp.ts @@ -108,7 +108,9 @@ export class McpServer { name, description: tool.description, inputSchema: tool.inputSchema - ? (zodToJsonSchema(tool.inputSchema) as Tool["inputSchema"]) + ? (zodToJsonSchema(tool.inputSchema, { + strictUnions: true, + }) as Tool["inputSchema"]) : EMPTY_OBJECT_JSON_SCHEMA, }; },