What is the Claude Agent SDK? (2026 definition)
In short
The Claude Agent SDK is Anthropic's Python and TypeScript library for building production AI agents. It exposes Claude Code's harness — agent loop, built-in tools, permissions, subagents, and MCP integration — as a library you install and run in your own process. It is the renamed Claude Code SDK, repositioned in early 2026 for general-purpose agent work beyond IDE coding.
In early 2026 Anthropic renamed the Claude Code SDK to the Claude Agent SDK. Same harness, broader scope. The old name signalled an IDE tool; the new name signals what it actually is — the general-purpose library for building agents on Claude, in Python or TypeScript, with the same loop that powers Claude Code itself.
It ships as two packages: @anthropic-ai/claude-agent-sdk on npm and claude-agent-sdk on PyPI. Both bundle a native Claude Code binary — you do not install Claude Code separately, and you do not run a hosted service. The harness runs in your own process; deployment is your responsibility.
The public API is intentionally small. One primitive — query(prompt, options) — returns an async iterator over messages. As you iterate, the SDK drives the tool loop, places prompt cache breakpoints, retries transient failures, and yields each intermediate step (reasoning, tool call, tool result) plus the final outcome. Everything else in the SDK — permissions, hooks, subagents, MCP loader, sessions, skills — is an option you pass into that call.
It is worth naming three related but distinct products to prevent confusion, because picking the wrong one is the most common expensive mistake we see teams make on their first Anthropic build:
- Claude Agent SDK — a library. You host, you scale, you observe. The subject of this guide.
- Managed Agents — Anthropic hosts both the loop and a sandbox. You call a REST endpoint and get an agent back. Different product, different billing, different trust boundary.
- Raw Anthropic SDK (Client SDK) — an HTTP client only. No harness, no built-in tools. You own the entire tool loop yourself.
Alice Labs runs the Claude Agent SDK across 100+ production deployments as an Anthropic Partner, primarily in the Nordics and broader Europe. The rest of this guide is organised around what actually breaks in those deployments — and what to do about it. For a broader comparison with LangGraph, CrewAI, and AutoGen, see our best AI agent frameworks guide for 2026.
Anthropic renamed the Claude Code SDK to the Claude Agent SDK
Claude Agent SDK vs Claude API (Client SDK): when to use which
In short
Use the Claude Agent SDK when the job is coding, filesystem, or research-shaped — you inherit Claude Code's loop, tools, permissions, and MCP loader for free. Use the raw Claude API (Client SDK) when the loop is narrow and custom — extraction, classification, single-turn RAG — and you want to define every tool yourself with no built-in filesystem or shell access.
Anthropic publishes a direct comparison table between the two SDKs, and the delta is larger than most teams expect. The Client SDK (@anthropic-ai/sdk, anthropic) is a thin HTTP client. You write the tool loop yourself — a while-loop over stop_reason === "tool_use", dispatching to functions you provide, appending tool results, and calling again. It exposes zero built-in tools.
The Agent SDK ships the loop, and it ships Claude Code's full set of built-in tools (Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch). It also ships context management, four permission modes, hooks, sessions, subagents, an MCP loader, skills, and slash-command support. All of it is inherited from Claude Code and behaves the same way.
If your project language is not Python or TypeScript, you can still drive the same harness — run the Claude Code CLI as a subprocess with -p "<prompt>" --output-format json. This is the escape hatch for Go, Rust, Java, and .NET codebases. The behaviour is identical because the underlying binary is the same.
Claude Agent SDK vs Claude API (Client SDK)
| Dimension | Claude Agent SDK | Claude API (Client SDK) |
|---|---|---|
| Agent loop | Built-in — SDK owns it | You write it yourself |
| Built-in tools | 8 tools — filesystem, shell, web | None — define every tool |
| Subagents | First-class via Agent tool | Manual — nested API calls |
| MCP integration | Native loader — stdio/http/sse/in-process | Not included |
| Permissions & hooks | 4 modes, PreToolUse/PostToolUse hooks | You implement |
| Best for | Coding, filesystem, research, multi-step | Extraction, classification, narrow single-turn tool loops |
The Alice Labs rule of thumb: if the agent needs to read or write files, run shell commands, spawn helpers, or coordinate across MCP-connected systems — pick the Agent SDK. If the agent is a fixed-shape tool loop over a few internal functions — pick the Client SDK. Mixing them in a single service is fine and common.
Installing the Claude Agent SDK and running your first query
In short
Install with npm install @anthropic-ai/claude-agent-sdk (Node.js 18+) or pip install claude-agent-sdk (Python 3.10+). Set ANTHROPIC_API_KEY in the process environment. The SDK bundles a native Claude Code binary — no separate install needed. The minimal working agent is 12 lines and handles orchestration, retries, and tool execution for you.
The install is deliberately boring. In TypeScript:
npm install @anthropic-ai/claude-agent-sdk # Node.js 18+ required
In Python — pip or uv, either works:
pip install claude-agent-sdk # or uv add claude-agent-sdk # Python 3.10+ required
Both packages bundle a native Claude Code binary. You do not install Claude Code separately, and you do not need to have Claude Code running. The SDK spawns the binary behind the scenes when you call query().
Authentication reads ANTHROPIC_API_KEY from the process environment. This catches a lot of first-time users, so it is worth stating: the SDK does not automatically load a .env file. Load it yourself (dotenv in Node, python-dotenv in Python) before you call query().
Third-party model providers work via environment flags — set the one that matches your infrastructure:
CLAUDE_CODE_USE_BEDROCK=1— AWS BedrockCLAUDE_CODE_USE_ANTHROPIC_AWS=1— Anthropic-on-AWSCLAUDE_CODE_USE_VERTEX=1— Google Vertex AICLAUDE_CODE_USE_FOUNDRY=1— Azure AI Foundry
The minimal working agent in TypeScript:
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "List the files in the current directory and summarise the project.",
options: {
allowedTools: ["Read", "Glob", "Grep"],
permissionMode: "plan",
},
})) {
if (message.type === "assistant") {
console.log(message.message.content);
}
}
The same shape in Python:
from claude_agent_sdk import query, ClaudeAgentOptions
async for message in query(
prompt="List the files in the current directory and summarise the project.",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Glob", "Grep"],
permission_mode="plan",
),
):
if message.type == "assistant":
print(message.message.content)
That is the whole surface. The SDK handles orchestration, tool dispatch, prompt caching, and retries. You consume the stream and decide what to render.
The agent loop: how Claude plans, calls tools, and decides when to stop
In short
The Claude Agent SDK's async iterator yields one message per step — Claude's reasoning, a tool call, a tool result, or the final outcome. The SDK owns orchestration, tool execution, prompt-cache placement, and retries; the caller consumes the stream. The loop ends when Claude finishes the task, hits a permission denial, or errors.
Every query() is a streaming, multi-step conversation. As you async for over the result, the SDK yields a message per step: an assistant reasoning turn, a tool use request, a tool result, and eventually a ResultMessage with the final outcome and session metadata.
The first message you receive from any query is a system:init message. It reports what built-in tools are available, which MCP servers connected successfully, and the session ID. Inspect it at the top of your handler — this is where you catch things like "my Slack MCP server failed to auth" before Claude starts trying to use it.
The loop terminates in one of three ways:
- Task complete — Claude decides no further tools are needed, produces a final message, and the SDK emits
ResultMessage. - Permission denial — the current
permissionModeor acanUseToolcallback denies a tool call and the agent cannot make progress. - Error — API error, tool crash, or timeout. The SDK yields the error message and then raises after the iterator drains.
For CI jobs, background workers, and scheduled tasks where live output is not needed, switch to single-turn mode. It collects the full message list at once instead of streaming — cleaner logs, simpler error handling, no async iteration:
// TypeScript — single-turn mode collects the full run
const messages = [];
for await (const m of query({ prompt, options })) messages.push(m);
const result = messages.find((m) => m.type === "result");
Streaming is worth the effort for anything user-facing. It is what makes an agent feel like it is thinking, not hanging.
Built-in tools: Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch
In short
The Claude Agent SDK ships eight built-in tools out of the box: Read, Write, Edit for files; Bash for shell; Glob and Grep for search; WebSearch and WebFetch for the web. Enable them via allowedTools (auto-approve) and disallowedTools (block). Common combos: read-only audit (Read/Grep/Glob), analyse-and-modify (Read/Edit/Glob), full automation (Read/Edit/Bash/Glob/Grep).
The built-in tool set is what differentiates the Agent SDK from every generic LLM wrapper. You do not define these tools — they are wired into the harness, they know how to work together, and they respect the same permission model as everything else.
The right way to think about them is as archetypes. Almost every deployment picks one:
- Read-only audit —
Read,Grep,Glob. Safe by construction. Perfect for code review, security scanning, documentation extraction. - Analyse-and-modify —
Read,Edit,Glob. Can refactor code but cannot run it. Ideal for large refactors where you want the agent contained. - Full automation —
Read,Edit,Bash,Glob,Grep. This is Claude Code's default surface. Grants shell access — expect to combine it with a hook-based audit trail. - Research — add
WebSearchandWebFetchto any of the above. They live in the same allowlist mechanism — no separate MCP server needed.
Tool selection is enforced with two lists and one callback. allowedTools auto-approves. disallowedTools blocks. Anything not on either list falls through to canUseTool, or to the current permission mode. If neither allowedTools includes Agent nor a canUseTool handler covers it, tool calls for subagents will be denied — a common gotcha we cover in the subagents section.
// Read-only audit agent — no writes, no shell
const options = {
allowedTools: ["Read", "Grep", "Glob"],
disallowedTools: ["Bash", "Write", "Edit"],
permissionMode: "plan",
};
For a deeper look at how tool-use patterns compose across different frameworks, our guide on AI agent tool-use patterns covers the four main archetypes.
Claude subagents: hierarchical delegation with isolated context
In short
Claude subagents are separate Claude instances the main agent spawns via the Agent tool. Each subagent has its own context window, tools, model, and system prompt. Only the subagent's final message returns to the parent — intermediate reasoning stays isolated. As of Claude Code v2.1.219, subagents run in the background by default and can spawn up to 3 nested layers (configurable via CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH).
Subagents are the single biggest architectural feature in the Claude Agent SDK. A subagent is a separate Claude instance the main agent spawns via the Agent tool. It has its own context window, its own allowlist, its own model, and its own system prompt. When it finishes, only its final message returns to the parent.
That last property matters more than it sounds. In a flat agent, every tool call and every intermediate reasoning turn bloats the parent's context. In a subagent, all of that stays isolated. The parent sees one clean summary — the subagent's answer — and can move on. In Alice Labs benchmarks, delegating heavy exploration to subagents keeps planner context under 30% utilisation for runs that would otherwise blow past 90%.
You can define subagents two ways:
- Programmatically, via the
agentsparameter — anAgentDefinitionin Python or a typed object in TypeScript. - As markdown files in
.claude/agents/, matching the same convention Claude Code uses. This is how you share subagents across a team.
As of Claude Code v2.1.219, the runtime defaults changed: subagents now run in the background by default, and up to three layers of nested subagents can spawn from a single query. The depth ceiling is configurable via CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH — raise it deliberately, not by reflex.
// TypeScript — inline subagent definition
const options = {
agents: {
"code-reviewer": {
description: "Reads code and returns review comments only",
tools: ["Read", "Grep", "Glob"],
model: "sonnet",
prompt: "You review code for correctness and readability. No writes.",
},
"test-runner": {
description: "Runs the test suite and reports failures",
tools: ["Bash(pytest*)", "Read"],
model: "haiku",
prompt: "You run tests and summarise failures.",
},
},
allowedTools: ["Read", "Edit", "Agent"],
};
Note the Agent entry in allowedTools. Without it, the parent cannot spawn subagents even if they are defined — the most common subagent bug we see in code reviews.
The Alice Labs pattern for a review workflow: a read-only code-reviewer on Sonnet, a test-runner with scoped Bash, and a security-scanner on Opus, dispatched in parallel from the main planner. Wall-clock time drops by roughly 60% versus running the same checks sequentially, and each subagent's transcript is independently auditable.
For deeper architectural context on multi-agent coordination, our multi-agent systems explained guide covers supervisor, hierarchical, and peer-to-peer patterns beyond the SDK layer.
Model configuration and fallback chains for Claude agents
In short
AgentDefinition.model accepts aliases (opus, sonnet, haiku, fable, inherit) or full IDs like claude-opus-5, claude-opus-4-8, claude-sonnet-5. Per-subagent overrides let you route cheap tasks to Haiku 4.5 and reserve Opus 5 for reasoning-heavy leaves. Server-side refusal fallbacks pair fallbacks:'default' with the server-side-fallback-2026-07-01 beta header so cyber-category refusals reroute to Opus 4.8 automatically.
Model routing is where most of the cost lives in a production Claude agent, and where most of the reliability wins live too. Two axes matter: the model you choose per subagent, and the fallback chain when the primary model refuses or errors.
The model field on any AgentDefinition — or on the top-level options — accepts either an alias or a full model ID. Aliases (opus, sonnet, haiku, fable, inherit) resolve to the current version behind the alias. Full IDs (claude-opus-5, claude-opus-4-8, claude-sonnet-5, claude-haiku-4-5) pin an exact version — the right choice for deployments where behaviour drift matters.
The effort level is separate from the model and configurable per agent — low, medium, high, xhigh, max. Claude Code's default for coding and agentic work is xhigh. Lower it for narrow, well-defined subagents to save budget without hurting quality.
Server-side refusal fallbacks — a June 2026 addition — are the reliability primitive most teams miss. Pair fallbacks: "default" with the server-side-fallback-2026-07-01 beta header on the underlying API, and cyber-category refusals on newer Opus models automatically reroute to Opus 4.8. Your agent finishes the task instead of stalling on a refusal your prompt could not anticipate.
// Alice Labs production default — tiered subagents + refusal fallback
const options = {
model: "claude-opus-5", // main planner
agents: {
"explorer": {
description: "Read-only exploration of the repo",
tools: ["Read", "Grep", "Glob"],
model: "claude-haiku-4-5", // cheap
},
"implementer": {
description: "Implements changes based on the plan",
tools: ["Read", "Edit", "Bash"],
model: "claude-sonnet-5", // balanced
},
},
extraBody: {
fallbacks: "default",
},
extraHeaders: {
"anthropic-beta": "server-side-fallback-2026-07-01",
},
};
Alice Labs' measured cost impact of the tier-by-role pattern is a 40–60% reduction versus single-model deployments across our internal analytics-agent benchmark set. Haiku 4.5 handles the volume of read-only grep-and-glob work at a fraction of Opus pricing; Opus stays available for the planning and critique steps where it earns its cost.
Connecting external tools via MCP (Model Context Protocol)
In short
MCP is the SDK's third-party extension surface — 200+ server implementations existed in 2026, including official servers for GitHub, Slack, Linear, Playwright, Postgres, and Notion. Three transports are supported: stdio (local processes), http/sse (remote), and in-process SDK MCP servers (custom tools in code). Tool naming convention: mcp__<server-name>__<tool-name>.
MCP is Anthropic's open protocol for connecting external systems to Claude. It is what you use when the built-in tools are not enough — when the agent needs to open a GitHub PR, query Postgres, run a Playwright browser, or read a Notion page. In 2026 the ecosystem crossed 200+ server implementations, with official servers maintained for the systems you would expect (GitHub, Slack, Linear, Playwright, Postgres, Notion) and community servers for the long tail.
The SDK supports three transports:
- stdio — the SDK spawns a local process and talks to it over stdin and stdout. This is how nearly every official server ships.
- http / sse — remote server behind a URL. Use for managed MCP services and shared team infrastructure.
- in-process SDK MCP server — you define tools in Python or TypeScript, and the SDK exposes them to Claude as if they were MCP tools. This is the right shape for custom tools that only your team will use.
Every MCP tool is namespaced mcp__<server-name>__<tool-name> — for example mcp__github__create_pull_request. Allowlist with wildcards when you trust a whole server (mcp__github__*) or enumerate specific tools when you do not.
// TypeScript — stdio MCP server + auto-approved GitHub tools
const options = {
mcpServers: {
github: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-github"],
env: { GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GH_TOKEN },
},
linear: {
transport: "http",
url: "https://mcp.linear.app/sse",
headers: { Authorization: `Bearer ${process.env.LINEAR_TOKEN}` },
},
},
allowedTools: ["Read", "mcp__github__*", "mcp__linear__list_issues"],
};
MCP servers connect non-blocking. Your query() starts before every server has finished handshaking. Inspect system:init.mcp_servers[].status — failed or needs-auth are real problems; pending is not. This trips up teams who write their own healthcheck expecting all-connected-or-fail semantics.
OAuth 2.1 credentials go in the headers map — the SDK does not run the browser OAuth flow itself. Do the token exchange upstream (your app's auth layer, Auth0, or the provider's CLI) and pass the bearer token to the SDK.
Permissions and safety: production-grade tool gating
In short
The Claude Agent SDK has four permission modes: default (prompt on write), acceptEdits (auto-approve file writes and filesystem Bash), plan (read-only), and bypassPermissions (dangerous — disables most prompts). Prefer allowedTools wildcards over permissionMode for MCP access. The canUseTool callback is the correct hook for human-in-the-loop approval UIs. Lifecycle hooks (PreToolUse, PostToolUse, Stop, SessionStart) run custom code at defined points — used for audit logging, PII scrubbing, and EU AI Act compliance evidence.
Permissions are the layer that turns a research prototype into something you can actually deploy. The SDK ships four modes, and picking the right one is the fastest reliability upgrade available:
- default — prompts on every write and Bash. The right choice for interactive local use, wrong for anything headless.
- acceptEdits — auto-approves file writes and filesystem-scoped Bash. Does not auto-approve MCP tools — a common misconception.
- plan — read-only. The agent can Read, Grep, Glob, WebSearch, WebFetch, and reason. It cannot Write, Edit, or Bash. This is the mode for audit and analysis agents.
- bypassPermissions — disables most prompts. Only use inside a sandbox with a network policy you trust. Named to look scary because it should be.
For MCP tools, do not rely on permissionMode at all — enumerate them in allowedTools with wildcards. acceptEdits covers filesystem writes but not MCP calls; the mode name misleads here and it is a routine source of "my agent keeps prompting me for the GitHub tool" issues.
For human-in-the-loop, the right hook is canUseTool. It fires before every tool call, receives the full tool input, and returns a decision. Wire it to your approval UI, your Jira integration, or your Slack bot:
// TypeScript — approve every Write via canUseTool
const options = {
canUseTool: async (toolName, input) => {
if (toolName === "Write") {
const approved = await askHumanViaSlack(toolName, input);
return { behavior: approved ? "allow" : "deny", reason: "human decision" };
}
return { behavior: "allow" };
},
};
Lifecycle hooks — PreToolUse, PostToolUse, Stop, SessionStart — are where enterprise compliance lives. A PreToolUse hook can stamp every tool call into an immutable audit ledger before it executes. A PostToolUse hook can scrub PII from the tool result before it reaches the model.
The Alice Labs EU AI Act-native pattern for high-risk deployments: a single PreToolUse hook that writes tool name, input, timestamp, user ID, and request ID to an append-only Postgres table. Add it once at agent-service startup and you have satisfied the tool-call logging portion of Article 12 with about five lines of code. For the broader compliance picture see our EU AI Act compliance checklist for 2026.
Shipping a Claude Agent SDK deployment? We've done 100+.
Alice Labs is an Anthropic Partner and has delivered 100+ production Claude Agent SDK systems across the Nordics and Europe — planner/worker/explorer tiering, MCP integrations, EU AI Act audit hooks, and Dynamic Workflows fan-out already solved.
Talk to a Claude Agent ExpertSessions, resume, and multi-turn agent state
In short
Each query() call starts a new session by default. To resume, pass resume: sessionId in options. Session IDs come from the ResultMessage.session_id emitted at the end of each query. Subagent transcripts persist independently and can be resumed via the agentId in the Agent tool result. Sessions can be forked to explore alternative paths, and auto-cleanup runs after cleanupPeriodDays (default 30).
The default session model in the SDK is single-shot. Each query() starts fresh, runs to completion, and the state is stored under a session ID you can look up or resume later. For user-facing products, this is where you plug in the "continue conversation" behaviour.
Capture the session ID from the ResultMessage emitted at the end of each query — it is the last message you will see in the stream:
let sessionId: string | undefined;
for await (const m of query({ prompt, options })) {
if (m.type === "result") sessionId = m.session_id;
}
// Later — resume the same session
for await (const m of query({
prompt: "Continue where we left off",
options: { ...options, resume: sessionId },
})) {
/* ... */
}
Subagent transcripts persist independently. When a subagent completes, the Agent tool result includes an agentId — you can resume that specific subagent later with its own full history intact. This is how you build long-running specialised workers that survive across parent-session boundaries.
Two features matter more than they look:
- Forking — you can fork a session to explore alternative paths without losing the parent state. Useful for what-if agents, plan comparison, and retry-with-different-approach workflows.
- Auto-cleanup — sessions are pruned after
cleanupPeriodDays(default 30). Raise the ceiling explicitly for compliance-sensitive deployments where retention windows are contractual.
For deeper architectural patterns on how agents hold state across turns and sessions, our AI agent memory systems guide covers session-level, episodic, and semantic memory beyond what the SDK ships out of the box.
Dynamic Workflows: scaling to hundreds of parallel subagents (June 2026)
In short
In June 2026 Anthropic upgraded subagents with Dynamic Workflows — the lead agent plans and fans out tens to hundreds of parallel subagents in a single session. The Workflow tool moves orchestration into a script the runtime executes outside the conversation context, available in TypeScript Agent SDK v0.3.149+. Performance Outcomes (also June 2026) add a separate grader that sends each subagent back to revise until its result meets a rubric.
Dynamic Workflows are the biggest scaling primitive Anthropic shipped in 2026. Before the change, subagent fan-out was capped by what fits in a conversation turn — a planner could delegate five or ten subagents, not two hundred. Dynamic Workflows lift that ceiling by moving the orchestration into a script the runtime executes outside the conversation.
The mechanism is a new Workflow tool. The planner emits a workflow plan; the runtime executes it; the results flow back as a single subagent-shaped summary. The lead agent's context stays clean while tens or hundreds of parallel workers run underneath. It is available in TypeScript Agent SDK v0.3.149 and later; add Workflow to allowedTools to auto-approve runs, and check the TypeScript reference for the tool's schema.
Performance Outcomes shipped alongside Dynamic Workflows in June 2026. It adds a separate grader agent that evaluates each subagent's result against a rubric and sends the subagent back to revise until the rubric passes. This is the same primitive Managed Agents' user.define_outcome uses — now available in the library SDK. It replaces the hand-rolled reflection loops most teams were writing themselves.
The Alice Labs use case that illustrates the difference: a 40-file security review across a microservices monorepo. Sequentially, one subagent per file, this was a 3-hour job. With Dynamic Workflows fanning out to 40 parallel security-scanner subagents, wall-clock time drops to 12 minutes. Same total token cost, twelve times faster.
The trap: parallelism amplifies mistakes. A subtly wrong system prompt in a subagent template gets 40× the exposure when you fan it out. Alice Labs' rule is to run every subagent template through a smoke test on a single well-known input before enabling fan-out in production.
TypeScript Agent SDK version that first shipped the Workflow tool
Billing model: Agent SDK credits vs Anthropic API credits (post June 15, 2026)
In short
On June 15, 2026 Anthropic split Claude Agent SDK subscription usage from interactive Claude Code — SDK-driven agents now draw from a separate monthly Agent SDK credit pool on subscription plans. Heavy headless users may hit limits sooner and can top up via API credits with a standard ANTHROPIC_API_KEY. For production, Alice Labs recommends API-key authentication (not subscription) to isolate agent traffic from developer workstations. Anthropic explicitly disallows third-party developers offering claude.ai login for products built on the Agent SDK — API-key auth only.
On June 15, 2026 Anthropic split subscription billing for the Claude Agent SDK away from interactive Claude Code. Under the new model, interactive Claude Code (your terminal or IDE session) and headless Claude Code (SDK-driven agents in your infra) draw from separate weekly token pools on subscription plans.
In practice this catches teams whose developer workstations and staging agents share a subscription. A heavy headless deployment now exhausts its own pool before the developer notices anything on the interactive side. When the pool runs out, you top up: attach a standard ANTHROPIC_API_KEY and the SDK falls through to API credits without additional configuration.
The Alice Labs recommendation for anything production-shaped is simpler: use API-key authentication, not subscription. Isolate agent traffic in its own billing entity so you can budget, forecast, and rate-limit independently of developer usage. API keys also make it trivial to rotate credentials for a specific deployment without disturbing your team's daily work.
One rule worth naming explicitly: Anthropic disallows third-party developers offering claude.ai login or claude.ai rate limits for products built on the Agent SDK. If you are shipping a customer-facing product, you use API keys — no exceptions.
For a broader treatment of build-vs-buy economics on production AI agents including model spend forecasting, see our build vs buy AI guide.
Deployment patterns: Docker, CI/CD, and hosted agents in 2026
In short
Anthropic ships a Hosting guide covering Docker, cloud, and CI/CD deployment shapes for the Agent SDK. The common production pattern: a containerised Python or Node service, agent triggered via HTTP webhook or SQS message, tools scoped by env-var-controlled allowedTools. Session persistence uses the SDK's session store or forks to Redis/Postgres via hooks for cross-container resume. Alice Labs runs the Agent SDK on customer AWS VPC or on-prem infrastructure to keep code and secrets inside the enterprise trust boundary.
Anthropic publishes a dedicated Hosting guide for the Agent SDK covering Docker, cloud, and CI/CD deployment shapes. It is worth reading end-to-end before your first production deployment. If you want Anthropic to run the loop and sandbox for you, that is a different product — Managed Agents, a separate REST service. The Agent SDK stays a library on your infrastructure.
The production shape we deploy most often at Alice Labs is deliberately unglamorous: a containerised Python or Node service, triggered by an HTTP webhook or a queue message (SQS, Pub/Sub, or RabbitMQ), with tool allowlists scoped by environment variable so staging and production can diverge without code changes. The agent runs to completion, emits its result, and the container recycles.
Production deployment patterns for the Claude Agent SDK
| Pattern | Shape | Best for |
|---|---|---|
| Webhook worker | Container + HTTP endpoint, autoscaled behind a load balancer | Customer-facing agents, real-time triggers |
| Queue consumer | Container reads SQS/Pub-Sub, runs agent, writes result | Batch document processing, back-office automation |
| CI/CD job | Runs as part of a pipeline — GitHub Actions, GitLab CI | Code review, security scans, doc generation |
| Scheduled task | Cron or EventBridge kicks a container on interval | Nightly audits, weekly reports, monitoring |
| Managed Agents (REST) | Anthropic hosts loop + sandbox — you call a REST endpoint | Teams that do not want to run their own infra |
Session persistence across container restarts is the one thing you always have to solve yourself. The SDK ships a local session store — great for single-container development, useless for a fleet. In production, use a PostToolUse hook to mirror session state to Redis or Postgres after every step, and pass resume: sessionId on the next invocation to rehydrate.
For EU deployments where code and secrets must stay inside the enterprise trust boundary, we run the Agent SDK on the customer's own AWS VPC or on-prem infrastructure with Anthropic-on-AWS or Bedrock. The Agent SDK is a library — the deployment surface is entirely within your control.
Skills, commands, and memory: reusing Claude Code's ecosystem
In short
The Claude Agent SDK auto-loads skills, slash commands, memory, and hooks from .claude/ (project) and ~/.claude/ (user) — same conventions as Claude Code. Skills are markdown files with a SKILL.md; Claude loads full skill content only when the task calls for it (progressive disclosure). Memory has three scopes: user, project, local — configurable per-subagent via AgentDefinition.memory. Plugins package skills, agents, hooks, and MCP servers into a single loadable bundle.
The Agent SDK inherits Claude Code's .claude/ configuration surface. Any skill, slash command, memory scope, or hook you have set up for Claude Code loads automatically when you call query(). This is the reuse primitive that separates the Agent SDK from generic LLM wrappers — you write configuration once and reuse it in your IDE and in production.
Four things load from .claude/ and ~/.claude/:
- Skills — markdown files with a
SKILL.mdand supporting references. Progressive disclosure: Claude sees only the one-line description until the task calls for the skill, then loads the full content. This is what keeps context budget under control when you have twenty skills installed. - Slash commands — short reusable prompts (like
/reviewor/deploy) shared across a team. - Memory — three scopes:
user(your personal notes),project(checked into the repo),local(project-scoped but gitignored). Configurable per-subagent viaAgentDefinition.memory. - Hooks — the same
PreToolUse/PostToolUse/Stop/SessionStartlifecycle hooks used for compliance and audit.
Plugins bundle all of the above into a single loadable unit. Ship a plugin once and every team can install skills, subagent definitions, MCP servers, and hooks in one command. This is the shape that scales agent capabilities across an engineering organisation.
One useful non-obvious feature: initialPrompt on an AgentDefinition. When set, the SDK auto-submits that prompt as the first user turn when the agent runs as the main thread. Perfect for role-locked deployments where the agent should always start with the same framing — "You are a support triage agent. Read the ticket at $TICKET_URL and…" — without leaking the framing into every caller.
Production best practices from 100+ Alice Labs Claude Agent SDK deployments
In short
Alice Labs' six production rules for the Claude Agent SDK: (1) start with the smallest allowlist that gets the job done; (2) route by model tier — Opus 5 planner, Sonnet 5 main work, Haiku 4.5 read-only — for 40–60% cost reduction; (3) wrap every production query() in try/except and check ResultMessage.subtype == 'error_during_execution'; (4) instrument PostToolUse hooks with tool_name, input, and duration; (5) treat MCP_TIMEOUT (default 30s) as the most common silent-slowdown cause; (6) log every tool call with a stable request-ID and retain for 6 months for EU AI Act compliance.
After 100+ production Claude Agent SDK deployments across the Nordics and Europe, the practices below are what actually keeps agents healthy in production. None of them are tricks — they are the boring compounding decisions that separate a demo from something you can put in front of a customer.
- Start with the smallest allowlist that ships the job. Every tool you allow is one more failure mode, one more prompt-injection target, and one more thing to audit. Expand only after you have seen the tool-choice traces on a real workload.
- Route by tier. Opus 5 for planning and critique, Sonnet 5 for main work, Haiku 4.5 for read-only exploration. Alice Labs' measured cost impact is 40–60% reduction versus single-model deployments — the biggest single-lever cost saving available.
- Wrap every production
query()in error handling.try/except APIErrorat the outer level, and checkResultMessage.subtype == "error_during_execution"in the stream — the SDK raises after yielding the error message, so an early break skips the actionable detail. - Instrument
PostToolUsehooks. Recordtool_name, input hash, duration, and outcome to your observability stack. MCP tool timeouts (MCP_TIMEOUT, default 30 seconds) are the most common silent-slowdown cause we see and are invisible without duration telemetry. - Log every tool call for compliance. For EU AI Act-scoped deployments, log tool name, input, output hash, request ID, user ID, and timestamp to an append-only store. Retain for 6 months minimum. The SDK's hook system makes this a five-line addition — no bespoke middleware required.
- Prompt-test at fan-out scale. A subtly wrong subagent system prompt amplifies 40× when Dynamic Workflows fans out. Smoke-test every subagent template against a single well-known input before enabling parallel fan-out.
For deeper coverage of the risks and controls specific to agentic systems, our AI agent security risks guide covers prompt injection, tool misuse, exfiltration paths, and the containment patterns for each.
If you are evaluating whether to build Claude agents in-house or engage external support, our build vs buy AI guide documents the same decision framework we use across Alice Labs' 100+ enterprise implementations.
About the Authors & Reviewers

