Claude Agent SDK
The Claude Agent SDK provides a Python interface for interacting with Claude's agent capabilities, allowing developers to define tools, manage sessions, and build conversational agents. It bundles the Claude CLI and runs it as a subprocess. The current version is 0.1.56, and releases are frequent, often weekly, bundling updates to the underlying Claude CLI.
Warnings
- breaking The `claude-agent-sdk` requires Python 3.10 or newer. Installing or running with older Python versions (e.g., 3.9) will result in compatibility errors.
- gotcha Large tool results (e.g., >50K characters) might be silently truncated in versions prior to 0.1.55 due to a bug in how `ToolAnnotations` were processed, potentially leading to incomplete data being processed by the agent.
- gotcha When using `client.query()` with a string prompt and many tool calls (especially with hooks/MCP servers), versions prior to 0.1.53 could encounter a deadlock, causing the application to hang.
- gotcha Fine-grained tool streaming (`include_partial_messages=True`) was not reliably delivering `input_json_delta` events for versions 0.1.36 through 0.1.47 without a specific server-side feature flag being enabled, leading to a degraded streaming experience.
- gotcha Authentication requires either the `ANTHROPIC_API_KEY` or `CLAUDE_CODE_TOKEN` environment variable to be set, or passed explicitly as `api_key` to `ClaudeSDKClient`. Forgetting this will lead to authentication failures.
Install
-
pip install claude-agent-sdk
Imports
- ClaudeSDKClient
from claude_agent_sdk import ClaudeSDKClient
- tool
from claude_agent_sdk import tool
- create_sdk_mcp_server
from claude_agent_sdk import create_sdk_mcp_server
Quickstart
import os
from claude_agent_sdk import ClaudeSDKClient, tool
# Set your API key as an environment variable or replace 'YOUR_ANTHROPIC_API_KEY'
# CLAUDE_CODE_TOKEN is also supported for authentication.
ANTHROPIC_API_KEY = os.environ.get('ANTHROPIC_API_KEY', 'YOUR_ANTHROPIC_API_KEY')
@tool
def get_current_weather(location: str) -> str:
"""Gets the current weather for a given location."""
if location == "San Francisco":
return "Sunny, 70F"
return "Cloudy, 50F"
async def main():
if ANTHROPIC_API_KEY == 'YOUR_ANTHROPIC_API_KEY':
print("Please set the ANTHROPIC_API_KEY environment variable or replace the placeholder.")
return
client = ClaudeSDKClient(api_key=ANTHROPIC_API_KEY)
try:
response = await client.query(
"What's the weather like in San Francisco?",
tools=[get_current_weather]
)
print(f"Agent response: {response.response}")
if response.tool_calls:
for call in response.tool_calls:
print(f"Tool call: {call.tool_name}({call.input_json})")
if response.messages:
for message in response.messages:
if hasattr(message, 'text'):
print(f"Message: {message.text}")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == '__main__':
import asyncio
asyncio.run(main())