Task statement 1.2 · Agents and workflows

1.2 · Agent Construction with Claude

Shelfwise, the course example, is built with the Python Agent SDK and runs as a long-lived service on infrastructure the team operates. Construction decides who writes the loop that calls Claude and runs tools, what limits it, where it runs, and which code runs on every tool call.

watch the video

Part 1 of 3 · Write your own agent loop or use the Agent SDK? · 4:57

Building an agent: 3 parts · 15 min, with chapters

Why it's tested

The tempting start is to hand-write the tool loop, because its core fits on one screen. It fails in production because those lines carry none of the harness: no turn or budget limit, no tool errors passed back, no context management and no log. The opposite mistake is a full agent runtime, with its subprocess and session files, when you need none of its sessions, permissions or hooks.

Start hereTwo terms this section adds

harness
The code around an agent loop that runs tools, enforces limits, handles errors, manages context and logs each step.
hook
A callback that runs your code at a fixed point in the agent loop, such as before a tool call, with no model involved.

KnowledgeThe Claude Agent SDK: the agent loop as a library

The Claude Agent SDK packages Claude Code's agent loop, built-in tools and context management as a Python or TypeScript library. It starts a Claude Code subprocess (5.2) that runs tools for Claude until Claude stops calling tools. In Python, query() starts a new session on each call, while ClaudeSDKClient holds one open across exchanges and can interrupt it. Both take ClaudeAgentOptions. Its allowed_tools pre-approves listed tools but leaves others available, so to remove a tool, use disallowed_tools or a tools list without it. Its system_prompt takes your own string or the claude_code preset (2.5).

Neither loop limit has a default, so the loop stops only when Claude stops calling tools. max_turns caps tool-use round trips, and max_budget_usd stops the query at an estimated cost. The stream ends with a ResultMessage whose subtype is success, error_max_turns, error_max_budget_usd, error_during_execution or error_max_structured_output_retries. Every subtype carries cost, turn count and session ID, but only success carries result. A single-shot query() raises after an error result, so a long-lived service wraps it in try.

KnowledgeCustom agent loops and harnesses

Under every agent sits the raw loop on the Messages API, the Claude API endpoint that returns one response per request and keeps no state. For tools your code executes, stop_reason, the field that says why Claude stopped, drives the loop:

  1. Send the conversation with your tools array.
  2. Claude asks for tools. Each call is a tool_use, a content block naming one tool and its input, and stop_reason is then "tool_use".
  3. Run each tool and build a tool_result, a block carrying that call's id and the tool's output.
  4. Send the whole conversation again: Claude's reply, then a user message holding the tool_result blocks.
  5. Repeat while stop_reason is "tool_use". The value end_turn means a final answer, and max_tokens, the output cap, needs handling of its own.

A harness is everything else a production loop needs: an iteration cap, a failing tool's error returned to Claude with is_error: true instead of a crash, a conversation kept inside the context window, and a log of each call. The client SDKs' tool runner, in beta, is a middle path: Python's client.beta.messages.tool_runner() runs @beta_tool functions, returns their exceptions as is_error results and stops at max_iterations. The docs prefer the manual loop when a step needs approval, custom logging or conditional execution. Write your own loop for that control over your own functions, and take the Agent SDK when the agent needs files, a shell, sessions and permissions.

KnowledgeManaged agent deployment models: self-hosted vs. Anthropic-hosted

An Agent SDK agent is self-hosted. Each session is a subprocess that owns a shell, a working directory and transcripts on local disk, so you run it in your container, choose an ephemeral, long-running or hybrid pattern, and add a SessionStore if transcripts must outlive a restart. The Anthropic-hosted model is Claude Managed Agents, in beta. You create an agent (/v1/agents), an environment (/v1/environments) and a session (/v1/sessions), then send user events and read progress as server-sent events (SSE), a one-way HTTP stream. Anthropic runs the loop, stores the history and, by default, runs tools in its own cloud sandbox. It suits long-running, asynchronous work with minimal infrastructure, but because it stores sessions it is not eligible for zero data retention.

Interactive · who runs each part in each deployment model

