Repository navigation
feat: Validate every call with a pydantic model of the endpoint's parameters - #196
Merged
Merged
Conversation
- Add build_request_model in _request_model.py: a pydantic model of the endpoint's parameters, strict, reading arguments by name rather than alias, with type aliases expanded so the helpers inside them apply. - Check first what the model can't show or hold: a default inside a helper, a default_factory without = None, and names pydantic drops or that shadow a BaseModel attribute. - Store it as Endpoint.request_model, built after plan_request, which still guards what pydantic sees. Nothing uses the model yet. - A parameter named _x, model_config, or like a BaseModel attribute (json, copy...) now raises DefinitionError. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Move the check for a helper or Send nested inside a parameter's type from the planner into build_request_model, which runs before pydantic sees the annotations. - Build the request model before plan_request, so the model's checks can replace the planner's one group at a time. - Make contains_metadata, is_helper and is_send public in _planner, for _request_model. - Split the default-inside-a-helper test: a default_factory without = None now gets its own message. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Add check_request_model in _request_rules.py, which reads the request model's fields, and call it from Endpoint right after building the model. - Move these rules there from the planner: every placeholder has a parameter, a parameter needs a helper, Url() needs a placeholder, a path parameter's helper, alias, None and Send, and a helper or Send on a model's field. - List every missing placeholder in path order, as written, when there are several; one keeps today's message. - Make parse_path, allows_none, all_plain, class_of and union_arms public in _planner, for _request_rules. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Move the checks for one kind of body, one Body(), clashing keys and non-ASCII header names from the planner into check_request_model. - Collect what those checks compare in one pass, in a _Parameters accumulator, keeping check_request_model under ruff's complexity limit. - Remove the planner's key and body checks and the spec attributes only they used; make fields_of, has_fields and has_model_serializer public. - No change in which endpoints are accepted, or in the messages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Move the checks of what a File() and a Body() can be, and that a stream matches the endpoint, from the planner into check_request_model, which now takes is_async; plan_request no longer does. - Require SkipValidation on a File() or Body() parameter typed as anything but str or bytes. Pydantic can't validate typing's IO types, and its dump would wrap a file or stream in an iterator, so such a value is sent as it is; SkipValidation says so in the signature. - Add SkipValidation to the docs samples and tests that send files or streams. - Breaking: an existing File() or Body() parameter typed as a file, stream, file tuple or Any now raises DefinitionError until it has SkipValidation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Add validate_call, which validates the arguments the caller passed with the endpoint's request model and raises ArgumentError, with pydantic's ValidationError as its cause, for the first one that doesn't fit. - Call it from Endpoint.request_arguments before the request is built. The request is still built from the caller's values. - Validate in pydantic's lax mode, converting what it can, such as "7" for an int. - Breaking: every call is validated, so annotated constraints such as Query(ge=1) apply without validate_arguments=True, and a str passed for a Sequence[str] parameter fails, as pydantic refuses it; annotate str | Sequence[str] to take either. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Remove the validate_arguments= option of ClientX and AsyncClientX, the check it turned on, and the endpoint's opt-in validator. - Keep in _validation.py only what clientx.tools uses and the error formatter, until tools validate with the request model. - Rewrite the validation tests for always-on, lax validation, and drop the option from the validating-arguments docs sample. - Breaking: passing validate_arguments= raises TypeError. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Add _request_routes.py: FieldRoute, where one field of the request model goes and the key it's sent under, and plan_routes, which builds them once the model is checked. - Store them as Endpoint.request_routes, next to the old plan. Nothing uses them yet. - Share is_spread, spread_keys and sent_key from _request_rules, so routes use the keys the rules check. - No change in behavior. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Rewrite build_request to follow the routes and take every value from the validated model, so its conversions and serializers apply: each field is dumped on its own, text in JSON form, JSON by alias, and files and the raw body are read from the model as they are. - Keep raising for NaN and infinity in JSON, and send nothing for a value pydantic's exclude_if leaves out. - Remove Send's exclude_unset, exclude_none and exclude_defaults, and the planner's checks of them; point the docs' Send table to exclude_if. - Breaking: the removed Send options raise TypeError; a model subclass is sent as its annotated type, without its extra fields, unless annotated SerializeAsAny; converted values are sent, such as 3.0 for a float passed 3. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Move path template parsing into _paths.py, and the helpers that tell what a type is into _annotations.py, each block as it was. - Make PLAIN_TYPES and is_plain public, as the planner still uses them. - Import them from their new modules everywhere; the planner imports back what it uses. - No change in behavior. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Check path, query, header and form values against the request model's serialization schema, so a serializer's return_type counts: a plain value dumps to a string, number or boolean. - Where the schema can't tell, as for Collection[str], judge by the type, unless it has a serializer; a type neither can judge, such as a class of your own, raises with a message that asks for a return_type. - Keep the first half of each message, and say what to change in the second. - The planner still runs after these checks, so no endpoint is accepted that wasn't before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Delete _planner.py and Endpoint.request_plan. Endpoint builds the request model's schema once and passes it to check_request_model and plan_routes. - Decide whether a lone Json() parameter is the whole body by what it dumps to. - Check the docs' Send table against a fixed map of the helper each option applies to. - Serializers in a parameter's type are allowed and run, a default_factory with = None runs when the argument is left out, and a Send option on a helper it doesn't apply to is ignored. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- An endpoint tool validates a model's arguments with the endpoint's request model, reading nested models by name, and takes its input schema from it. - The request model forbids arguments the endpoint doesn't have, so a tool's caller can't slip one past it. Nested models keep their own setting. - An unknown argument to an endpoint tool now reads "Extra inputs are not permitted". - @tool methods still validate as a call to a function. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DxGAoNbvS2EgPqBDbxUdKS
- @tool methods keep their function-call validator, now private to tools. - describe_errors moves to the request model, which uses it for each call. - No behavior changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DxGAoNbvS2EgPqBDbxUdKS
- The request model's docstring no longer mentions a per-endpoint model_config, which ClientX doesn't take. - No behavior changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DxGAoNbvS2EgPqBDbxUdKS
- The architecture section describes the request model, its rules and its routes, which replace the planner and the opt-in validator. - The call stage validates every call before building the request. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DxGAoNbvS2EgPqBDbxUdKS
- List what every call's validation adds, changes and removes, with each breaking change and its fix. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DxGAoNbvS2EgPqBDbxUdKS
- The requests guide explains validation: lax, constraints applied, converted values sent, a helper's strict=True, and ArgumentError. - The section and its sample move from the configuration page, which loses validate_arguments. - Plain values are judged by what they dump to, so serializers apply. - Document default_factory, exclude_if, and SkipValidation on files and streams; drop Send's dump options. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DxGAoNbvS2EgPqBDbxUdKS
… every call - Remove validate_arguments and Send's exclude_* options. - Describe lax validation on every call, a helper's strict=True, SkipValidation on files and streams, default_factory with = None, exclude_if, and the names a parameter can't have. - Judge plain values by what they dump to, so serializers apply. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DxGAoNbvS2EgPqBDbxUdKS
- A type of your own with a serializer can be sent, but a tool needs a validator too, or list_tools leaves its endpoint out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DxGAoNbvS2EgPqBDbxUdKS
- A dict for a model is read as the model reads one: by alias, dropping keys it doesn't have, unless its model_config says otherwise. - The changelog lists it as a breaking change: such a dict used to be sent as it was. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DxGAoNbvS2EgPqBDbxUdKS
- arguments_model checks the parameter names and builds the model, with the settings every arguments model shares; build_request_model adds the endpoint's checks and settings. - The name errors no longer assume an endpoint. - No behavior changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DxGAoNbvS2EgPqBDbxUdKS
- A @tool method's arguments are validated with a pydantic model built by arguments_model, as an endpoint's are, so every tool takes one path. - An unknown argument to a tool method reads "Extra inputs are not permitted". - A tool method's parameter can't be named model_config, start with _, or have the name of a BaseModel attribute, such as json: @tool raises DefinitionError. - The function-call validator is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DxGAoNbvS2EgPqBDbxUdKS
- A parameter whose type is, or holds, SecretStr, SecretBytes or Secret[...] raises DefinitionError when the class is defined: pydantic dumps one as "**********", so the API got the stars. - The message points to the client's auth= for credentials, or str to send the value. - A model's own secret fields are left to its author. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DxGAoNbvS2EgPqBDbxUdKS
- List each way a value can't go to its part, and each way the parameters don't fit together, on its own line. - No behavior changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DxGAoNbvS2EgPqBDbxUdKS
- Give each reason the errors guide lists for ArgumentError its own bullet, validation first. - No behavior changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DxGAoNbvS2EgPqBDbxUdKS
- Give plain values, helper arguments and defaults their own subsections under The helpers, each a lead sentence and a list. - Link the helpers table's first plain value to the new section. - No behavior changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DxGAoNbvS2EgPqBDbxUdKS
- Turn the path parameter rules, path errors, JSON rules, raw body, files, helper placement and dict-for-a-model text into lead sentences and lists. - Link the path parameter rule to the plain values section. - No behavior changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DxGAoNbvS2EgPqBDbxUdKS
- Turn lists packed into one sentence into lead sentences and lists: the verbs, the reasons not to use event hooks for credentials, the path, helper and ToolError errors, the reference's imports, return annotations, helpers, plain values, list_tools, hints, @tool and fastmcp_tool, and @tool's rules. - Link the reference's plain value to the requests guide's definition. - No behavior changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DxGAoNbvS2EgPqBDbxUdKS
- Require SkipValidation on a File() or Body() only when its type holds something pydantic can't validate, such as a binary file, a stream or Any. A (filename, content, content_type) tuple of str and bytes, or a list of them, validates and dumps as it is. - Check a file's or raw body's shape, and a stream's kind, before a missing SkipValidation, so Path gets the error that says what a file is. - Found by running gravitywell against this branch: its Teleporter upload failed at import. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Add _request_schema.py for what the rules and the routes both read: each field's serialization schema, whether it dumps to a plain value, spreading, and the keys values are sent under. - Leave _request_rules.py with only the rules and their errors, so the routes no longer import from it. - Note the new module in CLAUDE.md. - No behavior changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Drop SkipValidation from the files and JSON part samples, whose file tuples are validated now. - Say which File() and Body() types need it, a binary file, a stream or Any, in the requests guide, the errors guide, the reference, llms.txt and CLAUDE.md, and show the tuple case in the changelog entry. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Move SkipValidation onto the BytesIO case of the file values test, so the (filename, content, content_type, headers) case runs without it. - No behavior changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Give the helper reference an example of a default after = and of a default_factory with = None. - Name self as the first parameter, which the request model leaves out, in _request_model.py's docstrings. - No behavior changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Replaces the request planner and its per-argument specs with a pydantic model of each endpoint's parameters. The model is built when the class is defined, its fields are checked against the path and the helpers, and every call is validated with it before the request is built from the validated values. Tools validate with the same kind of model.
Changes
_request_model.py):build_request_modelturns an endpoint's parameters into a model withcreate_model. Each field keeps its full annotation and its default, andtypealiases are expanded so their helpers count. Before the model is built, the parameters are checked for nested helpers orSend, adefaultinside a helper, adefault_factorywithout= None, and names a model can't hold.arguments_modelbuilds the model itself, for endpoints and@toolmethods alike._request_rules.py): every definition rule runs on the model's fields, oneifper rule. A value is judged by what it dumps to, from the model's serialization schema, so a type with a serializer that dumps to text fits a query, header or form. AFile()orBody()typed anything butstrorbytesneedsSkipValidation._request_routes.py,_builder.py): routes say where each field goes. The builder dumps each validated field on its own, honours pydantic'sexclude_if, and still raises for NaN in JSON.strict=Truefor one strict parameter. A failure raisesArgumentErrornaming the parameter, with theValidationErroras its cause, before anything is sent.@toolmethod with a model of its own parameters. An unknown argument is rejected with pydantic's "Extra inputs are not permitted"._planner.pyand its specs,_validation.py, the client'svalidate_arguments=, andSend'sexclude_unset,exclude_noneandexclude_defaults.Sendkeepsembedandjson_part._paths.py, and the type helpers to_annotations.py, unchanged.SkipValidation,default_factory,exclude_ifand serializers. The reference, errors and tools pages,llms.txt,CLAUDE.mdand the changelog are updated.Breaking changes
All are listed in
CHANGELOG.mdunder[Unreleased], each with its fix:Query(ge=1), raisesArgumentError. Astrfor aSequence[str]parameter fails.3for afloatgoes out as3.0, a model is sent as its annotated type (SerializeAsAnykeeps a subclass's fields), and adictpassed for a model is read as the model reads one, by alias, with keys it doesn't have dropped.File()andBody()parameters whose type holds a binary file, a stream orAny(BinaryIO,Iterator[bytes]) needSkipValidation.str,bytes, and file tuples and lists of them, such astuple[str, bytes, str], are validated and need none.@toolmethod, can't be namedmodel_config, start with_, or have the name of aBaseModelattribute such asjson.validate_arguments=andSend'sexclude_*options are gone: useexclude_ifon the helper.SecretStr,SecretBytes,Secret[...]) raisesDefinitionError: pydantic sends one as**********, asmainlinedid for aJson()secret. Credentials go inauth=.Performance
Measured on a Raspberry Pi against
mainline, sending through a mock transport, best of 7 repeats:mainlinewithvalidate_arguments=True.list_toolsis about 25% faster, as it reuses the models built at definition.create_model. A 100-endpoint client imports about 80 ms slower on the Pi, against about 200 ms forimport clientxitself. A follow-up can skip the schema where an annotation's type already settles a rule, keeping every check at definition.Testing
make check: ruff, pyright (strict) and mypy, and 380 tests at 99% coverage. Each rule has a test, and the docs samples run.tuple[str, bytes, str]Teleporter upload, which led to letting file tuples ofstrandbytesgo withoutSkipValidation. Itsmainline, unchanged, now passes all 361 tests here, and a live Pi-hole (FTL v6.9) accepted the requests the branch builds, Teleporter export and multipart restore included.🤖 Generated with Claude Code
https://claude.ai/code/session_01DxGAoNbvS2EgPqBDbxUdKS