Skip to content

[BUG] schema-compat/zodToJsonSchema: nullable zod v4 enum/literal widens to type:[X,"null"] but keeps enum/const, so exported schema rejects null #24516

Closed

Description

@BlueX888

Describe the Bug

zodToJsonSchema (public export @mastra/core/utils/zod-to-json, implemented in packages/schema-compat/src/zod-to-json.ts) converts a zod v4 nullable enum/literal from anyOf: [{type: X, enum/const: ...}, {type: "null"}] into {type: [X, "null"], enum: [...]} (or const: ...), but leaves the sibling enum/const unchanged. In JSON Schema, type and enum/const are independent assertions that must all hold, so the resulting schema rejects null even though the source zod schema accepts it.

Concretely, z.object({ color: z.enum(['red','blue']).nullable() }) exports {"type":["string","null"],"enum":["red","blue"]}, under which {color: null} is invalid; z.literal('fast').nullable() exports {"type":["string","null"],"const":"fast"}, under which {speed: null} is invalid.

This is reachable from user-facing code: zodToJsonSchema is used to build server OpenAPI schemas (e.g. agents.ts serializing agent.requestContextSchema, openapi-utils.ts), dataset inputSchema/groundTruthSchema normalization, and model-facing tool parameter JSON Schemas via convertZodSchemaToAISDKSchema — so any zod v4 schema with a nullable enum/literal field publishes a JSON Schema that forbids a value the zod schema itself accepts.

The zod v3 branch of the same function leaves anyOf: [..., {type: "null"}] intact, so null stays valid there (verified in the repro).

Steps To Reproduce

Self-contained script against the published package (@mastra/[email protected] / @mastra/[email protected]; same result on monorepo HEAD 3fc8c2d35f724c3648150b29e50cf61a9360b274):

import { z } from 'zod/v4';
import { zodToJsonSchema } from '@mastra/core/utils/zod-to-json';
import Ajv from 'ajv';

const schema = z.object({ color: z.enum(['red', 'blue']).nullable() });
console.log('zod accepts {color:null}:', schema.safeParse({ color: null }).success);

const json = zodToJsonSchema(schema);
delete json.$schema;
console.log('zodToJsonSchema output:', JSON.stringify(json.properties.color));

const ajv = new Ajv({ strict: false });
const validate = ajv.compile(json);
console.log('JSON Schema accepts {color:"red"}:', validate({ color: 'red' }));
console.log('JSON Schema accepts {color:null}:', validate({ color: null }));

Actual output (verbatim, observed by two independent verifiers and re-run by me):

zod accepts {color:null}: true
zodToJsonSchema output: {"type":["string","null"],"enum":["red","blue"]}
JSON Schema accepts {color:"red"}: true
JSON Schema accepts {color:null}: false <- null rejected

Verbatim output from the second verifier, covering the literal (const) case and a control (widening without enum/const):

enum case  : {"type":["string","null"],"enum":["red","blue"]}
zod accepts null: true | ajv accepts {color:"red"}: true | ajv accepts {color:null}: false
const case : {"type":["string","null"],"const":"fast"}
zod accepts null: true | ajv accepts {speed:"fast"}: true | ajv accepts {speed:null}: false
control    : {"type":["string","null"]} | ajv accepts {name:null}: true

Control — the zod v3 path of the same function leaves anyOf intact and null stays valid:

zod v3 out: {"anyOf":[{"type":"string","enum":["red","blue"]},{"type":"null"}]}
JSON-Schema-valid( {color:null} ) v3 path: true

Raw zod v4 toJSONSchema() (upstream, no mastra) emits {"anyOf":[{"type":"string","enum":["red","blue"]},{"type":"null"}]} — null valid — so the defect is in mastra's anyOf merge, not in zod.

Link to Minimal Reproducible Example

https://github.com/BlueX888/mastra-zod-to-json-nullable-enum-repro

