关于 claude-agent-sdk
Claude Agent SDK 是用于构建 Agent 的 Python 和 TypeScript SDK,提供 Claude Code 的文件操作、命令执行和网页搜索等工具。它支持单次查询与持续会话,并可配置自定义工具、钩子、权限和子 Agent。
主要功能
- 01单次与持续查询模式
- 02文件、命令行和网页工具
- 03自定义工具与钩子
- 04工具权限控制
- 05创建子 Agent
- 06Python 与 TypeScript SDK
适用场景
- 01自动执行单次文件或编码任务
- 02构建支持后续交互的会话 Agent
- 03创建只读代码审查 Agent
- 04使用网页工具开展研究
MCP 相关
Agent 可将 MCP 服务作为自定义工具使用。SDK 支持在 Agent 配置中添加 MCP 服务。
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ tdimino/ claude-code-minoan --skill claude-agent-sdk安装后在 Claude Code 中输入/claude-agent-sdk确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
README.mdreferences/best-practices.mdbrowser-control.mdbuilt-in-tools.mdcustom-tools.mdhooks.mdmessage-types.mdpermissions.mdpython-sdk.mdsubagents.mdtroubleshooting.mdtemplates/agent-with-tracking-python.pycontinuous-chat-python.pycustom-tool-python.pyhook-example-python.pyresearch-agent-python.pysession-api-typescript.tssimple-agent-python.pyworkflows/add-custom-tools.mdadd-hooks.mdcreate-agent.md详细介绍
<essential_principles>
Claude Agent SDK 概览
Claude Agent SDK 为 Agent 提供与 Claude Code 相同的工具: 文件操作、bash 命令、网页搜索等。构建自主 Agent, 让它们读取文件、运行命令、搜索网页、编辑代码并验证工作成果。
两种查询方式
| 函数 | 会话 | 适用场景 |
|---|---|---|
query() | 每次新建 | 一次性任务、自动化 |
ClaudeSDKClient | 持续 | 对话、后续跟进、钩子 |
主要区别: query() 更简单,但不支持钩子、中断或
自定义工具。要使用高级功能,请使用 ClaudeSDKClient。
Agent 循环模式
Agent 通过反馈循环运行:
gather context → take action → verify work → repeat
安装
Python:
uv add claude-agent-sdk
TypeScript:
npm install @anthropic-ai/claude-agent-sdk
要求:
- 已安装 Claude Code CLI(
npm install -g @anthropic-ai/claude-code) - 已设置
ANTHROPIC_API_KEY环境变量
快速开始
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
async for message in query(
prompt="Find and fix bugs in auth.py",
options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"])
):
print(message)
asyncio.run(main())
</essential_principles>
您想做什么?
- 创建新 Agent - 从头开始构建 Agent
- 添加自定义工具 - 使用 @tool 装饰器或 MCP 服务创建工具
- 添加钩子 - 拦截工具调用,以便记录日志、验证或修改
- 配置权限 - 控制工具可以执行的操作
- 创建子 Agent - 定义可并行工作的专用 Agent
- 控制浏览器 - Chrome 扩展、dev-browser 技能
- 查看 API 参考 - Python 或 TypeScript SDK 详情
继续前请等待回复。
| 回复 | 加载 |
|---|---|
| 1、"create"、"new"、"build" | workflows/create-agent.md |
| 2、"tools"、"custom"、"@tool" | references/custom-tools.md |
| 3、"hooks"、"intercept" | references/hooks.md |
| 4、"permissions"、"can_use_tool" | references/permissions.md |
| 5、"subagent"、"parallel" | references/subagents.md |
| 6、"browser"、"chrome"、"automation" | references/browser-control.md |
| 7、"python"、"reference" | references/python-sdk.md |
| 7、"typescript"、"reference" | references/typescript-sdk.md |
| "built-in"、"tools" | references/built-in-tools.md |
| "message"、"types" | references/message-types.md |
| "best practices"、"patterns" | references/best-practices.md |
| "error"、"troubleshoot" | references/troubleshooting.md |
<quick_reference>
ClaudeAgentOptions(关键字段)
ClaudeAgentOptions(
# Tools
allowed_tools=["Read", "Write", "Bash"], # Built-in tools to enable
disallowed_tools=["WebSearch"], # Tools to block
# Prompts
system_prompt="You are...", # Custom system prompt
# Or use preset: {"type": "preset", "preset": "claude_code", "append": "..."}
# MCP Servers
mcp_servers={"calc": my_server}, # MCP server configs
# Permissions
permission_mode="acceptEdits", # default | acceptEdits | plan | bypassPermissions
can_use_tool=my_handler, # Custom permission callback
# Execution
cwd="/path/to/project", # Working directory
max_turns=10, # Limit iterations
env={"API_KEY": "..."}, # Environment variables
# Advanced
hooks={"PreToolUse": [...]}, # Behavior hooks
agents={"researcher": AgentDef(...)}, # Subagents
sandbox={"enabled": True}, # Sandbox settings
setting_sources=["project"], # Load .claude settings
)
内置工具
| 工具 | 用途 |
|---|---|
| Read | 读取文件(文本、图像、PDF、笔记本) |
| Write | 创建新文件 |
| Edit | 通过搜索/替换修改现有文件 |
| Bash | 运行终端命令 |
| Glob | 按模式查找文件(**/*.ts) |
| Grep | 使用正则表达式搜索文件内容 |
| WebSearch | 搜索网页 |
| WebFetch | 获取并解析网页 |
| Task | 启动子 Agent |
| NotebookEdit | 编辑 Jupyter 笔记本 |
| TodoWrite | 管理任务列表 |
| KillShell | 终止后台 shell |
| ExitPlanMode | 退出规划模式 |
消息类型
# All messages
Message = UserMessage | AssistantMessage | SystemMessage | ResultMessage
# Content blocks in AssistantMessage
ContentBlock = TextBlock | ThinkingBlock | ToolUseBlock | ToolResultBlock
错误类型
from claude_agent_sdk import (
CLINotFoundError, # Claude Code CLI not installed
CLIConnectionError, # Connection failed
ProcessError, # CLI process failed
CLIJSONDecodeError, # JSON parsing failed
)
</quick_reference>
<thinking_config>
思考与投入程度配置
通过 effort 参数控制 Agent 的思考深度,而不是在提示词层级添加“仔细思考”之类的指令:
| 使用场景 | 投入程度 | 说明 |
|---|---|---|
| 快速查询、简单编辑 | low | 思考开销极小 |
| 常规开发 | medium | 大多数 Agent 的默认值 |
| 复杂架构、安全 | high | 更深入的推理 |
| 深度研究、长期任务 | max | 最大思考预算 |
# Adaptive thinking (recommended for Claude 4.6)
options = ClaudeAgentOptions(
model="claude-opus-4-6", # or claude-sonnet-4-6
# Effort is controlled at the API level, not in the agent options
)
避免在 Agent 系统提示词中添加“仔细思考”或“务必全面”之类的内容——Claude 4.6 会根据任务复杂度自动调整思考深度。
</thinking_config>
常见模式
文件操作 Agent
options = ClaudeAgentOptions(
allowed_tools=["Read", "Write", "Edit", "Glob", "Grep"],
permission_mode="acceptEdits",
cwd="/path/to/project"
)
代码审查 Agent
options = ClaudeAgentOptions(
allowed_tools=["Read", "Glob", "Grep"], # Read-only
system_prompt="Review code for bugs, security issues, and style"
)
研究 Agent
options = ClaudeAgentOptions(
allowed_tools=["WebSearch", "WebFetch", "Write"],
max_turns=20 # Allow more iterations for research
)
使用工具的交互式聊天
async with ClaudeSDKClient(options) as client:
await client.query("What files are in this directory?")
async for msg in client.receive_response():
print(msg)
# Follow-up - Claude remembers context
await client.query("Show me the largest one")
async for msg in client.receive_response():
print(msg)
评论
支持 Markdown