# Claude Agent SDK

> Source: https://aiwiki.ai/wiki/claude_agent_sdk
> Updated: 2026-06-22
> Categories: AI Agents, Anthropic, Developer Tools, Open Source AI
> From AI Wiki (https://aiwiki.ai), a free encyclopedia of artificial intelligence. Quote with attribution.

The **Claude [Agent](/wiki/agent) SDK** is [Anthropic](/wiki/anthropic)'s official software development kit for building custom [AI agents](/wiki/ai_agents) powered by [Claude](/wiki/claude), released on September 29, 2025 as the renamed and expanded successor to the Claude Code SDK.[1][2] Available for both [Python](/wiki/python) and [TypeScript](/wiki/typescript), it provides developers with the same tools, agent loop, and context management infrastructure (the "agent harness") that powers [Claude Code](/wiki/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](/wiki/model_context_protocol) (MCP).[1]

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, customer support, and legal analysis.[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 is open source. The Python implementation lives at `anthropics/claude-agent-sdk-python` on [GitHub](/wiki/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

| Attribute | Value |
| --- | --- |
| Original name | Claude Code SDK |
| Renamed to | Claude Agent SDK |
| Rename date | September 29, 2025 |
| First PyPI prerelease | July 21, 2025 (`claude-code-sdk` 0.0.0.dev20250121) |
| First stable release | September 29, 2025 (alongside [Claude Sonnet 4.5](/wiki/claude_sonnet_4_5)) |
| Current Python version (mid-2026) | 0.2.105 (June 2026), bundling claude-cli ~2.1.150 |
| Languages | Python 3.10+, TypeScript / Node.js 18+ |
| License (SDK code) | MIT |
| License (CLI binary) | Anthropic Commercial Terms |
| Source | github.com/anthropics/claude-agent-sdk-python, github.com/anthropics/claude-agent-sdk-typescript |
| Default model | Claude Sonnet 4.5 (configurable to [Opus 4.7](/wiki/claude_opus_4_7), [Sonnet 4.6](/wiki/claude_sonnet_4_6), [Haiku 4.5](/wiki/claude_haiku_4_5)) |
| Inference backends | Anthropic API, [AWS Bedrock](/wiki/aws_bedrock), Google [Vertex AI](/wiki/vertex_ai), Microsoft Foundry |
| Documentation | docs.claude.com/en/api/agent-sdk |

## When was the Claude Agent SDK released?

The roots of the Claude Agent SDK trace back to February 2025, when Anthropic launched [Claude Code](/wiki/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).[12] Through July, August, and early September, the SDK existed as a thin Python wrapper that spawned the Claude Code CLI as a subprocess and parsed its streaming JSON output. Internal teams at Anthropic, plus a handful of design partners including Cursor and Vercel, were already using it to build production agents during this period.

The stable 1.0 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).[2][5] The rename was timed alongside the launch of [Claude Sonnet 4.5](/wiki/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] Apple's announcement specifically called out the SDK's hooks and subagents as the building blocks for Xcode's new agentic coding view.[11] The integration relies on Xcode Previews to give Claude visual feedback when it edits SwiftUI views, closing the verify step of the agent loop without a human in the middle.[11]

Releases on both SDKs are roughly weekly. By June 2026 the Python SDK had reached version 0.2.105, bundling Claude CLI in the 2.1.x series.[12] The changelog reads like a slow merger of features that previously lived only in the CLI: skills, hot reload, plan mode, named themes, the `/loop` slash command, extended-thinking effort levels (`low`, `medium`, `high`, `max`), a `SessionStore` protocol, and a steady stream of permission UX work.

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

| Language | Package | Status | Notes |
| --- | --- | --- | --- |
| [Python](/wiki/python) | `claude-agent-sdk` (PyPI) | Official, stable | Requires Python 3.10+. Async-first API based on `asyncio`. |
| [TypeScript](/wiki/typescript) | `@anthropic-ai/claude-agent-sdk` (npm) | Official, stable | Requires Node.js 18+. Uses async iterators and `AsyncGenerator`. |
| [Go](/wiki/go) | `humanloop-go-sdk`, `agent-sdk-go` | Community | Wraps the CLI; not feature-complete. |
| [Rust](/wiki/rust) | `claude-agent-rs` | Community | Bindings to the streaming JSON protocol. |
| [Java](/wiki/java) | `claude-agent-sdk-java` | Community | Maintained by independent contributors. |
| Ruby | `claude_agent_sdk` (gem) | Community | Thin wrapper over the CLI. |

The official Python and TypeScript SDKs share the same conceptual model. The names of options classes match (`ClaudeAgentOptions`), 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](/wiki/model_context_protocol) 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](/wiki/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](/wiki/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]

