agent-builder
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAgent Builder - Claude SDK & CLI Expert
Agent构建器 - Claude SDK与CLI专家
Triggers:
- "build agent", "create agent", "agent sdk", "claude sdk"
- "headless mode", "programmatic", "cli command"
- "claude -p", "query programmatically"
- "custom tools", "mcp server", "sdk mcp"
- "claude code api", "agent options"
触发词:
- "build agent", "create agent", "agent sdk", "claude sdk"
- "headless mode", "programmatic", "cli command"
- "claude -p", "query programmatically"
- "custom tools", "mcp server", "sdk mcp"
- "claude code api", "agent options"
Prefer Claude Code Headless Mode
优先选择Claude Code无头模式
This skill covers Claude Code's headless mode and the Agent SDK — not the raw Anthropic API.
text
Preferred: Claude Code CLI headless mode (claude -p)
Preferred: Claude Agent SDK (wraps Claude Code CLI)
Avoid: Raw Anthropic API (anthropic.Anthropic())
Avoid: Direct API calls with API keysWhy this matters:
- The Agent SDK wraps the Claude Code CLI — it does not use the raw Anthropic API
- Authentication comes from existing config — no API keys needed
~/.claude/ - All settings, MCP servers, and configuration inherit from your Claude Code setup
- You get Claude Code's full agent loop, tools, and context management
Rule: If code uses , , or requires , that is the wrong approach. Use or instead.
anthropic.Anthropic()anthropic.messages.create()ANTHROPIC_API_KEYclaude -pclaude_agent_sdk本技能涵盖Claude Code的无头模式和Agent SDK——不涉及原生Anthropic API。
text
优先选择:Claude Code CLI无头模式(claude -p)
优先选择:Claude Agent SDK(封装Claude Code CLI)
避免使用:原生Anthropic API(anthropic.Anthropic())
避免使用:需要API密钥的直接API调用重要原因:
- Agent SDK封装了Claude Code CLI——不使用原生Anthropic API
- 认证来自现有配置文件——无需API密钥
~/.claude/ - 所有设置、MCP服务器和配置均继承自你的Claude Code设置
- 你可获得Claude Code完整的Agent循环、工具和上下文管理能力
规则: 如果代码使用、或需要,则方法错误。请改用或。
anthropic.Anthropic()anthropic.messages.create()ANTHROPIC_API_KEYclaude -pclaude_agent_sdkCore Capabilities
核心功能
Build AI agents, run Claude Code programmatically, and execute CLI operations using:
- Claude Agent SDK Python - Programmatic agent creation with custom tools and hooks (wraps Claude Code CLI)
- Headless/Print Mode - Run Claude Code from CLI, scripts, CI/CD ()
claude -p - CLI Reference - All commands, flags, and configuration options
All of these use Claude Code's existing authentication from — no API keys required.
~/.claude/借助以下方式构建AI Agent、以编程方式运行Claude Code并执行CLI操作:
- Claude Agent SDK Python - 借助自定义工具和钩子以编程方式创建Agent(封装Claude Code CLI)
- 无头/打印模式 - 从CLI、脚本、CI/CD中运行Claude Code()
claude -p - CLI参考 - 所有命令、参数和配置选项
所有这些方式均使用Claude Code现有配置文件进行认证——无需API密钥。
~/.claude/Raw API vs Claude Code SDK Patterns
原生API与Claude Code SDK模式对比
Raw Anthropic API — do not use for agent automation
原生Anthropic API — 不用于Agent自动化
python
undefinedpython
undefinedAvoid — this is the raw Anthropic API, not Claude Code
避免使用——这是原生Anthropic API,非Claude Code
from anthropic import Anthropic
client = Anthropic(api_key="sk-...") # Requires separate API key
response = client.messages.create( # Bypasses agent loop
model="claude-sonnet-4-5",
messages=[{"role": "user", "content": "Hello"}]
)
**Problems:**
- Requires separate API key authentication
- Bypasses Claude Code's agent loop, tools, and context management
- No access to Read, Write, Bash tools
- No MCP server integration
- No session persistence or resumption
- Must handle tool calling manuallyfrom anthropic import Anthropic
client = Anthropic(api_key="sk-...") # 需要单独的API密钥
response = client.messages.create( # 绕过Agent循环
model="claude-sonnet-4-5",
messages=[{"role": "user", "content": "Hello"}]
)
**问题:**
- 需要单独的API密钥认证
- 绕过Claude Code的Agent循环、工具和上下文管理
- 无法访问Read、Write、Bash工具
- 无MCP服务器集成
- 无会话持久化或恢复功能
- 必须手动处理工具调用Claude Code Headless Mode — preferred
Claude Code无头模式 — 优先选择
python
undefinedpython
undefinedPreferred — Agent SDK wraps Claude Code CLI
优先选择——Agent SDK封装Claude Code CLI
from claude_agent_sdk import query, ClaudeAgentOptions
import anyio
async def main():
options = ClaudeAgentOptions(
allowed_tools=["Read", "Write", "Bash"], # Full tool access
permission_mode="acceptEdits"
)
# Uses ~/.claude/ config — no API key needed
async for message in query(prompt="Analyze this codebase", options=options):
print(message)
anyio.run(main)
**OR via CLI:**
```bashfrom claude_agent_sdk import query, ClaudeAgentOptions
import anyio
async def main():
options = ClaudeAgentOptions(
allowed_tools=["Read", "Write", "Bash"], # 完整工具访问权限
permission_mode="acceptEdits"
)
# 使用~/.claude/配置文件——无需API密钥
async for message in query(prompt="分析此代码库", options=options):
print(message)
anyio.run(main)
**或通过CLI:**
```bashClaude Code headless mode
Claude Code无头模式
claude -p "Analyze this codebase"
--allowedTools "Read,Write,Bash"
--output-format json
--allowedTools "Read,Write,Bash"
--output-format json
**Benefits:**
- Uses existing `~/.claude/` authentication
- Full Claude Code agent loop with all tools
- MCP server integration
- Session persistence and resumption
- Context management handled automatically
---claude -p "分析此代码库"
--allowedTools "Read,Write,Bash"
--output-format json
--allowedTools "Read,Write,Bash"
--output-format json
**优势:**
- 使用现有`~/.claude/`认证
- 具备完整Claude Code Agent循环及所有工具
- MCP服务器集成
- 会话持久化和恢复功能
- 自动处理上下文管理
---Documentation Sources
文档来源
Always fetch current documentation when needed:
- Agent SDK: https://github.com/anthropics/claude-agent-sdk-python
- Headless Mode: https://code.claude.com/docs/en/headless
- CLI Reference: https://code.claude.com/docs/en/cli-reference
必要时始终获取最新文档:
Workflow
工作流程
When invoked:
- Understand the requirement - What type of agent/automation is needed?
- Check dependencies - Verify Python version, packages, Claude Code installation
- Reference live docs - Fetch relevant documentation if details are unclear
- Build confidently - Write production-ready code with proper error handling
- Test immediately - Run and validate the implementation
调用本技能时:
- 理解需求 - 需要构建何种类型的Agent/自动化?
- 检查依赖 - 验证Python版本、包、Claude Code安装情况
- 参考实时文档 - 若细节不清晰,获取相关文档
- 放心构建 - 编写带有适当错误处理的生产级代码
- 立即测试 - 运行并验证实现效果
1. Agent SDK Python Patterns
1. Agent SDK Python模式
Installation & Setup
安装与设置
The Agent SDK wraps Claude Code CLI — it does not use the raw Anthropic API.
bash
undefinedAgent SDK封装Claude Code CLI——不使用原生Anthropic API。
bash
undefinedInstall Claude Code CLI first (if not already installed)
先安装Claude Code CLI(若未安装)
curl -fsSL https://claude.ai/install.sh | bash
curl -fsSL https://claude.ai/install.sh | bash
Install the Agent SDK (wraps Claude Code CLI)
安装Agent SDK(封装Claude Code CLI)
uv pip install claude-agent-sdk # Python 3.10+
**Authentication:** Uses existing `~/.claude/` config — no API keys needed.uv pip install claude-agent-sdk # Python 3.10+
**认证:** 使用现有`~/.claude/`配置文件——无需API密钥。Quick Start - Simple Query
快速入门 - 简单查询
This uses Claude Code CLI under the hood — not the raw Anthropic API.
python
import anyio
from claude_agent_sdk import query
async def main():
# Uses Claude Code CLI — inherits auth from ~/.claude/
async for message in query(prompt="What is 2 + 2?"):
print(message)
anyio.run(main)No API keys needed — authentication comes from your Claude Code installation.
底层使用Claude Code CLI——非原生Anthropic API。
python
import anyio
from claude_agent_sdk import query
async def main():
# 使用Claude Code CLI——从~/.claude/继承认证
async for message in query(prompt="2+2等于多少?"):
print(message)
anyio.run(main)无需API密钥 — 认证来自你的Claude Code安装配置。
Interactive Client
交互式客户端
python
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions
options = ClaudeAgentOptions(
system_prompt="You are a helpful assistant",
max_turns=10,
allowed_tools=["Read", "Write", "Bash"],
permission_mode='acceptEdits',
cwd="/path/to/project"
)
async with ClaudeSDKClient(options=options) as client:
await client.query("Analyze this codebase")
async for msg in client.receive_response():
if msg.type == "assistant":
for block in msg.content:
if block.type == "text":
print(block.text)python
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions
options = ClaudeAgentOptions(
system_prompt="你是一个乐于助人的助手",
max_turns=10,
allowed_tools=["Read", "Write", "Bash"],
permission_mode='acceptEdits',
cwd="/path/to/project"
)
async with ClaudeSDKClient(options=options) as client:
await client.query("分析此代码库")
async for msg in client.receive_response():
if msg.type == "assistant":
for block in msg.content:
if block.type == "text":
print(block.text)Custom Tools - SDK MCP Server
自定义工具 - SDK MCP服务器
python
from claude_agent_sdk import tool, create_sdk_mcp_server
@tool("greet", "Greet a user by name", {"name": str})
async def greet_user(args):
return {
"content": [{"type": "text", "text": f"Hello, {args['name']}!"}]
}
@tool("fetch_data", "Fetch data from API", {"endpoint": str})
async def fetch_data(args):
# Implementation
return {"content": [{"type": "text", "text": f"Data from {args['endpoint']}"}]}
server = create_sdk_mcp_server(
name="custom-tools",
version="1.0.0",
tools=[greet_user, fetch_data]
)
options = ClaudeAgentOptions(
mcp_servers={"tools": server},
allowed_tools=["mcp__tools__greet", "mcp__tools__fetch_data"]
)python
from claude_agent_sdk import tool, create_sdk_mcp_server
@tool("greet", "按名称问候用户", {"name": str})
async def greet_user(args):
return {
"content": [{"type": "text", "text": f"Hello, {args['name']}!"}]
}
@tool("fetch_data", "从API获取数据", {"endpoint": str})
async def fetch_data(args):
# 实现逻辑
return {"content": [{"type": "text", "text": f"Data from {args['endpoint']}"}]}
server = create_sdk_mcp_server(
name="custom-tools",
version="1.0.0",
tools=[greet_user, fetch_data]
)
options = ClaudeAgentOptions(
mcp_servers={"tools": server},
allowed_tools=["mcp__tools__greet", "mcp__tools__fetch_data"]
)Hooks - Deterministic Control
钩子 - 确定性控制
python
from claude_agent_sdk import HookMatcher
async def validate_bash_command(input_data, tool_use_id, context):
if input_data["tool_name"] != "Bash":
return {}
command = input_data["tool_input"].get("command", "")
forbidden = ["rm -rf", "dd if=", "mkfs"]
for pattern in forbidden:
if pattern in command:
return {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": f"Forbidden: {pattern}",
}
}
return {}
options = ClaudeAgentOptions(
allowed_tools=["Bash"],
hooks={
"PreToolUse": [
HookMatcher(matcher="Bash", hooks=[validate_bash_command]),
],
}
)python
from claude_agent_sdk import HookMatcher
async def validate_bash_command(input_data, tool_use_id, context):
if input_data["tool_name"] != "Bash":
return {}
command = input_data["tool_input"].get("command", "")
forbidden = ["rm -rf", "dd if=", "mkfs"]
for pattern in forbidden:
if pattern in command:
return {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": f"Forbidden: {pattern}",
}
}
return {}
options = ClaudeAgentOptions(
allowed_tools=["Bash"],
hooks={
"PreToolUse": [
HookMatcher(matcher="Bash", hooks=[validate_bash_command]),
],
}
)Error Handling
错误处理
python
from claude_agent_sdk import (
CLINotFoundError,
CLIConnectionError,
ProcessError,
CLIJSONDecodeError,
)
try:
async for message in query(prompt="Hello"):
pass
except CLINotFoundError:
print("Install Claude Code: curl -fsSL https://claude.ai/install.sh | bash")
except ProcessError as e:
print(f"Process failed: {e.exit_code}")
except CLIJSONDecodeError as e:
print(f"JSON parse error: {e}")python
from claude_agent_sdk import (
CLINotFoundError,
CLIConnectionError,
ProcessError,
CLIJSONDecodeError,
)
try:
async for message in query(prompt="Hello"):
pass
except CLINotFoundError:
print("安装Claude Code: curl -fsSL https://claude.ai/install.sh | bash")
except ProcessError as e:
print(f"进程失败: {e.exit_code}")
except CLIJSONDecodeError as e:
print(f"JSON解析错误: {e}")2. Headless/Print Mode CLI
2. 无头/打印模式CLI
Basic Usage
基本用法
bash
undefinedbash
undefinedSimple query
一次性查询
claude -p "What does the auth module do?"
claude -p "认证模块的作用是什么?"
Structured JSON output
结构化JSON输出
claude -p "Summarize this project" --output-format json
claude -p "总结此项目" --output-format json
Extract specific data with jq
使用jq提取特定数据
claude -p "Summarize this project" --output-format json | jq -r '.result'
undefinedclaude -p "总结此项目" --output-format json | jq -r '.result'
undefinedStructured Output with JSON Schema
带JSON Schema的结构化输出
bash
claude -p "Extract function names from auth.py" \
--output-format json \
--json-schema '{
"type": "object",
"properties": {
"functions": {"type": "array", "items": {"type": "string"}}
},
"required": ["functions"]
}' | jq '.structured_output'bash
claude -p "从auth.py中提取函数名" \
--output-format json \
--json-schema '{
"type": "object",
"properties": {
"functions": {"type": "array", "items": {"type": "string"}}
},
"required": ["functions"]
}' | jq '.structured_output'Streaming Responses
流式响应
bash
undefinedbash
undefinedStream with full events
带完整事件的流式输出
claude -p "Explain recursion"
--output-format stream-json
--verbose
--include-partial-messages
--output-format stream-json
--verbose
--include-partial-messages
claude -p "解释递归"
--output-format stream-json
--verbose
--include-partial-messages
--output-format stream-json
--verbose
--include-partial-messages
Extract only text deltas with jq
使用jq仅提取文本增量
claude -p "Write a poem"
--output-format stream-json
--verbose
--include-partial-messages |
jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'
--output-format stream-json
--verbose
--include-partial-messages |
jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'
undefinedclaude -p "写一首诗"
--output-format stream-json
--verbose
--include-partial-messages |
jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'
--output-format stream-json
--verbose
--include-partial-messages |
jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'
undefinedAuto-Approve Tools
自动批准工具
bash
undefinedbash
undefinedAllow specific tools without prompting
允许特定工具无需提示
claude -p "Run tests and fix failures"
--allowedTools "Bash,Read,Edit"
--allowedTools "Bash,Read,Edit"
claude -p "运行测试并修复失败项"
--allowedTools "Bash,Read,Edit"
--allowedTools "Bash,Read,Edit"
Git operations with prefix matching
带前缀匹配的Git操作
claude -p "Review staged changes and commit"
--allowedTools "Bash(git diff *)" "Bash(git log *)" "Bash(git status *)" "Bash(git commit *)"
--allowedTools "Bash(git diff *)" "Bash(git log *)" "Bash(git status *)" "Bash(git commit *)"
undefinedclaude -p "审查暂存的更改并提交"
--allowedTools "Bash(git diff *)" "Bash(git log *)" "Bash(git status *)" "Bash(git commit *)"
--allowedTools "Bash(git diff *)" "Bash(git log *)" "Bash(git status *)" "Bash(git commit *)"
undefinedContinue Conversations
继续对话
bash
undefinedbash
undefinedFirst request
首次请求
claude -p "Review this codebase for performance issues"
claude -p "审查此代码库的性能问题"
Continue most recent
继续最近的对话
claude -p "Focus on database queries" --continue
claude -p "重点关注数据库查询" --continue
Resume specific session
恢复特定会话
session_id=$(claude -p "Start review" --output-format json | jq -r '.session_id')
claude -p "Continue review" --resume "$session_id"
undefinedsession_id=$(claude -p "开始审查" --output-format json | jq -r '.session_id')
claude -p "继续审查" --resume "$session_id"
undefinedCustom System Prompts
自定义系统提示词
bash
undefinedbash
undefinedAppend to default prompt (recommended)
追加到默认提示词(推荐)
claude -p "Review this PR"
--append-system-prompt "You are a security engineer. Focus on vulnerabilities."
--append-system-prompt "You are a security engineer. Focus on vulnerabilities."
claude -p "审查此PR"
--append-system-prompt "你是一名安全工程师。重点关注漏洞。"
--append-system-prompt "你是一名安全工程师。重点关注漏洞。"
Replace entire prompt (full control)
替换整个提示词(完全控制)
claude -p "Analyze code"
--system-prompt "You are a Python expert who only writes type-annotated code"
--system-prompt "You are a Python expert who only writes type-annotated code"
claude -p "分析代码"
--system-prompt "你是一名Python专家,只编写带类型注解的代码"
--system-prompt "你是一名Python专家,只编写带类型注解的代码"
Load from file
从文件加载
claude -p "Review code"
--append-system-prompt-file ./prompts/style-rules.txt
--append-system-prompt-file ./prompts/style-rules.txt
---claude -p "审查代码"
--append-system-prompt-file ./prompts/style-rules.txt
--append-system-prompt-file ./prompts/style-rules.txt
---3. CLI Commands & Flags Reference
3. CLI命令与参数参考
Common Commands
常用命令
bash
undefinedbash
undefinedInteractive REPL
交互式REPL
claude
claude "explain this project"
claude
claude "解释此项目"
Headless/print mode
无头/打印模式
claude -p "query"
cat file | claude -p "analyze"
claude -p "query"
cat file | claude -p "analyze"
Continue conversations
继续对话
claude -c # most recent
claude -c -p "follow-up" # continue via SDK
claude -r "session-id" # resume specific
claude -c # 最近的对话
claude -c -p "follow-up" # 通过SDK继续
claude -r "session-id" # 恢复特定会话
Update
更新
claude update
claude update
MCP configuration
MCP配置
claude mcp
undefinedclaude mcp
undefinedEssential Flags
核心参数
| Flag | Purpose | Example |
|---|---|---|
| Auto-approve tools | |
| Block tools | |
| Restrict available tools | |
| Set model | |
| Limit turns | |
| Cost limit | |
| Output format | |
| Structured output | |
| Start in mode | |
| Additional dirs | |
| Custom subagents | |
| Browser automation | |
| Full logging | |
| 参数 | 用途 | 示例 |
|---|---|---|
| 自动批准工具 | |
| 阻止工具 | |
| 限制可用工具 | |
| 设置模型 | |
| 限制对话轮次 | |
| 成本限制 | |
| 输出格式 | |
| 结构化输出 | |
| 启动模式 | |
| 额外目录 | |
| 自定义子Agent | |
| 浏览器自动化 | |
| 完整日志 | |
Dynamic Subagents
动态子Agent
bash
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer",
"prompt": "Focus on code quality, security, best practices",
"tools": ["Read", "Grep", "Glob"],
"model": "sonnet"
},
"debugger": {
"description": "Debugging specialist",
"prompt": "Analyze errors, identify root causes",
"maxTurns": 10
}
}'bash
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer",
"prompt": "Focus on code quality, security, best practices",
"tools": ["Read", "Grep", "Glob"],
"model": "sonnet"
},
"debugger": {
"description": "Debugging specialist",
"prompt": "Analyze errors, identify root causes",
"maxTurns": 10
}
}'Permission Rule Syntax
权限规则语法
bash
undefinedbash
undefinedTool name only
仅工具名称
--allowedTools "Read" "Write"
--allowedTools "Read" "Write"
With argument pattern (exact match)
带参数模式(精确匹配)
--allowedTools "Bash(git status)"
--allowedTools "Bash(git status)"
With prefix matching (note the space before *)
带前缀匹配(注意*前的空格)
--allowedTools "Bash(git diff *)" "Bash(git log *)"
--allowedTools "Bash(git diff *)" "Bash(git log *)"
Block destructive patterns
阻止破坏性模式
--disallowedTools "Bash(rm -rf *)" "Bash(dd *)"
-----disallowedTools "Bash(rm -rf *)" "Bash(dd *)"
---Common Use Cases
常见用例
1. CI/CD Test & Fix Pipeline
1. CI/CD测试与修复流水线
python
from claude_agent_sdk import query, ClaudeAgentOptions
options = ClaudeAgentOptions(
allowed_tools=["Bash", "Read", "Edit"],
permission_mode="acceptEdits",
max_turns=20,
max_budget_usd=5.0
)
async for msg in query(
prompt="Run the test suite. Fix any failures. Re-run until all pass.",
options=options
):
# Process messages
passpython
from claude_agent_sdk import query, ClaudeAgentOptions
options = ClaudeAgentOptions(
allowed_tools=["Bash", "Read", "Edit"],
permission_mode="acceptEdits",
max_turns=20,
max_budget_usd=5.0
)
async for msg in query(
prompt="运行测试套件。修复所有失败项。重新运行直至全部通过。",
options=options
):
# 处理消息
pass2. Automated Code Review
2. 自动化代码审查
bash
#!/bin/bash
gh pr diff "$1" | claude -p \
--append-system-prompt "Security review: check for OWASP top 10, injection, XSS, auth issues" \
--allowedTools "Read" \
--output-format json \
--max-turns 3 | jq -r '.result'bash
#!/bin/bash
gh pr diff "$1" | claude -p \
--append-system-prompt "安全审查:检查OWASP十大漏洞、注入、XSS、认证问题" \
--allowedTools "Read" \
--output-format json \
--max-turns 3 | jq -r '.result'3. Custom Analysis Tool
3. 自定义分析工具
python
from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeSDKClient, ClaudeAgentOptions
@tool("analyze_file", "Analyze file metrics", {"path": str})
async def analyze_file(args):
# Custom analysis logic
with open(args["path"]) as f:
lines = len(f.readlines())
return {"content": [{"type": "text", "text": f"File has {lines} lines"}]}
server = create_sdk_mcp_server(name="analyzer", version="1.0.0", tools=[analyze_file])
options = ClaudeAgentOptions(
mcp_servers={"analyzer": server},
allowed_tools=["mcp__analyzer__analyze_file", "Read"],
system_prompt="You are a code quality analyzer"
)
async with ClaudeSDKClient(options=options) as client:
await client.query("Analyze all Python files in this directory")
async for msg in client.receive_response():
print(msg)python
from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeSDKClient, ClaudeAgentOptions
@tool("analyze_file", "分析文件指标", {"path": str})
async def analyze_file(args):
# 自定义分析逻辑
with open(args["path"]) as f:
lines = len(f.readlines())
return {"content": [{"type": "text", "text": f"文件包含{lines}行"}]}
server = create_sdk_mcp_server(name="analyzer", version="1.0.0", tools=[analyze_file])
options = ClaudeAgentOptions(
mcp_servers={"analyzer": server},
allowed_tools=["mcp__analyzer__analyze_file", "Read"],
system_prompt="你是一名代码质量分析师"
)
async with ClaudeSDKClient(options=options) as client:
await client.query("分析此目录下所有Python文件")
async for msg in client.receive_response():
print(msg)4. Database Query Agent
4. 数据库查询Agent
python
from claude_agent_sdk import tool, create_sdk_mcp_server
@tool("query_db", "Execute SQL query", {"query": str})
async def query_database(args):
# Safe parameterized query execution
result = execute_query(args["query"])
return {"content": [{"type": "text", "text": str(result)}]}
@tool("get_schema", "Get database schema", {})
async def get_schema(args):
schema = fetch_schema()
return {"content": [{"type": "text", "text": schema}]}
server = create_sdk_mcp_server(
name="db-tools",
version="1.0.0",
tools=[query_database, get_schema]
)python
from claude_agent_sdk import tool, create_sdk_mcp_server
@tool("query_db", "执行SQL查询", {"query": str})
async def query_database(args):
# 安全的参数化查询执行
result = execute_query(args["query"])
return {"content": [{"type": "text", "text": str(result)}]}
@tool("get_schema", "获取数据库架构", {})
async def get_schema(args):
schema = fetch_schema()
return {"content": [{"type": "text", "text": schema}]}
server = create_sdk_mcp_server(
name="db-tools",
version="1.0.0",
tools=[query_database, get_schema]
)Best Practices
最佳实践
Agent SDK
Agent SDK
- Use instead of the raw Anthropic API (
claude_agent_sdk)anthropic.Anthropic() - No API keys needed — uses Claude Code's config
~/.claude/ - Use for async execution
anyio.run() - Handle errors explicitly with try/except blocks
- Set and
max_turnsfor safetymax_budget_usd - Use hooks for deterministic control flow
- Prefer SDK MCP servers over external processes for custom tools
- Set for automation
permission_mode='acceptEdits'
- 使用而非原生Anthropic API(
claude_agent_sdk)anthropic.Anthropic() - 无需API密钥——使用Claude Code的配置文件
~/.claude/ - 使用执行异步代码
anyio.run() - 使用try/except块显式处理错误
- 设置和
max_turns以确保安全max_budget_usd - 使用钩子实现确定性控制流
- 自定义工具优先使用SDK MCP服务器而非外部进程
- 自动化场景设置
permission_mode='acceptEdits'
CLI/Headless
CLI/无头模式
- Use for parsing responses
--output-format json - Combine with for structured data extraction
jq - Set to prevent runaway costs
--max-turns - Use with specific patterns for security
--allowedTools - Capture for conversation continuation
session_id - Use for debugging
--verbose
- 使用以便解析响应
--output-format json - 结合提取结构化数据
jq - 设置防止成本失控
--max-turns - 使用并搭配特定模式以确保安全
--allowedTools - 捕获以便继续对话
session_id - 调试时使用
--verbose
Security
安全
- Do not use in production
--dangerously-skip-permissions - Validate inputs in custom tools
- Use permission rules to block destructive commands
- Set budget limits with
--max-budget-usd - Implement hooks for sensitive operations
- Review allowed tools before automation
- 生产环境中不要使用
--dangerously-skip-permissions - 自定义工具中验证输入
- 使用权限规则阻止破坏性命令
- 使用设置预算限制
--max-budget-usd - 对敏感操作实现钩子
- 自动化前审查允许的工具
Quick Decision Tree
快速决策树
Need to...
- Run one-off query →
claude -p "query" - Build custom agent → Agent SDK with
ClaudeSDKClient - Add custom tools → SDK MCP server with decorator
@tool - Control execution → Hooks with
HookMatcher - Stream responses →
--output-format stream-json - Get structured data →
--json-schema - Continue conversation → or
--continue--resume - Run in CI/CD → with
claude -p--allowedTools - Integrate with app → Python SDK with or
query()ClaudeSDKClient
需要...
- 运行一次性查询 →
claude -p "query" - 构建自定义Agent → 使用的Agent SDK
ClaudeSDKClient - 添加自定义工具 → 使用装饰器的SDK MCP服务器
@tool - 控制执行流程 → 使用的钩子
HookMatcher - 流式响应 →
--output-format stream-json - 获取结构化数据 →
--json-schema - 继续对话 → 或
--continue--resume - 在CI/CD中运行 → 搭配的
--allowedToolsclaude -p - 与应用集成 → 使用或
query()的Python SDKClaudeSDKClient
When to Fetch Docs
何时获取文档
Fetch live documentation when:
- API signatures or parameters are unclear
- New features or flags are mentioned
- Error messages reference unknown configuration
- Implementing complex hooks or MCP servers
- User asks about specific capabilities
Use tool to pull latest documentation from source URLs.
WebFetch以下情况获取实时文档:
- API签名或参数不清晰
- 提及新功能或参数
- 错误消息引用未知配置
- 实现复杂钩子或MCP服务器
- 用户询问特定功能
使用工具从源URL获取最新文档。
WebFetchImplementation Checklist
实施检查清单
Before writing code:
- Verify: Using Claude Code headless mode (or
claude -p) — not raw Anthropic APIclaude_agent_sdk - Verify: No API keys in code — authentication comes from config
~/.claude/ - Confirm Python version (3.10+)
- Verify Claude Code CLI installation ()
which claude - Check required packages with
uv pip list - Understand the specific use case
- Determine if SDK or CLI approach is needed
After writing code:
- Verify: Code uses or
claude_agent_sdk— notclaude -panthropic.Anthropic() - Verify: No or
ANTHROPIC_API_KEYparameters in codeapi_key= - Add error handling for all SDK exceptions
- Test with actual Claude Code installation
- Validate tool permissions and security
- Set appropriate limits (turns, budget)
- Document custom tools and their purposes
编写代码前:
- 验证: 使用Claude Code无头模式(或
claude -p)——而非原生Anthropic APIclaude_agent_sdk - 验证: 代码中无API密钥——认证来自配置文件
~/.claude/ - 确认Python版本(3.10+)
- 验证Claude Code CLI安装情况()
which claude - 使用检查所需包
uv pip list - 理解具体用例
- 确定需要SDK还是CLI方式
编写代码后:
- 验证: 代码使用或
claude_agent_sdk——而非claude -panthropic.Anthropic() - 验证: 代码中无或
ANTHROPIC_API_KEY参数api_key= - 添加针对所有SDK异常的错误处理
- 使用实际Claude Code安装进行测试
- 验证工具权限和安全性
- 设置适当的限制(轮次、预算)
- 记录自定义工具及其用途
Example: Complete Agent
示例:完整Agent
This uses Claude Code CLI via the Agent SDK — not the raw Anthropic API.
python
import anyio
from claude_agent_sdk import (
ClaudeSDKClient,
ClaudeAgentOptions,
tool,
create_sdk_mcp_server,
HookMatcher,
)本示例通过Agent SDK使用Claude Code CLI——而非原生Anthropic API。
python
import anyio
from claude_agent_sdk import (
ClaudeSDKClient,
ClaudeAgentOptions,
tool,
create_sdk_mcp_server,
HookMatcher,
)Using claude_agent_sdk (wraps Claude Code CLI)
使用claude_agent_sdk(封装Claude Code CLI)
Custom tool
自定义工具
@tool("get_config", "Get app configuration", {})
async def get_config(args):
return {"content": [{"type": "text", "text": "Config: {...}"}]}
@tool("get_config", "获取应用配置", {})
async def get_config(args):
return {"content": [{"type": "text", "text": "配置: {...}"}]}
Hook for validation
验证钩子
async def validate_edit(input_data, tool_use_id, context):
if input_data["tool_name"] != "Edit":
return {}
file_path = input_data["tool_input"].get("file_path", "")
if file_path.endswith(".env"):
return {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Cannot edit .env files",
}
}
return {}async def validate_edit(input_data, tool_use_id, context):
if input_data["tool_name"] != "Edit":
return {}
file_path = input_data["tool_input"].get("file_path", "")
if file_path.endswith(".env"):
return {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "无法编辑.env文件",
}
}
return {}Setup
设置
server = create_sdk_mcp_server("config-tools", "1.0.0", [get_config])
options = ClaudeAgentOptions(
system_prompt="You are a configuration management assistant",
allowed_tools=["Read", "Edit", "mcp__config_tools__get_config"],
mcp_servers={"config_tools": server},
hooks={"PreToolUse": [HookMatcher(matcher="Edit", hooks=[validate_edit])]},
max_turns=10,
max_budget_usd=1.0,
cwd="/path/to/project",
)
server = create_sdk_mcp_server("config-tools", "1.0.0", [get_config])
options = ClaudeAgentOptions(
system_prompt="你是一名配置管理助手",
allowed_tools=["Read", "Edit", "mcp__config_tools__get_config"],
mcp_servers={"config_tools": server},
hooks={"PreToolUse": [HookMatcher(matcher="Edit", hooks=[validate_edit])]},
max_turns=10,
max_budget_usd=1.0,
cwd="/path/to/project",
)
Run
运行
async def main():
async with ClaudeSDKClient(options=options) as client:
await client.query("Update the app configuration")
async for msg in client.receive_response():
if msg.type == "assistant":
for block in msg.content:
if hasattr(block, "text"):
print(block.text)
anyio.run(main)
---async def main():
async with ClaudeSDKClient(options=options) as client:
await client.query("更新应用配置")
async for msg in client.receive_response():
if msg.type == "assistant":
for block in msg.content:
if hasattr(block, "text"):
print(block.text)
anyio.run(main)
---Skill Invocation
技能调用
This skill provides:
- Complete Agent SDK implementation guidance
- Headless/CLI command construction
- Custom tool creation with MCP servers
- Hook implementation for control flow
- Security best practices
- Live documentation fetching when needed
Ask specific questions about building agents, running headless commands, or CLI usage.
本技能提供:
- 完整Agent SDK实施指南
- 无头/CLI命令构建
- 借助MCP服务器创建自定义工具
- 用于控制流的钩子实现
- 安全最佳实践
- 必要时获取实时文档
可针对构建Agent、运行无头命令或CLI使用提出具体问题。
Limitations
局限性
- The Agent SDK is Python-only (Python 3.10+); no JavaScript or other language bindings are covered here.
- Requires Claude Code CLI installed and authenticated via before any SDK or headless usage works.
~/.claude/ - This skill does not cover raw Anthropic API usage (); see the Anthropic API docs for that.
anthropic.Anthropic() - Agent processes launched via the SDK are ephemeral by default; session persistence requires explicit or session ID capture.
--resume - MCP server patterns in this skill use stdio transport; HTTP-based MCP transports require separate configuration not covered here.
- Agent SDK仅支持Python(Python 3.10+);此处不涵盖JavaScript或其他语言绑定。
- 使用SDK或无头模式前,需安装Claude Code CLI并通过完成认证。
~/.claude/ - 本技能不涵盖原生Anthropic API使用();相关内容请参考Anthropic API文档。
anthropic.Anthropic() - 默认情况下,通过SDK启动的Agent进程是临时的;会话持久化需要显式使用或捕获会话ID。
--resume - 本技能中的MCP服务器模式使用stdio传输;基于HTTP的MCP传输需要单独配置,此处不涵盖。
Output Format
输出格式
This skill produces runnable Python files and Bash scripts, not pseudocode or outlines.
Each code artifact includes imports, error handling, and executable entry points.
CLI examples include all required flags with concrete values ready to copy and run.
Custom tool definitions include the decorator, argument schema, and return format.
@tool本技能生成可运行的Python文件和Bash脚本,而非伪代码或大纲。
每个代码工件均包含导入、错误处理和可执行入口点。
CLI示例包含所有必要参数及可直接复制运行的具体值。
自定义工具定义包含装饰器、参数架构和返回格式。
@tool