Skip to content

transform_schema raises AssertionError on type arrays (e.g. type: ["string","null"]) #1876

Closed as not planned

Description

@cmun2

Summary

transform_schema in anthropic/lib/_parse/_transform.py raises
AssertionError: Expected code to be unreachable, but got: ['string', 'null']
when a JSON Schema uses an array for type. It fails before any request is
sent, so a caller gets an AssertionError rather than a validation error or a
400.

type as an array is valid JSON Schema (draft 4 onward), and it is the default
output of z.string().nullable() in Zod and Optional[str] in Pydantic — so it
arrives in tool schemas constantly rather than exceptionally.

It is also a shape the strict-tool-use documentation appears to expect. The
complexity-limits table counts these parameters explicitly:

"Total parameters that use anyOf or type arrays (for example,
"type": ["string", "null"]) across all strict schemas."

A schema shape that has its own budget line in the limits table should not be
unrepresentable in the transform.

Version

  • anthropic 1.0.0
  • Python 3.12.13

Reproduction

Self-contained, no API key, no network — the failure is in local schema
normalisation:

from anthropic.lib._parse._transform import transform_schema

transform_schema({
    "type": "object",
    "properties": {"cursor": {"type": ["string", "null"]}},
    "required": ["cursor"],
    "additionalProperties": False,
})
AssertionError: Expected code to be unreachable, but got: ['string', 'null']

A runnable script with controls: sdk-bug/repro_type_array_null.py

$ pip install 'anthropic==1.0.0'
$ python3 repro_type_array_null.py

It needs no API key and makes no network call. Observed output on anthropic 1.0.0 / Python 3.12.13 — 4 of 6 cases fail, both controls pass:

case result
{"type": ["string","null"]} AssertionError: ... but got: ['string', 'null']
{"type": ["integer","null"]} AssertionError: ... but got: ['integer', 'null']
{"type": ["number","null"]} AssertionError: ... but got: ['number', 'null']
{"type": ["string","number"]} AssertionError: ... but got: ['string', 'number']
{"anyOf": [{"type":"string"},{"type":"null"}]} OK
{"type": "string"} OK

The last two are controls: the anyOf spelling of exactly the same constraint
transforms fine. Only the type-array spelling crashes.

Cause

In transform_schema (anthropic/lib/_parse/_transform.py):

type_: Optional[SupportedTypes] = json_schema.pop("type", None)
...
    strict_schema["type"] = type_          # a list is accepted here unchecked
...
elif type_ == "boolean" or type_ == "integer" or type_ == "number" or type_ == "null" or type_ is None:
    pass
else:
    assert_never(type_)                     # reached with type_ == ['string', 'null']

type_ is annotated Optional[SupportedTypes], where SupportedTypes is a
union of string literals. A list is not one of them, but nothing enforces that
at runtime: the value is written straight into strict_schema["type"], and then
the dispatch chain falls through to assert_never, which is a static-exhaustiveness
device and not an input validator.

So this is a missing input-validation path rather than an intentional
restriction — the annotation says lists cannot occur, and the runtime lets them
in anyway.

Expected behaviour

Any of these would be an improvement on AssertionError; the first seems most
consistent with what the transform already does elsewhere:

  1. Normalise it. {"type": ["string","null"]} is semantically
    {"anyOf": [{"type":"string"}, {"type":"null"}]}, and the anyOf branch
    already works. The transform already rewrites oneOf into anyOf, so
    rewriting type arrays the same way would be in keeping with the existing
    design.
  2. Reject it explicitly with a ValueError naming the offending pointer, as
    the sibling path already does for a missing type:
    ValueError: Schema must have a 'type', 'anyOf', 'oneOf', or 'allOf' field.
  3. At minimum, do not surface assert_never to callers — an AssertionError
    reads as an SDK invariant break, which makes it hard to tell whether the
    caller's schema is at fault.

How often this shape appears

