跳到正文
FunCoding

搜索

搜索文档、智能体、博客、Skill 和 MCP

TypeScript SDK 参考:工具与权限类型

Agent SDK TypeScript 导出的内置工具输入类型(Agent、Bash、Read、Edit、Grep、Workflow、Task* 等)、工具输出类型,以及 PermissionUpdate、PermissionBehavior、PermissionUpdateDestination、PermissionRuleValue。

本页是 TypeScript Agent SDK 参考的第五部分:内置 Claude Code 工具的输入和输出 schema,以及权限更新类型。这些类型从 @anthropic-ai/claude-agent-sdk/sdk-tools 导出,可用于类型安全的工具交互。

工具输入类型

ToolInputSchemas

从 @anthropic-ai/claude-agent-sdk/sdk-tools 导出的工具输入类型的联合:

type ToolInputSchemas =
  | AgentInput
  | ArtifactInput
  | AskUserQuestionInput
  | BashInput
  | CronCreateInput
  | CronDeleteInput
  | CronListInput
  | EnterPlanModeInput
  | EnterWorktreeInput
  | ExitPlanModeInput
  | ExitWorktreeInput
  | FileEditInput
  | FileReadInput
  | FileWriteInput
  | GlobInput
  | GrepInput
  | ListMcpResourcesInput
  | McpInput
  | MonitorInput
  | NotebookEditInput
  | ProjectsInput
  | PushNotificationInput
  | ReadMcpResourceDirInput
  | ReadMcpResourceInput
  | RefreshMcpToolsInput
  | RemoteTriggerInput
  | ReportFindingsInput
  | ScheduleWakeupInput
  | ShowOnboardingRolePickerInput
  | TaskCreateInput
  | TaskGetInput
  | TaskListInput
  | TaskStopInput
  | TaskUpdateInput
  | TodoWriteInput
  | WebFetchInput
  | WebSearchInput
  | WorkflowInput;

Agent

工具名: Agent。旧名 Task 仍作为别名接受,并且 SDKSystemMessage init 消息里的 tools 数组为向后兼容目前仍把该工具列为 Task。mode 字段已弃用,在 Claude Code v2.1.212 及以上被忽略:子智能体要么在父会话的权限模式下运行,要么在其定义的 permissionMode 下运行,由子智能体继承规则决定。

type AgentInput = {
  description: string;
  prompt: string;
  subagent_type?: string;
  model?: "sonnet" | "opus" | "haiku" | "fable";
  run_in_background?: boolean;
  name?: string;
  team_name?: string; // 已弃用;被忽略
  mode?: "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan"; // 已弃用;被忽略
  isolation?: "worktree" | "remote";
};

启动新智能体自主处理复杂的多步骤任务。

AskUserQuestion

工具名: AskUserQuestion

type AskUserQuestionInput = {
  questions: Array<{
    question: string;
    header: string;
    options: Array<{ label: string; description: string; preview?: string }>;
    multiSelect: boolean;
  }>;
  answers?: Record<string, string>;
  annotations?: Record<string, { preview?: string; notes?: string }>;
  metadata?: { source?: string };
};

在执行期间向用户提出澄清问题(用法见「处理批准和用户输入」)。

Bash

工具名: Bash

type BashInput = {
  command: string;
  timeout?: number; // 毫秒。前台:默认上限 600000,更高的值被钳到上限。带 run_in_background(Claude Code v2.1.285 及以上):后台时限,省略时 1800000,上限 7200000(除非调高)
  description?: string;
  run_in_background?: boolean;
  dangerouslyDisableSandbox?: boolean;
};

执行 Bash 命令,可带超时和后台执行。工作目录在命令之间保持,包括多轮会话后续轮次里运行的命令;导出的环境变量这类 shell 状态则不保持。

Monitor

工具名: Monitor

type MonitorInput = {
  description: string;
  timeout_ms: number;
  command?: string;
  ws?: {
    url: string;
    protocols?: string[];
  };
};

运行后台来源并把每个事件交给 Claude,使它无需轮询就能作出反应:command 运行脚本并对每行 stdout 发出一个事件,ws 打开 WebSocket 并对每个文本帧发出一个事件。command 和 ws 要恰好提供一个(ws 来源需要较新的 Claude Code 版本)。timeout_ms 是监视的截止时间(毫秒),默认 300000,接受不超过 3600000 的值;有效截止时间最多 1800000(30 分钟),所以更大的被接受值会被缩短到它。到截止时间监视结束,Claude 收到一条通知。导出的类型把 timeout_ms 标为必需,因为 schema 会填充默认值;省略它的调用也能通过校验。Monitor 运行命令时遵循与 Bash 相同的权限规则;WebSocket 监视单独提示批准。

TaskOutput

在 Claude Code v2.1.277 中连同 TaskOutputInput 类型一起被移除。它之前用于取得运行中或已完成后台任务的输出;现在 Claude 改用 Read 读取后台任务的输出文件。仍然点名 TaskOutput 的 disallowedTools 条目或拒绝规则会被静默忽略。

Edit

工具名: Edit

type FileEditInput = {
  file_path: string;
  old_string: string;
  new_string: string;
  replace_all?: boolean;
};

对文件做精确的字符串替换。

Read

工具名: Read

type FileReadInput = {
  file_path: string;
  offset?: number;
  limit?: number;
  pages?: string;
};

从本地文件系统读取文件,包括文本、图片、PDF 和 Jupyter notebook。用 pages 指定 PDF 页范围(例如 "1-5")。对 PDF,Claude 在 Read 调用的 tool_result 内容里收到文件内容:返回 pdf 输出的读取带一个摘要 text 块和一个 document 块;返回 parts 输出的读取带摘要 text 块,后面跟每个提取页一个块。

Write

工具名: Write

type FileWriteInput = {
  file_path: string;
  content: string;
};

