The Claude Agent SDK is Anthropic's official software development kit for building custom AI agents powered by Claude. Available for both Python and TypeScript, it provides developers with the same tools, agent loop, and context management infrastructure that powers Claude Code, packaged as a programmable library. 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).
Originally released as the Claude Code SDK in mid-2025, the project was renamed to the Claude Agent SDK on September 29, 2025, to reflect its broader applicability beyond coding tasks. Anthropic recognized that developers were using the SDK for deep research, video creation, customer support, legal analysis, and many other non-coding applications. The rename signaled a shift in positioning from a coding-specific toolkit to a general-purpose agent runtime.
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. The first pre-release version of the Claude Code SDK appeared on PyPI on July 21, 2025 (version 0.0.0.dev20250121). The stable release 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).
The September 2025 launch coincided with the release of Claude Sonnet 4.5, and Anthropic published an engineering blog post titled "Building agents with the Claude Agent SDK" explaining the design philosophy. A notable 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.
As of March 2026, the Python SDK is at version 0.1.50, bundled with Claude CLI version 2.1.81.
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. Rather than requiring developers to implement their own tool execution loops and message passing, the SDK handles the entire agent loop internally.
The SDK operates on a continuous feedback cycle with four phases:
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.
The Python SDK offers two primary interfaces:
| Interface | Description | Use Case |
|---|---|---|
query() | Async generator function for simple queries | Lightweight, one-shot tasks |
ClaudeSDKClient | Full-featured client with session management | Multi-turn conversations, custom tools, hooks |
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)
One of the defining characteristics of the Claude Agent SDK is that it ships with a full set of built-in tools. 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.
| Tool | Description |
|---|---|
| Read | Read any file in the working directory |
| Write | Create new files |
| Edit | Make precise edits to existing files |
| Bash | Run terminal commands, scripts, and git operations |
| Glob | Find files by pattern (e.g., **/*.ts, src/**/*.py) |
| Grep | Search file contents using regular expressions |
| WebSearch | Search the web for current information |
| WebFetch | Fetch and parse web page content |
| AskUserQuestion | Prompt the user for clarifying input with multiple-choice options |
| Agent | Spawn and delegate tasks to subagents |
Developers control which tools are available through the allowed_tools parameter. For example, 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.
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:
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.
The Claude Agent SDK provides first-class support for the Model Context Protocol, an open standard for connecting AI agents to external tools and data sources. MCP enables agents to interact with databases, browsers, APIs, and hundreds of third-party services without hardcoding tool definitions.
MCP servers can be configured either in code or through a .mcp.json configuration file. The SDK supports multiple transport protocols: local processes communicate via stdin/stdout, while remote services use HTTP or Server-Sent Events (SSE).
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. This feature is available with Claude Sonnet 4 and later models.
Subagents allow a main agent to spawn specialized child agents that handle focused subtasks. Each subagent runs in its own fresh conversation with an isolated context window, custom system prompt, specific tool access, and independent permissions.
The key benefit of context isolation is that intermediate tool calls and results stay inside the subagent. Only the final result is returned to the parent agent. For instance, a research-assistant subagent might explore dozens of files, but the parent receives only a concise summary rather than every file the subagent read.
Multiple subagents can run concurrently, which significantly speeds up complex workflows. Claude automatically determines whether to invoke a subagent based on its description field, or developers can explicitly request one by name.
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)
Hooks allow developers to run custom code at specific points in the agent lifecycle. They can validate, log, block, or transform agent behavior without modifying the core agent loop.
Available hook events include:
| Hook Event | Trigger Point |
|---|---|
PreToolUse | Before a tool is invoked |
PostToolUse | After a tool completes |
Stop | When the agent finishes |
SessionStart | When a session begins |
SessionEnd | When a session ends |
UserPromptSubmit | When a user prompt is received |
A common use case is blocking dangerous commands. For example, a PreToolUse hook on the Bash tool can inspect the command string and deny execution if it contains prohibited patterns.
The SDK supports persistent sessions that maintain context across multiple exchanges. Claude remembers files it has read, analysis it has performed, and the full conversation history. Developers can capture a session ID from the first query and resume it later with full context preservation:
# First query: capture the session ID
async for message in query(
prompt="Read the authentication module",
options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"]),
):
if hasattr(message, "subtype") and message.subtype == "init":
session_id = message.session_id
# Resume with full context
async for message in query(
prompt="Now find all places that call it",
options=ClaudeAgentOptions(resume=session_id),
):
if hasattr(message, "result"):
print(message.result)
Sessions can also be forked to explore different approaches while preserving the original conversation state.
The SDK provides granular control over agent permissions:
acceptEdits to auto-approve file modifications).MCP tools require explicit permission before Claude can use them. Without permission, Claude sees that the tools exist but cannot invoke them.
pip install claude-agent-sdk
Requires Python 3.10 or later. The Claude Code CLI is automatically bundled with the package.
npm install @anthropic-ai/claude-agent-sdk
The SDK requires an Anthropic API key, set as an environment variable:
export ANTHROPIC_API_KEY=your-api-key
Alternatively, the SDK supports authentication through third-party cloud providers:
| Provider | Environment Variable | Details |
|---|---|---|
| Amazon Bedrock | CLAUDE_CODE_USE_BEDROCK=1 | Uses AWS credentials |
| Google Vertex AI | CLAUDE_CODE_USE_VERTEX=1 | Uses Google Cloud credentials |
| Microsoft Azure | CLAUDE_CODE_USE_FOUNDRY=1 | Uses Azure credentials |
The ClaudeAgentOptions class (Python) and equivalent TypeScript options object accept numerous configuration parameters:
| Parameter | Type | Description |
|---|---|---|
system_prompt | string or dict | Custom system prompt or preset (e.g., claude_code) |
max_turns | int | Maximum number of conversation turns |
allowed_tools | list | Tools pre-approved for auto-execution |
disallowed_tools | list | Tools to block entirely |
permission_mode | string | Auto-accept behavior for file edits |
cwd | string or Path | Working directory for the agent |
mcp_servers | dict | MCP server configurations |
hooks | dict | Hook handler registrations |
cli_path | string | Custom path to Claude Code CLI |
model | string | Claude model to use |
setting_sources | list | Filesystem settings to load (e.g., ["project"]) |
agents | dict | Subagent definitions |
betas | list | Beta features to enable (e.g., 1M context window) |
By default, the Agent SDK does not load filesystem settings (CLAUDE.md, settings.json, slash commands). This is a deliberate design choice for predictable behavior in CI/CD environments, deployed applications, and multi-tenant systems. Developers who want Claude Code's default behavior can set setting_sources=["user", "project", "local"].
Claude Code is Anthropic's agentic coding tool that lives in the terminal. The Claude Agent SDK is the library that powers Claude Code internally. The relationship can be summarized as follows:
| Aspect | Claude Code CLI | Claude Agent SDK |
|---|---|---|
| Interface | Interactive terminal | Programmatic library |
| Best for | Daily development, one-off tasks | CI/CD pipelines, production automation, custom applications |
| Tools | Full toolset | Same full toolset, configurable |
| Customization | CLAUDE.md, settings files | Full programmatic control, hooks, subagents |
| Languages | N/A (CLI) | Python and TypeScript |
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.
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.
| Feature | Claude Agent SDK | OpenAI Agents SDK | LangChain | CrewAI |
|---|---|---|---|---|
| Primary Language | Python, TypeScript | Python | Python, TypeScript | Python |
| Model Support | Claude only | OpenAI models only | 600+ model integrations | Multiple LLM providers |
| Built-in Tools | Yes (Read, Write, Bash, etc.) | Hosted tools (web search, code interpreter) | Via integrations | Via integrations |
| MCP Support | First-class, native | Limited | Via plugins | Via plugins |
| Multi-Agent | Subagents with context isolation | Handoffs between specialized agents | LangGraph for orchestration | Role-based collaborative agents |
| Agent Loop | Fully managed | Fully managed | Developer-controlled | Fully managed |
| Hooks/Lifecycle | PreToolUse, PostToolUse, Stop, etc. | Guardrails and tracing | Callbacks | Task callbacks |
| Session Management | Built-in resume and fork | Conversation threads | Memory modules | Shared memory |
| License | Anthropic Commercial Terms | MIT | MIT | MIT/Apache 2.0 |
| Voice/Multimodal | Text and code focused | Voice via Realtime API | Via integrations | Text focused |
| Design Philosophy | Hooks and lifecycle control | Handoffs and guardrails | Ecosystem breadth | Collaborative autonomy |
The Claude Agent SDK differentiates itself primarily 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.
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, while the Claude Agent SDK's strength lies in complex file system operations and code-related tasks.
CrewAI takes a fundamentally different approach by focusing 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.
The Claude Agent SDK supports a wide range of applications across different domains:
The SDK provides a structured error hierarchy for handling different failure modes:
| Error Class | Description |
|---|---|
ClaudeSDKError | Base error class for all SDK errors |
CLINotFoundError | Claude Code CLI not installed or not found |
CLIConnectionError | Connection issues with the CLI process |
ProcessError | CLI process failed (includes exit code) |
CLIJSONDecodeError | Failed to parse response JSON |
The SDK streams messages of several types during agent execution:
| Message Type | Description |
|---|---|
AssistantMessage | Response content from Claude |
UserMessage | User input forwarded to the agent |
SystemMessage | System-level instructions or status updates |
ResultMessage | Final result of the agent's work |
Content within messages is structured as blocks: TextBlock for text content, ToolUseBlock for tool invocations, and ToolResultBlock for tool execution results.
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 SDK repository on GitHub lists an MIT license for the SDK wrapper code, while the bundled Claude Code CLI binary falls under Anthropic's Commercial Terms. The SDK source code is publicly available on GitHub at anthropics/claude-agent-sdk-python and anthropics/claude-agent-sdk-typescript.
Developers who built on the original Claude Code SDK need to update their code for the renamed package. The migration involves changing package names, import paths, and one renamed type:
| Aspect | Old (Claude Code SDK) | New (Claude Agent SDK) |
|---|---|---|
| Python package | claude-code-sdk | claude-agent-sdk |
| TypeScript package | @anthropic-ai/claude-code | @anthropic-ai/claude-agent-sdk |
| Python import | from claude_code_sdk import ... | from claude_agent_sdk import ... |
| Options class | ClaudeCodeOptions | ClaudeAgentOptions |
The Agent SDK also introduced breaking changes: the system prompt no longer defaults to Claude Code's system prompt, and filesystem settings are no longer loaded automatically. These changes improve isolation and predictability for production deployments.