Skip to content

transform_schema raises AssertionError on valid list-form types, e.g. {"type": ["string", "null"]} #1764

Open

Description

@shamashel

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 type to 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 anyOf or 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 tool inputSchemas 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)

Environment

  • anthropic==0.112.0 (also reproduces against main's _transform.py)
  • Python 3.12.13, macOS arm64

Activity

  1. nightcityblade commented on Jul 17, 2026

    @nightcityblade

    Hi, I'd like to work on this. I'll submit a focused PR with regression coverage shortly.

  2. percymcn commented on Aug 9, 2026

    @percymcn

    Adding four things I measured today against anthropic==0.121.0 and @anthropic-ai/[email protected] that I think change the shape of the fix, since a PR is in flight.

    1. anyOf is 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_never is the last branch, but the interesting code is above it: the transformer dispatches on type_ with if type_ == "object" / elif type_ == "string" / elif type_ == "array" (lines 128/139/146 in 0.121.0). Those branches are the only place properties, required, items, minItems and format are read. Everything not read by them falls through to the catch-all that stringifies leftovers into description.

    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 anyOf rewrite in the issue body avoids this if the non-type keywords 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"] carrying properties, 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 _transformJSONSchema dispatches 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 an AssertionError where 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.

    transform_schema({"type": ["string"]})   # AssertionError: ... but got: ['string']

    ["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 type beside a combinator raises before the combinator is consulted.

    transform_schema({"type": ["string", "null"], "anyOf": [{"type": "string"}]})
    # AssertionError: ... but got: ['string', 'null']

    type_ is popped and asserted regardless of any_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 where anyOf is already present — merging the two is a semantic change, so raising a clear ValueError naming the conflict is probably better than producing a merged schema the caller didn't write. (The TS SDK takes the other route: it ignores type entirely 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"] alongside anyOf as a counted parameter, so the API accepts this shape. That makes this purely an SDK-side rejection of something the server takes.

    Finally, transform_schema is 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.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions