Skip to content
한국어

Build Your Own Agent with the Claude Agent SDK

In short
  • 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-sdk for Python and @anthropic-ai/claude-agent-sdk for 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_tools is a “list to allow without asking,” not a restriction that says “use only these.” To really block things, use disallowed_tools, permission_mode="dontAsk", and hooks.
  • Agent loops add up in cost. Always set max_turns and max_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.

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.

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

  • 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, pass setting_sources=[].
  • Conversation history (sessions) is saved on disk as JSONL files under ~/.claude/projects/.
0/6 done
  1. 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-agent
    python3 -m venv .venv && source .venv/bin/activate
    pip install claude-agent-sdk
    export ANTHROPIC_API_KEY="your-api-key-here"

    For TypeScript, do this.

    Terminal window
    npm init -y && npm pkg set type=module
    npm install @anthropic-ai/claude-agent-sdk zod
    npm 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 .env files 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=1 together with the corresponding cloud credentials.
    • The monthly API credits included with Max and Team plans can also be used with the Agent SDK (C2).
  2. 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 asyncio
    from 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 asking
    permission_mode="dontAsk", # Deny every other call that needs approval
    max_turns=15, # Cap on round trips that use tools
    max_budget_usd=1.0, # Stop when the estimated cost reaches 1 dollar
    cwd=".",
    )
    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_usd
    print(f"Done: {message.subtype}, turns {message.num_turns}, estimated cost {cost}")
    asyncio.run(main())
    Terminal window
    python review_agent.py

    query() is an async iterator. While the agent thinks, calls tools, and looks at the results, messages flow out one at a time. The final ResultMessage contains the reason it finished (subtype) and the estimated cost (total_cost_usd).

    subtype Meaning
    success Finished normally. The answer is in message.result.
    error_max_turns Hit max_turns.
    error_max_budget_usd Hit max_budget_usd.
    error_during_execution An 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 asking
    permissionMode: "dontAsk", // Deny every other call that needs approval
    maxTurns: 15, // Cap on round trips that use tools
    maxBudgetUsd: 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.ts
    Copy and paste this prompt

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

  3. 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 inventory and the tool name is get_stock, the name Claude sees is mcp__inventory__get_stock. If you put this name in allowed_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 asyncio
    from typing import Any
    from 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) and
    allowed_tools=["mcp__inventory__get_stock"], # auto-approve only this tool
    permission_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 and
    allowedTools: ["mcp__inventory__get_stock"], // auto-approve only this tool
    permissionMode: "dontAsk",
    maxTurns: 5,
    maxBudgetUsd: 0.5,
    },
    })) {
    if (message.type === "result" && message.subtype === "success") {
    console.log(message.result);
    }
    }
  4. 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 canUseTool callback.

    • 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 PreToolUse hook calls your code right before a tool runs. If you return permissionDecision: "deny", it’s blocked and the reason is passed to Claude. If you return {}, it goes ahead as is.
    • A hook’s matcher only compares tool names. Check arguments such as file paths inside the callback.

    Save it as guard_agent.py.

    import asyncio
    from typing import Any
    from claude_agent_sdk import ClaudeAgentOptions, HookMatcher, ResultMessage, query
    async 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 is
    async def main() -> None:
    options = ClaudeAgentOptions(
    allowed_tools=["Read", "Edit", "Bash"],
    disallowed_tools=["Bash(git push *)", "Bash(rm *)"], # Block once more with rules
    permission_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())
  5. 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 AgentDefinition entries in agents={...}. The description decides “when to call this subagent.”
    • The parent’s allowed_tools must include "Agent" for it to call subagents.
    • model is 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 AgentDefinition stay in camelCase (disallowedTools, maxTurns, permissionMode). If you write them in snake_case, you get a TypeError.
    • 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 asyncio
    from claude_agent_sdk import AgentDefinition, ClaudeAgentOptions, ResultMessage, query
    async def main() -> None:
    options = ClaudeAgentOptions(
    model="claude-opus-5-5",
    allowed_tools=["Read", "Grep", "Glob", "Agent"], # "Agent" must be present to call subagents
    permission_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())
  6. 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=True
    Continue a specific conversation resume=session_id
    Keep the original and try another direction resume=session_id with fork_session=True

    The session_id is in the ResultMessage. Save it as session_agent.py.

    import asyncio
    from 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_id
    saved_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_id in the code above is a placeholder. Replace it with the session_id value 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 SessionStore adapter or move the session files.
    • The official docs warn that if you break out while reading messages from ClaudeSDKClient, you can run into asyncio cleanup problems. Read all the way to the end.

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

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_tools is 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 like bypassPermissions or auto, they may run as is.
  • Fix: Use permission_mode="dontAsk" together with it, or remove the tool itself with disallowed_tools=["Bash"] or tools=["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_tools doesn’t include "Agent", or the description is vague so Claude doesn’t know when to use it.
  • Fix: Add "Agent" and write “when to use it” concretely in the description. You can also name it directly in the prompt, like “use security-reviewer to …”.
  • Cause: The event name is wrong (PreToolUse, case-sensitive), or the matcher doesn’t match the tool name. If you hit max_turns, the session can also end before the hook runs. Python SDK callbacks don’t support the SessionStart and SessionEnd events (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_KEY isn’t set in the shell where the agent runs. The SDK doesn’t read .env automatically.
  • 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 put CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 in 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_id to resume, and if you have several servers, share the history with a SessionStore.
  • Caps first, features later. Start a new agent small, like max_turns=10 and max_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. Recording total_cost_usd, num_turns, and session_id makes cost tracking and reproduction easier. The official reference says to use model_usage to 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.

Sources

Last verified: Nov 2, 2026

Prices, limits, and menu names change often. Before making an important decision, check the official pages above for the latest details.