What this is
What is a tool?
A tool is a function you let an AI language model ask for, so that its words can turn into an action, such as looking up a record, refunding a payment or sending an email. The language model only writes the request. Your code checks it and decides whether to carry it out, so every safeguard lives in your code. Tool design decides whether that request names the right tool, carries correct arguments and is safe to run.
Why it matters: The moment a language model's output does something rather than says something, a wrong call is visible to a customer, an auditor or a bank. A refund retried after its reply was lost, for one, pays the customer twice unless the tool was built to stop it.
At a glance
Key takeaways
- The model only writes a request (
tool_use). Your code checks it, runs it and returns atool_result. - Check both shape (JSON Schema) and meaning (business rules), and return every problem with its fix.
- The model picks a tool by its description: say what the tool does, when to use it, and when not to.
- A job of calls, each right with probability , succeeds with probability , so fewer, higher-level tools are more reliable.
- With a large catalogue, send the model only the tools relevant to each request.
- Writes carry idempotency keys, irreversible or high-value actions wait for human approval, and each agent's credentials allow only its job.
How it works, from scratch
A language model can only produce text, so anything it does in the world goes through code you own. Here that code is a tool registry: it holds the tools, shows them to the model, and checks every request the model makes before carrying it out.
Chapter 1
What a tool call is
Picture a new assistant who may not touch anything. When they need something done, they fill in a request form ("refund customer C-100, $20") and hand it to you. You decide whether to carry it out, and hand back a note saying what happened. A language model works with tools the same way. You send it a list of tools, each with a name, a description and the shape of its arguments. When it wants one, it stops and writes a tool call: the tool's name with the arguments filled in, like the form. Here is the whole exchange for "what's 2 + 3?" with one tool, written as the actual messages in the format of Talking to a language model:
you -> model tools: [{"name": "add", "description": "Add two integers.",
"input_schema": {"type": "object",
"properties": {"a": {"type": "integer"}, "b": {"type": "integer"}},
"required": ["a", "b"]}}]
user: "what's 2 + 3?"
model -> you tool_use {"id": "toolu_1", "name": "add", "input": {"a": 2, "b": 3}}
stop_reason: "tool_use" <- "please run this for me"
you (validate the input, run add(2, 3) -> 5)
you -> model user: tool_result {"tool_use_id": "toolu_1", "content": "5"}
model -> you "2 + 3 = 5." stop_reason: "end_turn"
The input_schema is a JSON Schema, a JSON document that describes the
shape other JSON must have: which fields exist, what type each is, and
which are required. It is the blank form the model fills in.
Figure 1 · Diagram
sequenceDiagram participant M as Model participant C as Your code participant T as The real system C->>M: tool definitions (name, description, JSON Schema) + user message M-->>C: tool_use: name + arguments (a filled-in form) C->>C: check the form (schema, business rules, permissions, approval) C->>T: carry it out T-->>C: result C->>M: tool_result (matched by tool_use_id) M-->>C: answer in words
In code: ToolRegistry.register adds a tool, ToolRegistry.definitions
lists them for the model, and ToolRegistry.call runs a call through the
checks. View source
Chapter 2
Validate every call before running it
The first thing your code does with a call is check it, the way a bank clerk checks a withdrawal slip twice. First, is it filled in properly: every box, a real date, a positive amount? Then, does it make sense: does the account exist, and does it have the money? For a tool call, the first check is the JSON Schema and the second is your business rules.
Take a payment tool with an amount, a currency (EUR, GBP or USD) and an
optional pay_on date. The model sends
{"ammount": 5, "currency": "usd", "pay_on": "next friday"}. The validator
returns every problem at once, each saying what a correct value looks
like:
$: missing required field 'amount'
$: unexpected field 'ammount' (allowed: amount, currency, pay_on)
$.currency: must be one of ['EUR', 'GBP', 'USD'], got 'usd'
$.pay_on: 'next friday' does not match the required format. Expected: date as YYYY-MM-DD
Given these four lines, the model can fix all four mistakes in one retry.
Given only invalid input, it has to guess.
Passing the schema is not enough. "C-999" matches the pattern ^C-\d+$
and still names a customer that doesn't exist. With the Claude API you can
mark a tool definition "strict": true, and the API then guarantees that
the model's arguments match the schema (Structured output
explains how such guarantees work). That settles the shape, not the truth,
so the business-rule check stays.
A full registry runs these two checks among others, in the order below. The last three (dry run, approval and the idempotency key) guard calls that change something, and are explained with the other safeguards at the end.
Figure 2 · Diagram
flowchart TD
A[tool_use from the model] --> U{Tool exists?}
U -->|no| E1[unknown_tool:<br/>list the real tools]
U -->|yes| P{Caller has the<br/>required scope?}
P -->|no| E2[denied]
P -->|yes| S{Matches the<br/>JSON Schema?}
S -->|no| E3[invalid:<br/>every problem, with the fix]
S -->|yes| B{Business rules pass?<br/>e.g. customer exists}
B -->|no| E4[rejected]
B -->|yes| D{Dry run?}
D -->|yes| E5[dry_run:<br/>describe, change nothing]
D -->|no| H{Needs human<br/>approval?}
H -->|yes, none given| E6[awaiting_approval]
H -->|declined| E7[declined]
H -->|no, or approved| I{Idempotency key<br/>seen before?}
I -->|yes| E8[duplicate:<br/>return first result]
I -->|no| X[run the tool: ok]
In code: validate checks a value against a subset of JSON Schema and
returns every problem with its path. ToolRegistry.call runs the checks in
the order shown and returns a ToolOutcome, and definitions(strict=True)
adds the strict flag. View source
Chapter 3
Descriptions are prompts
A call can pass every check and still be to the wrong tool. The model chooses a tool by reading its name and description, so the description is a prompt. Label a wall of drawers "stuff", "things" and "items", and even a careful person opens the wrong one; label them "Policies (PTO, travel, VPN). Not customers", and nobody hesitates.
To measure this without a real model, a stand-in picks the tool whose name
and description share the most words with the request. For "billing status
for customer 1042", the vague descriptions share no words with any tool, a
three-way tie, so the stand-in takes the first. The precise description of
lookup_record shares "billing", "status" and "customer", and wins.
Figure 3 · Chart
Vague descriptions pick the right tool for 2 of 6 requests; precise descriptions of the same tools get all 6 right
A real model reads far better than a word count, but it chooses from the
same text, so the same fixes help it: precise descriptions, few parameters,
an enum wherever the values form a closed set, and error messages that say
how to fix the call.
In code: pick_tool is the stand-in, and selection_accuracy scores it
on VAGUE_TOOLS and PRECISE_TOOLS. View source
Chapter 4
Fewer, higher-level tools
Every choice the model makes is a chance to choose wrong, so the number of calls a job takes matters too. Asking an assistant to "book my trip to Denver" is safer than dictating five separate forms (find a flight, hold a seat, find a hotel, reserve a room, add it to the calendar), because every hand-off is another chance to drop something.
Figure 4 · Diagram
flowchart LR
subgraph Low["Five low-level calls"]
direction LR
a1[get_customer] --> a2[get_price_list] --> a3[compute_tax] --> a4[render_pdf] --> a5[send_email]
end
subgraph High["One high-level call"]
direction LR
b1[create_invoice]
end
If each call is right with probability , independently of the others, a chain of calls all succeed with probability:
The formula and its symbols
Symbols
| Symbol | Meaning |
|---|---|
| probability that one call is chosen and filled in correctly | |
| number of calls in the chain |
In words: multiply the per-call success rate by itself once per call.
New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.
On the example: with and , , so about 1 run in 7 fails. With one high-level call it's .
In Python:
p = 0.97
# five calls that must all succeed
round(p ** 5, 3) # → 0.859
# about 1 run in 7 fails
round(1 - p ** 5, 2) # → 0.14
# one high-level call
p ** 1 # → 0.97
Figure 5 · Chart
Success falls with every extra call: at 99% per call twenty calls succeed about 82% of the time, at 90% ten calls barely a third
In code: chain_success evaluates . View source
Chapter 5
Too many tools: load only the relevant ones
Merging tools shortens the chains, but a real product still collects many tools, and a long list makes each choice harder. Selection accuracy drops as the list grows past a few dozen tools, and every definition costs input tokens on every call. So send only the tools a request needs, the way you would hand a plumber the five tools for today's job rather than send them into a warehouse of 500.
Take a catalogue of 30 tools and the request "I forgot my password and I'm
locked out". The request is embedded, compared with every tool description,
and only the top 5 tools go to the model, with reset_password first.
Figure 6 · Diagram
flowchart LR R[User request] --> E[Embed request] C[(Tool catalogue<br/>30 descriptions,<br/>embedded once)] --> S E --> S[Cosine similarity<br/>to every tool] S --> K[Top 5 tools] K --> M[Model sees<br/>only these 5]
Figure 7 · Chart
Each request is similar to only a small cluster of related tools and dim against the rest of the catalogue
Two other designs do the same job: route the request to a sub-agent that holds only the relevant tools, or use a provider's built-in tool search.
In code: select_tools ranks the catalogue against the request and
returns the top matches. View source
Chapter 6
Safety: idempotency, dry runs, approval, least privilege
With the right tool and valid arguments, a call can still do harm. It can run twice, it can be impossible to undo, or it can come from a model that was tricked. Four safeguards deal with these.
Idempotency. An operation is idempotent when doing it twice has the same effect as doing it once, like pressing a lift button twice. A refund is not, and agents retry. Suppose a refund call times out after the bank has processed it: the agent cannot tell, so it retries. The fix is an idempotency key, a unique id the caller sends with each write. The registry stores the result under that key, and a call that repeats the key gets the stored result back.
Figure 8 · Diagram
sequenceDiagram participant A as Agent participant R as Registry participant B as Bank A->>R: refund C-100 $20 (key req-1) R->>B: refund B-->>R: done R--xA: network timeout (reply lost) A->>R: retry: refund C-100 $20 (key req-1) R-->>A: duplicate: "refunded 20.00 to C-100" (no second refund)
Dry run. A dry run passes every check, then describes the action instead of doing it. It serves previews and shadow-mode rollouts (Safe deployment).
Human approval. Some actions should wait for a person, as spending over
a limit waits for a manager's signature. Irreversible actions, or ones over
a threshold such as refunds over $500, park as awaiting_approval until a
person decides.
Figure 9 · Diagram
sequenceDiagram
participant M as Model
participant R as Registry
participant H as Human approver
M->>R: refund C-100 $900
R->>H: approve refund_payment {amount: 900}?
alt approved
H-->>R: yes
R-->>M: ok: refunded
else declined
H-->>R: no
R-->>M: declined: do not retry, tell the user
end
Least privilege. Give each agent credentials for its own job only, the
way a valet key starts the car but won't open the boot. Credentials come as
scopes, named permissions such as payments:write. An agent that reads
tickets holds tickets:read, so even if a malicious email tricks it, it
cannot issue refunds.
In code: a Tool carries the scopes it needs, whether it reads, writes
or acts irreversibly, and an optional approval rule. ToolRegistry.call
enforces them, given the caller's credentials, an idempotency key, a
dry-run flag and an approver. View source
Test yourself
4 questions
Answer each one out loud or on paper before you open it.
Question 1Q: How do you design tools so the model picks the right one with correct arguments?Think it through, then reveal
A: Give each tool one clear job and a description that says what it does,
when to use it and when not to. Keep parameters few, use enums for closed
sets, and put the format in the schema description ("date as YYYY-MM-DD").
Prefer one high-level tool over several low-level ones. Validate every call
and return actionable errors so the model can self-correct. Measure tool
selection accuracy in evals, and load tools dynamically when there are many.
Question 2Q: The schema says customer_id must match ^C-\d+$. Is that enough validation?Think it through, then reveal
A: No. The schema checks shape, not truth. C-999 is well-formed and may not
exist. Add a business-rule check before acting, and return an error that
tells the model how to find the right id.
Question 3Q: A refund call timed out. Should the agent retry?Think it through, then reveal
A: Only if the call is idempotent. Send an idempotency key with every write, and the retry returns the original result instead of refunding twice.
Question 4Q: Why not give the agent one admin credential for everything?Think it through, then reveal
A: Blast radius. If the agent is tricked (for example by prompt injection in a document it reads), it can do anything the credential allows. Scope credentials per tool and per agent, and put irreversible actions behind human approval.
Primary sources
The papers behind this lesson
It showed a language model can learn when to call an API, which one and with what arguments, by keeping only the self-generated calls that made its predictions better, which is the idea behind tool calling being trained into today's models.
Read on rumblr →The paperResearcher's shelf
Further reading
- Anthropic, Writing effective tools for agents: https://www.anthropic.com/engineering/writing-tools-for-agents
- Anthropic, Building effective agents (appendix on prompt-engineering tools): https://www.anthropic.com/engineering/building-effective-agents
- Claude tool use overview: https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview
- Implementing tool use: https://docs.claude.com/en/docs/agents-and-tools/tool-use/implement-tool-use
- Understanding JSON Schema: https://json-schema.org/understanding-json-schema
- Stripe, idempotent requests: https://docs.stripe.com/api/idempotent_requests
About this lesson. This lesson is built from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it. Its hand-built interactive figures are still to come: the status page shows which lessons have them.