Claude Agent SDK: Build Agents in Python and TypeScript

By Updated

What is the Claude Agent SDK?

The Claude Agent SDK is Anthropic's library for Python and TypeScript that embeds Claude Code's agent loop, tools, permissions, hooks and sessions in your application. It starts the Claude Code binary as a child process on your machine and returns a stream of messages. In most cases you don't need to install Claude Code separately.

TL;DR

  • -Packages as of November 29, 2026: claude-agent-sdk 0.2.189 (Python 3.10+, Alpha classifier) and @anthropic-ai/claude-agent-sdk 0.3.332 (Node 18.14+). Both ship Claude Code inside.
  • -allowed_tools pre-approves calls and doesn't narrow the toolset. tools and disallowed_tools narrow it, dontAsk mode denies instead of prompting, and a PreToolUse hook with deny has the last word.
  • -By default the SDK reads user, project and local settings. In the author's test a "Reply ok" request took 646 input tokens with tools=[] and setting_sources=[], and 16,356 with the default tools.
  • -subtype=success doesn't mean the task is done: in the test a denied file write ended with success and is_error=False. Check permission_denials and the result itself.
  • -The project CLAUDE.md didn't load for the author in the bundled CLI 2.1.332, although the docs promise it. The changelog gave no reason, so check loading after every update.

The Claude Agent SDK is Anthropic’s library for Python and TypeScript that embeds Claude Code’s agent loop, with its tools, permissions, hooks and sessions, in your application. The SDK starts the Claude Code binary as a child process and returns a stream of messages. Choose it when an agent needs files, commands and multi-step work. For a single model request, the Claude API is enough.

TaskWhat to useWhat you get
An agent inside your own applicationAgent SDKClaude Code’s loop and tools in your process
Terminal work, one-off tasksClaude Code CLIan interface, claude -p for scripts
A direct model callClient SDKyou write the tool loop or use the beta runner
An agent on Anthropic’s sideManaged Agentsa cloud sandbox or your own, managed through an API

The table condenses the comparison in the docs. For other languages they recommend running the CLI with -p and --output-format json.

This article covers how to install the SDK, build an agent, restrict it and avoid a surprising bill. The documentation and changelogs were checked on November 29, 2026. The author’s tests are from the same day: claude-agent-sdk 0.2.189, Python 3.13, bundled CLI 2.1.332, subscription login, Haiku 5.5, a folder with calc.py and CLAUDE.md, one run each unless stated otherwise. The author didn’t run TypeScript; everything about it comes from the documentation. The Python examples are simplified from the test scripts and checked for syntax and imports; dontAsk, ClaudeSDKClient and the subagent options in env weren’t run against a model. For building an agent from scratch, see the AI agent tutorial.

Install the Claude Agent SDK

# Python 3.10+
uv init && uv add claude-agent-sdk
# or: python3 -m venv .venv && source .venv/bin/activate && pip install claude-agent-sdk

# TypeScript, Node 18.14+
npm init -y && npm pkg set type=module
npm install @anthropic-ai/claude-agent-sdk
npm install --save-dev tsx

export ANTHROPIC_API_KEY=your-api-key
PythonTypeScript
Version on Nov 29, 20260.2.189 (Nov 25)0.3.332 (Nov 24)
Bundled Claude Code2.1.332 (measured)2.1.332 (npm metadata)
License in the registryMITSEE LICENSE IN README.md
Required alongsidenothingzod 4, @anthropic-ai/sdk, @modelcontextprotocol/sdk (peer)

Version numbers differ between languages, so pin each one separately. The author’s Python environment took 397 MB because the CLI is inside. The earlier claude-code-sdk package was renamed, and ClaudeCodeOptions became ClaudeAgentOptions (migration guide).

Your first agent: query()

import asyncio
from claude_agent_sdk import (
    AssistantMessage, ClaudeAgentOptions, ResultError,
    ResultMessage, TextBlock, query,
)

