Slides · Harness engineering

The agent loop and tool design

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.

Source1 Building effective agents

Diagram

One turn of the loop

Diagram: Reading down, a reply with no tool call goes to a verification check before the run can end.

no

yes

yes

no

no

yes

stop

continue

Model reply

Tool call?

Done verified?

Permitted?

Return

Send failure back

DENIED

Run and log

Stop checks

Stop

Diagram summary: Reading down, a reply with no tool call goes to a verification check before the run can end. A proposed call passes a permission check, runs and is logged, then meets the stop checks. A failed verification or a denial feeds back into the next model reply (those return arrows are omitted for width), and the continue branch loops to it.

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.

CheckWho decidesStrength
The model says it is donethe modela claim only
The model flips a “passes” field after saying it testedthe model, under an instructionthe model can flip it untested
The harness runs the tests and reads the exit codethe harnessmechanical
Output validates against a schema and a required file existsthe harnessmechanical
  • Where meaning matters and no test exists, a separate checker is better than the same agent.

Source2 Effective harnesses for long-running agents

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?

  1. The agent replies “summary written”.
  2. The harness parses summary.json, validates the three fields against a schema, and checks every URL in sources was fetched during the run.
  3. 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 resultWhat the model can do
Error 500nothing useful; it tends to retry the same call
FileNotFoundError: [Errno 2] plus a tracebacklittle; 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.

Source3 Writing effective tools for agents — with agents

Diagram

Who handles which failure

Diagram: Reading down, the failure type picks the handler: transient failures are retried in the harness with backoff and reach the model only if...

transient

bad arguments

same call repeats

retries exhausted

Tool call fails

What kind?

Harness retries
with backoff

Return validation
message, cap repairs

Nudge once,
then stop or escalate

Return a short message

Diagram summary: Reading down, the failure type picks the handler: transient failures are retried in the harness with backoff and reach the model only if retries run out, bad arguments get a validation message with a repair cap, and repeated calls trigger a nudge then a stop. AWS’s guidance is exponential backoff with jitter, and retrying side-effecting calls is unsafe unless they are idempotent.

Source4 Timeouts, retries, and backoff with jitter

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).

AttemptResultWait before nextModel steps used
1rate limit1 s0
2rate limit2 s0
3successnone1 (it sees only the result)
  • Total extra wait: 1+2=3 s1 + 2 = 3\ \text{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.

Source4 Timeouts, retries, and backoff with jitter

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)) == 1

h hashes JSON. The detector flags when the last window calls share name, arguments and result.

Test historyResultReading
three identical empty search("order 4471") callsTruecaught
same search with spacing and word order changedFalsemissed
only two identical callsFalsewindow not full
third call returns a different resultFalseprogress
alternating A, B, A, B, A, BFalsemissed: 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, not user.
  • 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.

Sources3 Writing effective tools for agents — with agents1 Building effective agents

Process

How to improve tools: change the tool, not the prompt

  1. Run realistic multi-step tasks with checkable outcomes.
  2. Read the raw transcripts, including tool calls and results, and note which tool the agent misuses and how.
  3. Change the tool: merge overlaps, rename arguments, shorten results.
  4. Re-run on a held-out set so you do not overfit to the tasks you tuned on.
  5. 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.

Source3 Writing effective tools for agents — with agents

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.

Source5 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 postTokens
Five servers, 58 tools, definitions onlyabout 55,000
50 or more tools, every definition loadedabout 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:

  • 55,00058≈948\dfrac{55{,}000}{58} \approx 948 tokens per tool on average.
  • 77,000−8,700=68,30077{,}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.

Source6 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.

Source6 Introducing advanced tool use on the Claude Developer Platform

Diagram

Long outputs: keep the head and tail, offload the rest

Diagram: Reading down, a long tool output is split.

Tool prints
thousands of lines

Save full output
to a file

Keep first and last
lines in context

Redact secrets and
personal data

Tell the model the path
and how to search it

Short, useful result

Diagram summary: Reading down, a long tool output is split. The full text goes to a file, a short head and tail stays in context after redaction, and the model is told where the file is and how to search it. Anthropic notes Claude Code limits tool responses to 25,000 tokens by default and advises steering the agent with helpful instructions when you truncate; that number is specific to that product.

Source3 Writing effective tools for agents — with agents

Worked example

Worked example: what offloading saves

Illustrative numbers: a build prints 6,000 lines, at about 12 tokens per line.

OptionLines in contextTokens
Paste everything6,00072,000
First 40 plus last 40 lines, path to the full log80960
  • 6,000×12=72,0006{,}000 \times 12 = 72{,}000; 80×12=96080 \times 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

AspectNarrow, structured toolsA general shell
Audit and approvaleasyhard
Definitionsmany, with gaps for needs you did not foreseefew, very capable
Blast radiussmalllarge: needs a sandbox, allow and deny lists, timeouts, output caps
Outputshaped by youcan 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.

Source1 Building effective agents

Diagram

Crash, resume, replay

Diagram: The service ran step 7 but the crash hit before the save, so resume replays it; the same key (run id plus step, or a random UUID saved...
ServiceCheckpointHarnessServiceCheckpointHarnesscrash before savestep 7, key run1-s7okresume, load checkpointreplay step 7, key run1-s7saved result, no duplicate
Diagram summary: The service ran step 7 but the crash hit before the save, so resume replays it; the same key (run id plus step, or a random UUID saved before the call) lets the service return the saved result instead of a second ticket. Never use the step number alone, which collides across runs.

Sources7 Idempotent requests2 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 key4 (step 1 duplicated)
Tickets created, key per step3
Same key, different parametersraises an error
Key from run id + step: same step in two runsdifferent keys
Resume with the same run idsame 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.

Source7 Idempotent requests

Worked example

Where the crash lands decides what replays

Illustrative step: “send one email”, checkpoint saved after the step.

Crash happensAfter resumeEffect without a keyEffect with a key
before the tool runsstep runs onceone emailone email
after it runs, before the savestep runs againtwo emailsone email, repeat ignored
after the savestep skippedone emailone 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.

Source3 Writing effective tools for agents — with agents

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)

  1. Building effective agents (opens in a new tab)

    Erik S., Barry Zhang2024Article

    Used for Stopping conditions, the agent-computer interface, poka-yoke for tools, and testing in sandboxed environments.

  2. Effective harnesses for long-running agents (opens in a new tab)

    Justin Young2025Article

    Used for Agents marking features complete without end-to-end testing, and git as a recovery checkpoint.

  3. Writing effective tools for agents — with agents (opens in a new tab)

    Ken Aizawa2025Article

    Used for Actionable errors, few thoughtful tools, naming, response modes, transcript-driven improvement, the 25,000-token Claude Code default and namespacing effects.

  4. Timeouts, retries, and backoff with jitter (opens in a new tab)

    Amazon Web Services (Builders' Library, AWS Builder Center)2019Article

    Used for Exponential backoff with jitter, and the warning that side-effecting calls are unsafe to retry unless idempotent.

  5. Agent Harness (opens in a new tab)

    Microsoft Learn (Agent Framework)2026Documentation

    Used for The conditional line-edit tool that takes the expected line text, and its experimental status.

References

References & Sources (2 of 2)

  1. Introducing advanced tool use on the Claude Developer Platform (opens in a new tab)

    Bin Wu2025Article

    Used for Approximate token costs of loading many tool definitions versus using a tool-search step.

  2. Idempotent requests (opens in a new tab)

    Stripe2026Documentation

    Used for How idempotency keys let a retry return the saved result and reject reuse with different parameters.