Raise `UserError` from `JsonSchemaTransformer` on nodes that are not JSON Schemas

Merged
AD
1mo ago
+399-4

A JSON Schema must be an object or a boolean (draft 2020-12, ยง4.3). Tool schemas that come from outside Pydantic AI (Tool.from_schema, ExternalToolset, MCP inputSchema, AG-UI frontend tools) are passed through as plain dict[str, Any], so a node that is not a schema, for example the type name written where a subschema belongs, reaches the transformers unchecked:

{'type': 'object', 'properties': {'x': 'string'}}
# AttributeError: 'str' object has no attribute 'get'

The crash happens in prepare_request(), mid-run, with a traceback that ends in _json_schema._handle and never mentions the schema. Schemas generated by Pydantic are never affected, which is why this has gone unreported; it only shows up with hand-written or third-party schemas.

Change

The keywords the transformers read are listed once, in three small tables in _json_schema.py, and a short recursive function checks the schema against them when a JsonSchemaTransformer is constructed. Anything outside that shape raises UserError naming the tool and the node, before any request is made:

UserError: Tool 'lookup': Invalid JSON Schema at `properties.x`: a schema must be an object or a boolean, got 'string'

The shape is the closed list of what our code reads and would misbehave on, not the meta-schema:

  • keywords whose values are schemas, which the walker recurses into: properties, patternProperties, additionalProperties, items, prefixItems, allOf, anyOf, oneOf, $defs;
  • value keywords the transformers interpret: $ref (string), type (string, or list or tuple of strings), required and enum (lists or tuples), minItems (integer; Bedrock's strict transform compares it with >).

Keywords not listed pass through untouched, whatever their values, so provider extensions (nullable, format values, discriminator, x-โ€ฆ) are unaffected. parameters_json_schema stays dict[str, Any]. The only behaviour that changes is behaviour that crashed, or silently forwarded a malformed schema, before.

Why one up-front check rather than a guard at each read: the reads are spread over the base walker, the $defs inlining path (which reads before _handle runs) and each provider's transform() (required in OpenAI's, enum in Google's, minItems in Bedrock's), and several are wrapped in truthiness checks that let '' or 0 through. Per-site guards inherit each of those conditions and have to be kept in sync with every reader. One table has one rule: if a transformer starts reading a new keyword, add it. The check runs before any provider code, so the error is the same whichever model is in use, and it costs less than the deepcopy that walk() already does per request.

Why a plain function rather than a Pydantic TypedDict (which an earlier revision used): the object-or-boolean gate has to run before any union, so Pydantic's strict mode added nothing, its union errors needed a deepest-error heuristic to pick the right message, and half the messages came out in Pydantic's voice. The function is about forty lines, builds the path as it descends, and needs no type suppressions.

Not done here: validating at ToolDefinition construction. That would fail an MCP server's whole tools/list for one bad tool, and would turn a plain dataclass into a validating one for every user.

Tests

  • test_malformed_schema_raises_user_error: 25 shapes ร— 2 transformers, asserting the exact message and path, including falsy values, a bad $defs entry, a path through $defs.X.anyOf.1, $ref, type, required, enum and minItems.
  • test_malformed_schema_error_is_the_same_for_every_provider: the same input gives the same error from the OpenAI, Google, Google OpenAPI, Anthropic, Bedrock and OpenRouter transformers, at every strict value.
  • test_schema_shape_accepts_valid_schemas and test_schema_shape_accepts_a_boolean_defs_entry: shapes JSON Schema allows and the walker handles are not rejected: type as a list, booleans at every schema-valued position, empty containers, minItems: 0. A boolean $defs entry passes the check; the walker still crashes on it (#8621), and that stays a library bug rather than becoming a "your schema is invalid" error.
  • test_schema_shape_ignores_keywords_the_transformers_do_not_read: undeclared keywords pass through whatever their values.
  • test_agent_run_rejects_a_tool_schema_that_is_not_a_json_schema: public-API test through Agent + Tool.from_schema + FunctionModel, asserting the tool name is in the error; the model function and the tool body both assert they are never reached. Unit rather than VCR because the check fires before a request exists.

Precedent: #4771 / #4989 fixed the same line for boolean nodes. Booleans are valid schemas, so they were supported; strings and lists are not, so they are rejected. The mirror-image gap, a boolean $defs entry crashing the inlining path, is tracked separately in #8621.

Checklist

  • Any AI generated code has been reviewed line-by-line by the human PR author, who stands by it.
  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration, release note, and exact API-check waiver.
  • PR title is fit for the release changelog.

๐Ÿค– Generated with Claude Code

Update (taken over to land it, merged with main)

main moved since this was written, so the merge also does three things:

  • List-form items: main's walker now supports the draft 4 list form of items. The check accepts it and checks each member (items.N).

  • New keywords and pointer targets: the walker now also reads propertyNames, contains and JSON-pointer $refs. The first two are checked up front. Pointer targets, like draft-07 definitions, which the MCP TypeScript SDK writes, are checked when the walker reaches them.

  • Tool name on all walk-time errors: walk() now runs inside _customize_tool_def's try. Every UserError a transformer raises while walking a function or output tool's schema now starts with Tool '<name>': . That covers OpenAI's strict tuple errors, Gemini's recursive $ref errors and $ref lookup errors, not just the new check. test_openai_strict_tuple_guard_runs_before_request is updated for it.

  • Inputs that worked before keep working: a None value for a schema-valued keyword is treated as absent, and tuples are accepted for type, required and enum, since they serialize as JSON arrays. Raised by douwebot.