OPTIONS = ClaudeAgentOptions(
    model="haiku",
    tools=["Read", "Glob", "Grep"],
    allowed_tools=["Read", "Glob", "Grep"],
    permission_mode="dontAsk",
    setting_sources=[],
    strict_mcp_config=True,
    max_turns=10,
)

async def run(prompt: str) -> ResultMessage | None:
    result = None
    try:
        async for m in query(prompt=prompt, options=OPTIONS):
            if isinstance(m, AssistantMessage):
                for block in m.content:
                    if isinstance(block, TextBlock):
                        print(block.text)
            elif isinstance(m, ResultMessage):
                result = m
    except ResultError as e:
        print("run failed:", e.subtype)
    return result

Run it with asyncio.run(run("What does calc.py do?")). The same call in TypeScript:

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const m of query({
  prompt: "What does calc.py do?",
  options: {
    tools: ["Read", "Glob", "Grep"],
    allowedTools: ["Read", "Glob", "Grep"],
    permissionMode: "dontAsk",
    settingSources: [],
    strictMcpConfig: true,
  },
})) {
  if (m.type === "result") console.log(m.subtype, m.total_cost_usd);
}

A successful run isn’t a completed task

The author asked for a file to be created without granting permissions. The write was denied and there was no file, yet the result came back with subtype=success and is_error=False: the loop finished normally, and the model honestly reported the denial. Check three things: the subtype, the permission_denials list and the artifact itself (a file, a test, a database record).

On an error, a one-shot query() first yields a ResultMessage, then raises ResultError. In the test max_turns=1 produced error_max_turns and an exception. Without try the program crashes after it already has a useful result.

Conversations and sessions

You needPythonTypeScript
Several messages in one processClaudeSDKClientstreaming input to query()
Continue the folder’s latest sessioncontinue_conversation=Truecontinue: true
Continue a specific oneresume=session_idresume: sessionId
Branch from a sessionresume=..., fork_session=TrueforkSession: true
from claude_agent_sdk import ClaudeSDKClient

async def dialog() -> None:
    async with ClaudeSDKClient(options=OPTIONS) as client:
        for prompt in ("List the functions in calc.py", "Which one fails on []?"):
            await client.query(prompt)
            async for m in client.receive_response():
                if isinstance(m, ResultMessage):
                    print(m.result)

The Python reference asks you not to leave the message loop with break: it can cause asyncio cleanup issues. Take session_id from ResultMessage. In the test resume brought back a code word from the previous session.

According to the docs, a session is stored in ~/.claude/projects/<folder>/ on the machine where it was created. For another host, plug in a session_store or move the file. A fork copies the history, while working files stay shared.

Tools: built-in, custom, MCP

With default tools and setting_sources=[] the author’s session had 25 tools, with tools=[] none, with a custom server 26. Descriptions of loaded tools travel in every request, so the set affects both price and context:

“Reply ok” requestInput tokens
tools=[], setting_sources=[]646
default tools16,356

You describe a custom tool as a function, and the server lives in your process:

import json
from claude_agent_sdk import create_sdk_mcp_server, tool

@tool("convert", "Convert USD to EUR", {"amount": float})
async def convert(args):
    eur = round(args["amount"] * 0.92, 2)
    return {"content": [{"type": "text", "text": json.dumps({"eur": eur})}]}

rates = create_sdk_mcp_server("rates", "1.0.0", [convert])

tool_options = ClaudeAgentOptions(
    mcp_servers={"rates": rates},
    allowed_tools=["mcp__rates__convert"],
    setting_sources=[],
    strict_mcp_config=True,
)

The name is built as mcp__server__tool. In the test the call was denied without allowed_tools and landed in permission_denials; with it the answer was 9.2. The model found the tool through ToolSearch. External servers use the same mcp_servers field; the protocol is covered in MCP servers explained.

The docs now describe the pattern mcp__rates__* as working; "*" and "mcp__*" in allowed_tools are ignored. The author didn’t run the patterns.

