What you will be able to do
- Trace a request through the agent loop from assembled input to final result, and name the stop condition that ends it
- Decide for each tool whether your code or Anthropic executes it, and what that means for your loop
- Judge when a tool, an MCP connection or a stronger model belongs in the processing stage
- Design feedback into a run with tool results, hooks and graded outcomes so the system corrects itself
Key concept
The agent loop — The cycle at the centre of every Claude-based system: the input is assembled, Claude answers with text or tool calls, the tools run, and their results go back to Claude. The cycle repeats until Claude gives a response with no tool calls, and that response is the output.
1.The agent loop from input to output
Every Claude-based architecture, from a single tool call to a multi-hour coding agent, runs the same cycle. Draw that cycle first and the rest of the design hangs off it: where the input comes from, what runs during processing, what counts as output, and where feedback comes back in.
Input is more than the user's message. Each time Claude is called it sees the prompt, the system prompt, the tool definitions and the conversation history so far. So the design decisions that shape every turn sit here: which tools to expose, what instructions to give, how much history to carry. The Agent SDK marks the start of a run with a SystemMessage of subtype init, which carries the session metadata.
Processing happens in turns. Claude looks at the current state and replies with text, one or more tool calls, or both. The tools run, and each set of results goes back to Claude for its next decision. One full pass of evaluate-then-execute is a turn, and an agent may take many turns before it finishes.
Output comes when Claude gives a response that contains no tool calls. In the Agent SDK that final text arrives as an AssistantMessage, followed by a ResultMessage that holds the final text, token usage, cost and session ID. Check the ResultMessage subtype as well, because a run can end by hitting a limit rather than by succeeding.
A worked case shows the shape. The task is to fix a failing auth test. In turn 1 Claude runs npm test through Bash and gets back three failures. In turn 2 it reads auth.ts and auth.test.ts. In turn 3 it edits auth.ts and runs the tests again, and all three pass. The final turn has no tool call, only the text "Fixed the auth bug, all three tests pass now." Nobody coded those steps in advance. Claude chose each one based on the result of the step before.
With the raw Messages API you write this loop yourself. It is a while loop keyed on stop_reason: if the reason is tool_use, run the requested tools, add the tool_result blocks to the conversation and send it again. Any other stop reason ends the loop, and your application has to handle each one.
| stop_reason | What it means | What your code does next |
|---|---|---|
| tool_use | Claude wants one or more tools run | Run them, send tool_result blocks, call again |
| end_turn | Claude produced its final answer | Leave the loop and deliver the output |
| max_tokens, stop_sequence, refusal | Claude stopped for some other reason | Leave the loop and handle that case explicitly |
| pause_turn | A server-side tool loop hit its iteration cap with work still to do | Send the conversation again, including the paused response |
You also have to decide who hosts the loop. The Messages API is best for custom agent loops where you want fine-grained control. Claude Managed Agents gives you a ready-made harness: you don't build your own loop, tool execution or runtime, and it suits long-running, asynchronous work.
Checkpoint 1 of 9· Match them up
Your application drives the agent loop with the raw Messages API. Match each stop_reason to what your code should do next.
Tap a term, then the definition that fits it.
Only tool_use keeps the client loop running. end_turn is the finished answer, and max_tokens is a different reason for stopping that your code must handle. pause_turn is not a finished answer: the server-side loop paused, so you send the conversation back, including the paused response, and Claude carries on.
“A paused turn means the work isn't finished; re-send the conversation (including the paused response) to let the model continue where it left off.”Source: platform.claude.com
2.Who executes tools: client tools versus server tools
Claude never runs a tool itself. It emits a structured request, something outside the model carries it out, and the result goes back into the conversation. The main design question for any tool is therefore where its code runs, because that decides what your application is responsible for.
Tools fall into three groups. User-defined client tools carry most tool-use traffic. You write the schema, run the code and return the result. Claude sees the schema and the result but never your implementation. Anthropic-schema client tools (memory, bash, text_editor, computer, browser) run the same way, in your code. The difference is that Claude was trained on these exact signatures, so it calls them more reliably and recovers from errors better than it would with a custom tool that does the same job. Server tools (web_search, web_fetch, code_execution, tool_search) run on Anthropic's infrastructure. You enable them in the request and never build a tool_result for them.
| Tool kind | Who executes | Your loop's job |
|---|---|---|
| User-defined client tool | Your application | Run the operation, return tool_result, drive the loop |
| Anthropic-schema client tool (bash, text_editor, computer…) | Your application | Same as above; Claude calls it more reliably because the schema is trained-in |
| Server tool (web_search, web_fetch, code_execution, tool_search) | Anthropic | Enable it and read the results; resend on pause_turn |
Client tools put a round trip in every call. The model can't run your code, so it asks, you execute, you report back, and it carries on. Server tools turn that around. A single request can set off several searches or code runs inside Anthropic's own loop, and the response arrives with the server_tool_use blocks already done. Your application usually just reads the answer.
That server-side loop has two exits to design for. It has an iteration cap, and hitting the cap returns pause_turn instead of end_turn. The work isn't finished, so send the conversation again with the paused response and the model picks up where it stopped. Second, if Claude calls a server tool and a client tool in the same group of parallel calls, the response comes back as tool_use with a server_tool_use block that has no result yet. The API runs it only after you return the client tool results.
Checkpoint 2 of 9· Check yourself
A support agent gets four tools: a custom lookup_order tool, text_editor, computer and web_fetch. When Claude calls one of them, which one never needs your application to run it and build a tool_result?
Only server tools (web_search, web_fetch, code_execution, tool_search) run on Anthropic's infrastructure, so you enable them and read the results. text_editor and computer are Anthropic-schema client tools. Like lookup_order, your code runs them and returns the tool_result.
“For web_search, web_fetch, code_execution, and tool_search, Anthropic runs the code. You enable the tool in your request and the server handles everything else.”Source: platform.claude.com
Sources2
3.When a tool belongs in the design at all
Every tool adds a round trip, so include one only when it does something text alone can't. Tool use fits four situations:
- Actions with side effects, such as sending an email or updating a record. The model can describe them, but only a tool can do them.
- Fresh or external data, such as current prices or the contents of your database.
- Output that must have a fixed structure, where a schema enforces the fields.
- Calls into existing systems, such as internal APIs, databases and filesystems.
A design smell gives it away. If you find yourself writing a regex to pull a decision out of model output, that decision should have been a tool call. The reverse case matters as much. Summarization, translation and general-knowledge Q&A need no tool. And when the response is trivial, a tool's latency can cost more than the work itself.
Integrations with several systems raise another question: does each one need its own hand-written execution code? An agent that reads a wiki, queries a ticket database and posts to chat could each be a user-defined client tool, with your loop checking stop_reason and calling a handler for each. That is three integrations to build and maintain. Connecting MCP servers instead exposes each system through one standardized protocol. Claude still decides when to call each tool. Managed Agents, for example, declares MCP servers on the agent and supplies credentials when each session is created. Choosing between MCP and other integration mechanisms is covered under connection protocols.
Two shortcuts fail for different reasons. Pasting the wiki, database and chat contents into the system prompt gives Claude a stale copy and no way to act. It can't post a reply or see a ticket that changed a minute ago. A precomputed decision tree that runs fixed API calls without the model removes the very thing the agent loop adds: the model choosing the next step from the last result.
Checkpoint 3 of 9· Check yourself
A ticket-triage service asks Claude to decide whether each ticket should be escalated. The code then runs a regex over the reply to find 'ESCALATE: yes' or 'ESCALATE: no', and the match breaks whenever the wording changes. What is the right design fix?
Using a regex to pull a decision out of model output is the design smell that shows the decision belongs in a tool schema, where a guaranteed shape replaces fragile parsing. Prompt tweaks still leave you parsing free text. A fixed decision tree removes the model choosing each next step, which is what the agent loop adds.
“if you're writing a regex to extract a decision from model output, that decision should have been a tool call.”Source: platform.claude.com
Checkpoint 4 of 9· Exam question
An architect is building an agent that must read internal wiki pages, query a ticketing database, and post replies to a chat tool. The team wants to avoid writing and maintaining custom tool-execution code for each integration and wants the agent to autonomously decide when to call each system. Which architecture choice best satisfies this?
Correct answer: A — Connect the agent to MCP servers for the wiki, database, and chat tool so each system is exposed through one standardized protocol
- A. Correct. MCP is the standardized protocol for connecting an AI application to external data sources and tools such as wikis, databases, and chat apps, letting the agent discover and call them without bespoke integration code for each system.
- B. Incorrect. A manual Client SDK tool loop requires the team to implement and maintain the tool-execution logic themselves, which is exactly the maintenance burden they want to avoid.
- C. Incorrect. Embedding all wiki, database, and chat content in every prompt does not scale, quickly exceeds practical context limits, and cannot perform live actions like posting a reply.
- D. Incorrect. A static decision tree removes the model's autonomous judgment about when to call each system, contradicting the requirement that the agent decide dynamically.
4.Sizing the processing stage
The model that does the processing sets most of the system's cost and latency, and choosing it is an architecture decision. The default is to start small and earn the upgrade. Start with a fast, low-cost Haiku model, test it on real inputs, and move up to a more capable model only where the tests show a capability gap. Detailed model trade-offs are covered under model selection.
Take a ticket-triage pipeline with a strict cost ceiling per ticket. Sending every ticket through the largest model at maximum effort pays for capability most tickets never use. Agentic systems often trade latency and cost for better task performance, and that trade has to be justified rather than assumed. Picking a model at random for each ticket averages the cost, but quality becomes unpredictable and the design has no idea which tickets needed more. Replacing Claude with a separately trained classifier throws away the reasoning about edge cases the task needs. The approach that holds up is to benchmark the small model on real tickets, then route only the hard cases upward.
Checkpoint 5 of 9· Check yourself
An insurer is designing a pipeline that classifies incoming claim documents. Each document has a strict cost ceiling, and edge cases still need careful reasoning. Which way of choosing the processing model holds up?
The default is to start small and move up only on evidence of a capability gap. Benchmarking the small model on real inputs and routing just the hard cases upward meets the cost ceiling without losing quality. Sending everything to the largest model wastes money, random picks make quality unpredictable, and a separate classifier loses the reasoning the edge cases need.
“Routing easy/common questions to smaller, cost-efficient models like Claude Haiku 4.5 and hard/unusual questions to more capable models”Source: www.anthropic.com
Checkpoint 6 of 9· Exam question
A team is designing the processing stage of a customer-support architecture. Support tickets arrive continuously and must be triaged with strong reasoning about edge cases, but the team has a strict per-ticket cost ceiling and wants to avoid over-provisioning intelligence. Which approach best fits the input-to-processing handoff for this architecture?
Correct answer: A — Start triage on Claude Haiku 4.5, benchmark it against real tickets, and only route to a stronger model when a capability gap appears
- A. Correct. This mirrors Anthropic's documented model-selection approach: start with a fast, cost-effective model, benchmark against real use-case data, and upgrade only when a concrete capability gap is found, which fits a cost-constrained triage stage.
- B. Incorrect. Routing everything through the most capable, highest-effort model ignores the stated cost ceiling and is not the recommended starting point for high-volume, straightforward triage.
- C. Incorrect. Random alternation is not a model-selection strategy Anthropic documents; it introduces unpredictable accuracy without any evaluation basis.
- D. Incorrect. Replacing Claude entirely with an external classifier abandons the reasoning capability the scenario requires for edge cases and isn't a supported architecture pattern for this trade-off.
5.Feedback loops that correct the run
A system corrects itself during a run only if feedback from its environment comes back into the loop. There are three places to design that feedback in, each more structured than the last.
Tool results are the basic feedback channel. In the auth-bug run, the first npm test result is what sent Claude to read the files, and the second run confirmed the fix. Design tools that report checkable facts, such as test results, validator errors or schema failures, and Claude can react to them on its next turn. A tool that only says "done" gives it nothing to correct against.
Hooks turn feedback into code that runs every time, whatever the model decides. The Agent SDK lets hooks intercept, modify or block a tool call before it runs (PreToolUse), and fire after a tool has run (PostToolUse). Each HookMatcher pairs a matcher pattern such as Write|Edit with a list of callbacks. To write an audit entry every time the agent changes a file, register a PostToolUse hook matched to Edit|Write whose callback appends the entry. Putting "remember to log your edits" in the system prompt depends on the model complying on every turn of a multi-hour run. Polling the filesystem from outside only guesses at what changed. Asking the user to confirm each edit is a human approval gate, not an audit log.
async def log_tool_use(
input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
) -> dict[str, Any]:
"""Log all tool usage for auditing."""
print(f"Tool used: {input_data.get('tool_name')}")
return {}
options = ClaudeAgentOptions(
hooks={
"PreToolUse": [
HookMatcher(
matcher="Bash", hooks=[validate_bash_command], timeout=120
), # 2 min for validation
HookMatcher(
hooks=[log_tool_use]
), # Applies to all tools (per-event default timeout)
],Graded outcomes close the loop on the whole deliverable, not on individual tool calls. In Claude Managed Agents you define an outcome: a description of done plus a rubric. The harness then sets up a grader that checks the artifact against the rubric in a separate context window, so the agent's own implementation choices don't sway it. The grader's explanation of which criteria passed or failed goes back to the agent for its next iteration. This is the evaluator-optimizer pattern built into the harness.
{
"type": "user.define_outcome",
"description": "Build a DCF model for Costco in .xlsx",
"rubric": { "type": "file", "file_id": "file_01..." },
"max_iterations": 5
}A grader is only as good as its rubric. It scores each criterion on its own, so "The data looks good" produces noisy verdicts while "The CSV contains a price column with numeric values" produces a clear one. The iteration cap is the loop's stop condition. Without it, a rubric the agent can never satisfy would keep the agent revising indefinitely.
| result | What happens next |
|---|---|
| satisfied | Session transitions to idle |
| needs_revision | Agent starts a new iteration cycle with the grader's feedback |
| max_iterations_reached | One final acknowledgment turn, then idle; no further evaluation |
| failed | Session goes idle; the rubric does not apply to the deliverables |
| interrupted | The session was interrupted while an outcome was active |
Checkpoint 7 of 9· Check yourself
In a Claude Managed Agents session started with user.define_outcome, what checks the finished artifact against the rubric, and why is it set up that way?
Defining an outcome makes the harness set up a separate grader. It checks the whole deliverable in its own context window, so the agent is not grading its own work, and its explanation goes back to the agent for the next iteration. Hooks act on individual tool calls, not on the whole deliverable, and your application doesn't build a verdict.
“The grader uses a separate context window to avoid being influenced by the main agent's implementation choices.”Source: platform.claude.com
Checkpoint 8 of 9· Fill the gap
If the agent can never satisfy the rubric, this outcome session must not keep revising forever. Which field sets that stop condition?
{
"type": "user.define_outcome",
"description": "Build a DCF model for Costco in .xlsx",
"rubric": { "type": "file", "file_id": "file_01..." },
" ? ": 5
}max_iterations caps how many grade-and-revise cycles the outcome loop runs. It is optional, defaults to 3 and can be at most 20. When the cap is reached, the result is max_iterations_reached, there is one final acknowledgment turn, and the session goes idle with no further evaluation.
Source: platform.claude.comCheckpoint 9 of 9· Exam question
A production agent built with the Claude Agent SDK runs multi-hour autonomous coding sessions. The architecture needs a feedback loop that automatically writes an audit-log entry to disk every time the agent edits or writes a file, without the model having to be asked to do this in every prompt. Which mechanism should the architect use?
Correct answer: A — Register a PostToolUse hook matched to the Edit and Write tools that runs a callback to append an audit entry after each call
- A. Correct. Agent SDK hooks such as PostToolUse run deterministic callback code at a defined point in the agent lifecycle, and matching on Edit and Write is the documented way to log file changes automatically without relying on the model to remember.
- B. Incorrect. Relying on a prompt instruction is not deterministic; the model could omit the step under context pressure, so it doesn't guarantee the audit log is written every time.
- C. Incorrect. External polling and diffing is a workaround that duplicates functionality hooks already provide, adds latency, and can miss or misattribute rapid changes.
- D. Incorrect. Requiring manual confirmation on every edit breaks the autonomous, multi-hour operation the scenario describes and is not what audit logging requires.
Sources
(8)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://code.claude.com/docs/en/agent-sdk/agent-loopOfficial docs
“Claude receives your prompt, along with the system prompt, tool definitions, and conversation history.”
↩︎ The agent loop from input to output“Each set of tool results feeds back to Claude for the next decision.”
↩︎ The agent loop from input to output“Check the subtype field to determine whether the task succeeded or hit a limit.”
↩︎ The agent loop from input to output“You can use hooks to intercept, modify, or block tool calls before they run.”
↩︎ Feedback loops that correct the run“Claude continues calling tools and processing results until it produces a response with no tool calls.”
↩︎ Key concept“You can use hooks to intercept, modify, or block tool calls before they run.”
↩︎ Exam trap 3 - 2.
“execute the tools and continue the conversation”
↩︎ The agent loop from input to output“The model never executes anything on its own.”
↩︎ Who executes tools: client tools versus server tools“The primary axis along which tools differ is where the code executes.”
↩︎ Who executes tools: client tools versus server tools“so it calls them more reliably and recovers from errors more gracefully than it would with a custom tool that does the same thing”
↩︎ Who executes tools: client tools versus server tools“You never construct a tool_result block for these tools.”
↩︎ Who executes tools: client tools versus server tools“The model can't run your code, so every tool call is a round trip”
↩︎ Who executes tools: client tools versus server tools“if you're writing a regex to extract a decision from model output, that decision should have been a tool call.”
↩︎ When a tool belongs in the design at all“Every tool call is at least one extra round trip; for lightweight tasks the overhead can exceed the work.”
↩︎ When a tool belongs in the design at all“For web_search, web_fetch, code_execution, and tool_search, Anthropic runs the code.”
↩︎ Exam trap 1“A paused turn means the work isn't finished; re-send the conversation (including the paused response) to let the model continue where it left off.”
↩︎ Exam trap 2“A paused turn means the work isn't finished; re-send the conversation (including the paused response) to let the model continue where it left off.”
↩︎ Checkpoint“The tools in this category are memory, bash, text_editor, computer, and browser.”
↩︎ Prediction“For web_search, web_fetch, code_execution, and tool_search, Anthropic runs the code. You enable the tool in your request and the server handles everything else.”
↩︎ Checkpoint - 3.
“Instead of building your own agent loop, tool execution, and runtime, you get a fully managed environment”
↩︎ The agent loop from input to output - 4.
“This gives the agent access to external tools, data sources, and services through a standardized protocol.”
↩︎ When a tool belongs in the design at all - 5.
“starting with a faster, more cost-effective model like Claude Haiku 5.5 can be the optimal approach”
↩︎ Sizing the processing stage“Test your use case thoroughly.”
↩︎ Sizing the processing stage - 6.https://www.anthropic.com/engineering/building-effective-agentsSecondary source
“Agentic systems often trade latency and cost for better task performance, and you should consider when this tradeoff makes sense.”
↩︎ Sizing the processing stage“Routing easy/common questions to smaller, cost-efficient models like Claude Haiku 4.5 and hard/unusual questions to more capable models”
↩︎ Checkpoint - 7.https://code.claude.com/docs/en/agent-sdk/pythonOfficial docs
“Tool name or pattern to match (e.g., "Bash", "Write|Edit")”
↩︎ Feedback loops that correct the run - 8.
“That feedback is handed back to the agent for the next iteration.”
↩︎ Feedback loops that correct the run“The grader scores each criterion independently, so vague criteria produce noisy evaluations.”
↩︎ Feedback loops that correct the run“optional; default 3, max 20”
↩︎ Feedback loops that correct the run“The grader uses a separate context window to avoid being influenced by the main agent's implementation choices.”
↩︎ Exam trap 4“The grader uses a separate context window to avoid being influenced by the main agent's implementation choices.”
↩︎ Checkpoint