Claude Agent SDK for Python: Overview and Detailed Guide
The Claude Agent SDK for Python is a powerful, official Python library developed by Anthropic to facilitate the creation and management of AI agents using Claude AI models. Released as part of Anthropic's ecosystem for agentic AI development, it builds on the capabilities of Claude Code, allowing developers to integrate Claude's advanced reasoning, tool usage, and computer interaction features directly into Python applications. This SDK is particularly suited for building autonomous agents that can handle complex tasks like file operations, bash commands, custom tool integrations, and multi-turn conversations, all while maintaining high performance and ease of deployment.
Key Features and Capabilities
At its core, the SDK provides two primary interfaces: the query() function for simple, one-shot or multi-turn interactions, and the ClaudeSDKClient for more interactive, bidirectional sessions. The query() function acts as an async iterator that streams responses from Claude Code, making it ideal for quick prototyping. For instance, you can send a prompt like 'What is 2 + 2?' and receive streaming messages, including text blocks from assistant responses.
For advanced use cases, ClaudeSDKClient supports custom tools implemented as in-process MCP (Model Control Protocol) servers. These tools run directly within your Python process, avoiding the overhead of external subprocesses. Developers can define tools using a simple @tool decorator, specifying the tool's name, description, and input schema. An example is a 'greet' tool that takes a name parameter and returns a personalized message. The SDK handles tool invocation seamlessly, allowing Claude to call these functions during agent execution.
Hooks are another standout feature, enabling deterministic interventions in the agent loop. For example, you can implement a PreToolUse hook to inspect and approve or deny bash commands based on patterns, enhancing safety and control. This is crucial for production environments where security is paramount.
The SDK also integrates with Claude's built-in tools such as 'Read', 'Write', and 'Bash', configurable via ClaudeAgentOptions. Permissions can be set to auto-accept edits or require manual approval. Working directories can be specified for context-aware operations, and system prompts can be customized to define the agent's role.
Installation and Setup
To get started, ensure you have Python 3.10+, Node.js, and Claude Code 2.0.0+ installed globally via npm install -g @anthropic-ai/claude-code. Then, install the SDK with pip install claude-agent-sdk. The library handles communication with Claude Code via stdio, abstracting away much of the complexity.
Basic usage is straightforward:
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)This demonstrates the streaming nature of responses, where messages are yielded as they arrive.
For tool-enabled agents:
from claude_agent_sdk import ClaudeAgentOptions
options = ClaudeAgentOptions(
allowed_tools=["Read", "Write", "Bash"],
permission_mode='acceptEdits'
)
async for message in query(prompt="Create a hello.py file", options=options):
# Handle tool uses and results
passCustom MCP servers further extend functionality. By creating an in-process server with create_sdk_mcp_server, you can bundle multiple tools without managing separate processes, improving performance and simplifying debugging.
Error Handling and Best Practices
The SDK includes comprehensive error types like CLINotFoundError for missing dependencies, ProcessError for execution failures, and CLIJSONDecodeError for parsing issues. Robust error handling ensures reliable agent behavior in production.
Migration from the older Claude Code SDK is supported, with updates like renamed options (ClaudeCodeOptions to ClaudeAgentOptions) and enhanced isolation for settings and prompts. Examples in the repository, such as quick starts, streaming modes, and hook implementations, provide hands-on guidance.
Overall, this SDK empowers developers to leverage Claude's strengths in agentic AI, from simple queries to sophisticated, tool-augmented workflows, making it an essential tool for AI engineering projects.
