Claude Code Agent SDK 让开发者可以把 Claude Code 的 Agent 能力嵌入自己的应用、CI/CD 流水线和工作流自动化中。本文是 Agent SDK 的完整开发指南,从安装到生产部署。
Agent SDK 是什么?
Agent SDK 是 Claude Code 的可编程接口,让你能够:
- 无头模式运行:在 CI/CD 里自动化运行 Claude Code,不需要终端交互
- 自定义工具:给 Agent 注入额外的工具(调用你的 API、查询你的数据库)
- 编排多个 Agent:协调主 Agent 和多个 Sub-Agent 完成复杂任务
- Webhook 集成:通过 Routines 的
/fire端点从外部系统触发 - 结果处理:捕获 Agent 的输出、工具调用记录、Token 使用统计
安装
bash
npm install @anthropic-ai/claude-code
# 或
pip install anthropic-claude-code基础用法
TypeScript/JavaScript
typescript
import { ClaudeCode } from '@anthropic-ai/claude-code';
const agent = new ClaudeCode({
apiKey: process.env.ANTHROPIC_API_KEY,
model: 'claude-opus-4-7',
workingDirectory: '/path/to/project',
});
// 单次运行(无头模式)
const result = await agent.run({
prompt: '审查 src/ 目录下最近的代码变更,找出潜在的安全问题',
allowedTools: ['Read', 'Grep', 'Glob'], // 只读权限
maxTurns: 10,
});
console.log(result.response);
console.log('工具调用次数:', result.toolCalls.length);
console.log('Token 使用:', result.usage);Python
python
from anthropic_claude_code import ClaudeCode
agent = ClaudeCode(
api_key=os.environ["ANTHROPIC_API_KEY"],
model="claude-opus-4-7",
working_directory="/path/to/project",
)
result = agent.run(
prompt="分析这个 Bug 报告并实现修复:[Bug 详情]",
permission_mode="auto", # 使用 Auto Mode
max_turns=20,
)
print(result.response)权限模式配置
typescript
const agent = new ClaudeCode({
apiKey: process.env.ANTHROPIC_API_KEY,
});
// 只读模式(最安全)
const readOnlyResult = await agent.run({
prompt: '分析代码库架构',
permissionMode: 'readonly',
});
// Auto Mode(平衡安全和效率)
const autoResult = await agent.run({
prompt: '修复这个 Bug',
permissionMode: 'auto',
});
// 完全权限(CI 环境,有完整控制)
const fullResult = await agent.run({
prompt: '运行完整的测试套件并修复失败',
permissionMode: 'bypassPermissions', // 等同于 --dangerously-skip-permissions
});
// 自定义允许列表
const customResult = await agent.run({
prompt: '更新依赖并运行测试',
allowedTools: [
'Read(**)',
'Write(src/**)',
'Write(tests/**)',
'Bash(npm install)',
'Bash(npm test)',
'Bash(git add *)',
'Bash(git commit *)',
],
deniedTools: [
'Bash(rm -rf *)',
'Write(.env*)',
],
});流式响应
typescript
// 实时接收 Agent 的输出
const stream = agent.stream({
prompt: '实现用户注册功能',
permissionMode: 'auto',
});
for await (const event of stream) {
switch (event.type) {
case 'message':
process.stdout.write(event.text);
break;
case 'tool_call':
console.log(`\n[工具调用] ${event.tool}: ${event.input}`);
break;
case 'tool_result':
console.log(`[工具结果] ${event.result.substring(0, 100)}...`);
break;
case 'done':
console.log('\n[完成]', event.usage);
break;
}
}自定义工具注入
给 Agent 注入你自己的工具:
typescript
const agent = new ClaudeCode({
apiKey: process.env.ANTHROPIC_API_KEY,
customTools: [
{
name: 'query_database',
description: '查询生产数据库(只读)',
inputSchema: {
type: 'object',
properties: {
sql: {
type: 'string',
description: 'SQL SELECT 查询语句',
},
},
required: ['sql'],
},
handler: async ({ sql }) => {
// 验证只有 SELECT 语句
if (!sql.trim().toUpperCase().startsWith('SELECT')) {
throw new Error('只允许 SELECT 查询');
}
const result = await db.query(sql);
return JSON.stringify(result.rows);
},
},
{
name: 'send_slack_notification',
description: '发送 Slack 通知到指定频道',
inputSchema: {
type: 'object',
properties: {
channel: { type: 'string' },
message: { type: 'string' },
},
required: ['channel', 'message'],
},
handler: async ({ channel, message }) => {
await slack.chat.postMessage({ channel, text: message });
return 'Notification sent';
},
},
],
});
// Agent 现在可以使用这些自定义工具
const result = await agent.run({
prompt: '查询过去 24 小时的订单数据,分析异常,发送报告到 #ops-alerts',
});多 Agent 编排
typescript
// 主 Agent 协调多个子 Agent
async function orchestrateRefactoring(codebasePath: string) {
const orchestrator = new ClaudeCode({
apiKey: process.env.ANTHROPIC_API_KEY,
model: 'claude-opus-4-7',
workingDirectory: codebasePath,
});
// 第一步:分析和规划(只读)
const planResult = await orchestrator.run({
prompt: '分析整个代码库,制定把所有 callback 改为 async/await 的迁移计划,按模块分组,列出每个模块的预计工作量',
permissionMode: 'readonly',
});
console.log('迁移计划:', planResult.response);
// 第二步:并行执行(每个模块一个子 Agent)
const modules = parsePlan(planResult.response); // 从计划中提取模块列表
const moduleAgents = modules.map(module => new ClaudeCode({
apiKey: process.env.ANTHROPIC_API_KEY,
model: 'claude-sonnet-4-6', // 子任务用性价比更高的模型
workingDirectory: `${codebasePath}/${module.path}`,
}));
// 并行执行所有模块迁移
const results = await Promise.all(
moduleAgents.map((agent, i) =>
agent.run({
prompt: `按照迁移计划,把 ${modules[i].path} 模块的所有 callback 改为 async/await。完成后运行该模块的测试。`,
permissionMode: 'auto',
maxTurns: 30,
})
)
);
// 第三步:集成测试
const verificationResult = await orchestrator.run({
prompt: '运行完整的集成测试套件,汇报所有失败',
permissionMode: 'auto',
});
return {
plan: planResult.response,
moduleResults: results,
verification: verificationResult.response,
};
}CI/CD 集成
GitHub Actions
yaml
name: AI Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
ai-review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: 安装依赖
run: npm ci
- name: Claude Code 安全审查
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
node -e "
const { ClaudeCode } = require('@anthropic-ai/claude-code');
async function review() {
const agent = new ClaudeCode({
apiKey: process.env.ANTHROPIC_API_KEY,
workingDirectory: process.cwd(),
});
const result = await agent.run({
prompt: '对最近的 git 变更进行安全审查,检查 OWASP Top 10 中的常见漏洞,输出 JSON 格式的发现列表',
permissionMode: 'readonly',
maxTurns: 5,
});
console.log(result.response);
// 如果发现 Critical 问题,退出码非零
if (result.response.includes('CRITICAL')) {
process.exit(1);
}
}
review().catch(console.error);
"
- name: 发布审查结果
uses: actions/github-script@v7
if: always()
with:
script: |
// 把审查结果发布为 PR 评论错误处理和重试
typescript
async function runWithRetry(
agent: ClaudeCode,
prompt: string,
maxRetries = 3
): Promise<AgentResult> {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const result = await agent.run({
prompt,
permissionMode: 'auto',
timeoutMs: 300_000, // 5 分钟超时
});
return result;
} catch (error) {
if (error instanceof RateLimitError) {
const waitTime = error.retryAfter ?? 60;
console.log(`速率限制,等待 ${waitTime}s (attempt ${attempt}/${maxRetries})`);
await sleep(waitTime * 1000);
} else if (error instanceof TimeoutError && attempt < maxRetries) {
console.log(`超时,重试 (attempt ${attempt}/${maxRetries})`);
} else {
throw error;
}
}
}
throw new Error(`超过最大重试次数 ${maxRetries}`);
}成本监控
typescript
// 跟踪每次 Agent 运行的成本
const PRICING = {
'claude-opus-4-7': { input: 5 / 1_000_000, output: 25 / 1_000_000 },
'claude-sonnet-4-6': { input: 3 / 1_000_000, output: 15 / 1_000_000 },
'claude-haiku-4-5': { input: 1 / 1_000_000, output: 5 / 1_000_000 },
};
function calculateCost(usage: TokenUsage, model: string): number {
const pricing = PRICING[model];
return (
usage.inputTokens * pricing.input +
usage.outputTokens * pricing.output +
(usage.cacheReadTokens ?? 0) * pricing.input * 0.1
);
}
const result = await agent.run({ prompt });
const cost = calculateCost(result.usage, 'claude-opus-4-7');
console.log(`本次运行成本: $${cost.toFixed(4)}`);来源:Claude Code Agent SDK 官方文档 | 整理:ClaudeEagle