Skip to content

Claude Code Agent SDK 让你用 Python 或 TypeScript 构建能自主读文件、运行命令、搜索网页、编辑代码的 AI 代理,无需自己实现工具循环。安装后设置 ANTHROPIC_API_KEY 环境变量即可使用,也支持通过 Amazon Bedrock、Google Vertex AI 等第三方提供商认证。SDK 内置 Read、Edit、Bash、Glob、Grep 等工具,可通过 allowed_tools 控制权限,通过 hooks 拦截工具执行,通过子代理拆分复杂任务,通过 MCP 连接外部系统。

Claude Code Agent SDK 快速配置与能力概览

用 Claude Code 作为库来构建生产级 AI 代理

2026年6月15日起,订阅套餐中 Agent SDK 和 claude -p 的使用将计入新的月度 Agent SDK 配额,与交互使用限制分开。详情见如何在 Claude 套餐中使用 Claude Agent SDK

构建能够自主读文件、运行命令、搜索网页、编辑代码等的 AI 代理。Agent SDK 提供与 Claude Code 相同的工具、代理循环和上下文管理,可用 Python 和 TypeScript 编程。

python
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    async for message in query(
        prompt="Find and fix the bug in auth.py",
        options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"]),
    ):
        print(message)  # Claude 读取文件、找到 bug、编辑修复

asyncio.run(main())
typescript
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Find and fix the bug in auth.ts",
  options: { allowedTools: ["Read", "Edit", "Bash"] }
})) {
  console.log(message); // Claude 读取文件、找到 bug、编辑修复
}

Agent SDK 内置读取文件、运行命令和编辑代码的工具,所以你的代理可以立即开始工作,无需你实现工具执行。快速入门或浏览基于 SDK 构建的真实代理:

快速开始

安装

bash
npm install @anthropic-ai/claude-agent-sdk
bash
pip install claude-agent-sdk

TypeScript SDK 会将针对你平台的 Claude Code 原生二进制文件作为可选依赖打包,因此无需单独安装 Claude Code。

认证

Console 获取 API 密钥,然后设置为环境变量:

bash
export ANTHROPIC_API_KEY=your-api-key

SDK 还支持通过第三方 API 提供商认证:

  • Amazon Bedrock:设置 CLAUDE_CODE_USE_BEDROCK=1 环境变量并配置 AWS 凭证
  • Claude Platform on AWS:设置 CLAUDE_CODE_USE_ANTHROPIC_AWS=1ANTHROPIC_AWS_WORKSPACE_ID,然后配置 AWS 凭证
  • Google Vertex AI:设置 CLAUDE_CODE_USE_VERTEX=1 环境变量并配置 Google Cloud 凭证
  • Microsoft Azure:设置 CLAUDE_CODE_USE_FOUNDRY=1 环境变量并配置 Azure 凭证

详细设置见 Bedrock 指南Claude Platform on AWS 指南Vertex AI 指南Azure AI Foundry 指南

除非事先获得批准,Anthropic 不允许第三方开发者在其产品(包括基于 Claude Agent SDK 构建的代理)中提供 claude.ai 登录或速率限制。请使用本文档中描述的 API 密钥认证方法。

第一个例子

创建一个列出当前目录文件的代理:

python
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    async for message in query(
        prompt="What files are in this directory?",
        options=ClaudeAgentOptions(allowed_tools=["Bash", "Glob"]),
    ):
        if hasattr(message, "result"):
            print(message.result)

asyncio.run(main())
typescript
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "What files are in this directory?",
  options: { allowedTools: ["Bash", "Glob"] }
})) {
  if ("result" in message) console.log(message.result);
}

准备好构建了吗? 跟随快速入门创建一个能找出并修复 bug 的代理,只需几分钟。

能力

Claude Code 的所有强大功能在 SDK 中均可使用:

内置工具

你的代理开箱即可读文件、运行命令、搜索代码库。关键工具包括:

工具作用
Read读取工作目录中的任何文件
Write创建新文件
Edit对现有文件进行精确编辑
Bash运行终端命令、脚本、git 操作
Monitor监视后台脚本,对每一行输出作为事件做出反应
Glob按模式查找文件(**/*.tssrc/**/*.py
Grep使用正则搜索文件内容
WebSearch搜索网络获取最新信息
WebFetch获取并解析网页内容
AskUserQuestion向用户提出带有多个选项的澄清问题

此示例创建一个搜索代码库中 TODO 注释的代理:

python
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    async for message in query(
        prompt="Find all TODO comments and create a summary",
        options=ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep"]),
    ):
        if hasattr(message, "result"):
            print(message.result)

asyncio.run(main())
typescript
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Find all TODO comments and create a summary",
  options: { allowedTools: ["Read", "Glob", "Grep"] }
})) {
  if ("result" in message) console.log(message.result);
}

Hooks(钩子)

在代理生命周期的关键点运行自定义代码。SDK 钩子使用回调函数来验证、记录、阻止或转换代理行为。

可用钩子:PreToolUsePostToolUseStopSessionStartSessionEndUserPromptSubmit 等。

此示例将所有文件更改记录到审计文件:

python
import asyncio
from datetime import datetime
from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher

async def log_file_change(input_data, tool_use_id, context):
    file_path = input_data.get("tool_input", {}).get("file_path", "unknown")
    with open("./audit.log", "a") as f:
        f.write(f"{datetime.now()}: modified {file_path}\n")
    return {}

async def main():
    async for message in query(
        prompt="Refactor utils.py to improve readability",
        options=ClaudeAgentOptions(
            permission_mode="acceptEdits",
            hooks={
                "PostToolUse": [
                    HookMatcher(matcher="Edit|Write", hooks=[log_file_change])
                ]
            },
        ),
    ):
        if hasattr(message, "result"):
            print(message.result)

asyncio.run(main())
typescript
import { query, HookCallback } from "@anthropic-ai/claude-agent-sdk";
import { appendFile } from "fs/promises";

const logFileChange: HookCallback = async (input) => {
  const filePath = (input as any).tool_input?.file_path ?? "unknown";
  await appendFile("./audit.log", `${new Date().toISOString()}: modified ${filePath}\n`);
  return {};
};

for await (const message of query({
  prompt: "Refactor utils.py to improve readability",
  options: {
    permissionMode: "acceptEdits",
    hooks: {
      PostToolUse: [{ matcher: "Edit|Write", hooks: [logFileChange] }]
    }
  }
})) {
  if ("result" in message) console.log(message.result);
}

了解更多关于 hooks →

子代理(Sub-agents)

生成专门处理子任务的代理。主代理委派工作,子代理报告结果。

使用专门的指令定义自定义代理。在 allowed_tools 中包含 Agent,因为子代理是通过 Agent 工具调用的:

python
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

async def main():
    async for message in query(
        prompt="Use the code-reviewer agent to review this codebase",
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Glob", "Grep", "Agent"],
            agents={
                "code-reviewer": AgentDefinition(
                    description="Expert code reviewer for quality and security reviews.",
                    prompt="Analyze code quality and suggest improvements.",
                    tools=["Read", "Glob", "Grep"],
                )
            },
        ),
    ):
        if hasattr(message, "result"):
            print(message.result)

asyncio.run(main())
typescript
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Use the code-reviewer agent to review this codebase",
  options: {
    allowedTools: ["Read", "Glob", "Grep", "Agent"],
    agents: {
      "code-reviewer": {
        description: "Expert code reviewer for quality and security reviews.",
        prompt: "Analyze code quality and suggest improvements.",
        tools: ["Read", "Glob", "Grep"]
      }
    }
  }
})) {
  if ("result" in message) console.log(message.result);
}

子代理上下文中的消息包含 parent_tool_use_id 字段,可让你跟踪哪些消息属于哪个子代理执行。

了解更多关于子代理 →

MCP(Model Context Protocol)

通过 Model Context Protocol 连接外部系统:数据库、浏览器、API 以及数百种更多