向本地文件系统写文件,已存在则覆盖。

Glob

工具名: Glob

type GlobInput = {
  pattern: string;
  path?: string;
};

对任何规模的代码库都很快的文件模式匹配。

Grep

工具名: Grep

type GrepInput = {
  pattern: string;
  path?: string;
  glob?: string;
  type?: string;
  output_mode?: "content" | "files_with_matches" | "count";
  "-i"?: boolean;
  "-o"?: boolean; // 只打印每行的匹配部分;需要 output_mode: "content"
  "-n"?: boolean;
  "-B"?: number;
  "-A"?: number;
  "-C"?: number;
  context?: number;
  head_limit?: number;
  offset?: number;
  multiline?: boolean;
};

基于 ripgrep、支持正则的强大搜索工具。

TaskStop

工具名: TaskStop

type TaskStopInput = {
  task_id?: string;
  shell_id?: string; // 已弃用:改用 task_id
};

按 ID 停止运行中的后台任务或 shell。自 v2.1.198 起,task_id 还接受按智能体 ID 或名字指定的智能体团队队友或命名的后台智能体。

NotebookEdit

工具名: NotebookEdit

type NotebookEditInput = {
  notebook_path: string;
  cell_id?: string;
  new_source: string;
  cell_type?: "code" | "markdown";
  edit_mode?: "replace" | "insert" | "delete";
};

编辑 Jupyter notebook 文件里的单元格。

WebFetch

工具名: WebFetch

type WebFetchInput = {
  url: string;
  prompt: string;
};

从 URL 获取内容并用 AI 模型处理。

WebSearch

工具名: WebSearch

type WebSearchInput = {
  query: string;
  allowed_domains?: string[];
  blocked_domains?: string[];
};

搜索网络并返回格式化的结果。

Workflow

工具名: Workflow

type WorkflowInput = {
  script?: string;
  name?: string;
  scriptPath?: string;
  args?: unknown; // 任何 JSON 值;已发布的类型把它渲染成对象映射
  resumeFromRunId?: string;
  title?: string; // 被忽略;脚本的 meta 块设置标题
  description?: string; // 被忽略;脚本的 meta 块设置描述
};

运行动态工作流:一个在后台编排许多子智能体并返回一个合并结果的脚本(Agent SDK v0.3.149 及以上可用)。script、name、scriptPath 至少需要一个。

字段类型说明
scriptstring内联工作流脚本,必须以字面的 export const meta = { name, description } 开头,后面是使用 agent()、parallel()、pipeline() 和 phase() 的脚本体;meta 里可选的 phases 数组把智能体按命名阶段在进度视图里分组
namestring内置工作流或保存在 .claude/workflows/ 的工作流的名字,会被解析为脚本
scriptPathstring磁盘上工作流脚本文件的路径,优先于 script 和 name。Claude Code 会持久化每次调用的脚本并在结果里返回路径,所以你可以编辑该文件并用同一个 scriptPath 重新调用来迭代
argsunknown作为全局 args 暴露给脚本的输入值,用于参数化的命名工作流,如研究问题或文件路径列表;数组和对象要以真正的 JSON 值传递,不要传 JSON 编码的字符串
resumeFromRunIdstring要恢复的先前 Workflow 调用的运行 ID;输入没变的已完成 agent() 调用通常返回缓存的结果,其余的实时运行;仅限同一会话
titlestring被忽略;脚本的 meta 块设置标题
descriptionstring被忽略;脚本的 meta 块设置描述

TodoWrite

工具名: TodoWrite

type TodoWriteInput = {
  todos: Array<{
    content: string;
    status: "pending" | "in_progress" | "completed";
    activeForm: string;
  }>;
};

创建和管理结构化的任务列表以跟踪进度。

注意:下列工具默认只在 Claude 3.x 模型、Opus 4 到 4.7、Sonnet 4 到 4.6 和 Haiku 4.5 上可用;在其他每个模型上(包括 Claude Code 不认识的模型 ID),除非选择加入否则不可用:TodoWrite、TaskCreate、TaskGet、TaskUpdate、TaskList。这些工具可用的地方,Claude Code 提供四个 Task 工具,或在你设了 CLAUDE_CODE_ENABLE_TASKS=0 时改为提供 TodoWrite。这个默认集合适用于 Claude Code v2.1.268 及以上,TypeScript Agent SDK 从 v0.3.268 起捆绑它。

TaskCreate、TaskUpdate、TaskGet、TaskList

type TaskCreateInput = {
  subject: string;
  description: string;
  activeForm?: string;
  metadata?: Record<string, unknown>;
};

type TaskUpdateInput = {
  taskId: string;
  status?: "pending" | "in_progress" | "completed" | "deleted";
  subject?: string;
  description?: string;
  activeForm?: string;
  addBlocks?: string[];
  addBlockedBy?: string[];
  owner?: string;
  metadata?: Record<string, unknown>;
};

type TaskGetInput = {
  taskId: string;
};

type TaskListInput = {};

TaskCreate 创建单个任务并返回分配的 ID;TaskUpdate 按 ID 修补一个任务,把 status 设为 "deleted" 即删除;TaskGet 返回一个任务的完整详情,ID 找不到时返回 null;TaskList 返回当前列表里所有任务的快照。

ExitPlanMode 与 EnterPlanMode

type ExitPlanModeInput = {
  /** 已弃用:不再使用。 */
  allowedPrompts?: Array<{
    tool: "Bash";
    prompt: string;
  }>;
  [k: string]: unknown;
};

type EnterPlanModeInput = {};

ExitPlanMode 退出 plan 模式;allowedPrompts 字段已弃用且被忽略,Claude Code 仍接受它以使现有调用方和记录能通过校验(v2.1.205 之前它用来为实施计划请求基于提示的 Bash 权限)。EnterPlanMode 进入 plan 模式,Claude 在做出更改之前先研究并提出计划。

