Claude Agent SDK Python开发指南:从安装部署到安全工具开发
This technical guide provides comprehensive documentation for the Claude Agent SDK for Python, covering installation, basic usage, custom tool development with in-process MCP servers, security hooks implementation, error handling, and deployment workflows. It emphasizes security considerations through permission controls, tool restrictions, and automated monitoring hooks while detailing migration paths from external MCP servers to more secure in-process implementations. (本文档全面介绍Claude Agent SDK Python版的安装、基础使用、自定义工具开发、安全钩子实现、错误处理和部署流程。重点通过权限控制、工具限制和自动化监控钩子强调安全考量,并详细说明从外部MCP服务器迁移到更安全的进程内实现的路径。)
概述
The Claude Agent SDK用于与Claude Code交互的Python软件开发工具包,支持异步查询、自定义工具开发和安全监控功能。 for Python provides a powerful interface for developers to integrate Claude Code's capabilities directly into their Python applications. It enables programmatic interaction with Claude, supporting everything from simple queries to complex, stateful conversations with custom tools and hooks. This SDK abstracts the underlying CLI communication, offering a clean, asynchronous Python API.
Claude Agent SDK用于与Claude Code交互的Python软件开发工具包,支持异步查询、自定义工具开发和安全监控功能。 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+
Note: The Claude Code CLI is automatically bundled with the package. The SDK uses this bundled CLI by default. For advanced use cases, you can:
- Install Claude Code separately:
curl -fsSL https://claude.ai/install.sh | bash - Specify a custom CLI path via
ClaudeAgentOptions(cli_path="/path/to/claude")
先决条件:
- 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 路径。
快速入门
基本查询
The simplest way to use the SDK is the query() function. It's an asynchronous function that returns an AsyncIterator of response messages.
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。
使用配置选项
You can customize the interaction using ClaudeAgentOptions.
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自定义交互。
启用工具
Claude can interact with your system using tools like file operations and shell commands.
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 命令等工具与您的系统交互。
设置工作目录
Specify the working directory for file operations.
from pathlib import Path
options = ClaudeAgentOptions(
cwd="/path/to/project" # Can also use Path("/path/to/project")
)
为文件操作指定工作目录。
高级用法:ClaudeSDKClient
For more complex, interactive conversations, use ClaudeSDKClient. Unlike query(), it supports bidirectional communication, custom tools, and hooks.
对于更复杂、交互式的对话,请使用
ClaudeSDKClient。与query()不同,它支持双向通信、自定义工具和钩子。
自定义工具(进程内 MCP 服务器)
Custom tools are Python functions that Claude can invoke. They run as in-process MCP servers within your application, offering better performance and simpler deployment than external servers.
自定义工具是 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进行交互
进程内服务器的优势
- No subprocess management - Runs in the same process as your application (无需子进程管理 - 在与您的应用程序相同的进程中运行)
- Better performance - No IPC overhead for tool calls (更好的性能 - 工具调用无 IPC 开销)
- Simpler deployment - Single Python process instead of multiple (更简单的部署 - 单个 Python 进程而非多个)
- Easier debugging - All code runs in the same process (更易于调试 - 所有代码在同一进程中运行)
- Type safety - Direct Python function calls with type hints (类型安全 - 直接调用带有类型提示的 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}
)
迁移到进程内服务器可以简化架构并提升性能。
混合服务器支持
You can use both SDK (in-process) and external MCP servers together.
options = ClaudeAgentOptions(
mcp_servers={
"internal": sdk_server, # In-process SDK server
"external": { # External subprocess server
"type": "stdio",
"command": "external-server"
}
}
)
您可以同时使用 SDK(进程内)和外部 MCP 服务器。
钩子 (Hooks)
Hooks are Python functions that the Claude Code application invokes at specific points in the agent loop. They enable deterministic processing and automated feedback.
钩子是 Claude Code 应用程序在智能体循环的特定点调用的 Python 函数。它们支持确定性处理和自动反馈。
钩子示例:安全检查
This example shows how to use a PreToolUse hook to block specific Bash commands.
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 命令。
错误处理
The SDK provides specific exception types for different error scenarios.
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 为不同的错误场景提供了特定的异常类型。
类型系统
Key types are defined in src/claude_agent_sdk/types.py:
ClaudeAgentOptions- Configuration options (ClaudeAgentOptions- 配置选项)AssistantMessage,UserMessage,SystemMessage,ResultMessage- Message types (AssistantMessage,UserMessage,SystemMessage,ResultMessage- 消息类型)TextBlock,ToolUseBlock,ToolResultBlock- Content blocks (TextBlock,ToolUseBlock,ToolResultBlock- 内容块)
可用工具与示例
- Available Tools: See the official Claude Code documentation for a complete list. (可用工具:请参阅官方 Claude Code 文档获取完整列表。)
- Examples:
examples/quick_start.py- Basic usage example (examples/quick_start.py- 基本用法示例)examples/streaming_mode.py- ComprehensiveClaudeSDKClientexamples (examples/streaming_mode.py- 全面的ClaudeSDKClient示例)examples/streaming_mode_ipython.py- Interactive IPython examples (examples/streaming_mode_ipython.py- 交互式 IPython 示例)
从旧版本迁移
If upgrading from Claude Code SDK (versions < 0.1.0), note these key changes:
ClaudeCodeOptionsrenamed toClaudeAgentOptions(ClaudeCodeOptions重命名为ClaudeAgentOptions)- Merged system prompt configuration (合并了系统提示配置)
- Settings isolation and explicit control (设置隔离和显式控制)
- New programmatic subagents and session forking features (新的程序化子智能体和会话分叉功能)
Refer to CHANGELOG.md for complete migration details.
如果从 Claude Code SDK(版本 < 0.1.0)升级,请注意以下关键变更。有关完整的迁移详情,请参阅
CHANGELOG.md。
开发与构建
开发设置
Contributors should run the initial setup script to install git hooks:
./scripts/initial-setup.sh
This installs a pre-push hook that runs lint checks. Use git push --no-verify to skip temporarily.
贡献者应运行初始设置脚本以安装 git 钩子。这会安装一个运行 lint 检查的 pre-push 钩子。使用
git push --no-verify可临时跳过。
本地构建 Wheel
To build wheels with the bundled Claude Code CLI:
# 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
The build script downloads the CLI for your platform, bundles it, and builds both wheel and source distributions.
要构建包含捆绑 Claude Code CLI 的 wheel,请使用提供的脚本。构建脚本会为您的平台下载 CLI,将其捆绑,并构建 wheel 和源代码分发版。
发布流程
The package is published to PyPI via GitHub Actions. The workflow:
- Builds platform-specific wheels for macOS, Linux, and Windows (为 macOS、Linux 和 Windows 构建特定于平台的 wheel)
- Bundles the specified Claude Code CLI version (捆绑指定的 Claude Code CLI 版本)
- Publishes artifacts to PyPI (将构件发布到 PyPI)
- Creates a release branch with version updates (创建包含版本更新的发布分支)
- Opens a PR to
mainwith updated version files and CHANGELOG (向main分支发起包含更新版本文件和 CHANGELOG 的 PR)
软件包通过 GitHub Actions 发布到 PyPI。该工作流跟踪软件包版本和捆绑的 CLI 版本,允许独立更新。
许可证与条款
Use of this SDK is governed by Anthropic's Commercial Terms of Service, including when used to power products and services for your own customers. Refer to individual component LICENSE files for any differing terms.
本 SDK 的使用受 Anthropic 商业服务条款约束,包括当您用它为您自己的客户和最终用户提供产品和服务时。有关任何不同的条款,请参阅各个组件的 LICENSE 文件。
版权与免责声明:本文仅用于信息分享与交流,不构成任何形式的法律、投资、医疗或其他专业建议,也不构成对任何结果的承诺或保证。
文中提及的商标、品牌、Logo、产品名称及相关图片/素材,其权利归各自合法权利人所有。本站内容可能基于公开资料整理,亦可能使用 AI 辅助生成或润色;我们尽力确保准确与合规,但不保证完整性、时效性与适用性,请读者自行甄别并以官方信息为准。
若本文内容或素材涉嫌侵权、隐私不当或存在错误,请相关权利人/当事人联系本站,我们将及时核实并采取删除、修正或下架等处理措施。 也请勿在评论或联系信息中提交身份证号、手机号、住址等个人敏感信息。