此示例连接 Playwright MCP 服务器 为代理提供浏览器自动化能力:

python
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    async for message in query(
        prompt="Open example.com and describe what you see",
        options=ClaudeAgentOptions(
            mcp_servers={
                "playwright": {"command": "npx", "args": ["@playwright/mcp@latest"]}
            }
        ),
    ):
        if hasattr(message, "result"):
            print(message.result)

asyncio.run(main())
typescript
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Open example.com and describe what you see",
  options: {
    mcpServers: {
      playwright: { command: "npx", args: ["@playwright/mcp@latest"] }
    }
  }
})) {
  if ("result" in message) console.log(message.result);
}

了解更多关于 MCP →

权限控制

精确控制代理可以使用哪些工具。允许安全操作、阻止危险操作,或要求对敏感操作进行批准。

关于交互式批准提示和 AskUserQuestion 工具,参见处理批准和用户输入

此示例创建一个只读代理,可以分析但不能修改代码。allowed_tools 预批准了 ReadGlobGrep

python
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    async for message in query(
        prompt="Review this code for best practices",
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Glob", "Grep"],
        ),
    ):
        if hasattr(message, "result"):
            print(message.result)

asyncio.run(main())
typescript
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Review this code for best practices",
  options: {
    allowedTools: ["Read", "Glob", "Grep"]
  }
})) {
  if ("result" in message) console.log(message.result);
}

了解更多关于权限 →

会话(Sessions)

在多次交互中保持上下文。Claude 记住读取的文件、已完成的分析以及对话历史。稍后可以恢复会话,或者分叉以探索不同路径。

此示例从第一次查询中捕获会话 ID,然后恢复以使用完整上下文继续:

python
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage, ResultMessage

async def main():
    session_id = None

    # First query: capture the session ID
    async for message in query(
        prompt="Read the authentication module",
        options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"]),
    ):
        if isinstance(message, SystemMessage) and message.subtype == "init":
            session_id = message.data["session_id"]

    # Resume with full context from the first query
    async for message in query(
        prompt="Now find all places that call it",  # "it" = auth module
        options=ClaudeAgentOptions(resume=session_id),
    ):
        if isinstance(message, ResultMessage):
            print(message.result)

asyncio.run(main())
typescript
import { query } from "@anthropic-ai/claude-agent-sdk";

let sessionId: string | undefined;

// First query: capture the session ID
for await (const message of query({
  prompt: "Read the authentication module",
  options: { allowedTools: ["Read", "Glob"] }
})) {
  if (message.type === "system" && message.subtype === "init") {
    sessionId = message.session_id;
  }
}

// Resume with full context from the first query
for await (const message of query({
  prompt: "Now find all places that call it", // "it" = auth module
  options: { resume: sessionId }
})) {
  if ("result" in message) console.log(message.result);
}

了解更多关于会话 →

Claude Code 特性

SDK 还支持 Claude Code 基于文件系统的配置。使用默认选项时,SDK 会从工作目录中的 .claude/~/.claude/ 加载这些配置。要限制来源,请在选项中设置 setting_sources(Python)或 settingSources(TypeScript)。