ListMcpResources 与 ReadMcpResource

工具名: ListMcpResourcesTool、ReadMcpResourceTool

type ListMcpResourcesInput = {
  server?: string;
};

type ReadMcpResourceInput = {
  server: string;
  uri: string;
};

分别列出已连接服务器的可用 MCP 资源,以及从服务器读取一个具体的 MCP 资源。

EnterWorktree 与 ExitWorktree

type EnterWorktreeInput = {
  name?: string;
  path?: string;
};

type ExitWorktreeInput = {
  action: "keep" | "remove";
  discard_changes?: boolean;
};

EnterWorktree 创建并进入临时 git worktree 以便隔离工作;传 path 则切换到已有 worktree 而不是新建一个(首次进入时,目标必须是当前仓库的已注册 worktree,或在多仓库工作区里是嵌套在其中的仓库的)。ExitWorktree 退出当前 git worktree 并回到原来的工作目录:keep 把 worktree 和分支留在磁盘上,remove 把两者都删除;移除有未提交文件或未合并提交的 worktree 时 discard_changes 必须为 true。

CronCreate、CronDelete、CronList

type CronCreateInput = {
  cron: string;
  prompt: string;
  recurring?: boolean;
  durable?: boolean;
};

type CronDeleteInput = {
  id: string;
};

type CronListInput = {};

CronCreate 按本地时间的 5 字段 cron 计划安排提示运行;把 recurring 设为 false 则在下一次匹配时触发一次。任务默认限定在会话范围内,用 --resume 或 --continue 恢复会还原尚未过期的任务。把 durable 设为 true 请求持久化到 .claude/scheduled_tasks.json 使任务能在重启后存活;并非每个会话都支持持久调度:不支持时 Claude Code 接受 durable: true 但只创建会话级任务,读输出里的 durable 字段可知实际结果。CronDelete 按 CronCreate 返回的 ID 删除计划任务;CronList 列出计划任务:来自 .claude/scheduled_tasks.json 的持久任务和当前会话的会话级任务。

ScheduleWakeup

工具名: ScheduleWakeup

type ScheduleWakeupInput = {
  delaySeconds?: number;
  reason?: string;
  prompt?: string;
  noop?: boolean;
  stop?: boolean;
};

安排一次性唤醒,在延迟之后触发给定的提示。该工具支撑自定节奏的 /loop 命令。运行时把 delaySeconds 钳到 60 到 3600 秒之间。除非 stop 为 true,否则 delaySeconds、reason、prompt 和 noop 字段都是必需的。

RemoteTrigger

工具名: RemoteTrigger

type RemoteTriggerInput = {
  action:
    | "list"
    | "get"
    | "create"
    | "update"
    | "run"
    | "create_webhook_trigger"
    | "list_runs"
    | "get_run_log";
  trigger_id?: string;
  session_id?: string;
  cursor?: string;
  body?: {
    [k: string]: unknown;
  };
};

管理例程(Routines),即托管在云端的计划和触发式 Claude Code 运行;该工具支撑 /schedule 命令。get、update、run 和 list_runs 动作需要 trigger_id;create、update 和 create_webhook_trigger 需要 body。create_webhook_trigger 把事件源(如触发它的 GitHub 事件)附加到现有例程,body 点名来源、事件和要触发的例程(需要 Claude Code v2.1.225 及以上)。list_runs 列出例程最近的运行,get_run_log 读取一次运行的日志;session_id 点名要读取的运行(来自 list_runs 的结果),cursor 对两种动作的结果翻页;两者需要 Claude Code v2.1.227 及以上。该工具只在会话用启用了例程的套餐的 claude.ai 账号认证时可用,并在你组织的策略禁用云端会话时不存在;在 Claude Code v2.1.227 及以上,Owner 为组织关闭例程时它也不存在。

PushNotification

工具名: PushNotification

type PushNotificationInput = {
  message: string;
  status: "proactive";
};

向用户发送主动推送通知。message 保持在 200 字符以内,因为移动操作系统会截断更长的文本;推送投递经 Anthropic 托管的基础设施进行。

REPL

在 v2.1.275 中被移除。到 v2.1.274 为止,可以用 env 选项里的 CLAUDE_CODE_REPL=1 打开实验性的 REPL 工具。

ReportFindings

工具名: ReportFindings

type ReportFindingsInput = {
  level?: "low" | "medium" | "high" | "xhigh" | "max";
  findings: Array<{
    file: string;
    line?: number;
    summary: string;
    failure_scenario: string;
    short_summary?: string;
    category?: string;
    verdict?: "CONFIRMED" | "PLAUSIBLE";
    outcome?: "fixed" | "skipped" | "no_change_needed";
  }>;
};

以结构化列表报告代码审查发现,让 Claude Code 能渲染它们,而不是作为文本打印。level 是审查运行时的努力级别;发现按严重程度由高到低排序,每次调用最多 32 条,没有任何发现存活时数组为空(需要 Claude Code v2.1.196 及以上)。每条发现的字段:file 是发现所在的仓库相对路径,可选的 line 是它锚定的 1 起始行号;summary 是缺陷的一句话陈述,failure_scenario 描述导致错误输出或崩溃的具体输入和状态;short_summary 是用于紧凑显示的、最多 60 字符的可选压缩标签(需要 v2.1.212 及以上);category 是发现类型的可选简短 kebab-case 标识,如 correctness 或 test-coverage(需要 v2.1.199 及以上);verdict 在做了验证过程时设置,仅内联的审查中不存在;outcome 只在应用修复后重新报告时设置。

Artifact

工具名: Artifact

