Citation and evidence

Claude Agent SDK

36 min full readUpdated 27 references

This article's verification

Report a problem with this article

Edit article
More

Use this article

Raw MarkdownExplore connections

Improve this page

Revision historyDiscuss this article

Topics

AI AgentsAnthropicDeveloper ToolsOpen Source AI

Cite this article

The Claude Agent SDK is Anthropic's official software development kit for building custom AI agents powered by Claude, released on September 29, 2025 as the renamed and expanded successor to the Claude Code SDK.[1][2] Available for both Python and TypeScript, it provides developers with the same tools, agent loop, and context management infrastructure (the "agent harness") that powers Claude Code, packaged as a programmable library.[1][2] The SDK enables the creation of autonomous agents that can read files, execute terminal commands, search the web, edit code, and interact with external systems through the Model Context Protocol (MCP).[1]

Claude logo
Claude logo. Source: Wikimedia Commons, Public domain.

Anthropic describes the core idea in one sentence: "The key design principle behind the Claude Agent SDK is to give your agents a computer, allowing them to work like humans do."[2] The September 2025 rename from Claude Code SDK to Claude Agent SDK reflected that the same harness was being used well beyond coding, for deep research, video creation, and note-taking.[2] As Anthropic put it: "The agent harness that powers Claude Code (the Claude Code SDK) can power many other types of agents, too. To reflect this broader vision, we're renaming the Claude Code SDK to the Claude Agent SDK."[2]

The SDK's source is public on GitHub. The Python implementation lives at anthropics/claude-agent-sdk-python on GitHub under an MIT license,[3] and the TypeScript implementation lives at anthropics/claude-agent-sdk-typescript.[4] Both wrap the Claude Code CLI binary, which itself ships under Anthropic's Commercial Terms. The SDK is free to install and use; the only running cost is Claude API usage, billed per token through whichever inference backend the developer chooses (Anthropic API, AWS Bedrock, Google Vertex AI, or Microsoft Foundry).

Quick reference

AttributeValue
Original nameClaude Code SDK
Renamed toClaude Agent SDK
Rename dateSeptember 29, 2025
First Python releaseJune 12, 2025 (claude-code-sdk 0.0.10)
First claude-agent-sdk release0.1.0, September 29, 2025 (alongside Claude Sonnet 4.5); still pre-1.0 as of November 2026
Latest versions (October 31, 2026)Python 0.2.176 (bundled Claude CLI 2.1.316); TypeScript 0.3.316
LanguagesPython 3.10+, TypeScript / Node.js 18+
License (SDK code)MIT (Python); Anthropic Commercial Terms (TypeScript)
License (CLI binary)Anthropic Commercial Terms
Sourcegithub.com/anthropics/claude-agent-sdk-python, github.com/anthropics/claude-agent-sdk-typescript
Default modelClaude Code's default model unless set with the model option (for example Opus 4.7, Sonnet 4.6, Haiku 4.5)
Inference backendsAnthropic API, AWS Bedrock, Google Vertex AI, Microsoft Foundry
Documentationcode.claude.com/docs/en/agent-sdk

Expanded article table

When was the Claude Agent SDK released?

The roots of the Claude Agent SDK trace back to February 2025, when Anthropic launched Claude Code as a preview. Claude Code was an agentic command-line tool that allowed developers to delegate coding tasks directly from their terminal. By May 2025, Claude Code reached general availability alongside the release of Claude 4.

As Claude Code matured, Anthropic began exposing its internal infrastructure as a programmable SDK. Anthropic released the Claude Code SDK alongside Claude 4 on May 22, 2025, describing it as "an extensible Claude Code SDK, so you can build your own agents and applications using the same core agent as Claude Code."[24] The first Python claude-code-sdk release with downloadable files, version 0.0.10, was uploaded to PyPI on June 12, 2025.[22] Through the summer of 2025, the SDK existed as a thin Python wrapper that spawned the Claude Code CLI as a subprocess and parsed its streaming JSON output.

Version 0.1.0 of the renamed packages followed on September 29, 2025, at which point Anthropic also renamed the package from claude-code-sdk to claude-agent-sdk (Python) and from @anthropic-ai/claude-code to @anthropic-ai/claude-agent-sdk (TypeScript / JavaScript).[2][5] The rename was timed alongside the launch of Claude Sonnet 4.5 and the Claude Code 2.0 release.[2] Anthropic published an engineering post titled "Building agents with the Claude Agent SDK" on September 29, 2025, explaining the design philosophy: that giving a model access to a real computer, with real tools, is a shorter path to capable agents than reinventing tool calling on top of a chat API.[2]

A notable enterprise milestone came on February 3, 2026, when Apple announced that Xcode 26.3 would include a native integration with the Claude Agent SDK, bringing agentic coding capabilities to iOS, macOS, and visionOS development.[10][11] Anthropic's announcement said the integration brings Claude Code capabilities, including subagents, background tasks, and plugins, into Xcode.[10] The integration lets Claude capture Xcode Previews to check the interface it is building, which Anthropic said is particularly useful for SwiftUI views.[10][11]

Both SDKs release several times a week. By June 2026 the Python SDK had reached version 0.2.105, bundling Claude CLI 2.1.183, and by October 31, 2026 it had reached 0.2.176.[3][12] The changelogs track features that first lived in the CLI: skills options, effort levels (low, medium, high, max, later xhigh), a SessionStore protocol, plan-mode permission routing, and a steady stream of permission work.[3][4]

Languages and runtime support

Anthropic ships two first-party SDKs. Community ports cover most other languages, but they call into the same CLI binary under the hood, so feature parity is mostly a matter of which language you want to write your wrapper in.

