Typed Tool Contracts
In this article
- Write a typed contract for a tool that moves money: input rules, a closed result union and a declared side effect.
- Explain why strict tool use guarantees the shape of a call but not a rule that depends on live data.
- Predict, for a payload or a reply from the payment service, which result comes back and whether money moved.
- Test that only valid payloads reach the executor and that each failure comes back as the right variant.
- Terms defined here: side-effect semantics.
Overview
Strict tool use is on, and the model asks your refund tool for 60.00 EUR on an order that has 49.00 EUR left to refund. Every field has the right type. The schema is satisfied. What stops the payment?
Only your own code can. A typed contract for a tool has three parts: rules for every input, a closed list of results, and a plain statement of what the tool changes in the world. The tool's code enforces it on every call before anything happens. Below you write one for a refund tool in 40 lines of Pydantic, push four calls and one bad reply through it, and make the run a test that fails the day a wrong payload reaches the payment.
The refund tool
The shop here is invented, and so are its orders and numbers. Its support agent refunds customers through a tool named create_refund. Order O-1042 was paid 49.00 EUR and nothing has been refunded yet, so its refundable remainder is 49.00 EUR.
When the model wants a refund, it sends a tool call: the tool's name and arguments that fit the input schema. Your code runs the tool and returns a tool result. The tool contract for create_refund says:
| part | rule |
|---|---|
order_id | a string matching O- followed by digits |
amount | a decimal number of EUR, above 0, at most the refundable remainder |
currency | EUR or USD |
reason | damaged, not_delivered or unwanted |
| result | refunded(receipt_id), rejected(code) or uncertain(action_id), nothing else |
| rejection code | invalid_arguments, stale_state or policy_denial |
| side effect | writes money; not safe to retry without an idempotency key |
Look at the amount row. "Above 0" is a fact about the value alone. "At most the refundable remainder" is a fact about the value and the order as it stands right now. That difference decides where each rule can be checked.
What the schema can promise
With each request your code sends the model a list of tool definitions: a name, a description and a JSON Schema for the inputs. Setting strict: true on a definition makes Anthropic constrain Claude's sampling so the tool input always matches that schema [1]. Wrong types and missing required fields can no longer happen [1].
A schema can say "exclusiveMinimum": 0, so a JSON-valid amount of -5 is out. It cannot say "at most what order O-1042 can still refund". The schema is a fixed document sent with the request; the remainder lives in your database and drops after every refund. A call for 60.00 passes every schema rule, because 60.00 is a positive number with two decimals. Checking that a value which fits the schema is also right for the business is what semantic validation means, and the remainder check is one case of it.
So the executor, the code that performs the refund, checks every call before it pays: first the shape, with the same model the schema is generated from, then the rules that need live order state. The shape check repeats what strict mode did, because the executor cannot know who produced the payload: a model without strict mode, another provider, a test harness or a bug in your own glue code. A check in the executor holds for every caller.
The same holds for text that is not a call at all. "Refund 40 euros" in the conversation is a sentence, not a payload, and only JSON that parses into the input model reaches the payment code.
Before reading on, predict the result and code for each of four payloads: amount -5, amount 60.00, the text refund 40 euros, and amount 49.00.
Five payloads through the contract
Pydantic is a Python library whose typed models validate data and can also generate JSON Schema [2]. The program below is the whole contract and five inputs for it: four tool calls and one reply from the payment service. A dictionary stands in for the order database, and a list records each payment that would go out.
import json
from decimal import Decimal
from typing import Annotated, Literal
from pydantic import BaseModel, Field, TypeAdapter, ValidationError
REMAINDER = {'O-1042': Decimal('49.00')} # live order state
payments = []
class CreateRefund(BaseModel):
order_id: str = Field(pattern=r'^O-\d+$')
amount: Decimal = Field(gt=0, decimal_places=2)
currency: Literal['EUR', 'USD']
reason: Literal['damaged', 'not_delivered', 'unwanted']
class Refunded(BaseModel):
status: Literal['refunded']; receipt_id: str
class Rejected(BaseModel):
status: Literal['rejected']; code: Literal['invalid_arguments', 'stale_state', 'policy_denial']
class Uncertain(BaseModel):
status: Literal['uncertain']; action_id: str
Result = TypeAdapter(Annotated[Refunded | Rejected | Uncertain, Field(discriminator='status')])
def create_refund(raw: str):
try:
args = CreateRefund.model_validate_json(raw)
except ValidationError:
return Rejected(status='rejected', code='invalid_arguments')
if args.amount > REMAINDER.get(args.order_id, Decimal(0)):
return Rejected(status='rejected', code='stale_state')
payments.append(args) # the money moves here
return Refunded(status='refunded', receipt_id='rc-1')
def read_reply(raw: str, action_id: str):
try:
return Result.validate_json(raw)
except ValidationError:
return Uncertain(status='uncertain', action_id=action_id)
call = '{"order_id": "O-1042", "amount": %s, "currency": "EUR", "reason": "damaged"}'
for label, raw, want in [('-5', call % '-5', 'invalid_arguments'), ('60.00', call % '60.00', 'stale_state'),
('free text', 'refund 40 euros', 'invalid_arguments'), ('49.00', call % '49.00', 'refunded')]:
got = create_refund(raw)
assert getattr(got, 'code', got.status) == want and len(payments) == (want == 'refunded'), label
print(f'{label:>9} -> {want:17} payments made: {len(payments)}')
assert read_reply('"timeout"', 'a-1') == Uncertain(status='uncertain', action_id='a-1')
print(json.dumps(CreateRefund.model_json_schema()['properties']['amount']))Run with Pydantic 2.13, it prints:
-5 -> invalid_arguments payments made: 0
60.00 -> stale_state payments made: 0
free text -> invalid_arguments payments made: 0
49.00 -> refunded payments made: 1
{"anyOf": [{"exclusiveMinimum": 0.0, "type": "number"}, {"pattern": "^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d{0,2}0*$", "type": "string"}], "title": "Amount"}Only the 49.00 call moves the counter, so exactly one payment would have gone out. Each rejection stops at a different line, and that is why the codes differ:
-5is valid JSON but breaksgt=0, somodel_validate_jsonraises: a shape error,invalid_arguments.60.00passesmodel_validate_jsonand stops at the comparison with the remainder of 49.00, 11.00 EUR short. The arguments were fine as values; they do not fit the order as it is now, so the code isstale_state.refund 40 eurosis not JSON, so parsing fails and the payment line is never reached.
policy_denial is the third code, for a business rule that refuses an otherwise valid call, such as a refund window that has closed. This program checks no such rule; a real executor would put it next to the remainder check, still before the payment line.
The order of the checks matters as much as the checks. Move payments.append(args) above the remainder comparison and the 60.00 call would print stale_state while the money had already gone. The returned code would look right; only the counter shows the damage.
A closed result union
The three result classes form a discriminated union: status holds a different fixed value in each, so a reader checks status and knows which other field must be there. Result turns the union into one validator. The set is closed: any reply that is not exactly one of the three becomes uncertain in read_reply, which is where the tool reads what the payment service sent back.
The reply "timeout" shows why. It is a plain string with no status, so it fits no variant. A careless reader that only checks whether an exception was raised sees a string, no error, and reports the refund as done. The closed union refuses to guess: read_reply returns uncertain with the action_id of the call it was waiting on.
The three variants ask for three different reactions from the agent:
| result | what is known | what the agent does |
|---|---|---|
refunded | the money moved; receipt_id proves it | tell the customer |
rejected | nothing was paid | fix the arguments or explain the refusal |
uncertain | the money may or may not have moved | escalate to a person or a reconciliation job; never treat it as a failure to retry |
How the text inside a rejection reads, so the model can correct its next call, is the job of a structured tool error. The union only fixes which kinds of answer exist.
The side-effect declaration
The last row of the contract is plain words: "writes money; not safe to retry without an idempotency key". It states the tool's side-effect semantics, what calling it does beyond returning a result. Types cannot express this, yet it is the line that decides what may happen after uncertain.
Version 1 of this contract sends no idempotency key, so the payment service cannot tell a repeat from a new refund. If the reply to a 49.00 refund times out and the agent calls again, it may pay 49.00 a second time, 98.00 for one order. So in v1 the only safe move after uncertain is escalation. Leave the line out, and a generic retry wrapper written by someone who reads only the types will retry the call.
A tool that only reads, such as a lookup of an order's status, would declare that it changes nothing; retrying it after a timeout costs a request and nothing else. The declaration is what lets retry policy differ per tool without anyone reading the tool's code.
The MCP specification warns clients to treat tool annotations as untrusted unless the server is trusted [3]. The same holds inside your own system: the declaration informs people and retry policies, and the executor's code is what enforces the money rule.
One model for the schema and the executor
The model needs a JSON Schema for create_refund; the executor needs a validator. Written by hand in two places, they drift: someone tightens one and forgets the other. Pydantic generates the schema from the model, and model_json_schema returns it as a dict that json.dumps turns into valid JSON [2]. Send that dict as the tool's input schema, and the model and the executor work from one definition.
The last output line is the generated schema for amount. gt=0 became exclusiveMinimum [2]. The anyOf with two branches is there because the default generation mode describes what the validator accepts, and a Decimal field accepts either a number or a string [2]. So 49.00 and "49.00" both pass.
Two parts of the contract never reach the generated schema: the remainder rule and the side-effect line. The first lives in the executor, the second in the tool's description and your retry policy. Generation keeps shape in sync; it cannot carry rules that need your database.
The run as a test
The loop in the program is already a test. Each case names a payload and the variant it must produce, and the assert fails if a payload comes back as the wrong variant or if the payment count is not what that variant implies: 0 after each bad payload, 1 after the good one. The last assert pins the reply "timeout" to uncertain.
Write one case per check, so every line that can stop a call is proven to stop it, plus one case per result variant.
Asserting on the count, and not only on the returned code, is what catches the reordered executor from earlier: with the payment line moved above the remainder check, the run stops with an AssertionError at the 60.00 case.
Common mistakes
- Trusting the schema for business rules. Symptom: a 60.00 refund on a 49.00 order goes through, and every log line shows a valid call. Fix: check against order state in the executor, after the shape check and before the payment.
- An open result. Symptom:
"timeout"or{"ok": true}is reported as success because nothing raised. Fix: parse every reply into the closed union, and map anything that does not parse touncertain. - A hidden side effect. Symptom: a retry wrapper repeats a timed-out refund and pays twice. Fix: declare the side effect in the contract and escalate
uncertainwhile no idempotency key exists. - Testing only the returned code. Symptom: tests pass while a rejected call has already paid. Fix: assert on the side effect too, here the payment counter.
Sources
- Strict tool use. Anthropic. Checked 24 Oct 2026.
- JSON Schema (Pydantic concepts). Pydantic. Checked 24 Oct 2026.
- Tools (MCP specification 2026-07-28). Model Context Protocol project. Checked 25 Oct 2026.
Check yourself
Check yourself
Question 1 of 13
A tool may be retried after a timeout only if it is safe. Which part of the contract says so?
Your first check counts towards your result.