1.2 Constructing agents with Claude
Four ways to build one
Two independent questions separate them: who supplies the harness (the loop plus context management) and who supplies the deployment (the infrastructure it runs on).
| # | Approach | You write | Harness & deployment | Tools available |
|---|---|---|---|---|
| 1 | Claude API — manual loop | The while stop_reason === "tool_use" loop | You build the harness; you host | Only tools you define |
| 2 | Claude API — tool runner (client.beta.messages.tool_runner) | Just the tool functions | SDK supplies the loop (harness only); you host | Only tools you define |
| 3 | Managed Agents (beta, REST) | Agent config plus your tool results | Anthropic supplies the harness and hosts a per-session sandbox | Anthropic-hosted sandbox (bash, files, code execution) plus Skills/MCP plus your tools |
| 4 | Claude Agent SDK | A prompt plus options | SDK supplies the Claude Code harness (harness only); you host | Built-in Read/Write/Edit/Bash/Glob/Grep/WebSearch/WebFetch, plus MCP and subagents |
They sound alike and are different packages. The tool runner lives inside the regular API SDK (anthropic / @anthropic-ai/sdk) and loops over tools you define — no built-in tools, no filesystem, no sandbox. The Claude Agent SDK (claude-agent-sdk / @anthropic-ai/claude-agent-sdk) is Claude Code packaged as a library, with built-in tools, hooks, subagents, permissions, and sessions. Options 1, 2 and 4 are all harness-only — you host them. Only Managed Agents adds managed deployment.
The manual loop
- TypeScript
- Python
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const messages: Anthropic.MessageParam[] = [
{ role: "user", content: "Reconcile invoice INV-4471 against the purchase order." },
];
while (true) {
const response = await client.messages.create({
model: "claude-opus-5",
max_tokens: 16000,
thinking: { type: "adaptive" },
system: SYSTEM_PROMPT,
tools: TOOLS,
messages,
});
messages.push({ role: "assistant", content: response.content });
if (response.stop_reason !== "tool_use") break;
const results = await Promise.all(
response.content
.filter((b): b is Anthropic.ToolUseBlock => b.type === "tool_use")
.map(async (block): Promise<Anthropic.ToolResultBlockParam> => {
try {
// Always JSON.parse the input — never string-match the serialization.
return {
type: "tool_result",
tool_use_id: block.id,
content: JSON.stringify(await dispatch(block.name, block.input)),
};
} catch (err) {
return {
type: "tool_result",
tool_use_id: block.id,
is_error: true,
content: String(err),
};
}
}),
);
// All results in ONE user message, one per tool_use block.
messages.push({ role: "user", content: results });
}
import json
import anthropic
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Reconcile invoice INV-4471 against the purchase order."}]
while True:
response = client.messages.create(
model="claude-opus-5",
max_tokens=16000,
thinking={"type": "adaptive"},
system=SYSTEM_PROMPT,
tools=TOOLS,
messages=messages,
)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
break
results = []
for block in response.content:
if block.type != "tool_use":
continue
try:
results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(dispatch(block.name, block.input)),
})
except Exception as err:
results.append({
"type": "tool_result",
"tool_use_id": block.id,
"is_error": True,
"content": str(err),
})
messages.append({"role": "user", "content": results})
Four mechanical invariants:
- The assistant turn goes into history verbatim, including
tool_useblocks and thinking blocks. - Every
tool_useblock gets exactly onetool_resultwith a matchingtool_use_id— a failed tool returnsis_error: true, never a dropped block. - All
tool_resultblocks for one assistant turn go in a single user message. Splitting them trains the model out of parallel calls. - Parse
tool_use.inputwithJSON.parse/json.loads. Escaping varies by model; string matching on the serialized input is a latent bug.
The tool runner
Same loop, written once by the SDK, with per-turn hooks for approval gates, logging, error interception, result modification, and retries.
- TypeScript
- Python
import Anthropic from "@anthropic-ai/sdk";
import { betaZodTool } from "@anthropic-ai/sdk/helpers/beta/zod";
import { z } from "zod";
const lookupInvoice = betaZodTool({
name: "lookup_invoice",
description: "Fetch one invoice by its INV-prefixed identifier.",
inputSchema: z.object({ invoice_id: z.string() }),
run: async ({ invoice_id }) => JSON.stringify(await db.invoice(invoice_id)),
});
const runner = client.beta.messages.toolRunner({
model: "claude-opus-5",
max_tokens: 16000,
tools: [lookupInvoice],
messages: [{ role: "user", content: "Reconcile INV-4471." }],
});
const final = await runner;
from anthropic import Anthropic, beta_tool
client = Anthropic()
@beta_tool
def lookup_invoice(invoice_id: str) -> str:
"""Fetch one invoice by its INV-prefixed identifier."""
return json.dumps(db.invoice(invoice_id))
runner = client.beta.messages.tool_runner(
model="claude-opus-5",
max_tokens=16000,
tools=[lookup_invoice],
messages=[{"role": "user", "content": "Reconcile INV-4471."}],
)
final = runner.until_done()
Choose the manual loop only when you need control the per-turn hooks cannot express, or you must avoid a beta dependency.
Managed agent deployment models
| Anthropic-hosted (Managed Agents) | Self-hosted (manual loop / tool runner / Agent SDK) | |
|---|---|---|
| Agent loop runs | On Anthropic's orchestration layer | In your process |
| Tool execution | In a per-session container Anthropic provisions | Wherever your code runs |
| Config lifetime | Persisted, versioned Agent objects; sessions pin to a version | Whatever your deploy pipeline says |
| State | Server-side session, streamed as events | Yours to store |
| Scheduling | Deployments fire sessions on a cron cadence | You run the scheduler |
| Secrets | Vault environment_variable credentials, substituted at egress, never visible in the sandbox | Your own secret manager |
| Right when | You want Anthropic to run the loop and host the workspace; long-running or scheduled sessions | You must own the compute, the network position, or a custom tool runtime |
Mandatory flow for Managed Agents: create the Agent once (POST /v1/agents), then a Session per run. model, system, and tools live on the agent, never on the session. Never call agent creation in the request path — store the returned agent ID.
Hooks for deterministic actions
A hook is application code the harness runs at a lifecycle point. It is the only way to make a rule hold every time, because prompt compliance is probabilistic.
| Lifecycle point | Deterministic use |
|---|---|
| Before a tool call | Block or require approval — refunds over a threshold, writes outside an allowed path, destructive shell commands |
| After a tool call | Normalise heterogeneous results (timestamp formats, status codes) before the model sees them; redact secrets |
| Session start / end | Inject required context; emit an audit record |
| Before submit / on stop | Run a formatter, linter, or test suite and feed failures back |
Full Claude Code hook mechanics, event names, and the exit-code contract are on 7.3 Claude hooks.
Tool selection problems are fixed by better tool descriptions. Tool compliance problems — ordering, thresholds, forbidden operations — are fixed by a hook or a prerequisite check. Confusing the two is worth several items.
Quiz
- Question 1
A custom agent loop continues while stop_reason is "tool_use" and stores the text of any other response as the final answer. Answers are occasionally truncated mid-sentence, and those responses carry stop_reason "max_tokens". Which change is correct?
- Question 2
A team wants a coding agent that reads and edits files in a repository, runs the test suite, and delegates exploration to subagents. It must run inside their own VPC, on their hardware. Which surface gets them there with the least code written?
- Question 3
The agent occasionally issues a refund above the $500 policy cap. The cap is already stated in the system prompt and repeated in the process_refund tool description. Auditors want a guarantee, not a lower rate. What do you add?
Links
- https://code.claude.com/docs/en/agent-sdk/overview
- https://code.claude.com/docs/en/agent-sdk/agent-loop
- https://code.claude.com/docs/en/hooks
- https://platform.claude.com/docs/en/agents-and-tools/tool-use/how-tool-use-works
- https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls
- https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons