Slides · Harness engineering
The agent loop and tool design
1 / 27
The agent loop and tool design
What the harness does around the loop so an agent stops at the right time, recovers from failures and survives a crash.
By the end you can verify “done” mechanically, write errors a model can act on, design a small tool set, keep tool definitions and outputs out of the window, and make a long run resumable.
Concept
An empty result, four times
- An agent looks up order 4471 and gets an empty result. It looks again, then again, then a fourth time.
- Nobody told it what “not found” means or when to stop.
- A loop with a step cap is not yet a reliable agent. It can still declare victory early, burn its budget on a broken tool, pick the wrong tool from forty, or repeat a side effect after a crash.
- Each of these is a harness decision, and usually cheaper to fix there than in the prompt.
Concept
The model proposes, the harness disposes
- The model never touches the world. It proposes a tool call; the harness decides whether to run it, runs it and reports what happened.
- The same rule covers the end of the run. A reply with no tool call is the model saying it is finished. That is a hypothesis.
- Anthropic’s agent guidance says it is common to include stopping conditions such as a maximum number of iterations, and recommends extensive testing in sandboxed environments with appropriate guardrails.
- Stop controls (steps, budget, time, repeated-call detection, a human fallback) sit beside the done check, not instead of it.
Diagram
One turn of the loop
Compare
Make “done” as mechanical as you can
Young (Anthropic, 26 November 2025) reports agents marking features complete after only unit tests or curl calls, and later sessions declaring the whole job finished. Their remedy was a feature list plus instructions, which is still an instruction.
| Check | Who decides | Strength |
|---|---|---|
| The model says it is done | the model | a claim only |
| The model flips a “passes” field after saying it tested | the model, under an instruction | the model can flip it untested |
| The harness runs the tests and reads the exit code | the harness | mechanical |
| Output validates against a schema and a required file exists | the harness | mechanical |
- Where meaning matters and no test exists, a separate checker is better than the same agent.
Check yourself
Check: pick the done condition
A report-writing agent must deliver summary.json with fields title, findings (a list) and sources (a list of URLs). Which is the strongest harness-side done check?
- The agent replies “summary written”.
- The harness parses
summary.json, validates the three fields against a schema, and checks every URL insourceswas fetched during the run. - The agent is asked to re-read its own file and confirm it looks right.
Answer
Option 2. The harness runs it, it does not depend on the model’s narration, and it checks a property that matters (sources were actually fetched). Options 1 and 3 rely on the model’s own report. If validation fails, send the failure message back and continue.
Compare
Errors are observations
Anthropic’s tool-writing guidance says error responses should state specific, actionable improvements rather than opaque codes or tracebacks. The aim is that the agent can correct its input.
| Tool result | What the model can do |
|---|---|
Error 500 | nothing useful; it tends to retry the same call |
FileNotFoundError: [Errno 2] plus a traceback | little; noisy and unlabelled |
File not found: src/a.py. Use list_dir on the parent folder to see what exists. | fix the argument or look around |
A good result says what failed, why, and what to try next.
Diagram
Who handles which failure
Worked example
Worked example: a rate limit that clears
Illustrative: a search tool returns a rate-limit error twice, then succeeds. The harness waits 1 s, then 2 s (doubling each attempt, jitter omitted for clarity).
| Attempt | Result | Wait before next | Model steps used |
|---|---|---|---|
| 1 | rate limit | 1 s | 0 |
| 2 | rate limit | 2 s | 0 |
| 3 | success | none | 1 (it sees only the result) |
- Total extra wait: 1+2=3 s, and the model spends one step, not three.
- If the harness did not retry, each failure would cost the model a step, and the rate-limit episode would take three steps, two of them wasted on infrastructure flakiness.
- Cap the retries; if all fail, return one short message saying what failed and what to try.
Code
Detecting repeats: small and limited
Illustrative detector, run and tested in a scratch script.
Python
def no_progress(history, window=3):
recent = [(c["name"], h(c["args"]), h(c["result"])) for c in history[-window:]]
return len(recent) == window and len(set(recent)) == 1h hashes JSON. The detector flags when the last window calls share name, arguments and result.
| Test history | Result | Reading |
|---|---|---|
three identical empty search("order 4471") calls | True | caught |
| same search with spacing and word order changed | False | missed |
| only two identical calls | False | window not full |
| third call returns a different result | False | progress |
| alternating A, B, A, B, A, B | False | missed: no three identical in a row |
Near-identical queries need a similarity check on the arguments. A second check over a longer window (6 calls with at most 2 distinct signatures) flagged the A, B alternation but not 6 distinct calls; an A, B, C cycle needs a limit of 3 distinct signatures, and the limit is a trade-off against false alarms. Nudge once on a hit, then stop or escalate.
Concept
Designing the tool set
Tools are an interface for a user with a small, expensive working memory.
- Few, thoughtful tools for high-impact workflows, not one per endpoint. Anthropic’s example merges listing availability and booking into one scheduling tool.
- Write descriptions like onboarding a new colleague: purpose, when not to use it, what arguments mean. Use unambiguous names such as
user_id, notuser. - Return what the next step needs: readable fields, with an optional concise or detailed response mode.
- Hard to misuse: Anthropic’s agent guidance says to poka-yoke tools by changing the arguments so mistakes are harder to make.
- Split reading from writing and put destructive actions behind approval.
- Anthropic reports spending more time optimising tools than the overall prompt for its SWE-bench agent.
Sources[3] Writing effective tools for agents — with agents[1] Building effective agents
Process
How to improve tools: change the tool, not the prompt
- Run realistic multi-step tasks with checkable outcomes.
- Read the raw transcripts, including tool calls and results, and note which tool the agent misuses and how.
- Change the tool: merge overlaps, rename arguments, shorten results.
- Re-run on a held-out set so you do not overfit to the tasks you tuned on.
- Record what changed. Renaming a tool or an argument can change behaviour, and namespacing choices such as prefix versus suffix have been reported to matter and to differ by model.
Concept
Make edits conditional
- Microsoft’s Agent Framework documents a line-edit tool (
file_access_replace_lines) that takes the expected text of the line; if the line number no longer points at that text, the edit fails rather than landing on the wrong line. - That is optimistic concurrency applied to a model’s edits: state what you believe is there, and refuse if it is not.
- In that documentation, file access is marked experimental, so treat it as an example of the pattern, not a recommendation.
Source[5] Agent Harness
Check yourself
Check: spot the confusing pair
An agent has get_user(id) and get_customer(id). Transcripts show it passes a customer number to get_user about as often as it passes the right one. Name two changes to the tools and one thing you would not do.
Answer
Make the mistake hard to make (poka-yoke): name the arguments user_id and customer_id, and have each tool reject the other’s id format with a message such as “This looks like a customer id; call get_customer”. Re-run the failing transcripts, then confirm on a held-out set of tasks that the change did not just fit the ones you tuned on. A reminder in the system prompt is the weakest of these options, because the ambiguity lives in the tool.
Worked example
Tool definitions are a cost before work starts
Anthropic’s November 2025 post gives approximate figures, in beta, for its own setups.
| Figure in the post | Tokens |
|---|---|
| Five servers, 58 tools, definitions only | about 55,000 |
| 50 or more tools, every definition loaded | about 77,000 |
| Same, with a tool-search tool (about 500 up front plus the few tools found) | about 8,700 |
Arithmetic checked in a script:
- 5855,000≈948 tokens per tool on average.
- 77,000−8,700=68,300 fewer tokens, which is 88.7 percent of 77,000. The post’s own text says 85 percent, so treat all of these as orders of magnitude.
- Against an assumed 200,000-token window (illustrative), 77,000 is 38.5 percent gone before the first message.
Source[6] Introducing advanced tool use on the Claude Developer Platform
Concept
Progressive disclosure for tools
- Start the model with a way to find tools. Load a full definition only for the tools it needs.
- Tool tiers do a similar job: read-only tools always on, write tools enabled by mode, dangerous tools behind approval.
- Trade-off: one extra search step per new tool, and the search quality now decides whether the right tool is found.
- Third-party tool descriptions and results enter the prompt, so a server you did not write can carry instructions. That supply-chain risk is covered in the MCP and guardrails lessons.
Source[6] Introducing advanced tool use on the Claude Developer Platform
Diagram
Long outputs: keep the head and tail, offload the rest
Worked example
Worked example: what offloading saves
Illustrative numbers: a build prints 6,000 lines, at about 12 tokens per line.
| Option | Lines in context | Tokens |
|---|---|---|
| Paste everything | 6,000 | 72,000 |
| First 40 plus last 40 lines, path to the full log | 80 | 960 |
- 6,000×12=72,000; 80×12=960. Savings: about 98.7 percent in this made-up case.
- Do not summarise a log with a cheaper model when one failing line matters; keep a pointer to the raw text.
- Redact before anything enters context, because what enters context is logged and may be replayed.
Compare
A general shell versus narrow tools
| Aspect | Narrow, structured tools | A general shell |
|---|---|---|
| Audit and approval | easy | hard |
| Definitions | many, with gaps for needs you did not foresee | few, very capable |
| Blast radius | small | large: needs a sandbox, allow and deny lists, timeouts, output caps |
| Output | shaped by you | can be huge and needs truncation |
Most real harnesses mix them: structured tools for common, risky operations and a sandboxed shell for the long tail. Anthropic’s agent guidance recommends extensive testing in sandboxed environments.
Diagram
Crash, resume, replay
Sources[7] Idempotent requests[2] Effective harnesses for long-running agents
Code
Replay is safe only with idempotent tools
Illustrative service and runner, run in a scratch script with a simulated crash after step 1 executes but before its checkpoint is saved.
Python
def create(self, params, key=None):
if key is not None and key in self.seen:
old_params, result = self.seen[key]
if old_params != params:
raise ValueError("key reused with different parameters")
return result # repeat: return the saved result
ticket_id = self._insert(params)
if key is not None:
self.seen[key] = (copy.deepcopy(params), ticket_id)
return ticket_id| Test (3-step run, crash then resume) | Result |
|---|---|
| Tickets created, no key | 4 (step 1 duplicated) |
| Tickets created, key per step | 3 |
| Same key, different parameters | raises an error |
| Key from run id + step: same step in two runs | different keys |
| Resume with the same run id | same key |
Stripe documents this behaviour for API v1, where keys may be pruned after at least 24 hours, and its layer rejects reuse with different parameters. Git commits are a natural checkpoint for code agents (Anthropic’s long-running agents recovered a working state that way). The check-then-insert in this sketch is not atomic: two concurrent replays could both insert, so a real service needs a lock or a unique constraint on the key. The saved parameters are copied, because a stored reference breaks a later identical replay if the caller mutates its dict (tested). If a provider has no idempotency support, check your own sent log, keyed the same way, before you resend.
Source[7] Idempotent requests
Worked example
Where the crash lands decides what replays
Illustrative step: “send one email”, checkpoint saved after the step.
| Crash happens | After resume | Effect without a key | Effect with a key |
|---|---|---|---|
| before the tool runs | step runs once | one email | one email |
| after it runs, before the save | step runs again | two emails | one email, repeat ignored |
| after the save | step skipped | one email | one email |
- Only the middle row needs idempotency, and it is the one you cannot rule out by timing.
- Persist after every step: messages, tool results, the plan and the ids of side effects already made.
Concept
Treat tool schemas as a versioned interface
- A model’s behaviour can depend on tool names and shapes. Anthropic reports that even prefix versus suffix namespacing can have non-trivial effects, and says to test per model.
- Renaming a tool or changing an argument is therefore a behaviour change, not a refactor.
- Re-run your task set on every change and record what changed, so a regression can be traced to one edit.
Check yourself
Check: save before or after?
A harness marks each step “done” in its checkpoint file before it runs the tool, to avoid ever running a step twice. The process is killed in the middle of a send_email call. What happens on resume, and what is the trade-off against saving after the call?
Answer
On resume the step is already marked done, so it is skipped, and the email may never have been sent (or was only half done). Saving before gives at-most-once execution and can lose work silently; saving after gives at-least-once execution and needs idempotent tools or a sent log to avoid duplicates. For most side effects the second plus idempotency is the safer default, because a missing action is harder to notice than a repeated one that the service ignores.
Summary
Recap
- The model proposes, the harness disposes; “no tool call” is a claim to verify, ideally mechanically.
- Errors are observations: what failed, why, what to try. Retry transient failures in the harness; cap repairs; detect repeats.
- Few, non-overlapping, hard-to-misuse tools with short, readable output; fix tools, not prompts.
- Load definitions on demand; keep head and tail of long output and offload the rest; sandbox a shell.
- Persist after each step; replay needs idempotent tools; version tool schemas.
References
References & Sources (1 of 2)
Building effective agents (opens in a new tab)
Erik S., Barry Zhang2024Article
https://www.anthropic.com/engineering/building-effective-agents
Used for Stopping conditions, the agent-computer interface, poka-yoke for tools, and testing in sandboxed environments.
Effective harnesses for long-running agents (opens in a new tab)
Justin Young2025Article
https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents
Used for Agents marking features complete without end-to-end testing, and git as a recovery checkpoint.
Writing effective tools for agents — with agents (opens in a new tab)
Ken Aizawa2025Article
https://www.anthropic.com/engineering/writing-tools-for-agents
Used for Actionable errors, few thoughtful tools, naming, response modes, transcript-driven improvement, the 25,000-token Claude Code default and namespacing effects.
Timeouts, retries, and backoff with jitter (opens in a new tab)
Amazon Web Services (Builders' Library, AWS Builder Center)2019Article
https://builder.aws.com/content/3EumjoZascWd1oZiEgL8ORlv3qE/timeouts-retries-and-backoff-with-jitter
Used for Exponential backoff with jitter, and the warning that side-effecting calls are unsafe to retry unless idempotent.
Agent Harness (opens in a new tab)
Microsoft Learn (Agent Framework)2026Documentation
https://learn.microsoft.com/en-us/agent-framework/concepts/harness
Used for The conditional line-edit tool that takes the expected line text, and its experimental status.
References
References & Sources (2 of 2)
Introducing advanced tool use on the Claude Developer Platform (opens in a new tab)
Bin Wu2025Article
https://www.anthropic.com/engineering/advanced-tool-use
Used for Approximate token costs of loading many tool definitions versus using a tool-search step.
Idempotent requests (opens in a new tab)
Stripe2026Documentation
https://docs.stripe.com/api/idempotent_requests
Used for How idempotency keys let a retry return the saved result and reject reuse with different parameters.
Keys: ← → move, Home End first and last, F full screen.