Three deployment models side by side, each read from top to bottom: your app, the agent loop, where tools run, and where the session history is kept. Agent SDK, self-hosted: your app calls query(), a Claude Code subprocess you run executes the loop, tools run in your container, and transcripts sit on your disk or in a SessionStore. Managed Agents with a cloud sandbox: your app sends events through the API, and Anthropic runs the loop, runs tools in its cloud sandbox and stores the history. Managed Agents with a self-hosted sandbox: Anthropic runs the loop and stores the history, but each tool call is queued to a worker on your infrastructure. Agent SDK, self-hosted your app query() agent loop Claude Code subprocess tool call tools run in your container saved transcripts your disk or a SessionStore YOU RUN ALL FOUR Managed Agents, cloud your app events, SSE back agent loop run by Anthropic tool call tools run in Anthropic's cloud sandbox saved session history stored by Anthropic YOU RUN ONLY THE APP Managed Agents, self-hosted your app events, SSE back agent loop run by Anthropic queued tool call tools run on your worker result posted back session history stored by Anthropic YOU RUN THE APP AND THE TOOLS

Choose a deployment model to see who runs each part.

Agent SDK, self-hosted: your process starts a Claude Code subprocess, which runs the loop, executes tools in your container and writes transcripts to your disk or a SessionStore; only the model calls go out to the Claude API.

Managed Agents, cloud sandbox: your app creates a session and sends events; Anthropic runs the loop, executes tools in a sandbox it manages and stores the session's history, and streams progress back over SSE.

Managed Agents, self-hosted sandbox: Anthropic still runs the loop and stores the history, but each tool call is queued to a worker on your infrastructure, so files and processes stay there while tool inputs and outputs pass through Anthropic.

Each column reads downward. Blue is infrastructure you run, amber is Anthropic's, and the model is Anthropic's in all three.

More precise than the guide. The docs don't split hosting in two (as of 2026-10-04). Managed Agents always runs the loop, but a self_hosted environment sends each tool call to a worker on your infrastructure, so files and processes stay there, though tool inputs and outputs pass through Anthropic. Exam answer: self-hosted means you run the agent loop, usually the Agent SDK in your own container, and Anthropic-hosted means Managed Agents runs it, wherever its sandbox sits.

KnowledgeHooks for deterministic actions

Agent SDK hooks run in your own process. ClaudeAgentOptions.hooks maps an event name to HookMatcher entries, each holding a tool-name matcher such as "Write|Edit" and the callbacks. PreToolUse, the event before a tool runs, can return a permissionDecision of "allow", "deny", "ask" or "defer", or rewrite the call through updatedInput, and a deny holds even in bypassPermissions mode. PostToolUse, the event after a tool returns, can log the call or add additionalContext, but the tool has already run. The callback is ordinary code, so it acts on every matching call whatever Claude decides. Claude Code hooks are another layer: usually shell commands in .claude/settings.json, a settings file an SDK session reads only through setting_sources. 7.3 covers hooks as guardrails.

SkillWorked example: the lookup log that stayed empty

The shop owners asked for one log line per stock lookup, with branch, product and feed timestamp, so a disputed count can be traced. An engineer wrote it as a Claude Code hook, tested it in Claude Code and shipped it. A week later logs/lookups.jsonl held only those test lines:

# .claude/settings.json: Claude Code hook
"PostToolUse": [{"matcher": "mcp__stock__stock_lookup",
  "hooks": [{"type": "command", "command": "python hooks/log_lookup.py"}]}]
# service: ClaudeAgentOptions(setting_sources=[], ...)  no settings, no hook
# fix: Agent SDK hook
ClaudeAgentOptions(setting_sources=[], max_turns=4, max_budget_usd=0.03,
  hooks={"PostToolUse": [HookMatcher(matcher="mcp__stock__stock_lookup",
                                     hooks=[log_lookup])]})  logs lookups

The cause was the layer. The service passes setting_sources=[], so the shell hook ran only in the engineers' Claude Code sessions. As an Agent SDK callback, log_lookup runs in the service's process after successful lookups (4.1 adds failed ones), and PostToolUse fits because the log needs the tool's result. The same options cap a question at four tool-use turns, twice the usual, and $0.03, about twice a cold answer, which writes the cache. Shelfwise takes the self-hosted Agent SDK for a session per chat with resume, an MCP tool, permissions and hooks, though each answer is only three short requests. Only the weekly slow-stock review from 1.1, hypothetical and not built, would suit Managed Agents.

