Skip to content

feat: Validate every call with a pydantic model of the endpoint's parameters - #196

Merged
slatecipher merged 34 commits into
mainlinefrom
feat/endpoint-model
Dec 3, 2026
Merged

slatecipher merged 34 commits into
mainlinefrom
feat/endpoint-model

Conversation

@slatecipher

@slatecipher slatecipher commented Dec 2, 2026 •

Copy link
Copy Markdown
Owner

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 (_request_model.py): build_request_model turns an endpoint's parameters into a model with create_model. Each field keeps its full annotation and its default, and type aliases are expanded so their helpers count. Before the model is built, the parameters are checked for nested helpers or Send, a default inside a helper, a default_factory without = None, and names a model can't hold. arguments_model builds the model itself, for endpoints and @tool methods alike.
  • Rules (_request_rules.py): every definition rule runs on the model's fields, one if per 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. A File() or Body() typed anything but str or bytes needs SkipValidation.
  • Routes and builder (_request_routes.py, _builder.py): routes say where each field goes. The builder dumps each validated field on its own, honours pydantic's exclude_if, and still raises for NaN in JSON.
  • Every call is validated, in pydantic's lax mode, with a helper's strict=True for one strict parameter. A failure raises ArgumentError naming the parameter, with the ValidationError as its cause, before anything is sent.
  • Tools: an endpoint's tool validates with its request model, and a @tool method with a model of its own parameters. An unknown argument is rejected with pydantic's "Extra inputs are not permitted".
  • Removed: _planner.py and its specs, _validation.py, the client's validate_arguments=, and Send's exclude_unset, exclude_none and exclude_defaults. Send keeps embed and json_part.
  • Moved: the path parser to _paths.py, and the type helpers to _annotations.py, unchanged.
  • Docs: the requests guide gains "Validating arguments", moved from the configuration page, and covers SkipValidation, default_factory, exclude_if and serializers. The reference, errors and tools pages, llms.txt, CLAUDE.md and the changelog are updated.

Breaking changes

All are listed in CHANGELOG.md under [Unreleased], each with its fix:

  • Every call is validated, so an argument that doesn't fit its annotation, or a helper constraint such as Query(ge=1), raises ArgumentError. A str for a Sequence[str] parameter fails.
  • The validated values are sent: 3 for a float goes out as 3.0, a model is sent as its annotated type (SerializeAsAny keeps a subclass's fields), and a dict passed for a model is read as the model reads one, by alias, with keys it doesn't have dropped.
  • File() and Body() parameters whose type holds a binary file, a stream or Any (BinaryIO, Iterator[bytes]) need SkipValidation. str, bytes, and file tuples and lists of them, such as tuple[str, bytes, str], are validated and need none.
  • A parameter, on an endpoint or a @tool method, can't be named model_config, start with _, or have the name of a BaseModel attribute such as json.
  • validate_arguments= and Send's exclude_* options are gone: use exclude_if on the helper.
  • A parameter typed as a pydantic secret (SecretStr, SecretBytes, Secret[...]) raises DefinitionError: pydantic sends one as **********, as mainline did for a Json() secret. Credentials go in auth=.

Performance

Measured on a Raspberry Pi against mainline, sending through a mock transport, best of 7 repeats:

  • Calls cost 3 to 14% more (4 to 22 µs on 80 to 190 µs), about the same as mainline with validate_arguments=True.
  • list_tools is about 25% faster, as it reuses the models built at definition.
  • Defining a class is about 3.4 times slower: about 0.8 ms more per endpoint, half of it generating the serialization schema and most of the rest create_model. A 100-endpoint client imports about 80 ms slower on the Pi, against about 200 ms for import clientx itself. 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.
  • A route-parity check during the migration compared the new routes with the old planner's for 292 endpoints from the test suite: no differences.
  • gravitywell, the first real client, run against this branch: the first run failed at import on its tuple[str, bytes, str] Teleporter upload, which led to letting file tuples of str and bytes go without SkipValidation. Its mainline, 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.
  • A burn-in against a local httpbin: 97 live checks of paths, query values, headers, spreading, JSON, raw and streamed bodies, forms and files, responses, async clients, tools, and the new definition errors, all passing.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DxGAoNbvS2EgPqBDbxUdKS

slatecipher and others added 23 commits December 1, 2026 15:55
- 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
@slatecipher slatecipher added breaking change Changes public API behavior; call out in the changelog enhancement New feature or request labels Dec 2, 2026
@slatecipher slatecipher self-assigned this Dec 2, 2026
slatecipher and others added 4 commits December 1, 2026 20:24
- 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
slatecipher and others added 7 commits December 1, 2026 20:40
- 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>
@slatecipher
slatecipher merged commit 3dcddef into mainline Dec 3, 2026
8 checks passed
@slatecipher
slatecipher deleted the feat/endpoint-model branch December 3, 2026 00:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

breaking change Changes public API behavior; call out in the changelog enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant