Claude Code: Agent SDK
最后更新:2026-08-31
Agent SDK 把 Claude Code 的能力变成可编程的 API——在你的应用中嵌入 AI 编程能力,构建自定义的 AI 工作流。
💡 提示:Agent SDK 不是让 Claude Code 变成 API 服务器,而是提供一个 SDK 让你在代码中调用 Claude Code 的 Agent 能力——文件读写、代码生成、测试运行等。
📋 前置知识:第二十三章 Git 工作流与 GitHub Actions
1. 你将学到
- Agent SDK 的定位与架构
- SDK 安装与基本用法
- 核心 API 概览
- 自定义 Agent 构建
- SDK 与 CLI 的区别
2. Agent SDK 架构
(1) 定位
graph TB
A[你的应用] --> B[Agent SDK]
B --> C[Claude API]
B --> D[文件系统]
B --> E[Shell 执行]
B --> F[MCP 工具]
| 组件 | 说明 |
|---|---|
| Agent SDK | 编程接口,管理 Agent 生命周期 |
| Claude API | 底层 LLM 调用 |
| 工具系统 | 文件读写、Shell 执行等 |
| MCP | 可选的外部工具连接 |
(2) SDK vs CLI
| 维度 | CLI | SDK |
|---|---|---|
| 使用方式 | 终端命令 | 代码调用 |
| 交互 | 人机对话 | 编程接口 |
| 定制性 | 有限 | 完全可定制 |
| 集成 | 管道/脚本 | 深度嵌入 |
| 适用场景 | 日常开发 | 构建AI应用 |
▶ 示例 1: SDK 基本用法
TYPESCRIPT
import { Agent } from "@anthropic-ai/claude-code-sdk";
const agent = new Agent({
apiKey: process.env.ANTHROPIC_API_KEY,
model: "claude-sonnet-4-20250514",
workingDir: "./my-project",
});
const result = await agent.run("添加用户登录功能,包含 JWT 认证");
console.log(result.summary);
console.log(`Files modified: ${result.files.length}`);
console.log(`Tests passed: ${result.testsPassed}`);
3. 核心 API
(1) Agent 创建与配置
TYPESCRIPT
import { Agent, AgentConfig } from "@anthropic-ai/claude-code-sdk";
const config: AgentConfig = {
apiKey: "sk-ant-api03-xxxxx",
model: "claude-sonnet-4-20250514",
workingDir: "/path/to/project",
tools: ["Read", "Write", "Bash"],
maxTurns: 30,
style: "concise",
claudeMd: "./CLAUDE.md",
};
const agent = new Agent(config);
(2) 执行任务
TYPESCRIPT
// 基本执行
const result = await agent.run("修复所有 TypeScript 错误");
// 流式执行
const stream = agent.runStream("重构认证模块");
for await (const event of stream) {
console.log(event.type, event.data);
}
// 带上下文执行
const result = await agent.run("修改这个函数", {
files: ["src/auth/jwt.ts"],
context: "使用 RS256 算法替代 HS256",
});
(3) 结果处理
TYPESCRIPT
interface AgentResult {
summary: string;
files: FileChange[];
commands: CommandResult[];
testsPassed: number;
testsFailed: number;
tokensUsed: number;
cost: number;
duration: number;
}
// 处理结果
const result = await agent.run("添加用户搜索功能");
if (result.testsFailed > 0) {
console.log("有测试失败,需要修复");
const fixResult = await agent.run("修复失败的测试");
}
▶ 示例 2: 自定义工作流
TYPESCRIPT
// 自动代码审查 + 修复工作流
async function reviewAndFix(projectDir: string) {
const agent = new Agent({
apiKey: process.env.ANTHROPIC_API_KEY!,
workingDir: projectDir,
tools: ["Read", "Write", "Bash"],
});
// Step 1: 代码审查
const review = await agent.run(
"审查项目代码质量,列出所有需要修复的问题"
);
console.log("审查结果:", review.summary);
// Step 2: 自动修复
if (review.summary.includes("问题")) {
const fix = await agent.run(
"修复所有列出的代码质量问题,运行测试确认修复成功"
);
console.log("修复结果:", fix.summary);
console.log(`测试: ${fix.testsPassed} passed, ${fix.testsFailed} failed`);
}
}
4. 自定义 Agent
(1) 自定义工具
TYPESCRIPT
import { Agent, Tool } from "@anthropic-ai/claude-code-sdk";
const databaseQueryTool: Tool = {
name: "database_query",
description: "Execute a read-only SQL query on the database",
parameters: {
sql: { type: "string", description: "SQL query (SELECT only)" },
},
execute: async ({ sql }) => {
if (!sql.trim().toUpperCase().startsWith("SELECT")) {
throw new Error("Only SELECT queries are allowed");
}
const result = await db.query(sql);
return { rows: result.rows, count: result.rowCount };
},
};
const agent = new Agent({
apiKey: process.env.ANTHROPIC_API_KEY!,
tools: ["Read", "Write", databaseQueryTool],
});
(2) 事件监听
TYPESCRIPT
const agent = new Agent(config);
agent.on("file:read", (data) => {
console.log(`读取: ${data.filePath}`);
});
agent.on("file:write", (data) => {
console.log(`修改: ${data.filePath}`);
auditLog.record(data);
});
agent.on("bash:execute", (data) => {
console.log(`执行: ${data.command}`);
if (data.command.includes("DROP")) {
throw new Error("危险命令被拦截");
}
});
agent.on("complete", (result) => {
console.log(`完成: ${result.summary}`);
console.log(`Token: ${result.tokensUsed}, 费用: $${result.cost}`);
});
▶ 示例 3: 构建代码审查机器人
TYPESCRIPT
import { Agent } from "@anthropic-ai/claude-code-sdk";
class CodeReviewBot {
private agent: Agent;
constructor(apiKey: string) {
this.agent = new Agent({
apiKey,
model: "claude-sonnet-4-20250514",
tools: ["Read", "Bash"],
maxTurns: 15,
});
}
async reviewPR(repoDir: string, prDiff: string) {
this.agent.setWorkingDir(repoDir);
const result = await this.agent.run(
`审查以下 PR 变更:\n${prDiff}\n\n检查:
1. 安全漏洞
2. 性能问题
3. 代码风格
4. 缺失的测试
输出结构化报告`
);
return {
security: this.extractSection(result.summary, "安全"),
performance: this.extractSection(result.summary, "性能"),
style: this.extractSection(result.summary, "风格"),
testing: this.extractSection(result.summary, "测试"),
overallScore: this.calculateScore(result.summary),
};
}
private extractSection(text: string, keyword: string): string {
const regex = new RegExp(`${keyword}[::](.+?)(?=\\n\\n|$)`, "s");
const match = text.match(regex);
return match ? match[1].trim() : "No issues found";
}
private calculateScore(text: string): number {
let score = 100;
if (text.includes("严重")) score -= 30;
if (text.includes("警告")) score -= 10;
if (text.includes("建议")) score -= 5;
return Math.max(0, score);
}
}
// 使用
const bot = new CodeReviewBot(process.env.ANTHROPIC_API_KEY!);
const report = await bot.reviewPR("./my-repo", diffContent);
console.log(`审查评分: ${report.overallScore}/100`);
5. SDK 与 CLI 协作
(1) 场景选择
| 场景 | CLI | SDK |
|---|---|---|
| 日常开发 | ✅ | ❌ |
| CI/CD | ✅ (headless) | ✅ |
| 自定义工具 | ❌ | ✅ |
| Web 应用集成 | ❌ | ✅ |
| 批量自动化 | ⚠️ (脚本) | ✅ |
(2) 混合使用
BASH
# CLI 做日常开发
claude "重构这个模块"
# SDK 做自动化
node scripts/auto-review.ts
# SDK 生成 CLAUDE.md
# CLI 使用生成的 CLAUDE.md
❓ 常见问题
Q SDK 需要单独安装 Claude Code CLI 吗?
A 不需要。SDK 是独立的 npm 包,不依赖 CLI。但两者共用同一个 API Key。
Q SDK 的 API 稳定吗?
A 核心 API 稳定,但细节可能随版本变化。建议锁定版本号,关注 changelog。
Q SDK 能在浏览器中运行吗?
A 不能。SDK 需要 Node.js 环境,涉及文件系统和 Shell 操作,浏览器不支持。
Q SDK 调用费用和 CLI 一样吗?
A 一样。底层都是调用 Anthropic API,计费标准相同。
Q 如何调试 SDK 调用?
A 启用 debug 模式:
const agent = new Agent({ ..., debug: true })。查看详细日志。Q SDK 支持多 Agent 协作吗?
A 支持。可以创建多个 Agent 实例,每个负责不同任务。但需要自行协调。
📖 小节
- Agent SDK 提供编程接口,在代码中调用 Claude Code 能力
- 核心 API:创建 Agent、执行任务、处理结果、事件监听
- 可自定义工具、监听事件、构建完整工作流
- CLI 适合日常开发,SDK 适合自定义应用和深度集成
- 两者共用 API Key 和计费标准
📝 作业
- 基础题(难度⭐):用 SDK 创建一个 Agent,执行简单任务并打印结果。
- 进阶题(难度⭐⭐):用 SDK 构建一个自动代码审查脚本,输出结构化报告。
- 挑战题(难度⭐⭐⭐):用 SDK 构建一个完整的代码审查机器人,集成到 GitHub Webhook,自动审查新 PR。