特性说明位置
技能用 Markdown 定义的专门能力.claude/skills/*/SKILL.md
斜杠命令用于常见任务的自定义命令.claude/commands/*.md
记忆项目上下文和指令CLAUDE.md.claude/CLAUDE.md
插件通过自定义命令、代理和 MCP 服务器扩展通过 plugins 选项以编程方式提供

Agent SDK 与其他 Claude 工具的对比

Claude Platform 提供多种使用 Claude 构建的方式。以下是 Agent SDK 的定位:

与 Anthropic Client SDK 对比

Anthropic Client SDK 提供直接的 API 访问:你发送提示并自行实现工具执行。Agent SDK 为你提供内置工具执行的 Claude。

使用 Client SDK,你需要实现工具循环。使用 Agent SDK,Claude 会处理它:

python
# Client SDK: 你实现工具循环
response = client.messages.create(...)
while response.stop_reason == "tool_use":
    result = your_tool_executor(response.tool_use)
    response = client.messages.create(tool_result=result, **params)

# Agent SDK: Claude 自主处理工具
async for message in query(prompt="Fix the bug in auth.py"):
    print(message)
typescript
// Client SDK: 你实现工具循环
let response = await client.messages.create({ ...params });
while (response.stop_reason === "tool_use") {
  const result = yourToolExecutor(response.tool_use);
  response = await client.messages.create({ tool_result: result, ...params });
}

// Agent SDK: Claude 自主处理工具
for await (const message of query({ prompt: "Fix the bug in auth.ts" })) {
  console.log(message);
}

与 Claude CLI 对比

相同的能力,不同的界面:

使用场景最佳选择
交互式开发CLI
CI/CD 流水线SDK
自定义应用SDK
一次性任务CLI
生产自动化SDK

许多团队同时使用两者:CLI 用于日常开发,SDK 用于生产。工作流可以直接在两者之间转换。

与 Managed Agents 对比

Managed Agents 是一个托管的 REST API:Anthropic 运行代理和沙箱,你的应用发送事件并流式返回结果。Agent SDK 是一个在你的进程内运行代理循环的库。

Agent SDKManaged Agents
运行位置你的进程,你的基础设施Anthropic 管理的基础设施
接口Python 或 TypeScript 库REST API
代理工作的对象你基础设施上的文件每个会话一个受管沙箱
会话状态你文件系统上的 JSONLAnthropic 托管的事件日志
自定义工具进程内的 Python 或 TypeScript 函数Claude 触发工具,你执行并返回结果
最佳场景本地原型设计,直接操作你文件系统和服务的代理无需运行沙箱和会话基础设施的生产代理,长时间运行和异步会话

常见路径是先用 Agent SDK 在本地做原型,然后迁移到 Managed Agents 用于生产。

更新日志

查看 SDK 更新、bug 修复和新特性的完整更新日志:

报告 Bug

如果你遇到 Agent SDK 的 bug 或问题:

品牌指南

对于集成 Claude Agent SDK 的合作伙伴,使用 Claude 品牌是可选的。在你的产品中引用 Claude 时:

允许:

  • "Claude Agent"(下拉菜单首选)
  • "Claude"(当菜单已标记为"代理"时)
  • "{你的代理名称} Powered by Claude"(如果你已有代理名称)

不允许:

  • "Claude Code" 或 "Claude Code Agent"
  • Claude Code 品牌的 ASCII 艺术或模仿 Claude Code 的视觉元素

你的产品应保持自己的品牌,不应看起来是 Claude Code 或 Anthropic 的任何产品。有关品牌合规的问题,请联系 Anthropic 销售团队

许可和条款

Claude Agent SDK 的使用受 Anthropic 商业服务条款 约束,包括当你用它为你自己的客户和最终用户提供产品和服务时,除非特定组件或依赖项在相应组件的 LICENSE 文件中以不同许可表示。

下一步

常见问题

Agent SDK 跟 Claude CLI 有什么区别?

Agent SDK 是一个 Python/TypeScript 库,运行在你的进程内,适合 CI/CD 流水线、自定义应用和生产自动化。CLI 是交互式命令行工具,适合日常开发和一次性任务。两者能力相同,工作流可直接转换。

Agent SDK 需要设置 API 密钥吗?

是的。你需要从 Claude Console 获取 API 密钥,设置环境变量 ANTHROPIC_API_KEY。SDK 也支持通过 Amazon Bedrock、Google Vertex AI、Microsoft Azure 等第三方提供商认证,各自需要对应的环境变量和凭证。

Agent SDK 支持哪些第三方 API 提供商?

支持 Amazon Bedrock、Claude Platform on AWS、Google Vertex AI 和 Microsoft Azure AI Foundry。每个提供商需要设置对应的环境变量(如 CLAUDE_CODE_USE_BEDROCK=1)并配置 AWS 或 Google Cloud 凭证。