type ArtifactInput = {
  action?: "publish" | "list";
  file_path?: string;
  favicon?: string;
  icon?: string;
  limit?: number;
  scope?: "mine" | "shared" | "all";
  title?: string;
  description?: string;
  label?: string;
  url?: string;
  force?: boolean;
  capabilities?: Record<string, unknown>;
  contract?: "latest" | string;
};

把本地 .html 或 .md 文件发布为托管的 artifact 页面,或列出用户已发布的 artifacts。省略 action 或传 "publish" 来发布 file_path(发布动作必需)。下面每个字段适用于发布:icon 是 artifact 浏览器标签图标的一个简短通用词,如 chart 或 map,Claude 在首次发布时包含它,在更新时省略它以保持 artifact 已存储的图标;favicon 已弃用,Claude 省略它;title 在 HTML 文件没有 <title> 标签时给浏览器标签和画廊里的已发布页面命名;url 指向要就地更新的现有 artifact,而不是新建。force 是最后手段的覆盖,会丢弃另一个会话发布的较新版本:冲突时失败的发布会返回较新的内容,Claude 把自己的改动合并到该内容上,或重新读取 artifact,然后再次发布;只在用户明确要求丢弃时才传 force。传 "list" 枚举用户已发布的 artifacts,只有 limit 和 scope 可以随之传入;scope 默认 "mine"(列出用户拥有的 artifacts),"shared" 列出别人与用户分享的,"all" 两者都列。capabilities 是已发布页面使用的运行时能力,以能力名为键,如页面可能调用的连接器;artifact 服务验证该声明,并拒绝点名账号无法使用的能力或给某个能力无效配置的发布,传 {} 清除。contract 是已发布页面运行所对照的运行时版本:省略以保持 artifact 的当前版本,传 "latest" 升级,或传具体版本来固定或回滚(需要 Agent SDK v0.3.235 及以上)。这些类型被导出,但该工具在 Agent SDK 会话里默认关闭;发布还要求满足 artifacts 可用性表里的每个条件,用 API key 认证的会话不满足这些条件。

Projects

工具名: Projects

type ProjectsInput = {
  method:
    | "project_info"
    | "project_read"
    | "project_search"
    | "project_write"
    | "project_delete";
  path?: string;
  content?: string;
  local_path?: string;
  present_to_user?: boolean;
  query?: string;
  n?: number;
};

读写附加到会话的 claude.ai Project,按 method 分发:project_info 返回项目元数据和文档列表;project_read 按 path 读取一个文档;project_search 用 query 查询项目的知识库,n 限制命中数,默认 5;project_write 在 path 创建或替换文档,内容恰好来自 content(内联文本)或 local_path(工作目录内的文件)之一,present_to_user: true 把写入的文档标为用户需要看到的交付物;project_delete 按 path 删除文档。

ReadMcpResourceDir、RefreshMcpTools、ShowOnboardingRolePicker、McpInput

type ReadMcpResourceDirInput = {
  server: string;
  uri: string;
};

type RefreshMcpToolsInput = {
  server?: string; // 只刷新这个服务器;省略则刷新所有已连接服务器
};

type ShowOnboardingRolePickerInput = {};

type McpInput = {
  [k: string]: unknown;
};

ReadMcpResourceDirTool 列出 MCP 服务器上目录资源的直接子项,只能用于声明支持目录列表的服务器,列表不是递归的;并非每个会话都启用目录列表:关闭时,调用返回空的 resources 列表并带 error 字段。RefreshMcpTools 重新查询已连接 MCP 服务器的工具列表并应用变化;类型被导出,但只有在 env 选项里设了 CLAUDE_CODE_ENABLE_REFRESH_MCP_TOOLS=1、且会话至少有一个 MCP 服务器时,Claude Code 才注册该工具(需要 Claude Code v2.1.211 及以上)。ShowOnboardingRolePicker 在 Cowork 引导期间渲染可点击的角色选择条,让用户选择角色并装上匹配的插件;不带参数,角色列表由客户端定义,调用会阻塞到用户响应。McpInput 用于形如 mcp__<server>__<tool> 的动态 MCP 工具名:MCP 工具参数是开放对象,每个服务器定义自己的参数,所以该类型对字段名或值不加约束,具体工具接受哪些字段要查服务器自己的工具 schema。

工具输出类型

ToolOutputSchemas

从 @anthropic-ai/claude-agent-sdk/sdk-tools 导出的工具输出类型的联合,代表每个工具返回的实际响应数据:

type ToolOutputSchemas =
  | AgentOutput
  | ArtifactOutput
  | AskUserQuestionOutput
  | BashOutput
  | CronCreateOutput
  | CronDeleteOutput
  | CronListOutput
  | EnterPlanModeOutput
  | EnterWorktreeOutput
  | ExitPlanModeOutput
  | ExitWorktreeOutput
  | FileEditOutput
  | FileReadOutput
  | FileWriteOutput
  | GlobOutput
  | GrepOutput
  | ListMcpResourcesOutput
  | McpOutput
  | MonitorOutput
  | NotebookEditOutput
  | ProjectsOutput
  | PushNotificationOutput
  | ReadMcpResourceDirOutput
  | ReadMcpResourceOutput
  | RefreshMcpToolsOutput
  | RemoteTriggerOutput
  | ReportFindingsOutput
  | ScheduleWakeupOutput
  | ShowOnboardingRolePickerOutput
  | TaskCreateOutput
  | TaskGetOutput
  | TaskListOutput
  | TaskStopOutput
  | TaskUpdateOutput
  | TodoWriteOutput
  | WebFetchOutput
  | WebSearchOutput
  | WorkflowOutput;

Agent

