In the example, the number 5 appears in three files. functions.py sets MAX_PAGE_SIZE = 5 and never returns more passages than that from search_guidance. The docstring of the same function says top_k means "How many passages to return in this page, at most 5." And tools.py, in the input schema the model is given, says "maximum": 5. Today the three agree.
Now picture an ordinary change (illustrative; it has not happened in the example). A developer raises the page size to 10 in functions.py, updates the docstring, runs the unit tests of the function, and ships. The schema in tools.py still says 5. Nothing fails. The model keeps asking for at most 5 passages, because the definition tells it to, and the larger page is never used. The reverse change is worse: lower the page size to 3 in the function and leave the schema at 5, and a call with top_k 5 passes validation and gets three passages with no explanation. The tool's contract has two authors, and one of them did not hear about the change.
Schemas wrote the tool definition by hand: a name, a description and a JSON Schema for the arguments, which the model reads and the application validates. This page asks where that schema should come from. The answer most teams reach is the one compilers have offered for decades: write the shape of the data once, as a type, and let the schema, the validation and the typed object the function receives all come from it. The model proposes a call. Your code decides whether it runs, and on this page your code also decides what the model is told.
One shape, written once#
A type hint is a note in Python code that says what kind of value a parameter expects: in submission_id: str, the hint is str. Python does not use it while the program runs. The Python documentation, read on 2026-11-17, says so directly: the Python runtime does not enforce function and variable type annotations. Type checkers, editors and libraries read them. A function annotated submission_id: str will accept 1004 without complaint.
That is exactly why hints are useful here. They are written next to the code, so they change when the code changes, and a program can read them. If a program can read submission_id: str, it can write {"type": "string"}. That act, turning a type in code into a JSON Schema, is schema generation, and it removes one of the two authors from the story above.
Before AI. Java teams know this pattern from HTTP APIs. A Spring controller takes a request body as a class with fields and validation annotations; the framework turns the JSON body into that class, validates it, and an OpenAPI document can be generated from the same class. Nobody edits the OpenAPI file by hand, because the class is the source. The class is a data transfer object, and the tool's arguments are the same kind of thing: a shape that exists only to carry data across a boundary.
That kind of class has a name worth keeping. A DTO (data transfer object) is a type with fields and no behavior, used only to carry data from one system to another. A tool's arguments are a DTO whose sender is a model.
Diagram: One typed source, three things that must agree
Read left to right. The type is written once, next to the code. From it come the schema the model reads, the validator the adapter runs, and the typed object the function receives. A constraint the type cannot carry must be attached to it, or it is missing from all three.
- 1 · Written once
- Typed source: The shape of the arguments, declared in code next to the function.
- Constraints: Patterns, ranges, enums of nested fields: attached to the type or kept in one table beside it.
- 2 · Generated
- Input schema: Produced from the type and the constraints; never edited by hand.
- Validator: Checks each call against the same shape before the function runs.
- 3 · Received
- Typed object: A value that has passed validation; the function can trust its shape.
- 4 · Proven
- Equality test: Fails the build when the generated schema and the definition differ.
The diagram shows the goal. One typed source produces three things: the schema the model reads, the validator the adapter runs, and the typed object the function receives. When the type changes, all three change together. The rest of this page shows how close each language gets to that goal, and the specific places where it falls short.
The smallest version: a function's hints become its schema#
Here is the function behind get_roof_assessment, quoted from functions.py (the signature and the start of the docstring; the rest is left out):
def get_roof_assessment(world: World, submission_id: str) -> dict[str, Any]:
"""Ask the roof-data provider for the assessed roof age of one submission.
Args:
submission_id: The id of the submission, for example SUB-1004.
"""
Two parameters, and only one belongs to the model. world holds the provider stand-in, the stored rows and the clock; the application passes it, and the model must never see it. submission_id is the argument the model fills in.
The example's schema.py has a function, schema_from_function, that reads the signature, the type hints and the Args: section of the docstring, skips parameters named in skip (by default world), and builds an input schema. A parameter without a default becomes required. Its core is a small mapping from Python types to JSON Schema types, quoted from schema_for_hint:
simple = {str: "string", int: "integer", float: "number", bool: "boolean", type(None): "null"}
if hint in simple:
return {"type": simple[hint]}
The script below was written for this page and run in a scratch copy of the example. It generates the schema of a tool from its function, then compares the result with the hand-written definition in tools.py using schema.losses, which lists every keyword the definition has and the generated schema lacks. A successful run proves two things: generation recovers the type, the required list and the description from the code, and it cannot recover the pattern. The model here is a scripted stand-in, so these results show how the tool layer works, not how good any model is.
import json
import sys
from schema import losses
from tools import REGISTRY, generated_schema
tool = REGISTRY.resolve(sys.argv[1])
generated = generated_schema(tool)
print("generated from the hints:")
print(json.dumps(generated, indent=2))
print("lost, compared with the tool definition:")
for row in losses(generated, tool.input_schema):
print(f" {row['path'] or '(root)'} {row['keyword']}")
with_table = generated_schema(tool, with_constraints=True)
print("with the constraints table, still lost:", losses(with_table, tool.input_schema))
cd examples/uw-tools
/opt/homebrew/bin/python3 show_generated.py get_roof_assessment
generated from the hints:
{
"type": "object",
"properties": {
"submission_id": {
"type": "string",
"description": "The id of the submission, for example SUB-1004."
}
},
"required": [
"submission_id"
],
"additionalProperties": false
}
lost, compared with the tool definition:
/submission_id pattern
with the constraints table, still lost: []
Almost everything came from the code: the type, the description, the fact that the field is required, and no trace of world. One keyword is missing, and it is the one that would have caught "SUB-04". A plain str is any text. The rule that a submission id is SUB- and four digits lives nowhere in the type, so no generator can find it.
What generation loses#
The loss is small for one string and large for a nested object. record_recommendation takes the recommendation as recommendation: dict[str, Any], a dictionary with text keys and any values. Run the same script on it:
/opt/homebrew/bin/python3 show_generated.py record_recommendation
generated from the hints:
{
"type": "object",
"properties": {
"submission_id": {
"type": "string",
"description": "The id of the submission, for example SUB-1004."
},
"recommendation": {
"type": "object",
"description": "The recommendation: what is recommended, the reasons, the cited rule ids."
},
"idempotency_key": {
"type": "string",
"description": "The same value for every attempt of one logical write."
}
},
"required": [
"submission_id",
"recommendation",
"idempotency_key"
],
"additionalProperties": false
}
lost, compared with the tool definition:
/submission_id pattern
/recommendation/recommendation type
/recommendation/recommendation enum
/recommendation/reasons type
/recommendation/reasons/items type
(24 rows left out here: the types, lengths, counts, patterns and ranges of the other fields)
/recommendation required
/recommendation additionalProperties
/idempotency_key pattern
with the constraints table, still lost: []
(The output is trimmed in the middle, where the comment line says so; the full run printed 30 lost keywords.) The generated schema says that the recommendation is "an object", and nothing else. The enum of four verdicts, the const: true on requires_human, the pattern of a rule id, the seven required fields and the ban on extra fields are all gone. A model given this schema could write {"verdict": "bind"} and the generated validator would accept it. Every rule that Schemas wrote into the write tool to protect the underwriter's queue disappeared, because dict[str, Any] says nothing about its contents.
There are two ways to close the gap, and the example has both. The first is a constraints table next to the definitions: tools.CONSTRAINTS holds, per tool and parameter, exactly the keywords a hint cannot carry, and generated_schema(tool, with_constraints=True) merges them in. The last line of each run above shows the result: nothing lost, and the test test_constraints_table_closes_the_gap in test_tools.py checks this equality for all five tools on every run.
The second way puts the constraint on the type itself. Python's typing.Annotated[T, x] attaches metadata x to a type T; the typing documentation says static checkers treat it as T and tools that do not understand the metadata should too. The example reads its own Constraint metadata, and typing.Literal lists the allowed values. This function is quoted from the test test_annotated_constraint_and_literal:
def lookup(world: Any, submission_id: Annotated[str, Constraint(pattern="^SUB-[0-9]{4}$")],
mode: Literal["summary", "report"] = "summary") -> None:
"""Look something up.
Args:
submission_id: The id.
mode: How much to return.
"""
The test asserts that the generated schema of submission_id is {"type": "string", "pattern": "^SUB-[0-9]{4}$", "description": "The id."}, that mode becomes an enum of summary and report, and that only submission_id is required. The pattern now lives in the code, next to the parameter it constrains. That is the closest a plain Python function gets to one source.
Here is the comparison, which the lab below lets you walk through rung by rung:
| What the type says | Generated keyword | What it cannot say |
|---|---|---|
str | "type": "string" | the pattern of an id, a length |
int | "type": "integer" | a range such as 1 to 5 |
str with a default of None | "type": ["string", "null"], not required | when null is meaningful |
Literal["summary", "report"] | "enum": [...] | what each value means |
Annotated[str, Constraint(pattern=...)] | "pattern": ... added | rules across fields |
dict[str, Any] | "type": "object" | every field inside |
The lab walks record_recommendation up six rungs, from the Python function to an MCP tools/call. Edit the arguments to a bad value and see on which rung it is caught. The table after it holds the same information.
| Rung | What it holds | A recommendation of "bind" instead of one of the four verdicts |
|---|---|---|
| 1. Python function | record_recommendation(world, submission_id: str, recommendation: dict[str, Any], idempotency_key: str); the model never sees it | not checked |
| 2. Type hints | dict[str, Any]; Python does not check hints when the function runs | not checked |
| 3. Generated schema | recommendation is {"type": "object"}; 30 keywords lost | not caught: any object passes |
| 4. Tool definition | the full schema, with the constraints table merged in | caught: /recommendation/recommendation enum |
| 5. MCP tools/list entry | the same schema as inputSchema, plus title and annotations | |
| 6. MCP tools/call | result with isError true and an invalid_arguments result, attempt_number 0 | the function never runs; no row is written |
Pydantic: the model class is the schema and the validator#
Pydantic is a Python library that validates data against classes declared with type hints. Its documentation, read on 2026-11-17 (it has moved from docs.pydantic.dev to pydantic.dev), states version 2.14.3. It does in one class what the example does with three pieces: hints, a constraints table and a validator.
The shape below is the documented shape; not run here. It describes the arguments of record_recommendation as two classes. Each Field(...) carries a constraint that a plain hint could not, and model_json_schema() returns the JSON Schema.
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
class Recommendation(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
recommendation: Literal["approve", "decline", "request_info", "escalate"]
reasons: list[str] = Field(min_length=1, max_length=8)
citations: list[str] = Field(max_length=10)
missing: list[str]
stated_confidence: float = Field(ge=0, le=1)
requires_human: Literal[True]
policy_version: str = Field(pattern=r"^[0-9]{4}\.[0-9]+$")
class RecordRecommendationArgs(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
submission_id: str = Field(pattern=r"^SUB-[0-9]{4}$", description="The id of the submission, for example SUB-1004.")
recommendation: Recommendation
idempotency_key: str = Field(pattern=r"^SUB-[0-9]{4}:run-[0-9a-f]{4}:recommendation$")
schema = RecordRecommendationArgs.model_json_schema()
args = RecordRecommendationArgs.model_validate(call_arguments)
The documentation read today supports each piece. Field() takes pattern, min_length, max_length, ge, le and strict. model_json_schema() returns a dictionary that follows JSON Schema 2020-12, and nested models go into $defs and are referenced with $ref. The extra setting has three values, and its default is 'ignore': extra fields are dropped silently unless you choose 'forbid'. Strict mode can be set per field, per model with ConfigDict(strict=True), or per call.
Two of those defaults matter for tools. The first is coercion. Without strict mode Pydantic converts values where it can: the strict-mode page shows {'x': '123'} validated into an integer field as x=123. A model that writes "5" for top_k would be quietly accepted. That page does not say what lax mode does with an integer given for a text field, which is the UW-T01 mistake; with strict mode on, the question does not arise. The second is extra. With the default 'ignore', {"submission_id": "SUB-1004", "detail": "full"} validates and detail disappears, so the function never learns the model asked for something it does not offer. Set extra="forbid", and check the generated schema before you send it: the pages read today do not say whether 'forbid' produces additionalProperties: false in the schema.
The citations pattern is missing from the class above on purpose. A pattern on each element of a list needs list[Annotated[str, Field(pattern=...)]], which the fields page describes for list elements. It is the same lesson as dict[str, Any]: a constraint that is not on the type is not in the schema. Frameworks describes Pydantic in its own section, with validate_call, which validates a function's arguments against its hints before it runs.
Java: a record that cannot hold a bad value#
Java has a construct that fits a DTO closely. A Java record is a class declared by its components, such as record RoofAssessmentRequest(String submissionId), for which Java derives the canonical constructor, the accessors and methods such as equals automatically. JEP 395, read on 2026-11-17, delivered records in Java 16, and it says three things that matter here. A record is final and its fields are final. Its canonical constructor can be written in a compact form, without a parameter list. And in the compact form the fields are assigned automatically after the body runs, which makes the body the place for validation: if the body throws, no instance exists.
The example's java/TypedTool.java uses exactly that. Here is the input of get_roof_assessment, quoted from the file:
/** The input of get_roof_assessment. The compact constructor is stage 3: no invalid instance can exist. */
record RoofAssessmentRequest(String submissionId) {
RoofAssessmentRequest {
if (!SUBMISSION_ID.matcher(submissionId).matches())
throw new Rejected("validate", "/submission_id", "must match ^SUB-[0-9]{4}$; got \"" + submissionId + "\"");
}
}
Between the model's JSON and this record sits a step that every typed language needs. Deserialization is turning text, here a JSON object, into an instance of a type: reading {"submission_id": "SUB-1004"} and calling new RoofAssessmentRequest("SUB-1004"). It is where a wrong type, a missing field or an unknown field is found, before any constructor runs. The file does this by hand, with a small JSON parser and a bindRoof method, so that it runs on the standard library alone:
static RoofAssessmentRequest bindRoof(Map<String, Object> m) {
onlyFields(m, "submission_id");
return new RoofAssessmentRequest(requiredString(m, "submission_id"));
}
So every payload passes four stages in order. Parse turns JSON text into a map. Bind turns the map into the record's fields, refusing unknown fields, missing fields and wrong types. Validate is the compact constructor. Handle is the tool body, which only ever sees a valid record and returns the result envelope.
The program was compiled and run as a single-file program with the local JDK, openjdk version "23.0.1" 2024-10-15, in a scratch copy of the example. A successful run proves that each kind of bad payload is stopped at the stage that owns it, and that every rejection reaches the model as invalid_arguments with attempt_number 0, meaning the handler never ran. It does not prove what Jackson or Spring would do: the file's comments describe that, and none of it was run here.
cd examples/uw-tools/java
java TypedTool.java
valid handle - {"ok": true, "data": {"submission_id": "SUB-1004", "roof_age_years": 22, "evidence_id": "EV-ROOF-0412"}, "meta": {"tool": "get_roof_assessment", "attempt_number": 1, "evidence_ids": ["EV-ROOF-0412"]}}
wrong type bind /submission_id {"ok": false, "error": {"code": "invalid_arguments", "message": "/submission_id: expected string, got integer", "retryable": false}, "meta": {"tool": "get_roof_assessment", "attempt_number": 0, "evidence_ids": []}}
missing field bind /submission_id {"ok": false, "error": {"code": "invalid_arguments", "message": "/submission_id: missing required field submission_id", "retryable": false}, "meta": {"tool": "get_roof_assessment", "attempt_number": 0, "evidence_ids": []}}
unknown field bind /detail {"ok": false, "error": {"code": "invalid_arguments", "message": "/detail: unknown field detail", "retryable": false}, "meta": {"tool": "get_roof_assessment", "attempt_number": 0, "evidence_ids": []}}
bad pattern validate /submission_id {"ok": false, "error": {"code": "invalid_arguments", "message": "/submission_id: must match ^SUB-[0-9]{4}$; got \"SUB-04\"", "retryable": false}, "meta": {"tool": "get_roof_assessment", "attempt_number": 0, "evidence_ids": []}}
malformed JSON parse - {"ok": false, "error": {"code": "invalid_arguments", "message": "malformed JSON: unexpected end at 29", "retryable": false}, "meta": {"tool": "get_roof_assessment", "attempt_number": 0, "evidence_ids": []}}
valid write handle - {"ok": true, "data": {"recommendation_id": "REC-0001", "submission_id": "SUB-1004", "recommendation": "escalate", "status": "awaiting_underwriter"}, "meta": {"tool": "record_recommendation", "attempt_number": 1, "evidence_ids": []}}
value outside the enum bind /recommendation {"ok": false, "error": {"code": "invalid_arguments", "message": "/recommendation: must be one of approve, decline, request_info, escalate; got \"bind_policy\"", "retryable": false}, "meta": {"tool": "record_recommendation", "attempt_number": 0, "evidence_ids": []}}
bad idempotency key validate /idempotency_key {"ok": false, "error": {"code": "invalid_arguments", "message": "/idempotency_key: must match ^SUB-[0-9]{4}:run-[0-9a-f]{4}:recommendation$", "retryable": false}, "meta": {"tool": "record_recommendation", "attempt_number": 0, "evidence_ids": []}}
The columns are the payload, the stage that stopped it, the path, and the envelope the model reads. Look at where each row stops. UW-T01's number stops at bind, because the JSON type is wrong before any record exists. "SUB-04" passes bind, since it is a string, and stops at validate, in the constructor. bind_policy stops at bind, because the recommendation is a Java enum and binding is where text becomes an enum constant. In this file the recommendation is simplified to that one enum value; the full recommendation object of the Python example is not modelled. The output is identical to the run recorded in the example's README.
The lab below shows the recorded output of this program; it runs no Java in the browser. Pick a payload and see which stage rejects it and the envelope the model receives. The table after it holds the same information.
| Payload | Stage that stopped it | Path | Message in the envelope |
|---|---|---|---|
{"submission_id": "SUB-1004"} | handle (runs) | ok, roof age 22, EV-ROOF-0412 | |
{"submission_id": 1004} | bind | /submission_id | expected string, got integer |
{} | bind | /submission_id | missing required field submission_id |
{"submission_id": "SUB-1004", "detail": "full"} | bind | /detail | unknown field detail |
{"submission_id": "SUB-04"} | validate | /submission_id | must match ^SUB-[0-9]{4}$ |
{"submission_id": "SUB-1004" | parse | malformed JSON: unexpected end at 29 | |
| valid write | handle (runs) | ok, REC-0001, status awaiting_underwriter | |
recommendation bind_policy | bind | /recommendation | must be one of approve, decline, request_info, escalate |
idempotency key retry-2 | validate | /idempotency_key | must match the key pattern |
Every rejected payload gets invalid_arguments with attempt_number 0: nothing ran.
Diagram: TypedTool.java: four stages, each owns one kind of mistake
A payload moves left to right. Each stage stops one kind of mistake and reports the path. Every rejection reaches the model as invalid_arguments with attempt number 0, because the handler never ran.
- 1 · Parse
- JSON text to map: A tiny parser stands in for a library such as Jackson.
- 2 · Bind
- Map to fields: Refuses an unknown field, a missing field, a wrong JSON type and a value outside the enum.
- 3 · Validate
- Compact constructor: Checks the patterns; if it throws, no instance is created.
- 4 · Handle
- Tool body: Runs the tool and returns the result envelope.
The Java libraries, as documented#
In production Java, two libraries usually take the parse and bind stages and part of validate. They are described here from their documentation read on 2026-11-17; none of this was run.
Jackson is the common JSON library. Its wiki page on deserialization features (for Jackson 2) documents three defaults that decide what bind does. FAIL_ON_UNKNOWN_PROPERTIES is on by default, so an unknown field such as detail fails. FAIL_ON_MISSING_CREATOR_PROPERTIES is off by default, so a missing constructor property is filled with a null-style placeholder instead of failing: a missing submission_id would reach the record as null. And ACCEPT_FLOAT_AS_INT is on by default, so 1.25 given for an integer is truncated to 1. A framework may configure its mapper differently from these library defaults, and the Spring Boot pages read today do not list what its auto-configured mapper changes. Set the features you depend on explicitly, and write a test that sends an unknown field, a missing field and a fractional number.
Jakarta Validation (formerly Bean Validation; version 3.1 is the latest release and requires Java 17) expresses constraints as annotations. The specification's @Pattern takes a regexp, follows Java regular expression conventions, and considers null valid, so a required pattern needs @NotNull as well. The specification says records are supported, with constraints declared on the record components, and it also says a framework does not validate a record automatically in every environment: it states there are no requirements for providers to validate records automatically in Jakarta Context and Dependency Injection environments. Annotations describe; something must call the validator. The compact constructor of TypedTool.java has no such dependency, which is why the example uses it.
Spring AI turns annotated methods into tools. Its tool-calling page (version 2.0.2) says a JsonSchemaGenerator builds the input schema from a method's parameter list, takes descriptions from @ToolParam or from Jackson and Swagger annotations, and makes every parameter required by default. The page does not mention Jakarta Validation annotations, and it does not describe how the model's JSON arguments are turned into method parameters. So, as far as that documentation says, a @Pattern on a parameter is not known to appear in the generated schema. Generate the schema, print it, and compare it with what you meant, exactly as schema.losses does for the Python example. Frameworks describes Spring AI in its own section.
What this is not. This page covers where a tool's input schema comes from and how a typed handler rejects bad arguments. Typed data contracts in general, parsing and repairing model output, and evolving a schema without breaking its readers belong to Schema Engineering.
When the type and the schema disagree#
The failure this page exists to prevent is quiet. The example shows its most direct form. With validation switched off in the adapter, UW-T01's {"submission_id": 1004} reaches get_roof_assessment, whose hint says str. Python does not object. The test test_without_validation_the_bad_value_reaches_the_provider in test_tools.py records the outcome: the provider stand-in is called once and the result is not_found. The hint was a promise nobody checked, and the model was told something false.
Drift produces the same kind of result more slowly. The schema says one thing, the function does another, and every call that falls in the gap succeeds with a wrong answer, or fails in a way that does not mention the cause. A generated schema with a test that compares it to the definition, as test_constraints_table_closes_the_gap does, turns that gap into a failing build.
In a coding agent. A coding agent'sedit_file(path: str, old_text: str, new_text: str)gets a clean generated schema: three required strings. The type says nothing about the most important rule, thatpathmust stay inside the repository. That rule cannot live in a hint or a pattern; it lives in the harness code that resolves the path before writing. Generated schemas are good at shape and silent about authority. Harness Engineering covers the runtime that holds those checks.
Code first or schema first?Generate the schema from types, or generate types from a schema: both remove a second author
This page generates the schema from the code. The opposite design is equally old: write the JSON Schema (or an OpenAPI document) as the source, and generate the Python classes or Java records from it. Both remove the second author; they differ in who owns the contract.
Code first suits a tool owned by the team that writes the function. The schema follows every refactoring, the compiler and type checker help, and the test that compares generated and published schemas is short. Its weakness is that the published contract changes whenever someone renames a field, which is a breaking change for every caller that cached the old definition. A rename that looks like a cleanup in a pull request is a new tool for the model and an invalid call for every replayed trace.
Schema first suits a tool offered to many clients, for example from an MCP server used by several teams. The schema is reviewed as an interface, changes are deliberate, and each language generates its own types. Its weakness is the generator: each one supports a different part of JSON Schema, and a constraint the generator cannot express in types (a pattern, a const) must still be enforced by a validator that reads the schema itself.
A defensible middle is the one the example uses: types in code, constraints that types cannot carry in one table next to them, a generated schema, and a test that fails when the generated schema and the published definition differ. Whichever direction you choose, the test is what makes it one source.
Reading hints at run time has costsForward references, imports for type checkers only, and code inside annotations
schema_from_function calls typing.get_type_hints(fn, include_extras=True). The Python documentation, read on 2026-11-17, describes several behaviors of that function that a generator inherits. It evaluates annotations written as strings, so a hint that names a class imported only under if TYPE_CHECKING: raises NameError when the schema is generated, in production, on the first request. It strips Annotated unless include_extras=True is passed, which would silently drop every Constraint in the example. And the documentation warns that it may execute arbitrary code found in annotations.
Each of these has a simple defence. Generate every tool schema once, at start-up or in a build step, never lazily per request, so a broken hint fails a deploy and not a call. Keep include_extras=True covered by a test, as the example's test_annotated_constraint_and_literal does. And treat the modules that define tools as trusted code, because generating their schemas runs their annotations.
A second cost is semantic. Optional[str], a default of None, and "may be null" are three different statements that hints blur together. The example writes a parameter with a default as not required, and str with a default of None as ["string", "null"]. OpenAI's strict mode, as documented on 2026-11-17, wants every field required and nullable instead; Anthropic's strict mode allows optional fields. One function, two correct schemas, depending on the provider. Decide which one your generator produces, and test it against the provider you call.
Java: where a bad value slips between the stagesLibrary defaults, nulls from missing fields, and annotations nobody calls
The hand-written binder in TypedTool.java is strict on purpose: unknown field, missing field and wrong type all fail at bind with a path. A real deserializer has settings, and its defaults are not all strict. With Jackson 2's documented defaults, a missing creator property becomes a null-style placeholder. The compact constructor then calls SUBMISSION_ID.matcher(null), which throws a NullPointerException (checked with a three-line program on the same JDK 23.0.1), not the Rejected the adapter turns into invalid_arguments. The model would get an internal error for what is really a missing argument, and depending on how the exception is handled, the message might name a Java class. Either turn on FAIL_ON_MISSING_CREATOR_PROPERTIES or check for null first in the constructor.
Fractional numbers are the other quiet case. With ACCEPT_FLOAT_AS_INT on by default, top_k: 2.5 becomes 2. The Python validator in the example refuses 2.5 with type: expected integer, got number, and accepts 2.0 because JSON Schema counts 1.0 as an integer. The same tool, written twice, accepts different inputs unless both stacks are configured to agree, and a contract test that sends the same payloads to both is the only reliable check.
Then there are annotations that look like validation and are not run. A @Pattern on a record component documents a rule. The rule is enforced only when something calls a validator: a framework that does so for method parameters, or code you write. The Jakarta specification states that records are not validated automatically in every container environment. A compact constructor costs a few lines and runs every time the record is built, in every environment, including tests. Use annotations where a framework you rely on is documented to run them, and the constructor where the rule must hold everywhere.
One model, two schemas, and the provider's subsetValidation and serialization schemas differ, $ref may not be supported, and lax mode accepts more than the schema says
Pydantic's JSON Schema page, read on 2026-11-17, says model_json_schema() produces the validation schema by default and that the serialization schema can differ; its example is a Decimal field that accepts a number or a string when validating but is written out as a string. For a tool, the schema the model reads is the validation schema. Sending the serialization schema would tell the model a narrower truth than the code accepts, or a wider one.
Nested models go into $defs and are referenced with $ref. MCP's inputSchema may use any 2020-12 keyword, but a provider's strict mode may not accept all of them: Anthropic's subset, as documented on 2026-11-17, supports internal $ref and $defs but not recursive schemas, and does not support minimum, maximum, minLength or maxLength at all. A model class with a numeric range produces a schema that Anthropic's SDK helpers, as documented, rewrite by moving the range into the description. The class still validates the range in code; the model sees it only as text.
Lax mode adds a third gap. Without strict mode, Pydantic accepts "123" for an integer field, while the generated schema says "type": "integer". The schema the model reads is stricter than the validator that runs. That is harmless for a read and risky for a write, where a coerced value can change meaning. Use strict mode on every argument model of a write tool.
Checklist for Monday#
| Check | Why |
|---|---|
| Each tool's schema is generated from one typed source, at start-up or build time | A hand-written copy drifts; a lazy generator fails on a live request |
| A test compares the generated schema with the published definition | It turns drift into a failing build (test_constraints_table_closes_the_gap) |
Constraints a type cannot carry live next to the type: Annotated, Field(...), a constraints table | str and dict[str, Any] lose patterns, enums and nested rules |
| Parameters the model must not see are skipped by the generator | world never appears in a schema |
| Argument models of write tools use strict mode and forbid extra fields | Coercion and silently dropped fields change meaning |
| Java deserializer features are set explicitly and covered by tests | Library defaults turn a missing field into null and 2.5 into 2 |
| Rules that must hold everywhere are in the record's compact constructor | Annotations run only when something calls a validator |
| The generated schema is printed and checked against each provider's strict subset | Each provider enforces a different part of JSON Schema |
In one breath#
A schema written by hand is a second description of the function, and it drifts. Generate it from one typed source instead: type hints, a Pydantic model or a Java record, with the constraints that types cannot carry, such as patterns and nested rules, attached to the type or kept in one table next to it. Then test that the generated schema equals the published definition, and let the same type validate each call, so the model, the validator and the function all read one truth.
You can now produce a tool's schema and its validation from one typed source, in Python or Java, and prove at which stage a bad payload stops. Everything so far has been about what goes into a tool. The other direction is still open: what the function returns is read by a model, not by a compiler, and an exception or a stack trace is no use to it. Result contracts designs what comes back.