Repository navigation
Description
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
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:
typeandenum/constare independent assertions that must all hold, so{"type":["string","null"],"enum":["red","blue"]}rejectsnull(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]andconst→prop.enum = enumAllowsConst ? [constValue, null] : [null]), codified by tests such asopenai.test.ts:513(expect(mode.enum).toEqual(['fast','slow',1,2,null])). - The zod v3 branch of
fixAnyOfNullableleaves theanyOf:[...,{type:"null"}]intact, sonullstays valid there (shown in the control above) — the v4-only merge is the outlier. fixAnyOfNullable's own docstring says the conversion exists to fixanyOfpatterns "for nullable fields - required for OpenAI compatibility", i.e. to preserve the nullable pattern for providers, not to dropnull.
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
dane-ai-mastra commentedon Sep 20, 2026
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.
BlueX888 commentedon Sep 20, 2026
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:
Observed output:
Fix is ready on
BlueX888:fix/prep-zod-to-json-nullable-enum-loses-null(commit87b379a4). 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 unchangedVerified 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 caseHappy to open the PR once you confirm the approach or assign this to me.
mastra-platform commentedon Sep 22, 2026
zodToJsonSchemawidens a nullable zod v4 enum/literal totype: [X,"null"]but leavesenum/constwithoutnull, so the exported schema rejects a value the source zod schema acceptsnullinput@mastra/[email protected]; root cause pinned to exact lines; sibling fix pattern confirmed inopenai.tsfixAnyOfNullableplus one regression test, mirroring the existing nullable-value handling inprovider-compats/openai.tsjsonSchemapackages/schema-compat/src/zod-to-json.ts(fixAnyOfNullable): appendnulltoenumand convertconst→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'sanyOf: [{ type: X }, { type: "null" }]into a single node{ type: [X, "null"], ...fixedOther }.fixedOtherstill carries the branch'senum/constunchanged, and it is spread in after the widenedtype. In JSON Schema,typeandenum/constare conjunctive (all keywords on a node must hold), so the merged node asserts both "value isXornull" and "value is one of the enum members" —nullsatisfies the first but not the second, so the exported schema rejectsnulleven 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"}]};zodToJsonSchematurns that into{"type":["string","null"],"enum":["red","blue"]}.zodaccepts{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
zodToJsonSchemaOriginaland keeps theanyOf, so it is unaffected; only the v4 path (lines ~593–617) callsfixAnyOfNullable.prepareJsonSchemaForOpenAIStrictMode/stripUnsupportedStrictModeKeywordsare downstream and do not re-addnulltoenum/const.Affected surface.
zodToJsonSchemais re-exported as@mastra/core/utils/zod-to-json(packages/core/src/zod-to-json.ts:1) and used by:convertZodSchemaToAISDKSchema(packages/schema-compat/src/utils.ts:42) →packages/core/src/tools/tool-builder/builder.ts:529,555packages/server/src/server/handlers/agents.ts:829,1154(agentrequestContextSchema),processor-providers.ts:81,responses.adapter.ts:108(toolparameters), OpenAPI docs (openapi-utils.ts:314,333,363)packages/core/src/datasets/dataset.ts:199,202,manager.ts:135,138)Suggested direction. During the fold in
fixAnyOfNullable, widen value constraints the same wayprovider-compats/openai.tsdefaultObjectHandleralready does (lines ~375–378): appendnulltoenumand convertconst→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 inopenai.tsis exactly whyfixAnyOfNullableis now the outlier: it is the one nullable-widening site that still dropsnullfromenum/const. No open PR touchespackages/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 anoss-claimwith a ready branch.Assumptions
fixAnyOfNullableis the sole defective site; the v3 path is intentionally out of scope.nulltoenum, convertconstto a two-memberenum), matching the already-shipped sibling behavior inprovider-compats/openai.ts, rather than special-casing anything downstream.Toolsselected 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 coverspackages/schema-compatitself, so@mastra/core(reserved for directpackages/corebugs) was not applied.Open questions
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):
mkdir /tmp/repro && cd /tmp/repro; install@mastra/[email protected],[email protected](v4 API),[email protected].z.object({ color: z.enum(['red','blue']).nullable() })andz.object({ speed: z.literal('fast').nullable() }), converts withzodToJsonSchema, and validates{color:null}/{speed:null}with ajv.zod accepts {color:null}: true; raw zod v4 output{"anyOf":[{"type":"string","enum":["red","blue"]},{"type":"null"}]};zodToJsonSchemaoutput{"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/core1.67.0,@mastra/schema-compat1.3.10, zod 3.25.76 (v4 API), ajv ^8.17.1, Node v22.23.2.