教程

Claude Code Agent SDK 完整开发指南:构建自定义 AI Agent 工作流

Claude Code Agent SDK 完整开发指南:TypeScript/Python 两种 SDK 用法;四种权限模式(只读/Auto/完全权限/自定义白名单);流式响应实时接收输出;自定义工具注入(queryDatabase/sendSlackNotification 示例);多 Agent 编排(主 Agent + 并行子 Agent);GitHub Actions CI/CD 集成;错误处理和指数退避重试;成本监控(按模型计价)。

2026/5/36分钟 阅读ClaudeEagle

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

相关文章推荐

教程Claude Code 程序化调用完全指南:-p 标志、结构化输出、流式响应与会话续接Claude Code 程序化调用完全指南:-p/--print 非交互模式基础用法、三种输出格式(text/json/stream-json)、按 JSON Schema 提取结构化数据(structured_output 字段)、jq 解析响应、流式响应(stream-json + --verbose + --include-partial-messages + jq -rj 过滤 text_delta)、--allowedTools 自动批准工具(权限规则语法/末尾空格注意事项)、自动创建 Commit 示例、--append-system-prompt/--system-prompt 系统提示词、--continue/--resume 会话续接(Session ID 捕获)、GitHub Actions CI/CD 集成,以及 Python/TypeScript Agent SDK 高级用法入口。2026/3/8教程Claude Code 无头模式与 Agent SDK:非交互式脚本、CI/CD 集成完全指南Claude Code 无头模式与 Agent SDK 完全指南:-p 参数基础用法、三种输出格式(text/json/stream-json)、JSON Schema 结构化输出、精细工具权限控制、多轮对话 Session 管理,以及 GitHub Actions PR 安全审查和批量处理的 CI/CD 实战场景。2026/3/2教程Claude Code 与 GitHub Actions 集成完全指南:CI/CD 自动化的 5 个实用模式Claude Code 整合 GitHub Actions 的 5 个完整可用模式:PR 自动代码审查(触发+评论)、空 PR 自动生成描述、测试覆盖率分析和建议、安全扫描(发现 Critical 问题阻断合并)、变更日志自动生成。每个模式含完整 YAML 配置,以及 API Key 安全管理和成本控制建议。2026/4/24教程Claude Code GitHub Actions 实战:用 @claude 让 AI 自动修 bug、实现功能、生成 PRClaude Code GitHub Actions 实战教程:配置 @claude 命令触发 AI 自动修 bug、实现功能、生成 PR。含 2 步快速配置、3 个工作流示例、安全设置和常见问题排查。2026/4/9教程Claude Code + GitHub Actions:自动化代码审查与 CI/CD 集成完全指南Claude Code GitHub Actions 完整配置指南:5 分钟快速安装(GitHub App + API Key Secret + Workflow 文件)、四大使用场景(按需 PR 审查/Issue 自动实现/快速修复/自动 Changelog)、每 PR 自动触发审查配置、高级参数(模型/轮数/工具限制/AWS Bedrock)与安全最佳实践。2026/3/13教程Claude Code GitHub Actions 集成指南:让 AI 自动化你的 CI/CD 流水线Claude Code GitHub Actions 让 AI 融入 GitHub 工作流,支持通过 @claude 提及触发代码审查、自动创建 PR 和修复 Bug。本文涵盖快速安装、手动配置、Beta 到 v1.0 升级指南、实用工作流示例(PR 审查、Issue 自动修复)以及 AWS Bedrock/Google Vertex AI 集成方案。2026/2/27