type AgentOutput =
  | {
      status: "completed";
      agentId: string;
      agentType?: string;
      content: Array<{ type: "text"; text: string; citations?: unknown[] | null }>;
      resolvedModel?: string;
      modelsUsed?: string[];
      totalToolUseCount: number;
      totalDurationMs: number;
      totalTokens: number;
      usage: {
        input_tokens: number;
        output_tokens: number;
        cache_creation_input_tokens: number | null;
        cache_read_input_tokens: number | null;
        server_tool_use: {
          web_search_requests: number;
          web_fetch_requests: number;
        } | null;
        service_tier: string | null;
        cache_creation: {
          ephemeral_1h_input_tokens: number;
          ephemeral_5m_input_tokens: number;
        } | null;
        inference_geo?: string | null;
        speed?: string | null;
        iterations?: unknown;
        output_tokens_details?: {
          thinking_tokens?: number | null;
        } | null;
      };
      toolStats?: {
        readCount: number;
        searchCount: number;
        bashCount: number;
        editFileCount: number;
        linesAdded: number;
        linesRemoved: number;
        otherToolCount: number;
        frameCount?: number;
      };
      prompt: string;
      worktreePath?: string;
      worktreeBranch?: string;
    }
  | {
      status: "async_launched";
      isAsync?: true;
      agentId: string;
      description: string;
      resolvedModel?: string;
      modelsUsed?: string[];
      prompt: string;
      outputFile: string;
      canReadOutputFile?: boolean;
    }
  | {
      status: "remote_launched";
      taskId: string;
      sessionUrl: string;
      description: string;
      prompt: string;
      outputFile: string;
    };

返回子智能体的结果,按 status 字段区分:"completed" 表示已完成的任务,"async_launched" 表示后台任务,"remote_launched" 表示 Claude Code 分发到云端会话的任务(sessionUrl 链接到该会话)。在 completed 变体上,resolvedModel 点名子智能体起始使用的模型,当 availableModels 或其他覆盖生效时它可能与请求的 model 输入不同(该字段需要 Claude Code v2.1.174 及以上)。modelsUsed 按顺序列出子智能体用过的模型,只有发生了运行中途的模型交换时才出现,运行换回某个模型时它再次出现;在 async_launched 上,该列表涵盖转入后台之前用过的模型。如果 Claude Code 保留了子智能体的隔离 worktree,completed 结果上的 worktreePath 就是找到它的位置,worktreeBranch 是它的分支(Claude Code 用 git 创建 worktree 时才有)。Claude Code 从子智能体的最后一个 API 请求而不是整次运行填充 usage 和 totalTokens,所以 usage.service_tier 是 API 在该请求上报告的服务层级字符串;存在时,usage.output_tokens_details.thinking_tokens 是该请求的思考 token 数;usage.output_tokens_details 的含义与 Usage.output_tokens_details 相同、范围限于该最后请求,但这里它的每一层都是可选的,所以要同时守卫对象和字段,例如 usage.output_tokens_details?.thinking_tokens ?? 0。v2.1.207 之前,已发布的类型更窄:省略了 worktreePath、worktreeBranch、citations、toolStats.frameCount 以及 inference_geo、speed、iterations 这几个用量字段,并把 service_tier 类型定为固定的几个字符串。

AskUserQuestion

type AskUserQuestionOutput = {
  questions: Array<{
    question: string;
    header: string;
    options: Array<{ label: string; description: string; preview?: string }>;
    multiSelect: boolean;
  }>;
  answers: Record<string, string>;
  response?: string;
  annotations?: Record<string, { preview?: string; notes?: string }>;
  afkTimeoutMs?: number;
};

返回所提的问题和用户的回答。用户键入了自由回复而不是回答结构化问题时设置 response;存在时,Claude 收到 "The user responded: …" 而不是逐题的回答列表。

Bash

type BashOutput = {
  stdout: string;
  stderr: string;
  rawOutputPath?: string;
  interrupted: boolean;
  isImage?: boolean;
  backgroundTaskId?: string;
  backgroundedByUser?: boolean;
  timedOutAfterMs?: number;
  backgroundCwdHint?: string;
  backgroundEndsWithFinalResponse?: true;
  dangerouslyDisableSandbox?: boolean;
  returnCodeInterpretation?: string;
  noOutputExpected?: boolean;
  structuredContent?: unknown[];
  persistedOutputPath?: string;
  persistedOutputSize?: number;
  staleReadFileStateHint?: string;
  ghRateLimitHint?: string;
  gitOperation?: {
    commit?: { sha: string; kind: "committed" | "amended" | "cherry-picked"; branch?: string };
    push?: { branch: string };
    branch?: { ref: string; action: "merged" | "rebased" };
    pr?: {
      number: number;
      url?: string;
      action: "created" | "edited" | "merged" | "commented" | "closed" | "reopened" | "ready" | "draft" | "auto-merge-enabled" | "auto-merge-disabled";
    };
  };
};

stdout 携带命令的 stdout 和 stderr,合并成一个交错的流;stderr 携带工具自己添加的通知(如 shell 工作目录重置),不是命令的 stderr;backgroundTaskId 对后台命令存在。timedOutAfterMs 是命令达到超时并转入后台(而不是一开始就显式在后台)时设置的超时毫秒数。当前台运行的子智能体拥有一个被转入后台的命令时,该命令在该子智能体运行结束时结束;Claude Code 在这类命令上把 backgroundEndsWithFinalResponse 设为 true,命令能活过该轮次时省略该字段。Claude Code 把 gitOperation.commit.branch 设为 git 提交摘要行里点名的分支,在分离 HEAD 上做的提交则省略它(该字段需要 Agent SDK v0.3.227 及以上)。

Monitor

type MonitorOutput = {
  taskId: string;
  timeoutMs: number;
  persistent?: boolean;
};

返回运行中监视的后台任务 ID;用这个 ID 配合 TaskStop 可提前取消监视。

Edit