Permissions and hooks

Evaluation order

The documentation describes six steps: hooks, deny rules, ask rules, permission mode, allow rules, the can_use_tool callback. Each step can decide the call or pass it on.

What you setWhat it doesWhat it doesn’t do
allowed_tools=["Read"]approves calls in advancedoesn’t remove other tools, doesn’t limit bypassPermissions
tools=[...]sets the built-in toolsetdoesn’t control MCP servers
disallowed_tools=["Bash"]removes the tool from the requesta Bash(rm *) rule doesn’t catch /bin/rm
permission_mode="dontAsk"denies where there would have been a promptdoesn’t touch what needs no approval: reads in the folder, safe Bash commands, Agent
can_use_tooldecides calls that reached the prompt stagedoesn’t see calls approved earlier
PreToolUse hooksees approved calls too, deny works even in bypassPermissionsallow doesn’t override deny rules

The author’s tests confirm two rows: a hook with deny beat allowed_tools=["Bash"], and bypassPermissions together with disallowed_tools=["Bash"] didn’t run the command.

from claude_agent_sdk import (
    HookMatcher, PermissionResultAllow, PermissionResultDeny,
)

async def deny_bash(data, tool_use_id, context):
    return {"hookSpecificOutput": {
        "hookEventName": "PreToolUse",
        "permissionDecision": "deny",
        "permissionDecisionReason": "Bash is disabled",
    }}

async def guard(name, data, context):
    if name == "Write" and not data.get("file_path", "").endswith(".md"):
        return PermissionResultDeny(message="only .md files")
    return PermissionResultAllow()

async def stream(text: str):
    yield {"type": "user", "message": {"role": "user", "content": text}}

guarded = ClaudeAgentOptions(
    can_use_tool=guard,
    hooks={"PreToolUse": [
        HookMatcher(matcher="Bash", hooks=[deny_bash], on_failure="block"),
    ]},
    setting_sources=[],
)
# query(prompt=stream("Write notes.md"), options=guarded)

In Python can_use_tool needs a streaming prompt, and the docs add a hook that keeps the stream open. In the test the callback saw two Bash calls, and the denial on rm worked. The model had meanwhile merged creating and deleting the file into one command, so the file never appeared. Matching a command by substring is unreliable: for bans use the toolset and a sandbox.

Callback hooks live in your process. If a callback crashes, by default the call goes on as if no decision was made; on_failure="block" (since 0.2.177) turns the failure into a denial. Python has ten events, TypeScript has more, including SessionStart and InstructionsLoaded (table). Command hooks from settings.json are described in the Claude Code hooks guide. Permissions also protect against other people’s text in your data: see the article on prompt injection.

Isolation: what enters the session unasked

Settings: setting_sources

If the field isn’t set, the SDK reads what the CLI reads: user, project and local settings, CLAUDE.md files, skills, agents and commands. An empty list turns that off. The field’s description in package 0.2.189 recommends [] when the folder may not be yours: project settings can run hooks.

The author’s run with defaults brought up 63 tools, connected personal MCP servers, and answered an English question in Russian because the personal instructions say so. For a service on a server this is the worst kind of bug: the agent behaves differently on the developer’s machine than in production.

Connectors: strict_mcp_config

setting_sources=[] doesn’t close everything. The documentation lists sources that are read at any value: managed policies, ~/.claude.json, the project’s auto memory, and claude.ai connectors when you sign in through claude.ai. An empty mcp_servers doesn’t turn connectors off; for that there is strict_mcp_config=True, the disableClaudeAiConnectors setting and the variable ENABLE_CLAUDEAI_MCP_SERVERS=false.

In the author’s first series, connector tools got into the session in 2 runs out of 16: 157 and 209 tools. A “Reply ok” request cost $0.176 by the SDK’s estimate, against $0.0001 without them. In the second series (9 variants, 3 runs each) it never happened again, either with strict_mcp_config=True or without it. It looks like a startup race; the cause wasn’t established. So the author can’t call the flag a cure: it is documented, but the test didn’t confirm its effect. It’s safer to check the list at startup:

