Raise `UserError` from `JsonSchemaTransformer` on nodes that are not JSON Schemas
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),requiredandenum(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$defsentry, a path through$defs.X.anyOf.1,$ref,type,required,enumandminItems.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 everystrictvalue.test_schema_shape_accepts_valid_schemasandtest_schema_shape_accepts_a_boolean_defs_entry: shapes JSON Schema allows and the walker handles are not rejected:typeas a list, booleans at every schema-valued position, empty containers,minItems: 0. A boolean$defsentry 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 throughAgent+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 ofitems. The check accepts it and checks each member (items.N). -
New keywords and pointer targets: the walker now also reads
propertyNames,containsand JSON-pointer$refs. The first two are checked up front. Pointer targets, like draft-07definitions, 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'stry. EveryUserErrora transformer raises while walking a function or output tool's schema now starts withTool '<name>':. That covers OpenAI's strict tuple errors, Gemini's recursive$referrors and$reflookup errors, not just the new check.test_openai_strict_tuple_guard_runs_before_requestis updated for it. -
Inputs that worked before keep working: a
Nonevalue for a schema-valued keyword is treated as absent, and tuples are accepted fortype,requiredandenum, since they serialize as JSON arrays. Raised by douwebot.