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.
share
watch the video
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:
- Send the conversation with your
toolsarray. - 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". - Run each tool and build a tool_result, a block carrying that call's id and the tool's output.
- Send the whole conversation again: Claude's reply, then a user message holding the tool_result blocks.
- 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
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.
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.
- Only a
successresult carriesresulttext, and a single-shotquery()raises after any error result. - Managed Agents always runs the loop; a
self_hostedenvironment moves only tool execution onto your infrastructure. - PreToolUse can stop a tool call, while PostToolUse runs after it and can never undo it.