Simple definition#
The Claude Agent SDK is Claude Code as a library. From Python or TypeScript you call query(), and the SDK runs the same agent loop, built-in tools (read, edit, shell, search, web), permissions, sessions, hooks, sub-agents and MCP support that power the Claude Code CLI — inside a process you operate. You supply the prompt, the tools it may use, and callbacks that decide what it’s allowed to do.
Which Claude tool to build with#
| You want to | Use | You get |
|---|---|---|
| Embed a capable coding/file agent in your own Python or TypeScript app | Agent SDK | Claude Code’s loop, tools, permissions, sessions and hooks as a library |
| Interactive development, one-off tasks | Claude Code CLI | The terminal experience; claude -p for scripts |
| Call the model directly and own the loop | Client SDK (Messages API) | Full control; you write tools and the loop (or use the tool runner) |
| Anthropic hosts the agent and its sandbox | Managed Agents | Hosted harness configured through the API |
Other languages: run claude -p … --output-format json as a subprocess. See The Claude API for builders for the Client SDK and Managed Agents.
Install and authenticate#
pip install claude-agent-sdk # or: uv add claude-agent-sdk (Python 3.10+)
npm install @anthropic-ai/claude-agent-sdk # Node 18.14+
export ANTHROPIC_API_KEY=sk-ant-… # read from the process environment, not .env
Both packages bundle a native Claude Code binary. Cloud providers work with the same variables as the CLI (CLAUDE_CODE_USE_BEDROCK=1, CLAUDE_CODE_USE_VERTEX=1, CLAUDE_CODE_USE_FOUNDRY=1).
First agent#
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage
async def main():
async for message in query(
prompt="Review utils.py for bugs that would cause crashes. Fix any you find.",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Glob"],
permission_mode="acceptEdits",
max_turns=20,
),
):
if isinstance(message, AssistantMessage):
for block in message.content:
if hasattr(block, "text"):
print(block.text)
elif isinstance(message, ResultMessage):
print(f"Done: {message.subtype}, cost ${message.total_cost_usd or 0:.4f}")
asyncio.run(main())
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Review utils.py for bugs that would cause crashes. Fix any you find.",
options: { allowedTools: ["Read", "Edit", "Glob"], permissionMode: "acceptEdits", maxTurns: 20 },
})) {
if (message.type === "result") console.log(`Done: ${message.subtype}`);
}
query() returns an async stream of messages: system init, assistant text and tool calls, tool results, and a final result message (subtype is success, or e.g. error_max_turns; it carries cost and usage).
Key options#
| Option (Python / TypeScript) | Purpose |
|---|---|
allowed_tools / allowedTools |
Pre-approve tools (adds allow rules) |
disallowed_tools / disallowedTools |
Deny tools |
permission_mode / permissionMode |
default, acceptEdits, plan, auto, dontAsk, bypassPermissions |
can_use_tool / canUseTool |
Your callback for anything not resolved earlier |
system_prompt / systemPrompt |
Replace or append to the system prompt |
model, max_turns / maxTurns |
Model and turn cap |
cwd |
Working directory — give each session its own |
mcp_servers / mcpServers |
External or in-process MCP servers |
hooks |
Hook callbacks by event |
agents |
Sub-agent definitions |
setting_sources / settingSources |
Which of user, project, local settings, CLAUDE.md and skills to load |
resume, continue_conversation / continue, fork_session / forkSession |
Sessions |
output_format / outputFormat |
Validated structured output against a JSON Schema |
env |
Environment for the subprocess |
Permissions: evaluation order#
- Hooks (
PreToolUse) — can deny; anallowdoesn’t skip the next steps. - Deny rules — from
disallowed_toolsand settings. - Ask rules.
- Permission mode — e.g.
acceptEditsapproves edits,bypassPermissionsapproves almost everything. - Allow rules — from
allowed_toolsand settings. canUseToolcallback — your code decides (skipped and denied indontAsk).
from claude_agent_sdk import ClaudeAgentOptions, PermissionResultAllow, PermissionResultDeny
async def can_use_tool(tool_name, input_data, context):
if tool_name == "Bash" and "rm -rf" in input_data.get("command", ""):
return PermissionResultDeny(message="Destructive commands are not allowed")
return PermissionResultAllow(updated_input=input_data)
options = ClaudeAgentOptions(can_use_tool=can_use_tool)
TypeScript returns { behavior: "allow", updatedInput } or { behavior: "deny", message }.
Non-interactive runs need an explicit mode. If tool calls are unexpectedly denied after an upgrade, pass permission_mode / permissionMode explicitly rather than relying on the default.
Custom tools: in-process MCP servers#
from typing import Annotated, Any
from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions
@tool("get_order", "Look up an order by ID", {"order_id": Annotated[str, "Order ID"]})
async def get_order(args: dict[str, Any]) -> dict[str, Any]:
order = await orders_api.fetch(args["order_id"]) # your code
return {"content": [{"type": "text", "text": order.to_json()}]}
shop = create_sdk_mcp_server(name="shop", version="1.0.0", tools=[get_order])
options = ClaudeAgentOptions(
mcp_servers={"shop": shop},
allowed_tools=["mcp__shop__get_order"], # mcp__<server>__<tool>
)
TypeScript uses tool(name, description, zodSchema, handler) and createSdkMcpServer({...}). External MCP servers (stdio, HTTP) are passed the same way as config objects.
Hooks as callbacks#
from claude_agent_sdk import ClaudeAgentOptions, HookMatcher
async def protect_env(input_data, tool_use_id, context):
path = input_data["tool_input"].get("file_path", "")
if path.endswith(".env"):
return {"hookSpecificOutput": {
"hookEventName": input_data["hook_event_name"],
"permissionDecision": "deny",
"permissionDecisionReason": "Cannot modify .env files"}}
return {}
options = ClaudeAgentOptions(hooks={"PreToolUse": [HookMatcher(matcher="Write|Edit", hooks=[protect_env])]})
Same events and output fields as the hooks reference, as functions instead of shell commands — useful for audit logging, redaction (updatedInput, updatedToolOutput) and policy.
Sessions#
| Need | Use |
|---|---|
| Multi-turn chat in one process | ClaudeSDKClient (Python) or streaming input (TypeScript) |
| Pick up the most recent session after a restart | continue_conversation=True / continue: true |
| Resume a specific session | Capture session_id from the init message, pass resume |
| Branch from a past session | resume + fork_session |
async with ClaudeSDKClient(options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Grep"])) as client:
await client.query("Analyze the auth module")
async for m in client.receive_response(): ...
await client.query("Now refactor it to use JWT") # same session, full context
async for m in client.receive_response(): ...
Transcripts live on the container’s disk; to resume on another host, persist them (session storage options exist for this).
Configuration loading#
By default the SDK loads .claude/ configuration like the CLI: settings, CLAUDE.md, skills, commands, sub-agents and hooks. For a product, be explicit:
setting_sources=[]/settingSources: []— ignore user, project and local settings for a reproducible agent; include"project"if you rely on.claude/settings.jsonpermission rules.- Auto memory loads regardless — set
CLAUDE_CODE_DISABLE_AUTO_MEMORY=1inenvif you don’t want it. - Define the system prompt, tools, agents and MCP servers in code.
Hosting#
The SDK spawns a claude subprocess per session and talks to it over stdio; that process owns the shell, working directory and transcript. So:
| Pattern | Fits |
|---|---|
| Ephemeral — one container per task, destroyed after | Bug fixes, document extraction, translations |
| Long-running — persistent containers serving many sessions | Email triage, chat bots, per-user site builders |
| Hybrid — ephemeral containers that resume persisted sessions | Intermittent long tasks |
| Multi-agent container — several SDK processes sharing a workspace | Cooperating agents |
- Start at 1 GiB RAM, 5 GiB disk, 1 CPU per agent; memory grows with session length.
- Outbound HTTPS to the API (or your provider) and to any MCP servers; nothing listens except your app.
- Run each agent in a sandboxed container with scoped network egress; separate
cwdper session; per-tenant isolation for multi-tenant products. - Cap with
max_turns, tracktotal_cost_usd, and export OpenTelemetry for observability.
Common mistakes#
Review questions#
How does the Agent SDK differ from the Client SDK? The Agent SDK runs Claude Code’s full agent loop with built-in tools, permissions and sessions; the Client SDK calls the Messages API and leaves the loop and tools to you.
In what order are tool calls decided?
Hooks → deny rules → ask rules → permission mode → allow rules → canUseTool.
How do you add your own business tool?
Define it with tool(), wrap it in create_sdk_mcp_server, pass it in mcp_servers, and allow mcp__<server>__<tool>.
References#
- Anthropic, Agent SDK overview and Quickstart.
- Anthropic, Permissions, Custom tools, Hooks and Sessions.
- Anthropic, Hosting the Agent SDK and Secure deployment.
- Anthropic, Python SDK reference and TypeScript SDK reference.