Claude Agent SDK Python开发指南:从安装部署到安全工具开发
AIAI Summary (BLUF)
本文档全面介绍Claude Agent SDK Python版的安装、基础使用、自定义工具开发(基于进程内MCP服务器)、安全钩子实现、错误处理及部署流程。重点通过权限控制、工具限制与自动化监控钩子强化安全性,并详述从外部MCP服务器迁移至更安全的进程内实现路径。
概述
Claude Agent SDK for Python 为开发者提供了一个强大的接口,用于将 Claude Code 的能力直接集成到他们的 Python 应用程序中。它支持与 Claude 的程序化交互,涵盖从简单查询到具有自定义工具和钩子的复杂、有状态对话的所有场景。该 SDK 抽象了底层的 CLI 通信,提供了一个简洁的异步 Python API。
安装与先决条件
安装
To install the SDK, use pip:
pip install claude-agent-sdk
使用 pip 安装 SDK:
系统要求
Prerequisites:
- Python 3.10+
先决条件:
- Python 3.10+
注意: Claude Code CLI 已自动捆绑在软件包中。SDK 默认使用此捆绑的 CLI。对于高级用例,您可以:
- 单独安装 Claude Code:
curl -fsSL https://claude.ai/install.sh | bash - 通过
ClaudeAgentOptions(cli_path="/path/to/claude")指定自定义 CLI 路径。
快速入门
基本查询
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)
使用 SDK 最简单的方式是 query() 函数。它是一个异步函数,返回响应消息的 AsyncIterator。
使用配置选项
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, TextBlock
# Simple query with message processing
async for message in query(prompt="Hello Claude"):
if isinstance(message, AssistantMessage):
for block in message.content:
if isinstance(block, TextBlock):
print(block.text)
# Query with custom 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)
您可以使用 ClaudeAgentOptions 自定义交互。
启用工具
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 here
pass
Claude 可以使用文件操作和 shell 命令等工具与您的系统交互。
设置工作目录
from pathlib import Path
options = ClaudeAgentOptions(
cwd="/path/to/project" # Can also use Path("/path/to/project")
)
为文件操作指定工作目录。
高级用法:ClaudeSDKClient
对于更复杂、交互式的对话,请使用 ClaudeSDKClient。与 query() 不同,它支持双向通信、自定义工具和钩子。
自定义工具(进程内 MCP 服务器)
自定义工具是 Claude 可以调用的 Python 函数。它们作为进程内 MCP 服务器在您的应用程序中运行,与外部服务器相比,提供了更好的性能和更简单的部署。
创建简单工具
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")
async for msg in client.receive_response():
print(msg)
- 使用
@tool装饰器定义工具 - 创建 SDK MCP 服务器
- 在
ClaudeAgentOptions中配置服务器和允许的工具 - 使用
ClaudeSDKClient进行交互
进程内服务器的优势
从外部服务器迁移
# 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}
)
迁移到进程内服务器可以简化架构并提升性能。
混合服务器支持
options = ClaudeAgentOptions(
mcp_servers={
"internal": sdk_server, # In-process SDK server
"external": { # External subprocess server
"type": "stdio",
"command": "external-server"
}
}
)
您可以同时使用 SDK(进程内)和外部 MCP 服务器。
钩子 (Hooks)
钩子是 Claude Code 应用程序在智能体循环的特定点调用的 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)
此示例展示了如何使用 PreToolUse 钩子来阻止特定的 Bash 命令。
错误处理
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}")
SDK 为不同的错误场景提供了特定的异常类型。
类型系统
可用工具与示例
- Examples:
从旧版本迁移
如果从 Claude Code SDK(版本 < 0.1.0)升级,请注意以下关键变更。有关完整的迁移详情,请参阅 CHANGELOG.md。
开发与构建
开发设置
./scripts/initial-setup.sh
贡献者应运行初始设置脚本以安装 git 钩子。这会安装一个运行 lint 检查的 pre-push 钩子。使用 git push --no-verify 可临时跳过。
本地构建 Wheel
# Install build dependencies
pip install build twine
# Build wheel with bundled CLI
python scripts/build_wheel.py
# Build with specific versions
python scripts/build_wheel.py --version 0.1.4 --cli-version 2.0.0
# Clean bundled CLI after building
python scripts/build_wheel.py --clean
要构建包含捆绑 Claude Code CLI 的 wheel,请使用提供的脚本。构建脚本会为您的平台下载 CLI,将其捆绑,并构建 wheel 和源代码分发版。
发布流程
软件包通过 GitHub Actions 发布到 PyPI。该工作流跟踪软件包版本和捆绑的 CLI 版本,允许独立更新。
许可证与条款
本 SDK 的使用受 Anthropic 商业服务条款约束,包括当您用它为您自己的客户和最终用户提供产品和服务时。有关任何不同的条款,请参阅各个组件的 LICENSE 文件。
版权与免责声明:本文仅用于信息分享与交流,不构成任何形式的法律、投资、医疗或其他专业建议,也不构成对任何结果的承诺或保证。
文中提及的商标、品牌、Logo、产品名称及相关图片/素材,其权利归各自合法权利人所有。本站内容可能基于公开资料整理,亦可能使用 AI 辅助生成或润色;我们尽力确保准确与合规,但不保证完整性、时效性与适用性,请读者自行甄别并以官方信息为准。
若本文内容或素材涉嫌侵权、隐私不当或存在错误,请相关权利人/当事人联系本站,我们将及时核实并采取删除、修正或下架等处理措施。也请勿在评论或联系信息中提交身份证号、手机号、住址等个人敏感信息。