Co-Founder, Alice Labs
Co-Founder at Alice Labs. Builds AI automation, agent workflows and integration systems that hold up in real business operations.
- AI automation & agent systems lead
- Workflow design across 100+ deployments
- Specialist in RAG, integrations & APIs

Co-Founder, Alice Labs
Co-Founder at Alice Labs. Author of 7 research reports on AI adoption, governance and labor markets cited across EU, OECD and US benchmarks.
- 8+ years in AI strategy & implementation
- Top-5 AI Speaker, Sweden (Mindley 2025)
- 100+ enterprise AI engagements
Frequently Asked Questions
What is the Claude Agent SDK?
The Claude Agent SDK is Anthropic's library for building production AI agents in Python and TypeScript. It packages the same agent loop, built-in tools (Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch), context management, permissions, hooks, subagents, and MCP integration that power Claude Code, exposed as a query(prompt, options) primitive. Alice Labs, an Anthropic Partner, has shipped 100+ production Claude Agent SDK deployments across the Nordics and Europe.
Is the Claude Agent SDK the same as the Claude Code SDK?
Yes — Anthropic renamed the Claude Code SDK to the Claude Agent SDK in early 2026 to signal that it is the general-purpose agent library, not a coding-only tool. The npm package is @anthropic-ai/claude-agent-sdk and the PyPI package is claude-agent-sdk. The underlying harness is unchanged; the rename reflects broader positioning for agentic use cases beyond IDE coding.
What is the difference between the Claude Agent SDK and the Claude API (Client SDK)?
The Claude API SDK (@anthropic-ai/sdk, anthropic) is a raw HTTP client — you write the tool loop yourself and supply every tool. The Claude Agent SDK ships the full Claude Code harness: the loop, built-in file and shell tools, context management, permissions, subagents, and MCP loader. Alice Labs' rule: use the Agent SDK for coding, filesystem, and research work; use the Client SDK when the loop is narrow and custom, such as extraction or classification.
How do I install the Claude Agent SDK?
TypeScript: npm install @anthropic-ai/claude-agent-sdk (Node.js 18+ required). Python: pip install claude-agent-sdk or uv add claude-agent-sdk (Python 3.10+ required). Both packages bundle a native Claude Code binary — no separate Claude Code install needed. Set ANTHROPIC_API_KEY in your process environment before calling query() — the SDK does not automatically load a .env file.
What built-in tools does the Claude Agent SDK ship with?
Eight built-in tools ship with every install: Read, Write, and Edit for files; Bash for shell commands; Glob and Grep for search; WebSearch and WebFetch for the web. They are enabled via allowedTools (auto-approve) and disallowedTools (block). Common combos: read-only audit (Read/Grep/Glob), analyse-and-modify (Read/Edit/Glob), and full automation (Read/Edit/Bash/Glob/Grep).
What are Claude subagents and when should I use them?
Claude subagents are separate Claude instances the main agent spawns via the Agent tool. Each has its own context window, tools, model, and system prompt. Only the subagent's final message returns to the parent — intermediate reasoning stays isolated, reducing context bloat. Use them to delegate heavy exploration, run parallel work, or scope specialist tasks (a security-scanner on Opus, a test-runner with Bash, a code-reviewer read-only on Sonnet). As of Claude Code v2.1.219, subagents run in the background by default and can spawn up to 3 nested layers.
How do I connect external tools to a Claude agent?
Use MCP (Model Context Protocol). The SDK supports three transports: stdio for local processes, http/sse for remote servers, and in-process SDK MCP servers for tools you define in code. MCP crossed 200+ server implementations in 2026 with official servers for GitHub, Slack, Linear, Playwright, Postgres, and Notion. Tools are namespaced mcp__<server-name>__<tool-name> and allowlisted with wildcards like mcp__github__*.
What permission modes does the Claude Agent SDK support?
Four modes: default (prompt on write), acceptEdits (auto-approve file writes and filesystem Bash), plan (read-only — Read, Grep, Glob, WebSearch, WebFetch only), and bypassPermissions (disables most prompts — sandbox only). For MCP tools, prefer allowedTools wildcards over permissionMode — acceptEdits does not auto-approve MCP calls, a common misconception. Use the canUseTool callback for human-in-the-loop approval UIs.
Which Claude model should I use for a production agent?
Alice Labs' default production stack across 100+ deployments: claude-opus-5 for the primary planner, claude-sonnet-5 for main worker subagents, and claude-haiku-4-5 for read-only exploration and grep-heavy work. Pair with server-side refusal fallbacks (fallbacks: 'default' + the server-side-fallback-2026-07-01 beta header) so cyber-category refusals reroute to Opus 4.8 automatically. Measured cost reduction versus single-model deployments: 40–60%.
What are Dynamic Workflows in the Claude Agent SDK?
Dynamic Workflows, added in June 2026, let the lead agent fan out tens to hundreds of parallel subagents in a single session. The new Workflow tool moves orchestration into a script the runtime executes outside the conversation context — available in TypeScript Agent SDK v0.3.149+. Include Workflow in allowedTools to auto-approve runs. Performance Outcomes (also June 2026) adds a separate grader that sends each subagent back to revise until its result meets a rubric.
How is Claude Agent SDK billing different from regular Claude Code billing?
On June 15, 2026 Anthropic split Claude Agent SDK subscription usage into a separate monthly credit pool. Interactive Claude Code (your terminal/IDE session) and headless Claude Code (SDK-driven agents) now draw from separate weekly token pools on subscription plans. Heavy headless users may hit limits sooner and can top up via API credits with a standard ANTHROPIC_API_KEY. For production, Alice Labs recommends API-key authentication to isolate agent traffic from developer workstations.
Can I use the Claude Agent SDK with AWS Bedrock or Google Vertex AI?
Yes. Set the corresponding environment variable before starting your process: CLAUDE_CODE_USE_BEDROCK=1 for AWS Bedrock, CLAUDE_CODE_USE_ANTHROPIC_AWS=1 for Anthropic-on-AWS, CLAUDE_CODE_USE_VERTEX=1 for Google Vertex AI, or CLAUDE_CODE_USE_FOUNDRY=1 for Azure AI Foundry. The rest of the SDK API is unchanged. This is the standard deployment shape for EU customers running the agent inside their own VPC.
How do sessions and resume work in the Claude Agent SDK?
Each query() starts a new session by default. Capture the session ID from ResultMessage.session_id at the end of a query, then resume by passing resume: sessionId in the options on the next call. Subagent transcripts persist independently and can be resumed via the agentId in the Agent tool result. Sessions can be forked to explore alternative paths, and auto-cleanup runs after cleanupPeriodDays (default 30).
How does the Claude Agent SDK support EU AI Act compliance?
Two features carry most of the weight: (1) lifecycle hooks (PreToolUse, PostToolUse, Stop, SessionStart) let you log every tool call to an immutable audit ledger — the Alice Labs pattern is a single PreToolUse hook writing tool name, input, timestamp, user ID, and request ID to an append-only Postgres table; (2) the canUseTool callback provides human-in-the-loop approval for high-risk actions. Retain logs for 6 months minimum for high-risk system compliance. Always consult legal counsel for compliance determinations.
What language can I use if my project isn't Python or TypeScript?
Drive the same harness by running the Claude Code CLI as a subprocess with -p '<prompt>' --output-format json. You lose typed language bindings but keep every feature — tools, subagents, MCP, permissions, hooks. This is the standard escape hatch for Go, Rust, Java, and .NET codebases; behaviour is identical because the underlying binary is the same one the Python and TypeScript SDKs ship.
What are the most common Claude Agent SDK deployment mistakes?
Based on Alice Labs' 100+ production deployments, the top five are: (1) forgetting to include 'Agent' in allowedTools when defining subagents — they silently never spawn; (2) relying on acceptEdits for MCP tools, which does not cover them — use allowedTools wildcards instead; (3) not loading .env before calling query() — the SDK reads ANTHROPIC_API_KEY from the process env only; (4) treating pending MCP servers as failures in health checks — only failed and needs-auth are actionable; (5) shipping a subtly wrong subagent prompt into Dynamic Workflows fan-out and amplifying the mistake 40× before catching it.
How do I add human-in-the-loop approval to a Claude agent?
Use the canUseTool callback. It fires before every tool call, receives the tool name and full input, and returns { behavior: 'allow' | 'deny', reason? }. Wire it to your approval UI, Slack bot, or ticketing system. Because subagents and hooks persist state, an approval decision can happen minutes or hours later — the agent resumes when the callback returns. This is the correct primitive for enterprise governance workflows integrated with Jira, ServiceNow, or Linear.
Does the Claude Agent SDK replace Claude Code, LangGraph, or CrewAI?
It replaces neither Claude Code nor competing agent frameworks — it serves different needs. Claude Code remains the IDE/terminal experience; the Agent SDK is the library shape for production agents. Against LangGraph and CrewAI, the choice depends on ecosystem: pick the Claude Agent SDK when you want Claude Code's built-in tools and subagent model out of the box; pick LangGraph when you need explicit graph-based state control across any LLM provider; pick CrewAI for role-based multi-agent scenarios. Compare all three in our best AI agent frameworks guide for 2026.
Microsoft Agent Framework 1.0 Guide 2026 (MAF) | Alice Labs
Next in AI AgentsAI Agent Observability Guide 2026 | Alice Labs
Further reading
- Claude Agent SDK Official Documentation — Anthropic· code.claude.com
- Claude Agent SDK Quickstart· code.claude.com
- Anthropic Blog — Dynamic Workflows in Claude Code (June 2026)· claude.com
- Model Context Protocol Specification· modelcontextprotocol.io
- Claude Agent SDK Subagents Reference· code.claude.com
Related services
Related reading
Best AI Agent Frameworks 2026: The Enterprise Comparison
Compare the Claude Agent SDK, LangGraph, CrewAI, AutoGen, and other frameworks on state management, multi-agent support, and enterprise production fit.
deepdiveLangGraph Tutorial 2026: Build Stateful AI Agents for Enterprise
The Python-first alternative to the Claude Agent SDK — graph-based state, checkpointers, and supervisor multi-agent patterns.
deepdiveMulti-Agent Systems Explained: Patterns, Trade-offs, and Enterprise Use Cases
Architectural context for Claude subagents and Dynamic Workflows — supervisor, hierarchical, and collaborative coordination patterns.
deepdiveAI Agent Architecture Patterns for Enterprise
The five core agent architecture patterns — ReAct, Plan-and-Execute, Supervisor, Reflection, and Tool-Use — with implementation guidance.
deepdiveAI Agent Security Risks and Controls
Prompt injection, tool misuse, exfiltration paths, and the containment patterns you need before shipping any Claude Agent SDK deployment.
deepdiveAI Agent Memory Systems
Session, episodic, and semantic memory in production AI agents — how to extend the Agent SDK's session store for long-running workflows.
deepdiveCrewAI Guide 2026
The role-based multi-agent alternative — CrewAI's approach to supervisor patterns and enterprise deployments.
Sources
- Claude Agent SDK — OverviewAnthropic · Anthropic“Anthropic renamed the Claude Code SDK to the Claude Agent SDK in early 2026. It ships as @anthropic-ai/claude-agent-sdk (npm) and claude-agent-sdk (PyPI), exposing Claude Code's harness through a single query(prompt, options) primitive.”(accessed 2026-08-02)
- Claude Agent SDK QuickstartAnthropic · Anthropic“TypeScript install: npm install @anthropic-ai/claude-agent-sdk (Node.js 18+). Python install: pip install claude-agent-sdk or uv add claude-agent-sdk (Python 3.10+). Both packages bundle a native Claude Code binary and read ANTHROPIC_API_KEY from process env.”(accessed 2026-08-02)
- Claude Agent SDK SubagentsAnthropic · Anthropic“Subagents are separate Claude instances the main agent spawns via the Agent tool with their own context, tools, and model. As of Claude Code v2.1.219, subagents run in the background by default and can spawn up to 3 nested layers via CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH.”(accessed 2026-08-02)
- Claude Agent SDK Tools ReferenceAnthropic · Anthropic“Eight built-in tools ship with every install: Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch. Selection is enforced via allowedTools (auto-approve), disallowedTools (block), and the canUseTool callback (per-call decision).”(accessed 2026-08-02)
- Claude Agent SDK — MCP IntegrationAnthropic · Anthropic“MCP crossed 200+ server implementations in 2026 with official servers for GitHub, Slack, Linear, Playwright, Postgres, and Notion. Three transports supported: stdio, http/sse, and in-process SDK MCP servers. Tool naming: mcp__<server-name>__<tool-name>.”(accessed 2026-08-02)
- Claude Agent SDK — PermissionsAnthropic · Anthropic“Four permission modes: default, acceptEdits, plan, bypassPermissions. acceptEdits does not auto-approve MCP tools — enumerate them in allowedTools with wildcards. canUseTool is the correct hook for human-in-the-loop approval UIs.”(accessed 2026-08-02)
- Claude Agent SDK — HostingAnthropic · Anthropic“Anthropic ships a dedicated Hosting guide covering Docker, cloud, and CI/CD deployment shapes for the Agent SDK. Managed Agents is a separate REST product for teams that want Anthropic to host loop and sandbox.”(accessed 2026-08-02)
- A Harness for Every Task — Dynamic Workflows in Claude CodeAnthropic · Anthropic“In June 2026 Anthropic upgraded subagents with Dynamic Workflows — the lead agent plans and fans out tens to hundreds of parallel subagents in a single session. The Workflow tool moves orchestration into a script the runtime executes outside conversation context. Available in TypeScript Agent SDK v0.3.149+.”(accessed 2026-08-02)
- Claude Code Features — Skills, Commands, MemoryAnthropic · Anthropic“The Agent SDK auto-loads skills, slash commands, memory, and hooks from .claude/ (project) and ~/.claude/ (user) — same conventions as Claude Code. Plugins bundle skills, subagents, hooks, and MCP servers into a single loadable unit.”(accessed 2026-08-02)
- Enterprise Claude Agent SDK Implementation DataAlice Labs · Alice Labs“Alice Labs has delivered 100+ production Claude Agent SDK deployments since 2023 as an Anthropic Partner. Measured cost reduction from tier-by-role model routing (Opus 5 planner / Sonnet 5 worker / Haiku 4.5 explorer): 40–60% vs single-model deployments.”(accessed 2026-08-02)
Next scheduled review: