08A.6 Designing Tools Models Can Use
Lesson 03.5 showed you the mechanics: how a tool definition goes on the wire, how a tool_call comes back, how you return a result. Lesson 08A.2 showed you the loop that repeats that round trip until the model has an answer. This lesson is about the thing in between: the tools themselves. A tool is the only interface a model has to your systems, and almost every agent failure you will debug in production — the wrong tool chosen, an invented order ID, a refund issued twice, a raw database dump flooding the context window — is really a design failure, not a model failure. This lesson teaches you to design tools the way the providers' own engineering teams do: as prompts the model reads, contracts your code enforces, and safety boundaries your policy layer guards.
What you'll learn
- Why a tool is "an interface for a model, not an API for a programmer": the two contracts (what the model sees, what your code runs) and why the description is the highest-leverage prompt you will ever write
- How to name tools and namespaces so the model picks the right one; how to write descriptions that say what the tool does, when to use it, when not to, and what it doesn't return
- Parameter design: few, typed, enumerated, bounded and described parameters; why free-form string blobs are an anti-pattern; what strict schemas guarantee and where they stop
- How many tools is too many — the measured evidence, the providers' guidance, and the three escape hatches (grouping, per-step restriction, tool search)
- Granularity: primitives vs task-level tools, consolidation with an
actionparameter, composite "do what I mean" tools, and returning what the model needs rather than the API's raw dump - Results design: concise high-signal output, handles vs content, cursor pagination, truncation markers, actionable error messages, units and timestamps, and keeping secrets and PII out
- Safety in tool design: read/write/destructive risk classes, acting as the user with least privilege, idempotency keys, dry-run modes, confirmation parameters, argument validation against injection, rate limits and output sanitisation, and tool timeouts (choosing one per tool, cancelling a call, returning a timeout the model can act on, and how timeouts interact with idempotency keys)
- A taxonomy of tool types — retrieval, SQL, HTTP APIs, calculators, files, browsing, messaging, human-in-the-loop and scratchpad tools — each with a worked design
- The running example's full tool set for the support assistant (orders, tickets, refunds, docs search) with schemas, a registry, safety metadata, tests and a tool-use eval harness
- How to generate tool definitions from type hints and OpenAPI specs, why auto-generated tools from big specs perform badly, and how to version tool schemas
What you don't need
- API keys. Every code sample in this lesson is pure local Python over in-memory fake data; you can run all of it, including the tests, without a model or a key. The eval harness shows where a live model plugs in, and its demo runs on a scripted fake.
- The tool-calling wire formats. Lesson 03.5 owns them; this lesson links back whenever a design decision depends on one.
- The agent loop itself. Budgets, stop conditions, tracing and approval plumbing belong to lesson 08A.2; this lesson designs the tools those mechanisms guard.
- Prompt-craft fundamentals. Descriptions are prompts, so the principles in lesson 04.1 apply directly; this lesson applies them to tool definitions specifically.
Setup
The samples need Python 3.11+ and Pydantic. Lessons of this module share one project folder; if you haven't created it yet, run uv init tools-agents --bare --python 3.13 && cd tools-agents first (see lesson 03.1, Part 4 for the full setup), then add:
uv add pydantic pytest
# or: pip install pydantic pytest(pytest 9.2.0 is the current release as of November 2026; check PyPI for the latest.) No .env file is needed — nothing here calls a provider. Where a sample would benefit from a live model, the lesson says so and shows the free local stand-in option from lesson 03.1, Part 12.
The code builds four files in the project folder: support_data.py (fake company data and a toy docs retriever), support_tools.py (the redesigned tools, their schemas and the registry), test_support_tools.py (unit and schema-snapshot tests) and tool_eval.py (the tool-use eval harness). Each is printed in full where it is introduced. If you completed 08A.2, its support_tools.py, agent.py and scripted.py are already in the folder — the support_tools.py printed in Part 6 replaces it (same filename, redesigned contents; rename the old copy first if you want to keep it for 08A.2's own exercises).
What you must be able to do after this lesson#
- Write a tool name, description and parameters that a model can pick and call correctly
- Choose the right granularity for a tool
- Design tool results that are concise, paginated and actionable
- Classify tools by risk and make side-effect tools safe and idempotent
- Choose a per-tool timeout, cancel a slow call, and return a timeout error that is safe to retry
- Build a small tool set for a support assistant
- Measure whether a tool set works and improve it
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "The model called the wrong tool." | 1.3 Names and 1.4 Descriptions |
| "Just wrap the endpoint; the model will figure it out." | 1.1 The two contracts and 2.5 Return what the model needs |
| "Our tool has 14 parameters, what's the problem?" | 1.6 Parameters |
| "Should we enable strict mode on the tools?" | 1.7 Strict schemas |
| "We gave the agent access to all 80 internal APIs." | 1.8 How many tools is too many and Part 7 |
"Why does list_orders return 4,000 tokens of JSON?" |
3.1 High-signal output and 3.3 Pagination |
| "The model retried the refund and the customer got two refunds." | 4.3 Idempotency and 4.4 Dry-run modes |
| "Can't the model just be trusted to pass valid arguments?" | 4.6 Argument validation |
"The agent wrote DROP TABLE into a search box." |
4.6 Argument validation and Part 5.2 |
| "How do we know if a new tool description is better?" | 8.2 Tool-use evals |
| "We auto-generated tools from our OpenAPI spec and accuracy tanked." | 7.2 From OpenAPI specs |
Part 1: A tool is a prompt the model reads#
1.1 The two contracts#
A normal function has one contract: the signature your caller writes code against. A tool has two contracts that must agree:
- The model-facing contract — the tool's
name,descriptionand input schema. This is prompt text. The model reads it and decides whether to call the tool and what arguments to produce. Nothing else about your implementation is visible to the model. - The code-facing contract — the Python function, its types, its side effects, its dependencies. This is ordinary software: validated, tested, logged.
flowchart LR
subgraph model_sees ["What the model sees"]
N["name"] --> D["description<br/>(plain text prompt)"]
D --> S["input schema<br/>(JSON Schema: fields, types,<br/>enums, descriptions)"]
end
subgraph code_runs ["What your code runs"]
F["Python function<br/>+ injected dependencies"]
G["validation → policy →<br/>execution → result shaping"]
end
model_sees == "the only channel between them:<br/>name + JSON arguments out,<br/>text/JSON result back" ==> code_runsAnthropic's engineering team puts it precisely in "Writing effective tools for agents" (September 2025): tools are "a contract between deterministic systems and non-deterministic agents". Your function is deterministic — same input, same output. The agent is not — it might call the tool, answer from memory, ask a clarifying question, or hallucinate a call entirely. You design for that asymmetry.
Two consequences follow immediately:
- Everything the model needs to choose and call the tool correctly must be inside the name, description and schema. If the information lives only in your docstring, your OpenAPI spec or a wiki page, the model never sees it.
- Everything your code needs to stay safe must live outside the model's control. Authentication, authorisation, rate limits, idempotency and approval checks belong to your dispatch layer, never to parameters the model fills in. A parameter like
confirmed: boolthat the model sets itself is a deliberateness signal, not a security control — Part 4 makes this precise.
1.2 What the model actually sees#
For every tool you register, the provider renders roughly this into the request (the exact wire format per provider is lesson 03.5, Part 2):
| Field | Role for the model | Your responsibility |
|---|---|---|
name |
The handle it emits in the call | Unique, unambiguous, namespaced, stable |
description |
The only prose it reads before deciding | What/when/when-not/caveats, written like a prompt |
parameters (a JSON Schema) |
The shape of the arguments it must produce | Few fields, precise types, enums, descriptions with units and formats |
strict (provider-dependent) |
Whether decoding is constrained to the schema | See 1.7 |
And on the way back, the model sees only what your function returns — serialised as text or JSON into the tool-result slot. It never sees your exceptions, your logs, your database rows or your HTTP status codes unless you put them there. Results design is Part 3.
1.3 Names: the first thing the model reads#
The name does three jobs at once: it is the key your dispatch table uses, the token the model pattern-matches on, and (for humans reading transcripts) the label in your logs. Anthropic's rule is ^[a-zA-Z0-9_-]{1,128}$; OpenAI allows up to 64 characters with letters, digits, underscores and dashes; Gemini asks for underscores or camelCase (03.5, 2.9). Design to the strictest provider you might route to.
Naming rules that measurably matter:
- Namespace by service or domain once you have more than a handful of tools.
orders_getvstickets_getbeatsgetvsget2. Anthropic's docs suggest prefixes likegithub_list_prs,slack_send_message; their engineering post notes that prefix-vs-suffix namespacing had "non-trivial effects" on their tool-use evals and "vary by LLM" — so treat the scheme as an eval'd choice, not a law. - Use verb-noun or noun-verb consistently. Pick one (
orders_get,tickets_create,refunds_issue,docs_search) and never mix (getOrder,create_ticket,searchDocs). Inconsistent morphology makes the model work harder to learn your vocabulary. - Make confusable tools impossible to confuse by name.
orders_get(fetch one) andorders_search(find many) are clear;ordersandorderare a coin flip. - No abbreviations the model might expand wrongly.
custcould be customer, custom or customs. Spell it out; tokens are cheap next to a wrong call. - Never rename casually. The name is part of the model's learned context within a conversation; 03.5, 14.5 shows that on Claude 5.1+ a changed
toolslist can invalidate preserved thinking blocks. Version deliberately (Part 7.4).
1.4 Descriptions: the highest-leverage text you write#
If you fix one thing in this lesson, fix descriptions. Anthropic calls detailed descriptions "by far the most important factor in tool performance" and recommends "at least 3–4 sentences" covering what the tool does, when to use it, when not to, what each parameter means, and what it doesn't return (define-tools, as of November 2026). Their engineering post adds the framing: describe the tool "to a new hire on your team" — make explicit the specialised formats, niche terminology and relationships between resources that you take for granted.
A strong description answers, in order:
- What it does — the operation and the resource, in one sentence.
- When to use it — the user intents or situations that should trigger it.
- When not to use it — the neighbouring intents that belong to a different tool. This is the most-often-skipped and highest-value sentence: it is how you resolve ambiguity between similar tools.
- What it returns and what it does not return — so the model doesn't call it expecting data it won't get, then call three more tools to compensate.
- Caveats — side effects, latency, cost, rate limits, data freshness, permissions required.
Prompt gallery — descriptions, before and after. These are the same tool; only the description changes.
Weak:
name: get_order
Description: Gets an order.
parameters: {"order_id": {"type": "string"}}Strong:
name: orders_get
Description: Fetches one order by its order ID (format ORD-NNNN, from the customer's
confirmation email or the orders page) or by the customer's email address. Returns the
order status, item summary, totals, payment method (brand and last4 only) and timestamps.
Use this when the user asks about a specific order's status, contents or delivery date.
Do NOT use this to list or search across orders — use orders_search for that. Do NOT
use it for returns or refunds — use refunds_issue after confirming with the user.
Returns an error (not an empty object) when no order matches; the error lists what was
tried and suggests the next step.
parameters: {
"order_id": {"type": "string", "description": "Order ID like ORD-1042. Provide this OR customer_email, not both."},
"customer_email": {"type": "string", "description": "The customer's email address, exactly as registered. Alternative to order_id when the user doesn't have the ID."}
}The weak version leaves the model to guess: is get_order for one order or many? What format is order_id? What comes back? The strong version answers all of it — and notice the negative guidance ("Do NOT use this to list…") doing the disambiguation work that namespacing alone can't.
1.5 Worked examples: input_examples and examples in prose#
Two mechanisms put concrete calls in front of the model:
input_examples— an optional array of schema-valid example inputs on Anthropic tool definitions (define-tools, verified November 2026). Each example must validate againstinput_schema. Use it for complex tools with nested objects or format-sensitive parameters — it teaches shape faster than prose.- Examples inside the description — works on every provider. OpenAI's guide recommends including "examples and edge cases", with the caveat that "adding examples may hurt performance for reasoning models" (function-calling guide). On reasoning models, prefer
input_examples(Anthropic) or keep prose examples minimal and let the schema carry the shape.
When examples earn their tokens: ambiguous formats ("2026-11-05" vs "05/11/2026"), enum-like free text that should have been an enum, and multi-field coordination ("start_date must be before end_date"). When they don't: anything the schema already says, or examples that just repeat the description.
1.6 Parameters: few, typed, enumerated, bounded, described#
The input schema is the second half of the prompt. The rules, distilled from all four providers' guidance:
- Few parameters. Every parameter is a decision the model must make correctly. OpenAI's intern test applies: "Can an intern/human correctly use the function given nothing but what you gave the model?" If a human would ask questions, the schema is missing answers.
- Typed, not stringly-typed.
status: "shipped"as an enum beatsstatus_filter: string. Enums "prevent invalid states" — OpenAI's own example istoggle_light(on: bool, off: bool)allowing contradictory calls; a singlestate: enum["on","off"]doesn't (function-calling guide). - Bounded numbers.
limit: intwithminimum: 1, maximum: 20, default: 5beats unbounded. Bounds also protect your downstream systems. Two caveats oncestrictis on (1.7): Anthropic's strict mode rejectsminimum/maximumwith a 400 and OpenAI's strict mode wants every property required, so a strict schema cannot carry a default. Say the range in the description ("1 to 20, default 5") and enforce it in your validator, which is where 08A.2'sjson_schema()and this lesson'sField(ge=, le=)bounds do their real work. - Descriptions carry units and formats. "amount in cents (2599 = $25.99)", "ISO 8601 date", "order ID like ORD-1042". The model can't see your code's units.
- No free-form blobs. A parameter like
query: stringdescribed as "the user's question, or SQL, or a natural-language instruction" invites the model to stuff instructions into it — unpredictable behaviour and an injection surface. If you need open-ended input, make it one parameter with one job and validate hard in code (4.6). - Don't make the model fill arguments you already know. OpenAI's example: if you already have the
order_idfrom context, bind it in code and exposesubmit_refund()with no parameters, rather than asking the model to echo an ID it might corrupt (function-calling guide). Every parameter you add is a hallucination opportunity removed only if the model truly must supply it. - Optional vs required is a design decision. 03.4 covers the strict-mode mechanics (
X | Nonewith no default = nullable-but-required); here the design question is which fields should be omittable. Fewer required fields = fewer ways to fail; more required fields = less guessing. When two parameters are alternatives (order_idorcustomer_email), enforce "exactly one" in a validator, not just prose — and say so in the description. Note the hard limit, scoped correctly: vanilla JSON Schema can express these constraints —oneOf/not, andif/then/elseplusdependentRequired/dependentSchemassince draft 2019-09 — but none of the providers' strict-schema subsets support those keywords (03.4, 4.1 lists them as unsupported or unlisted for OpenAI, Anthropic and Gemini alike). So in practice "exactly one of" and "required whenactionis X" exist only as validator errors plus description prose. That's why 6.3'sOrdersGetArgsputs the rule in both field descriptions (the class docstring only reaches the schema's top-leveldescription, which providers render inconsistently — the per-field text is what the model reliably reads).
1.7 Strict schemas and where they stop#
Strict tool schemas constrain the model's generated arguments to your JSON Schema at decode time — the same machinery as structured outputs (03.4, Part 4 owns the per-provider subset and limits; 03.5, Part 10 covers the request flags). Design consequences:
- Write schemas to the intersection of the providers you might route to: Anthropic's complexity limits (20 strict tools, 24 optional parameters, 16 union-typed parameters per request), OpenAI's everything-required rule, Gemini's silently-ignored keywords (03.4, 4.1).
- Numeric and length bounds are not part of the strict subset on every provider. As of November 2026, Anthropic's structured-outputs page lists
minimum,maximum,multipleOf,minLengthandmaxLengthas not supported (a 400, unless an SDK helper such astransform_schemamoves them into the description). Keep bounds in the Pydantic model (your validator enforces them) and mirror them in the field description, so the model is told the range even when the schema cannot carry it. - Strict mode guarantees shape, not semantics. A schema-valid
order_id: "ORD-9999"that doesn't exist is still a bad call. Your function must validate against the world, not just the schema — 4.6 and 03.5, 7.1. - Strict mode does not fix bad descriptions. It makes wrong-shaped arguments rarer; wrong-valued arguments (real format, wrong entity) are unaffected — those are description and eval problems.
- Even with strict mode on, validate anyway: the local stand-in ignores
strict, some providers fall back to non-strict silently, and OpenRouter routes to whatever the endpoint supports (03.5, 10.5). requiredvs optional is a per-provider design decision, not a schema accident.extra="forbid"gets you"additionalProperties": false, but which fields are required differs: OpenAI strict wants every property listed inrequired(make optional-but-present fieldsX | None— "nullable but required", 03.4, 2.4), while Anthropic keeps Pydantic'srequiredlist and counts optional parameters against its complexity limits. Decide the required set deliberately per 1.6; the registry'sspecs()emits the Pydantic schema and each provider's wire adapter applies its own transform (03.5, Part 2).
1.8 How many tools is too many?#
This is the question with the best evidence in the whole lesson, and the answer is "fewer than you think":
- Measured accuracy decay. LongFuncEval (Kate et al., arXiv:2505.10570, April 2025) varied tool-catalogue size while holding tasks constant and found performance drops of 7% to 85% as the number of tools grows, plus 7–91% degradation in answer retrieval as tool responses grow longer. The Berkeley Function Calling Leaderboard (BFCL V4) exists precisely to measure this per model — check your model's scores before assuming your tool count is safe.
- Provider guidance (all as of November 2026): OpenAI — "Aim for fewer than 20 functions available at the start of a turn… a soft suggestion", and "keep the number of initially available functions small for higher accuracy… evaluate your performance with different numbers of functions" (function-calling guide); Google — "Keep active set to 10-20 tools maximum" (function-calling doc); Anthropic — no number, but "consolidate related operations into fewer tools" (define-tools).
- Cost compounds it. Every definition is input tokens on every request (03.5, 14.1); twenty well-described tools can cost a few thousand tokens before the user speaks.
The three escape hatches, in order of preference:
- Design fewer, better tools — consolidation and task-level tools (Part 2). This is almost always the right answer.
- Restrict the active set per step —
allowed_tools/allowed_function_nameskeep definitions cached while narrowing the choice (03.5, 3.1). - Deferred loading / tool search — for genuinely large surfaces (dozens to hundreds of tools): OpenAI's
tool_search(modelsgpt-5.4and later) and Anthropic'stool_search_tool_regex_20251119/_bm25_20251119let the model discover and load definitions on demand (03.5, 14.4; the full treatment is lesson 08A.8).
Part 2: Granularity — how much should one call do?#
2.1 The spectrum#
Before the split-vs-merge question, the prior one: should this capability be a tool at all? Some things shouldn't:
- Answer from context — if the information is already in the window or the user's message, a tool adds a failure mode, not a capability. A
get_current_timetool when the system prompt could carry the date is a tax on every request. - Produce a formatted response — when the deliverable is structured output rather than an action, a response schema (03.4) beats a tool call every time.
- Encode a fixed procedure — multi-step workflows with no per-step decisions belong to workflow code (08A.9), not to a model-facing tool; a tool that just replays a script you could have run in code buys you variance for nothing.
- Needs authority or state you can't expose — if the capability requires credentials the model must never see, or hardware/a human in the loop, it's not a tool yet; it's a workflow step or an approval-gated action (4.2, 4.5).
The test a capability must pass to earn a tool: the model must decide to invoke it, supply arguments only it can produce, and act on state your code owns. If any of those is false, you're building an API endpoint with extra steps — and every extra tool is selection-accuracy and token budget spent for nothing (1.8).
Tools that do qualify sit on a spectrum from primitives (one verb, one resource: get_order, update_order_field) to task-level tools (a whole workflow behind one call: resolve_shipping_claim). Neither end is universally right:
| Primitives | Task-level / composite | |
|---|---|---|
| Model freedom | High — it composes steps itself | Low — the workflow is fixed in code |
| Tokens per task | More round trips, more intermediate results in context | One call, one shaped result |
| Reliability | More chances to pick wrong tool/args per step | Fewer decisions, but the tool must anticipate the cases |
| Flexibility | Handles novel combinations | Brittle when the real task differs from the baked-in path |
| Best for | Exploratory, variable tasks; powerful models | High-frequency, well-understood workflows |
Anthropic's engineering post frames the goal as "a few thoughtful tools targeting specific high-impact workflows" — start there and scale. Their worked examples of consolidation:
list_users+list_events+create_event→ oneschedule_eventthat finds availability and booksread_logs→search_logsreturning only relevant lines plus contextget_customer_by_id+list_transactions+list_notes→ oneget_customer_contextcompiling what the agent needs
2.2 Consolidation: one tool, an action parameter#
Anthropic's define-tools page recommends grouping related operations "into a single tool with an action parameter" rather than create_pr, review_pr, merge_pr as three tools. This is the same instinct as a CLI with subcommands (git commit, git push) or a REST resource with methods.
name: tickets_manage
description: Manages support tickets for one customer. Actions: "create" (open a new
ticket — requires subject and body), "list" (the customer's tickets, newest first,
paginated), "get" (one ticket by ID with its full thread), "add_note" (append an
internal note to an existing ticket — does NOT notify the customer), "close"
(resolve a ticket; requires resolution_summary). Use tickets_manage for anything
about tickets; use refunds_issue for money movement instead.
parameters: {
"action": {"type": "string", "enum": ["create", "list", "get", "add_note", "close"]},
"customer_email": {"type": "string"},
"ticket_id": {"type": "string", "description": "Required for get, add_note, close."},
...
}Trade-off to state honestly: consolidation reduces tool count but can produce a fatter schema with action-conditional required fields — which strict modes express awkwardly ("ticket_id required unless action is list"). The alternative, several small tools, is clearer per-call but costs selection accuracy at scale. Rule of thumb: consolidate operations on the same resource that share parameters and permissions; keep separate tools when the risk classes differ (a read and a destructive write should not share a schema the model might confuse).
2.3 Composite and "do what I mean" tools#
The strongest tools often encode your domain knowledge as a single call. schedule_event doesn't expose calendar primitives — it does the whole job: check availability, propose times, book, invite. The model supplies intent; the tool supplies procedure.
Design rules for composites:
- The parameters are the intent, not the steps.
schedule_event(attendees, topic, window)— notcheck_availability+create_event+send_invites. - Return the outcome, not the intermediate states. "Booked: Tue 14:00–14:30 with Jane and Alice; invites sent" beats three raw API responses.
- Keep a primitive escape hatch. When the composite can't express an edge case, the model needs some path — either parameters on the composite (
force: true,prefer: enum) or a sibling primitive tool. A composite with no escape hatch becomes a support ticket generator. - Watch the description budget. A composite's description must cover every action's semantics — the token cost lands on every request (03.5, 14.1).
2.4 Chatty sequences are a design smell#
If transcripts show the model calling get_order → get_order_items → get_order_shipping → get_order_payment in sequence every time, that's your signal to consolidate into one orders_get that returns the composed view (3.1 and 3.2 decide what goes in it). Anthropic's post recommends exactly this analysis: "Tracking tool calls can help reveal common workflows that agents pursue and offer some opportunities for tools to consolidate."
The reverse also happens: one mega-tool do_anything(intent: string, params: object) that internally branches is worse — the schema can't constrain params, the description can't cover every branch, and you've moved the decision problem inside untyped code. Granularity is about matching the schema's expressive power to the task's real variability.
2.5 Return what the model needs, not the API's dump#
The result side of granularity: a tool that wraps a verbose internal API should reshape the response. Anthropic's post is blunt: return "only high signal information… prioritize contextual relevance over flexibility, and eschew low-level technical identifiers". Their address-book example is the canonical case — list_contacts returning everything forces the model to read hundreds of irrelevant entries token-by-token; search_contacts lets it skip to the relevant page, exactly as a human would.
Part 3 is entirely about this. The one-line version: the context window is the scarcest resource in the system; every token a tool returns is a token not available for reasoning.
2.6 Decision table: split or merge?#
| Situation | Design choice |
|---|---|
| Same resource, same permissions, always called together | Merge into one tool (composite or action param) |
| Same resource, different risk classes (read vs destructive) | Keep separate tools — the risk class must be unambiguous |
| Different resources but one user intent ("check order and refund if damaged") | Keep separate tools; let the agent compose — that's what it's for |
| Primitive exists but model must chain 4+ calls for every task | Composite tool that returns the composed result |
| Workflow is fixed, high-frequency, well-understood | Task-level tool; the procedure lives in code, not in the prompt |
| Novel combinations are common and unpredictable | Primitives + strong descriptions; resist over-consolidation |
| Parameters would become action-conditional spaghetti | Split by action into sibling tools sharing a namespace |
Part 3: Results design — what comes back#
The tool result is the second half of the interface, and it lands directly in the model's context. LongFuncEval measured 7–91% degradation in answer retrieval as tool responses grow longer (arXiv:2505.10570) — result size is a first-order accuracy variable, not just a cost one.
3.1 High-signal output#
Return fields the model needs for its next decision, not fields that exist in your database:
- Include: human-meaningful names, statuses, the fields the user asked about, identifiers the model must echo into a follow-up call, and enough provenance to cite or verify.
- Exclude: internal UUIDs the model can't use, raw timestamps in epoch form, full objects "just in case", debug fields, fields only your UI needs.
Anthropic's post recommends a response_format enum ("concise" / "detailed") when the agent sometimes needs technical identifiers to chain calls — expose both modes deliberately rather than always returning the fat version. Their Slack-style example showed concise mode cutting thread responses to a fraction of the default size.
3.2 IDs and handles vs content#
Two identifier philosophies, and the choice matters:
- Semantic identifiers (order IDs like
ORD-1042, ticket refs likeTCK-8831, customer emails) — the model reads, reasons about and echoes them reliably. Anthropic found that "merely resolving arbitrary alphanumeric UUIDs to more semantically meaningful and interpretable language… significantly improves Claude's precision in retrieval tasks by reducing hallucinations." - Opaque handles (UUIDs, cursor tokens, internal row IDs) — necessary when the real key is ugly, but return them alongside the semantic handle, labelled, so the model can use whichever the next tool needs.
The rule: every identifier the model must pass to another tool should appear verbatim in a previous result, labelled with what it is. If refunds_issue needs order_id, then orders_get and orders_search must return order_id in a field literally named order_id. The model can't invent what it never saw — which is exactly what you want.
3.3 Pagination, cursors and truncation markers#
List-shaped results need a contract for "there is more":
{
"orders": [ {"order_id": "ORD-1042", "status": "delivered", "total": "64.99 USD", "ordered_at": "2026-10-28T14:03:00Z"} ],
"returned": 5,
"has_more": true,
"next_cursor": "eyJvZmZzZXQiOjV9",
"note": "Showing newest 5 of 23 orders. Pass next_cursor as 'cursor' to orders_search for the next page, or narrow with 'status'."
}Design rules:
next_cursoris opaque to the model — an encoded position (offset, keyset pair, search-after token), never something it should parse or construct. Your code encodes/decodes it; a tampered cursor becomes a validation error, not a crash or a data leak.- State the totals and the narrowing hint. "5 of 23" plus "narrow with
status" teaches the model to refine rather than blindly paginate — Anthropic's post recommends exactly this steering in truncated responses. - Default page sizes are small (3–10 for rich objects). The model can always ask for more; it can't un-read what you sent.
- Truncation is explicit, never silent.
"truncated": trueplus what was cut and how to get the rest. A silently clipped list teaches the model the world ends at your limit. - Prefer filtering parameters over pagination when the model knows what it wants (
status,since,customer_email). Pagination is for genuine browsing; filters are for targeted retrieval — expose both, describe when each applies.
3.4 Errors the model can act on#
A tool error is not a crash — it's a message the model reads and responds to. 03.5, 7.4 owns the wire mechanics (is_error on Anthropic, "error" key on Gemini, plain text elsewhere); the content design is yours:
| Bad | Good |
|---|---|
Error: not found |
Error: no order found with order_id 'ORD-9999'. The ID may be mistyped — order IDs look like ORD-1042. Try orders_search with the customer's email, or ask the user to check their confirmation email. |
Error: invalid input |
Error: invalid arguments for refunds_issue: amount_cents must be a positive integer in cents (2599 = $25.99), got -500. The order's remaining refundable amount is 4199 cents. |
Error: timeout |
Error: docs_search timed out after 10s. Retry once; if it fails again, answer from the tools you already have and tell the user the docs search is unavailable. |
Traceback (most recent call last)… |
Never. Stack traces leak internals and teach the model nothing actionable. Log them; send a sentence. |
Anthropic's guidance: include "what went wrong and what Claude should try next" — "Rate limit exceeded. Retry after 60 seconds." Their post adds that error responses can steer behaviour: an error that says "use the status filter to narrow results" is a prompt in disguise. Write error strings like descriptions: specific, instructional, free of internals.
3.5 Units, timestamps, formats#
The model can't see your code's conventions, so the result must carry them:
- Money: pick one representation and label it.
"total_cents": 6499invites arithmetic errors;"total": "64.99 USD"is readable but stringly; the safest is both intent and clarity —"total": {"amount_cents": 6499, "currency": "USD"}or"total": "64.99 USD"consistently. Whatever you choose, the parameter descriptions and the result fields must use the same convention — a model that passesamount_centsbut readstotal_usdwill mis-convert. - Timestamps: ISO 8601 with timezone (
2026-10-28T14:03:00Z) — unambiguous, sortable, parseable. Say "UTC" or include the offset. Relative times ("3 days ago") are for humans; give the model absolute ones and let it compute relatives if needed. - Dates vs datetimes: an order
ordered_at(datetime) and apromised_delivery_date(date) are different types — don't blur them. - Enums in results: return the same enum values the parameters accept (
"status": "delivered"), so the model can echo a status straight back intoorders_search(status=...)without translation.
3.6 Secrets and PII in tool output#
Tool results enter the model's context, get logged in traces, and may be echoed to users. Design results as if they'll be screenshotted:
- Never return secrets: API keys, tokens, session cookies, full card numbers, passwords, connection strings.
payment: {"brand": "visa", "last4": "4242"}— never"pan": "4242424242424242". - Return the minimum PII the task needs.
customer_emailmasked asj***@example.comwhen the model only needs to confirm identity; full email only when a downstream tool genuinely requires it. - Other tenants' data is the cardinal sin. A
customer_emailargument must scope every query — 4.2 makes this a hard rule, and Module 06, 6.6 covers the same isolation problem for retrieval. - Untrusted content stays labelled. A
docs_searchsnippet quoting a doc that says "ignore previous instructions…" is data, not instructions — 03.5, 7.5 and Module 12 own the defence-in-depth; your part is returning content in a shape that can't masquerade as a system message.
Part 4: Safety in tool design#
4.1 Risk classes#
Every tool gets exactly one risk class, declared as metadata and enforced by your dispatch layer:
| Class | Definition | Examples | Default handling |
|---|---|---|---|
read |
No observable state change; safe to repeat | orders_get, docs_search, tickets_list |
Execute freely (still rate-limited and validated) |
write |
Creates or modifies state, reversible or low-harm | tickets_create, a tickets_add_note that appends a note |
Execute; log; idempotency preferred |
destructive |
Money, deletion, external messages, irreversible or high-harm | refunds_issue, send_email, delete_account |
Dry-run by default; explicit execute flag; app-side approval before real execution |
The class is a design artefact first: it forces you to answer "what's the worst this can do?" before writing the function. It's a runtime artefact second: the loop or policy layer reads it to decide whether to pause for approval (08A.2 builds the pause/resume hook; 08A.10 and 08A.14 build the approval UX and policy engine).
4.2 Authority: act as the user, least privilege#
The tool's authority must match the requesting user's authority — never the service account's:
- Per-user credentials or scoping. If the user can only see their own orders,
orders_getmust filter by their customer ID — bound from the session, not from a model-suppliedcustomer_emailthe model could change to someone else's. The classic confused-deputy bug: the model "helpfully" looks up another customer's order because the tool didn't scope the query. - Least privilege per tool. The docs-search tool gets a read-only retriever; the refunds tool gets a payments client scoped to refunds only — not the whole payments API. If a tool is compromised (via injection or a bad call), its blast radius is its credential's scope.
- Separate the tool's authority from the user's intent. A support agent acting "as the user" can read what they can read; but writing on their behalf (refunds, emails to third parties) usually needs a higher bar than the user's own session — hence approvals, not just authentication.
4.3 Idempotency keys and safe retries#
Agents retry — the loop retries on errors, the user says "try again", the network flakes. A non-idempotent tool executed twice is a real-world bug (two refunds, two tickets, two emails). The industry-standard answer is the idempotency key: the client generates a unique key per logical operation; the server dedupes on it. Stripe's idempotent-requests doc is the canonical description: keys up to 255 characters, V4-UUID-style randomness suggested, the first response (including errors) is saved and replayed, and "if incoming parameters fail validation… we don't save the idempotent result" — retries of invalid requests are safe to repeat.
For tools, the design rules:
- The app generates the key, not the model. OpenAI's guidance — "don't make the model fill arguments you already know" — applies with force here: a model-supplied
idempotency_keywill be invented, reused or corrupted. Your loop/app derives it from the request context. The scheme 08A.2 prescribes is a hash of(run_id, tool_name, canonical_args): the run/conversation scope means two legitimately identical operations on different days get different keys, while a retried or resumed run re-issuing the same call hits the same key and replays the stored result. A bare hash of the arguments alone is not safe — it would collapse distinct logical operations that happen to share args (two identical $25 refunds requested a week apart would share a key, and the second would silently replay the first's result instead of executing). - Natural idempotency where possible.
tickets_createcan dedupe on (customer, subject-hash) within a window and return the existing ticket with"duplicate": true— no key needed, and retries become harmless. Prefer this when the domain allows it. - Key scope and TTL. Dedupe within a sane window (hours to days; Stripe's v1 API may prune a key once it is at least 24 hours old, and a reused key after that starts a new request). Store (key → result) so a retry returns the same result, not just "already done".
- Reads are naturally idempotent — mark them
idempotent=Trueand skip the machinery.
4.4 Dry-run and preview modes#
For any destructive tool, the default call should be a preview: same validation, same lookups, but no state change — returning exactly what would happen:
refunds_issue(order_id="ORD-1042", amount_cents=2500, reason="damaged item", execute=false)
→ {"dry_run": true,
"would_refund": {"order_id": "ORD-1042", "order_status": "delivered",
"eligible": true,
"refund": {"amount_cents": 2500, "amount": "25.00 USD",
"to": "visa ••4242"},
"reason": "damaged item",
"remaining_refundable_cents": 6499},
"next_step": "Show the user this preview. Call again with execute=true ONLY after they confirm — and only when 'eligible' is true."}This does three jobs: it lets the model verify its own arguments before committing (it sees the resolved order, the real refundable amount, the destination, and an eligible flag that mirrors the real call's status gate — a cancelled order previews as ineligible instead of advertising money it can't move), it gives the approval step something concrete to display, and it makes the irreversible call a deliberate second act. The execute flag is a deliberateness control — the authorisation still belongs to your policy layer (4.5).
4.5 Confirmation parameters and human approval#
The tempting design — confirmed: bool the model must set — is necessary but not sufficient. It proves the model intended the call; it doesn't prove a human approved it. The model can set confirmed=true on its own initiative, especially under prompt injection. The layered design:
- Tool level:
execute/dry_runparameter — makes the real call a distinct, describable act. - Loop level: the agent loop recognises
destructivetools and pauses for approval before dispatch (08A.2 builds the hook; 08A.10 covers approval patterns). - Policy level: your code decides whether this call needs approval based on risk class, amount thresholds, user role — not on anything the model says (08A.14).
- Provider level (optional): Anthropic's
allowed_callersfield can restrict who may invoke a tool ("direct"for the model's owntool_useblocks, the default, or a code-execution caller such as"code_execution_20260120"for code running in the sandbox) — verified on the tool-reference page as of November 2026.
4.6 Argument validation and injection#
The model's arguments are untrusted input — as untrusted as a web form, because they can be steered by anything the model read (a malicious doc, a poisoned ticket, a web page). 03.5, Part 7 owns the baseline (schema validation, dispatch table, never eval); the injection-specific layer:
- SQL: never interpolate model arguments into query text. Use bound parameters or — better for agents — an allow-list of named queries. The
sqlite3demo below is stdlib-only and runs for real:
# s4_6_sql_injection.py — why tool args never touch SQL text (stdlib only, real output)
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id TEXT, customer TEXT, status TEXT, total_cents INTEGER)")
db.executemany("INSERT INTO orders VALUES (?,?,?,?)",
[("ORD-1042", "ana@example.com", "delivered", 6499),
("ORD-1043", "bo@example.com", "shipped", 1200)])
# NAIVE: the model's argument goes straight into the query text.
# A customer_email of "x' OR '1'='1" returns EVERY order.
evil_email = "x' OR '1'='1"
q_naive = f"SELECT id, total_cents FROM orders WHERE customer = '{evil_email}'"
print("naive :", db.execute(q_naive).fetchall())
# SAFE: bound parameter — the value is data, never syntax.
q_safe = "SELECT id, total_cents FROM orders WHERE customer = ?"
print("bound :", db.execute(q_safe, (evil_email,)).fetchall())
# SAFEST for agents: an allow-list of named queries; the model picks a NAME,
# never writes SQL. No parameter can escape into syntax at all.
QUERIES = {
"orders_by_email": "SELECT id, status, total_cents FROM orders WHERE customer = ?",
}
print("allowlist:", db.execute(QUERIES["orders_by_email"], ("ana@example.com",)).fetchall())naive : [('ORD-1042', 6499), ('ORD-1043', 1200)]
bound : []
allowlist: [('ORD-1042', 'delivered', 6499)]The naive query leaked both customers' orders; the bound one returned none (correctly — no such customer); the allow-list can't even express the attack. For an agent, prefer the allow-list: the model chooses which query, your code owns how it's written.
- Shell: never
subprocesswith model strings; allow-list executables, pass args as lists (shell=False), fixed working directories, timeouts. - Paths: resolve and prefix-check (
Path(p).resolve()must stay under the allowed root) — a../../etc/passwdargument is a traversal, andresolve()is what catches the encoded variants. - URLs / SSRF: an
urlparameter is a server-side fetch waiting to happen — allow-list schemes (httpsonly) and hosts, resolve DNS and reject private/loopback ranges, cap response size. Browsing tools (5.6) live or die by this. - The schema is not the validator. Strict mode guarantees shape; your code guarantees the world (the order exists, the amount is within the refundable balance, the path is inside the sandbox). Both layers, always — 03.4, Part 6 is the same argument for outputs.
4.7 Rate limits, quotas and allow-lists#
Tools need their own budgets, independent of the model's:
- Per-tool rate limits (calls/minute per user/session) stop a looping agent from hammering a downstream API — and stop a prompt-injected agent from doing it on purpose. A token bucket per tool is ~15 lines; the registry in Part 6 implements one.
- Per-call budgets: max rows, max response tokens, max pagination depth — enforced in the tool, returned as explicit truncation (3.3).
- Allow-lists at two levels: which tools a given agent/user may see at all (your dispatch table already 404s unknown names — 03.5, 7.2), and which arguments are acceptable (enums, regexes, ranges, existence checks).
- Cost visibility: a tool that calls a paid API (search, SMS, LLM-in-tool) should log its spend per call — 03.7 owns cost tracking; 08A.14 owns budgets across an agent run.
4.8 Output sanitisation#
What a tool returns can be as dangerous as what it accepts:
- Redact before returning: the function strips secrets/PII at the boundary, so they never reach the model's context (where they'd be logged, cached and echoable) — 3.6.
- Untrusted content is data: results from web pages, tickets, emails and uploaded docs are wrapped/labelled as data, never concatenated into instruction-looking text — 03.5, 7.5.
- Don't let tool output auto-trigger tools: a
docs_searchresult containing "call refunds_issue for order X" is an injection attempt; the policy layer treats tool results as untrusted when deciding the next call's permissions (08A.14, Module 12).
4.9 Tool timeouts and cancellation#
Every tool call needs a timeout, because a slow tool holds the whole run: the model is waiting, the user is waiting and a worker is blocked. The loop in 08A.2 already wraps each call in a timeout; this section covers how to choose the value, what a timeout does and does not stop, and what the model should be told. The run-level deadline (the wall-clock max_seconds of the whole agent run) is a different limit that lives in 08A.2, section 3.3. A per-tool timeout must always be shorter than what is left of the run deadline, otherwise one slow tool can eat the whole run.
Choosing a per-tool timeout. One global number is wrong for every tool at once. Set it per tool, from measurement:
- Take the tool's slowest normal call (the p99 latency from your traces, see 08A.2, section 4.3) and add headroom, usually 1.5 to 3 times.
- Reads can have a short timeout: a read that has not answered in a few seconds is usually stuck, and retrying is harmless.
- Writes need a longer timeout, or no thread timeout at all (see the warning below), because giving up early is the dangerous choice for them.
- Search, browsing and code-execution tools are slow by nature. Give them their own larger value, and let the tool take a
timeout_sargument capped by a hard maximum (the code-execution tool in 5.4 does this). - Keep the timeout in the tool's registry entry next to its risk class, so the number is reviewed with the tool.
A timeout stops waiting, not working. asyncio.wait_for and future.result(timeout=...) both stop waiting for the answer. Neither can stop a Python thread that is already running. The work carries on and may finish after you have reported failure. To really cancel, the tool must cooperate: check a threading.Event (or an asyncio cancellation) between small slices of work, and stop when it is set. For tools that cannot be interrupted half way (a payment call, a database commit) there is no cancel; the only safe design is idempotency.
Return the timeout as an error the model can act on. A bare timeout string teaches the model nothing. Say what happened, whether the work may still complete, and the one next step you want (3.4 has the general rules). The right advice differs by risk class:
| Tool kind | Timeout message tells the model | Why |
|---|---|---|
read |
Retry once, then answer from what you have or tell the user the system is slow | A repeated read is harmless |
write |
The action may still complete. Do not start a new one. Repeat the same call (it is safe) or check the status | A "new" attempt could double-execute |
destructive |
Do not retry. Tell the user the outcome is unknown and a person must check | Approval was given for one execution, not two |
The interaction with idempotency keys. A timeout on a write turns "did it happen?" into an open question, and the model's natural reaction is to call the tool again. That is only safe if the retry carries the same idempotency key as the first call (4.3). Three rules follow:
- The app derives the key from
(run_id, tool_name, canonical_args). The model never supplies it, so a retry of the same logical call always lands on the same key. - The tool must handle three states for a key: not seen (run it), running (answer "still in progress", do not start a second copy) and done (replay the stored result). Many first versions forget the running state, and a retry that arrives while the first call is still working then executes twice.
- The stored key must outlive the timeout, the retry delay and the longest human approval wait. A key that expires after the timeout is no protection.
The script below runs all of this with fake tools and no network. It uses real threads and asyncio, scaled to milliseconds so it finishes in about a second and a half. Save it as tool_timeouts.py and run python3 tool_timeouts.py.
"""Tool timeouts, cancellation and idempotency. Stdlib only, no keys, no network."""
import asyncio
import hashlib
import json
import threading
import time
from dataclasses import dataclass
from typing import Callable
LEDGER: list[dict] = [] # the "real world": refunds that actually committed
STORE: dict[str, dict] = {} # idempotency store: key -> {"state", "result"}
LOCK = threading.Lock()
SLICES_RUN = 0 # how many 10 ms slices the slow search really ran
def idem_key(run_id: str, tool: str, args: dict) -> str:
canonical = json.dumps(args, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(f"{run_id}|{tool}|{canonical}".encode()).hexdigest()[:12]
# --- fake tools (they take a cancel event and a key; the runner supplies both) ---
def orders_get(order_id: str, cancel: threading.Event) -> str:
return json.dumps({"order_id": order_id, "status": "delivered"})
def docs_search(query: str, cancel: threading.Event) -> str:
"""A slow read tool. It checks the cancel event every 10 ms, so it can stop early."""
global SLICES_RUN
for _ in range(100): # would take 1000 ms if left alone
if cancel.is_set():
return "cancelled"
time.sleep(0.010)
SLICES_RUN += 1
return "10 articles"
def refunds_issue(order_id: str, amount_cents: int, key: str) -> str:
"""A slow write tool (300 ms). It cannot be cancelled half way, so it dedupes on the key."""
with LOCK:
entry = STORE.get(key)
if entry: # a retry: replay the result or report progress
if entry["state"] == "done":
return entry["result"] + " (replayed)"
return "Error: this refund is still being processed. Check again shortly."
STORE[key] = {"state": "running", "result": ""}
time.sleep(0.300) # the slow payment provider
LEDGER.append({"order_id": order_id, "amount_cents": amount_cents})
result = f"refund of {amount_cents} cents issued for {order_id}"
with LOCK:
STORE[key] = {"state": "done", "result": result}
return result
def refunds_naive(order_id: str, amount_cents: int, key: str) -> str:
"""The same tool WITHOUT an idempotency check, for contrast."""
time.sleep(0.300)
LEDGER.append({"order_id": order_id, "amount_cents": amount_cents, "tool": "naive"})
return f"refund of {amount_cents} cents issued for {order_id}"
# --- the runner ------------------------------------------------------------------
@dataclass
class ToolSpec:
fn: Callable
timeout_ms: int # per-tool: the tool's slowest normal call plus headroom
risk: str # "read" or "write"
on_timeout: str # what the model is told to do next
SPECS = {
"orders_get": ToolSpec(orders_get, 200, "read",
"Retry once; if it fails again, tell the user the order system is slow."),
"docs_search": ToolSpec(docs_search, 300, "read",
"Retry once with a shorter query, or answer from what you already have."),
"refunds_issue": ToolSpec(refunds_issue, 100, "write",
"The refund may still complete. Do NOT start a new refund. Call this tool again "
"with the SAME arguments: it is safe and returns the stored result."),
"refunds_naive": ToolSpec(refunds_naive, 100, "write",
"Try again."),
}
async def run_tool(run_id: str, name: str, args: dict) -> tuple[str, bool]:
spec = SPECS[name]
cancel = threading.Event()
kwargs = dict(args)
if spec.risk == "write":
kwargs["key"] = idem_key(run_id, name, args) # the app derives the key, not the model
else:
kwargs["cancel"] = cancel
task = asyncio.create_task(asyncio.to_thread(spec.fn, **kwargs))
try:
# shield(): a timeout stops WAITING for the thread; it does not (and cannot) kill it
out = await asyncio.wait_for(asyncio.shield(task), timeout=spec.timeout_ms / 1000)
return out, out.startswith("Error")
except asyncio.TimeoutError:
cancel.set() # ask a cooperative tool to stop
if spec.risk == "read":
await asyncio.wait({task}, timeout=0.05) # short grace period, then move on
outcome = "stopped" if task.done() else "still running in the background"
return (f"Error: {name} timed out after {spec.timeout_ms} ms (work {outcome}). "
f"{spec.on_timeout}"), True
async def main() -> None:
t0 = time.perf_counter()
async def call(label: str, run_id: str, name: str, args: dict) -> None:
result = await run_tool(run_id, name, args)
print(f" [{(time.perf_counter() - t0) * 1000:4.0f} ms] {label}: {result}")
print("1. fast tool inside its timeout")
await call("orders_get", "run-1", "orders_get", {"order_id": "ORD-1042"})
print("2. slow read tool: timeout, then cooperative cancel")
await call("docs_search", "run-1", "docs_search", {"query": "refund policy"})
await asyncio.sleep(0.2)
print(f" slices run: {SLICES_RUN} of 100 (the thread really stopped)")
print("3. slow write tool WITH an idempotency key")
refund = {"order_id": "ORD-1042", "amount_cents": 2500}
await call("first call ", "run-1", "refunds_issue", refund)
print(" ledger right after the timeout:", LEDGER)
await call("retry at once ", "run-1", "refunds_issue", refund)
await asyncio.sleep(0.3)
print(" ledger after the slow call finished:", LEDGER)
await call("retry later ", "run-1", "refunds_issue", refund)
print(" refunds committed:", len(LEDGER), "(one logical call, one refund)")
print("4. the same tool WITHOUT a key: the 'safe' retry pays twice")
del LEDGER[:]
naive = {"order_id": "ORD-2001", "amount_cents": 2500}
await call("first call ", "run-3", "refunds_naive", naive)
await call("model retries ", "run-3", "refunds_naive", naive)
await asyncio.sleep(0.4)
print(" refunds committed:", len(LEDGER), "<- two refunds from one logical call")
asyncio.run(main())Real output from one run (the millisecond stamps and the slice count vary slightly between runs):
1. fast tool inside its timeout
[ 1 ms] orders_get: ('{"order_id": "ORD-1042", "status": "delivered"}', False)
2. slow read tool: timeout, then cooperative cancel
[ 305 ms] docs_search: ('Error: docs_search timed out after 300 ms (work stopped). Retry once with a shorter query, or answer from what you already have.', True)
slices run: 25 of 100 (the thread really stopped)
3. slow write tool WITH an idempotency key
[ 607 ms] first call : ('Error: refunds_issue timed out after 100 ms (work still running in the background). The refund may still complete. Do NOT start a new refund. Call this tool again with the SAME arguments: it is safe and returns the stored result.', True)
ledger right after the timeout: []
[ 607 ms] retry at once : ('Error: this refund is still being processed. Check again shortly.', True)
ledger after the slow call finished: [{'order_id': 'ORD-1042', 'amount_cents': 2500}]
[ 909 ms] retry later : ('refund of 2500 cents issued for ORD-1042 (replayed)', False)
refunds committed: 1 (one logical call, one refund)
4. the same tool WITHOUT a key: the 'safe' retry pays twice
[1009 ms] first call : ('Error: refunds_naive timed out after 100 ms (work still running in the background). Try again.', True)
[1111 ms] model retries : ('Error: refunds_naive timed out after 100 ms (work still running in the background). Try again.', True)
refunds committed: 2 <- two refunds from one logical callRead the output in four steps:
- Step 1 is the normal case: the call finishes inside its 200 ms limit.
- Step 2 is a cooperative cancel. The timeout fires at 300 ms, the runner sets the event, and the search stops after about 25 of its 100 slices. The thread is freed and the model gets a clear next step.
- Step 3 is the safe write. The timeout fires while the payment is still in flight, so the ledger is empty at that moment, yet the refund does commit 300 ms later. The immediate retry is told the refund is still in progress instead of starting a second one, and the later retry replays the stored result. One logical call, one refund.
- Step 4 is the same tool without the check. The "just try again" message produces two refunds for one request. This is the bug that the warning in 08A.2, section 6.3 describes, shown in numbers.
Part 5: A taxonomy of tool types#
Reference
Not all tools are CRUD. This catalogue covers the shapes agents actually need, each with a compact worked design — name, description essence, argument shape, result shape, risk class. The running example in Part 6 implements four of them in full.
5.1 Retrieval and search tools#
Purpose: let the agent query a corpus — docs, tickets, knowledge base — without loading it into context.
name: docs_search
risk: read | idempotent: yes
args: {query: string (required, the search text), top_k: int 1-5 default 3}
result: [{title, source, snippet}] — no scores, no raw chunks; snippet ≤ ~40 wordsDesign notes: search, don't list (Anthropic's search_contacts vs list_contacts lesson); return handles (source doc IDs) the model can cite; snippets sized for decision-making, not comprehension — the model reads more via a follow-up call if needed. For RAG-backed agents this wraps the Module 07 docs_qa retriever — the Retriever protocol from 06.10 (search(query, k, filters) -> list[Hit]) is exactly the seam a tool needs. Hybrid/BM25/dense trade-offs are Module 06's subject; your concern is only the result shape.
5.2 Database and SQL tools (read-only)#
Purpose: let the agent answer questions about structured business data.
Two viable designs, in increasing safety:
- Named queries (allow-list) —
orders_by_email,orders_in_range,top_customers. The model picks a name and fills typed parameters; your code owns the SQL. Safest; best for known question patterns. - A constrained query tool — e.g.
query_orders(filters: {...})where filters are typed fields mapped to a fixed WHERE builder. More flexible than named queries, still no free SQL.
What you should never ship: run_sql(query: string) — even "read-only". A read-only role still leaks every table's contents to anyone who can steer the model, and SQL has a thousand ways to be slow (cartesian joins, missing indexes) that become your outage. If you must expose SQL, enforce: a read-only DB role, statement timeout, row cap, and result truncation — and read Module 12 first.
name: db_orders_query
risk: read | idempotent: yes
args: {customer_email?: string, status?: enum, placed_after?: ISO date, limit: int ≤ 50}
result: {rows: [...], returned, has_more, next_cursor}5.3 HTTP API wrappers#
Purpose: reach a third-party or internal REST/GraphQL API.
The tool is an adapter, not a proxy: authenticate with credentials your code holds (never model-supplied), map the model's clean arguments to the API's shape, and reshape the response to high-signal fields (2.5). Watch for: APIs whose responses are huge (paginate or filter before returning), APIs that need multi-step auth (do it inside the tool), and APIs with their own rate limits (your per-tool limiter should be stricter than theirs). Timeouts and retries per 03.8; every upstream failure becomes an actionable error result (3.4).
name: shipment_track
risk: read | idempotent: yes
args: {tracking_number: string (required, e.g. "FP-88231-AA"),
carrier?: enum["fastpost","dhl","ups"] — omit to auto-detect}
result: {carrier, status, status_detail,
checkpoints: [{at, location, event}], # newest first, ≤ 5
eta?: ISO date, events_truncated: bool}5.4 Calculation and code-execution tools#
Purpose: arithmetic the model is bad at (it will confidently compute 6499 * 1.2 wrong often enough to matter), data transformation, chart data prep.
- Calculator tools: a tiny safe expression evaluator — allow-listed operations on numbers, no eval. Cheap, deterministic, eliminates a whole error class.
- Code execution: running model-written code is powerful and dangerous; the sandbox question is 08A.15's subject, and provider-hosted code interpreters are 08A.8's. If you build your own, the tool contract is: input code + optional files → output stdout/result/error, with strict time/memory/network limits and no secrets in the sandbox.
name: calc
risk: read | idempotent: yes
args: {expression: string — arithmetic only: + - * / % ** ( ) and decimals,
e.g. "6499 * 0.1 + 250"}
result: {value: 899.9} or {error: "unexpected character '='"} — never a traceback
name: run_python
risk: write (sandboxed: no network, no secrets, no host FS) | idempotent: no
args: {code: string (required), timeout_s?: int 1-30 default 10}
result: {stdout: ≤ 8 KB, return_value?: repr, error?: {type, message},
truncated: bool}5.5 File tools#
Purpose: read/write files in a sandboxed workspace — the backbone of coding and document agents.
Design rules: paths are resolved and confined to an allowed root (4.6); read/list/search are read class, write/edit/delete are write/destructive; results return file content truncated with offsets (start_line, end_line, total_lines) so the model pages through large files instead of dumping them; edits return a diff or unified patch summary, not the whole file. The full coding-agent treatment — edit formats, repo context, verification loops — is 08A.15.
name: file_read
risk: read | idempotent: yes
args: {path: string — must resolve under /workspace,
offset?: int (line number, default 1), limit?: int 1-400 default 200}
result: {path, content, start_line, end_line, total_lines, has_more: bool}
name: file_write
risk: write | idempotent: no (dedupe on path+content hash if retries matter)
args: {path: string, content: string,
mode?: enum["create","overwrite","append"] default "create"}
result: {path, bytes_written, lines_changed}5.6 Browsing tools#
Purpose: fetch and read web pages.
The deadliest tool type for injection: every page is untrusted content entering the context (03.5, 7.5, Module 12). Design: URL allow-list or domain policy in code; scheme restricted to http(s); DNS-resolution check against private/loopback ranges (SSRF); response size cap; content converted to readable text (boilerplate stripped); the result labelled as fetched external content with its URL and fetch timestamp. "Never bypass CAPTCHAs or paywalls" belongs in the description and the code. Provider-hosted web search/fetch tools and their citation formats are 08A.8.
name: web_fetch
risk: read | idempotent: yes (same URL under the same policy → same fetch)
args: {url: string (https only, public hosts — enforced in code, not prose),
max_chars?: int 1000-20000 default 8000}
result: {url, final_url, title, fetched_at,
text: boilerplate-stripped, ≤ max_chars,
truncated: bool, next_offset?: int} # page through long pages5.7 Messaging and email tools#
Purpose: send Slack messages, emails, SMS, create calendar invites — anything that reaches a human outside your system.
Always destructive or high-write: the blast radius is a real person's inbox. The pattern that works: send_email defaults to draft mode (draft: true creates a reviewable draft, returns its ID; draft: false sends — gated by approval). The description says plainly "this emails a real person; draft first". Recipients must come from tool-resolved values (looked up by ID/email the user provided), never model-invented addresses — validate the address exists in your contacts before sending.
name: send_email
risk: destructive | idempotent: no (drafts are safe; sends are not)
args: {to_contact_id: string (a KNOWN contact — never a raw address the model
invents), subject: string, body: string,
send?: bool default false}
result (send=false): {draft_id, to, subject, preview: first ~200 chars} — nothing sent
result (send=true): {message_id, sent_at} — reachable only after approval5.8 Human-in-the-loop tools#
Purpose: the "ask the user" tool — when the agent genuinely can't proceed without information or a decision only the human can make.
name: ask_user
risk: read (it changes nothing; it pauses the loop)
args: {question: string, options?: [string, ...], context?: string}
result: {answer: string} — the user's reply, fed back as the tool resultThis is how an agent asks clarifying questions mid-run instead of guessing. Design notes: keep questions specific and optioned when possible ("Which order — ORD-1042 or ORD-1043?" beats "Which order?"); context explains why you're asking so the user can answer well; the loop must support pausing (08A.2 / 08A.10); and the description must teach when to ask vs when to proceed with a stated assumption — the single most important sentence in an agent's tool set is usually here. Over-asking is its own failure mode (see 8.4).
5.9 Scratchpad / "think" tools#
Purpose: give the model a place to write working notes — plans, intermediate results, hypotheses — that persist across the run without polluting the user-facing transcript.
Evidence this helps: Google's function-calling docs recommend wrapping pre-tool working notes in a dedicated update() function call (with previous_step, plan, next_step, external params) as the preferred fix for models that must emit structured notes before tool calls (function-calling doc, "Workarounds for pre-tool text requirements", verified November 2026). The pattern generalises: think(notes: string) or update_plan(steps: [...]) tools externalise the model's reasoning into inspectable, loggable artefacts.
name: think
risk: read (writes run-scoped notes, not world state) | idempotent: yes
args: {notes: string — working reasoning, hypotheses, dead ends to revisit}
result: {note_id, chars_stored} — lands in traces, not the user-facing answer
name: update_plan
risk: read (run-scoped) | idempotent: yes
args: {steps: [{description: string,
status: enum["pending","in_progress","done"]}],
notes?: string}
result: {plan_revision, steps: n} — the current plan, readable on the next turnWhen it earns its place: multi-step tasks where the plan should survive context trimming (04.7); debugging (you can read the scratchpad in traces); steering (the user can see and correct the plan). When it doesn't: single-step tasks, or reasoning models that already think natively — a scratchpad on top of thinking tokens is often wasted context. Keep scratchpad content out of results returned to other tools; it's for the model and the trace, not for downstream consumers.
5.10 The catalogue#
| Tool type | Risk class | Key design rule |
|---|---|---|
| Retrieval/search | read | search, don't list; snippets sized for decisions |
| Database/SQL | read | allow-listed queries or typed filters; never free SQL |
| HTTP API | read/write | adapter with your credentials; reshape responses |
| Calculator/code exec | read (exec: write+) | safe eval or sandboxed runtime; no secrets inside |
| File ops | read/write/destructive | path sandbox; paged reads; diff-sized writes |
| Browsing | read | untrusted content; URL/SSRF policy; size caps |
| Messaging/email | destructive | draft-by-default; resolved recipients; approval |
| Human-in-the-loop | read | specific questions; options when possible; ask-vs-assume guidance |
| Scratchpad/think | read | for plans that must persist; not for one-step tasks |
Part 6: The running example — the support assistant's tools#
The module's running example is a support and operations assistant for the fictional company: it looks up orders, searches the docs, creates tickets and issues refunds (with approval). This part builds its complete tool set — the design decisions first, then the code.
08A.2's minimal support_tools.py |
This redesign | The rule it applies |
|---|---|---|
lookup_order, search_docs, create_ticket, issue_refund, run_report, submit_answer |
orders_get, orders_search, tickets_create, tickets_list, refunds_issue, docs_search |
Domain-prefixed, verb-consistent names (1.3) |
issue_refund — risk="write", amount: float dollars |
refunds_issue — risk="destructive", amount_cents: int, execute dry-run flag |
Money movement is destructive (4.1); integer cents (3.5); preview-first (4.4) |
run_tool / REGISTRY / ToolSpec |
Tool / ToolRegistry.dispatch |
Adds rate limits, app-supplied idempotency keys and dry-run awareness (4.3, 4.7) |
IDs A17/B22/C09, float totals, no pagination |
ORD-NNNN semantic IDs, *_cents integers, ISO timestamps, cursor pagination |
3.2, 3.3, 3.5 |
| No dedupe, no dry-run, no result shaping | Natural idempotency, dry-run previews, composed high-signal views | 4.3, 4.4, 2.5 |
run_report and submit_answer don't appear: operational reports are a workflow concern (08A.9 — a fixed procedure doesn't need per-step model decisions), and submit_answer is the loop's finish-tool convention (08A.2), not a domain tool. This file designs the customer-facing surface.
6.1 The design, tool by tool#
| Tool | Risk | Idempotent? | Shape rationale |
|---|---|---|---|
orders_get |
read | yes | One order by ID or email — exactly-one validator; returns composed view (status, items, totals, payment brand/last4, timestamps) so the model needs one call, not four |
orders_search |
read | yes | Cursor-paginated list scoped to a customer; status enum filter; next_cursor + "narrow with status" hint |
tickets_create |
write | yes (natural dedupe) | Opens a ticket; dedupes on customer+subject so a model retry can't double-post; returns ticket ID in TCK-NNNN form |
tickets_list |
read | yes | Same pagination contract as orders_search — consistent result shapes teach the model once |
refunds_issue |
destructive | no — app-supplied key | execute=false dry-run by default (previews need no key — they mutate nothing); validates order state and refundable balance; real execution requires the dispatch layer's idempotency key and (in production) human approval |
docs_search |
read | yes | Wraps a Retriever-protocol object (the Module 07 docs_qa retriever plugs in here); returns title/source/snippet, no scores |
Naming: domain-prefix (orders_, tickets_, refunds_, docs_) — the namespacing rule from 1.3. Descriptions follow the 1.4 template including explicit when-not-to-use guidance. All argument models are Pydantic with extra="forbid" — one class generates the JSON Schema and validates incoming arguments, so schema and validator can't disagree: undeclared arguments are rejected, not silently dropped (03.5, 2.1).
6.2 support_data.py — fake data and a toy retriever#
Everything is in-memory and deterministic; KeywordRetriever stands in for the Module 07 docs_qa retriever behind the same search(query, k, filters) protocol.
# support_data.py — the fictional company's data, all fake and in-memory.
# Stdlib only: this file runs with no packages installed.
from __future__ import annotations
import re
from dataclasses import dataclass, field
CUSTOMERS = {
"ana@example.com": {"name": "Ana Ruiz", "tier": "gold", "since": "2024-03-11"},
"bo@example.com": {"name": "Bo Tanaka", "tier": "standard", "since": "2025-01-19"},
}
# Orders carry everything a support agent needs to answer "where is my order",
# "what did I buy" and "can I get a refund" — nothing it doesn't.
ORDERS = {
"ORD-1042": {
"order_id": "ORD-1042", "customer_email": "ana@example.com",
"status": "delivered", "currency": "USD",
"items": [{"sku": "WB-881", "name": "Wireless earbuds", "qty": 1, "unit_price_cents": 5999},
{"sku": "CB-102", "name": "USB-C cable 1m", "qty": 2, "unit_price_cents": 250}],
"total_cents": 6499,
"ordered_at": "2026-10-28T14:03:00Z", "delivered_at": "2026-11-01T09:41:00Z",
"tracking": {"carrier": "FastPost", "number": "FP-88231-AA"},
"payment": {"brand": "visa", "last4": "4242"},
"refunds": [], # list of {"id", "amount_cents", "reason", "at"}
},
"ORD-1043": {
"order_id": "ORD-1043", "customer_email": "bo@example.com",
"status": "shipped", "currency": "USD",
"items": [{"sku": "KB-220", "name": "Mechanical keyboard", "qty": 1, "unit_price_cents": 12000}],
"total_cents": 12000,
"ordered_at": "2026-11-02T08:15:00Z", "promised_delivery": "2026-11-09",
"tracking": {"carrier": "FastPost", "number": "FP-90117-BC"},
"payment": {"brand": "mastercard", "last4": "5555"},
"refunds": [],
},
"ORD-1044": {
"order_id": "ORD-1044", "customer_email": "ana@example.com",
"status": "cancelled", "currency": "USD",
"items": [{"sku": "MS-310", "name": "Mouse pad XL", "qty": 1, "unit_price_cents": 1800}],
"total_cents": 1800,
"ordered_at": "2026-09-14T11:20:00Z", "cancelled_at": "2026-09-15T10:02:00Z",
"payment": {"brand": "visa", "last4": "4242"},
"refunds": [{"id": "RF-001", "amount_cents": 1800, "reason": "customer request",
"at": "2026-09-16T12:00:00Z"}],
},
}
TICKETS = {} # ticket_id -> ticket record; tickets_create adds to this
DOCS = [
{"id": "handbook-returns", "title": "Returns and refunds policy",
"text": "Customers may return unused items within 30 days of delivery for a full refund. "
"Damaged or defective items are eligible for a refund at any time. Refunds are "
"issued to the original payment method within 5 business days."},
{"id": "handbook-shipping", "title": "Shipping and delivery",
"text": "Orders ship within 1-2 business days. Standard delivery takes 3-7 business days. "
"Express delivery takes 1-2 business days. Tracking is emailed when the order ships."},
{"id": "handbook-warranty", "title": "Warranty",
"text": "All electronics carry a 2-year limited warranty covering manufacturing defects. "
"Accidental damage is not covered. Warranty claims require the order ID."},
{"id": "faq-headphones", "title": "FAQ: earbud connectivity",
"text": "If earbuds disconnect frequently, reset them by holding both touch pads for 10 "
"seconds, then re-pair. Firmware updates are applied automatically in the app."},
]
@dataclass(frozen=True)
class Hit:
"""One search result — the shape the Module 07 Retriever protocol returns."""
id: str
score: float
text: str = ""
metadata: dict = field(default_factory=dict)
source: str = ""
class KeywordRetriever:
"""A tiny stand-in for the docs_qa retriever: scores docs by query-term overlap.
Real deployments use the Module 07 retriever (dense/hybrid); the tool only
needs the search(query, k, filters) -> list[Hit] shape."""
def __init__(self, docs: list[dict]):
self._docs = docs
def search(self, query: str, k: int = 3, filters: dict | None = None) -> list[Hit]:
terms = {t for t in re.findall(r"[a-z0-9]+", query.lower()) if len(t) > 2}
scored = []
for d in self._docs:
hay = f"{d['title']} {d['text']}".lower()
score = sum(hay.count(t) for t in terms)
if score:
scored.append(Hit(id=d["id"], score=float(score), text=d["text"],
metadata={"title": d["title"]}, source="docs"))
scored.sort(key=lambda h: h.score, reverse=True)
return scored[:k]6.3 support_tools.py — schemas, functions, registry, dispatch#
This file is the heart of the lesson. It has four layers, and the separation is the design:
- Argument models (Pydantic) — generate the JSON Schema and validate calls.
- Tool functions — pure Python over the fake data; dependencies (the retriever) are injected at construction, never taken from the model. Idempotency is not a function concern —
dispatch()owns it, which is whyrefunds_issuetakes no store. Toolmetadata — risk class, idempotency, rate limit, declared next to the function so they can't drift apart.ToolRegistry.dispatch— the single gate every call passes through: allow-list → rate limit → argument validation → idempotency (mutating calls only — a dry-run preview is not an operation) → execute → error capture. It returns(result, is_error), the shape every agent loop needs; 08A.2'srun_agent/_execute_oneplays the same role over its ownToolSpecregistry, so wiring this file into that loop means callingdispatch()from the loop's execution step (or adaptingTooltoToolSpec).
# support_tools.py — the support assistant's REDESIGNED tools, schemas and registry.
# Same filename as 08A.2's file on purpose: this version replaces it (see the
# lesson text). Everything is pure-local: in-memory fake data, no network, no
# API keys. dispatch() is the single gate every call passes through — the same
# seam 08A.2's run_agent uses, with rate limiting and idempotency added.
from __future__ import annotations
import base64
import json
import time
import uuid
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
from typing import Any, Callable, Literal
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
from support_data import CUSTOMERS, DOCS, ORDERS, TICKETS, KeywordRetriever
Risk = Literal["read", "write", "destructive"]
# ---------------------------------------------------------------------------
# Argument models: one per tool. model_json_schema() produces the wire schema;
# model_validate() is the runtime check. They cannot disagree — and
# extra="forbid" makes that literal: every schema carries
# "additionalProperties": false (the strict-mode subset all providers require)
# and an invented extra argument is a validation error, not a silent drop.
# ---------------------------------------------------------------------------
class OrderStatus(str, Enum):
PLACED = "placed"; SHIPPED = "shipped"; DELIVERED = "delivered"
CANCELLED = "cancelled"; REFUNDED = "refunded"
class TicketPriority(str, Enum):
LOW = "low"; NORMAL = "normal"; HIGH = "high"; URGENT = "urgent"
class TicketStatus(str, Enum):
OPEN = "open"; PENDING = "pending"; CLOSED = "closed"
class OrdersGetArgs(BaseModel):
"""Exactly one of order_id / customer_email must be given."""
model_config = ConfigDict(extra="forbid")
order_id: str | None = Field(default=None,
description="Order ID like ORD-1042, from the customer's confirmation email. "
"Provide this OR customer_email — exactly one of the two, never both.")
customer_email: str | None = Field(default=None,
description="Customer's registered email, exactly as registered. Provide this OR "
"order_id — exactly one of the two, never both; use when the user "
"doesn't have the order ID.")
@model_validator(mode="after")
def _exactly_one(self):
# Blank strings count as absent: {"order_id": ""} is schema-valid but
# semantically "no id" — without the strip() check it would pass
# validation and then crash the function's email branch on None.
has_id = bool(self.order_id and self.order_id.strip())
has_email = bool(self.customer_email and self.customer_email.strip())
if has_id == has_email:
raise ValueError("provide exactly one of order_id or customer_email")
return self
class OrdersSearchArgs(BaseModel):
model_config = ConfigDict(extra="forbid")
customer_email: str = Field(description="The customer's registered email address.")
status: OrderStatus | None = Field(default=None,
description="Optional filter: only orders in this status.")
limit: int = Field(default=5, ge=1, le=20,
description="Max orders to return (1-20). Default 5.")
cursor: str | None = Field(default=None,
description="Opaque cursor from a previous next_cursor. Omit for the first page.")
class TicketsCreateArgs(BaseModel):
model_config = ConfigDict(extra="forbid")
customer_email: str = Field(description="The customer's registered email address.")
subject: str = Field(min_length=4, max_length=120,
description="Short summary of the issue, e.g. 'Earbuds left channel silent'.")
body: str = Field(min_length=10, max_length=4000,
description="What the customer reported, in their words where possible.")
priority: TicketPriority = Field(default=TicketPriority.NORMAL,
description="low | normal | high | urgent. Use urgent only for safety issues or "
"customers threatening chargebacks; default normal.")
order_id: str | None = Field(default=None,
description="Related order ID like ORD-1042, if the ticket is about an order.")
class TicketsListArgs(BaseModel):
model_config = ConfigDict(extra="forbid")
customer_email: str = Field(description="The customer's registered email address.")
status: TicketStatus | None = Field(default=None,
description="Optional filter: open | pending | closed.")
limit: int = Field(default=5, ge=1, le=20)
cursor: str | None = Field(default=None)
class RefundsIssueArgs(BaseModel):
model_config = ConfigDict(extra="forbid")
order_id: str = Field(description="Order ID like ORD-1042. Must be delivered or shipped.")
amount_cents: int = Field(gt=0,
description="Refund amount in cents (2500 = $25.00). Cannot exceed the order's "
"remaining refundable amount, which orders_get reports.")
reason: str = Field(min_length=4, max_length=300,
description="Why the refund is being issued, e.g. 'damaged on arrival'.")
execute: bool = Field(default=False,
description="false (default) returns a dry-run preview of exactly what would happen. "
"Set true ONLY after the user has confirmed the refund in the conversation.")
class DocsSearchArgs(BaseModel):
model_config = ConfigDict(extra="forbid")
query: str = Field(min_length=3, max_length=300,
description="What to look up in the help docs, e.g. 'refund damaged item policy'.")
top_k: int = Field(default=3, ge=1, le=5,
description="Number of doc snippets to return (1-5). Default 3.")
# ---------------------------------------------------------------------------
# Result shaping helpers — every tool returns the same envelope so the model
# learns one result grammar: data + pagination/error hints, never raw dumps.
# ---------------------------------------------------------------------------
def _order_view(o: dict) -> dict:
"""The composed order view: everything support needs, nothing it doesn't."""
total = o["total_cents"]
refunded = sum(r["amount_cents"] for r in o.get("refunds", []))
return {
"order_id": o["order_id"],
"customer_email": o["customer_email"],
"status": o["status"],
"currency": o["currency"],
"items": o["items"],
"total": f'{total / 100:.2f} {o["currency"]}',
"total_cents": total,
"ordered_at": o["ordered_at"],
"delivered_at": o.get("delivered_at"),
"promised_delivery": o.get("promised_delivery"),
"tracking": o.get("tracking"),
"payment": o.get("payment"), # brand + last4 only — never a PAN
"refundable_cents": total - refunded if o["status"] in ("delivered", "shipped") else 0,
"refunds": o.get("refunds", []),
}
def _encode_cursor(offset: int) -> str:
return base64.urlsafe_b64encode(json.dumps({"o": offset}).encode()).decode()
def _decode_cursor(cursor: str) -> int:
try:
return int(json.loads(base64.urlsafe_b64decode(cursor.encode()))["o"])
except Exception:
raise ValueError("invalid cursor — omit it for the first page")
# ---------------------------------------------------------------------------
# Tool functions. Signatures take ONLY model-facing args; dependencies are
# closed over at build time.
# ---------------------------------------------------------------------------
def _make_orders_get():
def orders_get(order_id: str | None = None, customer_email: str | None = None) -> dict:
if order_id:
o = ORDERS.get(order_id.upper())
if not o:
known = ", ".join(sorted(ORDERS))
raise LookupError(
f"no order found with order_id '{order_id}'. IDs look like ORD-1042 "
f"(known: {known}). If the user doesn't have the ID, try "
f"orders_search with their email address.")
return {"order": _order_view(o)}
if not customer_email:
# defensive: dispatch()'s validator already rejects this, but a
# direct call must still fail with a model-readable message,
# not AttributeError on None.lower()
raise LookupError(
"provide exactly one of order_id or customer_email — "
"a blank string counts as absent.")
email = customer_email.lower()
matches = [o for o in ORDERS.values() if o["customer_email"] == email]
if not matches:
raise LookupError(
f"no orders found for '{email}'. Check the spelling, or ask the user for "
f"the email they used at checkout — it may differ from this one.")
if len(matches) == 1:
return {"order": _order_view(matches[0])}
return {"orders": [_order_view(o) for o in matches],
"note": "Multiple orders — show the user the list or ask which one."}
return orders_get
def _make_orders_search():
def orders_search(customer_email: str, status: str | None = None,
limit: int = 5, cursor: str | None = None) -> dict:
email = customer_email.lower()
if email not in CUSTOMERS:
raise LookupError(
f"no customer registered with '{email}'. Check the spelling — the address "
f"must match the account exactly.")
rows = [o for o in ORDERS.values() if o["customer_email"] == email]
if status:
rows = [o for o in rows if o["status"] == status]
rows.sort(key=lambda o: o["ordered_at"], reverse=True)
offset = _decode_cursor(cursor) if cursor else 0
page = rows[offset:offset + limit]
has_more = offset + limit < len(rows)
return {
"orders": [_order_view(o) for o in page],
"returned": len(page), "total_matching": len(rows), "has_more": has_more,
"next_cursor": _encode_cursor(offset + limit) if has_more else None,
"note": ("Newest first. Pass next_cursor as 'cursor' for the next page, or "
"narrow with 'status' (placed|shipped|delivered|cancelled|refunded)."
if has_more else "No more orders."),
}
return orders_search
def _make_tickets_create():
def tickets_create(customer_email: str, subject: str, body: str,
priority: str = "normal", order_id: str | None = None) -> dict:
email = customer_email.lower()
if email not in CUSTOMERS:
raise LookupError(f"no customer registered with '{email}'.")
if order_id and order_id.upper() not in ORDERS:
raise LookupError(
f"no order '{order_id}'. Create the ticket without order_id, or check the ID.")
# Natural idempotency: same customer + same subject + still OPEN returns
# the existing ticket instead of duplicating it — a retried call is
# harmless. A closed ticket must NOT block a legitimate new one about a
# recurring issue, so the scan filters on status == "open".
for tid, t in TICKETS.items():
if (t["customer_email"] == email and t["status"] == "open"
and t["subject"].lower() == subject.lower()):
return {"ticket_id": tid, "status": t["status"], "duplicate": True,
"note": "An identical open ticket already exists; not creating a second."}
tid = f"TCK-{len(TICKETS) + 1001}"
TICKETS[tid] = {
"ticket_id": tid, "customer_email": email, "subject": subject,
"body": body, "priority": priority, "order_id": order_id.upper() if order_id else None,
"status": "open", "created_at": datetime.now(timezone.utc).isoformat(),
}
return {"ticket_id": tid, "status": "open", "priority": priority,
"note": "Ticket created. Give the customer the ticket_id for reference."}
return tickets_create
def _make_tickets_list():
def tickets_list(customer_email: str, status: str | None = None,
limit: int = 5, cursor: str | None = None) -> dict:
email = customer_email.lower()
rows = [t for t in TICKETS.values() if t["customer_email"] == email]
if status:
rows = [t for t in rows if t["status"] == status]
rows.sort(key=lambda t: t["created_at"], reverse=True)
offset = _decode_cursor(cursor) if cursor else 0
page = rows[offset:offset + limit]
has_more = offset + limit < len(rows)
return {
"tickets": [{k: t[k] for k in ("ticket_id", "subject", "status", "priority",
"created_at", "order_id")} for t in page],
"returned": len(page), "has_more": has_more,
"next_cursor": _encode_cursor(offset + limit) if has_more else None,
}
return tickets_list
def _make_refunds_issue():
def refunds_issue(order_id: str, amount_cents: int, reason: str,
execute: bool = False) -> dict:
o = ORDERS.get(order_id.upper())
if not o:
raise LookupError(
f"no order found with order_id '{order_id}'. Check the ID — orders look "
f"like ORD-1042 — or find it with orders_get/orders_search first.")
# Eligibility mirrors _order_view: only delivered/shipped orders are
# refundable. A preview must never advertise an amount the real call
# would refuse — that is exactly what the dry-run exists to prevent.
eligible = o["status"] in ("delivered", "shipped")
refunded = sum(r["amount_cents"] for r in o["refunds"])
refundable = o["total_cents"] - refunded if eligible else 0
preview = {
"order_id": o["order_id"], "order_status": o["status"],
"eligible": eligible,
"refund": {"amount_cents": amount_cents,
"amount": f"{amount_cents / 100:.2f} {o['currency']}",
"to": f"{o['payment']['brand']} ••{o['payment']['last4']}"},
"reason": reason,
"remaining_refundable_cents": refundable,
}
if not eligible:
preview["note"] = (
f"Only delivered or shipped orders are refundable; this order is "
f"'{o['status']}'. A real call would be rejected — offer the returns "
f"policy (docs_search) or open a ticket (tickets_create) instead.")
if not execute:
return {"dry_run": True, "would_refund": preview,
"next_step": "Show the user this preview. Call again with "
"execute=true ONLY after they confirm — and only "
"when 'eligible' is true."}
if not eligible:
raise ValueError(
f"cannot refund order {o['order_id']}: status is '{o['status']}'. "
f"Only delivered or shipped orders are refundable.")
if amount_cents > refundable:
raise ValueError(
f"amount_cents {amount_cents} exceeds the remaining refundable "
f"{refundable} cents on {o['order_id']} (already refunded "
f"{o['total_cents'] - refundable} of {o['total_cents']}).")
rid = f"RF-{len(o['refunds']) + 1:03d}"
rec = {"id": rid, "amount_cents": amount_cents, "reason": reason,
"at": datetime.now(timezone.utc).isoformat()}
o["refunds"].append(rec)
# Idempotency is the dispatch() gate's job (key -> stored result), not
# the function's — the function just performs the mutation.
return {"refunded": True, "refund": {**preview["refund"], "id": rid, "at": rec["at"]},
"remaining_refundable_cents": refundable - amount_cents,
"note": "Refund issued to the original payment method; allow 5 business days."}
return refunds_issue
def _make_docs_search(retriever):
def docs_search(query: str, top_k: int = 3) -> dict:
hits = retriever.search(query, k=top_k)
if not hits:
return {"results": [],
"note": "No docs matched. Try different words, or create a ticket "
"if the question is account-specific."}
out = []
for h in hits:
words = h.text.split()
snippet = " ".join(words[:40]) + ("…" if len(words) > 40 else "")
out.append({"title": h.metadata.get("title", h.id), "source": h.id,
"snippet": snippet})
return {"results": out,
"note": "Snippets are excerpts — cite 'source' when telling the user."}
return docs_search
# ---------------------------------------------------------------------------
# Registry: metadata + the dispatch gate.
# ---------------------------------------------------------------------------
@dataclass(frozen=True)
class Tool:
"""One tool: its model-facing definition AND its safety metadata."""
name: str
description: str
args_model: type[BaseModel]
fn: Callable[..., Any]
risk: Risk = "read"
idempotent: bool = True
max_calls_per_minute: int | None = None
def _problems(exc: Exception) -> str:
"""Model-readable validation problems: `field: message`, no pydantic URLs, no input echo.
(3.4: an error is a prompt for the model, not a log line for you.)"""
if isinstance(exc, ValidationError):
return "; ".join(
(f"{'.'.join(map(str, e['loc']))}: " if e["loc"] else "")
+ e["msg"].removeprefix("Value error, ")
for e in exc.errors())
if isinstance(exc, json.JSONDecodeError):
return f"the arguments are not valid JSON ({exc.msg})"
return f"{type(exc).__name__}: {exc}"
class _RateLimiter:
"""Sliding-window calls/minute per tool name."""
def __init__(self):
self._hits: dict[str, deque] = {}
def allow(self, name: str, limit: int | None) -> bool:
if limit is None:
return True
now = time.monotonic()
q = self._hits.setdefault(name, deque())
while q and now - q[0] > 60:
q.popleft()
if len(q) >= limit:
return False
q.append(now)
return True
class _IdempotencyStore:
"""key -> completed result, TTL'd. The APP supplies keys (never the model)."""
def __init__(self, ttl_s: float = 24 * 3600):
self._done: dict[str, tuple[float, Any]] = {}
self._ttl = ttl_s
def seen(self, key: str) -> Any | None:
if key in self._done and time.monotonic() - self._done[key][0] < self._ttl:
return self._done[key][1]
return None
def mark_done(self, key: str, result: Any = "ok") -> None:
self._done[key] = (time.monotonic(), result)
class ToolRegistry:
"""The single gate every tool call passes through."""
def __init__(self, tools: list[Tool]):
self._tools = {t.name: t for t in tools}
self._limiter = _RateLimiter()
self.idempotency = _IdempotencyStore()
# -- model-facing view -------------------------------------------------
def specs(self) -> list[dict]:
"""Provider-neutral definitions; 03.5 maps these to each wire format."""
return [{"name": t.name, "description": t.description,
"parameters": t.args_model.model_json_schema()} for t in self._tools.values()]
# -- execution -----------------------------------------------------------
def dispatch(self, name: str, args: dict | str,
*, idempotency_key: str | None = None) -> tuple[Any, bool]:
"""Returns (result_or_error_message, is_error). Never raises for bad calls."""
tool = self._tools.get(name)
if tool is None:
return (f"Error: unknown tool '{name}'. Available tools: "
f"{sorted(self._tools)}. Check the name and try again.", True)
if not self._limiter.allow(name, tool.max_calls_per_minute):
return (f"Error: {name} rate limit reached "
f"({tool.max_calls_per_minute}/min). Wait and retry, or tell the "
f"user this action is temporarily unavailable.", True)
try:
raw = json.loads(args) if isinstance(args, str) else args
parsed = tool.args_model.model_validate(raw)
except Exception as e:
return (f"Error: invalid arguments for {name}: {_problems(e)}. "
f"Fix them and call again.", True)
# Idempotency keys gate MUTATING calls only. A non-idempotent tool's
# dry-run preview (execute=false) changes no state, so it needs no key
# and must neither replay a stored result nor be stored itself — a
# preview is not an operation, and a same-key execute=true retry after
# a preview must still run for real.
will_mutate = not tool.idempotent and bool(getattr(parsed, "execute", True))
if will_mutate:
if not idempotency_key:
return (f"Error: {name} is not idempotent and requires an "
f"idempotency_key from the application before it can run.", True)
prior = self.idempotency.seen(idempotency_key)
if prior is not None:
return ({"duplicate": True, "prior_result": prior,
"note": "This exact call already completed; returning the "
"stored result instead of repeating it."}, False)
try:
result = tool.fn(**parsed.model_dump())
except Exception as e:
# Errors are messages FOR THE MODEL: what failed + what to try. No tracebacks.
return (f"Error: {name} failed: {type(e).__name__}: {e}", True)
if will_mutate and idempotency_key:
self.idempotency.mark_done(idempotency_key, result)
return (result, False)
def build_registry() -> ToolRegistry:
"""The support assistant's tool set, with descriptions written per Part 1."""
return ToolRegistry([
Tool(
name="orders_get",
description="Fetches ONE order by order_id (format ORD-NNNN, from the "
"customer's confirmation email) or by customer_email — provide "
"exactly one, never both. Returns status, items, totals, payment "
"brand/last4, timestamps and refundable_cents. Use for questions "
"about a specific order: where it is, what was bought, refund "
"eligibility. Do NOT use to list or browse orders — use "
"orders_search. Errors say what was tried and what to try next.",
args_model=OrdersGetArgs, fn=_make_orders_get(), risk="read",
max_calls_per_minute=60),
Tool(
name="orders_search",
description="Lists a customer's orders, newest first, with cursor "
"pagination. Requires the customer's registered email; optional "
"'status' filter (placed|shipped|delivered|cancelled|refunded) "
"and 'limit' (1-20, default 5). Returns orders plus "
"has_more/next_cursor — pass next_cursor back as 'cursor' for "
"the next page, or narrow with 'status' instead of paging "
"through everything. Use when the user asks about their orders "
"generally or doesn't know the order ID.",
args_model=OrdersSearchArgs, fn=_make_orders_search(), risk="read",
max_calls_per_minute=60),
Tool(
name="tickets_create",
description="Opens a support ticket for a customer: subject (short summary), "
"body (the issue in the customer's words), priority "
"(low|normal|high|urgent — urgent only for safety issues or "
"chargeback threats), optional order_id if it's about an order. "
"Returns a TCK-NNNN ticket_id to quote to the customer. "
"Identical tickets (same customer + subject) are not duplicated. "
"Use after confirming the issue with the user; do NOT create a "
"ticket for questions docs_search can answer.",
args_model=TicketsCreateArgs, fn=_make_tickets_create(), risk="write",
max_calls_per_minute=20),
Tool(
name="tickets_list",
description="Lists a customer's support tickets, newest first, paginated "
"like orders_search (cursor + limit, optional status filter: "
"open|pending|closed). Use to check whether an issue is already "
"ticketed before creating a duplicate, or to give the customer "
"a status update on an existing ticket.",
args_model=TicketsListArgs, fn=_make_tickets_list(), risk="read",
max_calls_per_minute=60),
Tool(
name="refunds_issue",
description="Issues a refund on a delivered or shipped order — this MOVES "
"REAL MONEY back to the customer's card. Parameters: order_id, "
"amount_cents (in cents: 2500 = $25.00; cannot exceed "
"refundable_cents from orders_get), reason, and execute. "
"execute=false (default) returns a dry-run preview — ALWAYS "
"preview first, show the user what will happen, and only call "
"with execute=true after they explicitly confirm. Do NOT use "
"for order cancellation (that's a different flow) or for "
"partial-policy questions (use docs_search first).",
args_model=RefundsIssueArgs, fn=_make_refunds_issue(), risk="destructive",
idempotent=False, max_calls_per_minute=5),
Tool(
name="docs_search",
description="Searches the company help docs and policies (returns, refunds, "
"shipping, warranty, product FAQs). Returns up to top_k (1-5, "
"default 3) snippets with their doc 'source' id — cite the "
"source when answering. Use FIRST for any policy or how-to "
"question before answering from memory; docs are the source of "
"truth and may be newer than your knowledge. Do NOT use for "
"account-specific data (orders, tickets) — use those tools.",
args_model=DocsSearchArgs,
fn=_make_docs_search(KeywordRetriever(DOCS)), risk="read",
max_calls_per_minute=60),
])6.4 test_support_tools.py — unit tests and schema snapshots#
# test_support_tools.py — run with: uv run pytest test_support_tools.py -v
import pytest
from support_data import ORDERS
from support_tools import (DocsSearchArgs, OrdersGetArgs, OrdersSearchArgs,
RefundsIssueArgs, TicketsCreateArgs, TicketsListArgs,
build_registry)
@pytest.fixture
def reg():
return build_registry()
# --- schema snapshot: the wire contract is part of the API -------------------
def test_orders_get_schema_snapshot():
schema = OrdersGetArgs.model_json_schema()
props = schema["properties"]
assert set(props) == {"order_id", "customer_email"}
# Both fields optional in the schema; exactly-one is enforced by the
# model_validator — and EACH field description tells the model so, because
# no provider's strict-schema subset can express "exactly one of" (the
# class docstring only reaches the schema's top-level description, which
# providers render inconsistently — the per-field prose is what the model
# reliably reads).
assert "exactly one" in OrdersGetArgs.model_fields["order_id"].description
assert "exactly one" in OrdersGetArgs.model_fields["customer_email"].description
def test_all_schemas_forbid_extra_args():
# extra="forbid" -> "additionalProperties": false on every object — the
# strict-mode subset providers require, and the guarantee that an invented
# argument is a validation error rather than a silently dropped field.
for model in (OrdersGetArgs, OrdersSearchArgs, TicketsCreateArgs,
TicketsListArgs, RefundsIssueArgs, DocsSearchArgs):
assert model.model_json_schema().get("additionalProperties") is False
def test_extra_arg_is_rejected_not_dropped(reg):
out, err = reg.dispatch("orders_get",
{"order_id": "ORD-1042", "admin": True})
assert err and "invalid arguments" in out
def test_refunds_schema_has_execute_default_false():
schema = RefundsIssueArgs.model_json_schema()
assert schema["properties"]["execute"]["default"] is False
assert schema["properties"]["amount_cents"]["exclusiveMinimum"] == 0
# --- happy paths ------------------------------------------------------------
def test_orders_get_by_id(reg):
out, err = reg.dispatch("orders_get", {"order_id": "ord-1042"})
assert not err and out["order"]["order_id"] == "ORD-1042"
assert out["order"]["payment"] == {"brand": "visa", "last4": "4242"} # no PAN
assert out["order"]["refundable_cents"] == 6499
def test_orders_get_requires_exactly_one(reg):
out, err = reg.dispatch("orders_get", {})
assert err and "exactly one" in out
out, err = reg.dispatch("orders_get", {"order_id": "ORD-1042",
"customer_email": "a@b.c"})
assert err
# blank strings are schema-valid but semantically absent — a clean
# validation error, never an AttributeError from the email branch
out, err = reg.dispatch("orders_get", {"order_id": ""})
assert err and "exactly one" in out
out, err = reg.dispatch("orders_get", {"order_id": " "})
assert err and "exactly one" in out
def test_orders_search_paginates(reg):
# seed extra orders for ana so pagination is visible
for i in range(6):
ORDERS[f"ORD-20{i}"] = {**ORDERS["ORD-1042"], "order_id": f"ORD-20{i}",
"ordered_at": f"2026-10-0{i+1}T00:00:00Z"}
out, err = reg.dispatch("orders_search",
{"customer_email": "ana@example.com", "limit": 3})
assert not err and out["returned"] == 3 and out["has_more"]
out2, _ = reg.dispatch("orders_search",
{"customer_email": "ana@example.com", "limit": 3,
"cursor": out["next_cursor"]})
assert out2["orders"][0]["order_id"] != out["orders"][0]["order_id"]
def test_tickets_create_dedupes(reg):
a, ea = reg.dispatch("tickets_create", {
"customer_email": "ana@example.com", "subject": "Earbud left channel silent",
"body": "Left earbud has no sound since Tuesday."})
b, eb = reg.dispatch("tickets_create", {
"customer_email": "ana@example.com", "subject": "Earbud left channel silent",
"body": "Left earbud has no sound since Tuesday."})
assert not ea and not eb
assert a["ticket_id"] == b["ticket_id"] and b["duplicate"] is True
def test_refund_dry_run_then_execute(reg):
out, err = reg.dispatch("refunds_issue", {
"order_id": "ORD-1042", "amount_cents": 2500, "reason": "damaged item"})
assert not err and out["dry_run"] is True # execute defaults False
# execute=true without an idempotency key is refused by the gate
out, err = reg.dispatch("refunds_issue", {
"order_id": "ORD-1042", "amount_cents": 2500, "reason": "damaged item",
"execute": True})
assert err and "idempotency_key" in out
# with a key it runs once; the same key replays the stored result
out, err = reg.dispatch("refunds_issue", {
"order_id": "ORD-1042", "amount_cents": 2500, "reason": "damaged item",
"execute": True}, idempotency_key="conv-1:call-9")
assert not err and out["refunded"] is True
out2, _ = reg.dispatch("refunds_issue", {
"order_id": "ORD-1042", "amount_cents": 99999, "reason": "retry",
"execute": True}, idempotency_key="conv-1:call-9")
assert out2["duplicate"] is True # key wins over new args
# over-refund is now correctly rejected (3999 left after the 2500 refund)
out, err = reg.dispatch("refunds_issue", {
"order_id": "ORD-1042", "amount_cents": 99999, "reason": "too much",
"execute": True}, idempotency_key="conv-1:call-10")
assert err and "exceeds" in out
def test_preview_never_touches_idempotency(reg):
# A dry-run is not an operation: it needs no key, and a key supplied WITH a
# preview must neither replay a stored result nor be consumed by it — the
# same key on the real call must still execute.
out, err = reg.dispatch("refunds_issue", {
"order_id": "ORD-1043", "amount_cents": 1000, "reason": "preview",
"execute": False}, idempotency_key="conv-2:call-1")
assert not err and out["dry_run"] is True
out, err = reg.dispatch("refunds_issue", {
"order_id": "ORD-1043", "amount_cents": 1000, "reason": "real",
"execute": True}, idempotency_key="conv-2:call-1")
assert not err and out["refunded"] is True
def test_refund_preview_flags_ineligible_order(reg):
# ORD-1044 is 'cancelled' — the dry-run must not advertise a refundable
# amount the real call would refuse.
out, err = reg.dispatch("refunds_issue", {
"order_id": "ORD-1044", "amount_cents": 500, "reason": "changed mind"})
assert not err and out["dry_run"] is True
assert out["would_refund"]["eligible"] is False
assert "delivered or shipped" in out["would_refund"]["note"]
assert out["would_refund"]["remaining_refundable_cents"] == 0
def test_docs_search(reg):
out, err = reg.dispatch("docs_search", {"query": "refund damaged item policy"})
assert not err and out["results"]
assert out["results"][0]["source"] == "handbook-returns"
assert "snippet" in out["results"][0]
def test_unknown_tool_and_bad_args(reg):
out, err = reg.dispatch("delete_all_orders", {})
assert err and "unknown tool" in out
out, err = reg.dispatch("orders_get", "{not json")
assert err and "invalid arguments" in out
def test_rate_limit(reg):
reg3 = build_registry()
t = reg3._tools["orders_get"]
reg3._tools["orders_get"] = t.__class__(**{**t.__dict__, "max_calls_per_minute": 2})
for _ in range(2):
reg3.dispatch("orders_get", {"order_id": "ORD-1042"})
out, err = reg3.dispatch("orders_get", {"order_id": "ORD-1042"})
assert err and "rate limit" in outTwo honest notes on the tests: test_orders_search_paginates mutates the shared ORDERS dict (fine for a demo; in a real suite use a fixture that deep-copies), and test_rate_limit reaches into _tools — acceptable in tests, ugly in production; a with_overrides() constructor would be cleaner. The schema snapshot idea generalises: model_json_schema() output is your wire contract, so a golden-file test catches accidental description/schema drift — the same instinct as 03.10's recorded-response tests, applied to tool definitions.
Run them: uv run pytest test_support_tools.py -v. All pure local — no keys, no network, no model.
Part 7: Producing tool definitions at scale#
Deep-dive
7.1 From type hints and docstrings#
Every provider SDK can generate a schema from your code rather than hand-written JSON:
- Anthropic: the
@beta_tooldecorator builds the schema from type hints + docstring (03.5, 15.2);input_examplescan be added on top. - OpenAI:
pydantic_function_tool()converts a Pydantic model/function to a Responses tool (03.5, 15.1). - Gemini: pass a plain Python callable and
automatic_function_callingruns it inside the SDK (03.5, 15.3).
The design consequence: your docstrings become your descriptions. A generated tool inherits whatever the docstring says — so the 1.4 rules apply to docstrings with doubled force, and generated schemas need the same review a hand-written one would. Generation saves typing, not judgement.
7.2 From OpenAPI specs — and why auto-generation disappoints#
The tempting move: point a generator at your company's OpenAPI spec (OAS v3.2.1 is the current spec, September 2026) and emit one tool per operation. Mechanically it works — operationId → name, parameters/requestBody → JSON Schema, description passthrough — and it fails in predictable ways:
- No when-not-to-use. API descriptions say what an endpoint does; they never say which of 40 endpoints the model should pick for "my order is late". Selection ambiguity is the dominant failure (1.8).
- Raw parameter names and shapes.
customer_idvsuser_idvsaccount_uuidacross services; deeply nested request bodies the model must fill perfectly; file-upload and webhook operations that make no sense as tools. - Surface explosion. A 200-endpoint spec becomes 200 tools — far past every provider's guidance, guaranteed accuracy decay (LongFuncEval) and a token bill on every request.
- No result shaping. The tool returns the API's raw response — the exact anti-pattern of 2.5.
The right workflow is generate → curate: use the spec to draft candidate tools, then delete, merge and rewrite until the set matches your eval tasks (Anthropic's post: "a few thoughtful tools targeting specific high-impact workflows… scaling up from there"). Auto-generation is a first draft, not a design.
7.3 Wrapping existing services vs writing native tools#
When a capability already exists (an internal service, a SaaS API, a CLI), wrap it rather than reimplement — but the wrapper is where the design lives: your code owns auth, argument mapping, pagination, retries, result shaping and risk classification; the model sees only the clean tool. The anti-pattern is the transparent proxy — exposing the service's whole API surface as tools (same failure as 7.2). A wrapper that hides complexity is a feature; one that merely renames endpoints is technical debt with extra steps.
7.4 Versioning tool schemas#
Tool schemas are API contracts with an unusual property: the caller is a model that learned your old version. Breaking changes (renamed parameters, removed fields, changed enums, altered result shapes) degrade behaviour silently — the model keeps emitting the old shape and your validation rejects it, or worse, accepts it wrongly.
- Additive changes are safe: new optional parameters, new enum values the model may now legitimately emit (describe them), new result fields (models ignore what they don't need). Still snapshot-test them.
- Breaking changes need a version story: rename the tool (
orders_get_v2) during a transition window, or version in the description, and keep the old schema alive until transcripts show the model has migrated. Anthropic's own provider tools version by date suffix in thetypefield (web_search_20250305is the documented example of the pattern, verified on the tool-reference) — the same instinct applied to built-ins. - Never edit a description's meaning without re-evaluating. A "small" wording change is a prompt change; 8.3 is how you check it didn't regress.
- Schema snapshot tests (6.4) are your tripwire: any schema diff shows up in review, not in production transcripts.
Part 8: Measuring and improving tools#
Deep-dive
Tools are prompts, and prompts are tested — but tool testing has a second dimension: the code must also be correct. The pyramid has four levels.
8.1 The test pyramid for tools#
| Level | What it checks | How | Cost |
|---|---|---|---|
| Unit | The function's logic: validation, edge cases, error paths | pytest, pure local | Cheap; run always |
| Contract | The schema the model sees is what you intend | model_json_schema() snapshot + provider subset lint (03.4, 4.6) |
Cheap; run always |
| Integration | dispatch gate: allow-list, rate limits, idempotency, error results | pytest against ToolRegistry (6.4) |
Cheap; run always |
| Behavioural | Does the model call the right tool with the right args? | tool-use evals (8.2) | Expensive; run on changes |
The first three levels catch code bugs deterministically. Only the fourth catches design bugs — and only it can tell you whether a description rewrite helped.
8.2 Tool-use evals: the harness#
A tool-use eval asks: given task prompts, does the model (a) choose the right tool, (b) fill arguments correctly, (c) recover from tool errors, (d) avoid forbidden calls? Anthropic's "Writing effective tools" is the canonical methodology: generate realistic tasks (theirs: multi-tool-call scenarios like "schedule a meeting with Jane, attach last week's notes, book a room" — not "call get_weather"), run an agentic loop per task, grade the trajectory and the outcome, and analyse transcripts for clusters of confusion. Their "Demystifying evals for AI agents" (January 2026) supplies the vocabulary — task, trial, grader, transcript, outcome, harness — that Module 10A owns in depth.
tool_eval.py is a minimal harness: tasks specify the prompt, the expected tool sequence and argument constraints; a grader checks the trajectory; the same file runs against a live CallModel or a scripted fake so the harness itself is testable without keys.
# tool_eval.py — a minimal tool-use eval harness.
# CallModel/QueuedModel are THIS FILE's local seam — deliberately not 08A.2's
# ChatAdapter/ScriptedModel (an async call(history) -> ModelTurn inside
# run_agent). Bridging the two needs an adapter mapping ModelTurn <-> ModelReply
# plus a Tool -> ToolSpec shim; the lesson text sketches it. To eval a live
# model, wrap your provider's call_model (03.5 / 08A.2) in a CallModel.
from __future__ import annotations
import json
from dataclasses import dataclass, field
from typing import Any, Callable
from support_tools import ToolRegistry, build_registry
@dataclass
class ToolCall:
name: str
args: dict
@dataclass
class ModelReply:
"""What one model turn produces: text, tool calls, or both."""
text: str = ""
tool_calls: list[ToolCall] = field(default_factory=list)
# An injectable model seam for THIS file: (messages, tool_specs) -> ModelReply.
# 08A.2's canonical loop uses a different seam — an async ChatAdapter whose
# call(history) returns a ModelTurn — so QueuedModel does NOT plug into
# run_agent directly. See the bridging sketch in the lesson text (8.2).
CallModel = Callable[[list[dict], list[dict]], ModelReply]
class QueuedModel:
"""Replays canned replies — this file's deterministic stand-in for a model.
(08A.2's ScriptedModel is the equivalent fake for run_agent; the two seams
differ — see the CallModel comment above.)"""
def __init__(self, replies: list[ModelReply]):
self._replies = list(replies)
self.calls: list[dict] = []
def __call__(self, messages: list[dict], specs: list[dict]) -> ModelReply:
self.calls.append({"messages": messages, "specs": specs})
return self._replies.pop(0) if self._replies else ModelReply(text="done")
@dataclass
class EvalTask:
prompt: str
expect_tools: list[str] = field(default_factory=list) # tools that MUST be called
forbid_tools: list[str] = field(default_factory=list) # tools that MUST NOT be called
arg_checks: dict[str, Callable[[dict], bool]] = field(default_factory=dict)
max_steps: int = 6
@dataclass
class Trial:
task: EvalTask
trajectory: list[dict] = field(default_factory=list) # every call + result
final_text: str = ""
steps: int = 0
def run_trial(task: EvalTask, model: CallModel, registry: ToolRegistry,
*, run_id: str = "eval") -> Trial:
"""One agentic loop, bounded. Deliberately minimal — call → dispatch →
repeat; 08A.2's run_agent is the production version of this shape."""
trial = Trial(task=task)
messages = [{"role": "user", "content": task.prompt}]
specs = registry.specs()
for _ in range(task.max_steps):
reply = model(messages, specs)
trial.steps += 1
if reply.text and not reply.tool_calls:
trial.final_text = reply.text
break
results = []
for call in reply.tool_calls:
trial.trajectory.append({"tool": call.name, "args": call.args})
# The app mints the key — 4.3's (run_id, tool, canonical args)
# scheme: two identical refunds on different runs are different
# operations, while a retried or re-issued identical call in
# THIS run replays the stored result instead of double-charging.
# Identical repeats inside one run collapse to one operation —
# that collapse is the point of idempotency.
key = (f"{run_id}:{call.name}:"
f"{json.dumps(call.args, sort_keys=True, default=str)}")
out, is_err = registry.dispatch(call.name, call.args,
idempotency_key=key)
results.append({"tool_call_id": f"c{len(trial.trajectory)}",
"name": call.name, "output": out, "is_error": is_err})
messages.append({"role": "assistant", "tool_calls": reply.tool_calls})
messages.append({"role": "tool", "results": results})
if not reply.tool_calls:
break
return trial
def grade(task: EvalTask, trial: Trial) -> dict:
"""Trajectory grading: right tools, forbidden tools, argument predicates."""
called = [c["tool"] for c in trial.trajectory]
missing = [t for t in task.expect_tools if t not in called]
forbidden = [t for t in task.forbid_tools if t in called]
arg_fails = []
for t in trial.trajectory:
check = task.arg_checks.get(t["tool"])
if check and not check(t["args"]):
arg_fails.append(t["tool"])
return {"pass": not missing and not forbidden and not arg_fails,
"missing_tools": missing, "forbidden_tools": forbidden,
"arg_failures": arg_fails, "steps": trial.steps,
"tools_called": called}
def run_eval(tasks: list[EvalTask], model: CallModel,
registry: ToolRegistry | None = None) -> dict:
registry = registry or build_registry()
trials = [run_trial(t, model, registry, run_id=f"eval-{i}")
for i, t in enumerate(tasks)]
grades = [grade(t, tr) for t, tr in zip(tasks, trials)]
passed = sum(g["pass"] for g in grades)
return {"tasks": len(tasks), "passed": passed,
"accuracy": passed / len(tasks) if tasks else 0.0,
"trials": [(t.prompt, tr.trajectory, g) for t, tr, g in zip(tasks, trials, grades)]}
# --- demo: the harness runs with no model and no keys -------------------------
if __name__ == "__main__":
# A scripted "model" that does the right thing for two tasks and skips the
# preview step on the third — so the grader has something to catch.
model = QueuedModel([
ModelReply(tool_calls=[ToolCall("docs_search", {"query": "refund damaged policy"})]),
ModelReply(text="Yes — damaged items are refundable within the policy."),
ModelReply(tool_calls=[ToolCall("orders_get", {"customer_email": "ana@example.com"})]),
ModelReply(text="Ana's most recent order is ORD-1042, delivered."),
ModelReply(tool_calls=[ToolCall("refunds_issue", {
"order_id": "ORD-1042", "amount_cents": 2500,
"reason": "damaged", "execute": True})]),
ModelReply(text="Refund issued."),
])
tasks = [
EvalTask(prompt="Can I return earbuds bought last week if damaged?",
expect_tools=["docs_search"]),
EvalTask(prompt="Where is Ana's order?",
expect_tools=["orders_get"], forbid_tools=["refunds_issue"]),
EvalTask(prompt="Refund $25 on ORD-1042 for a damaged item.",
expect_tools=["orders_get", "refunds_issue"],
forbid_tools=["tickets_create"]),
]
report = run_eval(tasks, model)
print(json.dumps({k: v for k, v in report.items() if k != "trials"}, indent=2))
for prompt, traj, g in report["trials"]:
print(f"\n{prompt}\n tools: {[c['tool'] for c in traj]} -> pass={g['pass']}"){
"tasks": 3,
"passed": 2,
"accuracy": 0.6666666666666666
}
Can I return earbuds bought last week if damaged?
tools: ['docs_search'] -> pass=True
Where is Ana's order?
tools: ['orders_get'] -> pass=True
Refund $25 on ORD-1042 for a damaged item.
tools: ['refunds_issue'] -> pass=False8.3 A/B testing descriptions and mining transcripts#
Description A/B testing follows the prompt-testing discipline of 04.9, scoped to one variable: change one thing in one tool's description (add the when-not-to-use sentence, fix a unit, add an example), rerun the same eval tasks, compare accuracy and the transcript-level metrics (wrong-tool rate, arg-error rate, steps per task, tokens per task). Anthropic's post reports "even small refinements to tool descriptions can yield dramatic improvements" — and their SWE-bench result came from "precise refinements to tool descriptions". Treat description changes like code changes: small, measured, reversible.
Transcript mining is the cheap version when you don't have an eval suite yet: log every real tool call (name, args, result summary, latency — 03.10 covers logging), then cluster the failures. Anthropic's post workflow: collect transcripts → have an agent (or yourself) find where calls went wrong → the patterns name the design fix. The recurring clusters and their fixes:
| Cluster in transcripts | Likely design flaw |
|---|---|
| Model calls tool A when B was meant | Names/descriptions overlap — sharpen the when-not-to-use lines, or rename |
| Model invents plausible-but-wrong IDs/emails | Result didn't echo the needed identifier, or description lacks a format example |
| Model retries the same failing call | Error message isn't actionable — it doesn't say what to try next (3.4) |
| Model chains 4+ calls for one intent | Missing composite tool (2.3) |
| Model stuffs instructions into a free-text param | Param is a free-form blob — constrain it (1.6) |
| Model calls the tool when it shouldn't | Description lacks the "do NOT use when…" clause, or the answer was in context already |
8.4 Common model mistakes and what they tell you#
| Mistake | What it looks like | Design response |
|---|---|---|
| Wrong tool | orders_get called for a "list my orders" question |
Sharpen when-not-to-use in both descriptions; check names aren't confusable |
| Missing args | Call arrives without required field (non-strict fallback) | Strict schema; clearer field descriptions; input_examples |
| Hallucinated args | order_id: "ORD-9999", invented email |
Result must echo real IDs; error messages that teach the correct format; consider binding known values in code instead of asking the model (1.6) |
| Repeated identical calls | Same tool+args 3× in a row | Loop detection is 08A.2's job; your part: error results that offer a different path, and rate limits that bound the damage |
| Over-calling | Tool called for something answerable from context | Description: "use only when…"; check the system prompt isn't forcing tool use (tool_choice is 03.5's subject) |
| Under-calling | Model answers from memory when fresh data existed | Description: "always check X first"; freshness caveats in the result |
| Ignored error results | Model repeats the failed call verbatim | Error text must name the fix ("use the status filter", "the ID format is ORD-NNNN") |
| Unsafe escalation | execute=true without user confirmation |
That's a policy failure, not a model failure — 4.5, 08A.14 |
8.5 The consolidated decision table#
| Design question | Default answer | Escalate when |
|---|---|---|
| Expose as a tool at all? | Only when the model must decide to invoke it — else answer from context, emit structured output, or keep it in workflow code (2.1) | The capability is a fixed procedure or needs no model decision → don't pay tool-count and token costs for it |
| How many tools? | Fewest that cover your eval tasks; <20 initial, aim lower | >20 needed → grouping, per-step restriction, tool search (1.8) |
| Merge or split? | Merge same-resource/same-risk ops; split across risk classes | Params become action-conditional spaghetti → split (2.6) |
| Primitive or composite? | Composite for known high-frequency workflows; primitives for novel tasks | Composite can't express an edge case → add escape params or a sibling primitive |
| How much in the result? | Minimum the next decision needs; paginated, cursor-based | Model needs raw detail sometimes → response_format concise/detailed (3.1) |
| Error style? | Actionable, model-readable, no internals | Same error repeats → the tool or schema is wrong, not the model |
| Free-text params? | Last resort; typed/enum/bounded first | Genuinely open input → validate hard, treat as untrusted (4.6) |
| Risk class? | read unless state changes; destructive for money/deletion/external messages |
Unsure → destructive; over-classifying costs an approval, under-classifying costs an incident |
| Idempotency? | Natural dedupe > app-supplied key > none | Non-idempotent writes must have a key or an approval gate |
| Generate from spec/code? | Generate a draft, then curate against eval tasks | Never ship unreviewed auto-generated surfaces (7.2) |
8.6 The failure gallery#
| Failure | Symptom in production | Root cause (usually) | Fix |
|---|---|---|---|
| Tool-description drift | Accuracy decays after a "harmless" doc edit | Description is a prompt; the edit changed behaviour | Snapshot tests + eval regression on any description change |
| Schema/result mismatch | Model echoes fields you renamed | Result shape changed without description update | Version the contract; snapshot-test both directions |
| Context flood | Answers degrade on long sessions; costs spike | Tools return raw API dumps | Result shaping, pagination, truncation markers (Part 3) |
| The infinite retry | Same failing call 10×, bill shock | Non-actionable error + no loop detection | Error text with next step; budgets in 08A.2 |
| Duplicate side effects | Two refunds, two emails | Non-idempotent tool + retried call | Idempotency keys / natural dedupe (4.3) |
| Confused deputy | Agent reads/acts on another user's data | Tool didn't scope to the requesting user | Bind identity in code, never from model args (4.2) |
| Injection via tool output | Agent takes instructions from a fetched page | Untrusted content treated as instructions | Label as data; policy layer re-checks permissions (4.8, Module 12) |
| Auto-generated surface | 80 tools, 30% accuracy, huge token bill | Spec→tools with no curation | Generate→curate→eval (7.2) |
| Hallucinated world | Model calls tools for entities that don't exist | No existence check / unhelpful not-found error | Validate against the world; errors that teach correct formats (4.6, 3.4) |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "A tool is just a function with a JSON schema." | It's a prompt (name + description + schema) on one side and a contract (validation, safety, results) on the other. The description is the highest-leverage text in the system (1.1, 1.4). |
| "Strict mode means the arguments are correct." | Strict guarantees shape; semantics (does the order exist? is the amount valid?) are your code's job (1.7, 4.6). |
| "More tools = more capable agent." | Accuracy drops with tool count — measured 7–85% in LongFuncEval; providers advise <20 initial tools, Google 10–20 max (1.8). |
| "Wrap the API endpoint and ship it." | Auto-generated tools lack when-not-to-use guidance, result shaping and consolidation — they reliably underperform curated sets (7.2). |
| "The model will figure out the parameters from the types." | Types constrain shape, not meaning. Units, formats, enums and examples live in descriptions — the model never sees your code (1.6). |
"A confirmed: true parameter makes a dangerous tool safe." |
It proves intent, not authorisation. The model can set it itself; real enforcement is app-side policy + human approval (4.5). |
| "Tool errors should be terse like log lines." | They're prompts to the model — write what failed and what to try next, no tracebacks (3.4). |
| "Returning more data is always safer." | Every token a tool returns is context the model can't use for reasoning; raw dumps measurably degrade retrieval and explode cost (3.1). |
| "If the unit tests pass, the tool is good." | Unit tests cover code; only tool-use evals cover whether the model calls it correctly (8.1, 8.2). |
| "Changing a description is a docs edit." | It's a prompt change — re-evaluate before shipping (8.3). |
| "The model can be trusted with the user's full permissions." | Tools must act as the user, with per-tool least privilege — a confused deputy leaks across tenants (4.2). |
Key takeaways#
- A tool has two contracts: the model-facing one (name, description, schema — all prompt text) and the code-facing one (validation, safety, result shaping). Design both; neither substitutes for the other.
- Descriptions are the highest-leverage prompt you write: what/when/when-not/what-it-returns/caveats, in 3–4+ sentences, written like a briefing for a new hire. Side effects and limitations belong in them.
- Parameters: few, typed, enumerated, bounded, unit-described. Enums prevent invalid states; free-form blobs invite injection; never ask the model for values your code already knows.
- Strict schemas guarantee shape, not semantics — and each provider supports a different subset (03.4, Part 4). Write to the intersection and validate anyway.
- Fewer tools is more accurate: measured double-digit drops as catalogues grow; consolidate same-resource operations, restrict per-step sets, and use tool search only past ~20 tools.
- Match granularity to the workflow: composite "do what I mean" tools for known high-frequency paths, primitives for novel tasks — always with an escape hatch.
- Results are context budget: high-signal fields, semantic IDs the model can echo, opaque cursors, explicit truncation, actionable errors, labelled units — and never secrets or other tenants' data.
- Safety is designed in, not bolted on: risk classes, act-as-user credentials, idempotency keys generated by the app, dry-run defaults on destructive tools, approval gates that the model can't self-authorise, injection-proof argument handling.
- Every tool gets its own timeout, and a timeout stops waiting, not working: choose it from the tool's p99, cancel cooperatively where you can, tell the model whether the work may still complete, and let the same idempotency key make the retry safe (4.9).
- Tool types share patterns: search don't list, read-only SQL via allow-lists, adapters for APIs, sandboxed files, untrusted-content browsing, draft-first messaging, ask-the-user and scratchpad tools for control.
- Measure what you ship: unit + schema-snapshot + dispatch tests deterministically; tool-use evals measure the model; description changes are prompt changes — A/B them.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Tool description | The plain-text prompt inside a tool definition telling the model what the tool does, when to use it and when not to |
input_examples |
Anthropic's optional array of schema-valid example inputs on a tool definition |
| Namespacing | Grouping tool names under a shared prefix (orders_, tickets_) to keep selection unambiguous at scale |
| Risk class | A per-tool label — read, write or destructive — that drives validation, approval and audit behaviour |
| Composite tool | A single tool that performs a whole multi-step workflow behind intent-level parameters |
| Consolidation | Merging several small tools on one resource into fewer, more capable tools (often via an action parameter) |
| Opaque cursor | An encoded pagination token the model passes back verbatim without parsing it |
| Truncation marker | An explicit "truncated": true (or equivalent) field telling the model a result was cut and how to get more |
| Idempotency key | A client-generated unique key that makes a retried operation return the stored result instead of repeating it |
| Natural idempotency | Designing a tool so retries are harmless by construction (e.g. dedupe on customer+subject) |
| Tool timeout | A per-tool limit on how long the loop waits for a result; it stops the waiting, not necessarily the work |
| Cooperative cancellation | A tool checking a cancel signal between small slices of work so it can stop when asked |
| Dry-run (preview) | A tool mode that validates and previews an action without performing it (execute=false); distinct from 06.2's cost-estimation "dry-run mode" |
| Confused deputy | A vulnerability where a tool acts with more authority than the requesting user is entitled to |
| Tool-use eval | A behavioural test measuring whether a model picks the right tool with the right arguments on realistic tasks |
| Schema snapshot test | A golden-file test over model_json_schema() output that catches accidental contract drift |
| Actionable error | A tool error message written for the model: what failed plus what to try next |
| Scratchpad tool | A tool that gives the model a place to write working notes/plans during a run |
All terms are also collected in the glossary.
Exercises#
-
Descriptions (Part 1): take one tool from
build_registry()and rewrite its description to be worse (vague, no when-not-to-use). Then write the strongest version you can. Which details did you cut first, and why? -
Parameters (1.6):
TicketsCreateArgs.bodyaccepts up to 4000 chars of free text. Argue for and against adding acategory: enumparameter. What breaks if the model picks the wrong category? -
Results (Part 3): modify
_order_viewto also return the customer's full profile (name, since, tier, internal notes). Which fields would you cut for the model-facing result, and how would you keep them available to your UI? -
Safety (Part 4): add a
send_ticket_replytool (writes a reply visible to the customer). Decide its risk class, whether it's idempotent, its dry-run shape, and what the description must say. Implement it insupport_tools.pyand extend the tests. -
Injection (4.6): write a
ticket_searchtool that takes aquerystring and runs it againstTICKETSusing Python'sremodule. Where could a malicious query cause harm (ReDoS, matching everything)? Harden it. -
Pagination (3.3): corrupt
next_cursorhandling: pass a hand-made base64 cursor{"o": -5}toorders_search. What happens? Fix_decode_cursorto reject negative/oversized offsets. -
Eval harness (8.2): add a fourth
EvalTask— "Ana wants to return her earbuds" — whose correct trajectory isorders_get→docs_search→ answer. Script aQueuedModelthat gets it wrong (callsrefunds_issueimmediately) and show the grader catching theforbid_toolsviolation. -
A/B descriptions (8.3): pick
docs_search. Write two description variants differing only in the "use FIRST for policy questions" sentence. Runrun_evalwith aQueuedModelscripted to calldocs_searchonly when the description contains "policies" — describe (don't run) how you'd measure the difference on a live model. -
OpenAPI curation (7.2): sketch (on paper or in a comment) the tool set you'd generate from a hypothetical
/v1/orders,/v1/orders/{id}/refund,/v1/ticketsspec, then delete/merge until it matchesbuild_registry(). What did you remove? -
Versioning (7.4): rename
orders_get's parametercustomer_email→email. List every place the change ripples (schema, description, tests, transcripts, cached prompts) and write the migration note you'd leave for the next engineer. -
Bridge the seams (8.2): write the ~30-line adapter the lesson sketches: an
EvalAdapterimplementing 08A.2'sChatAdapterprotocol (initial_history, asynccallviaasyncio.to_threadaround this file's synchronousCallModel,append_assistant,append_results) plus aToolSpecshim over this lesson'sTool. Then run oneEvalTaskthrough 08A.2'srun_agentand confirm the trajectory matchesrun_trial's. -
Bind the caller (4.2, 6.3): change
ToolRegistry.dispatchto acceptcaller_email: str, dropcustomer_emailfrom every schemaspecs()returns, and makeorders_get,orders_search,tickets_createandtickets_listuse the caller's email instead of a model argument. Makeorders_get(order_id="ORD-1043")called asana@example.comreturn the same "no order found" error as a missing ID. Add tests for: a model-suppliedcustomer_emailis rejected as an unknown argument (it is no longer in the schema), and Ana can never read Bo's order by ID.
Hints for the exercises
- The details people cut first from the strong version are usually the when-not-to-use sentence and the "what it does not return" sentence; those are the two that stop the model calling the wrong neighbour or calling again for data that will not come.
- For: an enum lets you route and report by category. Against: it is a decision the model must get right with no ground truth, and a wrong category silently mis-routes the ticket. Prefer deriving the category in code from the order or the text, or make it optional with an explicit
"other"value and measure how often it is right. - Keep
nameandtieronly if the answer needs them; cutinternal_notesalways (it is staff-only and a prompt-injection surface). Keep the full profile available to your UI by returning it from a separate UI endpoint, not through the tool. - Risk class
destructive(a customer sees it and it cannot be unsent); not idempotent unless you dedupe on(ticket_id, body hash); dry-run returns the rendered reply and the recipient; the description must say it messages a real customer and that a draft comes first. - Harm: catastrophic backtracking on patterns like
(a+)+$, and a query of.*matching every ticket. Harden by treating the query as a literal (re.escape), capping its length, capping matches, and running the search with a timeout. - A negative offset becomes a slice counted from the end of the list (
rows[-5:-2]forlimit=3), so the call "works" and returns the wrong page, or an empty one whenlimitis 5. Rejectoffset < 0andoffset > len(rows)with aValueError("invalid cursor ..."). - The scripted model's first reply is
ModelReply(tool_calls=[ToolCall("refunds_issue", {...})]); withforbid_tools=["refunds_issue"]the grade reportsforbidden_tools: ['refunds_issue']andmissing_toolslistsorders_getanddocs_search. - A fixed task set, one changed sentence, several trials per task, and compare wrong-tool rate, argument-error rate and steps per task; report the difference with its spread, not a single run.
- Typical survivors:
orders_get,orders_search,refunds_issue(with a dry-run flag),tickets_create,tickets_list. Typical removals: the raw/v1/orders/{id}variants that differ only by sub-resource, webhook and admin endpoints, and any bulk operations. - Ripples: the Pydantic model and JSON Schema, the description text, every test and snapshot, recorded transcripts and eval tasks that use the old name, and prompt caches (a changed tool definition is a cache miss). Migration note: accept both names for one release by adding a deprecated alias field, then remove it once transcripts show no old-shape calls.
- Map
ModelReply.tool_callsto 08A.2'sToolCall(id=..., name=..., arguments=...)andModelTurn(tool_calls=..., finish_reason="tool_calls"); return a call-freeModelTurn(text=...)for the final reply; run the synchronous model withawait asyncio.to_thread(self._model, messages, specs). - Keep identity out of the model-facing schema, and treat "belongs to another customer" exactly like "does not exist". Test both directions: an unknown extra argument is rejected, and a cross-customer ID lookup is indistinguishable from a missing ID.
Check yourself#
- What are the two contracts of a tool, and which fields belong to each?The model-facing contract (name, description, input schema — all prompt text the model reads to decide and fill arguments) and the code-facing contract (the function, its validation, safety metadata and result shaping). The model never sees the code; the code never sees the prose.
- Why is the tool description called "the highest-leverage prompt you write"?Because it's the only channel through which the model learns when to call the tool, how to fill its arguments and what to expect back — and it's billed as input tokens on every request. Anthropic calls detailed descriptions "by far the most important factor in tool performance".
- What four things should a strong tool description cover beyond "what it does"?When to use it, when not to use it (disambiguation from neighbouring tools), what it returns and doesn't return, and caveats (side effects, limits, freshness).
- When should two operations be consolidated into one tool with an
actionparameter, and when should they stay separate?When they share a resource, parameters and permissions and are frequently chained — consolidation cuts selection ambiguity and context. Keep them separate when risk classes differ or when parameters would become action-conditional spaghetti. - Why is a
confirmed: boolparameter the model sets itself not a security control?It proves the model intended the call, not that a human authorised it — the model can set the flag itself, especially under injection. Authorisation belongs to the app-side policy layer and human approval. - What does strict tool schema mode guarantee, and what does it not guarantee?It guarantees the arguments match the schema's shape (types, required fields, enums within the provider's supported subset). It says nothing about whether the values are correct, exist, or are safe — semantic validation is still your job.
- According to LongFuncEval, what happens to function-calling accuracy as the number of tools grows?Accuracy drops — measured between 7% and 85% across models as catalogue size grows, with similar degradation from longer tool responses and longer conversations.
- Name the three escape hatches when you need more tools than the "fewer than 20" guidance.Design fewer/better tools (consolidation), restrict the active set per step (
allowed_tools/allowed_function_names), and deferred loading/tool search for genuinely large surfaces. - What is an opaque cursor, and why must the model never parse it?An encoded pagination token (offset/keyset) the client generates and decodes. The model must pass it back verbatim — if it parses or constructs one, it can forge positions or crash the decoder; opaque means "not your problem to understand".
- What makes a tool error message "actionable", and why does that matter for agent behaviour?It says what failed and what to try next, written for the model to act on — specific, instructional, free of stack traces and internals. Errors that don't guide recovery produce repeated identical failing calls.
- How does an idempotency key differ from natural idempotency, and who should generate the key?An idempotency key is a unique token the application generates per logical operation so a retry returns the stored result; natural idempotency is designing the operation so retries are harmless by construction (e.g. dedupe on customer+subject). The key must come from the app/context, never the model — a model-supplied key gets invented, reused or corrupted.
- Why should
refunds_issuedefault toexecute=falseinstead of requiringexecute=true?Because the default should be the safe act: a preview the model can verify and show the user.execute=truebecomes a deliberate second call — easier to gate behind approval and harder to trigger by accident or injection. - What's wrong with exposing
run_sql(query: string)to an agent even with a read-only DB role?A read-only role still exposes every table to anyone who can steer the model, and agents can write pathological queries (cartesian joins, missing indexes) that become outages. Prefer allow-listed named queries or typed filter objects; free SQL is an injection and DoS surface. - What four levels make up the test pyramid for tools, and which one measures model behaviour?Unit tests (function logic), contract/schema snapshot tests (the wire definition), integration tests (the dispatch gate: rate limits, idempotency, error results), and behavioural tool-use evals (does the model choose and fill correctly). Only the fourth measures model behaviour.
- Why is changing a tool description a prompt change rather than a docs edit?Because the description is prompt text the model conditions on — a wording change alters selection and argument behaviour exactly like a prompt edit. It needs eval regression testing, versioning discipline and transcript monitoring, not just a docs review.
Further resources#
- 08A.4 — Harness Engineering: tool design as one part of the harness, with the evidence for fewer, better tools (Anthropic, Vercel) and mistake-to-tool fixes.
- Anthropic Engineering, "Writing effective tools for agents — with agents" (September 2025): the canonical methodology — prototypes, evals, consolidation, namespacing, token-efficient results, description prompt-engineering, and the SWE-bench description-refinement result.
- Anthropic Docs, Define tools and Tool reference: name rules,
input_examples, best practices,strict,defer_loading,allowed_callers, date-versioned tool types. - OpenAI, Function calling guide and Tool search: best practices (intern test, don't-fill-known-args, combine sequential calls, <20 soft suggestion), strict mode, deferred loading.
- Google, Function calling with the Gemini API: best practices (10–20 active tools max) and the
update()function-call workaround for pre-tool working notes. - Kate et al., LongFuncEval: Measuring the effectiveness of long context models for function calling (arXiv, April 2025): the measured accuracy decay as tool catalogues, tool responses and conversations grow.
- Berkeley Function Calling Leaderboard (BFCL) V4: live per-model function-calling accuracy — check your model before setting tool-count expectations.
- Stripe, Idempotent requests: the reference design for idempotency keys (generation, replay, parameter-mismatch errors, retention).
- OpenAPI Specification (v3.2.1, September 2026): the spec you'd generate tool candidates from — then curate.
- Anthropic, "Demystifying evals for AI agents" (January 2026): eval vocabulary and methodology; Module 10A owns evaluation in depth.
← 08A.5 — Required Agent Security | Module 08A overview | 08A.7 — Tool Safety in the Loop: Idempotency, Validation and Truncation →