Repository navigation
Description
Summary
transform_schema (the structured-output schema transformer used by messages.parse / beta.messages.parse) crashes with an AssertionError on any schema that uses the list form of type — e.g. {"type": ["string", "null"]} — which is valid JSON Schema and explicitly supported by the Anthropic structured-outputs API.
The failure happens at request-build time, before any API call.
Repro
from anthropic import transform_schema
# Valid JSON Schema; also documented as supported by the structured-outputs API
transform_schema({"type": ["string", "null"]})One-liner:
python -c 'from anthropic import transform_schema; transform_schema({"type": ["string", "null"]})'Actual (on anthropic==0.112.0; the relevant code is unchanged on current main of src/anthropic/lib/_parse/_transform.py):
AssertionError: Expected code to be unreachable, but got: ['string', 'null']
A more realistic nested variant fails the same way:
transform_schema({
"type": "object",
"properties": {"name": {"type": ["string", "null"]}},
"required": ["name"],
"additionalProperties": False,
})Expected
An equivalent transformed schema, e.g. rewriting the type union into anyOf branches:
{"anyOf": [{"type": "string"}, {"type": "null"}]}Why this should be supported
- JSON Schema allows
typeto be "a string or an array of strings" — the list form is standard, not an extension. - The structured outputs docs explicitly document type arrays as supported (and meter them): "Total parameters that use
anyOfor type arrays (for example,"type": ["string", "null"]) across all strict schemas." So the API accepts this shape; only the SDK-side transformer rejects it. - Nullable-type unions are pervasive in real schemas: Pydantic
Optional[...]fields in older/alternative generators, OpenAPI 3.1 output, GraphQL-derived schemas, and MCP toolinputSchemas commonly emit"type": [..., "null"].
Root cause
In src/anthropic/lib/_parse/_transform.py, type_ is typed and handled as a scalar:
type_: Optional[SupportedTypes] = json_schema.pop("type", None)
...
elif type_ == "boolean" or type_ == "integer" or type_ == "number" or type_ == "null" or type_ is None:
pass
else:
assert_never(type_)A list value matches none of the scalar branches and falls into assert_never.
Suggested fix
When type_ is a list, canonicalize it before the scalar handling, e.g. rewrite {"type": [t1, t2, ...], **rest} into an anyOf of single-type branches (with sibling constraints attached to the non-null branches) and recurse. Single-element lists can collapse to the scalar form.
Related (not duplicates)
- fix(parse): treat empty/typeless schema as "any" in transform_schema #1691 handles empty/typeless
{}sub-schemas (ValueErrorpath) — a different gap in the same function. - Structured outputs: "compiled grammar is too large" error needs better documentation and higher limits for complex schemas #1185 discusses grammar-size limits and mentions type arrays as API-supported; it does not cover this SDK-side crash.
Environment
anthropic==0.112.0(also reproduces againstmain's_transform.py)- Python 3.12.13, macOS arm64
Activity
nightcityblade commentedon Jul 17, 2026
Hi, I'd like to work on this. I'll submit a focused PR with regression coverage shortly.
percymcn commentedon Aug 9, 2026
Adding four things I measured today against
anthropic==0.121.0and@anthropic-ai/[email protected]that I think change the shape of the fix, since a PR is in flight.1.
anyOfis the right target, but only if the type-specific keywords move onto the branch — otherwise the fix trades this crash for a silent one.The
assert_neveris the last branch, but the interesting code is above it: the transformer dispatches ontype_withif type_ == "object"/elif type_ == "string"/elif type_ == "array"(lines 128/139/146 in0.121.0). Those branches are the only placeproperties,required,items,minItemsandformatare read. Everything not read by them falls through to the catch-all that stringifies leftovers intodescription.So if list-form support is added by teaching
type_to accept a list and copying it through, this:{"type": ["object", "null"], "properties": {"a": {"type": "string"}}, "required": ["a"]}comes back as
{"type": ["object", "null"], "description": '{properties: {"a":{"type":"string"}}, required: ["a"]}'}— the whole subtree silently stops being schema, and the transformer never recurses into it, so nested
$refs and nested demotions are never processed either. That is a worse failure than the current crash, because nothing raises.The
anyOfrewrite in the issue body avoids this if the non-typekeywords are distributed onto the matching branch:{"anyOf": [{"type": "object", "properties": {...}, "required": [...]}, {"type": "null"}]}which then recurses normally. Worth pinning a regression case with
type: ["object","null"]carryingproperties, not just the scalar["string","null"]in the repro — the scalar case passes either way and would hide this.2. This is not hypothetical: the TypeScript SDK already ships exactly that behaviour, so the two SDKs disagree.
@anthropic-ai/[email protected]'s_transformJSONSchemadispatches the same way (type === 'object', strict equality against a string), does not raise on a list, and produces the gutted output above. Measured on the same schemas. So today a Python caller gets anAssertionErrorwhere a TypeScript caller gets a silently unenforced schema — same version string, opposite failure. Whichever way this is fixed, it's probably worth deciding whether the TS transformer should match, since a schema shared between two services currently behaves differently in each.3. A one-element list raises too.
["string"]is exactly equivalent to"string", and OpenAPI/JSON-Schema tooling emits it fairly often. Cheap regression case, and it also rules out a fix that only special-cases[..., "null"].4. A list
typebeside a combinator raises before the combinator is consulted.type_is popped and asserted regardless ofany_of, so this raises even though the schema already has the form the fix rewrites to. Whatever the rewrite does, it needs a decision for the case whereanyOfis already present — merging the two is a semantic change, so raising a clearValueErrornaming the conflict is probably better than producing a merged schema the caller didn't write. (The TS SDK takes the other route: it ignorestypeentirely once it sees a combinator.)One note on the docs point in the issue body, which I think is right and worth keeping front-and-centre: the structured-outputs docs meter
"type": ["string", "null"]alongsideanyOfas a counted parameter, so the API accepts this shape. That makes this purely an SDK-side rejection of something the server takes.Finally,
transform_schemais usable as an offline oracle for the regression tests — it needs no API key and no network, so the whole battery above can run in CI.