Skip to content

参考数据:Agent SDK 参考 — TypeScript

Data: Agent SDK reference — TypeScript

v2.1.63

TypeScript Agent SDK reference including installation, quick start, custom tools, and hooks

Agent SDK — TypeScript

Claude Agent SDK 提供了一个高级接口,用于构建具备内置工具、安全功能和智能体能力的 AI 智能体。

安装

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

快速开始

typescript
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生成子智能体

权限系统

typescript
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(模型上下文协议)支持

typescript
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 定义在进程内运行的自定义工具:

typescript
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);
}

钩子

typescript
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);
}

可用的钩子事件:PreToolUsePostToolUsePostToolUseFailureNotificationUserPromptSubmitSessionStartSessionEndStopSubagentStartSubagentStopPreCompactPermissionRequestSetupTeammateIdleTaskCompletedConfigChange


常用选项

query() 接受一个顶层的 prompt(字符串)和一个 options 对象:

typescript
query({ prompt: "...", options: { ... } })
选项类型描述
cwdstring文件操作的工作目录
allowedToolsarray智能体可以使用的工具(例如 ["Read", "Edit", "Bash"]
toolsarray要提供的内置工具(限制默认集合)
disallowedToolsarray明确禁止使用的工具
permissionModestring如何处理权限提示
allowDangerouslySkipPermissionsbool必须为 true 才能使用 permissionMode: "bypassPermissions"
mcpServersobject要连接的 MCP 服务器
hooksobject用于自定义行为的钩子
systemPromptstring自定义系统提示
maxTurnsnumber停止前的最大智能体轮次
maxBudgetUsdnumber查询的最大预算(美元)
modelstring模型 ID(默认值:由 CLI 确定)
agentsobject子智能体定义(Record<string, AgentDefinition>
outputFormatobject结构化输出模式
thinkingobject思考/推理控制
betasarray要启用的 Beta 功能(例如 ["context-1m-2025-08-07"]
settingSourcesarray要加载的设置(例如 ["project"])。默认值:无(不使用 CLAUDE.md 文件)
envobject为会话设置的环境变量

子智能体

typescript
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);
}

消息类型

typescript
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; // 捕获以供稍后恢复使用
  }
}

最佳实践

  1. 始终指定 allowedTools — 明确列出智能体可以使用的工具
  2. 设置工作目录 — 始终为文件操作指定 cwd
  3. 使用适当的权限模式 — 从 "default" 开始,仅在需要时升级
  4. 处理所有消息类型 — 检查 result 属性以获取智能体输出
  5. 限制 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

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

Quick Start

typescript
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

ToolDescription
ReadRead files in the workspace
WriteCreate new files
EditMake precise edits to existing files
BashExecute shell commands
GlobFind files by pattern
GrepSearch files by content
WebSearchSearch the web for information
WebFetchFetch and analyze web pages
AskUserQuestionAsk user clarifying questions
AgentSpawn subagents

Permission System

typescript
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 (requires allowDangerouslySkipPermissions: true in options)

MCP (Model Context Protocol) Support

typescript
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:

typescript
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

typescript
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:

typescript
query({ prompt: "...", options: { ... } })
OptionTypeDescription
cwdstringWorking directory for file operations
allowedToolsarrayTools the agent can use (e.g., ["Read", "Edit", "Bash"])
toolsarrayBuilt-in tools to make available (restricts the default set)
disallowedToolsarrayTools to explicitly disallow
permissionModestringHow to handle permission prompts
allowDangerouslySkipPermissionsboolMust be true to use permissionMode: "bypassPermissions"
mcpServersobjectMCP servers to connect to
hooksobjectHooks for customizing behavior
systemPromptstringCustom system prompt
maxTurnsnumberMaximum agent turns before stopping
maxBudgetUsdnumberMaximum budget in USD for the query
modelstringModel ID (default: determined by CLI)
agentsobjectSubagent definitions (Record<string, AgentDefinition>)
outputFormatobjectStructured output schema
thinkingobjectThinking/reasoning control
betasarrayBeta features to enable (e.g., ["context-1m-2025-08-07"])
settingSourcesarraySettings to load (e.g., ["project"]). Default: none (no CLAUDE.md files)
envobjectEnvironment variables to set for the session

Subagents

typescript
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

typescript
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

  1. Always specify allowedTools — Explicitly list which tools the agent can use
  2. Set working directory — Always specify cwd for file operations
  3. Use appropriate permission modes — Start with "default" and only escalate when needed
  4. Handle all message types — Check for result property to get agent output
  5. Limit maxTurns — Prevent runaway agents with reasonable limits