Build production AI agents with Claude Code as a library 使用 Claude Code 作为库构建生产级 AI 代理
The Claude Code SDK has been renamed to the Claude Agent SDK. Claude Code SDK 已更名为 Claude Agent SDK。
Build AI agents that autonomously read files, run commands, search the web, edit code, and more. The Agent SDK gives you the same tools, agent loop, and context management that power Claude Code, programmable in Python and TypeScript. 让你构建能够自主读取文件、运行命令、搜索网络、编辑代码等功能的 AI 代理。Agent SDK 提供了与 Claude Code 相同的工具、代理循环和上下文管理功能,可用 Python 和 TypeScript 进行编程。
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Find and fix the bug in auth.py",
options: { allowedTools: ["Read", "Edit", "Bash"] }
})) {
console.log(message); // Claude reads the file, finds the bug, edits it
}
The Agent SDK includes built-in tools for reading files, running commands, and editing code, so your agent can start working immediately without you implementing tool execution. Agent SDK 包含用于读取文件、运行命令和编辑代码的内置工具,因此你的代理可以立即开始工作,而无需你实现工具执行。
Get started 开始使用
Install the SDK 安装SDK
npm install @anthropic-ai/claude-agent-sdk
Set your API key 设置你的 API 密钥
Get an API key from the Console, then set it as an environment variable: 从控制台获取 API 密钥,然后将其设置为环境变量:
export ANTHROPIC_API_KEY=your-api-key
The SDK also supports authentication via third-party API providers: SDK 也支持通过第三方 API 提供者进行认证:
- Amazon Bedrock: set
CLAUDE_CODE_USE_BEDROCK=1environment variable and configure AWS credentials 配置 AWS 凭证 - Google Vertex AI: set
CLAUDE_CODE_USE_VERTEX=1environment variable and configure Google Cloud credentials 配置 Google Cloud 凭证 - Microsoft Azure: set
CLAUDE_CODE_USE_FOUNDRY=1environment variable and configure Azure credentials
Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK. Please use the API key authentication methods described in this document instead. 除非事先获得批准,Anthropic 不允许第三方开发者为其产品(包括基于 Claude Agent SDK 构建的代理)提供 claude.ai 登录或速率限制。请改用本文档中描述的 API 密钥认证方法。
Run your first agent运行你的第一个代理
This example creates an agent that lists files in your current directory using built-in tools. 此示例创建一个使用内置工具列出当前目录中文件的代理。
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);
}
Capabilities 功能
Everything that makes Claude Code powerful is available in the SDK: 使Claude Code强大的一切都可以在SDK里面获得:
Built-in tools 内置工具
Your agent can read files, run commands, and search codebases out of the box. Key tools include: 你的代理可以开箱即用地读取文件、运行命令和搜索代码库。关键工具包括:
| Tool | What it does |
|---|---|
| Read | Read any file in the working directory |
| Write | Create new files |
| Edit | Make precise edits to existing files |
| Bash | Run terminal commands, scripts, git operations |
| Glob | Find files by pattern (**/*.ts, src/**/*.py) |
| Grep | Search file contents with regex |
| WebSearch | Search the web for current information搜索网络以获取最新信息 |
| WebFetch | Fetch and parse web page content |
| AskUserQuestion | Ask the user clarifying questions with multiple choice options使用多选项让用户回答澄清问题 |
This example creates an agent that searches your codebase for TODO comments: 下面例子创建了一个搜索你的代码库中 TODO 注释的代理:
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Find all TODO comments and create a summary",查找所有 TODO 注释并创建摘要
options: { allowedTools: ["Read", "Glob", "Grep"] }
})) {
if ("result" in message) console.log(message.result);
}
Hooks
Run custom code at key points in the agent lifecycle. SDK hooks use callback functions to validate, log, block, or transform agent behavior. 在agent生命周期的关键点运行自定义代码。SDK 钩子使用回调函数来验证、记录、阻止或转换代理行为。
Available hooks: PreToolUse, PostToolUse, Stop, SessionStart, SessionEnd, UserPromptSubmit, and more.
This example logs all file changes to an audit file: 这个示例将所有文件更改记录到审计文件中:
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",重构utils.py以提高可读性
options: {
permissionMode: "acceptEdits",
hooks: {
PostToolUse: [{ matcher: "Edit|Write", hooks: [logFileChange] }]
}
}
})) {
if ("result" in message) console.log(message.result);
}
Subagents子代理
Spawn specialized agents to handle focused subtasks. Your main agent delegates work, and subagents report back with results. 创建专门的agents来处理子任务。你的主agent分配工作,子代理返回结果。
Define custom agents with specialized instructions. Include Task in allowedTools since subagents are invoked via the Task tool:
定义具有专门指令的自定义agents。在allowedTools中包含Task,因为子代理通过 Task 工具被调用:
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", "Task"],
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);
}
Messages from within a subagent's context include a parent_tool_use_id field, letting you track which messages belong to which subagent execution.
子代理上下文中的消息包含一个 parent_tool_use_id 字段,让你可以跟踪哪些消息属于哪个子代理执行。
MCP
Connect to external systems via the Model Context Protocol: databases, browsers, APIs, and hundreds more. 通过模型上下文协议连接外部系统,比如:数据库、浏览器、API等等
This example connects the Playwright MCP server to give your agent browser automation capabilities: 此示例连接[Playwright MCP 服务器],为你的代理提供浏览器自动化功能:
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);
}
Permissions权限
Control exactly which tools your agent can use. Allow safe operations, block dangerous ones, or require approval for sensitive actions. 控制你的代理可以使用哪些工具。允许安全操作,阻止危险操作,或要求敏感操作获得批准。
For interactive approval prompts and the AskUserQuestion tool, see Handle approvals and user input.
对于交互式审批提示和 AskUserQuestion 工具,请参阅 处理审批和用户输入
This example creates a read-only agent that can analyze but not modify code: 此示例创建了一个只读代理,它可以分析但不能修改代码:
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"],
permissionMode: "bypassPermissions"
}
})) {
if ("result" in message) console.log(message.result);
}
Sessions会话
Maintain context across multiple exchanges. Claude remembers files read, analysis done, and conversation history. Resume sessions later, or fork them to explore different approaches. 在多次交互中保持上下文。Claude 记得读取的文件、完成的分析以及对话历史。稍后可以继续会话,或者fork克隆它们以探索不同的方法。
This example captures the session ID from the first query, then resumes to continue with full context: 这个示例从第一个查询中捕获会话 ID,然后继续使用完整上下文:
import { query } from "@anthropic-ai/claude-agent-sdk";
let sessionId: string | undefined;
// First query: capture the session ID 捕获会话 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 features 功能
The SDK also supports Claude Code's filesystem-based configuration. To use these features, set setting_sources=["project"] (Python) or settingSources: ['project'] (TypeScript) in your options.
SDK 还支持基于文件系统的 Claude 配置。要使用这些功能,请在选项中设置setting_sources=["project"](Python)或settingSources: ['project'](TypeScript)。
| Feature | Description | Location |
|---|---|---|
| Skills | 专业能力Specialized capabilities defined in Markdown | .claude/skills/SKILL.md |
| Slash commands | Custom commands for common tasks常见任务的定制命令 | .claude/commands/*.md |
| Memory | Project context and instructions 项目上下文和指令 | CLAUDE.md or .claude/CLAUDE.md |
| Plugins | Extend with custom commands, agents, and MCP servers | Programmatic via plugins option |
Compare the Agent SDK to other Claude tools 将 Agent SDK 与其他 Claude 工具进行比较
The Claude platform offers multiple ways to build with Claude. Here's how the Agent SDK fits in: Claude 平台提供了多种使用 Claude 进行构建的方式。以下是 Agent SDK 如何融入其中的情况:
Agent SDK vs Client SDK
The Anthropic Client SDK gives you direct API access: you send prompts and implement tool execution yourself. The Agent SDK gives you Claude with built-in tool execution. Anthropic客户端 SDK为你提供直接的 API 访问:你发送提示并自行实现工具执行。代理 SDK为你提供带有内置工具执行的 Claude。
With the Client SDK, you implement a tool loop. With the Agent SDK, Claude handles it: 使用客户端 SDK,你需要实现工具循环。使用代理 SDK,Claude 会处理它:
// Client SDK: You implement the tool loop 你实现工具循环
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 handles tools autonomously 自动处理工具
for await (const message of query({ prompt: "Fix the bug in auth.py" })) {
console.log(message);
}
Agent SDK vs Claude Code CLI
Same capabilities, different interface: 相同功能,不同界面,下面是选择标准:
| Use case | Best choice |
|---|---|
| Interactive development | CLI |
| CI/CD pipelines | SDK |
| Custom applications | SDK |
| One-off tasks一次性任务 | CLI |
| Production automation生产自动化 | SDK |
Many teams use both: CLI for daily development, SDK for production. Workflows translate directly between them. 很多团队同时使用两者:CLI 用于日常开发,SDK 用于生产。工作流程可以直接在两者之间转换。