type FileEditOutput = {
  filePath: string;
  oldString: string;
  newString: string;
  originalFile: string | null;
  structuredPatch: Array<{
    oldStart: number;
    oldLines: number;
    newStart: number;
    newLines: number;
    lines: string[];
  }>;
  userModified: boolean;
  replaceAll: boolean;
  gitDiff?: {
    filename: string;
    status: "modified" | "added";
    additions: number;
    deletions: number;
    changes: number;
    patch: string;
    repository?: string | null;
  };
};

返回编辑操作的结构化 diff。

Read

type FileReadOutput =
  | {
      type: "text";
      file: {
        filePath: string;
        content: string;
        numLines: number;
        startLine: number;
        totalLines: number;
        /** 整文件读取因超过 token 上限而被自动分页时为 true(content 是部分的第一页)。 */
        truncatedByTokenCap?: boolean;
      };
    }
  | {
      type: "image";
      file: {
        base64: string;
        type: "image/jpeg" | "image/png" | "image/gif" | "image/webp";
        originalSize: number;
        dimensions?: {
          originalWidth?: number;
          originalHeight?: number;
          displayWidth?: number;
          displayHeight?: number;
        };
      };
    }
  | {
      type: "notebook";
      file: {
        filePath: string;
        cells: unknown[];
      };
    }
  | {
      type: "pdf";
      file: {
        filePath: string;
        base64: string;
        originalSize: number;
      };
    }
  | {
      type: "parts";
      file: {
        filePath: string;
        originalSize: number;
        count: number;
        outputDir: string;
      };
      /** 第一个提取页的文档页码;给 tool_result 内容里的页面图片加标签。 */
      firstPage?: number;
      /** 仅进程内:页面图片字节作为 image 块在 tool_result 内容里交付,不保留在发出的 tool_use_result 上,所以该键在那里不存在。 */
      pages?: {
        base64: string;
        mediaType: "image/jpeg" | "image/png" | "image/gif" | "image/webp";
        error?: string;
      }[];
    }
  | {
      type: "file_unchanged";
      file: {
        filePath: string;
      };
      /** 去重匹配的是启动时播种的条目(CLAUDE.md/嵌套记忆)而不是先前的 Read tool_result 时设置。 */
      source?: "seeded";
    };

按适合文件类型的格式返回文件内容,按 type 字段区分。

Write

type FileWriteOutput = {
  type: "create" | "update";
  filePath: string;
  content: string;
  structuredPatch: Array<{
    oldStart: number;
    oldLines: number;
    newStart: number;
    newLines: number;
    lines: string[];
  }>;
  originalFile: string | null;
  gitDiff?: {
    filename: string;
    status: "modified" | "added";
    additions: number;
    deletions: number;
    changes: number;
    patch: string;
    repository?: string | null;
  };
  userModified?: boolean;
};

返回写入结果和结构化 diff 信息。originalFile 和 structuredPatch 的内容取决于写入:新创建的文件,originalFile 为 null 且 structuredPatch 为空;覆盖时,originalFile 携带先前内容,除非该内容大于约 10 MB,此时 Claude Code 跳过 diff,返回 originalFile 为 null 且 structuredPatch 为空;写入没有改变任何东西或 diff 超时时,structuredPatch 也为空。

Glob

type GlobOutput = {
  durationMs: number;
  numFiles: number;
  filenames: string[];
  truncated: boolean;
  totalMatches?: number;
  countIsComplete?: boolean;
};

返回匹配 glob 模式的文件路径,按修改时间排序。totalMatches 和 countIsComplete 需要 Claude Code v2.1.191 及以上:totalMatches 报告截断前匹配文件的数量;countIsComplete 为 false 时,totalMatches 是下限,因为底层搜索自己截断了结果。

Grep

type GrepOutput = {
  mode?: "content" | "files_with_matches" | "count";
  numFiles: number;
  filenames: string[];
  content?: string;
  numLines?: number;
  numMatches?: number;
  totalFiles?: number;
  totalLines?: number;
  appliedLimit?: number;
  appliedOffset?: number;
};

返回搜索结果,形状随 mode 变化:文件列表、带匹配的内容,或匹配计数。count 模式下,numFiles 和 numMatches 是整个结果集的总数,不是分页后的切片。totalFiles 需要 Claude Code v2.1.208 及以上,报告 files_with_matches 模式下 head_limit 和 offset 分页之前的结果总数;totalLines 需要 v2.1.210 及以上,报告分页之前的行总数。

TaskStop、NotebookEdit、WebFetch、WebSearch

type TaskStopOutput = {
  message: string;
  task_id: string;
  task_type: string;
  command?: string;
};

type NotebookEditOutput = {
  new_source: string;
  old_source?: string;
  cell_id?: string;
  cell_type: "code" | "markdown";
  language: string;
  edit_mode: string;
  error?: string;
  notebook_path: string;
  original_file: string;
  updated_file: string;
};

type WebFetchOutput = {
  bytes: number;
  code: number;
  codeText: string;
  result: string;
  durationMs: number;
  url: string;
  artifactRead?: {
    slug: string;
    ver?: string;
    seeded?: false;
  };
};

type WebSearchOutput = {
  query: string;
  results: Array<
    | {
        tool_use_id: string;
        content: Array<{ title: string; url: string }>;
      }
    | string
  >;
  durationSeconds: number;
  searchCount?: number;
};

TaskStop 返回停止后台任务后的确认;NotebookEdit 返回带原始和更新后文件内容的 notebook 编辑结果;WebFetch 返回获取的内容以及 HTTP 状态和元数据,其中 artifactRead 是 Claude Code 自己对 artifact 读取的记录,只在 Claude 获取了会话可发布到的 artifact 时才有,会话恢复时 Claude Code 读回它,使之后的发布基于正确的版本,你的代码不需要使用它;WebSearch 返回来自网络的搜索结果。

Workflow

