Skip to content

zod v4: toJSONSchema options are hardcoded — z.date() breaks tools/list; output schemas advertise required/closed shapes the raw structuredContent can't satisfy #2464

Open

Description

@jtemps

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" + render ZodDate as { type: "string", format: "date-time" } (matches serialization and the v3 path),
  • drop defaulted fields from required in output conversion,
  • drop additionalProperties: false in 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

  1. added
    triage
    on Jul 9, 2026
  2. ghost added
    bug
    on Jul 9, 2026
  3. ghost added
    ready for work
    on Jul 9, 2026
  4. ghost added
    P2
    on Jul 9, 2026
  5. ghost added
    fix proposed
    on Jul 9, 2026
  6. ghost removed
    triage
    on Jul 9, 2026
  7. added
    v2
    v1
    on Aug 18, 2026
  8. yiidtw commented on Nov 30, 2026

    @yiidtw

    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 overwrite checks — .trim(), .toLowerCase(), .toUpperCase(), .normalize(), .overwrite(fn).

    The server validates structuredContent with zod (which accepts it, because the checks after the transform see the transformed value), then ships the raw object. The advertised outputSchema puts those post-transform checks on the raw value, so the SDK's own Client.callTool rejects the result.

    Reproduction

    import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";   // v2: "@modelcontextprotocol/server"
    import { Client } from "@modelcontextprotocol/sdk/client/index.js";    // v2: "@modelcontextprotocol/client"
    import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
    import { z } from "zod";
    
    const server = new McpServer({ name: "repro", version: "0.0.0" });
    server.registerTool("t", { outputSchema: z.object({ s: z.string().toLowerCase().regex(/^[a-z]+$/) }) },
      async () => ({ content: [], structuredContent: { s: "ABC" } }));
    const client = new Client({ name: "c", version: "0.0.0" });
    const [a, b] = InMemoryTransport.createLinkedPair();
    await Promise.all([server.connect(a), client.connect(b)]);
    console.log((await client.listTools()).tools[0].outputSchema.properties.s);
    await client.callTool({ name: "t", arguments: {} });

    Output with @modelcontextprotocol/sdk 1.32.2 and with @modelcontextprotocol/server / client 2.4.0, both on zod 4.6.7:

    field tool returns server zod advertised callTool
    z.string().toLowerCase().regex(/^[a-z]+$/) "ABC" accepts {"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 " accepts {"type":"string","maxLength":3} -32602 ... data/s must NOT have more than 3 characters
    control: z.string().regex(/^[a-z]+$/) "abc" accepts {"type":"string","pattern":"^[a-z]+$"} accepted

    (v2 throws the same message without the MCP error -32602: prefix.)

    Why switching io does not fix it

    zod 4.6.7 emits the same schema for these fields under both io: "output" and io: "input", because aggregateChecks (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 the io: "input" approach from #2467 would still advertise pattern: "^[a-z]+$" for a raw "ABC". The zod 3 path (vendored zod-to-json-schema, pipeStrategy) behaves the same: it treats trim/toLowerCase as no-ops (parsers/string.js:182-185). That package is archived.

    Suggested fix

    In the override hook that #2556 adds (zodConversionOptions), for any string node whose def.checks contain an overwrite check, 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:

    override: ({ zodSchema, jsonSchema }) => {
      const checks = zodSchema._zod?.def?.checks ?? [];
      const i = checks.findIndex(c => c._zod?.def?.check === "overwrite");
      if (i < 0) return;
      const before = z.toJSONSchema(zodSchema.clone({ ...zodSchema._zod.def, checks: checks.slice(0, i) }), { io: "input" });
      for (const k of ["minLength", "maxLength", "pattern", "format", "contentEncoding", "allOf", "anyOf"]) {
        delete jsonSchema[k];
        if (k in before) jsonSchema[k] = before[k];
      }
    }

    Results: toLowerCase().regex(...) → {"type":"string"}; trim().max(3) → {"type":"string"}; min(5).trim() → keeps minLength: 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 advertised io: "output" schema would still be wrong for min(5).trim() and regex(/^[A-Z]+$/).toLowerCase() (zod emits minLength: 5 / pattern: "^[A-Z]+$" for an output that can be "ab" / "abc"). That part is a zod issue: colinhacks/zod#6784

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2bugfix proposedready for workv1v2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions