Three Ways to Build the Loop: Agent SDK, Custom Loop, and Managed Agents
CoreConstruct Claude agents with the Agent SDK, custom loops, and hooks · Difficulty 2/5
Explanation
Three Ways to Build the Loop
Once a task has earned agentic autonomy, there are three legitimate wiring paths, ordered by how much of the runtime you own:
- Custom agent loop / harness -- you write the loop yourself over the Messages API: send messages, receive
tool_useblocks, execute the tools, feed backtool_resultblocks, repeat untilstop_reasonis `end_turn`. Maximum control, and every behavior a managed layer would give you for free -- context management, retries, parallel tool handling -- becomes code you own. - **Claude Agent SDK** -- Anthropic's framework, running that identical loop but *inside your own process this time*, taking tool execution, context management, and the iteration mechanics off your plate while giving you built-in tools, session handling, subagents, and hooks out of the box. Reach for this when the SDK's managed mechanics and Anthropic-maintained tooling already cover what you need.
- Claude Managed Agents (public beta) -- Anthropic runs the loop *and* the execution sandbox for you, off in Anthropic's own infrastructure rather than your process. Your application registers the agent's definition a single time -- model, system prompt, tools, MCP servers, skills -- keeps a lookup reference to it, feeds in user events, and reads the response back through a server-sent event stream.
The choice is not about which is "more advanced" -- it is about how much infrastructure you're willing to hand off, and what your compliance constraints allow. Whichever path you pick, the underlying tool-use loop is identical; what changes is who runs each iteration.
Claude Managed Agents: The Trade Underneath the Convenience
A raw loop or the Agent SDK still puts your own code in the driver's seat for every pass through the cycle: issue the call, parse the tool-use blocks, run the tools, append what came back. Under Managed Agents that entire cycle moves off your machine -- Anthropic's own orchestration handles each turn and a hosted sandbox actually runs the tool calls, leaving your application with a much narrower job: register the agent as a resource once, and then just push events in and read the event stream that comes back.
| Category | What moves off your plate | What you pick up in exchange |
|---|---|---|
| Execution & infrastructure | Iteration itself, the sandbox that runs tools, retries inside the loop, the whole tool-execution runtime | A resource definition you version, plus a thin layer in your app for sending events and reading the stream back |
| Session duration & state | Keeping a long session alive -- these can run for a long time without your process ever holding the connection open | State that lives server-side, under Anthropic's own retention rules rather than yours |
| Sandbox lifecycle | Spinning the sandbox up and tearing it down around each tool call | Whatever the managed sandbox happens to expose -- you're constrained to its tool and execution model instead of your own setup |
Reach for Managed Agents specifically where a task's duration makes holding a loop open in-process impractical, where standing up and hardening your own sandbox isn't something you want to take on, or where handing off the loop, sandbox, and execution runtime entirely is simply the tradeoff you'd rather make.
The Constraint That Rules Managed Agents Out: ZDR and HIPAA
Managed Agent sessions being stateful and stored server-side is the same property that lets a session run for hours unattended -- and it's also exactly what keeps Managed Agents **off the list of options eligible for a Zero Data Retention agreement or a HIPAA BAA** today. A workload carrying PHI, or one bound by a ZDR commitment, simply can't use this path, however well it would otherwise fit -- the Agent SDK or a self-built loop on an approved configuration is where that work has to go instead. This isn't a matter of taste; the constraint overrides convenience, speed of setup, or how much nicer the managed path would be to build.
Teams often start by building against the Agent SDK on a laptop, then migrate to Managed Agents once the behavior is proven out and nothing regulatory blocks the move. What carries over is the agent's concept -- its prompt, its tools, its model choice -- but not the code as-is: it has to be re-expressed, not exported wholesale. The Agent SDK's agent lives in code and filesystem config; Managed Agents' version of the same agent is a versioned resource (POST /v1/agents) that a session looks up by ID.
Deployment Models (Self-Hosted vs. Anthropic-Hosted)
| Model | Character |
|---|---|
| Anthropic-hosted / managed (Agent SDK's hosted option, or Managed Agents) | Anthropic runs some or all of the agent infrastructure; less operational burden, less control over the environment |
| Self-hosted (in-process) | You run the loop and tools in your own environment; maximum control over data flow, networking, and least-privilege boundaries, at the cost of operating it yourself |
Neither option is universally correct: the decision trades operational burden against control over data residency, networking, and least privilege -- and for regulated data, that tradeoff may not even be a choice (see the next concept).
Common exam traps
- Assuming there are only two ways to build an agent loop. A scenario that mentions a hosted, versioned, event-streamed agent definition with no loop code in your own process is describing Managed Agents, not the Agent SDK.
- Assuming "managed/hosted" always wins because it's less work. Self-hosting gives tighter control over data residency and least privilege -- a legitimate, sometimes required, reason to run the loop yourself. For PHI or ZDR workloads, self-hosting isn't just preferred, it's the only option Managed Agents' storage model permits.
- Assuming the Agent SDK and a custom loop are mutually exclusive skill levels rather than a tradeoff between managed convenience and full control.
Key Takeaways
- There are three wiring paths for an agent loop: a custom loop over the Messages API (full control, full responsibility), the Claude Agent SDK (managed loop running in your own process), and Claude Managed Agents (Anthropic runs the loop and the sandbox server-side, public beta)
- With Managed Agents you define the agent once as a versioned API resource, refer to it by ID, and stream results back over server-sent events -- you stop owning the loop, the sandbox, and in-loop retries
- Managed Agent sessions are stateful and stored server-side, which is exactly why they are NOT currently eligible for Zero Data Retention (ZDR) or a HIPAA Business Associate Agreement (BAA) -- PHI or ZDR workloads must use the Agent SDK or a raw loop instead
- A common progression is prototyping on the Agent SDK, then moving to Managed Agents for production -- expect a re-expression of the agent definition as a versioned resource, not a direct code export
- Anthropic-hosted deployment lowers operational burden; self-hosted deployment maximizes control over data flow, networking, and least privilege -- and for regulated data, the choice may be made for you
Glossary Terms
The choice of where an agent's loop and tools run: Anthropic-hosted/managed (Anthropic runs the infrastructure, lowering operational burden but reducing environment control) versus self-hosted/in-process (the developer runs the loop and tools in their own environment, maximizing control over data flow, networking, and least privilege at the cost of operating it themselves). Neither option is universally correct -- the decision trades operational burden against control over data residency and least privilege.
Anthropic's Python SDK for building agentic applications with Claude. Provides primitives for agentic loop management, subagent orchestration, tool integration, and lifecycle hooks. Imported as `claude_agent_sdk`. Removes the boilerplate of raw-API agentic loops so architects can focus on design rather than plumbing.
A stop_reason value indicating Claude finished its response naturally without hitting a limit or requesting a tool. In agentic loops, this signals the loop should stop and the final response should be presented to the user.
A field in the Claude API response indicating why the model stopped generating. Values: 'end_turn' (natural completion), 'max_tokens' (hit limit), 'stop_sequence' (hit custom stop), 'tool_use' (wants to call a tool). The primary signal for controlling agentic loops.
A content block type in the user message that returns the output of a tool execution back to Claude. Must include the 'tool_use_id' matching the original tool_use block. Can be text, images, or error messages. Claude processes the result and continues reasoning.
A content block type in Claude's response indicating the model wants to call a specific tool. Contains 'id', 'name', and 'input' fields. The agent must execute the tool and return results in a tool_result content block for the conversation to continue.
The US Health Insurance Portability and Accountability Act, governing the protection of protected health information (PHI). Design implications include using HIPAA-eligible services and business associate agreements, and restricting or redacting PHI across the pipeline rather than assuming the model alone is compliant. Compliance is a property of the whole system -- data handling, access, retention, and contracts -- not of the model in isolation.
Related Concepts
Hooks as Deterministic Guardrails
Hooks (PreToolUse, PostToolUse) are code callbacks at fixed points in the agent loop and behave deterministically
Regulated-Data Deployment Constraints: Privilege, HIPAA, GDPR, and FedRAMP
A regulated-data constraint (privilege, HIPAA, GDPR, FedRAMP, internal residency policy) decides the endpoint, credentials, and log destination before any prompt/tool/memory design choice is made
Recurring Agent Patterns and Abstraction Frameworks
The tool-use loop -- emit tool_use, execute, return tool_result, continue -- is the core agent cycle, grounded in real environment feedback