LanguagePackageStatusNotes
Pythonclaude-agent-sdk (PyPI)Official, stableRequires Python 3.10+. Async-first API based on asyncio.
TypeScript@anthropic-ai/claude-agent-sdk (npm)Official, stableRequires Node.js 18+. Uses async iterators and AsyncGenerator.
Goclaude-agent-sdk-go (several independent projects)CommunityWraps the CLI; not feature-complete.
Rustclaude-agent-rsCommunityBindings to the streaming JSON protocol.
Javaclaude-agent-sdk-javaCommunityMaintained by independent contributors.
Rubyclaude-agent-sdk (gem)CommunityUnofficial wrapper over the CLI runtime.

Expanded article table

The official Python and TypeScript SDKs share the same conceptual model. The options correspond (Python's ClaudeAgentOptions and TypeScript's Options type, with snake_case versus camelCase names), the lifecycle hooks fire at the same points, and tool names (Read, Bash, Glob) are identical across runtimes. A subagent definition written in Python can be ported to TypeScript in a few minutes. This is largely because both SDKs delegate the actual work to the same CLI binary, which spawns as a child process and communicates over JSONL on stdout.

How does the Claude Agent SDK work?

The Claude Agent SDK is built around the idea that giving an AI model access to a computer's terminal provides it with everything it needs to accomplish complex tasks.[2] Anthropic states the principle directly: "give your agents a computer, allowing them to work like humans do."[2] Rather than requiring developers to implement their own tool execution loops and message passing, the SDK handles the entire agent loop internally.[1]

The agent loop

The SDK operates on a continuous feedback cycle that Anthropic frames as "gather context, take action, verify work, repeat":[2]

  1. Gather context. The agent retrieves and searches for relevant information using file system tools, web search, or MCP servers.
  2. Take action. The agent executes tasks using the tools available to it, such as running bash commands, editing files, or calling external APIs.
  3. Verify work. The agent evaluates the quality of its output through rules-based feedback, visual verification, or secondary model evaluation.
  4. Iterate. Based on verification results, the agent refines and improves its work until the task is complete.

This loop runs autonomously. Unlike the lower-level Anthropic API Client SDK, where the developer must implement the tool execution cycle manually, the Agent SDK handles tool invocation, result processing, and multi-turn conversation management on its own.[1] The developer's job is to define the system prompt, the available tools, the allowed permissions, and the success criteria. Everything between the prompt and the final answer is the SDK's responsibility.

This is a deliberate inversion of the usual framework design. LangChain and similar libraries give the developer raw building blocks: a prompt template, a tool registry, an output parser, a memory module, a chain. The Agent SDK gives the developer a black box that already runs and asks the developer to configure how it should behave. The trade-off is less flexibility for far less code.

Two API surfaces

The Python SDK offers two primary interfaces:[1]

InterfaceDescriptionUse case
query()Async generator function for simple queriesLightweight, one-shot tasks
ClaudeSDKClientFull-featured client with session managementMulti-turn conversations, custom tools, hooks

Expanded article table

The query() function is the simpler entry point. Developers pass a prompt and options, then iterate over streamed messages:

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    async for message in query(
        prompt="Find all TODO comments and create a summary",
        options=ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep"]),
    ):
        if hasattr(message, "result"):
            print(message.result)

asyncio.run(main())

The ClaudeSDKClient provides full control over conversations, including the ability to resume sessions, use custom tools, and register hooks:

from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions

options = ClaudeAgentOptions(
    system_prompt="You are a helpful assistant",
    max_turns=1
)

async with ClaudeSDKClient(options=options) as client:
    await client.query("Tell me a joke")
    async for msg in client.receive_response():
        print(msg)

The TypeScript SDK has no client class: its query() function returns a Query object, and multi-turn sessions use streaming input mode or the session options.

What tools are built into the Claude Agent SDK?

One of the defining characteristics of the Claude Agent SDK is that it ships with a full set of built-in tools.[1] Developers do not need to implement file reading, command execution, or code editing from scratch. The SDK bundles the Claude Code CLI, which provides these capabilities automatically. Anthropic notes that tools "are the primary building blocks of execution for your agent" and are kept prominent in Claude's context window so they are the first actions the model considers.[2]

ToolDescriptionTypical use
ReadRead any file in the working directory, with line numbers and offsetsReading source files, configs, logs
WriteCreate new filesGenerating new modules, reports, manifests
EditMake precise string replacements in existing filesRefactors, bug fixes, surgical edits
NotebookEditEdit cells in Jupyter notebooksData science notebooks (.ipynb)
BashRun terminal commands, scripts, and git operationsTests, builds, version control, system queries
GlobFind files by pattern (e.g., **/*.ts, src/**/*.py); as of late 2026, Glob and Grep are left out of the default tool set on macOS, Linux and WSL unless named in the allowed tools[27]Locating files by name
GrepSearch file contents using regular expressionsFinding code that matches a pattern
WebSearchSearch the web for current informationLooking up library docs, news, recent events
WebFetchFetch and parse web page contentReading specific URLs the user provides
AskUserQuestionPrompt the user for clarifying input with multiple-choice optionsDisambiguating fuzzy requests
TodoWriteTrack multi-step plans inside a long task (as of late 2026 disabled by default in favor of TaskCreate, TaskGet, TaskList, and TaskUpdate)[27]Long-running agents that need to remember subtasks
AgentSpawn and delegate tasks to subagentsDecomposing big jobs into focused chunks

Expanded article table

Developers control which tools are available through the allowed_tools parameter.[1] A read-only analysis agent might only have access to Read, Glob, and Grep, while a fully autonomous coding agent might use all available tools. Disallowing Bash is the simplest way to keep an agent from running arbitrary shell commands; many production deployments do exactly this and rely only on the structured editors.

