CertSafari
    Anthropic Claude Certified Architect – Professional (CCAR-P)· Lessons

    Domain 1 · Lesson 2/38

    End-to-end agent architecture: the loop, tool execution and feedback

    Design end-to-end architectures

    19 min read
    2.83% of exam
    8 sources
    Published 19 Oct 2026
    Docs as of 14 Oct 2026

    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.

    What the application does for each stop_reason
    stop_reasonWhat it meansWhat your code does next
    tool_useClaude wants one or more tools runRun them, send tool_result blocks, call again
    end_turnClaude produced its final answerLeave the loop and deliver the output
    max_tokens, stop_sequence, refusalClaude stopped for some other reasonLeave the loop and handle that case explicitly
    pause_turnA server-side tool loop hit its iteration cap with work still to doSend 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.

    Sources123

    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.

    Where each kind of tool sits in the architecture
    Tool kindWho executesYour loop's job
    User-defined client toolYour applicationRun the operation, return tool_result, drive the loop
    Anthropic-schema client tool (bash, text_editor, computer…)Your applicationSame as above; Claude calls it more reliably because the schema is trained-in
    Server tool (web_search, web_fetch, code_execution, tool_search)AnthropicEnable 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?

    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?

    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?

    Sources24

    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?

    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?

    Sources56

    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.

    Agent SDK (Python): hook callbacks registered through HookMatcher; a PostToolUse entry takes the same list shapepython
    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.

    The event that starts an outcome-oriented session (max_iterations is optional: default 3, max 20)json
    {
      "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.

    How each outcome evaluation result routes the loop
    resultWhat happens next
    satisfiedSession transitions to idle
    needs_revisionAgent starts a new iteration cycle with the grader's feedback
    max_iterations_reachedOne final acknowledgment turn, then idle; no further evaluation
    failedSession goes idle; the rubric does not apply to the deliverables
    interruptedThe 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?

    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
    }

    Checkpoint 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?

    Sources178

    Sources

    (8)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “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. 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. 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. 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. 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. 6.
      “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. 7.
      “Tool name or pattern to match (e.g., "Bash", "Write|Edit")”
      ↩︎ Feedback loops that correct the run
    8. 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

    Ready to test yourself?

    Practise the 12 questions on this subdomain.

    Spotted a mistake, or was something unclear? Tell us.