type WorkflowOutput = {
  status: "async_launched" | "remote_launched";
  taskId: string;
  taskType?: "local_workflow" | "remote_agent";
  workflowName?: string;
  runId?: string;
  summary?: string;
  transcriptDir?: string;
  scriptPath?: string;
  sessionUrl?: string; // 工作流作为云端会话启动时设置
  warning?: string;
  error?: string;
};

工具接受调用后立即返回,最终结果稍后作为任务完成到达。在把运行视为已启动之前要先检查 error:语法检查失败的脚本返回设了 error 的 status: "async_launched",而运行并没有启动。

字段类型说明
status"async_launched" | "remote_launched"工具接受了调用:"async_launched" 表示进程内运行,"remote_launched" 表示分发到云端会话而不是在进程内运行
taskIdstring该运行的后台任务标识
taskType"local_workflow" | "remote_agent"已注册后台任务的任务类型,与 status 分支一致
workflowNamestring工作流脚本里的 meta.name
runIdstring在之后的调用里作为 resumeFromRunId 传入的工作流运行标识;remote_launched 的运行没有,其恢复句柄是云端会话 URL
summarystring工作流做什么的一行描述
transcriptDirstring执行期间写入子智能体记录的目录
scriptPathstring该运行的持久化工作流脚本的路径;编辑它并作为 scriptPath 传回,即可不重发脚本地重新运行
sessionUrlstring云端会话 URL,status 为 "remote_launched" 时设置
warningstring非阻塞的提醒,例如本地 git 状态与云端会话将克隆的已推送分支分歧
errorstring脚本语法检查失败时设置;存在时,尽管有 launched 状态,运行并没有开始

TodoWrite 与 Task 工具

type TodoWriteOutput = {
  oldTodos: Array<{
    content: string;
    status: "pending" | "in_progress" | "completed";
    activeForm: string;
  }>;
  newTodos: Array<{
    content: string;
    status: "pending" | "in_progress" | "completed";
    activeForm: string;
  }>;
};

type TaskCreateOutput = {
  task: {
    id: string;
    subject: string;
  };
};

type TaskUpdateOutput = {
  success: boolean;
  taskId: string;
  updatedFields: string[];
  error?: string;
  statusChange?: {
    from: string;
    to: string;
  };
};

type TaskGetOutput = {
  task: {
    id: string;
    subject: string;
    description: string;
    status: "pending" | "in_progress" | "completed";
    blocks: string[];
    blockedBy: string[];
  } | null;
};

type TaskListOutput = {
  tasks: Array<{
    id: string;
    subject: string;
    status: "pending" | "in_progress" | "completed";
    owner?: string;
    blockedBy: string[];
  }>;
};

TodoWrite 返回之前和更新后的任务列表;TaskCreate 返回已创建的任务及其分配的 ID;TaskUpdate 返回更新结果,包括哪些字段变了;TaskGet 返回完整的任务记录,ID 找不到时 task 为 null;TaskList 返回当前列表里所有任务的快照。

计划、worktree 与 MCP 资源

type ExitPlanModeOutput = {
  plan: string | null;
  isAgent: boolean;
  filePath?: string;
  hasTaskTool?: boolean;
  planWasEdited?: boolean;
  awaitingLeaderApproval?: boolean;
  requestId?: string;
};

type EnterPlanModeOutput = {
  message: string;
};

type EnterWorktreeOutput = {
  worktreePath: string;
  worktreeBranch?: string;
  message: string;
};

type ExitWorktreeOutput = {
  action: "keep" | "remove";
  originalCwd: string;
  worktreePath: string;
  worktreeBranch?: string;
  tmuxSessionName?: string;
  discardedFiles?: number;
  discardedCommits?: number;
  message: string;
};

type ListMcpResourcesOutput = Array<{
  uri: string;
  name: string;
  mimeType?: string;
  description?: string;
  server: string;
}>;

type ReadMcpResourceOutput = {
  contents: Array<{
    uri: string;
    mimeType?: string;
    text?: string;
    blobSavedTo?: string;
  }>;
  error?: string;
};

type ReadMcpResourceDirOutput = {
  resources: Array<{
    uri: string;
    name: string;
    mimeType?: string;
  }>;
  error?: string;
};

type RefreshMcpToolsOutput = Array<{
  server: string;
  status: "refreshed" | "error" | "not_connected";
  toolCount?: number; // 该服务器现在可用的工具数
  added?: string[]; // 这次刷新添加的工具名
  removed?: string[]; // 这次刷新移除的工具名
  error?: string; // 刷新为何失败或服务器为何不可用
}>;

ExitPlanMode 返回退出 plan 模式后的计划状态;EnterPlanMode 返回已进入 plan 模式的确认;EnterWorktree 返回 git worktree 的信息;ExitWorktree 返回所采取的动作以及所退出 worktree 的详情。ListMcpResources 返回可用 MCP 资源的数组,ReadMcpResource 返回所请求 MCP 资源的内容。ReadMcpResourceDir 返回目录资源的直接子项:子目录以 mimeType "inode/directory" 出现,服务器无法列出目录时 error 携带人类可读的消息。RefreshMcpTools 每个服务器返回一个条目:refreshed 表示重新查询到的工具列表已应用,error 表示重新查询失败并保留了先前的工具集,not_connected 表示服务器没有可查询的活动连接。

计划任务、通知与其他

type CronCreateOutput = {
  id: string;
  humanSchedule: string;
  recurring: boolean;
  durable?: boolean; // 持久化到 .claude/scheduled_tasks.json 时为 true;仅会话级时为 false
};

type CronDeleteOutput = {
  id: string;
};

type CronListOutput = {
  jobs: {
    id: string;
    cron: string;
    humanSchedule: string;
    prompt: string;
    recurring?: boolean;
    durable?: boolean;
  }[];
};

type ScheduleWakeupOutput = {
  scheduledFor: number;
  clampedDelaySeconds: number;
  wasClamped: boolean;
  stopped?: boolean;
  cancelledWakeups?: number;
};