Custom tools (in-process MCP servers)

Beyond built-in tools, developers can define custom Python functions that Claude can invoke. These are registered as in-process MCP servers, which avoids the overhead of subprocess management and inter-process communication:[6]

from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions, ClaudeSDKClient

@tool("greet", "Greet a user", {"name": str})
async def greet_user(args):
    return {
        "content": [
            {"type": "text", "text": f"Hello, {args['name']}!"}
        ]
    }

server = create_sdk_mcp_server(
    name="my-tools",
    version="1.0.0",
    tools=[greet_user]
)

options = ClaudeAgentOptions(
    mcp_servers={"tools": server},
    allowed_tools=["mcp__tools__greet"]
)

In-process tools offer better performance, simpler deployment, and easier debugging compared to external MCP servers running as separate processes.[3] Type hints in the @tool decorator double as the JSON Schema that Claude sees, so the developer never has to write the schema by hand.

Model Context Protocol integration

The Claude Agent SDK provides first-class support for the Model Context Protocol, the open standard Anthropic introduced in November 2024 for connecting AI agents to external tools and data sources.[6] MCP enables agents to interact with databases, browsers, APIs, and hundreds of third-party services without hardcoding tool definitions.[6]

Transports

MCP servers can run in three different transport modes, all of which the SDK supports:[6]

TransportWhere it runsWhen to use
stdioLocal subprocessDefault for local servers (filesystem, shell, git tools)
Streamable HTTPRemote HTTP endpointHosted enterprise servers, SaaS connectors
SSE (Server-Sent Events)Remote endpoint with streamingOlder remote servers; being phased out in favor of Streamable HTTP

Expanded article table

The in-process MCP server variant introduced earlier is a fourth option that exists only inside the SDK; it skips the wire format entirely and just calls a Python or TypeScript function.[6]

Configuration

MCP servers can be configured either in code or through a .mcp.json configuration file.[6] A practical example connects the Playwright MCP server for browser automation:

async for message in query(
    prompt="Open example.com and describe what you see",
    options=ClaudeAgentOptions(
        mcp_servers={
            "playwright": {"command": "npx", "args": ["@playwright/mcp@latest"]}
        }
    ),
):
    if hasattr(message, "result"):
        print(message.result)

The SDK also supports MCP tool search, which dynamically loads tools on demand instead of preloading all tool definitions into the context window.[6] This feature is available with Claude Sonnet 4 and later models, and matters most for agents connected to dozens of MCP servers at once. Without tool search, every server's full tool list would land in the system prompt and chew through context.

Permissions for MCP tools

MCP tools require explicit permission before Claude can use them.[6] Without permission, Claude sees that the tools exist but cannot invoke them. The SDK's permission flow is the same one Claude Code uses interactively: a tool call is paused, a callback fires, the developer's code (or the user, in interactive mode) approves or denies, and the agent loop continues.

Hooks system

Hooks are the SDK's main mechanism for running custom code at well-defined points in the agent lifecycle.[8] They can validate, log, block, or transform agent behavior without modifying the core agent loop.[8] Shell command hooks from Claude Code settings files also run in SDK agents when the matching setting source is loaded, and SDK callback hooks use the same JSON output format as Claude Code's shell hooks.[8]

Hook events

Hook eventTrigger pointCommon uses
PreToolUseBefore a tool is invokedValidate or block dangerous commands; redact secrets
PostToolUseAfter a tool completesLog tool usage; collect telemetry; run linters
UserPromptSubmitWhen a user prompt is receivedInject context; rewrite prompts; classify intent
StopWhen the agent finishes a turnNotify external systems; save artifacts
SubagentStopWhen a subagent finishesAggregate or route subagent results
SessionStartWhen a session begins (TypeScript callbacks or settings-file hooks only)Bootstrap state; load user-specific context
SessionEndWhen a session ends (TypeScript callbacks or settings-file hooks only)Persist memory; emit usage metrics
NotificationWhen the agent surfaces a status messageForward to chat UIs or logs

Expanded article table

Practical example

A common use case is blocking dangerous commands. A PreToolUse hook on the Bash tool can inspect the command string and deny execution if it matches a blocklist:[8]

from claude_agent_sdk import HookMatcher, HookContext

async def block_destructive(input_data, tool_use_id, context: HookContext):
    cmd = input_data["tool_input"].get("command", "")
    if any(bad in cmd for bad in ["rm -rf /", "mkfs", ":(){ :|:& };:"]):
        return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny"}}
    return {}

options = ClaudeAgentOptions(
    hooks={
        "PreToolUse": [HookMatcher(matcher="Bash", hooks=[block_destructive])]
    }
)

Hooks can also be specified as shell commands in settings.json, the same JSON format Claude Code uses.[8] This means an organization can define a single set of safety hooks, drop the file into .claude/settings.json, and have it apply uniformly to interactive Claude Code sessions and to programmatic SDK agents running in production.

Skills integration

Claude Skills are Anthropic's packaging format for reusable workflows.[9] Anthropic launched Skills publicly on October 16, 2025 across Claude.ai, Claude Code, the Anthropic API, and the Claude Agent SDK simultaneously.[14]

Skill format

A skill is a directory containing a SKILL.md file with YAML frontmatter, plus any supporting files (templates, reference docs, scripts) that the workflow needs:[9]

---
name: pdf-processing
description: Extract text and tables from PDFs, fill forms, merge documents. Use when the user mentions PDFs.
---

# PDF processing

