Claude Code SDK:使用指南
SDK
使用 SDK 以编程方式将 Claude Code 集成到您的应用程序中。
通过 Claude Code SDK,开发者可以编程方式将 Claude Code 集成到他们的应用程序中。它能够将 Claude Code 作为子进程运行,从而提供构建由 AI 驱动的编码助手和工具的方式,这些助手和工具可以利用 Claude 的强大功能。
该 SDK 目前支持命令行使用。TypeScript 和 Python SDK 即将推出。
基本 SDK 用法
Claude Code SDK 允许您从应用程序以非交互模式使用 Claude Code。 这是一个基本示例:
# 运行单个 prompt 并退出(打印模式)
$ claude -p "Write a function to calculate Fibonacci numbers"
# 使用管道提供 stdin
$ echo "Explain this code" | claude -p
# 以 JSON 格式输出,带有元数据
$ claude -p "Generate a hello world function" --output-format json
# 实时流式传输 JSON 输出
$ claude -p "Build a React component" --output-format stream-json
高级用法
多轮对话
对于多轮对话,您可以恢复对话或从最近的会话继续:
# 继续最近的对话
$ claude --continue
# 继续并提供新的 prompt
$ claude --continue "Now refactor this for better performance"
# 通过会话 ID 恢复特定对话
$ claude --resume 550e8400-e29b-41d4-a716-446655440000
# 在打印模式下恢复(非交互式)
$ claude -p --resume 550e8400-e29b-41d4-a716-446655440000 "Update the tests"
# 在打印模式下继续(非交互式)
$ claude -p --continue "Add error handling"
自定义系统 Prompts
您可以提供自定义系统 prompts 以指导 Claude 的行为:
# 覆盖系统 prompt(仅适用于 --print)
$ claude -p "Build a REST API" --system-prompt "You are a senior backend engineer. Focus on security, performance, and maintainability."
# 带有特定要求的系统 prompt
$ claude -p "Create a database schema" --system-prompt "You are a database architect. Use PostgreSQL best practices and include proper indexing."
您还可以将指令附加到默认系统 prompt:
# 附加系统 prompt(仅适用于 --print)
$ claude -p "Build a REST API" --append-system-prompt "After writing code, be sure to code review yourself."
MCP 配置
Model Context Protocol (MCP) 允许您使用来自外部服务器的其他工具和资源来扩展 Claude Code。 使用 --mcp-config
标志,您可以加载 MCP 服务器,这些服务器提供诸如数据库访问、API 集成或自定义工具之类的专门功能。
使用您的 MCP 服务器创建一个 JSON 配置文件:
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"/path/to/allowed/files"
]
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "your-github-token"
}
}
}
}
然后将其与 Claude Code 一起使用:
# 从配置加载 MCP 服务器
$ claude -p "List all files in the project" --mcp-config mcp-servers.json
# 重要提示:必须使用 --allowedTools 显式允许 MCP 工具
# MCP 工具遵循格式:mcp__$serverName__$toolName
$ claude -p "Search for TODO comments" \
--mcp-config mcp-servers.json \
--allowedTools "mcp__filesystem__read_file,mcp__filesystem__list_directory"
# 使用 MCP 工具在非交互模式下处理权限 prompt
$ claude -p "Deploy the application" \
--mcp-config mcp-servers.json \
--allowedTools "mcp__permissions__approve" \
--permission-prompt-tool mcp__permissions__approve
注意:使用 MCP 工具时,必须使用 --allowedTools
标志显式允许它们。 MCP 工具名称遵循模式 mcp__<serverName>__<toolName>
,其中:
serverName
是来自您的 MCP 配置文件的键toolName
是该服务器提供的特定工具
此安全措施可确保仅在明确允许的情况下才使用 MCP 工具。
可用的 CLI 选项
该 SDK 利用 Claude Code 中所有可用的 CLI 选项。 以下是 SDK 使用的关键选项:
| Flag | Description | Example |
| ---------------------- | ---------------------------------------- | ------------------------------------------ |
| --print
, -p
| 以非交互模式运行 | claude -p "query"
|
| --output-format
| 指定输出格式 (text
, json
, stream-json
) | claude -p --output-format json
|
| --resume
, -r
| 通过会话 ID 恢复对话 | claude --resume abc123
|
| --continue
, -c
| 继续最近的对话 | claude --continue
|
| --verbose
| 启用详细日志记录 | claude --verbose
|
| --max-turns
| 限制非交互模式下的代理 turns | claude --max-turns 3
|
| --system-prompt
| 覆盖系统 prompt(仅适用于 --print
) | claude --system-prompt "Custom instruction"
|
| --append-system-prompt
| 附加到系统 prompt(仅适用于 --print
) | claude --append-system-prompt "Custom instruction"
|
| --allowedTools
| 允许工具的逗号/空格分隔列表(包括 MCP 工具) | claude --allowedTools "Bash(npm install),mcp__filesystem__*"
|
| --disallowedTools
| 拒绝工具的逗号/空格分隔列表 | claude --disallowedTools "Bash(git commit),mcp__github__*"
|
| --mcp-config
| 从 JSON 文件加载 MCP 服务器 | claude --mcp-config servers.json
|
| --permission-prompt-tool
| 用于处理权限 prompts 的 MCP 工具(仅适用于 --print
) | claude --permission-prompt-tool mcp__auth__prompt
|
有关 CLI 选项和功能的完整列表,请参见 CLI usage 文档。
输出格式
SDK 支持多种输出格式:
文本输出(默认)
仅返回响应文本:
$ claude -p "Explain file src/components/Header.tsx"
# Output: This is a React component showing...
JSON 输出
返回包括元数据的结构化数据:
$ claude -p "How does the data layer work?" --output-format json
响应格式:
{
"type": "result",
"subtype": "success",
"cost_usd": 0.003,
"is_error": false,
"duration_ms": 1234,
"duration_api_ms": 800,
"num_turns": 6,
"result": "The response text here...",
"session_id": "abc123"
}
流式 JSON 输出
流式传输接收到的每个消息:
$ claude -p "Build an application" --output-format stream-json
每个会话都以初始 init
系统消息开始,然后是用户和助手消息的列表,最后是带有统计信息的最终 result
系统消息。 每个消息都作为单独的 JSON 对象发出。
消息模式
从 JSON API 返回的消息根据以下模式严格类型化:
type Message =
// An assistant message
| {
type: "assistant";
message: APIAssistantMessage; // from Anthropic SDK
session_id: string;
}
// A user message
| {
type: "user";
message: APIUserMessage; // from Anthropic SDK
session_id: string;
}
// Emitted as the last message
| {
type: "result";
subtype: "success";
cost_usd: float;
duration_ms: float;
duration_api_ms: float;
is_error: boolean;
num_turns: int;
result: string;
session_id: string;
}
// Emitted as the last message, when we've reached the maximum number of turns
| {
type: "result";
subtype: "error_max_turns";
cost_usd: float;
duration_ms: float;
duration_api_ms: float;
is_error: boolean;
num_turns: int;
session_id: string;
}
// Emitted as the first message at the start of a conversation
| {
type: "system";
subtype: "init";
session_id: string;
tools: string[];
mcp_servers: {
name: string;
status: string;
}[];
};
我们很快将以与 JSONSchema 兼容的格式发布这些类型。 我们对主要的 Claude Code 包使用语义版本控制,以传达此格式的重大更改。
例子
简单脚本集成
#!/bin/bash
# 简单的函数来运行 Claude 并检查退出代码
run_claude() {
local prompt="$1"
local output_format="${2:-text}"
if claude -p "$prompt" --output-format "$output_format"; then
echo "Success!"
else
echo "Error: Claude failed with exit code $?" >&2
return 1
fi
}
# 使用示例
run_claude "Write a Python function to read CSV files"
run_claude "Optimize this database query" "json"
使用 Claude 处理文件
# 通过 Claude 处理文件
$ cat mycode.py | claude -p "Review this code for bugs"
# 处理多个文件
$ for file in *.js; do
echo "Processing $file..."
claude -p "Add JSDoc comments to this file:" < "$file" > "${file}.documented"
done
# 在 pipeline 中使用 Claude
$ grep -l "TODO" *.py | while read file; do
claude -p "Fix all TODO items in this file" < "$file"
done
会话管理
# 启动一个会话并捕获会话 ID
$ claude -p "Initialize a new project" --output-format json | jq -r '.session_id' > session.txt
# 继续相同的会话
$ claude -p --resume "$(cat session.txt)" "Add unit tests"
# 列出最近的会话
$ claude logs
最佳实践
- 使用 JSON 输出格式 进行响应的程序化解析:
# 使用 jq 解析 JSON 响应
result=$(claude -p "Generate code" --output-format json)
code=$(echo "$result" | jq -r '.result')
cost=$(echo "$result" | jq -r '.cost_usd')
- 优雅地处理错误 - 检查退出代码和 stderr:
if ! claude -p "$prompt" 2>error.log; then
echo "Error occurred:" >&2
cat error.log >&2
exit 1
fi
- 使用会话管理 以在多轮对话中维护上下文
- 考虑长时间运行操作的超时:
timeout 300 claude -p "$complex_prompt" || echo "Timed out after 5 minutes"
- 在进行多个请求时,遵守速率限制,并在调用之间添加延迟
实际应用
Claude Code SDK 可以在您的开发工作流程中实现强大的集成。 一个值得注意的例子是 Claude Code GitHub Actions,它使用 SDK 直接在您的 GitHub 工作流程中提供自动代码审查、PR 创建和问题分类功能。
相关资源
- CLI usage and controls - 完整的 CLI 文档
- GitHub Actions integration - 使用 Claude 自动化您的 GitHub 工作流程
- Tutorials - 常见用例的循序渐进指南