Typed Tool Contracts
In this article
- Write a typed contract for a tool that moves money, with input rules, a closed set of results and a declared side effect.
- Explain why strict tool use guarantees the shape of a call but cannot know how much an order may still refund.
- Predict, for a payload or a tool reply, which result comes back and whether the executor ran.
- Generate the schema the model sees from the same Pydantic model the executor checks calls with.
- Terms defined here: side-effect semantics.
Overview
A support agent can refund customers. The model decides when to refund and writes the arguments: which order, how much, why. Your code then moves real money. So what stands between a wrong argument and a wrong payment?
The answer is a contract the tool's own code enforces: rules for every input, a fixed list of results, and a plain statement of what the tool changes in the world. You write one for a refund tool in Python and run five payloads through it. Afterwards you can say which checks the model provider can enforce for you, which only your code can do, and how to read a reply that fits no expected result.
A refund tool and its contract
Take a made-up online shop whose support agent issues refunds through a tool called 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 plus arguments that fit the tool's input schema. Your code runs the tool and sends a tool result back. The tool contract is the part both sides agree on, and for create_refund it has three parts.
- Inputs with rules.
order_idmatchesO-followed by digits; this contract requires theO-prefix the shop's order ids carry, so a bare1042fails asinvalid_arguments.amountis a decimal number of euros, above zero and at most the remainder.currencyisEURorUSD.reasonisdamaged,not_deliveredorunwanted. - A closed set of results. The tool returns
refundedwith areceipt_id,rejectedwith acode(invalid_arguments,stale_stateorpolicy_denial), oruncertainwith anaction_id. Nothing else. - A declared side effect. "Writes money; not safe to retry without an idempotency key."
The first two parts are types. The third is plain words, and it decides what the agent may do when a payment goes wrong.
Shape is guaranteed, rules are not
Your code sends the model a list of tool definitions with each request: a name, a description and a JSON Schema for the inputs; Anthropic lets you mark one strict: true. [2] With strict: true on a tool definition, Claude's tool inputs are guaranteed to match your JSON Schema, because the model's output is constrained to schema-valid tokens while it is generated. [2] Designing a Good Tool Schema showed this: strict mode fixes the type of each argument, and shape is not a business rule.
That is a guarantee about shape. A schema can say that amount is a number above zero, so -5 is out. No schema keyword can say "at most what order O-1042 can still refund", because the remainder is a fact in your database that changes after every refund, and the schema is a fixed document sent with the request.
So the executor, the code that performs the refund, checks every call itself before anything happens: first the shape, then the rules that need live order state. Only a call that passes both reaches the payment. Checking that a value which fits the schema is also right for the business is called semantic validation, and the remainder check is one case of it.
Before you read the program, predict: the model asks for 60.00 EUR on order O-1042. Does that call pass the schema? Does the money move?
Five payloads through the contract
The program below is the whole contract in Pydantic, a Python library whose models can also produce JSON Schema. [1] It runs four calls through create_refund and reads one bad reply; a small in-memory table stands in for the shop's database.
import json
from decimal import Decimal
from typing import Annotated, Literal
from pydantic import BaseModel, Field, TypeAdapter, ValidationError
REMAINDER = {'O-1042': Decimal('49.00')} # order state, read by the executor
executed = []
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')
executed.append(args) # the money would move here
return Refunded(status='refunded', receipt_id='rc-1')
def read_result(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 in [('49.00', call % '49.00'), ('-5', call % '-5'),
('60.00', call % '60.00'), ('free text', 'refund 40 euros')]:
print(f'{label:>9}: {create_refund(raw)!r:58} payments made: {len(executed)}')
print(' timeout:', repr(read_result('"timeout"', 'a-1')))
print(json.dumps(CreateRefund.model_json_schema()['properties']['amount']))The output, as printed by a run with Pydantic 2.13:
49.00: Refunded(status='refunded', receipt_id='rc-1') payments made: 1
-5: Rejected(status='rejected', code='invalid_arguments') payments made: 1
60.00: Rejected(status='rejected', code='stale_state') payments made: 1
free text: Rejected(status='rejected', code='invalid_arguments') payments made: 1
timeout: Uncertain(status='uncertain', action_id='a-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 on the right, so only one payment would have happened; the shop's approval of refunds above 40.00 EUR is left out of this program. The -5 call is valid JSON, and it fails at model_validate_json because gt=0 forbids it: a shape error, so invalid_arguments. The 60.00 call is the one you predicted: it passes every schema rule, since 60.00 is a positive number with two decimals, and it stops only at the line that compares it with the remainder of 49.00. That check reads live order state, so it returns stale_state: the call does not fit the order as it is now. The third code, policy_denial, is for a business rule that refuses the call, such as a refund window; this program checks none.
The free-text payload, "refund 40 euros", is not JSON at all, so parsing fails and the executor never sees it. A sentence that sounds like an instruction is still not a call: only a payload that fits CreateRefund and passes the checks above can run.
A closed result
The three result classes form a discriminated union: the status field holds a different fixed value in each, so a reader looks at status and knows which other field to expect. In the program, Result is that union as one validator: it reads status first, then checks the reply against the one class that value names. The set is closed. A reply that is none of the three is not a fourth kind of success. read_result is where the tool reads the payment service's reply and maps it to one of the three results; anything that does not fit becomes uncertain.
That is what happens to the reply "timeout". It has no status, so read_result cannot parse it as any variant, and it returns uncertain with the action_id of the call it was waiting on. A careless reader that checks only "did the call raise?" would see a string, no exception, and report the refund as done.
rejected means nothing was paid, and the model may fix the arguments or tell the customer. uncertain means the money may or may not have moved, so the agent escalates it to a person or a reconciliation job and does not treat it as a failure to retry. The wording inside each result, so the model can recover, is the work of a structured tool error: the union only fixes which kinds of answer exist.
What the tool changes
The third part of the contract declares side-effect semantics: what running the tool does to the world beyond returning a result. For create_refund the declaration is one line: "writes money; not safe to retry without an idempotency key".
That line decides what the agent may do after uncertain. Version 1 of this contract is the version before the action id, such as r-7f3:3:refund, is carried as an idempotency_key field: a value sent with each request that lets the payment service recognise a repeat, so a second call looks like a new request. A second call after a timeout could pay 49.00 EUR twice, so in v1 there is no safe retry after uncertain, only escalation. Leave the line out and a retry policy written by someone who sees only the types will retry it.
One model, two uses
The model needs a JSON Schema for create_refund, and the executor needs a validator. Written separately, they drift. Pydantic creates JSON Schemas from models automatically, and model_json_schema returns the schema as a dict you can serialise to JSON. [1] Pass that dict as the tool's input schema and the model and the executor work from one definition.
The last line of the output shows the result for amount. The gt=0 rule became exclusiveMinimum, the same mapping as in Pydantic's own gt=30 example. [1] By default the generated schema describes what the validator accepts, and a Decimal field accepts a number or a string. [1] That is why anyOf lists two branches: 49.00 as a number and "49.00" as a string both pass.
The rule at work
A tool contract is more than JSON shape: input rules, including those that need live state, a closed result union and a declared side effect. Generate the model's schema from the same typed model, and let the executor's checks decide every call before anything changes.
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 schema check and before the payment.
- An open result. Symptom: a reply such as
"timeout"or{"ok": true}is read 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 generic retry wrapper repeats a timed-out refund and pays twice. Fix: write "writes money; not safe to retry without an idempotency key" into the contract, and escalate
uncertainwhile no key exists.
In production
Descriptive extras on a tool definition are not a guarantee: the MCP specification tells clients to treat tool annotations as untrusted unless they come from trusted servers. [3] The same holds in your own system: a side-effect line in a description informs people and retry policies, and the executor's code is what enforces it.
MCP lets a tool declare an output schema, and clients should validate structured results against it. [3] Run the result union check where the reply enters your agent, and log every uncertain with its action_id, so a person can find the payment and settle it.
Sources
- JSON Schema (Pydantic concepts). Pydantic. Checked 24 Oct 2026.
- Strict tool use. Anthropic. 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.