Claude Code SDK 入门:Agent SDK 详解
从安装到调用,系统学习 Claude Code Agent SDK 的核心能力
什么是 Claude Code SDK
Claude Code 不仅是一个 CLI 工具,它还提供了 SDK(Software Development Kit),让我们可以在自己的程序中调用 Claude Code 的能力。
简单来说:
- CLI 模式:你在终端里和 Claude Code 对话
- SDK 模式:你的代码和 Claude Code 对话
这意味着我们可以构建自动化工具、CI 集成、自定义 IDE 插件,甚至是完整的 AI 驱动的开发平台。
安装
前置条件
- Node.js 18+
- Claude Code CLI 已安装并认证
- TypeScript(推荐)
安装 SDK
npm install @anthropic-ai/claude-code
验证安装
import { claude } from "@anthropic-ai/claude-code";
async function main() {
const result = await claude("你好,Claude Code!");
console.log(result);
}
main();
运行:
npx tsx test.ts
如果看到 Claude 的回复,说明安装成功。
基础用法
最简单的调用
import { claude } from "@anthropic-ai/claude-code";
// 发送一条消息,获取回复
const response = await claude("解释一下 TypeScript 的 infer 关键字");
console.log(response.text);
带选项的调用
import { claude } from "@anthropic-ai/claude-code";
const response = await claude("重构这个函数", {
// 工作目录
cwd: "/path/to/project",
// 允许的工具
allowedTools: ["Read", "Write", "Edit", "Bash"],
// 最大 Token 数
maxTokens: 4096,
// 系统提示
systemPrompt: "你是一个专注于代码质量的助手",
// 超时时间(毫秒)
timeout: 60000,
});
console.log(response.text);
console.log(response.usage); // Token 使用统计
指定工作目录
SDK 默认使用当前进程的工作目录。在自动化场景中,我们通常需要指定项目路径:
const response = await claude("运行测试并报告结果", {
cwd: "/home/user/projects/my-app",
});
对话管理
多轮对话
Claude Code SDK 支持多轮对话,保持上下文连贯:
import { claude, Conversation } from "@anthropic-ai/claude-code";
// 创建对话
const conversation = new Conversation({
cwd: "/path/to/project",
});
// 第一轮
const r1 = await conversation.send("读取 src/utils/format.ts 的内容");
console.log(r1.text);
// 第二轮(Claude 记得之前读取的文件)
const r2 = await conversation.send("给这个文件添加单元测试");
console.log(r2.text);
// 第三轮
const r3 = await conversation.send("运行测试确认通过");
console.log(r3.text);
// 结束对话
await conversation.close();
对话选项
const conversation = new Conversation({
cwd: "/path/to/project",
systemPrompt: "你是一个代码审查专家,关注安全和性能",
allowedTools: ["Read", "Grep", "Glob"],
maxTurns: 10, // 最大对话轮数
});
对话历史
// 获取对话历史
const history = conversation.getHistory();
for (const message of history) {
console.log(`[${message.role}] ${message.content}`);
}
工具访问控制
SDK 允许我们精确控制 Claude Code 可以使用哪些工具:
工具列表
| 工具 | 说明 | 风险等级 |
|---|---|---|
| Read | 读取文件 | 低 |
| Glob | 文件搜索 | 低 |
| Grep | 内容搜索 | 低 |
| Write | 写入文件 | 中 |
| Edit | 编辑文件 | 中 |
| Bash | 执行命令 | 高 |
| WebFetch | 网络请求 | 中 |
只读模式
// 只允许读取操作,适合代码审查场景
const response = await claude("审查 src/ 目录下的代码质量", {
allowedTools: ["Read", "Glob", "Grep"],
});
完全控制模式
// 允许所有操作,适合自动化修复场景
const response = await claude("修复所有 ESLint 错误", {
allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"],
permissions: {
allow: [
"Bash(npx eslint *)",
"Bash(npx prettier *)",
],
deny: [
"Bash(rm *)",
"Bash(git push *)",
],
},
});
流式输出
对于长时间运行的任务,流式输出可以实时显示进度:
基础流式输出
import { claude } from "@anthropic-ai/claude-code";
const stream = claude.stream("分析整个项目的架构", {
cwd: "/path/to/project",
});
for await (const event of stream) {
switch (event.type) {
case "text":
process.stdout.write(event.content);
break;
case "tool_use":
console.log(`\n[使用工具: ${event.tool}]`);
break;
case "tool_result":
console.log(`[工具结果: ${event.tool}]\n`);
break;
case "error":
console.error(`错误: ${event.message}`);
break;
}
}
带进度回调的调用
const response = await claude("重构所有组件", {
cwd: "/path/to/project",
onProgress: (event) => {
if (event.type === "tool_use") {
console.log(`正在使用 ${event.tool}: ${event.input?.file_path || ""}`);
}
},
});
错误处理
常见错误类型
import { claude, ClaudeError, TimeoutError, AuthError } from "@anthropic-ai/claude-code";
try {
const response = await claude("执行任务", {
timeout: 30000,
});
console.log(response.text);
} catch (error) {
if (error instanceof TimeoutError) {
console.error("任务超时,考虑增加 timeout 或简化任务");
} else if (error instanceof AuthError) {
console.error("认证失败,请检查 API Key 或重新登录");
} else if (error instanceof ClaudeError) {
console.error(`Claude Code 错误: ${error.message}`);
console.error(`错误码: ${error.code}`);
} else {
console.error("未知错误:", error);
}
}
重试策略
async function withRetry<T>(
fn: () => Promise<T>,
maxRetries: number = 3,
delay: number = 1000
): Promise<T> {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
if (i === maxRetries - 1) throw error;
console.log(`重试 ${i + 1}/${maxRetries}...`);
await new Promise((r) => setTimeout(r, delay * (i + 1)));
}
}
throw new Error("不应该到达这里");
}
const response = await withRetry(() =>
claude("执行可能失败的任务", { timeout: 30000 })
);
TypeScript 类型
SDK 提供了完整的 TypeScript 类型定义:
核心类型
import type {
ClaudeResponse,
ClaudeOptions,
ConversationOptions,
StreamEvent,
ToolUseEvent,
TextEvent,
Usage,
} from "@anthropic-ai/claude-code";
// ClaudeResponse
interface ClaudeResponse {
text: string;
usage: Usage;
toolCalls: ToolCall[];
duration: number;
}
// Usage
interface Usage {
inputTokens: number;
outputTokens: number;
totalTokens: number;
}
// ClaudeOptions
interface ClaudeOptions {
cwd?: string;
allowedTools?: string[];
permissions?: Permissions;
systemPrompt?: string;
maxTokens?: number;
timeout?: number;
onProgress?: (event: StreamEvent) => void;
}
自定义类型扩展
// 为特定场景创建类型化的封装
interface CodeReviewResult {
issues: Array<{
file: string;
line: number;
severity: "error" | "warning" | "info";
message: string;
}>;
summary: string;
score: number;
}
async function reviewCode(projectPath: string): Promise<CodeReviewResult> {
const response = await claude(
`审查项目代码,以 JSON 格式返回结果,包含 issues 数组(每个 issue 有 file, line, severity, message)、summary 和 score(1-10)`,
{
cwd: projectPath,
allowedTools: ["Read", "Glob", "Grep"],
}
);
return JSON.parse(response.text);
}
实战示例
示例 1:自动化代码审查工具
import { claude } from "@anthropic-ai/claude-code";
import { execSync } from "child_process";
async function reviewPR(prNumber: number) {
// 获取 PR 变更的文件
const diffOutput = execSync(
`gh pr diff ${prNumber} --name-only`
).toString();
const changedFiles = diffOutput.trim().split("\n");
console.log(`审查 PR #${prNumber},共 ${changedFiles.length} 个文件变更`);
const response = await claude(
`请审查以下文件的变更,关注:
1. 代码质量和可读性
2. 潜在的 Bug
3. 性能问题
4. 安全隐患
变更的文件:${changedFiles.join(", ")}
请给出具体的改进建议。`,
{
cwd: process.cwd(),
allowedTools: ["Read", "Glob", "Grep"],
}
);
return response.text;
}
// 使用
const review = await reviewPR(42);
console.log(review);
示例 2:批量文件处理
import { claude } from "@anthropic-ai/claude-code";
import { glob } from "glob";
async function addJSDocToFiles(pattern: string) {
const files = await glob(pattern);
for (const file of files) {
console.log(`处理: ${file}`);
try {
await claude(
`给 ${file} 中所有导出的函数添加 JSDoc 注释。
保持现有代码不变,只添加缺失的 JSDoc。`,
{
cwd: process.cwd(),
allowedTools: ["Read", "Edit"],
timeout: 30000,
}
);
console.log(`完成: ${file}`);
} catch (error) {
console.error(`失败: ${file}`, error);
}
}
}
// 使用
await addJSDocToFiles("src/utils/**/*.ts");
示例 3:智能测试生成器
import { claude, Conversation } from "@anthropic-ai/claude-code";
async function generateTests(sourceFile: string) {
const conversation = new Conversation({
cwd: process.cwd(),
systemPrompt: `你是一个测试专家。生成的测试应该:
- 使用 Vitest 框架
- 覆盖正常路径和边界情况
- 使用 describe/it 结构
- Mock 外部依赖`,
});
// 第一步:分析源文件
const analysis = await conversation.send(
`分析 ${sourceFile},列出所有需要测试的函数和它们的行为`
);
console.log("分析完成:", analysis.text);
// 第二步:生成测试
const tests = await conversation.send(
`基于分析结果,生成完整的测试文件`
);
console.log("测试生成完成");
// 第三步:运行测试
const result = await conversation.send(
`运行生成的测试,如果有失败的,修复它们`
);
console.log("测试验证:", result.text);
await conversation.close();
}
// 使用
await generateTests("src/utils/format.ts");
配置与环境变量
环境变量
| 变量 | 说明 | 默认值 |
|---|---|---|
| ANTHROPIC_API_KEY | API 密钥 | 从 CLI 认证继承 |
| CLAUDE_CODE_MODEL | 使用的模型 | claude-sonnet-4-20250514 |
| CLAUDE_CODE_MAX_TOKENS | 最大输出 Token | 4096 |
编程式配置
import { configure } from "@anthropic-ai/claude-code";
// 全局配置
configure({
model: "claude-sonnet-4-20250514",
maxTokens: 8192,
timeout: 120000,
defaultTools: ["Read", "Glob", "Grep"],
});
最佳实践
1. 始终设置超时
// 不好:没有超时,可能无限等待
await claude("复杂任务");
// 好:设置合理的超时
await claude("复杂任务", { timeout: 60000 });
2. 最小权限原则
// 不好:给所有权限
await claude("读取文件", { allowedTools: ["Read", "Write", "Edit", "Bash"] });
// 好:只给需要的权限
await claude("读取文件", { allowedTools: ["Read"] });
3. 结构化输出
// 不好:自由文本输出,难以解析
const response = await claude("列出所有 TODO");
// 好:要求 JSON 格式输出
const response = await claude(
"列出所有 TODO,以 JSON 数组格式返回,每项包含 file, line, content 字段"
);
const todos = JSON.parse(response.text);
4. 资源清理
const conversation = new Conversation({ cwd: "/path" });
try {
await conversation.send("任务 1");
await conversation.send("任务 2");
} finally {
// 始终关闭对话,释放资源
await conversation.close();
}
SDK 是 Claude Code 从”个人工具”进化为”团队基础设施”的关键。掌握了它,你就能把 AI 编码能力嵌入到任何工作流中——从 CI/CD 到自定义 IDE,从代码审查到自动化测试,可能性是无限的。
相关文章
评论
加载中...
评论
加载中...