返回资料库 Claude Code 专题

Claude Agent SDK:用代码构建 AI Agent 应用

Claude Agent SDK 是 Anthropic 推出的编程式 Agent 开发接口,让你可以用 Python 或 TypeScript 代码调用 Claude Code 的全部能力——包括代码理解、文件编辑、命令执行、多 Agent 协作等。

来源:platform.claude.com/agent-sdk · docs.anthropic.com/sdk · npm @anthropic-ai/claude-code | 整理时间:2026-04-07


Claude Agent SDK 是什么?

Claude Agent SDK 是 Anthropic 推出的编程式 Agent 开发接口,让你可以用 Python 或 TypeScript 代码调用 Claude Code 的全部能力——包括代码理解、文件编辑、命令执行、多 Agent 协作等。

SDK 的两种形态

SDK 包名 语言 定位
Claude Code SDK @anthropic-ai/claude-code TypeScript/Python 较成熟,将 Claude Code 作为子进程运行
Claude Agent SDK claude-agent-sdk (PyPI) / @anthropic-ai/claude-code (npm) Python/TypeScript 更新,提供原生 query() API

Agent SDK 是 Claude Code SDK 的演进方向,提供更原生的编程接口。

CLI vs SDK 对比

维度 Claude Code CLI Agent SDK
交互方式 终端对话 编程 API
集成方式 独立工具 嵌入到应用代码
输出控制 终端显示 JSON / 流式
权限管理 用户手动批准 程序化控制
适用场景 日常编码 构建 AI 应用

安装与配置

1. 安装 CLI(前置条件)

# macOS / Linux
curl -fsSL https://claude.ai/install.sh | sh

# 或 Homebrew
brew install claude

2. 安装 SDK

# Python
pip install claude-agent-sdk

# TypeScript
npm install @anthropic-ai/claude-code

3. 认证方式(四选一)

方式 环境变量 说明
Anthropic API Key ANTHROPIC_API_KEY 直连 Anthropic API
Amazon Bedrock CLAUDE_CODE_USE_BEDROCK=1 通过 AWS Bedrock
Google Vertex AI CLAUDE_CODE_USE_VERTEX=1 通过 Google Cloud
Azure AI Foundry Azure 配置 通过 Azure
export ANTHROPIC_API_KEY="sk-ant-..."

核心 API:query() 函数

query() 是 Agent SDK 的核心接口,接收提示词和配置选项,返回流式消息。

TypeScript 接口

import { query } from "@anthropic-ai/claude-code";

const result = await query({
  prompt: string,
  options: {
    allowedTools?: string[],      // 允许的工具白名单
    disallowedTools?: string[],   // 禁止的工具黑名单
    maxTurns?: number,            // 最大执行轮次
    systemPrompt?: string,        // 自定义系统提示
    appendSystemPrompt?: string,  // 追加系统提示
    cwd?: string,                 // 工作目录
    abortController?: AbortController,  // 中断控制
  }
});

Python 接口

from claude_agent_sdk import query, ClaudeAgentOptions

async for message in query(
    prompt="分析项目结构",
    options=ClaudeAgentOptions(
        allowed_tools=["Read", "Glob"],
    ),
):
    print(message)

内置工具

工具 功能
Read 读取文件内容
Edit 编辑文件
Bash 执行 Shell 命令
Glob 文件模式搜索
Grep 内容搜索
Write 创建/覆写文件

实战示例

示例 1:代码审查 Agent(TypeScript)

import { query } from "@anthropic-ai/claude-code";

async function reviewCode(projectPath: string) {
  const messages = await query({
    prompt: "审查这个项目的代码质量,找出潜在 bug 和改进点",
    options: {
      allowedTools: ["Read", "Glob", "Grep"],
      maxTurns: 20,
      systemPrompt: "你是一位资深代码审查专家。输出结构化的审查报告。",
      cwd: projectPath,
    },
  });

  for (const msg of messages) {
    if (msg.type === "result") {
      console.log(msg.result);
    }
  }
}

reviewCode("/path/to/project");

示例 2:自动化修复 Agent(Python)

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def fix_bugs():
    async for message in query(
        prompt="找出并修复 auth.py 中的安全漏洞",
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Edit", "Bash", "Glob"],
        ),
    ):
        if hasattr(message, "result"):
            print(f"修复完成: {message.result}")
        elif hasattr(message, "tool_use"):
            print(f"正在执行: {message.tool_use}")

asyncio.run(fix_bugs())

示例 3:多步骤文档生成

import { query } from "@anthropic-ai/claude-code";

async function generateDocs(repoPath: string) {
  // 步骤 1:分析项目结构
  const analysis = await query({
    prompt: "分析这个项目的架构,列出所有公开 API",
    options: { allowedTools: ["Read", "Glob"], cwd: repoPath },
  });

  // 步骤 2:生成文档
  const apiSummary = analysis
    .filter((m) => m.type === "result")
    .map((m) => m.result)
    .join("\n");

  const docs = await query({
    prompt: `根据以下 API 分析结果,生成 API 文档:\n\n${apiSummary}`,
    options: { allowedTools: ["Write"], cwd: repoPath },
  });

  return docs;
}

高级功能

权限控制

// 白名单模式:只允许读取和搜索
const result = await query({
  prompt: "分析代码",
  options: {
    allowedTools: ["Read", "Glob", "Grep"],
  },
});

// 黑名单模式:禁止执行命令
const result = await query({
  prompt: "重构代码",
  options: {
    disallowedTools: ["Bash"],
  },
});

流式输出

# CLI 流式 JSON 输出
echo '{"prompt":"分析项目"}' | claude --output-format stream-json
// SDK 流式处理
const messages = await query({
  prompt: "重构认证模块",
  options: { maxTurns: 10 },
});

for (const msg of messages) {
  switch (msg.type) {
    case "assistant":
      console.log("Claude:", msg.content);
      break;
    case "tool_use":
      console.log("工具调用:", msg.name, msg.input);
      break;
    case "result":
      console.log("结果:", msg.result);
      break;
  }
}

MCP 服务器集成

const result = await query({
  prompt: "查询数据库中的用户列表",
  options: {
    settingSources: {
      "db-server": {
        command: "npx",
        args: ["-y", "@modelcontextprotocol/server-postgres"],
        env: { DATABASE_URL: "postgresql://..." },
      },
    },
  },
});

典型应用场景

场景 说明 推荐工具
代码审查 CI PR 提交时自动审查 Read, Glob
自动化测试生成 为新代码生成测试 Read, Write, Bash
文档自动更新 代码变更时更新文档 Read, Glob, Write
安全扫描 检测安全漏洞 Read, Grep
代码迁移 批量重构和迁移 Read, Edit, Glob

相关链接

常见问题

Claude Agent SDK:用代码构建 AI Agent 应用 适合什么读者?

Claude Agent SDK:用代码构建 AI Agent 应用 适合希望系统掌握 Claude Code 专题 的读者,尤其是需要从概念快速过渡到实践的人。页面包含主题摘要、相关阅读和来源链接,便于形成可执行的学习路径。

阅读 Claude Agent SDK:用代码构建 AI Agent 应用 需要多久?

当前页面预估阅读时长约 8 分钟。建议先读正文结论,再根据“同专题延伸”继续阅读,通常 20 到 40 分钟可以建立完整主题框架。

如何把 Claude Agent SDK:用代码构建 AI Agent 应用 的内容用于实际项目?

先按正文中的关键概念完成最小可运行示例,再把示例嵌入你当前项目流程。你可以结合来源链接验证细节,并使用同专题文章补齐部署、协作和评估步骤。