2.2 Agentic Loops and the Claude Agent SDK

Key Takeaways

  • Every agent runs the same loop: gather context, take action through tools, verify the result, then repeat until a stop condition is met.
  • The Claude Agent SDK packages this loop with built-in tool execution, the agentic file/bash toolset, subagents, hooks, and session management so you do not hand-roll the orchestration.
  • Bound every loop with explicit stopping conditions — a maximum turn or token budget, a cost ceiling, or a success check — so a stuck agent cannot run away.
  • Verification is the step most candidates forget: an agent that acts without checking the result hallucinates progress; pair actions with tests, validators, or a fresh-context reviewer.
  • Server-managed agents (Managed Agents) run the loop and host the tool sandbox on Anthropic's side; the Agent SDK runs the loop client-side in your own process.
Last updated: June 2026

The Agentic Loop, Step by Step

Underneath every Claude agent — whether you build it with the Messages API by hand, the Claude Agent SDK, or server-managed Managed Agents — is one repeating loop. Anthropic describes it as three phases that cycle until the task is done:

  1. Gather context. The model pulls in what it needs: the user request, retrieved documents, file contents, prior tool results. Context is finite, so this phase is also about pruning what is no longer relevant.
  2. Take action. The model emits a tool_use block. Your executor (or the SDK) runs the real function — read a file, run a shell command, query an API — and returns a tool_result.
  3. Verify the work. The model inspects the result. Did the test pass? Did the file actually change? Is the answer grounded in the retrieved context? If not, it loops back to gather more context and act again.

The loop ends on a stop condition: the task is verified complete, a turn or token budget is exhausted, a tool returns a terminal error, or a human declines an approval. An agent without an explicit stop condition is the classic CCA-F distractor — it can spin forever, burning cost and risking destructive actions.

What the Claude Agent SDK Gives You

The Claude Agent SDK is Anthropic's framework (available for TypeScript and Python) for building agents on top of the same loop. It exists so you do not re-implement orchestration, tool plumbing, and session handling for every project. The exam tests recognition of what the SDK provides rather than line-by-line syntax.

SDK capabilityWhat it doesWhy it matters on the exam
Agent loopRuns gather-act-verify automatically, calling the API and executing toolsYou declare tools and a prompt; the SDK drives the loop
Built-in toolsetFile read/write/edit, bash, glob, grep, web fetch and searchCovers the common agent actions without custom code
Custom toolsYour own functions exposed with a JSON schemaConnect the agent to your systems under least privilege
SubagentsScoped child agents with their own context and toolsIsolate a specialist task; protect the main context window
HooksDeterministic code fired at lifecycle events (before/after a tool)Enforce policy the model cannot skip — gate or validate actions
Session managementPersist and resume conversation state across runsLong or interrupted tasks continue where they left off
MCP integrationAttach Model Context Protocol servers as tool sourcesReuse external integrations through a uniform interface

The SDK is client-side: the loop runs in your process, and tools execute on your infrastructure. That is the opposite of server-managed Managed Agents, where Anthropic runs the loop and hosts a sandbox container — a distinction the exam draws (covered in 2.3).

Bounding the Loop: Stopping Conditions and Budgets

The most testable reliability control for an agent is the bound on its loop. A correct agent answer almost always names at least one of these:

  • Max turns / max tool calls. A hard ceiling on iterations. If the agent has not finished in N steps, it stops and escalates rather than looping.
  • Token or cost budget. A spend cap so an expensive model in a tight loop cannot produce a surprise bill. The Anthropic API exposes a task budget concept that lets the model see a running countdown and wrap up gracefully, distinct from max_tokens, which is an enforced per-response ceiling the model is not aware of.
  • Success check. A programmatic test (tests pass, schema validates, the target file exists) that ends the loop the moment the goal is verifiably met.
  • Timeout. A wall-clock limit so a hung tool call cannot stall the whole task.

Worked numeric example: an agent runs at most 8 turns, each turn averages 3,000 input and 800 output tokens, and you cap spend at a task budget. At roughly $5 per million input and $25 per million output tokens for a mid-tier model, one turn costs about (3,000 / 1,000,000 x $5) + (800 / 1,000,000 x $25) = $0.015 + $0.020 = $0.035, so 8 turns is about $0.28 per task before caching. Prompt caching the stable system prompt and tool definitions can cut the input share to roughly a tenth. The point for the exam is that you can reason about the bound, not memorize prices.

Verification Is Not Optional

The phase candidates most often drop is verify. An agent that acts and immediately reports success — without checking the result — is the source of the confident-but-wrong failure the exam loves to describe. Build verification in:

  • For code agents: run the test suite or a linter after an edit (a Claude Code PostToolUse hook does this deterministically). Treat a green suite as the success signal, not the model's own claim.
  • For retrieval/Q&A agents: require the answer to cite the retrieved passages, and plant an eval question whose answer is not in the context to confirm the agent abstains instead of fabricating.
  • For high-stakes agents: use a separate, fresh-context reviewer (a subagent or a second model call) to check the work, because a model critiquing its own long transcript is biased toward declaring success.

Anthropic's framing is that the verify step is what converts a plausible action into a trustworthy one. On the exam, an option that adds an explicit verification or test gate beats an option that simply adds another retry or a stronger model.

Mapping Loop Phases to Failure Modes

Loop phaseIf it is weakControl that fixes it
Gather contextStale or bloated context degrades answersRetrieve fresh data; prune old turns; compact history
Take actionWrong tool or over-broad permissionLeast-privilege tools; clear tool descriptions
VerifyAgent declares false successTests, schema validation, fresh-context reviewer
Stop conditionLoop runs awayMax turns, task budget, timeout, success check

Reading a scenario, locate which phase is failing and reach for the matching control rather than stacking every control at once. That targeted matching is the behavior the CCA-F measures.

Test Your Knowledge

Which sequence correctly describes the core agentic loop that the Claude Agent SDK runs?

A
B
C
D
Test Your Knowledge

An agent built with the Claude Agent SDK keeps editing files and reporting success, but a reviewer later finds the changes never actually pass the tests. Which improvement most directly addresses this?

A
B
C
D