AI Development

AD-03

Design tools and the agent loop

What you'll produce: Tool contracts

Definition

An agent is a model that calls tools in a loop, using each result to choose the next step. A tool contract is the written agreement for one tool, covering its purpose, inputs, outputs, side effects, permissions, errors, and approval rule. The set of contracts plus the loop's stopping rules defines what the agent is able to do and what it is not.

TL;DR

Why the tools are the design

Simon Willison records a definition he heard at an Anthropic event and decided he could live with: an agent is a model that uses tools in a loop. It is short, and it puts the engineering in the right place. The model is a given. What you design is the set of tools and the rules of the loop.

Anthropic's guide to building agents says the same from the builder's side. Agents are usually simple to implement, so the care belongs in the toolset and its documentation. The authors report spending more time on tools than on the overall prompt while building a coding agent. They suggest putting as much effort into the interface between agent and computer as teams normally put into interfaces for people.

There is also a cost argument for restraint. Chip Huyen works through the arithmetic of multi-step tasks: at 95 percent accuracy per step, a ten-step task succeeds about 60 percent of the time. Every extra step and every ambiguous tool makes that worse. So the first design question is whether you need a loop at all.

Workflow or loop

Anthropic separates two kinds of system. In a workflow, code decides the order of model and tool calls. In an agent, the model decides. Their advice is to find the simplest thing that works and add autonomy only when it measurably helps, because agents trade cost and latency for flexibility.

Use a loop when you cannot predict how many steps a task takes or in what order. Use a workflow when you can. Our own note on when not to deploy an agent adds a blunter test: if a deterministic script would remove most of the work, write the script.

What goes in a tool contract

A contract is one page per tool. These are the fields that do the work.

Field What to write Why
Name and purpose A verb and an object, plus when to use it and when not to Overlapping descriptions make the model unsure which tool to pick
Inputs Types, formats, allowed values, one example Constrained inputs make errors hard to express
Output Fields returned and a size cap Results stay in the window for the rest of the run
Side effects Nothing, or exactly what changes and whether it can be undone Separates reads from writes
Permission scope The narrowest credential that works Limits damage from any wrong call
Approval None, or who approves and what they see Puts a person where the cost is
Errors Each error, worded so the model knows the next move A good error is a recovery instruction

Three habits from the sources are worth adopting.

Write for the caller. Read the description as if you were the model and had nothing else. Anthropic suggests treating it like documentation for a new colleague, with example usage, edge cases, and clear boundaries from neighbouring tools.

Make mistakes hard to express. Anthropic's example is a file tool that failed when the agent used relative paths after changing directory. Requiring absolute paths ended the problem. The general move is to change the arguments so the wrong call cannot be formed.

Keep outputs small. Anthropic's engineering note on connecting agents to many tools describes two drains on the window: definitions loaded up front and intermediate results passed through the model. Return the fields the task needs, cap the size, and write anything larger to a file.

Limits on the loop

A loop needs to know when to stop. Anthropic's guide recommends that the agent check real results from its environment at each step, and that builders set a stopping condition, for example a cap on iterations. Write down three numbers, a list, and one sentence: maximum steps, spend cap, timeout, the points where the loop pauses for a person, and what done means.

Chip Huyen distinguishes read-only actions from write actions. Reads let the agent look. Writes let it change things, and that is where a wrong call has a cost. Our post on blocking a single write action describes the pattern we use: rules set before the run about what the agent may do, a pause at the writes that matter, and a log of every action and approval afterwards.

Then check combinations. Willison's lethal trifecta names three capabilities that are dangerous together: access to private data, exposure to content an attacker could have written, and a way to send data out. A model cannot reliably tell instructions in a document from instructions from its operator. If one agent has all three, split the tools across agents or gate the outbound channel.

Worked example: an invoice matching agent

This example is fictional. A finance team wants an agent that matches supplier invoices to purchase orders and schedules payment for clean matches.

The first draft exposes eleven endpoints of the accounting system as tools. In testing on 30 invoices, the model picks between two search tools inconsistently, passes dates in three formats, and in one run schedules the same payment twice after a timeout.

The team rewrites the set as four contracts.

  • get_invoice reads one invoice by its eight-digit ID and returns nine fields.
  • find_purchase_orders takes a supplier ID and an amount range and returns at most five candidates. It replaces both search tools.
  • flag_mismatch writes a note to the review queue. It is reversible and needs no approval.
  • schedule_payment takes an invoice ID, a purchase order ID, and an idempotency key. Dates use one format. Payments above a set amount pause for the finance lead, who sees the invoice, the matched order, and the difference.

The loop is limited to twelve steps and stops when the invoice is either scheduled or flagged. Invoice PDFs are untrusted content, so the agent that reads them has no tool that sends anything outside the accounting system.

On the same 30 invoices, tool choice errors drop to zero and the duplicate payment cannot recur, because a repeated key is rejected. Two invoices still fail on a currency mismatch the tools do not expose. That goes on the list for the next revision.

Common failure modes

  • One tool per endpoint. The model inherits an interface designed for programs.
  • Errors only an engineer can read. The agent retries the same call until the step limit.
  • Writes with broad credentials. The permission system says yes to an action nobody intended.
  • No definition of done. The loop keeps working after the task is finished, or stops before it is.
  • Reviewing tools one at a time. Each tool is safe alone, and the combination is not.
  • Testing the final answer only. Check the tool name, the arguments, the result, and the resulting state as separate assertions, which is how Hamel Husain recommends testing tool calls.

How it connects to the other pillars

The product pillar decides where people stay in the loop. A review-gate map says which decisions need a person, and the approval field in each contract is where that map becomes enforceable.

The factory pillar depends on the same contracts at a larger scale. When many agent workers run at once, isolation is what keeps one worker's tools from touching another's files or credentials. Narrow permission scopes and gated writes are the per-tool version of that isolation, and a factory inherits whatever discipline the contracts already have.

Run it yourself

Time: ~1 day for five to ten tools

  1. Decide between a fixed workflow and a loop — You need: The task description and several examples of how it is done today. You get: A written decision. Use a workflow if the steps are known in advance, and a loop if the number and order of steps cannot be predicted. A loop costs more and compounds errors. Choose it for a reason you can state.
  2. List the actions and classify them — You need: The spec's allowed and prohibited actions. You get: An action list marked read or write, reversible or not, with the cost of a wrong call for each.
  3. Write one contract per tool — You need: The action list and the underlying APIs. You get: A contract per tool with name, when to use it, when not to, inputs with types and limits, output shape and size cap, side effects, permission scope, errors, and approval rule. Make mistakes hard to express. Require absolute identifiers, use enumerations in place of free text, and add an idempotency key on writes.
  4. Review the tool set as a whole — You need: All contracts side by side. You get: Overlapping tools merged or given clear boundaries, unused tools removed, and any risky combination split across agents or gated.
  5. Set the loop limits — You need: Typical and worst-case step counts from examples, plus cost and time targets. You get: A maximum step count, a spend cap, a timeout, a definition of done, and the points where the loop pauses for a person.
  6. Test the tools with the model — You need: 20 or more task inputs, including ones designed to tempt a wrong tool or a bad argument. You get: A record of tool choice and argument errors, and revised descriptions or parameters that remove them.

Do it with AI

You are helping me write tool contracts for one AI agent. Use only the information I give you. If something needed for a contract is missing, put it in an open-questions list. Do not guess API behaviour.

Agent task: [ONE SENTENCE]
Allowed actions from the spec: [LIST]
Prohibited actions from the spec: [LIST]
Underlying APIs or functions available: [FOR EACH: NAME, WHAT IT DOES, PARAMETERS, WHAT IT RETURNS, WHETHER IT CHANGES DATA]
Cost of a wrong action, in plain terms: [FOR EACH WRITE ACTION]
Token ceiling for tool definitions and for one tool result: [NUMBERS]

First, tell me whether this task needs an agent loop or whether a fixed sequence of calls would do, with your reasoning.

Then, for each tool the agent needs, write a contract with these fields:
- name (a verb and an object, unambiguous next to the other tools)
- use when / do not use when
- inputs (name, type, allowed values or format, required or optional, one example)
- output (fields returned, maximum size, what happens to larger results)
- side effects (none, or exactly what changes and whether it can be undone)
- permission scope (the narrowest credential that works)
- approval (none, or who approves and what they are shown)
- errors (each error the model may see, worded so it knows what to do next)
- test cases (three inputs with the expected tool call and arguments, including one where the right move is not to call this tool)

After the contracts, list any two tools whose descriptions overlap, any tool I could remove, and any combination that gives the agent private data, untrusted input, and a way to send data out. Finish with proposed loop limits: maximum steps, spend cap, timeout, definition of done, and pause points.

Chain it

  1. Action classifier — Turns the spec's allowed actions and the API list into a classified action list; The spec and the API documentation → Actions marked read or write, reversible or not, with the cost of a wrong call; gate: The risk approver confirms the write actions and which of them need approval
  2. Contract writer — Drafts one contract per tool with constrained inputs, capped outputs, and actionable errors; The classified action list and API details → A full set of draft tool contracts
  3. Tool tester — Runs task inputs through the model with the draft tools and records wrong tool choices and malformed arguments; The draft contracts and a set of test inputs → An error table by tool, with suggested changes to names, descriptions, and parameters
  4. Combination reviewer — Checks the full tool set for overlap, unused tools, and risky combinations of data access, untrusted input, and outbound channels; The tested contracts and the data each tool touches → A list of merges, removals, and splits; gate: The engineer who owns the agent signs the final tool set and the loop limits

How AI changes this

Automate

Keep human

Stage

FAQ

How many tools should an agent have?

As few as the task needs. Each tool adds a definition to the window and one more option the model can choose wrongly. A practical check is to remove a tool and rerun your tests. If results do not get worse, leave it out. If the agent needs many tools across tasks, load a subset per task.

Should every API endpoint become a tool?

No. APIs are shaped for programs. A tool should match a step in the task. It is often better to combine several endpoints into one tool that returns only the fields the model needs, or to split one broad endpoint into a read tool and a separately gated write tool.

What makes a good error message for a model?

One that says what went wrong and what to try next, in a sentence or two. For example, state that the order ID was not found and that IDs are eight digits. A raw stack trace or a large JSON error body spends tokens and leaves the model guessing.

When does a tool call need human approval?

When the action is hard to undo, costly if wrong, or sends information outside the system. Approval should show the reviewer the action, the arguments, and the context that led to it. Reads and reversible low-cost writes can usually run without a pause, with every call logged.

Sources

Related