Use pdfplumber to extract text from PDFs.
See FORMS.md for the form-filling reference.

The name field is the unique identifier (lowercase, hyphenated, maximum 64 characters).[9] The description is what Claude sees first when deciding whether to load the skill.

Discovery and loading

The SDK loads skills from these locations:[9]

ScopeLocationUse
User~/.claude/skills/Personal workflows that follow you across projects
Project.claude/skills/ (in working directory)Team-shared skills checked into a repo
Pluginskills/ inside a plugin loaded by local pathSkills bundled with a Claude Code plugin

Expanded article table

At session start, the SDK indexes every skill it finds and adds the name and description of each to the agent's system prompt.[9] The body of the SKILL.md is not loaded yet. When the user's request matches a skill description, the agent reads the full body, and only then opens supporting files as needed. This is the progressive disclosure pattern: the cost of having many skills installed is roughly one line of system prompt per skill.[14]

Configuration

Skills loading is controlled through setting_sources.[9] Setting it to ["user", "project"] enables both user-level and repo-level skills:

options = ClaudeAgentOptions(
    setting_sources=["user", "project"],
    permission_mode="acceptEdits",
)

When setting_sources is omitted, query() loads user, project, and local filesystem settings, so the SDK discovers eligible user- and project-level skills by default.[1][19] Pass setting_sources=[] to opt out of those sources, or pass an explicit subset to limit them.[19]

What are subagents in the Claude Agent SDK?

Subagents allow a main agent to spawn specialized child agents that handle focused subtasks.[7] Each subagent runs in its own fresh conversation with an isolated context window, custom system prompt, specific tool access, and independent permissions.[7] The Claude Agent SDK supports subagents by default.[2]

The key benefit of context isolation is that intermediate tool calls and results stay inside the subagent.[7] Only the final result is returned to the parent agent.[7] A research-assistant subagent might explore dozens of files, but the parent receives only a concise summary rather than every file the subagent read. This pattern is how teams keep agents on task across hour-long jobs without filling the context window with debug noise.

Multiple subagents can run concurrently, which significantly speeds up complex workflows.[7] Claude automatically determines whether to invoke a subagent based on its description field, or developers can explicitly request one by name.[7]

from claude_agent_sdk import AgentDefinition, query, ClaudeAgentOptions

async for message in query(
    prompt="Use the code-reviewer agent to review this codebase",
    options=ClaudeAgentOptions(
        allowed_tools=["Read", "Glob", "Grep", "Agent"],
        agents={
            "code-reviewer": AgentDefinition(
                description="Expert code reviewer for quality and security reviews.",
                prompt="Analyze code quality and suggest improvements.",
                tools=["Read", "Glob", "Grep"],
            )
        },
    ),
):
    if hasattr(message, "result"):
        print(message.result)

Subagents can themselves spawn subagents. By default the SDK allows three layers below the main agent, adjustable with CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH, and caps concurrent subagents at 20.[7]

Sessions

By default, the SDK records a session's conversation history on disk, including prompts, tool calls, tool results, and responses. A session does not contain a filesystem snapshot. Resuming restores the recorded conversation, while files remain in their current state in the selected working directory.[16]

Continue, resume, and fork

Without forking, continue and resume both return to stored conversation history, but they select the session differently. Python's continue_conversation=True and TypeScript's continue: true resume the most recent session for the working directory. The resume option takes a specific session ID. Python's ClaudeSDKClient maintains one session across calls to client.query(), while TypeScript uses continue: true to continue automatically across separate query() calls.[16]

Forking copies the conversation into a new session and leaves the original history unchanged. In Python, the options are resume=session_id and fork_session=True; TypeScript uses resume: sessionId and forkSession: true. The fork gets its own session ID. It branches the transcript, not the filesystem, so sessions that use the same working directory still see the same files.[16]

These SDK options parallel Claude Code's Claude --continue and Claude --resume command-line options, but the interfaces differ. The SDK's resume option is ID-based. The interactive CLI can also open a session picker or resolve a session name.[16][18]

Capture and resume by ID

The Python SDK exposes the session ID on each ResultMessage. An application can retain that value and pass it to a later query:[16]

import asyncio
from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query

async def main():
    session_id = None

    # First query: capture the session ID from the result message
    async for message in query(
        prompt="Read the authentication module",
        options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"]),
    ):
        if isinstance(message, ResultMessage):
            session_id = message.session_id

    if session_id is None:
        raise RuntimeError("The session did not return an ID")

    # Resume the recorded conversation by ID
    async for message in query(
        prompt="Now find all places that call it",
        options=ClaudeAgentOptions(resume=session_id),
    ):
        if isinstance(message, ResultMessage) and message.subtype == "success":
            print(message.result)

asyncio.run(main())

Storage and host boundaries

Without a custom store, transcripts are local files under ~/.claude/projects/<encoded-cwd>/, or under $CLAUDE_CONFIG_DIR/projects/ when that environment variable is set. An SDK release whose bundled Claude Code version is 2.1.223 or later can look beyond the current project and its git worktrees for a unique session ID on the same machine. Older bundled versions limit that lookup to the current project and its worktrees. A session ID alone does not transfer its transcript to another host.[16]

To resume across hosts, an application can copy the JSONL transcript or attach a SessionStore adapter that mirrors transcript entries to an application-controlled backend. Store keys derive from the working directory, so the resumed query must use a matching working directory. Both SDKs include an InMemorySessionStore for development and testing and provide conformance tests for custom adapters. Anthropic also publishes copy-in reference adapters for S3, Redis, and PostgreSQL; they are examples rather than backend adapters distributed in the packages.[16][17]

