# claude-agent-sdk

> Python SDK for Claude Code

- **URL**: https://www.freshcrate.ai/projects/claude-agent-sdk
- **Author**: pypi
- **Category**: AI Agents
- **Latest version**: `v0.2.88` (2026-06-02)
- **License**: MIT
- **Source**: https://github.com/anthropics/claude-agent-sdk-python
- **Homepage**: https://pypi.org/project/claude-agent-sdk/
- **Language**: Python
- **GitHub**: 6,458 stars, 909 forks
- **Registry**: pypi (`claude-agent-sdk`)
- **Tags**: `ai`, `anthropic`, `claude`, `pypi`, `sdk`

## Description

# Claude Agent SDK for Python

Python SDK for Claude Agent. See the [Claude Agent SDK documentation](https://platform.claude.com/docs/en/agent-sdk/python) for more information.

## Installation

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

**Prerequisites:**

- Python 3.10+

**Note:** The Claude Code CLI is automatically bundled with the package - no separate installation required! The SDK will use the bundled CLI by default. If you prefer to use a system-wide installation or a specific version, you can:

- Install Claude Code separately: `curl -fsSL https://claude.ai/install.sh | bash`
- Specify a custom path: `ClaudeAgentOptions(cli_path="/path/to/claude")`

## Quick Start

```python
import anyio
from claude_agent_sdk import query

async def main():
    async for message in query(prompt="What is 2 + 2?"):
        print(message)

anyio.run(main)
```

## Basic Usage: query()

`query()` is an async function for querying Claude Code. It returns an `AsyncIterator` of response messages. See [src/claude_agent_sdk/query.py](src/claude_agent_sdk/query.py).

```python
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, TextBlock

# Simple query
async for message in query(prompt="Hello Claude"):
    if isinstance(message, AssistantMessage):
        for block in message.content:
            if isinstance(block, TextBlock):
                print(block.text)

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

async for message in query(prompt="Tell me a joke", options=options):
    print(message)
```

### Using Tools

By default, Claude has access to the full [Claude Code toolset](https://code.claude.com/docs/en/settings#tools-available-to-claude) (Read, Write, Edit, Bash, and others). `allowed_tools` is a permission allowlist: listed tools are auto-approved, and unlisted tools fall through to `permission_mode` and `can_use_tool` for a decision. It does not remove tools from Claude's toolset. To block specific tools, use `disallowed_tools`. See the [permissions guide](https://platform.claude.com/docs/en/agent-sdk/permissions) for the full evaluation order.

```python
options = ClaudeAgentOptions(
    allowed_tools=["Read", "Write", "Bash"],  # auto-approve these tools
    permission_mode='acceptEdits'  # auto-accept file edits
)

async for message in query(
    prompt="Create a hello.py file",
    options=options
):
    # Process tool use and results
    pass
```

### Working Directory

```python
from pathlib import Path

options = ClaudeAgentOptions(
    cwd="/path/to/project"  # or Path("/path/to/project")
)
```

## ClaudeSDKClient

`ClaudeSDKClient` supports bidirectional, interactive conversations with Claude
Code. See [src/claude_agent_sdk/client.py](src/claude_agent_sdk/client.py).

Unlike `query()`, `ClaudeSDKClient` additionally enables **custom tools** and **hooks**, both of which can be defined as Python functions.

### Custom Tools (as In-Process SDK MCP Servers)

A **custom tool** is a Python function that you can offer to Claude, for Claude to invoke as needed.

Custom tools are implemented in-process MCP servers that run directly within your Python application, eliminating the need for separate processes that regular MCP servers require.

For an end-to-end example, see [MCP Calculator](examples/mcp_calculator.py).

#### Creating a Simple Tool

```python
from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions, ClaudeSDKClient

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

# Create an SDK MCP server
server = create_sdk_mcp_server(
    name="my-tools",
    version="1.0.0",
    tools=[greet_user]
)

# Use it with Claude. allowed_tools pre-approves the tool so it runs
# without a permission prompt; it does not control tool availability.
options = ClaudeAgentOptions(
    mcp_servers={"tools": server},
    allowed_tools=["mcp__tools__greet"]
)

async with ClaudeSDKClient(options=options) as client:
    await client.query("Greet Alice")

    # Extract and print response
    async for msg in client.receive_response():
        print(msg)
```

#### Benefits Over External MCP Servers

- **No subprocess management** - Runs in the same process as your application
- **Better performance** - No IPC overhead for tool calls
- **Simpler deployment** - Single Python process instead of multiple
- **Easier debugging** - All code runs in the same process
- **Type safety** - Direct Python function calls with type hints

#### Migration from External Servers

```python
# BEFORE: External MCP server (separate process)
options = ClaudeAgentOptions(
    mcp_servers={
        "calculator": {
            "type": "stdio",
            "command": "python",
            "args": ["-m", "calculator_server"]
        }
    }
)

# AFTER: SDK MCP server (in-process

## Recent releases

| Version | Date | Urgency | Changes |
| --- | --- | --- | --- |
| `v0.2.88` | 2026-06-02 | High | ### Bug Fixes  - **Trio compatibility for session stores**: Ported `session_store` code paths (`TranscriptMirrorBatcher`, `session_resume`, `sessions`) from raw `asyncio` primitives to `anyio`, fixing a crash (`TypeError: trio.run received unrecognized yield message`) when passing `session_store=` to `query()` or `ClaudeSDKClient` under trio (#990)  ### Internal/Other Changes  - Switched e2e CI jobs (`test-e2e`, `test-e2e-docker`, `test-examples`) from static API key to workload identity federa |
| `v0.2.87` | 2026-05-23 | High | ### Internal/Other Changes  - Updated bundled Claude CLI to version 2.1.150 - Switched CI workflows from static API key to Workload Identity Federation for Claude authentication, using short-lived tokens instead of long-lived secrets (#984)   ---  **PyPI:** https://pypi.org/project/claude-agent-sdk/0.2.87/  ```bash pip install claude-agent-sdk==0.2.87 ``` |
| `v0.2.85` | 2026-05-22 | High | ### Internal/Other Changes  - Updated bundled Claude CLI to version 2.1.148   ---  **PyPI:** https://pypi.org/project/claude-agent-sdk/0.2.85/  ```bash pip install claude-agent-sdk==0.2.85 ``` |
| `v0.2.82` | 2026-05-15 | High | ### Breaking  - **Breaking:** MCP servers now connect in the background by default; sessions start immediately and slow servers report `status: "pending"` in `init` until ready. Set `MCP_CONNECTION_NONBLOCKING=0` to restore the old behavior of waiting up to 5s before the first query, or mark a server `alwaysLoad: true` to require it in turn 1. - **Breaking:** Headless and SDK sessions now use Task tools (`TaskCreate` / `TaskUpdate` / `TaskGet` / `TaskList`) instead of `TodoWrite`. Tool consum |
| `v0.1.80` | 2026-05-09 | High | ### Internal/Other Changes  - Updated bundled Claude CLI to version 2.1.138   ---  **PyPI:** https://pypi.org/project/claude-agent-sdk/0.1.80/  ```bash pip install claude-agent-sdk==0.1.80 ``` |
| `v0.1.73` | 2026-05-04 | High | ### New Features  - **Eager session store flushing**: Added `session_store_flush` option to `ClaudeAgentOptions` (`"batched"` or `"eager"`). When set to `"eager"`, the transcript mirror delivers frames to `SessionStore.append()` in near-real-time instead of waiting for the end-of-turn flush, enabling live-tailing UIs, cross-process resume, and crash-durability use cases (#905)  ### Internal/Other Changes  - Updated bundled Claude CLI to version 2.1.128   ---  **PyPI:** https://pypi.org/project/ |
| `v0.1.71` | 2026-04-29 | High | ### New Features  - **Domain allowlist fields for sandbox network config**: Added `allowedDomains`, `deniedDomains`, `allowManagedDomainsOnly`, and `allowMachLookup` fields to `SandboxNetworkConfig`, bringing parity with the TypeScript schema and enabling Python SDK users to configure network allowlists with proper type hints (#893)  ### Internal/Other Changes  - Updated bundled Claude CLI to version 2.1.123   ---  **PyPI:** https://pypi.org/project/claude-agent-sdk/0.1.71/  ```bash pip install |
| `v0.1.66` | 2026-04-23 | High | ### Internal/Other Changes  - Updated bundled Claude CLI to version 2.1.119   ---  **PyPI:** https://pypi.org/project/claude-agent-sdk/0.1.66/  ```bash pip install claude-agent-sdk==0.1.66 ``` |
| `0.1.64` | 2026-04-21 | Low | Imported from PyPI (0.1.64) |
| `v0.1.64` | 2026-04-20 | High | ### New Features  - **SessionStore adapter**: Full SessionStore support at parity with the TypeScript SDK. Includes a `SessionStore` protocol with 5 methods (`append`, `load`, `list_sessions`, `delete`, `list_subkeys`), `InMemorySessionStore` reference implementation, transcript mirroring via `--session-mirror`, session resume from store, and 9 new async store-backed helper functions (`list_sessions_from_store`, `get_session_messages_from_store`, `fork_session_via_store`, etc.). Also adds a 13- |

## Citation

- HTML: https://www.freshcrate.ai/projects/claude-agent-sdk
- Markdown: https://www.freshcrate.ai/projects/claude-agent-sdk.md
- Dependencies JSON: https://www.freshcrate.ai/api/projects/claude-agent-sdk/deps

_Generated by freshcrate.ai. Indexes pypi releases for AI-agent ecosystem packages._