from claude_agent_sdk import SystemMessage

EXPECTED = {"Read", "Glob", "Grep"}

async def checked(prompt: str) -> None:
    extra: set[str] = set()
    async for m in query(prompt=prompt, options=OPTIONS):
        if isinstance(m, SystemMessage) and m.subtype == "init":
            extra = set(m.data["tools"]) - EXPECTED
            if extra:
                print("unexpected tools:", sorted(extra))

The check reports extras but doesn’t stop the run. If you need it to stop, use ClaudeSDKClient and its interrupt().

CLAUDE.md: the docs and the test disagree

According to the docs, setting_sources=["project"] loads CLAUDE.md from the working folder. The author’s file had one rule: end every answer with the word ZEBRA.

RunInstruction in context
SDK, bundled CLI 2.1.332, ["project"]no
same with the claude_code presetno
same with default sourcesno
SDK with cli_path to installed CLI 2.1.322yes
claude -p 2.1.322yes

The author read the Claude Code changelog from 2.1.323 to 2.1.332. Two entries concern delivering CLAUDE.md to the model: 2.1.332 fixes it being sent again after a move into a worktree, and 2.1.330 fixes link reference definitions being dropped from files with an HTML comment. Neither explains the gap. The file has no section for 2.1.324. The TypeScript SDK changelog for 0.3.323-0.3.332 doesn’t mention CLAUDE.md, the Python SDK changelog ends at 0.2.178, and GitHub releases 0.2.179-0.2.189 carry no description of changes. The cause wasn’t found. It may be a build bug or a quirk of the author’s environment: one machine, one model and one run each were tested.

In practice, check loading with a marker word after every SDK update. Per the reference, ClaudeSDKClient.get_context_usage() returns a memoryFiles list. If the rules are mandatory, pass the text explicitly. The author didn’t run this variant against a model:

from pathlib import Path

explicit = ClaudeAgentOptions(
    setting_sources=[],
    system_prompt={
        "type": "preset",
        "preset": "claude_code",
        "append": Path("CLAUDE.md").read_text(encoding="utf-8"),
    },
)

What to put in the file is covered in the CLAUDE.md guide. The preset here isn’t accidental: without system_prompt the SDK uses a minimal prompt which, according to the docs, omits Claude Code’s security and safety instructions.

Several tenants on one host

The docs warn that default query() options don’t provide multi-tenant isolation. Their recipe: a separate filesystem per tenant, setting_sources=[] and CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 in env. That doesn’t turn off an organization’s server-managed policies.

Subagents

from claude_agent_sdk import AgentDefinition

with_agent = ClaudeAgentOptions(
    allowed_tools=["Agent", "Read"],
    agents={"reader": AgentDefinition(
        description="Reads files and summarizes them",
        prompt="Read the file and summarize it in one sentence.",
        tools=["Read"],
        model="haiku",
    )},
    env={"CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH": "1"},
    setting_sources=[],
)

In the test Agent and Read were called. From its parent a subagent receives only the prompt string, and the parent gets the final result back. The defaults are a depth of 3 levels and 20 concurrent subagents. AgentDefinition fields in Python are camelCase (disallowedTools, maxTurns). When a subagent pays off is covered in the article on Claude Code subagents.

Structured output

The field output_format={"type": "json_schema", "schema": {...}} asks for an answer that follows JSON Schema draft-07, and the result is in structured_output. The author got {'functions': ['mean'], 'handles_empty': False}, with a service call to StructuredOutput visible in the stream. If the model doesn’t fit the schema after retries, the subtype is error_max_structured_output_retries. A schema checks the shape; check the meaning yourself. For a comparison of modes, see the article on structured output.

