概述
claude-code-sdk-python 是一个专为 Claude Agent 设计的 Python 开发工具包(SDK),允许开发者轻松地与 Claude AI 助手集成,构建强大的 AI 应用程序。本指南将从基础安装到高级自定义工具开发,全面介绍该 SDK 的使用方法。
安装与环境准备
系统要求
- Python 3.10+
- Node.js
- Claude Code 2.0.0+
本文介绍了 claude-code-sdk-python 的使用指南。涵盖环境准备、基础查询、内置工具启用与权限控制、自定义工具开发(MCP 服务器)、错误处理及流模式等核心功能。通过示例代码展示了如何集成 Claude AI 助手构建应用程序,适合 Python 开发者快速上手。
claude-code-sdk-python 是一个专为 Claude Agent 设计的 Python 开发工具包(SDK),允许开发者轻松地与 Claude AI 助手集成,构建强大的 AI 应用程序。本指南将从基础安装到高级自定义工具开发,全面介绍该 SDK 的使用方法。
首先,通过 pip 安装 SDK:
pip install claude-agent-sdk
然后安装 Claude Code:
npm install -g @anthropic-ai/claude-code
以下是一个简单的使用示例,演示如何向 Claude 发送查询并获取响应:
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)
您可以通过 ClaudeAgentOptions 类自定义查询行为:
from claude_agent_sdk import query, ClaudeAgentOptions
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)
query() 函数是 SDK 的核心,用于向 Claude 发送查询。它返回一个异步迭代器,您可以通过它获取响应消息流。
ClaudeSDKClient 支持与 Claude Code 进行双向交互对话,相比基本的 query() 函数,它提供了更多高级功能,如自定义工具和钩子。
要使用 Claude 的内置工具,需要在选项中指定允许的工具:
options = ClaudeAgentOptions(
allowed_tools=["Read", "Write", "Bash"],
permission_mode='acceptEdits' # 自动接受文件编辑
)
async for message in query(
prompt="Create a hello.py file",
options=options
):
# 处理工具使用和结果
pass
您可以通过钩子(Hooks)实现对工具使用的细粒度控制,例如阻止特定命令执行:
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]),
],
}
)
claude-code-sdk-python 允许您创建自定义工具,这些工具作为进程内 MCP 服务器运行,无需单独的进程。这提供了更好的性能和更简单的部署方式。
以下是创建自定义工具的基本步骤:
@tool 装饰器定义工具函数create_sdk_mcp_server 创建 MCP 服务器from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions, ClaudeSDKClient
# 使用@tool 装饰器定义工具
@tool("greet", "Greet a user", {"name": str})
async def greet_user(args):
return {
"content": [
{"type": "text", "text": f"Hello, {args['name']}!"}
]
}
# 创建 SDK MCP 服务器
server = create_sdk_mcp_server(
name="my-tools",
version="1.0.0",
tools=[greet_user]
)
# 在客户端中使用
options = ClaudeAgentOptions(
mcp_servers={"tools": server},
allowed_tools=["mcp__tools__greet"]
)
async with ClaudeSDKClient(options=options) as client:
await client.query("Greet Alice")
async for msg in client.receive_response():
print(msg)
下面是一个完整的计算器工具集实现,包含加、减、乘、除等基本运算:
# 定义计算器工具
@tool("add", "Add two numbers", {"a": float, "b": float})
async def add_numbers(args: dict[str, Any]) -> dict[str, Any]:
result = args["a"] + args["b"]
return {
"content": [{"type": "text", "text": f"{args['a']} + {args['b']} = {result}"}]
}
@tool("subtract", "Subtract one number from another", {"a": float, "b": float})
async def subtract_numbers(args: dict[str, Any]) -> dict[str, Any]:
result = args["a"] - args["b"]
return {
"content": [{"type": "text", "text": f"{args['a']} - {args['b']} = {result}"}]
}
# 更多工具定义...
# 创建计算器服务器
calculator = create_sdk_mcp_server(
name="calculator",
tools=[add_numbers, subtract_numbers, multiply_numbers, divide_numbers, square_root, power]
)
# 使用计算器工具
options = ClaudeAgentOptions(
mcp_servers={"calc": calculator},
allowed_tools=[
"mcp__calc__add",
"mcp__calc__subtract",
"mcp__calc__multiply",
"mcp__calc__divide",
"mcp__calc__sqrt",
"mcp__calc__power",
],
)
SDK 提供了多种异常类型,帮助您处理不同的错误场景:
from claude_agent_sdk import (
ClaudeSDKError, # 基础错误
CLINotFoundError, # Claude Code 未安装
CLIConnectionError, # 连接问题
ProcessError, # 进程失败
CLIJSONDecodeError, # JSON 解析问题
)
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}")
SDK 支持流模式,允许您实时处理 Claude 的响应:
async with ClaudeSDKClient(options=options) as client:
await client.query("Tell me a story")
async for message in client.receive_response():
# 实时处理消息
print(message)
您可以同时使用进程内 SDK MCP 服务器和外部 MCP 服务器:
options = ClaudeAgentOptions(
mcp_servers={
"internal": sdk_server, # 进程内 SDK 服务器
"external": { # 外部子进程服务器
"type": "stdio",
"command": "external-server"
}
}
)
SDK 提供了完整的类型定义,帮助您编写类型安全的代码。主要类型包括:
ClaudeAgentOptions - 配置选项AssistantMessage, UserMessage, SystemMessage, ResultMessage - 消息类型TextBlock, ToolUseBlock, ToolResultBlock - 内容块如果您正在从 Claude Code SDK(版本<0.1.0)升级,请参考 CHANGELOG.md 了解重大变更和新功能,包括:
ClaudeCodeOptions 重命名为 ClaudeAgentOptionsclaude-code-sdk-python 为开发者提供了与 Claude AI 助手交互的强大工具。通过本指南,您已经了解了从基础安装到高级自定义工具开发的全部内容。无论是构建简单的查询应用,还是开发复杂的自定义工具,claude-code-sdk-python 都能满足您的需求。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML 转 Markdown 互为补充。 在线工具,Markdown 转 HTML在线工具,online