Build Your Own Agent with the Claude Agent SDK
- The Agent SDK is Claude Code as a library. You call the same tools (reading and editing files, Bash, search), agent loop, permissions, hooks, subagents, and sessions from Python or TypeScript code.
- The packages are
claude-agent-sdkfor Python and@anthropic-ai/claude-agent-sdkfor TypeScript. Both bundle the Claude Code executable, so most of the time you don’t need to install it separately. - The agent runs in a process on your computer or server. If you want hosting handled for you too, see Managed Agents.
allowed_toolsis a “list to allow without asking,” not a restriction that says “use only these.” To really block things, usedisallowed_tools,permission_mode="dontAsk", and hooks.- Agent loops add up in cost. Always set
max_turnsandmax_budget_usd.
The examples follow the official documentation. We verified the syntax on 2026-10-11, and also confirmed that the imports, option names, and types are correct in the installed SDKs (Python 0.2.165, TypeScript 0.3.296). We didn’t make any real model calls.
What you’ll be able to do after this tutorial
Section titled “What you’ll be able to do after this tutorial”- Install the Agent SDK and build a read-only agent that reads files to find bugs.
- Attach your own business function (for example, inventory lookup) as a tool that Claude calls.
- Narrow what the agent can do with allow and deny rules, permission modes, and hooks.
- Split work with subagents and continue a conversation with a session ID.
Concepts to know first
Section titled “Concepts to know first”The subagents, hooks, and permission modes you saw in C14 were used in Claude Code through settings files. The Agent SDK lets you use those features in code.
Four ways to call Claude from code
Section titled “Four ways to call Claude from code”This is a summary of the comparison in the official overview docs.
| What you want | What to pick | Who runs the loop |
|---|---|---|
| Put a Claude Code-style agent inside your own app | Agent SDK | Your process (it launches the bundled Claude Code executable as a subprocess) |
| Develop interactively in the terminal | Claude Code CLI (C12, C14) | Your computer |
| Call the API directly and write the tool loop yourself | Client SDK (C16, Tool use) | Your code (the SDK helps if you use the tool runner) |
| Run a hosted agent through the API | Managed Agents | Anthropic’s servers |
If you want to use the same loop from another language, you can run Claude Code as a subprocess with the -p option and --output-format json (tutorial 07).
How it relates to Claude Code
Section titled “How it relates to Claude Code”- The Agent SDK launches the Claude Code executable as a subprocess and talks to it over standard input and output. One session is one process.
- If you leave settings out, it reads user, project, and local settings exactly like the Claude Code CLI.
CLAUDE.md, the skills, subagents, and commands in the.claude/folder, and the hooks in settings files all apply automatically. To start clean with only your code, passsetting_sources=[]. - Conversation history (sessions) is saved on disk as JSONL files under
~/.claude/projects/.
Step by step
Section titled “Step by step”-
Install the SDK and set the key
You need Python 3.10 or later (Node.js 18 or later for TypeScript). Install it in a virtual environment.
Terminal window mkdir my-agent && cd my-agentpython3 -m venv .venv && source .venv/bin/activatepip install claude-agent-sdkexport ANTHROPIC_API_KEY="your-api-key-here"For TypeScript, do this.
Terminal window npm init -y && npm pkg set type=modulenpm install @anthropic-ai/claude-agent-sdk zodnpm install --save-dev tsx typescript- Don’t write the key in code; supply it only as an environment variable (C16). The SDK doesn’t read
.envfiles automatically. If you keep it in a file, load it yourself. - If you use Bedrock, Vertex, or Foundry, you can also use environment variables like
CLAUDE_CODE_USE_BEDROCK=1together with the corresponding cloud credentials. - The monthly API credits included with Max and Team plans can also be used with the Agent SDK (C2).
- Don’t write the key in code; supply it only as an environment variable (C16). The SDK doesn’t read
-
Your first agent: a read-only code reviewer
This agent only reads and searches files. It doesn’t allow tools that edit files or run commands, and it denies calls that need approval instead of asking (
dontAsk). Be sure to set two caps.max_turns: a cap on the number of round trips that use tools.max_budget_usd: it stops when the estimated cost calculated by the SDK reaches this value. Since it’s an estimate it can overshoot a little, so leave some margin.
Save it as
review_agent.py.import asynciofrom claude_agent_sdk import (AssistantMessage,ClaudeAgentOptions,ResultMessage,TextBlock,ToolUseBlock,query,)async def main() -> None:options = ClaudeAgentOptions(model="claude-sonnet-5-5",allowed_tools=["Read", "Glob", "Grep"], # Tools to auto-approve without askingpermission_mode="dontAsk", # Deny every other call that needs approvalmax_turns=15, # Cap on round trips that use toolsmax_budget_usd=1.0, # Stop when the estimated cost reaches 1 dollarcwd=".",)async for message in query(prompt="Skim the Python files in this folder and list up to 3 bugs that could cause a crash. Don't modify any files.",options=options,):if isinstance(message, AssistantMessage):for block in message.content:if isinstance(block, TextBlock):print(block.text)elif isinstance(block, ToolUseBlock):print(f"[tool call] {block.name}")elif isinstance(message, ResultMessage):cost = message.total_cost_usdprint(f"Done: {message.subtype}, turns {message.num_turns}, estimated cost {cost}")asyncio.run(main())Terminal window python review_agent.pyquery()is an async iterator. While the agent thinks, calls tools, and looks at the results, messages flow out one at a time. The finalResultMessagecontains the reason it finished (subtype) and the estimated cost (total_cost_usd).subtypeMeaning successFinished normally. The answer is in message.result.error_max_turnsHit max_turns.error_max_budget_usdHit max_budget_usd.error_during_executionAn error occurred during execution. The same agent in TypeScript
import { query } from "@anthropic-ai/claude-agent-sdk";for await (const message of query({prompt:"Skim the code in this folder and list up to 3 bugs that could cause a crash. Don't modify any files.",options: {model: "claude-sonnet-5-5",allowedTools: ["Read", "Glob", "Grep"], // Tools to auto-approve without askingpermissionMode: "dontAsk", // Deny every other call that needs approvalmaxTurns: 15, // Cap on round trips that use toolsmaxBudgetUsd: 1.0, // Stop when the estimated cost reaches 1 dollar},})) {if (message.type === "assistant") {for (const block of message.message.content) {if (block.type === "text") console.log(block.text);else if (block.type === "tool_use") console.log(`[tool call] ${block.name}`);}} else if (message.type === "result") {console.log(`Done: ${message.subtype}, estimated cost ${message.total_cost_usd}`);}}Terminal window npx tsx review-agent.tsCopy and paste this promptBuild a read-only code review agent with the Agent SDK (Python). Allow only the Read, Glob, and Grep tools, set permission_mode to dontAsk, make sure to set caps with max_turns and max_budget_usd, and have it read the API key only from an environment variable.
-
Attach your own tool: inventory lookup
You can write functions that Claude can call. It works by creating a small MCP server containing your tools inside the same process, so you don’t need to start a separate server.
- Use
@tool(name, description, input schema)to turn a function into a tool. The description is what Claude uses to decide “when to call it.” - If the server key is
inventoryand the tool name isget_stock, the name Claude sees ismcp__inventory__get_stock. If you put this name inallowed_tools, it runs without asking. tools=[]removes all built-in tools (Bash, Edit, and so on). This agent can only look up inventory.- Return failures with
is_error: True, and Claude will read the content and explain it to the user.
Save it as
stock_agent.py. The inventory data is fake values for the example.import asynciofrom typing import Anyfrom claude_agent_sdk import (ClaudeAgentOptions,ResultMessage,create_sdk_mcp_server,query,tool,)# Fake inventory data for the example. In real use, change it to read your internal DB or API.STOCK = {"A-100": 12, "B-200": 0, "C-300": 45}@tool("get_stock","Look up the current stock quantity by product code. Read-only.",{"sku": str},)async def get_stock(args: dict[str, Any]) -> dict[str, Any]:sku = str(args["sku"]).strip().upper()if sku not in STOCK:return {"content": [{"type": "text", "text": f"Unknown product code: {sku}"}],"is_error": True,}return {"content": [{"type": "text", "text": f"{sku} stock: {STOCK[sku]} units"}]}inventory = create_sdk_mcp_server(name="inventory", version="1.0.0", tools=[get_stock])async def main() -> None:options = ClaudeAgentOptions(mcp_servers={"inventory": inventory},tools=[], # Remove all built-in tools (Bash, Edit, and so on) andallowed_tools=["mcp__inventory__get_stock"], # auto-approve only this toolpermission_mode="dontAsk",max_turns=5,max_budget_usd=0.5,)async for message in query(prompt="Tell me the stock for A-100 and B-200, and let me know if any product is sold out.",options=options,):if isinstance(message, ResultMessage) and message.subtype == "success":print(message.result)asyncio.run(main())TypeScript version (input schema with zod)
import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";import { z } from "zod";// Fake inventory data for the example. In real use, change it to read your internal DB or API.const STOCK: Record<string, number> = { "A-100": 12, "B-200": 0, "C-300": 45 };const getStock = tool("get_stock","Look up the current stock quantity by product code. Read-only.",{ sku: z.string().describe("Product code, e.g. A-100") },async (args) => {const sku = args.sku.trim().toUpperCase();if (!(sku in STOCK)) {return {content: [{ type: "text" as const, text: `Unknown product code: ${sku}` }],isError: true,};}return { content: [{ type: "text" as const, text: `${sku} stock: ${STOCK[sku]} units` }] };},{ annotations: { readOnlyHint: true } },);const inventory = createSdkMcpServer({ name: "inventory", version: "1.0.0", tools: [getStock] });for await (const message of query({prompt: "Tell me the stock for A-100 and B-200, and let me know if any product is sold out.",options: {mcpServers: { inventory },tools: [], // Remove all built-in tools andallowedTools: ["mcp__inventory__get_stock"], // auto-approve only this toolpermissionMode: "dontAsk",maxTurns: 5,maxBudgetUsd: 0.5,},})) {if (message.type === "result" && message.subtype === "success") {console.log(message.result);}} - Use
-
Lock down permissions: rules and hooks
If you need write or execute tools, narrow things down in four layers. For each call, the SDK checks in this order: hooks -> deny rules -> ask rules -> permission mode -> allow rules -> the
canUseToolcallback.- If you write only a name, like
disallowed_tools=["Bash"], the tool disappears from Claude’s view. If you use a scoped rule like"Bash(rm *)", the tool stays and only the matching calls are denied in any mode. - A
PreToolUsehook calls your code right before a tool runs. If you returnpermissionDecision: "deny", it’s blocked and the reason is passed to Claude. If you return{}, it goes ahead as is. - A hook’s
matcheronly compares tool names. Check arguments such as file paths inside the callback.
Save it as
guard_agent.py.import asynciofrom typing import Anyfrom claude_agent_sdk import ClaudeAgentOptions, HookMatcher, ResultMessage, queryasync def block_risky(input_data: dict[str, Any], tool_use_id: str | None, context: Any) -> dict[str, Any]:"""Block Bash commands that contain risky patterns before they run."""command = input_data.get("tool_input", {}).get("command", "")if any(word in command for word in ("rm -rf", "git push", "curl ")):return {"hookSpecificOutput": {"hookEventName": "PreToolUse","permissionDecision": "deny","permissionDecisionReason": "Risky commands or commands that reach outside aren't allowed.",}}return {} # Empty dictionary: go ahead as isasync def main() -> None:options = ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"],disallowed_tools=["Bash(git push *)", "Bash(rm *)"], # Block once more with rulespermission_mode="acceptEdits",hooks={"PreToolUse": [HookMatcher(matcher="Bash", hooks=[block_risky])]},max_turns=20,max_budget_usd=2.0,)async for message in query(prompt="Run the tests and fix the ones that fail.", options=options):if isinstance(message, ResultMessage):print(message.subtype, message.total_cost_usd)asyncio.run(main()) - If you write only a name, like
-
Split work with subagents
A subagent is a helper agent with its own context and tool permissions (for the concept, see C14). Only the final report comes back to the parent, so the parent’s context fills up more slowly.
- Put
AgentDefinitionentries inagents={...}. Thedescriptiondecides “when to call this subagent.” - The parent’s
allowed_toolsmust include"Agent"for it to call subagents. modelis an alias like"sonnet","opus", or"haiku", or a full model ID. Sending light reviews to a cheaper model lowers cost (C15).- Some field names in
AgentDefinitionstay in camelCase (disallowedTools,maxTurns,permissionMode). If you write them in snake_case, you get aTypeError. - A subagent can’t see the parent’s conversation or system prompt. Any file paths or decisions it needs must go into the prompt you pass to the Agent tool.
Save it as
subagent_agent.py.import asynciofrom claude_agent_sdk import AgentDefinition, ClaudeAgentOptions, ResultMessage, queryasync def main() -> None:options = ClaudeAgentOptions(model="claude-opus-5-5",allowed_tools=["Read", "Grep", "Glob", "Agent"], # "Agent" must be present to call subagentspermission_mode="dontAsk",agents={"security-reviewer": AgentDefinition(description="A read-only reviewer that finds security vulnerabilities. Use it to review authentication and input validation.",prompt="You are a security reviewer. Read the code and report only the vulnerabilities, briefly. Do not modify any files.",tools=["Read", "Grep", "Glob"],model="sonnet",),"test-gap-finder": AgentDefinition(description="A reviewer that finds functions missing tests.",prompt="You are a test coverage reviewer. Report the important functions that have no tests, as a list.",tools=["Read", "Grep", "Glob"],model="haiku",),},env={"CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH": "1", # Keep subagents from creating more subagents"CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS": "3",},max_turns=30,max_budget_usd=3.0,)async for message in query(prompt="Use security-reviewer and test-gap-finder to review this repository, and summarize it on one page.",options=options,):if isinstance(message, ResultMessage) and message.subtype == "success":print(message.result)asyncio.run(main()) - Put
-
Sessions: continuing a conversation
A session is the conversation history the agent has built up (prompts, tool calls and results, responses). The SDK saves it to disk automatically. File changes aren’t saved (files need a separate checkpoint feature).
What you want How Multiple turns in one process Python ClaudeSDKClient(in TypeScript,continue: true)Continue the most recent conversation after a restart continue_conversation=TrueContinue a specific conversation resume=session_idKeep the original and try another direction resume=session_idwithfork_session=TrueThe
session_idis in theResultMessage. Save it assession_agent.py.import asynciofrom claude_agent_sdk import (AssistantMessage,ClaudeAgentOptions,ClaudeSDKClient,ResultMessage,TextBlock,query,)def show(message) -> None:if isinstance(message, AssistantMessage):for block in message.content:if isinstance(block, TextBlock):print(block.text)elif isinstance(message, ResultMessage):print(f"[{message.subtype}] session_id={message.session_id}")async def main() -> None:options = ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep"],permission_mode="dontAsk",max_turns=10,max_budget_usd=1.0,)# 1) Multiple turns within one process: ClaudeSDKClient continues the session for you.async with ClaudeSDKClient(options=options) as client:await client.query("Analyze how the auth module is structured.")async for message in client.receive_response():show(message)await client.query("Explain again just the riskiest part of that analysis.")async for message in client.receive_response():show(message)# 2) After restarting the process: continue with a saved session_idsaved_session_id = "your-saved-session_id-here"async for message in query(prompt="Continuing from there, suggest how to fix that part.",options=ClaudeAgentOptions(resume=saved_session_id,allowed_tools=["Read", "Glob", "Grep"],permission_mode="dontAsk",max_turns=10,max_budget_usd=1.0,),):show(message)asyncio.run(main())saved_session_idin the code above is a placeholder. Replace it with thesession_idvalue printed on your first run.- Session files exist only on the computer that created them. To continue on another server, you have to copy the conversation history to shared storage with a
SessionStoreadapter or move the session files. - The official docs warn that if you
breakout while reading messages fromClaudeSDKClient, you can run into asyncio cleanup problems. Read all the way to the end.
Quick reference
Section titled “Quick reference”Commonly used options (ClaudeAgentOptions; camelCase in TypeScript)
Section titled “Commonly used options (ClaudeAgentOptions; camelCase in TypeScript)”| Option | What it does |
|---|---|
allowed_tools |
Tools to auto-approve without asking. It doesn’t block tools you don’t list. |
disallowed_tools |
Deny rules. A bare name removes the tool; something like Bash(rm *) denies only matching calls. |
tools |
The set of built-in tools available. [] removes all built-in tools. MCP tools aren’t affected. |
permission_mode |
default, dontAsk, acceptEdits, plan, auto, bypassPermissions |
max_turns |
Cap on tool round trips |
max_budget_usd |
Cap on estimated cost (it’s an estimate, so it can overshoot) |
model |
Model ID or alias. If omitted, the default model is used. |
system_prompt |
System prompt |
mcp_servers |
Custom tool servers or external MCP servers |
agents |
Subagent definitions |
hooks |
Hook callbacks |
setting_sources |
Which settings to load. If omitted, all of user, project, and local. [] turns them all off. |
resume, continue_conversation, fork_session |
Resuming and branching sessions |
cwd |
Working folder. Project settings and CLAUDE.md are looked for in this folder. |
env |
Subprocess environment variables |
Permission modes
Section titled “Permission modes”| Mode | Behavior |
|---|---|
default |
No auto-approval. Calls that need approval go to the canUseTool callback. |
dontAsk |
Denies instead of asking. Tools on the allow list and calls that need no approval still run. |
acceptEdits |
Auto-approves file edits and file commands like mkdir, rm, and mv (only inside the working folder). |
plan |
Only plans; doesn’t edit files. |
auto |
A model classifier reviews each action and allows or blocks it. |
bypassPermissions |
Skips most approvals. Use only in an isolated environment. |
Packages and requirements
Section titled “Packages and requirements”| Item | Value |
|---|---|
| Python package | claude-agent-sdk (Python 3.10 or later) |
| TypeScript package | @anthropic-ai/claude-agent-sdk (Node.js 18 or later) |
| Starting point for hosting | The guidance is to start at about 1 GiB RAM, 5 GiB disk, and 1 CPU per agent. Memory grows with longer sessions. |
| Network | Outbound HTTPS to api.anthropic.com (the corresponding endpoints for Bedrock and Vertex) |
| Models and pricing | Same as C16. Opus 5.5 claude-opus-5-5 $4/$20, Sonnet 5.5 claude-sonnet-5-5 $2/$10 (per 1 million tokens, as of 2026-10-11) |
Common sticking points
Section titled “Common sticking points”I put only Read in allowed_tools, but Bash runs too
Section titled “I put only Read in allowed_tools, but Bash runs too”- Cause:
allowed_toolsis an “auto-approve list.” There are tools you didn’t list, and if they need approval, it falls through to the permission mode. In modes likebypassPermissionsorauto, they may run as is. - Fix: Use
permission_mode="dontAsk"together with it, or remove the tool itself withdisallowed_tools=["Bash"]ortools=["Read", "Glob", "Grep"].
I defined a subagent, but Claude doesn’t call it
Section titled “I defined a subagent, but Claude doesn’t call it”- Cause: The parent’s
allowed_toolsdoesn’t include"Agent", or thedescriptionis vague so Claude doesn’t know when to use it. - Fix: Add
"Agent"and write “when to use it” concretely in thedescription. You can also name it directly in the prompt, like “use security-reviewer to …”.
The hook doesn’t run
Section titled “The hook doesn’t run”- Cause: The event name is wrong (
PreToolUse, case-sensitive), or the matcher doesn’t match the tool name. If you hitmax_turns, the session can also end before the hook runs. Python SDK callbacks don’t support theSessionStartandSessionEndevents (only TypeScript does). - Fix: Check the event name, and narrow it down by leaving the matcher empty so it applies to every call.
An auth error (Not logged in, Invalid API key) appears
Section titled “An auth error (Not logged in, Invalid API key) appears”- Cause:
ANTHROPIC_API_KEYisn’t set in the shell where the agent runs. The SDK doesn’t read.envautomatically. - Fix: Set the environment variable in the same shell, or load it directly in code.
The CLAUDE.md and settings from my own computer leak into the agent
Section titled “The CLAUDE.md and settings from my own computer leak into the agent”- Cause: If you omit
setting_sources, the default is to read all of user, project, and local settings. - Fix: Start service agents with
setting_sources=[]. If you handle multiple users in one container, the official docs say to give each user a separate working folder and also putCLAUDE_CODE_DISABLE_AUTO_MEMORY=1in the environment.
I try to resume a session but get a new conversation
Section titled “I try to resume a session but get a new conversation”- Cause:
query()creates a new session on each call. Session files exist only on the computer that created them and can’t be found from another server. - Fix: Pass the right
session_idtoresume, and if you have several servers, share the history with aSessionStore.
Practical tips
Section titled “Practical tips”- Caps first, features later. Start a new agent small, like
max_turns=10andmax_budget_usd=1.0, and raise them as you see results. The official hosting docs also say token costs are usually much larger than container costs, and that one long session can spend several dollars in tokens. - Log the
ResultMessage. Recordingtotal_cost_usd,num_turns, andsession_idmakes cost tracking and reproduction easier. The official reference says to usemodel_usageto see subagents accurately. - Cheap models and narrow tools for subagents. For read-only review,
tools=["Read", "Grep", "Glob"]and a small model are enough. - Have a person confirm writes. For an agent that edits files, either get the plan first with
permission_mode="plan", or manage the working folder with Git so you can undo changes. - Run it isolated. The official hosting docs recommend running the SDK in a container sandbox. It’s safer to let outbound calls through a proxy that allows only approved domains, and to keep tool credentials out of the agent’s environment.
- If you don’t want to run servers yourself, compare Managed Agents, where Anthropic hosts the agent loop and sandbox.
What to read next
Section titled “What to read next”- 4. Run agents on a server with Managed Agents — handing off the agent loop too
- 1. Build a work bot with tool use — writing the tool loop yourself through the API, without the SDK
- C14. Claude Code core features — using subagents, hooks, and permission modes through settings files
- 7. Claude Code headless mode and GitHub Actions automation — running the same agent in CI
Sources
Last verified: Nov 2, 2026
- Agent SDK overview code.claude.com
- Agent SDK quickstart code.claude.com
- Agent SDK reference - Python code.claude.com
- Give Claude custom tools code.claude.com
- Configure permissions code.claude.com
- Intercept and control agent behavior with hooks code.claude.com
- Subagents in the SDK code.claude.com
- Work with sessions code.claude.com
- Use Claude Code features in the SDK code.claude.com
- Hosting the Agent SDK code.claude.com
- Models overview (model IDs and pricing) platform.claude.com
- claude-agent-sdk (PyPI) pypi.org
- @anthropic-ai/claude-agent-sdk (npm) www.npmjs.com
Prices, limits, and menu names change often. Before making an important decision, check the official pages above for the latest details.
Finished this tutorial?
Progress is saved only in this browser and never sent anywhere.