Cost and limits

  • total_cost_usd is a client-side estimate from a built-in price table. The docs ask you not to bill users by it.
  • usage counts the main loop without subagents. For accounting use model_usage. In streaming mode the totals are cumulative, so you need the last result.
  • max_turns isn’t set by default. Without it a session can run for a long time.
  • max_budget_usd is checked after a turn. In the test a $0.0005 limit gave error_max_budget_usd at an estimate of $0.0012: 2.4 times over. Set a hard ceiling in the Console.

The SDK turns prompt caching on by itself; how it works is covered in the article on prompt caching.

Hosting

Each agent is a separate process with state on disk. The documentation gives a starting estimate of 1 GiB of memory, 5 GiB of disk and 1 CPU and calls it a floor: memory grows with session length. A minimal container costs roughly $0.05 an hour, and tokens usually cost an order of magnitude more. Keep secrets outside: a proxy puts the key into the request, and the agent doesn’t see it (secure deployment). The author didn’t measure memory or load.

Subscription, API key and products for others

RunWhat is charged
SDK with a subscription loginplan limits
SDK with a key from an organization linked to Max, Ultra, or Teammonthly API credits, then purchased ones
SDK with an ordinary Console keyAPI balance

Source: Help Center, updates dated October 7 and June 15, 2026; the math is in subscription or API. In a product for other people you can’t offer claude.ai login or its rate limits without Anthropic’s approval; the docs require an API key. Use of the SDK is governed by the Commercial Terms, except components with their own license. You can’t use the name “Claude Code” in your product, but “Powered by Claude” is allowed.

Where to start

  1. Pin the package version and write down the bundled CLI version.
  2. Start with read-only tools, dontAsk, setting_sources=[] and strict_mcp_config=True.
  3. Compare the tool list in the init message with the expected one.
  4. Check permission_denials and the artifact, not just subtype.
  5. Set max_turns and max_budget_usd, allowing for the overshoot.
  6. Check that CLAUDE.md loads with a marker, or pass the text through append.
  7. Before production, move the agent into a container with a restricted network.

Frequently Asked Questions

How is the Agent SDK different from the Claude API?
With the Claude API (Client SDK) you write the tool loop yourself or use the beta runner. In the Agent SDK the loop, file tools, permissions, hooks, subagents and sessions are ready: it is Claude Code as a library. For an answer that needs no files or commands, the API is simpler and lighter.
Do I need Claude Code installed separately?
Usually not: the packages for both languages include a native binary. The documented exceptions are pip installing a source distribution instead of a wheel (for example, on ARM64 Windows) and npm skipping optional dependencies. In those cases install Claude Code separately; in TypeScript, set pathToClaudeCodeExecutable.
Can I use the Claude Agent SDK on a Max subscription?
For your own runs, yes: according to the Help Center, signing in with a plan draws from its subscription limits (November 29, 2026). You can't offer claude.ai login or its rate limits in your own product without Anthropic's approval, so a product needs an API key.
How do I limit what an agent can do?
Narrow the set with tools, remove the rest with disallowed_tools, set permission_mode="dontAsk", and add a PreToolUse hook with deny for whatever is always forbidden. allowed_tools doesn't do this: it pre-approves calls. Restrict network and files with a container or a sandbox.
Why doesn't the SDK see CLAUDE.md?
First check that setting_sources is unset or contains project, and that cwd points at the right folder. In the author's test that wasn't enough: the bundled CLI 2.1.332 didn't load the file, the installed 2.1.322 did. The cause wasn't found. It's safer to read the file yourself and pass it through the system prompt's append.
How do I find out what a run cost?
From total_cost_usd in ResultMessage, which is a client-side estimate from a built-in price table and isn't billing data. For tokens use model_usage: the usage field doesn't include subagents. On a subscription the number shows the API equivalent and isn't charged to your card separately.
Should I use query() or ClaudeSDKClient?
query() fits a task that ends in one result: CI, a script, queue processing. In Python, ClaudeSDKClient keeps one session open, takes further messages and can be interrupted. TypeScript has no separate client, so you continue a conversation with continue or resume.