### Quick Start Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md A basic example demonstrating how to use the `query` function to get a response from Claude Code. ```APIDOC ## 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) ``` ``` -------------------------------- ### Installation Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md Install the Claude Agent SDK for Python using pip. Ensure you have Python 3.10+ and Node.js installed, along with the Claude Code npm package. ```APIDOC ## Installation ```bash pip install claude-agent-sdk ``` **Prerequisites:** - Python 3.10+ - Node.js - Claude Code: `npm install -g @anthropic-ai/claude-code` ``` -------------------------------- ### Quick Start: Basic Query with Claude Agent SDK Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md A simple asynchronous Python script demonstrating how to perform a basic query to Claude Code using the `query` function and `anyio` for running the async main function. ```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) ``` -------------------------------- ### Install Claude Agent SDK for Python Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md Installs the Claude Agent SDK for Python using pip. Ensure you have Python 3.10+ and Node.js, and Claude Code installed globally. ```bash pip install claude-agent-sdk ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/e2e-tests/README.md Installs the necessary development dependencies for running the end-to-end tests using pip. This includes the SDK and any testing utilities. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Migration from External Servers to SDK MCP Servers Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md Provides a code example illustrating the migration from using external MCP servers to the more streamlined in-process SDK MCP servers. ```APIDOC ### 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) 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} ) ``` ``` -------------------------------- ### Implement PreToolUse Hook for Bash Command Security in Python Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md This example demonstrates how to implement a 'PreToolUse' hook to intercept and validate bash commands before they are executed by the Claude SDK client. It defines a function `check_bash_command` that denies commands containing specific forbidden patterns. This is useful for enhancing security by preventing the execution of potentially harmful scripts. ```python 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( allowed_tools=["Bash"], hooks={ "PreToolUse": [ HookMatcher(matcher="Bash", hooks=[check_bash_command]), ], } ) async with ClaudeSDKClient(options=options) as client: # Test 1: Command with forbidden pattern (will be blocked) await client.query("Run the bash command: ./foo.sh --help") async for msg in client.receive_response(): print(msg) print("\n" + "=" * 50 + "\n") # Test 2: Safe command that should work await client.query("Run the bash command: echo 'Hello from hooks example!'") async for msg in client.receive_response(): print(msg) ``` -------------------------------- ### Basic Query with Options in Claude Agent SDK Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md Demonstrates making a simple query and a query with custom options, including system prompts and max turns, using the `query` function from the Claude Agent SDK. ```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 with query() Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md Demonstrates how to enable and use tools like 'Read', 'Write', and 'Bash' within the `query()` function, including setting permission modes for file edits. ```APIDOC ## Using Tools ```python options = ClaudeAgentOptions( allowed_tools=["Read", "Write", "Bash"], 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 ``` ``` -------------------------------- ### Create and Use In-Process SDK MCP Server for Custom Tools Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md Defines a custom tool (`greet_user`) using the `@tool` decorator and creates an in-process SDK MCP server. This server is then used with `ClaudeSDKClient` to allow Claude to invoke the custom 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 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) ``` -------------------------------- ### Using Tools with Claude Agent SDK Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md Shows how to configure Claude Agent SDK options to allow specific tools (Read, Write, Bash) and set permission modes for accepting file edits during queries. ```python options = ClaudeAgentOptions( allowed_tools=["Read", "Write", "Bash"], 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 ``` -------------------------------- ### Migrate from External to SDK MCP Server Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md Compares the configuration for using external MCP servers (separate processes) with the simpler, in-process configuration for SDK MCP servers in Claude Agent SDK. ```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) 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} ) ``` -------------------------------- ### Setting Working Directory with query() Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md Shows how to specify the working directory for Claude Code operations using the `cwd` option in `ClaudeAgentOptions`. ```APIDOC ## Working Directory ```python from pathlib import Path options = ClaudeAgentOptions( cwd="/path/to/project" # or Path("/path/to/project") ) ``` ``` -------------------------------- ### Setting Working Directory with Claude Agent SDK Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md Illustrates how to specify a working directory for Claude Agent SDK queries using either a string path or a Path object. ```python from pathlib import Path options = ClaudeAgentOptions( cwd="/path/to/project" # or Path("/path/to/project") ) ``` -------------------------------- ### Mixed Server Support Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md Demonstrates how to configure `ClaudeAgentOptions` to use both in-process SDK MCP servers and external subprocess MCP servers simultaneously. ```APIDOC ### Mixed Server Support You can use both SDK and external MCP servers together: ```python options = ClaudeAgentOptions( mcp_servers={ "internal": sdk_server, # In-process SDK server "external": { # External subprocess server "type": "stdio", "command": "external-server" } } ) ``` ``` -------------------------------- ### Troubleshooting: Set API Key Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/e2e-tests/README.md Provides the command to set the ANTHROPIC_API_KEY environment variable if encountered an error related to its absence. ```bash export ANTHROPIC_API_KEY=sk-ant-... ``` -------------------------------- ### Run Specific Test File with Pytest Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/CLAUDE.md This command demonstrates how to run tests from a specific file, 'test_client.py', located in the 'tests/' directory using Pytest. This is useful for targeted testing. ```bash python -m pytest tests/test_client.py ``` -------------------------------- ### Benefits of In-Process SDK MCP Servers Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md Highlights the advantages of using in-process SDK MCP servers, including no subprocess management, better performance, simpler deployment, easier debugging, and type safety. ```APIDOC ### 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 ``` -------------------------------- ### Mixed MCP Server Support in Claude Agent SDK Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md Demonstrates how to configure Claude Agent SDK options to use both in-process SDK MCP servers and external subprocess-based MCP servers simultaneously. ```python options = ClaudeAgentOptions( mcp_servers={ "internal": sdk_server, # In-process SDK server "external": { # External subprocess server "type": "stdio", "command": "external-server" } } ) ``` -------------------------------- ### Hooks with ClaudeSDKClient Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md Explains the concept of hooks in the Claude Code application, which are Python functions invoked at specific points in the agent loop to provide deterministic processing and feedback. ```APIDOC ## 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 [Claude Code Hooks Reference](https://docs.anthropic.com/en/docs/claude-code/hooks). For more examples, see examples/hooks.py. ``` -------------------------------- ### Run All Project Tests with Pytest Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/CLAUDE.md This snippet shows the command to execute all tests within the 'tests/' directory using the Pytest framework. Pytest is a popular testing framework for Python. ```bash python -m pytest tests/ ``` -------------------------------- ### Custom Tools with ClaudeSDKClient Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md Implement custom tools as in-process SDK MCP servers within your Python application. This offers better performance and simpler deployment compared to external MCP servers. ```APIDOC ## 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 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) ``` ``` -------------------------------- ### Lint and Style Code with Ruff Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/CLAUDE.md This snippet demonstrates how to use Ruff for linting and automatically fixing code style issues in the project's source and test files. Ruff is a fast Python linter and formatter. ```bash python -m ruff check src/ tests/ --fix python -m ruff format src/ tests/ ``` -------------------------------- ### ClaudeSDKClient Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md The `ClaudeSDKClient` class enables bidirectional, interactive conversations with Claude Code, supporting custom tools and hooks for more advanced interactions. ```APIDOC ## 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. ``` -------------------------------- ### Set Anthropic API Key Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/e2e-tests/README.md Sets the ANTHROPIC_API_KEY environment variable required for the end-to-end tests. This is a mandatory step before running any tests. ```bash export ANTHROPIC_API_KEY="your-api-key-here" ``` -------------------------------- ### Run All End-to-End Tests Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/e2e-tests/README.md Executes all end-to-end tests using the pytest framework. The '-v' flag provides verbose output during test execution. ```bash python -m pytest e2e-tests/ -v ``` -------------------------------- ### Run a Specific End-to-End Test Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/e2e-tests/README.md Executes a single, specific end-to-end test file and test case using pytest. Replace 'test_mcp_calculator.py' and 'test_basic_addition' with the desired test. ```bash python -m pytest e2e-tests/test_mcp_calculator.py::test_basic_addition -v ``` -------------------------------- ### Basic Usage: query() Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md The `query()` function is an asynchronous function for querying Claude Code, returning an iterator of response messages. It can be used with simple prompts or with advanced options like system prompts and max turns. ```APIDOC ## Basic Usage: query() `query()` is an async function for querying Claude Code. It returns an `AsyncIterator` of response messages. ### Simple query ```python from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, TextBlock 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 ```python 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) ``` ``` -------------------------------- ### Handle Claude SDK Errors in Python Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/README.md This Python snippet illustrates how to handle various exceptions that can be raised by the Claude SDK client. It includes specific error types like `CLINotFoundError`, `CLIConnectionError`, `ProcessError`, and `CLIJSONDecodeError`, providing basic error messages for each. Proper error handling is crucial for robust application development. ```python from claude_agent_sdk import ( ClaudeSDKError, # Base error CLINotFoundError, # Claude Code not installed CLIConnectionError, # Connection issues ProcessError, # Process failed CLIJSONDecodeError, # JSON parsing issues ) try: async for message in query(prompt="Hello"): pass except CLINotFoundError: print("Please install Claude Code") except ProcessError as e: print(f"Process failed with exit code: {e.exit_code}") except CLIJSONDecodeError as e: print(f"Failed to parse response: {e}") ``` -------------------------------- ### Typecheck Source Code with Mypy Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/CLAUDE.md This command utilizes Mypy to perform static type checking specifically on the source code files within the 'src/' directory. Mypy helps catch type errors before runtime. ```bash python -m mypy src/ ``` -------------------------------- ### Run End-to-End Tests with 'e2e' Marker Source: https://github.com/anthropics/claude-code-sdk-python/blob/main/e2e-tests/README.md Runs only the end-to-end tests marked with the 'e2e' marker using pytest. This is useful for isolating specific test categories. ```bash python -m pytest e2e-tests/ -v -m e2e ```