The session store uses a dual-write design. The Claude Code subprocess first writes transcript batches to local disk, then the SDK forwards the same batches to the store. A run resumed from the store uses a temporary config directory and removes that local copy when the run ends. The SDK rejects using a session store together with file checkpointing because checkpoint files are not mirrored.[17]

Permissions and safety

The SDK evaluates tool permissions through hooks, deny rules, ask rules, the active permission mode, allow rules, and the can_use_tool callback.[15]

SettingEffect
allowed_toolsPre-approves specific tools for automatic execution
disallowed_toolsExplicitly blocks tools the agent should never use
permission_mode="default"No auto-approvals; unmatched tool requests go to can_use_tool
permission_mode="acceptEdits"Auto-approves file edits and common filesystem operations
permission_mode="dontAsk"Denies unmatched requests instead of calling can_use_tool
permission_mode="bypassPermissions"Auto-approves most calls that reach the mode check; hooks, deny rules, and ask rules still apply, and critical-path rm and rmdir operations go to can_use_tool
permission_mode="plan"Claude explores and plans without editing source files; edit requests go to can_use_tool
can_use_tool callbackProgrammatic per-call permission decisions

Expanded article table

The can_use_tool callback receives requests routed to it by ask rules and permission-mode safeguards, along with requests that the other evaluation steps leave unresolved. In dontAsk mode, the callback is skipped and the request is denied.[15] The callback receives the tool name, input, and context and returns an allow or deny result. Applications can use it to present approval requests or apply their own authorization logic.[15]

MCP tools require explicit permission before Claude can use them.[6] Without permission, Claude sees that the tools exist but cannot invoke them.

Plan mode

The SDK's permission_mode="plan" setting lets Claude explore the codebase and produce a plan without editing source files. Read-only tools run as in default mode; file edits are never auto-approved and instead route to can_use_tool. Shell commands that modify files follow the same routing on Claude Code 2.1.212 or later. Claude may use AskUserQuestion to clarify requirements.[15]

Cost tracking

In Python, each assistant message carries a per-step usage breakdown.[20] The ResultMessage at the end of a query carries cumulative usage and per-model model_usage token counts plus total_cost_usd, a cost estimate that the SDK computes locally and that Anthropic says is not authoritative billing data.[20] Cost tracking is one of the SDK's most underrated features. It removes the need to instrument the underlying API calls separately:

async for msg in client.receive_response():
    if isinstance(msg, ResultMessage):
        print(f"Cost: ${(msg.total_cost_usd or 0):.4f} (usage: {msg.usage})")

Each query() call's total_cost_usd includes subagent requests; applications that make several calls add the per-call totals themselves. The max_budget_usd option (maxBudgetUsd in TypeScript) caps a call's spend and stops further subagent spawning when reached.[20][7]

Configuration options

The ClaudeAgentOptions class (Python) and equivalent TypeScript options object accept numerous configuration parameters:[1]

ParameterTypeDescription
system_promptstring or dictCustom system prompt or preset (e.g., claude_code)
max_turnsintMaximum number of conversation turns
allowed_toolslistTools pre-approved for auto-execution
disallowed_toolslistTools to block entirely
permission_modestringActive tool permission mode (default, acceptEdits, dontAsk, bypassPermissions, plan, or auto where available).[15]
cwdstring or PathWorking directory for the agent
mcp_serversdictMCP server configurations
hooksdictHook handler registrations
cli_pathstringCustom path to Claude Code CLI
modelstringClaude model to use
setting_sourceslistFilesystem settings to load (e.g., ["project"])
agentsdictSubagent definitions
betaslistBeta features to enable (e.g., 1M context window)
max_thinking_tokensintDeprecated cap on thinking tokens; use thinking instead
continue_conversation (Python) / continue (TypeScript)boolResume the most recent session for the working directory
resumestringSession ID to resume
fork_session (Python) / forkSession (TypeScript)boolFork the resumed history under a new session ID
session_store (Python) / sessionStore (TypeScript)SessionStoreMirror transcript entries to an application-controlled backend

Expanded article table

By default, query() loads the user, project, and local filesystem setting sources, matching Claude Code. Set setting_sources=[] to opt out, or pass an explicit subset to limit the sources. Include "project" when you want CLAUDE.md project instructions.[1][19]

Installation and authentication

Python

pip install claude-agent-sdk

Requires Python 3.10 or later.[12] The Claude Code CLI is automatically bundled with the package.

TypeScript / JavaScript

npm install @anthropic-ai/claude-agent-sdk

Requires Node.js 18 or later.[13] The native Claude Code binary for each platform ships as an optional dependency, such as @anthropic-ai/claude-agent-sdk-darwin-arm64.[13]

Authentication

The SDK requires an Anthropic API key, set as an environment variable:[1]

export ANTHROPIC_API_KEY=your-api-key

Alternatively, the SDK supports authentication through third-party cloud providers:[1]

ProviderEnvironment variableDetails
Amazon BedrockCLAUDE_CODE_USE_BEDROCK=1Uses AWS credentials
Google Vertex AICLAUDE_CODE_USE_VERTEX=1Uses Google Cloud credentials
Microsoft FoundryCLAUDE_CODE_USE_FOUNDRY=1Uses Azure credentials
Claude Platform on AWSCLAUDE_CODE_USE_ANTHROPIC_AWS=1 and ANTHROPIC_AWS_WORKSPACE_IDUses AWS credentials

Expanded article table

Anthropic's documentation says that, unless previously approved, third-party developers may not offer claude.ai login or rate limits in products built on the SDK, and directs them to API key authentication instead.[1]

How does the Claude Agent SDK relate to Claude Code?

