Claude Agent SDK 完整开发指南
如果你使用过 Claude Code,你会发现 AI Agent 能够真正完成工作:读取文件、执行命令、编辑代码、分解任务步骤。它不仅帮助你编写代码,更像一位思考周密的工程师,能够接管问题并逐步解决。
Claude Agent SDK 是支撑 Claude Code 的同一引擎,现在开放给开发者使用。你可以用它构建自己的 Agent,解决任何你想解决的问题。
这是 Claude Code 背后的基础设施,以库的形式提供。你可以获得完整的 Agent 循环、内置工具、上下文管理等功能,基本上省去了所有你需要自己构建的部分。
本指南将从零开始构建一个代码审查 Agent。完成后,你将拥有一个能够分析代码库、发现 bug 和安全问题、返回结构化反馈的工具。
更重要的是,你将理解 SDK 的工作原理,从而能够构建任何你实际需要的东西。
我们要构建什么
我们的代码审查 Agent 将:
- 分析代码库中的 bug 和安全问题
- 自主读取文件和搜索代码
- 提供结构化、可操作的反馈
- 跟踪工作进度
技术栈
- 运行时 - Claude Code CLI
- SDK - @anthropic-ai/claude-agent-sdk
- 语言 - TypeScript
- 模型 - Claude Opus 4.5
SDK 提供的核心能力
如果你用过原始 API 构建 Agent,你会知道这个模式:调用模型,检查是否需要使用工具,执行工具,将结果反馈回去,重复直到完成。构建任何复杂功能时这会变得很繁琐。
SDK 处理了这个循环:
// 不使用 SDK:你需要管理循环
let response = await client.messages.create({...});
while (response.stop_reason === "tool_use") {
const result = yourToolExecutor(response.tool_use);
response = await client.messages.create({ tool_result: result, ... });
}
// 使用 SDK:Claude 管理它
for await (const message of query({ prompt: "Fix the bug in auth.py" })) {
console.log(message); // Claude 读取文件、发现 bug、编辑代码
}你还可以开箱即用地获得这些工具:
- Read - 读取工作目录中的任何文件
- Write - 创建新文件
- Edit - 对现有文件进行精确编辑
- Bash - 运行终端命令
- Glob - 按模式查找文件
- Grep - 用正则搜索文件内容
- WebSearch - 搜索网页
- WebFetch - 获取和解析网页
你不需要自己实现这些功能。
前置要求
- 安装 Node.js 18+
- Anthropic API 密钥(在这里获取)
开始使用
步骤 1:安装 Claude Code CLI
Agent SDK 使用 Claude Code 作为运行时:
npm install -g @anthropic-ai/claude-code安装后,在终端运行 claude 并按照提示进行身份验证。
步骤 2:创建项目
mkdir code-review-agent && cd code-review-agent
npm init -y
npm install @anthropic-ai/claude-agent-sdk
npm install -D typescript @types/node tsx步骤 3:设置 API 密钥
export ANTHROPIC_API_KEY=your-api-key你的第一个 Agent
创建 agent.ts:
import { query } from "@anthropic-ai/claude-agent-sdk";
async function main() {
for await (const message of query({
prompt: "What files are in this directory?",
options: {
model: "opus",
allowedTools: ["Glob", "Read"],
maxTurns: 250
}
})) {
if (message.type === "assistant") {
for (const block of message.message.content) {
if ("text" in block) {
console.log(block.text);
}
}
}
if (message.type === "result") {
console.log("\nDone:", message.subtype);
}
}
}
main();运行它:
npx tsx agent.tsClaude 将使用 Glob 工具列出文件并告诉你发现了什么。
理解消息流
query() 函数返回一个异步生成器,在 Claude 工作时流式传输消息。以下是关键消息类型:
for await (const message of query({ prompt: "..." })) {
switch (message.type) {
case "system":
// 会话初始化信息
if (message.subtype === "init") {
console.log("Session ID:", message.session_id);
console.log("Available tools:", message.tools);
}
break;
case "assistant":
// Claude 的响应和工具调用
for (const block of message.message.content) {
if ("text" in block) {
console.log("Claude:", block.text);
} else if ("name" in block) {
console.log("Tool call:", block.name);
}
}
break;
case "result":
// 最终结果
console.log("Status:", message.subtype); // "success" 或错误类型
console.log("Cost:", message.total_cost_usd);
break;
}
}构建代码审查 Agent
现在让我们构建一些实用的东西。创建 review-agent.ts:
import { query } from "@anthropic-ai/claude-agent-sdk";
async function reviewCode(directory: string) {
console.log(`\n🔍 Starting code review for: ${directory}\n`);
for await (const message of query({
prompt: `Review the code in ${directory} for:
1. Bugs and potential crashes
2. Security vulnerabilities
3. Performance issues
4. Code quality improvements
Be specific about file names and line numbers.`,
options: {
model: "opus",
allowedTools: ["Read", "Glob", "Grep"],
permissionMode: "bypassPermissions", // 自动批准读操作
maxTurns: 250
}
})) {
// 实时显示 Claude 的分析
if (message.type === "assistant") {
for (const block of message.message.content) {
if ("text" in block) {
console.log(block.text);
} else if ("name" in block) {
console.log(`\n📁 Using ${block.name}...`);
}
}
}
// 显示完成状态
if (message.type === "result") {
if (message.subtype === "success") {
console.log(`\n✅ Review complete! Cost: $${message.total_cost_usd.toFixed(4)}`);
} else {
console.log(`\n❌ Review failed: ${message.subtype}`);
}
}
}
}
// 审查当前目录
reviewCode(".");添加结构化输出
对于编程使用,你需要结构化数据。SDK 支持 JSON Schema 输出:
const reviewSchema = {
type: "object",
properties: {
issues: {
type: "array",
items: {
type: "object",
properties: {
severity: { type: "string", enum: ["low", "medium", "high", "critical"] },
category: { type: "string", enum: ["bug", "security", "performance", "style"] },
file: { type: "string" },
line: { type: "number" },
description: { type: "string" },
suggestion: { type: "string" }
},
required: ["severity", "category", "file", "description"]
}
},
summary: { type: "string" },
overallScore: { type: "number" }
},
required: ["issues", "summary", "overallScore"]
};
async function reviewCodeStructured(directory: string) {
for await (const message of query({
prompt: `Review the code in ${directory}. Identify all issues.`,
options: {
model: "opus",
allowedTools: ["Read", "Glob", "Grep"],
permissionMode: "bypassPermissions",
maxTurns: 250,
outputFormat: {
type: "json_schema",
schema: reviewSchema
}
}
})) {
if (message.type === "result" && message.subtype === "success") {
const review = message.structured_output;
// 处理结构化结果
console.log(`\n📊 Code Review Results\n`);
console.log(`Score: ${review.overallScore}/100`);
// ... 显示问题列表
}
}
}权限处理
默认情况下,SDK 在执行工具前会请求批准。你可以自定义:
权限模式
options: {
// 标准模式 - 提示批准
permissionMode: "default",
// 自动批准文件编辑
permissionMode: "acceptEdits",
// 无提示(谨慎使用)
permissionMode: "bypassPermissions"
}自定义权限处理器
对于细粒度控制,使用 canUseTool:
options: {
canUseTool: async (toolName, input) => {
// 允许所有读操作
if (["Read", "Glob", "Grep"].includes(toolName)) {
return { behavior: "allow", updatedInput: input };
}
// 阻止写入特定文件
if (toolName === "Write" && input.file_path?.includes(".env")) {
return { behavior: "deny", message: "Cannot modify .env files" };
}
return { behavior: "allow", updatedInput: input };
}
}创建子 Agent
对于复杂任务,你可以创建专门的子 Agent:
import { query, AgentDefinition } from "@anthropic-ai/claude-agent-sdk";
async function comprehensiveReview(directory: string) {
for await (const message of query({
prompt: `Perform a comprehensive code review of ${directory}.
Use the security-reviewer for security issues and test-analyzer for test coverage.`,
options: {
model: "opus",
allowedTools: ["Read", "Glob", "Grep", "Task"], // Task 启用子 Agent
permissionMode: "bypassPermissions",
maxTurns: 250,
agents: {
"security-reviewer": {
description: "Security specialist for vulnerability detection",
prompt: `You are a security expert. Focus on:
- SQL injection, XSS, CSRF vulnerabilities
- Exposed credentials and secrets
- Insecure data handling
- Authentication/authorization issues`,
tools: ["Read", "Grep", "Glob"],
model: "sonnet"
} as AgentDefinition
}
}
})) {
// 处理消息
}
}会话管理
对于多轮对话,捕获并恢复会话:
async function interactiveReview() {
let sessionId: string | undefined;
// 初始审查
for await (const message of query({
prompt: "Review this codebase and identify the top 3 issues",
options: {
model: "opus",
allowedTools: ["Read", "Glob", "Grep"],
maxTurns: 250
}
})) {
if (message.type === "system" && message.subtype === "init") {
sessionId = message.session_id;
}
}
// 使用同一会话的后续问题
if (sessionId) {
for await (const message of query({
prompt: "Now show me how to fix the most critical issue",
options: {
resume: sessionId, // 继续对话
allowedTools: ["Read", "Glob", "Grep"],
maxTurns: 250
}
})) {
// Claude 记住之前的上下文
}
}
}使用钩子
钩子让你拦截和自定义 Agent 行为:
import { HookCallback, PreToolUseHookInput } from "@anthropic-ai/claude-agent-sdk";
const auditLogger: HookCallback = async (input, toolUseId, { signal }) => {
if (input.hook_event_name === "PreToolUse") {
const preInput = input as PreToolUseHookInput;
console.log(`[AUDIT] ${new Date().toISOString()} - ${preInput.tool_name}`);
}
return {}; // 允许操作
};
const blockDangerousCommands: HookCallback = async (input, toolUseId, { signal }) => {
if (input.hook_event_name === "PreToolUse") {
const preInput = input as PreToolUseHookInput;
if (preInput.tool_name === "Bash") {
const command = (preInput.tool_input as any).command || "";
if (command.includes("rm -rf") || command.includes("sudo")) {
return {
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: "Dangerous command blocked"
}
};
}
}
}
return {};
};使用 MCP 添加自定义工具
通过 Model Context Protocol 扩展 Claude 的自定义工具:
import { tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";
// 创建自定义工具
const customServer = createSdkMcpServer({
name: "code-metrics",
version: "1.0.0",
tools: [
tool(
"analyze_complexity",
"Calculate cyclomatic complexity for a file",
{
filePath: z.string().describe("Path to the file to analyze")
},
async (args) => {
// 你的复杂度分析逻辑
const complexity = calculateComplexity(args.filePath);
return {
content: [{
type: "text",
text: `Cyclomatic complexity for ${args.filePath}: ${complexity}`
}]
};
}
)
]
});
// 使用自定义工具
for await (const message of query({
prompt: generateMessages(),
options: {
model: "opus",
mcpServers: {
"code-metrics": customServer
},
allowedTools: ["Read", "mcp__code-metrics__analyze_complexity"],
maxTurns: 250
}
})) {
// ...
}成本跟踪
跟踪 API 成本用于计费:
for await (const message of query({ prompt: "..." })) {
if (message.type === "result" && message.subtype === "success") {
console.log("Total cost:", message.total_cost_usd);
console.log("Token usage:", message.usage);
// 按模型细分(对子 Agent 很有用)
for (const [model, usage] of Object.entries(message.modelUsage)) {
console.log(`${model}: $${usage.costUSD.toFixed(4)}`);
}
}
}下一步
代码审查 Agent 涵盖了核心功能:query()、allowedTools、结构化输出、子 Agent 和权限管理。
如果你想深入了解:
更多功能
生产部署
完整参考
参考资料
本指南基于 SDK V1 版本。V2 目前正在开发中,稳定后将更新本指南。