Skip to main content

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).

#ApproachYou writeHarness & deploymentTools available
1Claude API — manual loopThe while stop_reason === "tool_use" loopYou build the harness; you hostOnly tools you define
2Claude API — tool runner (client.beta.messages.tool_runner)Just the tool functionsSDK supplies the loop (harness only); you hostOnly tools you define
3Managed Agents (beta, REST)Agent config plus your tool resultsAnthropic supplies the harness and hosts a per-session sandboxAnthropic-hosted sandbox (bash, files, code execution) plus Skills/MCP plus your tools
4Claude Agent SDKA prompt plus optionsSDK supplies the Claude Code harness (harness only); you hostBuilt-in Read/Write/Edit/Bash/Glob/Grep/WebSearch/WebFetch, plus MCP and subagents
Tool runner is not the Claude Agent SDK

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​

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 });
}

Four mechanical invariants:

  1. The assistant turn goes into history verbatim, including tool_use blocks and thinking blocks.
  2. Every tool_use block gets exactly one tool_result with a matching tool_use_id — a failed tool returns is_error: true, never a dropped block.
  3. All tool_result blocks for one assistant turn go in a single user message. Splitting them trains the model out of parallel calls.
  4. Parse tool_use.input with JSON.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.

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;

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 runsOn Anthropic's orchestration layerIn your process
Tool executionIn a per-session container Anthropic provisionsWherever your code runs
Config lifetimePersisted, versioned Agent objects; sessions pin to a versionWhatever your deploy pipeline says
StateServer-side session, streamed as eventsYours to store
SchedulingDeployments fire sessions on a cron cadenceYou run the scheduler
SecretsVault environment_variable credentials, substituted at egress, never visible in the sandboxYour own secret manager
Right whenYou want Anthropic to run the loop and host the workspace; long-running or scheduled sessionsYou 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 pointDeterministic use
Before a tool callBlock or require approval — refunds over a threshold, writes outside an allowed path, destructive shell commands
After a tool callNormalise heterogeneous results (timestamp formats, status codes) before the model sees them; redact secrets
Session start / endInject required context; emit an audit record
Before submit / on stopRun 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.

The exam's favourite pairing

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​

  1. 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?

  2. 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?

  3. 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?