The agent loop and tool design
- Advanced
- 35 min
- Lesson 2 of 7 in Harness engineering
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
Before you start
- Completed:What is an agent harness?
- Completed:Function and tool callingTools and agents
You will be able to
- Explain why the model proposes and the harness disposes, and why a model's claim that it is done is a hypothesis the harness verifies.
- Turn tool failures into results an LLM can act on, and keep infrastructure retries out of the model's step budget.
- Design a small set of tools for an agent: few and non-overlapping, hard to misuse, with readable, token-efficient output.
- Keep a large tool catalog and large tool outputs from filling the context window, and weigh a general shell tool against narrow tools.
- Make a long run resumable, explain why replay is safe only with idempotent tools, and treat tool schemas as a versioned interface.
Vihaan looks up order 4471. The system answers with an empty result, so he looks it up again. Same answer. He tries a third time.
“Right away,” he tells the log, and starts a fourth.
Nobody told him when to stop, or what “not found” means. What should an empty result make an agent do?
Concept
You already know the pieces: a tool call is a proposal (function and tool calling), and an agent repeats it until a goal is met, under stopping controlsStopping controlsThe limits that end an agent loop: a checkable done criterion, step cap, time and cost budgets, loop detection and escalation to a human.Open the glossary entry (agentic patterns). This lesson is about what the harness does around that loop so it behaves in production. Four things matter most: who decides the work is done, what the model sees when a tool fails, how the tools are shaped, and what survives a crash. In the story, the Yard’s long store stands in for that harness.
Why It Matters
A loop with a step cap is not yet a reliable agent. The same agent can still declare victory too early, burn its budget retrying a broken tool, pick the wrong one of forty overlapping tools, or start over after a crash and repeat a side effect. Each of those is a harness decision, and each is cheaper to fix in the harness than to hope away in the prompt. Anthropic’s engineering team described the effort in its December 2024 post on building agents: invest as much in the agent-computer interface as in a human-computer interface. They report spending more time optimizing the tools than the overall prompt when building their SWE-bench agent.
Mental Model
Vihaan is the model: willing and literal. The tool layer around him is the harness. Whether a lookup came back empty is something the tool can tell him, in words he can act on (“order 4471 does not exist; the closest match is 4417; ask the customer to confirm”), and the harness, not Vihaan, decides how many tries are enough. An agent that can only be told “not found” will search again.
The model proposes, the harness disposes
The model never touches the world directly. It proposes a tool call; the harness decides whether to run it, runs it, and returns what happened. The same rule applies to the end of the run: a message with no tool call is the model saying it is finished. That is a hypothesis, and the harness checks it.
Anthropic’s post on long-running agents (November 2025) shows why the check matters. Agents working across many context windows often marked features complete without testing them end to end, and in later sessions an agent could see earlier progress and declare the whole job finished. Their remedy combined a JSON feature list that starts all failing with strongly worded instructions to change an entry only by setting it to passing after testing like a user would (the first lesson of this module tells the same story from the harness side).
That remedy is an instruction, not a mechanism: the model could still flip the field without testing. A stronger check is one the harness runs itself: the tests pass, the output matches a schema, a required file exists. Make your done check as mechanical as you can. The stopping controls from the earlier lesson (steps, budget, time, repeated-call detection, a human fallback) still apply; this check sits alongside them.
Errors are observations
When a tool fails, the model has to decide what to do next, and it only knows what you tell it. A stack trace or “Error 500” gives it little to act on. Anthropic’s tool-writing guidance (September 2025) says to make errors actionable rather than opaque codes or tracebacks, so the agent can correct its input. A result written for a model says what failed, why, and what to try:
File not found: src/a.py. Did you mean src/app.py?
Use list_dir("src") to see what exists.| Tool result | What the model can do with it |
|---|---|
Error 500 | Nothing useful, so it tends to retry the same call |
FileNotFoundError: [Errno 2] plus a traceback | Little: noisy and unlabelled |
File not found: src/a.py. Did you mean src/app.py? Use list_dir("src") to see what exists. | Correct its argument or look around: what failed, why, what to try |
A few rules follow from treating errors as observations:
- Bad arguments: validate against the schema and return the validation message, with a cap on repair attempts so the model cannot loop on a malformed call.
- Transient failures (a timeout, a rate limit): retry in the harness with backoff, out of the model’s sight. Otherwise the model spends its step budget on infrastructure flakiness. Return a message only when retries are exhausted.
- Claims about actions: a model can say it ran a check it did not run. Where it matters, the harness runs the check itself, in a hook after the step, instead of trusting the narration.
- Repeats: if the same call with the same arguments fails or returns the same thing several times, that is a no-progress signal. Nudge once, then stop or escalate. The empty lookup in the story is this case.
An illustrative detector (not a library) shows how small it can be:
def no_progress(history, window=3):
recent = [(c.name, c.args_hash, c.result_hash) for c in history[-window:]]
return len(recent) == window and len(set(recent)) == 1This catches only identical calls. Near-identical queries need a similarity check on the arguments, which is the point of the advanced practice question below.
Designing the tool set
Tools are an agent-computer interfaceAgent-computer interface (ACI)The tools, their names, descriptions, arguments and results as an agent experiences them. Anthropic's advice is to give it as much design effort as a human-computer interface.Open the glossary entry: an interface for a user with a small, expensive working memory. Anthropic’s September 2025 guidance gives a useful set of defaults, which you should test rather than take on faith:
- Few, thoughtful tools for high-impact workflows, not one tool per backend endpoint. Related steps can be one tool: a scheduling tool that finds a free slot and books it in one call. Tools that overlap, or whose purpose is vague, confuse the agent and can distract it from an efficient route.
- Names and descriptions for the model. Write the description as you would for a new colleague: what it is for, when not to use it, what the arguments mean. Prefer unambiguous parameter names (
user_idoveruser). Consistent prefixes by service or resource can help the agent choose; test whether prefix or suffix works better for your model. - Return what the next step needs. High-signal, readable fields, not internal identifiers. A parameter that lets the agent ask for a concise or a detailed response gives it control over the size.
- Hard to misuse. Anthropic’s December 2024 post calls this poka-yoke: change the arguments so mistakes are harder to make. The tool-calling lesson covers definitions; the habit to add here is to look for the mistake in your transcripts and then change the argument that allowed it.
- Split reading from writing, and keep destructive operations separate and approval-gated.
- Make edits conditional. Microsoft’s Agent Framework documents a line-edit tool,
file_access_replace_lines, that takes the expected text of the line, so a stale line number fails instead of editing the wrong line. That is optimistic concurrency, applied to a model’s edits. (In that documentation file access is available in Python and still marked experimental, so treat it as an example of the pattern, not a recommendation.)
How you improve tools matters as much as how you write them. Run realistic multi-step tasks with checkable outcomes, read the transcripts, and note which tool the agent misuses and how. Then change the tool, not the prompt. Keep a held-out set of tasks so your changes do not overfit.
Keeping tools and their output out of the window
Two costs hit the context window before any work happens: the tool definitions and the tool results.
Definitions. Every tool you list takes space. Anthropic’s November 2025 post gives an example of five servers with 58 tools that consumed about 55,000 tokens of definitions before the conversation started. In a separate comparison with 50 or more tools it reports about 77,000 tokens in use before work began when every definition is loaded, against about 8,700 with a tool-search step (about 500 tokens up front plus the few tools it found). Those are the vendor’s own measurements, so treat them as an order of magnitude. The pattern is progressive disclosure (see tool searchTool searchA way to load tool definitions on demand: the model starts with a search step and receives full definitions only for the tools it finds, so a large catalog does not fill the context window.Open the glossary entry): the model starts with a way to find tools, and full definitions load only for the ones it needs. Tool tiers do a similar job: read-only tools always on, write tools enabled by mode, dangerous tools behind approval.
| Strategy (vendor’s own measurement, order of magnitude) | Tokens used before work starts |
|---|---|
| Load every definition up front (50 or more tools) | about 77,000 |
| Tool-search step, load only the tools needed | about 8,700 |
Results. A test run can print thousands of lines. Keep the first and last lines in context, write the full output to a file, and tell the model the path and how to search it. For a noisy source such as a long web page, summarise with a cheaper model and keep a pointer to the raw text; do not do this for a log where one failing line matters. Redact secrets and personal data before they enter context, because what enters context is logged and may be replayed. Anthropic’s tool-writing post notes that Claude Code limits tool responses to 25,000 tokens by default, and advises that if you truncate, you send helpful instructions with the result so the agent searches more narrowly. The number is specific to that product and may change.
A general shell tool. Giving an agent a shell lets it build what it needs and replaces many narrow tools. The cost is blast radius and noise:
| Narrow, structured tools | A general shell |
|---|---|
| Easy to audit, approve and constrain | Few definitions, very capable, composable |
| Many definitions; gaps when you did not foresee a need | Large blast radius: needs a sandbox, allow and deny lists, timeouts and output caps |
| Output is shaped by you | Output can be huge and needs truncation |
Most real harnesses mix them: structured tools for the common, risky operations and a sandboxed shell for the long tail. Tool descriptions and results from third-party servers also enter the prompt, so a server you did not write can carry instructions; that supply-chain risk is covered in Model Context Protocol and guardrails and prompt injection.
Durable loops
Long runs crash. After each step, persist what you would need to continue: the messages, the tool results, the plan, and the identifiers of any side effects already made. On resume, replay is safe only if the tools are idempotent, because a step that already succeeded will run again. An idempotency keyIdempotency keyA unique value sent with a side-effecting request so the receiver can recognise a repeat and not act twice. It protects against retries and loops.Open the glossary entry lets the service recognise the repeat and ignore it; a conditional edit fails harmlessly. For code agents, git commits are a natural checkpoint: you can revert a bad change and recover the last working state, which is how Anthropic’s long-running agents recovered.
Treat tool schemas as a versioned interface
A model’s behaviour can depend on the names and shapes of the tools it is given. Anthropic’s tool-writing post notes that even a choice such as prefix or suffix namespacing can have non-trivial effects, and says to test it per model. Renaming a tool or changing an argument can therefore change what the agent does. Re-run your tasks on every change, and record what changed.
Real-World Application
An email agent. The loop proposes send_email; the harness checks permissions and a daily rate limit, requires approval for external recipients, sends with an idempotency key built from the draft, and records the message id before the next step. If the process crashes between sending and saving, the resume sends again with the same key. If the mail provider supports idempotency keys, it treats the second call as a repeat; if it does not, the harness checks its own sent log, keyed the same way, before it resends. A failed send returns “Recipient address rejected: no such mailbox. Check the address with lookup_contact”, not a stack trace. When the model says the batch is done, the harness counts the sent ids against the list.
Interview Perspective
Expect: “How does your loop decide that the work is finished, and what does the model see when a tool fails?” “An agent keeps repeating a near-identical search. What do you build?” “How would you expose a large internal API surface to an agent: tools, loading and permissions?”
A strong answer separates who proposes from who verifies, lists the stop conditions, treats errors as observations, shortens and offloads outputs, and says what happens on resume. Common mistakes: trusting “I’m done” without a check; returning raw ten-thousand-line outputs; fifty similar tools with vague descriptions; retrying non-idempotent actions after a crash; fixing tool confusion with more prompt text instead of changing the tool; allowing an arbitrary shell with no sandbox. A misconception to watch for: “if the model emits no tool call, the task is done.”
Provenance: Common industry pattern. These are typical of agent-engineering interviews; none is verified for a named company.
Practice Questions
- Basic: List five stop conditions for an agent loop and what each protects against.
- Intermediate: Redesign a
do_database_thing(sql, mode)tool for safety and clarity. - Advanced: An agent loops calling
searchwith near-identical queries for 40 steps. Design the detection and a recovery policy, and say what you log. - Product-Company: You must expose 120 internal APIs to an agent. How do you structure tools, loading and permissions?
Activity
Take one tool from an agent you know. Write the result it returns for three failures: a bad argument, a timeout that retried and gave up, and “nothing found”. Then rewrite each so that a model, reading only that text, would know what to do next. Count how many tokens the original success result used and cut it in half without losing what the next step needs.
Homework
Write a one-page design for the loop of an agent that sends emails. Cover the stop conditions, how “done” is verified, the error messages for three failures, the idempotency key, the approval rule, and the checkpoint written after each step. State what you would test first, in the transcripts, to find where the model misuses the tools.
Quick Revision
- The model proposes, the harness disposes. “No tool call” is a claim; verify it.
- Make “done” mechanical: tests, schema, a required artefact, or a check the harness runs itself.
- Errors are observations: what failed, why, what to try. Retry transient failures in the harness; cap repair attempts; detect repeats.
- Few, non-overlapping, hard-to-misuse tools with readable, short output; fix tools, not prompts.
- Load tool definitions on demand; keep head and tail of long output and offload the rest; redact first.
- A shell is powerful and risky: sandbox it. Persist after each step; replay needs idempotent tools; version tool schemas.
Check yourself
- Walk-through: Describe your loop: how it stops, how it handles a tool error, and how it keeps a 5,000-line test output out of the context.
- Variation: The same for an agent that sends emails: what changes about idempotency, approval and rate limits?
- Common misconception: “If the model emits no tool call, the task is done.” It is saying it is done; the harness checks.
Related
Resources & Further Reading
Checked sources to go deeper. The essential ones come first in each group.
Official documentation
Handle tool calls (opens in a new tab)Essential
Shows how tool results and errors are returned to the model in the API, which is where your actionable error text actually goes.
Tool search tool (opens in a new tab)
The official page for the tool-search mechanism behind the on-demand loading slide, with current limits and usage.
Define tools (opens in a new tab)
Covers writing tool descriptions and schemas, the front line of making a tool hard to misuse.
Further reading
LLM06:2025 Excessive Agency (opens in a new tab)
Explains why broad tools and permissions are a risk, which is the reason to prefer narrow tools or a sandboxed shell.
Research papers
ReAct: Synergizing Reasoning and Acting in Language Models (opens in a new tab)
The original reason-and-act loop; useful for seeing what the harness adds when the loop must survive failures.
Hands-on
Building Effective Agents Cookbook (claude-cookbooks, patterns/agents) (opens in a new tab)
Runnable agent patterns where you can add a verification step and a stop condition to a working loop.
More for this module: Harness engineering resources
Practice
Test what you just read. Quizzes and cards are grouped by module: Harness engineering.
Check yourself12 questions on what this lesson set out to teach
Checking answers needs JavaScript. You can still read every question and option below.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.