Claude Agent SDK 入门

Claude Agent SDK 将 Claude Code 的核心能力抽象为可编程库。它不只是 “ 调 API”,而是提供了一套完整的 Agent 运行时——包含决策循环、工具执行、上下文管理。核心能力包括:

  • Agent Loop:自主决策的执行循环
  • Context Management:上下文管理
  • Built-in Tools:读文件、改文件、跑命令、联网搜索等

1. 架构概览

%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#4F46E5', 'primaryTextColor': '#000', 'primaryBorderColor': '#3730A3', 'lineColor': '#6366F1', 'secondaryColor': '#10B981', 'tertiaryColor': '#F59E0B'}}}%%
flowchart TB
    subgraph SDK["Claude Agent SDK"]
        AL["Agent Loop"]
        CM["Context Management"]
        BT["Built-in Tools"]
    end

    subgraph Tools["内置工具"]
        RF["读文件"]
        WF["写文件"]
        RC["运行命令"]
        WS["联网搜索"]
    end

    APP["你的应用"] --> SDK
    SDK --> API["Claude API"]
    BT --> Tools

    classDef primary fill:#4F46E5,stroke:#3730A3,color:#fff
    classDef success fill:#10B981,stroke:#059669,color:#fff
    classDef info fill:#06B6D4,stroke:#0891B2,color:#fff

    class SDK primary
    class APP,API success
    class Tools info

1.1 API Client Vs Agent Runtime

普通 Claude API 是 “ 单轮问答 “:你发 prompt,模型返回 response,完事。

Claude Agent SDK 是 “ 自主循环 “:Agent 观察环境、决定动作、执行工具、验证结果,循环往复直到任务完成。

%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#4F46E5', 'primaryTextColor': '#000', 'primaryBorderColor': '#3730A3', 'lineColor': '#6366F1', 'secondaryColor': '#10B981', 'tertiaryColor': '#F59E0B'}}}%%
flowchart LR
    subgraph API["普通 Claude API"]
        A1["Prompt"] --> A2["Response"]
    end

    subgraph SDK["Claude Agent SDK"]
        B1["Task"] --> B2["Agent Loop"]
        B2 --> B3["Tool 执行"]
        B3 --> B4["结果验证"]
        B4 -->|"未完成"| B2
        B4 -->|"完成"| B5["最终输出"]
    end

    classDef primary fill:#4F46E5,stroke:#3730A3,color:#fff
    classDef success fill:#10B981,stroke:#059669,color:#fff

    class API primary
    class SDK success
维度Claude APIClaude Agent SDK
交互模式单轮请求 - 响应多轮自主循环
工具调用需自己解析并执行工具调用结果内置工具 + 自动执行运行时
上下文手动拼接 messages自动管理、压缩、截断
会话控制无状态可持久化、可恢复

一句话:API 是 “ 你问我答 “,Agent SDK 是 “ 你下任务,我干活 “。

1.2 Agent Loop 原理

Agent SDK 的核心是一个四步循环(类似决策循环模型):

Gather Context(收集上下文)

Agent 读取当前环境信息:

  • 文件内容(通过 Read 等文件工具)
  • 命令输出(通过 Bash 等命令工具)
  • 网页搜索结果(通过 WebSearch 等联网工具)
  • 已有对话历史

:内置工具名以官方文档为准,不同版本可能有差异。

Decide & Act(决策并执行)

基于上下文,Agent 决定下一步动作:

  • 调用哪个工具?
  • 传什么参数?
  • 是否需要先执行其他前置操作?

Agent 不只是 “ 说要做什么 “,而是真正执行——写文件、跑命令、编辑代码。

Verify(验证结果)

执行后,Agent 自动验证:

  • 文件是否正确写入?
  • 命令是否成功?
  • 代码是否编译通过?

如果验证失败,Agent 会自我修正——这是 Agent 与传统 pipeline 的关键区别。

Repeat or Return

任务完成则返回结果;否则带着新上下文进入下一轮循环。

1.3 上下文管理机制

长时间运行的 Agent 会积累大量上下文,导致 token 溢出。SDK 内置两种策略:

策略触发条件行为
自动压缩上下文接近 token 上限将早期对话摘要化
截断压缩后仍超限丢弃最早的轮次

这意味着你可以让 Agent 运行数小时,而不用担心 context window 爆炸。

2. 安装和使用

1
2
3
4
5
pip install claude-agent-sdk
echo 'ANTHROPIC_API_KEY=你的key' > .env

# 或直接导出环境变量
# export ANTHROPIC_API_KEY=你的key

SDK 提供两种入口,适用于不同场景:

%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#4F46E5', 'primaryTextColor': '#000', 'primaryBorderColor': '#3730A3', 'lineColor': '#6366F1', 'secondaryColor': '#10B981', 'tertiaryColor': '#F59E0B'}}}%%
flowchart LR
    subgraph query["query()"]
        Q1["一次性任务"]
        Q2["每次新会话"]
        Q3["简单、上手快"]
    end

    subgraph client["ClaudeSDKClient"]
        C1["多轮对话"]
        C2["会话保持"]
        C3["支持 hooks、custom tools"]
    end

    U["选择入口"] --> |"触发任务<br/>拿结果走人"| query
    U --> |"长期会话<br/>交互式应用"| client

    classDef primary fill:#4F46E5,stroke:#3730A3,color:#fff
    classDef success fill:#10B981,stroke:#059669,color:#fff
    classDef decision fill:#F59E0B,stroke:#D97706,color:#000

    class query primary
    class client success
    class U decision
模式适用场景会话保持高级能力
query()一次性任务,每次新会话
ClaudeSDKClient多轮对话,交互式应用hooks, custom tools

2.1 query() 示例

query() 适合 “ 触发一次任务,拿到结果走人 “ 的场景:每次调用 query() 都是新会话,不保留历史。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# query_demo.py
import asyncio
from claude_agent_sdk import query, AssistantMessage, TextBlock

async def ask(prompt: str):
print(f"\n=== query() ===")
async for msg in query(prompt=prompt):
if isinstance(msg, AssistantMessage):
for block in msg.content:
if isinstance(block, TextBlock):
print(f"Claude: {block.text}")

async def main():
# 第一次调用
await ask("请记住:我的小狗叫豆豆。只回答"记住了"。")

# 第二次调用 —— 新会话,不记得上次内容
await ask("我的小狗叫什么?只回答名字。")

asyncio.run(main())

2.2 ClaudeSDKClient 示例

ClaudeSDKClient 保持会话状态,支持多轮对话,ClaudeSDKClient 还支持 hooks(拦截工具调用)和 custom tools(扩展能力)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# client_demo.py
import asyncio
from claude_agent_sdk import ClaudeSDKClient, AssistantMessage, TextBlock

async def print_response(client: ClaudeSDKClient):
async for msg in client.receive_response():
if isinstance(msg, AssistantMessage):
for block in msg.content:
if isinstance(block, TextBlock):
print(f"Claude: {block.text}")

async def main():
async with ClaudeSDKClient() as client:
print("\n=== ClaudeSDKClient | same session ===")

await client.query("请记住:我的小狗叫豆豆。只回答"记住了"。")
await print_response(client)

# 同一会话,能记住上次内容
await client.query("我的小狗叫什么?只回答名字。")
await print_response(client)

asyncio.run(main())

3. Custom Tools 实战

SDK 通过 MCP(Model Context Protocol) 扩展工具。你可以定义任意 Python 函数,让 Agent 调用。

3.1 定义 Custom Tool

使用 @tool 装饰器:

:以下代码为概念演示,具体 API 请以 官方文档 为准。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 导入路径以官方文档为准
from claude_agent_sdk.mcp import tool, create_sdk_mcp_server

@tool(
name="get_weather",
description="获取指定城市的天气",
input_schema={
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称"}
},
"required": ["city"]
}
)
async def get_weather(city: str) -> str:
# 实际调用天气 API
return f"{city} 今日晴,25°C"

# 创建 MCP Server
mcp_server = create_sdk_mcp_server(
name="weather_tools",
tools=[get_weather]
)

3.2 注册到 Client

1
2
3
4
5
6
7
8
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions

async def main():
options = ClaudeAgentOptions(mcp_servers=[mcp_server])

async with ClaudeSDKClient(options=options) as client:
await client.query("北京今天天气怎么样?")
# Agent 会自动调用 mcp__weather_tools__get_weather

工具名遵循 mcp__{server_name}__{tool_name} 格式。

3.3 Hooks:拦截与审计

通过 PreToolUse / PostToolUse 拦截工具调用,实现审计或安全控制:

:Hook 函数签名以官方文档为准,以下为概念演示。

1
2
3
4
5
6
7
8
9
10
11
12
13
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions

# Hook 函数签名以官方文档为准
def pre_tool_hook(tool_name: str, tool_input: dict) -> bool:
# 返回 False 可阻止工具执行
if tool_name == "Bash" and "rm -rf" in tool_input.get("command", ""):
print("危险命令被拦截")
return False
return True

options = ClaudeAgentOptions(
hooks={"PreToolUse": pre_tool_hook}
)

4. 常见问题

4.1 其他语言支持

Python 和 TypeScript 是官方 Agent SDK 支持的语言。其他语言(Java、Go、C#、Ruby、PHP 等)官方提供的是 Claude API Client SDK,不包含 Agent Loop 和工具执行运行时。

如需在其他语言中使用 Agent SDK 能力,常见做法是将 Agent SDK(Python/Node)部署为独立服务,通过 HTTP/RPC 调用。

4.2 CCR 兼容性

CCR(Claude Code Router)是 Claude Code 的模型代理工具,Agent SDK 与 CCR 兼容,测试通过:

1
2
eval "$(ccr activate)"
ccr code