参考数据:Agent SDK 参考 — TypeScript
Data: Agent SDK reference — TypeScript
v2.1.63TypeScript Agent SDK reference including installation, quick start, custom tools, and hooks
Agent SDK — TypeScript
Claude Agent SDK 提供了一个高级接口,用于构建具备内置工具、安全功能和智能体能力的 AI 智能体。
安装
npm install @anthropic-ai/claude-agent-sdk快速开始
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Explain this codebase",
options: { allowedTools: ["Read", "Glob", "Grep"] },
})) {
if ("result" in message) {
console.log(message.result);
}
}内置工具
| 工具 | 描述 |
|---|---|
| Read | 读取工作空间中的文件 |
| Write | 创建新文件 |
| Edit | 对现有文件进行精确编辑 |
| Bash | 执行 shell 命令 |
| Glob | 按模式查找文件 |
| Grep | 按内容搜索文件 |
| WebSearch | 在网络上搜索信息 |
| WebFetch | 获取并分析网页 |
| AskUserQuestion | 向用户询问澄清问题 |
| Agent | 生成子智能体 |
权限系统
for await (const message of query({
prompt: "Refactor the authentication module",
options: {
allowedTools: ["Read", "Edit", "Write"],
permissionMode: "acceptEdits",
},
})) {
if ("result" in message) console.log(message.result);
}权限模式:
"default":对危险操作进行提示"plan":仅进行规划,不执行"acceptEdits":自动接受文件编辑"dontAsk":不进行提示(适用于 CI/CD)"bypassPermissions":跳过所有提示(需要在选项中设置allowDangerouslySkipPermissions: true)
MCP(模型上下文协议)支持
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 工具
您可以使用 tool() 和 createSdkMcpServer 定义在进程内运行的自定义工具:
import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";
const myTool = tool("my-tool", "Description", { input: z.string() }, async (args) => {
return { content: [{ type: "text", text: "result" }] };
});
const server = createSdkMcpServer({ name: "my-server", tools: [myTool] });
// 传递给 query
for await (const message of query({
prompt: "Use my-tool to do something",
options: { mcpServers: { myServer: server } },
})) {
if ("result" in message) console.log(message.result);
}钩子
import { query, HookCallback } from "@anthropic-ai/claude-agent-sdk";
import { appendFileSync } from "fs";
const logFileChange: HookCallback = async (input) => {
const filePath = (input as any).tool_input?.file_path ?? "unknown";
appendFileSync(
"./audit.log",
`${new Date().toISOString()}: modified ${filePath}\n`,
);
return {};
};
for await (const message of query({
prompt: "Refactor utils.py to improve readability",
options: {
allowedTools: ["Read", "Edit", "Write"],
permissionMode: "acceptEdits",
hooks: {
PostToolUse: [{ matcher: "Edit|Write", hooks: [logFileChange] }],
},
},
})) {
if ("result" in message) console.log(message.result);
}可用的钩子事件:PreToolUse、PostToolUse、PostToolUseFailure、Notification、UserPromptSubmit、SessionStart、SessionEnd、Stop、SubagentStart、SubagentStop、PreCompact、PermissionRequest、Setup、TeammateIdle、TaskCompleted、ConfigChange
常用选项
query() 接受一个顶层的 prompt(字符串)和一个 options 对象:
query({ prompt: "...", options: { ... } })| 选项 | 类型 | 描述 |
|---|---|---|
cwd | string | 文件操作的工作目录 |
allowedTools | array | 智能体可以使用的工具(例如 ["Read", "Edit", "Bash"]) |
tools | array | 要提供的内置工具(限制默认集合) |
disallowedTools | array | 明确禁止使用的工具 |
permissionMode | string | 如何处理权限提示 |
allowDangerouslySkipPermissions | bool | 必须为 true 才能使用 permissionMode: "bypassPermissions" |
mcpServers | object | 要连接的 MCP 服务器 |
hooks | object | 用于自定义行为的钩子 |
systemPrompt | string | 自定义系统提示 |
maxTurns | number | 停止前的最大智能体轮次 |
maxBudgetUsd | number | 查询的最大预算(美元) |
model | string | 模型 ID(默认值:由 CLI 确定) |
agents | object | 子智能体定义(Record<string, AgentDefinition>) |
outputFormat | object | 结构化输出模式 |
thinking | object | 思考/推理控制 |
betas | array | 要启用的 Beta 功能(例如 ["context-1m-2025-08-07"]) |
settingSources | array | 要加载的设置(例如 ["project"])。默认值:无(不使用 CLAUDE.md 文件) |
env | object | 为会话设置的环境变量 |
子智能体
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);
}消息类型
for await (const message of query({
prompt: "Find TODO comments",
options: { allowedTools: ["Read", "Glob", "Grep"] },
})) {
if ("result" in message) {
console.log(message.result);
} else if (message.type === "system" && message.subtype === "init") {
const sessionId = message.session_id; // 捕获以供稍后恢复使用
}
}最佳实践
- 始终指定 allowedTools — 明确列出智能体可以使用的工具
- 设置工作目录 — 始终为文件操作指定
cwd - 使用适当的权限模式 — 从
"default"开始,仅在需要时升级 - 处理所有消息类型 — 检查
result属性以获取智能体输出 - 限制 maxTurns — 通过合理的限制防止智能体失控
英文原文 / English Original
Agent SDK — TypeScript
The Claude Agent SDK provides a higher-level interface for building AI agents with built-in tools, safety features, and agentic capabilities.
Installation
npm install @anthropic-ai/claude-agent-sdkQuick Start
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Explain this codebase",
options: { allowedTools: ["Read", "Glob", "Grep"] },
})) {
if ("result" in message) {
console.log(message.result);
}
}Built-in Tools
| Tool | Description |
|---|---|
| Read | Read files in the workspace |
| Write | Create new files |
| Edit | Make precise edits to existing files |
| Bash | Execute shell commands |
| Glob | Find files by pattern |
| Grep | Search files by content |
| WebSearch | Search the web for information |
| WebFetch | Fetch and analyze web pages |
| AskUserQuestion | Ask user clarifying questions |
| Agent | Spawn subagents |
Permission System
for await (const message of query({
prompt: "Refactor the authentication module",
options: {
allowedTools: ["Read", "Edit", "Write"],
permissionMode: "acceptEdits",
},
})) {
if ("result" in message) console.log(message.result);
}Permission modes:
"default": Prompt for dangerous operations"plan": Planning only, no execution"acceptEdits": Auto-accept file edits"dontAsk": Don't prompt (useful for CI/CD)"bypassPermissions": Skip all prompts (requiresallowDangerouslySkipPermissions: truein options)
MCP (Model Context Protocol) Support
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);
}In-Process MCP Tools
You can define custom tools that run in-process using tool() and createSdkMcpServer:
import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";
const myTool = tool("my-tool", "Description", { input: z.string() }, async (args) => {
return { content: [{ type: "text", text: "result" }] };
});
const server = createSdkMcpServer({ name: "my-server", tools: [myTool] });
// Pass to query
for await (const message of query({
prompt: "Use my-tool to do something",
options: { mcpServers: { myServer: server } },
})) {
if ("result" in message) console.log(message.result);
}Hooks
import { query, HookCallback } from "@anthropic-ai/claude-agent-sdk";
import { appendFileSync } from "fs";
const logFileChange: HookCallback = async (input) => {
const filePath = (input as any).tool_input?.file_path ?? "unknown";
appendFileSync(
"./audit.log",
`\${new Date().toISOString()}: modified \${filePath}\\n`,
);
return {};
};
for await (const message of query({
prompt: "Refactor utils.py to improve readability",
options: {
allowedTools: ["Read", "Edit", "Write"],
permissionMode: "acceptEdits",
hooks: {
PostToolUse: [{ matcher: "Edit|Write", hooks: [logFileChange] }],
},
},
})) {
if ("result" in message) console.log(message.result);
}Available hook events: PreToolUse, PostToolUse, PostToolUseFailure, Notification, UserPromptSubmit, SessionStart, SessionEnd, Stop, SubagentStart, SubagentStop, PreCompact, PermissionRequest, Setup, TeammateIdle, TaskCompleted, ConfigChange
Common Options
query() takes a top-level prompt (string) and an options object:
query({ prompt: "...", options: { ... } })| Option | Type | Description |
|---|---|---|
cwd | string | Working directory for file operations |
allowedTools | array | Tools the agent can use (e.g., ["Read", "Edit", "Bash"]) |
tools | array | Built-in tools to make available (restricts the default set) |
disallowedTools | array | Tools to explicitly disallow |
permissionMode | string | How to handle permission prompts |
allowDangerouslySkipPermissions | bool | Must be true to use permissionMode: "bypassPermissions" |
mcpServers | object | MCP servers to connect to |
hooks | object | Hooks for customizing behavior |
systemPrompt | string | Custom system prompt |
maxTurns | number | Maximum agent turns before stopping |
maxBudgetUsd | number | Maximum budget in USD for the query |
model | string | Model ID (default: determined by CLI) |
agents | object | Subagent definitions (Record<string, AgentDefinition>) |
outputFormat | object | Structured output schema |
thinking | object | Thinking/reasoning control |
betas | array | Beta features to enable (e.g., ["context-1m-2025-08-07"]) |
settingSources | array | Settings to load (e.g., ["project"]). Default: none (no CLAUDE.md files) |
env | object | Environment variables to set for the session |
Subagents
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);
}Message Types
for await (const message of query({
prompt: "Find TODO comments",
options: { allowedTools: ["Read", "Glob", "Grep"] },
})) {
if ("result" in message) {
console.log(message.result);
} else if (message.type === "system" && message.subtype === "init") {
const sessionId = message.session_id; // Capture for resuming later
}
}Best Practices
- Always specify allowedTools — Explicitly list which tools the agent can use
- Set working directory — Always specify
cwdfor file operations - Use appropriate permission modes — Start with
"default"and only escalate when needed - Handle all message types — Check for
resultproperty to get agent output - Limit maxTurns — Prevent runaway agents with reasonable limits