I hit this while running transform_schema over a corpus of 14,804 tool schemas collected from 617 public MCP servers — real tools/list responses obtained by launching each server over stdio, not scraped manifests. The corpus, the collection harness and the per-verdict reproduction commands are public: cmun2/mcp-schema-census. Counts, tool-unit:

type array tools servers
["string","null"] 57 17
["integer","null"] 9 2
["number","null"] 7 6
["string","number"] 7 3
other arrays (5 shapes) 8 5
any type array 88 30

75 of the 88 involve an array containing "null" — i.e. the plain
"this field is optional/nullable" case, not anything exotic.

For context, in the same run transform_schema raised on 75/617 servers overall
(12.2%); this AssertionError is the second-largest cause after
ValueError: Schema must have a 'type', ... (150 tools).

I have not included any third-party schema in this report. The reproduction
above is written from scratch and the corpus numbers are aggregate counts.

Activity

  1. russlan23 commented on Aug 23, 2026

    @russlan23

    I checked the current main implementation and the existing tests in tests/lib/_parse/test_transform.py. The scalar type annotation is not enforced at runtime, so a list reaches assert_never after the schema has already been partially copied.

    Would you welcome a focused PR that:

    • recognizes a valid non-empty JSON Schema type array before scalar dispatch;
    • normalizes each member into an anyOf branch and runs each branch through transform_schema, preserving the existing object, array, string-format, and extra-key handling;
    • raises ValueError for malformed or unsupported type arrays rather than exposing AssertionError; and
    • adds regression coverage for a nullable primitive, a mixed primitive union, a nested property, invalid arrays, and input immutability?

    The change would stay in src/anthropic/lib, which CONTRIBUTING.md identifies as outside generated code. Normalization appears most consistent with the existing oneOf-to-anyOf behavior and the documented strict-schema type-array budget, but I will use explicit rejection instead if that is the intended API contract.

    AI assistance disclosure: drafted with Codex; I verified the proposal against current main, the existing transform tests, CONTRIBUTING.md, SECURITY.md, and the MIT license.

  2. cmun2 commented on Aug 23, 2026

    @cmun2
    Author

    Thanks for digging into this — your reading of the cause matches mine exactly, including that the value is written into strict_schema before the dispatch chain reaches assert_never.

    I confirmed the src/anthropic/lib/ point directly: CONTRIBUTING.md says "The generator will never modify the contents of the src/anthropic/lib/ and examples/ directories", so _parse/_transform.py is hand-maintained and a PR can land there.

    Since I have the reproduction and the corpus this came out of, I'll go ahead and open the PR rather than leave the question waiting — the approach is the one you proposed (normalise a type array into anyOf branches, ValueError for malformed ones instead of surfacing assert_never). If you would rather take it, say so and I'll close mine; and if it's useful I'm happy to add you as Co-authored-by, since your write-up covered the same ground independently.

    Two things from the corpus that are worth having in the tests, since they decide which shapes matter:

    type array tools servers
    ["string","null"] 57 17
    ["integer","null"] 9 2
    ["number","null"] 7 6
    ["string","number"] 7 3
    other arrays (5 shapes) 8 5
    any type array 88 30

    75 of the 88 contain "null" — so nullable dominates, but ["string","number"] is real and a nullable-only fix would miss it. Your "mixed primitive union" case covers that.

    One design point in favour of normalising rather than rejecting: it does not change the complexity accounting. The limits table counts "Total parameters that use anyOf or type arrays" as one budget, so rewriting a type array into anyOf leaves the count where it was.

    Worth stating plainly: neither of us can approve anything here, and a maintainer may prefer explicit rejection over normalisation. If that is the intended contract, the change is small either way.

  3. added a commit that references this issue on Aug 23, 2026
    90cf3c1
  4. dtmeadows-ant commented on Sep 2, 2026

    @dtmeadows-ant
    Contributor

    Hey @cmun2 — thanks for the thorough write-up and the corpus numbers. This is the same root cause as #1764, so I'm going to fold it in there to keep the discussion in one place; the census data is a useful signal for how we handle the ["object", ...] and multi-scalar shapes, not just the nullable one.

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