type RemoteTriggerOutput = {
  status: number;
  json: string;
  summary?: string;
};

type PushNotificationOutput = {
  message: string;
  pushSent?: boolean;
  localSent?: boolean;
  disabledReason?: "config_off" | "user_present" | "no_transport";
  sentAt?: string;
};

type ReportFindingsOutput = {
  count: number;
  level?: "low" | "medium" | "high" | "xhigh" | "max";
  findings: Array<{
    file: string;
    line?: number;
    summary: string;
    failure_scenario: string;
    short_summary?: string;
    category?: string;
    verdict?: "CONFIRMED" | "PLAUSIBLE";
    outcome?: "fixed" | "skipped" | "no_change_needed";
  }>;
};

type ShowOnboardingRolePickerOutput = {
  role?: string;
  dismissed?: boolean;
};

type McpOutput =
  | string
  | {
      type: string;
      [k: string]: unknown;
    }[]
  | {
      [k: string]: unknown;
    };

CronCreate 返回任务 ID 和计划的人类可读描述;CronDelete 返回被删除任务的 ID;CronList 返回计划任务:来自 .claude/scheduled_tasks.json 的持久任务和当前会话的会话级任务,会话级任务带 durable: false,从磁盘读取的任务省略该字段。ScheduleWakeup 返回唤醒将触发的 epoch 毫秒时间戳、实际使用的延迟,以及所请求的延迟是否被钳制;调用以 stop: true 结束循环时 stopped 为 true(需要 Claude Code v2.1.202 及以上)。RemoteTrigger 返回触发器操作的 API 响应状态和正文。PushNotification 返回投递详情,包括是否发送了推送或本地通知以及投递被跳过的原因。ReportFindings 返回已报告的发现数量、审查运行时的努力级别,以及为结果正文回显的发现(需要 Claude Code v2.1.196 及以上;回显的 short_summary 字段需要 v2.1.212 及以上)。ShowOnboardingRolePicker 返回用户的选择:用户选了角色标签或键入了角色时有 role,关闭选择器时 dismissed: true,空对象表示用户批准了调用但没选角色。McpOutput 用于动态 MCP 工具名:MCP 工具结果按服务器的不同以字符串或内容块数组返回,导出类型末尾的普通对象分支是 schema 生成的产物:SDK 不返回裸对象。

Artifact 与 Projects 的输出

type ArtifactOutput =
  | {
      url: string;
      path: string;
      title?: string;
      version?: string;
      capabilities?: unknown;
      stored?: {
        contract: string;
        capabilities?: Record<string, unknown>;
      };
      warnings?: string[];
      contract?: string;
      updated?: boolean;
      liveSubscription?: string;
    }
  | {
      artifacts: Array<{
        title: string;
        url: string;
        updatedAt?: string;
        rel?: "mine" | "shared";
      }>;
      truncated?: boolean;
      scope?: "shared" | "all";
    };

type ProjectsOutput =
  | {
      method: "project_info";
      notice?: string;
      name: string;
      description: string;
      instructions: string;
      docs: Array<{ path: string; created_at: string | null }>;
      files?: Array<{
        path: string;
        file_kind: string;
        created_at: string | null;
      }>;
      sync_sources?: Array<{
        type: string | null;
        config: Record<string, unknown>;
      }>;
      knowledge: {
        knowledge_size: number;
        max_knowledge_size: number;
      };
    }
  | {
      method: "project_read";
      notice?: string;
      path: string;
      file_kind?: string;
      content?: string;
      local_file?: string;
      created_at: string | null;
    }
  | {
      method: "project_search";
      notice?: string;
      rag: boolean;
      hits?: Array<{ name?: string; doc_uuid?: string; text?: string }>;
      docs?: string[];
    }
  | {
      method: "project_write";
      notice?: string;
      path: string;
      doc_uuid: string;
      replaced: boolean;
      present_to_user?: boolean;
      local_path?: string;
    }
  | {
      method: "project_delete";
      notice?: string;
      path: string;
      deleted: boolean;
    };

Artifact 的发布动作返回已发布页面的 url 和被发布的本地 path,发布重新部署了现有 artifact 时 updated 为 true,warnings 携带发布时的任何提示;列出动作返回 artifacts 数组。Projects 按 method 字段区分,与输入对应:project_read 把小的文本文档内联在 content 里返回,把较大的文档写到 local_file 路径;project_search 在项目索引可用时返回 rag: true 的 RAG hits。

权限类型

PermissionUpdate

更新权限的操作。

type PermissionUpdate =
  | {
      type: "addRules";
      rules: PermissionRuleValue[];
      behavior: PermissionBehavior;
      destination: PermissionUpdateDestination;
    }
  | {
      type: "replaceRules";
      rules: PermissionRuleValue[];
      behavior: PermissionBehavior;
      destination: PermissionUpdateDestination;
    }
  | {
      type: "removeRules";
      rules: PermissionRuleValue[];
      behavior: PermissionBehavior;
      destination: PermissionUpdateDestination;
    }
  | {
      type: "setMode";
      mode: PermissionMode;
      destination: PermissionUpdateDestination;
    }
  | {
      type: "addDirectories";
      directories: string[];
      destination: PermissionUpdateDestination;
    }
  | {
      type: "removeDirectories";
      directories: string[];
      destination: PermissionUpdateDestination;
    };

PermissionBehavior、PermissionUpdateDestination、PermissionRuleValue

type PermissionBehavior = "allow" | "deny" | "ask";

type PermissionUpdateDestination =
  | "userSettings" // 全局用户设置
  | "projectSettings" // 每目录的项目设置
  | "localSettings" // 本地项目设置
  | "session" // 仅当前会话
  | "cliArg"; // CLI 参数

type PermissionRuleValue = {
  toolName: string;
  ruleContent?: string;
};