Clone, npm install, node repro.mjs — no API keys, no docker services, no LLM calls. Pure runtime schema-conversion behavior (not mastra build/mastra dev).

Expected Behavior

zodToJsonSchema output must accept null whenever the source zod schema does, including when the non-null branch carries enum or const.

Basis:

  • JSON Schema draft 2020-12 §6.1.1/§6.1.2: type and enum/const are independent assertions that must all hold, so {"type":["string","null"],"enum":["red","blue"]} rejects null (confirmed with ajv above).
  • Sibling code in the same package performs the identical optional→nullable widening but preserves null: packages/schema-compat/src/provider-compats/openai.ts:375-378 (prop.enum = [...prop.enum, null] and const → prop.enum = enumAllowsConst ? [constValue, null] : [null]), codified by tests such as openai.test.ts:513 (expect(mode.enum).toEqual(['fast','slow',1,2,null])).
  • The zod v3 branch of fixAnyOfNullable leaves the anyOf:[...,{type:"null"}] intact, so null stays valid there (shown in the control above) — the v4-only merge is the outlier.
  • fixAnyOfNullable's own docstring says the conversion exists to fix anyOf patterns "for nullable fields - required for OpenAI compatibility", i.e. to preserve the nullable pattern for providers, not to drop null.

Suggested fix direction (happy to open the PR once a maintainer approves this report): when widening in fixAnyOfNullable, if the non-null branch carries enum, append null (enum: [...enum, null]); if it carries const, convert to enum: [const, null] — mirroring openai.ts defaultObjectHandler. Alternatively, skip the anyOf → type: [...] widening when the non-null branch has enum/const and leave the anyOf intact.

Environment Information

- Mastra monorepo commit where the defect is located: 3fc8c2d35f724c3648150b29e50cf61a9360b274
  (packages/schema-compat/src/zod-to-json.ts, fixAnyOfNullable, ~line 117)
- Also reproduces on published packages: @mastra/core 1.67.0 (@mastra/schema-compat 1.3.10)
- zod 3.25.76 (zod v4 API via the zod/v4 entrypoint), ajv ^8.17.1
- Node v22.23.2, npm, macOS (Apple silicon)
- LLM provider: none needed — pure schema conversion at runtime, no API calls, no docker services

Root cause