Claude Code is Anthropic's agentic coding tool that lives in the terminal. The Claude Agent SDK is the library (the "agent harness") that powers Claude Code internally; Anthropic's documentation describes the SDK as a library that runs the Claude Code binary, with Claude Code's built-in tools, permissions, sessions, and hooks.[1] The relationship can be summarized as follows:

AspectClaude Code CLIClaude Agent SDK
InterfaceInteractive terminalProgrammatic library
Best forDaily development, one-off tasksCI/CD pipelines, production automation, custom applications
ToolsFull toolsetSame full toolset, configurable
CustomizationCLAUDE.md, settings filesFull programmatic control, hooks, subagents
LanguagesN/A (CLI)Python and TypeScript
Settings loaded by defaultYesYes (user, project, and local)[1][19]
Skills available by defaultYesYes, from the default user and project sources[1][19]
OutputPretty terminal UIStructured JSON stream

Expanded article table

Many development teams use both: the CLI for interactive daily work and the SDK for production automation. Workflows translate directly between the two because they share the same underlying infrastructure. A developer can prototype a workflow in Claude Code, get the prompt and tool config right, and then drop the same setup into a Python script for batch use without rewriting anything.

How does the Claude Agent SDK compare with other agent frameworks?

The Claude Agent SDK enters a competitive landscape that includes several other frameworks for building AI agents. Each has different design priorities and trade-offs. The single biggest split is between all-in-one runtimes like the Claude Agent SDK and the OpenAI Agents SDK, which give you a working agent the moment you supply a prompt, and toolkits like LangChain or LlamaIndex, which give you a box of parts and ask you to assemble the agent yourself.

FrameworkPrimary languageModel supportBuilt-in toolsMCP supportMulti-agentHooks / lifecycleLicense
Claude Agent SDKPython, TypeScriptAnthropic ClaudeYes (Read, Write, Bash, etc.)First-class, nativeSubagents with context isolationPreToolUse, PostToolUse, Stop, etc.MIT (Python SDK) / Anthropic Commercial Terms (TypeScript SDK, CLI)
OpenAI Agents SDKPython, TypeScriptOpenAI GPT, partially provider-agnosticHosted tools (web search, code interpreter, file search)Yes (hosted MCP, Streamable HTTP, SSE, stdio)[25]Handoffs between specialized agentsGuardrails and tracingMIT
LangChain / LangGraphPython, TypeScript600+ model integrationsVia integrationsVia pluginsLangGraph for orchestrationCallbacksMIT
LlamaIndexPython, TypeScriptMany providersStrong on data loadersVia pluginsWorkflow frameworkEvent handlersMIT
CrewAIPythonMultiple LLM providersVia integrationsVia pluginsRole-based collaborative agentsTask callbacksMIT
AutoGen (being archived; succeeded by Microsoft Agent Framework)[26]PythonMultiple providersVia integrationsVia pluginsConversable multi-agent groupsLimitedMIT
StrandsPythonBedrock-first, multiple providersStrong AWS integrationsYesMulti-agent supportedCallbacksApache 2.0
Pydantic AIPythonMultiple providersLightweightYesYesType-safe lifecycleMIT

Expanded article table

Key differentiators

The Claude Agent SDK differentiates itself through its tight integration with Claude and its built-in toolset. Unlike LangChain, which serves as a model-agnostic framework with broad integrations, the Claude Agent SDK is purpose-built for Claude and ships with production-ready tools out of the box. The single-vendor focus is the trade-off: if you need to swap to GPT or Gemini midway through a project, the Claude Agent SDK is not the right framework. If you have already chosen Claude, it is the shortest path to a working agent.

Compared to the OpenAI Agents SDK, which focuses on handoffs between specialized agents with validation guardrails, the Claude Agent SDK centers on hooks and subagents for lifecycle control. The OpenAI SDK has strengths in multimodal and voice scenarios through GPT-4o and the Realtime API. The Claude Agent SDK inherits Claude's particular skill at long-horizon coding work.

CrewAI focuses on collaborative autonomy, where agents assume specific roles and coordinate like a team. The Claude Agent SDK's subagent model provides more hierarchical control, with a parent agent delegating to children that report back. AutoGen sits between the two, with conversable agents that can talk to each other directly. Strands is AWS's agent framework, optimized for Bedrock and AWS service integrations. Pydantic AI is the lightest of the bunch, betting that strong typing and structured outputs are most of what an agent framework actually needs.

Real-world use cases and deployments

The Claude Agent SDK supports a wide range of applications across different domains. The list below combines public integration announcements with the agent types Anthropic's engineering post gives as examples.

DeploymentUse of the SDKSource
JetBrains Claude AgentThird-party agent in JetBrains IDEs' AI chat, built on the Claude Agent SDK (September 2025)JetBrains blog[21]
Apple Xcode 26.3 agentic codingNative integration; Claude can capture Xcode Previews to check its UI workAnthropic and Apple, Feb 2026[10][11]
Claude Code (the CLI)The SDK runs the Claude Code binary and exposes the same agent harnessAnthropic docs and engineering blog[1][2]
Finance agentsAgents that evaluate investments using external APIs and dataAnthropic engineering blog[2]
Personal assistant agentsAgents that book travel, manage calendars and assemble briefs across applicationsAnthropic engineering blog[2]
Customer support agentsAgents that handle ambiguous requests such as service ticketsAnthropic engineering blog[2]
Deep research agentsAgents that synthesize findings across large document collectionsAnthropic engineering blog[2]

Expanded article table

Software development

The most common use case remains software work. The full toolset is purpose-built for it: Bash for tests and builds, Read/Write/Edit for code, Glob/Grep for navigation, WebFetch and WebSearch for documentation lookups. Typical agents include bug detection and fixing agents, code review agents, CI/CD automation, and SRE bots that monitor systems and respond to incidents.