| 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:

```python
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:

```python
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 exposes the same two patterns through its `query()` function and `ClaudeAgentClient` class, with idiomatic Node.js types.

## 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 agents" and are kept prominent in Claude's context window so they are the first actions the model considers.[2]

| Tool | Description | Typical use |
| --- | --- | --- |
| **Read** | Read any file in the working directory, with line numbers and offsets | Reading source files, configs, logs |
| **Write** | Create new files | Generating new modules, reports, manifests |
| **Edit** | Make precise string replacements in existing files | Refactors, bug fixes, surgical edits |
| **NotebookEdit** | Edit cells in [Jupyter](/wiki/jupyter) notebooks | Data science notebooks (.ipynb) |
| **Bash** | Run terminal commands, scripts, and git operations | Tests, builds, version control, system queries |
| **Glob** | Find files by pattern (e.g., `**/*.ts`, `src/**/*.py`) | Locating files by name |
| **Grep** | Search file contents using regular expressions | Finding code that matches a pattern |
| **WebSearch** | Search the web for current information | Looking up library docs, news, recent events |
| **WebFetch** | Fetch and parse web page content | Reading specific URLs the user provides |
| **AskUserQuestion** | Prompt the user for clarifying input with multiple-choice options | Disambiguating fuzzy requests |
| **TodoWrite** | Track multi-step plans inside a long task | Long-running agents that need to remember subtasks |
| **Agent** | Spawn and delegate tasks to subagents | Decomposing big jobs into focused chunks |

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]

```python
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.[6] 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](/wiki/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]

| Transport | Where it runs | When to use |
| --- | --- | --- |
| stdio | Local subprocess | Default for local servers (filesystem, shell, git tools) |
| Streamable HTTP | Remote HTTP endpoint | Hosted enterprise servers, SaaS connectors |
| SSE (Server-Sent Events) | Remote endpoint with streaming | Older remote servers; being phased out in favor of Streamable HTTP |

The in-process [MCP server](/wiki/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](/wiki/playwright_mcp) server for browser automation:

```python
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] The hooks system in the SDK is the same one used by Claude Code, which means a hook script written for the CLI works inside an SDK agent and vice versa.[8]

### Hook events

| Hook event | Trigger point | Common uses |
| --- | --- | --- |
| `PreToolUse` | Before a tool is invoked | Validate or block dangerous commands; redact secrets |
| `PostToolUse` | After a tool completes | Log tool usage; collect telemetry; run linters |
| `UserPromptSubmit` | When a user prompt is received | Inject context; rewrite prompts; classify intent |
| `Stop` | When the agent finishes a turn | Notify external systems; save artifacts |
| `SubagentStop` | When a subagent finishes | Aggregate or route subagent results |
| `SessionStart` | When a session begins | Bootstrap state; load user-specific context |
| `SessionEnd` | When a session ends | Persist memory; emit usage metrics |
| `Notification` | When the agent surfaces a status message | Forward to chat UIs or logs |

### 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]

```python
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](/wiki/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] The SDK has supported skills natively since CLI version 2.1, with hot reload added shortly after.[9]

### 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 searches three locations for skills, in this order:[9]

| Scope | Location | Use |
| --- | --- | --- |
| User | `~/.claude/skills/` | Personal workflows that follow you across projects |
| Project | `.claude/skills/` (in working directory) | Team-shared skills checked into a repo |
| Plugin | `.claude/plugins/<plugin>/skills/` | Skills bundled with a Claude Code plugin |

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:

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

If `setting_sources` is left unset (the default), no filesystem settings are loaded at all, including skills.[9] This is intentional: production agents running in CI or in multi-tenant servers usually do not want to inherit whatever happens to be in `~/.claude/skills/` on the build host.

## 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]

```python
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, but most production deployments cap recursion at one or two levels. Going deeper tends to confuse the parent's notion of what the agent is supposed to be doing.

## Sessions

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:

