Repository navigation
Description
Summary
When tools use zod v4 schemas, the SDK's zod→JSON Schema conversion (server/zod-json-schema-compat.ts, toJsonSchemaCompat) calls zod's native toJSONSchema with hardcoded options and no passthrough, producing three behaviors that break real servers. All three stem from the same asymmetry: the SDK converts and validates with the tool's zod schema, but sends the tool's raw structuredContent object (validation does not replace/serialize the payload), so the advertised schema must describe the serialized form of a raw object.
Versions: @modelcontextprotocol/sdk 1.29.0, zod 4.4.3.
1. z.date() anywhere in a tool schema kills tools/list
zod v4's toJSONSchema defaults to unrepresentable: "throw", so listing tools throws:
McpError: MCP error -32603: Date cannot be represented in JSON Schema
The zod v3 path (vendored zod-to-json-schema) rendered z.date() as { "type": "string", "format": "date-time" } — which is also what JSON.stringify actually puts on the wire for a Date. Servers migrating v3→v4 with Date-valued fields (e.g. ORM entities) lose tools/list entirely. Switching schemas to z.iso.datetime() is not a workaround: server-side output validation then rejects the tools' raw Date values before serialization (isError: true, "expected string").
2. Defaulted output-schema fields are advertised as required
With io: "output" semantics, zod v4 lists .default() fields in required. But the server ships the tool's raw return value — zod never fills defaults into the response — so a tool that omits a defaulted field violates its own advertised schema, and spec-compliant validating clients reject the response. (zod-to-json-schema kept defaulted fields optional.)
3. additionalProperties: false on output objects can't be honored
Plain z.object() converts with additionalProperties: false on outputs, while zod validation tolerates and passes through unknown keys on the raw object. Any tool returning extra keys (very common when returning spread ORM/service objects) produces responses that validating clients reject. We caught four production tools failing this way once we added client-side ajv validation of serialized results.
Repro (issues 1 & 2 in one tool)
const server = new McpServer({ name: "repro", version: "1.0.0" });
server.registerTool(
"t",
{
description: "repro",
inputSchema: { when: z.date() }, // (1) tools/list throws
outputSchema: { counted: z.number().default(0), // (2) advertised as required
name: z.string() },
},
async () => ({ content: [], structuredContent: { name: "x" } }) // omits `counted` → strict clients reject
);Proposal
Either (preferred, minimal) expose conversion options on registerTool/server config — at least unrepresentable and override passthrough to toJSONSchema — or make the defaults wire-truthful:
unrepresentable: "any"+ renderZodDateas{ type: "string", format: "date-time" }(matches serialization and the v3 path),- drop defaulted fields from
requiredin output conversion, - drop
additionalProperties: falsein output conversion (or strip unknown keys during output validation so the promise is actually kept).
We currently carry exactly these three adjustments as a ~30-line pnpm patch to zod-json-schema-compat (both dists), with contract tests pinning the behaviors — happy to send a PR if maintainers agree on the direction.
Activity
fix(core-internal): position-independent catch degrade; unwrap pipe/p…
fix(core-internal): broaden structural tolerance walk; loud/quiet roo…
fix(core-internal): null-tolerant array/tuple elements; quiet never v…
fix(core-internal): output-root loudness parity; file verdicts; posit…
fix(core-internal): io-aware pipe loudness; quiet symbol literals; an…
fix(core-internal): conjunction-preserving oneOf rewrite; skip negate…
fix(core-internal): all-key object proof; contains skip; io-aware big…
fix(core-internal): restore every()-proof for untouched allOf; extend…
fix(core-internal): complete reference-target keep; loud output date …
refactor(core-internal): replace ref-repair machinery with a referenc…
fix(core-internal): wrap stamp reads the strict pre-loosen snapshot; …
fix(core-internal): nonoptional probe deferral; deferred id strip on …
yiidtw commentedon Nov 30, 2026
Another instance of the same asymmetry, not covered by the three cases above or by #2467 / #2556: string transforms that zod 4 implements as in-place
overwritechecks —.trim(),.toLowerCase(),.toUpperCase(),.normalize(),.overwrite(fn).The server validates
structuredContentwith zod (which accepts it, because the checks after the transform see the transformed value), then ships the raw object. The advertisedoutputSchemaputs those post-transform checks on the raw value, so the SDK's ownClient.callToolrejects the result.Reproduction
Output with
@modelcontextprotocol/sdk1.32.2 and with@modelcontextprotocol/server/client2.4.0, both onzod4.6.7:callToolz.string().toLowerCase().regex(/^[a-z]+$/)"ABC"{"type":"string","pattern":"^[a-z]+$"}-32602 Structured content does not match the tool's output schema: data/s must match pattern "^[a-z]+$"z.string().trim().max(3)" ab "{"type":"string","maxLength":3}-32602 ... data/s must NOT have more than 3 charactersz.string().regex(/^[a-z]+$/)"abc"{"type":"string","pattern":"^[a-z]+$"}(v2 throws the same message without the
MCP error -32602:prefix.)Why switching
iodoes not fix itzod 4.6.7 emits the same schema for these fields under both
io: "output"andio: "input", becauseaggregateChecks(zod/v4/core/json-schema-processors.js:66-74) folds every check on the string node into one conjunction and the overwrite check contributes nothing. So theio: "input"approach from #2467 would still advertisepattern: "^[a-z]+$"for a raw"ABC". The zod 3 path (vendoredzod-to-json-schema,pipeStrategy) behaves the same: it treatstrim/toLowerCaseas no-ops (parsers/string.js:182-185). That package is archived.Suggested fix
In the
overridehook that #2556 adds (zodConversionOptions), for any string node whosedef.checkscontain anoverwritecheck, keep only the constraints declared before the first overwrite. Those are the ones the raw value must satisfy. A sketch, tested against the cases above:Results:
toLowerCase().regex(...)→{"type":"string"};trim().max(3)→{"type":"string"};min(5).trim()→ keepsminLength: 5(the raw value had to pass it); fields with no transform are unchanged. In every case the raw value the server accepts validates against the advertised schema.The alternative is to ship the parsed value instead of the raw
structuredContent. That would also change what clients receive, and the advertisedio: "output"schema would still be wrong formin(5).trim()andregex(/^[A-Z]+$/).toLowerCase()(zod emitsminLength: 5/pattern: "^[A-Z]+$"for an output that can be"ab"/"abc"). That part is a zod issue: colinhacks/zod#6784