Business applications

Many teams use the SDK for non-coding work.[2] Customer support agents handle ticket routing and draft responses. Legal analysis agents review contracts and summarize documents. Financial analysis agents evaluate investments and generate reports. Research assistants synthesize information from multiple documents.

Enterprise integration

The most prominent enterprise integration is Apple's Xcode 26.3, released February 2026, which natively integrates the Claude Agent SDK to enable autonomous coding for iOS, macOS, and visionOS development.[10][11] The integration includes visual verification through Xcode Previews, which closes the verify step of the agent loop without a human in the middle.[11]

Through MCP, agents can also connect to Slack, GitHub, Asana, Google Drive, and hundreds of other services.[6] The SDK does not bake in connectors for any specific SaaS product; that is the MCP ecosystem's job.

Error handling and message types

The SDK provides a structured error hierarchy for handling different failure modes:[1]

Error classDescription
ClaudeSDKErrorBase error class for all SDK errors
CLINotFoundErrorClaude Code CLI not installed or not found
CLIConnectionErrorConnection issues with the CLI process
ProcessErrorCLI process failed (includes exit code)
CLIJSONDecodeErrorFailed to parse response JSON

Expanded article table

Message types and content blocks

The SDK streams messages of several types during agent execution:[1]

Message typeDescription
AssistantMessageResponse content from Claude
UserMessageUser input forwarded to the agent
SystemMessageSystem-level instructions or status updates
ResultMessageFinal result of the agent's work, including usage and cost

Expanded article table

Content within messages is structured as blocks: TextBlock for text content, ToolUseBlock for tool invocations, ToolResultBlock for tool execution results, and ThinkingBlock for extended-thinking traces when that mode is enabled.

Is the Claude Agent SDK open source?

The Python wrapper code is open source under an MIT license; the TypeScript wrapper and the bundled Claude Code CLI binary are not.[3][4] Use of the Claude Agent SDK is governed by Anthropic's Commercial Terms of Service. This applies even when the SDK is used to power products and services made available to third-party customers and end users. Individual components or dependencies may be covered by separate licenses as indicated in their respective LICENSE files.

The Python repository carries an MIT license for the SDK wrapper code,[3] while the TypeScript repository's LICENSE.md states "All rights reserved" and makes use subject to Anthropic's Commercial Terms of Service.[4] The bundled Claude Code CLI binary also falls under the Commercial Terms. Practically speaking, the Python wrapper code is forkable and modifiable under MIT terms; the TypeScript package and the CLI binary are not.

The SDK source code is publicly available at anthropics/claude-agent-sdk-python[3] and anthropics/claude-agent-sdk-typescript.[4] Bugs are reported through each repository's GitHub issues.[1]

How do I migrate from the Claude Code SDK?

Developers who built on the original Claude Code SDK need to update their code for the renamed package.[5] The migration involves changing package names, import paths, and one renamed type:[5]

AspectOld (Claude Code SDK)New (Claude Agent SDK)
Python packageclaude-code-sdkclaude-agent-sdk
TypeScript package@anthropic-ai/claude-code@anthropic-ai/claude-agent-sdk
Python importfrom claude_code_sdk import ...from claude_agent_sdk import ...
Options classClaudeCodeOptionsClaudeAgentOptions

Expanded article table

The Agent SDK introduced a system-prompt breaking change beyond the package rename: it no longer uses Claude Code's system prompt by default, so applications must request that preset or provide a custom prompt when they need it.[5] Version 0.1.0 also briefly stopped loading filesystem settings by default, but Anthropic reverted that default. Current query() calls load user, project, and local setting sources when setting_sources is omitted; no migration action is needed for that default.[5][19]

The old claude-code-sdk package still installs, but its final release (0.0.25, September 29, 2025) is marked deprecated and no longer maintained; it is a standalone package rather than an alias of claude-agent-sdk.[22]

Recent additions

The SDK's release cadence is fast. Notable additions since the September 2025 rename include (versions and dates from the Python changelog and PyPI):[3][12]

DateAdditionWhy it matters
Oct 2025Claude Skills integrationReusable workflows packaged as SKILL.md files, loaded on demand[14]
Feb 2026effort option (low, medium, high, max) and thinking configuration (Python 0.1.36)Finer control over extended thinking; max_thinking_tokens deprecated
Feb 2026Apple Xcode 26.3 native integrationBrings the SDK into Apple's IDE; JetBrains had shipped an SDK-based Claude Agent in September 2025[10][21]
Apr 2026SessionStore protocol in Python 0.1.64, at parity with TypeScriptPluggable session persistence, with copy-in S3, Redis and Postgres reference adapters
2026xhigh effort levelAn Opus 4.7-specific level that falls back to high on other models

Expanded article table

Documentation and learning resources

Anthropic maintains the canonical documentation at code.claude.com/docs/en/agent-sdk (older docs.claude.com links redirect there).[1] It includes a quickstart, a guide for each capability, and separate Python and TypeScript references.

The Python repository's examples/ directory holds short feature scripts (quick start, hooks, custom MCP tools, permission callbacks, session stores), and the TypeScript repository's holds reference session-store adapters.[3][4] Anthropic's separate claude-agent-sdk-demos repository has demo apps including an email agent, a research agent, a resume generator, an Excel demo and a simple chat app.[23] Anthropic's cookbook also has Claude Agent SDK recipes, such as one for migrating from the OpenAI Agents SDK.[5]

Continue reading

More from See also

Topics:AI AgentsAnthropicDeveloper ToolsOpen Source AI