packages/schema-compat/src/zod-to-json.ts:99-117 — in fixAnyOfNullable, when the anyOf: [{type: X}, {type: "null"}] pattern is detected, the branches are merged into type: [X, "null"] while fixedOther (which still carries the branch's enum/const) is spread in unchanged. Since enum/const and type are conjunctive, the merged schema forbids null. The zod v3 branch never enters this widening path.

Related

Searched existing issues/PRs: found only general strict-mode-compat items (#16383, #12284, and PRs #16616/#17360), all about optional-field/required-array/strictMode handling and empty-schema mangling; none covers fixAnyOfNullable dropping null from enum/const. No open PR touches packages/schema-compat/src/zod-to-json.ts.

Verification

  • I have searched the existing issues to make sure this is not a duplicate
  • I have included sufficient information for the team to reproduce and understand the issue

Activity

  1. dane-ai-mastra commented on Sep 20, 2026

    @dane-ai-mastra
    Contributor

    Thank you for opening this issue. It is waiting for maintainer triage or approval.

    Please wait until maintainers remove the triage or approval label before opening a pull request.

  2. BlueX888 commented on Sep 20, 2026

    @BlueX888
    Author

    Reproduced this. Root cause: packages/schema-compat/src/zod-to-json.ts:99-117 — in fixAnyOfNullable, the anyOf:[{type:X},{type:"null"}] branches are folded into type:[X,"null"] while fixedOther (still carrying the branch enum/const) is spread in unchanged; type and enum/const are conjunctive, so the folded schema rejects null

    Minimal reproduction:

    git clone https://github.com/BlueX888/mastra-zod-to-json-nullable-enum-repro && cd mastra-zod-to-json-nullable-enum-repro && npm install && node repro.mjs
    

    Observed output:

    zod accepts {color:null}: true
    zodToJsonSchema output: {"type":["string","null"],"enum":["red","blue"]}
    JSON Schema accepts {color:"red"}: true
    JSON Schema accepts {color:null}: false <- null rejected
    

    Fix is ready on BlueX888:fix/prep-zod-to-json-nullable-enum-loses-null (commit 87b379a4). Widens the value constraints during the fold: const becomes enum:[const,null] and enum gets null appended, mirroring the optional-to-nullable widening in provider-compats/openai.ts; the zod v3 path (which keeps anyOf) is unchanged
    Verified with: pnpm --filter @mastra/schema-compat test src/zod-to-json.test.ts — 127 passed, 1 skipped, including the new should keep null valid for nullable enums and literals case

    Happy to open the PR once you confirm the approach or assign this to me.

  3. mastra-platform commented on Sep 22, 2026

    @mastra-platform
    Contributor

    Opened by @a6da4c65-53b6-4d71-8f8e-52562d2afd3a

    Type bug — zodToJsonSchema widens a nullable zod v4 enum/literal to type: [X,"null"] but leaves enum/const without null, so the exported schema rejects a value the source zod schema accepts
    Route Plan fix
    Severity 🟠 high — silent correctness bug: the exported JSON Schema contradicts the source zod schema and rejects valid null input
    Confidence high — reproduced against published @mastra/[email protected]; root cause pinned to exact lines; sibling fix pattern confirmed in openai.ts
    Effort low — localized fix in fixAnyOfNullable plus one regression test, mirroring the existing nullable-value handling in provider-compats/openai.ts
    Impact medium — affects serialized/tool schemas whenever a nullable enum/literal is used; workaround is to pass tool parameters as a raw jsonSchema
    Next step Plan the fix in packages/schema-compat/src/zod-to-json.ts (fixAnyOfNullable): append null to enum and convert const → enum: [const, null] during the fold. Reporter has a ready branch (BlueX888:fix/prep-zod-to-json-nullable-enum-loses-null) usable as reference.

    Understanding

    Genuine bug, confirmed. In packages/schema-compat/src/zod-to-json.ts, fixAnyOfNullable (lines ~99–125) folds a nullable schema's anyOf: [{ type: X }, { type: "null" }] into a single node { type: [X, "null"], ...fixedOther }. fixedOther still carries the branch's enum / const unchanged, and it is spread in after the widened type. In JSON Schema, type and enum/const are conjunctive (all keywords on a node must hold), so the merged node asserts both "value is X or null" and "value is one of the enum members" — null satisfies the first but not the second, so the exported schema rejects null even though the zod schema (z.enum([...]).nullable(), z.literal(x).nullable()) accepts it.

    For the example schema, zod v4 emits {"anyOf":[{"type":"string","enum":["red","blue"]},{"type":"null"}]}; zodToJsonSchema turns that into {"type":["string","null"],"enum":["red","blue"]}. zod accepts {color: null}; ajv validating the exported schema rejects it. The literal case yields {"type":["string","null"],"const":"fast"} — same defect.

    Contributing areas. The zod v3 path (line ~620) uses zodToJsonSchemaOriginal and keeps the anyOf, so it is unaffected; only the v4 path (lines ~593–617) calls fixAnyOfNullable. prepareJsonSchemaForOpenAIStrictMode / stripUnsupportedStrictModeKeywords are downstream and do not re-add null to enum/const.

    Affected surface. zodToJsonSchema is re-exported as @mastra/core/utils/zod-to-json (packages/core/src/zod-to-json.ts:1) and used by:

    • tool parameter/output schemas via convertZodSchemaToAISDKSchema (packages/schema-compat/src/utils.ts:42) → packages/core/src/tools/tool-builder/builder.ts:529,555
    • server serialization: packages/server/src/server/handlers/agents.ts:829,1154 (agent requestContextSchema), processor-providers.ts:81, responses.adapter.ts:108 (tool parameters), OpenAPI docs (openapi-utils.ts:314,333,363)
    • datasets (packages/core/src/datasets/dataset.ts:199,202, manager.ts:135,138)

    Suggested direction. During the fold in fixAnyOfNullable, widen value constraints the same way provider-compats/openai.ts defaultObjectHandler already does (lines ~375–378): append null to enum and convert const → enum: [const, null]. This keeps the exported schema accepting exactly what the source schema accepts. The v3 path should stay untouched.

    Related work / regression context. This is the same class as closed #23173 ("Optional scalar enum/const rejects null in OpenAI strict schemas", labels Tools, effort:low, impact:medium) — but #23173 was fixed in the provider-compat path (provider-compats/openai.ts, PRs #23179/#23452, test #23898). The sibling fix in openai.ts is exactly why fixAnyOfNullable is now the outlier: it is the one nullable-widening site that still drops null from enum/const. No open PR touches packages/schema-compat/src/zod-to-json.ts, and existing tests (zod-to-json.test.ts) have no nullable enum/literal case, so nothing would have caught this. Reporter also has an oss-claim with a ready branch.

    Assumptions

    • The most plausible reading of the issue is the one the reporter and the code both support: fixAnyOfNullable is the sole defective site; the v3 path is intentionally out of scope.
    • The correct fix is to preserve the source schema's accepted value set (append null to enum, convert const to a two-member enum), matching the already-shipped sibling behavior in provider-compats/openai.ts, rather than special-casing anything downstream.
    • Domain label Tools selected for consistency with the sibling issue [BUG] Optional scalar enum/const rejects null in OpenAI strict schemas, breaking native image viewing #23173 and because the highest-friction manifestation is tool parameter schemas; no row in the domain table clearly covers packages/schema-compat itself, so @mastra/core (reserved for direct packages/core bugs) was not applied.
    • Severity/impact kept consistent with the merged precedent for this bug class; the reporter's ready branch is treated as a reference, not as an approved contribution.

    Open questions

    • Whether to accept the reporter's ready branch (BlueX888:fix/prep-zod-to-json-nullable-enum-loses-null) as the fix or implement in-house — a maintainer/contribution policy decision, not resolvable from code.

    Reproduction

    Reproduced locally against the published package (not a code reimplementation):

    1. mkdir /tmp/repro && cd /tmp/repro; install @mastra/[email protected], [email protected] (v4 API), [email protected].
    2. Run a script that builds z.object({ color: z.enum(['red','blue']).nullable() }) and z.object({ speed: z.literal('fast').nullable() }), converts with zodToJsonSchema, and validates {color:null} / {speed:null} with ajv.
    3. Observed: zod accepts {color:null}: true; raw zod v4 output {"anyOf":[{"type":"string","enum":["red","blue"]},{"type":"null"}]}; zodToJsonSchema output {"type":["string","null"],"enum":["red","blue"]}; JSON Schema accepts {color:null}: false. Literal case: output {"type":["string","null"],"const":"fast"}; JSON Schema accepts {speed:null}: false.

    Environment: mastra monorepo 3fc8c2d35, @mastra/core 1.67.0, @mastra/schema-compat 1.3.10, zod 3.25.76 (v4 API), ajv ^8.17.1, Node v22.23.2.

  4. added
    bugSomething isn't working
    @mastra/coreIssues whose primary fix belongs in @mastra/core
    on Sep 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

@mastra/coreIssues whose primary fix belongs in @mastra/coreToolsIssues with user made tools for Agent tool callingbugSomething isn't workingeffort:lowimpact:mediumTriage impact: mediump: highHigh prioritystatus: auto-triagedIssue has been auto-triaged

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions