anthropics/claude-agent-sdk-python
Python
Captured source
source ↗anthropics/claude-agent-sdk-python
Language: Python
License: MIT
Stars: 7264
Forks: 1088
Open issues: 312
Created: 2025-06-11T21:33:43Z
Pushed: 2026-06-10T21:15:09Z
Default branch: main
Fork: no
Archived: no
README:
Claude Agent SDK for Python
Python SDK for Claude Agent. See the Claude Agent SDK documentation for more information.
Installation
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
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).
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 (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 for the full evaluation order.
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
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
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
# 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)
from my_tools import add, subtract # Your tool functions
calculator = create_sdk_mcp_server(
name="calculator",
tools=[add, subtract]
)
options = ClaudeAgentOptions(
mcp_servers={"calculator": calculator}
)Mixed Server Support
You can use both SDK and external MCP servers together:
options = ClaudeAgentOptions(
mcp_servers={
"internal": sdk_server, # In-process SDK server
"external": { # External subprocess server
"type": "stdio",
"command": "external-server"
}
}
)Hooks
A hook is a Python function that the Claude Code _application_ (_not_ Claude) invokes at specific points of the Claude agent loop. Hooks can provide deterministic processing and automated feedback for Claude. Read more in Intercept and control agent behavior with hooks.
For more examples, see examples/hooks.py.
Example
from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient, HookMatcher
async def check_bash_command(input_data, tool_use_id, context):
tool_name = input_data["tool_name"]
tool_input = input_data["tool_input"]
if tool_name != "Bash":
return {}
command = tool_input.get("command", "")
block_patterns = ["foo.sh"]
for pattern in block_patterns:
if pattern in command:
return {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": f"Command contains invalid pattern: {pattern}",
}
}
return {}
options = ClaudeAgentOptions(…Excerpt shown — open the source for the full document.
Notability
notability 7.0/10New SDK, high stars, notable traction.