References

  1. ^1 ^2 ^3 ^4 ^5 ^6 ^7 ^8 ^9 ^10 ^11 ^12 ^13 ^14 ^15 ^16 ^17 ^18 ^19 ^20 ^21 ^22Anthropic. "Agent SDK overview." Claude API Documentation. docs.claude.com/...overview
  2. ^1 ^2 ^3 ^4 ^5 ^6 ^7 ^8 ^9 ^10 ^11 ^12 ^13 ^14 ^15 ^16 ^17 ^18 ^19Anthropic. "Building agents with the Claude Agent SDK." Anthropic Engineering Blog, September 29, 2025. anthropic.com/...-agents-with-the-claude-agent-sdk
  3. ^1 ^2 ^3 ^4 ^5 ^6 ^7 ^8 ^9Anthropic. "claude-agent-sdk-python." GitHub. github.com/...claude-agent-sdk-python
  4. ^1 ^2 ^3 ^4 ^5 ^6Anthropic. "claude-agent-sdk-typescript." GitHub. github.com/...claude-agent-sdk-typescript
  5. ^1 ^2 ^3 ^4 ^5 ^6Anthropic. "Migrate to Claude Agent SDK." Claude API Documentation. docs.claude.com/...migration-guide
  6. ^1 ^2 ^3 ^4 ^5 ^6 ^7 ^8 ^9 ^10Anthropic. "Connect to external tools with MCP." Claude API Documentation. docs.claude.com/...mcp
  7. ^1 ^2 ^3 ^4 ^5 ^6 ^7 ^8Anthropic. "Subagents in the SDK." Claude API Documentation. docs.claude.com/...subagents
  8. ^1 ^2 ^3 ^4 ^5Anthropic. "Hooks in the SDK." Claude API Documentation. docs.claude.com/...hooks
  9. ^1 ^2 ^3 ^4 ^5 ^6Anthropic. "Skills in the SDK." Claude API Documentation. docs.claude.com/...skills
  10. ^1 ^2 ^3 ^4 ^5 ^6Anthropic. "Apple's Xcode now supports the Claude Agent SDK." Anthropic News, February 2026. anthropic.com/...apple-xcode-claude-agent-sdk
  11. ^1 ^2 ^3 ^4 ^5Apple. "Xcode 26.3 unlocks the power of agentic coding." Apple Newsroom, February 2026. apple.com/...3-unlocks-the-power-of-agentic-coding
  12. ^1 ^2 ^3PyPI. "claude-agent-sdk." pypi.org/...claude-agent-sdk
  13. ^1 ^2npm. "@anthropic-ai/claude-agent-sdk." npmjs.com/...claude-agent-sdk
  14. ^1 ^2 ^3Anthropic. "Equipping agents for the real world with Agent Skills." Anthropic Engineering Blog, October 16, 2025. anthropic.com/...-the-real-world-with-agent-skills
  15. ^1 ^2 ^3 ^4 ^5Anthropic. "Configure permissions." Claude Code documentation, Agent SDK. Accessed September 2, 2026. code.claude.com/...permissions
  16. ^1 ^2 ^3 ^4 ^5 ^6 ^7Anthropic. "Work with sessions." Claude Code documentation, Agent SDK. Accessed September 2, 2026. code.claude.com/...sessions
  17. ^1 ^2Anthropic. "Persist sessions to external storage." Claude Code documentation, Agent SDK. Accessed September 2, 2026. code.claude.com/...session-storage
  18. ^Anthropic. "Manage sessions." Claude Code documentation. Accessed September 2, 2026. code.claude.com/...sessions
  19. ^1 ^2 ^3 ^4 ^5 ^6Anthropic. "Agent SDK reference - Python." Claude Code documentation. Accessed September 2, 2026. code.claude.com/...python
  20. ^1 ^2 ^3Anthropic. "Track cost and usage." Claude Code documentation, Agent SDK. Accessed November 3, 2026. code.claude.com/...cost-tracking
  21. ^1 ^2JetBrains. "Introducing Claude Agent in JetBrains IDEs." JetBrains AI Blog, September 2025. blog.jetbrains.com/...aude-agent-in-jetbrains-ides
  22. ^1 ^2PyPI. "claude-code-sdk." pypi.org/...claude-code-sdk
  23. ^Anthropic. "claude-agent-sdk-demos." GitHub. github.com/...claude-agent-sdk-demos
  24. ^Anthropic. "Introducing Claude 4." Anthropic News, May 22, 2025. anthropic.com/...claude-4
  25. ^OpenAI. "Model context protocol (MCP)." OpenAI Agents SDK documentation. openai.github.io/...mcp
  26. ^Microsoft. "AutoGen" (repository README). GitHub. github.com/...autogen
  27. ^1 ^2Anthropic. "Tools reference." Claude Code documentation. Accessed November 3, 2026. code.claude.com/...tools-reference

Improve this article

Add missing citations, update stale details, or write a clearer explanation. Anyone can edit: changes go live when you publish, and every edit is checked by an editor.

12 revisions · v12 · 7,183 words · full history

Fact-checks are independent of edits: a reviewer re-verifies the article against its sources and stamps the date. How we verify

Research and drafting on this wiki are AI-assisted, under named human editorial standards. How AI is used here

Reviewer note: Independent fact-check of the full article against its cited sources (170 claims, 34 sources fetched); 25 material + 24 minor fixed

Cite this page: AI Wiki. "Claude Agent SDK." aiwiki.ai, updated 1 Nov 2026, fact-checked 2 Nov 2026. CC BY 4.0. https://aiwiki.ai/wiki/claude_agent_sdk

Edit article