```python
# 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. A common pattern is to fork at a decision point, run two candidate agents in parallel against the fork, and pick the one whose verification step succeeds. As of the 2026 releases, both SDKs expose a `SessionStore` protocol (with an in-memory reference implementation) so applications can persist and reload session state through their own storage layer.[12]

### Session teleportation

Claude Code 2.1 introduced session teleportation, which the SDK exposes through the same resume mechanism.[16] A developer can pause an agent on a laptop, capture its session ID, and resume the same conversation later from a CI worker or a production server. The full transcript and any persistent state move with the session ID.

## Permissions and safety

The SDK provides granular control over agent permissions. Permissions exist at two layers: which tools are available at all, and how the agent is allowed to invoke them.

| Setting | Effect |
| --- | --- |
| `allowed_tools` | Pre-approves specific tools for automatic execution |
| `disallowed_tools` | Explicitly blocks tools the agent should never use |
| `permission_mode="default"` | Agent must request approval for write operations |
| `permission_mode="acceptEdits"` | Auto-approves file modifications |
| `permission_mode="acceptAll"` | Auto-approves every tool call (use with care) |
| `permission_mode="plan"` | Plan mode: agent drafts a plan first, executes after approval |
| `can_use_tool` callback | Programmatic per-call permission decisions |

The `can_use_tool` callback is the most flexible option.[15] It receives the tool name and arguments and returns either an `allow` or `deny` decision. This is how teams build custom approval flows: route bash commands through a sandbox, escalate file writes outside the working directory to a human reviewer, or rate-limit web fetches.

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

Plan mode, added during Claude Code 2.0 and exposed through the SDK's `permission_mode="plan"` setting, asks the agent to produce a plan before executing anything.[15] The agent reads files and gathers context, but does not write, edit, or run shell commands until the plan is approved. This is the recommended mode for unfamiliar codebases or tasks where the cost of a wrong action is high. Once the plan is accepted, the agent runs in normal mode with the plan as scaffolding.

## Cost tracking

Every message the SDK streams includes the token counts for that turn.[1] The `ResultMessage` at the end of a query includes a final `usage` object summing input tokens, output tokens, cache reads, cache writes, and the dollar-equivalent cost based on the active model's pricing.[1] Cost tracking is one of the SDK's most underrated features. It removes the need to instrument the underlying API calls separately:

```python
async for msg in client.receive_response():
    if hasattr(msg, "usage"):
        print(f"Cost: ${msg.usage.cost_usd:.4f} ({msg.usage.input_tokens} in, {msg.usage.output_tokens} out)")
```

The SDK also exposes a Cost API at the session level, which aggregates spend across an entire conversation including subagent calls. Engineering teams use this to set per-task budgets and to bail out of runaway agents that have started looping.

## Configuration options

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

| 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 (`default`, `acceptEdits`, `acceptAll`, `plan`) |
| `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) |
| `max_thinking_tokens` | int | Cap on extended thinking tokens per turn |
| `resume` | string | Session ID to resume |
| `fork_session` | bool | Fork the resumed session into a new branch |

By default, the Agent SDK does not load filesystem settings (CLAUDE.md, settings.json, slash commands).[1] 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"]`.[1]

## Installation and authentication

### Python

```bash
pip install claude-agent-sdk
```

Requires Python 3.10 or later.[12] The Claude Code CLI is automatically bundled with the package. The first import triggers an integrity check on the bundled binary.

### TypeScript / JavaScript

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

Requires Node.js 18 or later.[13] The CLI binary is fetched as a postinstall step.

### Authentication

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

```bash
export ANTHROPIC_API_KEY=your-api-key
```

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

| 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 Foundry | `CLAUDE_CODE_USE_FOUNDRY=1` | Uses Azure credentials |

For enterprise customers using SSO, the SDK also supports OAuth flows through the bundled CLI's `claude login` command. Once a user is authenticated interactively, the SDK picks up the cached credentials and runs without an explicit API key.

## 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 describes Claude Code itself as a thin interface over the SDK.[2] 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 |
| Settings loaded by default | Yes | No (must opt in via `setting_sources`) |
| Skills loaded by default | Yes | No (must opt in via `setting_sources`) |
| Output | Pretty terminal UI | Structured JSON stream |

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](/wiki/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.

| Framework | Primary language | Model support | Built-in tools | MCP support | Multi-agent | Hooks / lifecycle | License |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Claude Agent SDK | Python, TypeScript | [Anthropic](/wiki/anthropic) Claude | Yes (Read, Write, Bash, etc.) | First-class, native | Subagents with context isolation | PreToolUse, PostToolUse, Stop, etc. | MIT (SDK) / Anthropic Commercial (CLI) |
| [OpenAI Agents SDK](/wiki/openai_agents_sdk) | Python | [OpenAI](/wiki/openai) GPT, partially provider-agnostic | Hosted tools (web search, code interpreter, file search) | Limited | Handoffs between specialized agents | Guardrails and tracing | MIT |
| [LangChain](/wiki/langchain) / [LangGraph](/wiki/langgraph) | Python, TypeScript | 600+ model integrations | Via integrations | Via plugins | LangGraph for orchestration | Callbacks | MIT |
| [LlamaIndex](/wiki/llamaindex) | Python, TypeScript | Many providers | Strong on data loaders | Via plugins | Workflow framework | Event handlers | MIT |
| [CrewAI](/wiki/crewai) | Python | Multiple LLM providers | Via integrations | Via plugins | Role-based collaborative agents | Task callbacks | MIT |
| [AutoGen](/wiki/autogen) | Python | Multiple providers | Via integrations | Via plugins | Conversable multi-agent groups | Limited | MIT |
| [Strands](/wiki/strands) | Python | Bedrock-first, multiple providers | Strong AWS integrations | Yes | Multi-agent supported | Callbacks | Apache 2.0 |
| [Pydantic AI](/wiki/pydantic_ai) | Python | Multiple providers | Lightweight | Yes | Yes | Type-safe lifecycle | MIT |

### 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](/wiki/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](/wiki/strands) is AWS's agent framework, optimized for Bedrock and AWS service integrations. [Pydantic AI](/wiki/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 mixes Anthropic's own usage, public customer announcements, and patterns that have shown up in third-party blog posts and conference talks.

| Deployment | Use of the SDK | Source |
| --- | --- | --- |
| [Cursor](/wiki/cursor) Background Agents | Long-running coding agents that run on cloud workers and open PRs autonomously | Cursor changelog, late 2025 |
| GitHub Copilot Workspace tasks | Some task-execution flows wrap the Agent SDK alongside Copilot's own runtime | [GitHub](/wiki/github) blog |
| Apple Xcode 26.3 agentic coding | Native integration; Xcode UI calls the SDK with Xcode Previews as the verification step | Apple Newsroom, Feb 2026 |
| Anthropic Claude Code (the CLI) | Claude Code is a thin user interface over the same library | Anthropic engineering blog |
| Anthropic internal SRE | On-call agents that triage alerts and draft mitigations | Anthropic engineering talks |
| Anthropic Code Review | The 2026 Code Review product is built on the SDK plus subagents | Anthropic news, March 2026 |
| [Devin](/wiki/devin) competitors | Several autonomous coding startups use the SDK as their execution layer | Various |
| Cloud sandbox providers | Companies that sell ephemeral VMs for agents (e.g., E2B, Daytona) ship Claude Agent SDK templates | Vendor docs |
| Customer support automation | Help-desk agents that read knowledge bases via MCP and draft responses | Anthropic case studies |
| Legal contract review | Document review agents that compare drafts against precedent libraries | Anthropic case studies |
| Financial analysis | Portfolio agents that pull market data via MCP and produce reports | Industry talks |
| Research assistants | Multi-document research agents that synthesize findings across PDFs and the web | Various |

### 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 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 |

### Message types and content blocks

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

| 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, including usage and cost |

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 wrapper code is open source under an MIT license, while the bundled Claude Code CLI binary is not. 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 and TypeScript SDK source repositories on [GitHub](/wiki/github) carry an MIT license for the SDK wrapper code,[3][4] while the bundled Claude Code CLI binary falls under Anthropic's Commercial Terms. Practically speaking, the wrapper code is forkable and modifiable under MIT terms; the CLI binary is not.

The SDK source code is publicly available at `anthropics/claude-agent-sdk-python`[3] and `anthropics/claude-agent-sdk-typescript`.[4] Issues and pull requests are accepted, and Anthropic's engineering team reviews them on roughly a weekly cadence.

## 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]

| 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 that go beyond a simple rename.[5] The system prompt no longer defaults to Claude Code's system prompt; an SDK agent now starts with no role unless one is provided.[5] Filesystem settings (CLAUDE.md, slash commands, settings.json) are no longer loaded automatically; they must be enabled with `setting_sources`.[5] These changes improve isolation and predictability for production deployments, at the cost of a small migration burden.

For at least a year after the rename, both package names continued to install. The old `claude-code-sdk` package became a thin alias that imports from `claude-agent-sdk` and emits a deprecation warning, so existing projects do not silently break.

## Recent additions

The SDK's release cadence is fast. The most consequential additions since the September 2025 stable release include:

| Date | Addition | Why it matters |
| --- | --- | --- |
| Oct 2025 | [Claude Skills](/wiki/claude_skills) integration | Reusable workflows packaged as `SKILL.md` files, loaded on demand |
| Nov 2025 | Streamable HTTP transport for MCP | Replaces SSE for remote MCP servers; cleaner error semantics |
| Dec 2025 | Plan mode in the SDK | Makes the agent draft a plan before any write or shell action |
| Jan 2026 | Long-running tool support | Tool calls that take minutes (e.g., builds, video renders) no longer time out |
| Feb 2026 | Apple Xcode native integration | First major IDE to ship the SDK as a built-in feature |
| Feb 2026 | Improved permission UX | Per-call approval callbacks with structured reasons |
| Mar 2026 | Code Review subagent product | Anthropic's first product built on the SDK as a paid offering |
| Apr 2026 | [Claude Opus 4.7](/wiki/claude_opus_4_7) as default | Default model upgraded from Sonnet 4.5 to Opus 4.7 for new SDK projects that opt into Opus pricing |
| Jun 2026 | `SessionStore` protocol and thinking effort levels | Pluggable session persistence at TS/Python parity; `low`/`medium`/`high`/`max` extended-thinking control |

## Documentation and learning resources

Anthropic maintains the canonical documentation at `docs.claude.com/en/api/agent-sdk`.[1] The site is organized into a tutorial track, a reference for every option and tool, and a growing catalog of cookbook recipes. Both Python and TypeScript share the same conceptual docs, with code samples shown side by side.

The two GitHub repositories include `examples/` directories with runnable agents: a code reviewer, a research assistant, a Slack bot, a documentation generator, and a web scraper.[3][4] The `anthropic-cookbook` repository on GitHub holds longer-form notebooks, including an agent that orchestrates [computer use](/wiki/computer_use) through the SDK and a multi-agent research pipeline.

## See also

- [Claude](/wiki/claude)
- [Claude Code](/wiki/claude_code)
- [Claude Skills](/wiki/claude_skills)
- [AI Agents](/wiki/ai_agents)
- [Anthropic API](/wiki/anthropic_api)
- [Model Context Protocol](/wiki/model_context_protocol)
- [LangChain](/wiki/langchain)
- [CrewAI](/wiki/crewai)
- [OpenAI Agents SDK](/wiki/openai_agents_sdk)
- [Anthropic](/wiki/anthropic)
- [Tool Use](/wiki/tool_use)

## References

1. Anthropic. "Agent SDK overview." Claude API Documentation. https://docs.claude.com/en/api/agent-sdk/overview
2. Anthropic. "Building agents with the Claude Agent SDK." Anthropic Engineering Blog, September 29, 2025. https://www.anthropic.com/engineering/building-agents-with-the-claude-agent-sdk
3. Anthropic. "claude-agent-sdk-python." GitHub. https://github.com/anthropics/claude-agent-sdk-python
4. Anthropic. "claude-agent-sdk-typescript." GitHub. https://github.com/anthropics/claude-agent-sdk-typescript
5. Anthropic. "Migrate to Claude Agent SDK." Claude API Documentation. https://docs.claude.com/en/api/agent-sdk/migration-guide
6. Anthropic. "Connect to external tools with MCP." Claude API Documentation. https://docs.claude.com/en/api/agent-sdk/mcp
7. Anthropic. "Subagents in the SDK." Claude API Documentation. https://docs.claude.com/en/api/agent-sdk/subagents
8. Anthropic. "Hooks in the SDK." Claude API Documentation. https://docs.claude.com/en/api/agent-sdk/hooks
9. Anthropic. "Skills in the SDK." Claude API Documentation. https://docs.claude.com/en/api/agent-sdk/skills
10. Anthropic. "Apple's Xcode now supports the Claude Agent SDK." Anthropic News, February 2026. https://www.anthropic.com/news/apple-xcode-claude-agent-sdk
11. Apple. "Xcode 26.3 unlocks the power of agentic coding." Apple Newsroom, February 2026. https://www.apple.com/newsroom/2026/02/xcode-26-point-3-unlocks-the-power-of-agentic-coding/
12. PyPI. "claude-agent-sdk." https://pypi.org/project/claude-agent-sdk/
13. npm. "@anthropic-ai/claude-agent-sdk." https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk
14. Anthropic. "Equipping agents for the real world with Agent Skills." Anthropic Engineering Blog, October 16, 2025. https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills
15. Anthropic. "Plan mode and permission UX." Anthropic Engineering Blog, December 2025.
16. Anthropic. "Claude Code 2.1 release notes." Anthropic Documentation.
17. Cursor. "Background Agents." Cursor changelog, late 2025. https://cursor.com/changelog

