The agent loop and tool design

  • Advanced
  • 35 min
  • Lesson 2 of 7 in Harness engineering
  • Last verified

Open slides(27 slides)

Before you start

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.

Diagram: One turn of the loop.

no

yes

no

yes

no

yes

continue

stop

Assemble context

Model call

Tool calls?

Verified done?

Return result

Feed the failure back

Permitted?

Return DENIED or ask a human

Execute

Observe: shorten, offload, redact

Log and checkpoint

Stop checks

Stop with a reason

Diagram summary: One turn of the loop. A reply with no tool call goes to a verification check before the run ends; a proposed call goes through a permission check, execution, shortening of the output, logging and checkpointing, and then the stop checks.

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 resultWhat the model can do with it
Error 500Nothing useful, so it tends to retry the same call
FileNotFoundError: [Errno 2] plus a tracebackLittle: 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:

Python

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

This 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_id over user). 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 neededabout 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.

Diagram: A long tool output is split.

Tool runs: thousands of lines

Save the full output to a file

Keep first and last lines in context

Tell the model the file path
and how to search it

Redact secrets and personal data

Context gets a short, useful result

Diagram summary: A long tool output is split. The full text goes to a file, a short head and tail stays in context after secrets are redacted, and the model is told where the file is and how to search it. The window stays small without losing the detail.

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 toolsA general shell
Easy to audit, approve and constrainFew definitions, very capable, composable
Many definitions; gaps when you did not foresee a needLarge blast radius: needs a sandbox, allow and deny lists, timeouts and output caps
Output is shaped by youOutput 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.

Diagram: The harness normally saves what it needs after each step, including which side effects already happened.
Tool or serviceCheckpoint storeHarnessTool or serviceCheckpoint storeHarnesscrash before the checkpoint is savedstep 7: create_ticket (key run1-s7)okresume: load last checkpoint (step 7 not recorded)replay step 7 with key run1-s7already done, same result, no duplicatecontinue with step 8
Diagram summary: The harness normally saves what it needs after each step, including which side effects already happened. Here the crash hits after the tool ran but before the save, so on resume the checkpoint does not show step 7 and the harness replays it. Because the tool recognises the idempotency key, the repeat does not create a duplicate.

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 search with 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.

Resources & Further Reading

Checked sources to go deeper. The essential ones come first in each group.

Official documentation

Further reading

Research papers

Hands-on

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.

0 of 12 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveExplain why the model proposes and the harness disposes, and why a model's claim that it is done is a hypothesis the harness verifies.

  1. Question 1 of 12Your agent replies "All tests pass, task complete" without calling any tool. What should the harness do?

    Choose one answer.

  2. Question 2 of 12Why is "the model emitted no tool call" a weak definition of done?

    Choose one answer.

ObjectiveTurn tool failures into results an LLM can act on, and keep infrastructure retries out of the model's step budget.

  1. Question 3 of 12A search tool times out for a moment because of network trouble. Which handling does the lesson recommend?

    Choose one answer.

  2. Question 4 of 12Which of these tool results are written so that a model can act on them? Select all that apply.

    Choose all that apply.

ObjectiveDesign a small set of tools for an agent: few and non-overlapping, hard to misuse, with readable, token-efficient output.

  1. Question 5 of 12An agent has 40 tools. Many overlap and are described as "gets data", and it often picks the wrong one. What is the best first change?

    Choose one answer.

  2. Question 6 of 12A lookup tool feeds an agent that must pick its next action. Which result design is best?

    Choose one answer.

  3. Question 12 of 12An agent edits files by line number, and a stale number made it overwrite the wrong line. Which tool change makes that mistake harder?

    Choose one answer.

ObjectiveKeep a large tool catalog and large tool outputs from filling the context window, and weigh a general shell tool against narrow tools.

  1. Question 7 of 12Forty tool definitions of about 500 tokens each are loaded before every task. What does this cost, and what is one fix?

    Choose one answer.

  2. Question 8 of 12Which are sound ways to handle a very large tool output? Select all that apply.

    Choose all that apply.

  3. Question 11 of 12Why might a team give an agent a sandboxed shell as well as its structured tools?

    Choose one answer.

ObjectiveMake a long run resumable, explain why replay is safe only with idempotent tools, and treat tool schemas as a versioned interface.

  1. Question 9 of 12A run crashes after send_invoice succeeded but before its result was saved. On resume the step runs again. What prevents a duplicate invoice?

    Choose one answer.

  2. Question 10 of 12You rename a tool and change one of its arguments. Why re-run your evaluation tasks?

    Choose one answer.