Before building an agent, ask: who should run the loop, and where must the tools run? Your code, over your own functions with a check between steps → your own Messages API loop. Your code, needing files, a shell and sessions → the Agent SDK in your container. Anthropic, for long-running asynchronous work → Managed Agents, with a self-hosted sandbox if tools must run inside your network.
Takeaway
  • Only a success result carries result text, and a single-shot query() raises after any error result.
  • Managed Agents always runs the loop; a self_hosted environment moves only tool execution onto your infrastructure.
  • PreToolUse can stop a tool call, while PostToolUse runs after it and can never undo it.

check yourself

0 / 3 answered

A payroll company's backend is written only in Java and runs as stateless Lambda functions. It wants Claude to answer HR admins' questions by calling three of its own read-only endpoints, two to four calls an answer, with its authorisation service approving each call first. Its API organisation has zero data retention, which every feature used must keep.Which construction approach meets these constraints with the least new infrastructure?

Select one.

A records team's Python Agent SDK agent tidies a shared drive. To protect folders under legal hold, the team registered a HookMatcher with matcher "Bash" under PostToolUse, whose callback returns permissionDecision "deny" for any command naming /legal-hold/. A log shows the callback ran on rm -r /legal-hold/2019 and returned deny within 40 ms, yet the folder is gone.What is the most likely root cause?

Select one.

A data team already runs its agents on Claude Managed Agents in cloud environments with limited networking. A new migration agent must run shell commands against a warehouse that is reachable only on the company's private network, and the security team will not open any inbound firewall port. Everything else about the agent stays as it is.Which TWO changes let the migration agent's tool calls reach the warehouse without opening inbound access?

Select two.

sources

  1. Claude Code Docs, "Agent SDK overview": the same tools, agent loop and context management that power Claude Code; the comparison of the Agent SDK, the Client SDK with its beta tool runner, and Managed Agents. Checked 2026-10-04.
  2. Claude Code Docs, "How the agent loop works": turns; max_turns and max_budget_usd, both "No limit" by default; the five ResultMessage subtypes; result only on success; a single-shot query() raises after an error result. Checked 2026-10-04.
  3. Claude Code Docs, "Agent SDK reference - Python": query() and ClaudeSDKClient; the ClaudeAgentOptions fields; allowed_tools "does not restrict Claude to only these tools"; HookMatcher. Checked 2026-10-04.
  4. Claude Code Docs, "Hosting the Agent SDK": the subprocess model and its local state; the ephemeral, long-running, hybrid and multi-agent patterns; SessionStore; Managed Agents as the hosted alternative. Checked 2026-10-04.
  5. Claude Code Docs, "Intercept and control agent behavior with hooks" and "Configure permissions": matchers, events, permissionDecision values, additionalContext, deny over every other decision; hooks run first, and a hook deny holds in bypassPermissions mode; settings-file hooks load through setting sources. Checked 2026-10-04.
  6. Claude Code Docs, "Automate actions with hooks": hooks give "deterministic control" rather than relying on the model to choose an action. Checked 2026-10-04.
  7. Claude API Docs, "How tool use works" and "Tool runner (SDK)": the client-tool loop keyed on stop_reason; the tool runner in beta, max_iterations, exceptions returned with is_error: true, and the manual loop for approval, custom logging or conditional execution. Checked 2026-10-04.
  8. Claude API Docs, "Claude Managed Agents overview", "Get started" and "Self-hosted sandboxes": beta status and header; agent, environment, session and events; /v1/agents, /v1/environments, /v1/sessions; when to use it; self_hosted environments and workers. Checked 2026-10-04.
  9. Claude API Docs, "API and data retention": Managed Agents is not eligible for zero data retention, because its sessions are stateful. Checked 2026-10-04.
  10. The lookup log, the stock server's mcp__stock__stock_lookup name and the turn and budget limits are this course's additions to Shelfwise; the weekly slow-stock review is hypothetical and not built.