mirror of
https://github.com/claude-code-best/claude-code.git
synced 2026-06-15 12:55:51 +00:00
docs: 重写工具系统,从35字段列举改为设计分析
移除 TypeScript 类型定义、源码路径和 buildTool 代码, 聚焦统一接口的设计洞察(动态描述、校验-权限分离、 渲染一等公民)、分层注册策略和调用链路的错误处理设计。 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,12 +1,10 @@
|
||||
---
|
||||
title: "工具系统设计 - AI 如何从说到做"
|
||||
description: "深入理解 Claude Code 的 Tool 抽象设计:从类型定义、注册机制、调用链路到渲染系统,揭示 50+ 内置工具如何通过统一的 Tool 接口协同工作。"
|
||||
keywords: ["工具系统", "Tool 抽象", "AI 工具", "function calling", "buildTool", "getTools"]
|
||||
title: "工具系统"
|
||||
description: "AI 本质上只能生成文本。工具是 AI 的双手——让它能读文件、跑命令、搜代码。理解统一接口、分层注册和调用链路的设计。"
|
||||
keywords: ["工具系统", "Tool 抽象", "AI 工具", "function calling"]
|
||||
---
|
||||
|
||||
{/* 本章目标:基于 src/Tool.ts 和 src/tools.ts 揭示工具系统的完整架构 */}
|
||||
|
||||
## AI 为什么需要工具
|
||||
## 核心问题
|
||||
|
||||
大语言模型本质上只能做一件事:**根据输入文本,生成输出文本**。
|
||||
|
||||
@@ -14,159 +12,93 @@ keywords: ["工具系统", "Tool 抽象", "AI 工具", "function calling", "buil
|
||||
|
||||
工具是 AI 的双手。AI 说"我想读这个文件",工具系统替它真正去读;AI 说"我想执行这条命令",工具系统替它真正去跑。
|
||||
|
||||
## Tool 类型:35 个字段的统一接口
|
||||
## 统一接口:一个工具长什么样
|
||||
|
||||
所有工具都实现 `src/Tool.ts:368` 的 `Tool<Input, Output, Progress>` 类型。这不是一个 class,而是一个包含 35+ 字段的**结构化类型**(structural typing),任何满足该接口的对象就是一个工具:
|
||||
所有工具——无论是读文件、执行命令还是启动子 Agent——都实现同一个接口。这不是一个类,而是一个结构化类型:任何满足该接口的对象就是一个工具。
|
||||
|
||||
### 核心四要素
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| `name` | `string` | 唯一标识(如 `Read`、`Bash`、`Agent`) |
|
||||
| `description()` | `(input) => Promise<string>` | **动态描述**——根据输入参数返回不同描述(如 `Execute skill: ${skill}`) |
|
||||
| `inputSchema` | `z.ZodType` | Zod schema,定义参数类型和校验规则 |
|
||||
| `call()` | `(args, context, canUseTool, parentMessage, onProgress?) => Promise<ToolResult<Output>>` | 执行函数 |
|
||||
|
||||
### 注册与发现
|
||||
|
||||
| 字段 | 说明 |
|
||||
| 要素 | 作用 |
|
||||
|------|------|
|
||||
| `aliases` | 别名数组(向后兼容重命名) |
|
||||
| `searchHint` | 3-10 词的短语,供 ToolSearch 关键词匹配(如 `"jupyter"` for NotebookEdit) |
|
||||
| `shouldDefer` | 是否延迟加载(配合 ToolSearch 按需加载) |
|
||||
| `alwaysLoad` | 永不延迟加载(如 SkillTool 必须在 turn 1 可见) |
|
||||
| `isEnabled()` | 运行时开关(如 PowerShellTool 检查平台) |
|
||||
| **name** | 唯一标识(如 `Read`、`Bash`、`Agent`) |
|
||||
| **description()** | 动态描述——根据输入参数返回不同描述 |
|
||||
| **inputSchema** | 参数类型和校验规则(Zod schema) |
|
||||
| **call()** | 执行函数——真正做事的地方 |
|
||||
|
||||
### 安全与权限
|
||||
**设计洞察**:`description()` 是动态的而非静态字符串。这意味着同一个工具在不同参数下可以展示不同的描述——例如 Agent 工具会显示它正在执行的具体子任务。
|
||||
|
||||
| 字段 | 说明 |
|
||||
|------|------|
|
||||
| `validateInput()` | 输入校验(在权限检查之前),返回 `ValidationResult` |
|
||||
| `checkPermissions()` | 权限检查(在校验之后),返回 `PermissionResult` |
|
||||
| `isReadOnly()` | 是否只读操作(影响权限模式) |
|
||||
| `isDestructive()` | 是否不可逆操作(删除、覆盖、发送) |
|
||||
| `isConcurrencySafe()` | 相同输入是否可以并行执行 |
|
||||
| `preparePermissionMatcher()` | 为 Hook 的 `if` 条件准备模式匹配器 |
|
||||
| `interruptBehavior()` | 用户中断时的行为:`'cancel'` 或 `'block'` |
|
||||
### 安全层字段
|
||||
|
||||
### 输出与渲染
|
||||
工具接口包含了完整的安全控制:
|
||||
|
||||
| 字段 | 说明 |
|
||||
|------|------|
|
||||
| `maxResultSizeChars` | 结果字符上限(超出则持久化到磁盘,如 `100_000`) |
|
||||
| `mapToolResultToToolResultBlockParam()` | 将 Output 映射为 API 格式的 `ToolResultBlockParam` |
|
||||
| `renderToolResultMessage()` | React 组件渲染工具结果到终端 |
|
||||
| `renderToolUseMessage()` | React 组件渲染工具调用过程 |
|
||||
| `backfillObservableInput()` | 在不破坏 prompt cache 的前提下回填可观察字段 |
|
||||
- **validateInput()** — 输入校验(在权限检查之前)
|
||||
- **checkPermissions()** — 权限检查(在校验之后)
|
||||
- **isReadOnly()** — 是否只读(影响权限模式的自动审批)
|
||||
- **isDestructive()** — 是否不可逆(触发更严格的确认)
|
||||
- **interruptBehavior()** — 用户中断时的行为(取消 vs 阻塞)
|
||||
|
||||
### 上下文与 Prompt
|
||||
**设计考量**:校验和权限是两个独立步骤,有明确的执行顺序。校验先于权限——如果输入本身不合法,就不需要检查权限。这避免了在无效输入上触发权限 UI 的尴尬体验。
|
||||
|
||||
| 字段 | 说明 |
|
||||
|------|------|
|
||||
| `prompt()` | 返回该工具的详细使用说明,注入到 System Prompt |
|
||||
| `outputSchema` | 输出 Zod schema(用于类型安全的结果处理) |
|
||||
| `getPath()` | 提取操作的文件路径(用于权限匹配和 UI 显示) |
|
||||
### 渲染字段
|
||||
|
||||
## 工具注册:`getTools()` 的分层组装
|
||||
每个工具不仅有执行逻辑,还有 UI 渲染:
|
||||
- 工具调用时的进度展示
|
||||
- 工具结果的内容渲染
|
||||
- 活动描述(为 spinner 提供文字,如 "Reading src/foo.ts")
|
||||
|
||||
`src/tools.ts` 的 `getAllBaseTools()`(第 195 行)是工具注册的核心:
|
||||
**设计哲学**:工具不是黑盒。用户应该实时看到 AI 正在做什么、结果是什么。渲染与执行是同一接口的一等公民。
|
||||
|
||||
## 工具注册:分层组装
|
||||
|
||||
工具不是一次性全部加载的。系统使用分层注册策略:
|
||||
|
||||
### 固定工具(始终可用)
|
||||
|
||||
文件操作(Read/Write/Edit)、命令执行(Bash)、搜索(Glob/Grep)、Web(Fetch/Search)等基础工具始终在工具列表中。
|
||||
|
||||
### 条件工具(运行时检查)
|
||||
|
||||
| 条件 | 加载的工具 |
|
||||
|------|-----------|
|
||||
| 需要搜索能力 | GlobTool、GrepTool |
|
||||
| 平台是 Windows | PowerShellTool |
|
||||
| Worktree 模式 | EnterWorktree/ExitWorktree |
|
||||
| Agent Swarms 启用 | Teams 相关工具 |
|
||||
|
||||
### Feature-flag 工具
|
||||
|
||||
通过 feature flag 控制的实验性工具——协调者模式工具、KAIROS 工具等。
|
||||
|
||||
**关键设计**:工具列表在每次 API 调用时重新组装,而非全局缓存。因为 `isEnabled()` 的结果可能随运行时状态变化——例如 MCP 服务器在会话中途连接或断开。
|
||||
|
||||
## 工具调用链路
|
||||
|
||||
从 AI 发出调用到结果回传,经过一条严格的管道:
|
||||
|
||||
```
|
||||
固定工具(始终可用):
|
||||
AgentTool, BashTool, FileReadTool, FileEditTool, FileWriteTool,
|
||||
NotebookEditTool, WebFetchTool, WebSearchTool, TodoWriteTool,
|
||||
AskUserQuestionTool, SkillTool, EnterPlanModeTool, ExitPlanModeV2Tool,
|
||||
TaskOutputTool, BriefTool, ListMcpResourcesTool, ReadMcpResourceTool
|
||||
|
||||
条件工具(运行时检查):
|
||||
← hasEmbeddedSearchTools() ? [] : [GlobTool, GrepTool]
|
||||
← isTodoV2Enabled() ? V2 Tasks : []
|
||||
← isWorktreeModeEnabled() ? Worktree : []
|
||||
← isAgentSwarmsEnabled() ? Teams : []
|
||||
← isToolSearchEnabled() ? ToolSearch: []
|
||||
← isPowerShellToolEnabled() ? PowerShell: []
|
||||
|
||||
Feature-flag 工具:
|
||||
← feature('COORDINATOR_MODE') ? [coordinatorMode tools]
|
||||
← feature('KAIROS') ? [SleepTool, SendUserFileTool, ...]
|
||||
← feature('WEB_BROWSER_TOOL') ? [WebBrowserTool]
|
||||
← feature('HISTORY_SNIP') ? [SnipTool]
|
||||
|
||||
Ant-only 工具:
|
||||
← process.env.USER_TYPE === 'ant' ? [REPLTool, ConfigTool, TungstenTool]
|
||||
API 返回 tool_use → 输入校验 → 权限检查 → 执行 → 结果格式化 → 回传 API
|
||||
```
|
||||
|
||||
`getTools()`(第 274 行)在 `getAllBaseTools()` 基础上应用权限过滤:
|
||||
每一步都有明确的失败路径:
|
||||
- 校验失败 → 返回错误,AI 可以修正参数重试
|
||||
- 权限拒绝 → 返回拒绝原因,AI 可以调整方案
|
||||
- 执行出错 → 返回错误信息,AI 可以诊断重试
|
||||
|
||||
```typescript
|
||||
export const getTools = (permissionContext): Tools => {
|
||||
const base = getAllBaseTools()
|
||||
// 过滤 blanket deny 规则命中的工具
|
||||
return filterToolsByDenyRules(base, permissionContext)
|
||||
}
|
||||
```
|
||||
|
||||
**关键设计**:工具列表在每次 API 调用时组装(而非全局缓存),因为 `isEnabled()` 的结果可能随运行时状态变化。
|
||||
|
||||
## `buildTool()` 工厂函数
|
||||
|
||||
大多数工具通过 `buildTool()` 创建(`src/Tool.ts:789`),它是一个类型安全的构造器:
|
||||
|
||||
```typescript
|
||||
export const BashTool: Tool<...> = buildTool({
|
||||
name: 'Bash',
|
||||
inputSchema: lazySchema(() => z.object({command: z.string(), ...})),
|
||||
// ...其他字段
|
||||
}) satisfies ToolDef<Input, Output, Progress>
|
||||
```
|
||||
|
||||
`satisfies ToolDef` 确保编译时类型检查,`lazySchema` 延迟 Zod schema 解析(避免循环依赖)。
|
||||
|
||||
## 工具调用的完整链路
|
||||
|
||||
从 AI 发出 `tool_use` 到结果回传,经过以下步骤:
|
||||
|
||||
```
|
||||
1. API 返回 tool_use block(包含 name + input)
|
||||
↓
|
||||
2. StreamingToolExecutor.addTool() / runTools()
|
||||
↓
|
||||
3. findToolByName() 查找工具
|
||||
↓
|
||||
4. validateInput() — 输入校验
|
||||
↓ 失败 → 返回错误 tool_result
|
||||
5. canUseTool() — 权限 UI(Ask 模式下弹确认)
|
||||
↓ 拒绝 → 返回拒绝 tool_result
|
||||
6. checkPermissions() — 规则匹配
|
||||
↓
|
||||
7. call() — 执行实际操作
|
||||
↓ onProgress() 回调实时更新 UI
|
||||
8. 返回 ToolResult<Output>
|
||||
↓
|
||||
9. mapToolResultToToolResultBlockParam() — 转为 API 格式
|
||||
↓
|
||||
10. 新消息追加到对话 → 进入下一轮迭代
|
||||
```
|
||||
**设计考量**:错误不是异常——它们是正常的对话流程。AI 看到错误信息后会自行调整,不需要人类介入。这把"AI 犯错 → 人类纠正"的循环转变为"AI 试错 → 自我纠正"的循环。
|
||||
|
||||
## 工具结果的预算控制
|
||||
|
||||
每个工具通过 `maxResultSizeChars` 声明输出上限:
|
||||
每个工具声明自己的输出上限(BashTool: 30K 字符,SkillTool: 100K 等)。超出上限的结果被持久化到磁盘,AI 只收到预览 + 文件路径。
|
||||
|
||||
- **BashTool**:`30_000`(命令输出)
|
||||
- **SkillTool**:`100_000`(技能执行结果)
|
||||
- **FileReadTool**:`Infinity`(文件内容不走持久化,避免 Read→file→Read 循环)
|
||||
**为什么不无限返回**?因为工具输出的 token 会累积到上下文中。一个 `find /` 命令可能产生几十万字符的输出——如果不限制,几次工具调用就能耗尽整个上下文窗口。
|
||||
|
||||
超出上限的结果被 `applyToolResultBudget()`(`src/utils/toolResultStorage.ts`)持久化到磁盘,AI 只收到预览 + 文件路径。
|
||||
FileReadTool 故意设为无上限——文件内容需要完整呈现给 AI,截断可能导致错误的代码修改。
|
||||
|
||||
## MCP 工具的扩展
|
||||
|
||||
MCP Server 提供的工具通过 `mcpInfo` 字段标记来源:
|
||||
MCP(Model Context Protocol)允许外部工具注册到系统中。MCP 工具的 schema 使用 JSON Schema 而非 Zod,因为 schema 来自远程协议而非本地定义。
|
||||
|
||||
```typescript
|
||||
mcpInfo?: { serverName: string; toolName: string }
|
||||
```
|
||||
|
||||
MCP 工具的 `inputJSONSchema` 直接使用 JSON Schema(而非 Zod),因为 schema 来自远程协议。它们通过 `filterToolsByDenyRules()` 支持 `mcp__server` 前缀的 blanket deny 规则。
|
||||
MCP 工具支持 `mcp__server` 前缀的 deny 规则——用户可以精确控制哪些 MCP 服务器的哪些工具被禁止使用。
|
||||
|
||||
## 50+ 内置工具全景
|
||||
|
||||
@@ -191,16 +123,8 @@ MCP 工具的 `inputJSONSchema` 直接使用 JSON Schema(而非 Zod),因
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## 工具的可视化渲染
|
||||
## 接下来
|
||||
|
||||
工具不仅能"做事",还能"展示"。每个工具通过 React 组件定义 UI 渲染:
|
||||
|
||||
- **FileEdit** → `renderToolResultMessage` 展示语法高亮的 diff 视图
|
||||
- **Bash** → 实时显示命令输出(通过 `onProgress` 回调),带进度指示
|
||||
- **Grep** → 高亮匹配结果,显示文件路径和行号链接
|
||||
- **Agent** → 显示子 Agent 的进度条和状态
|
||||
- **SkillTool** → 渲染技能执行进度
|
||||
|
||||
`isSearchOrReadCommand()` 允许工具声明自己是搜索/读取操作,触发 UI 的折叠显示模式(避免大量搜索结果占满屏幕)。
|
||||
|
||||
`getActivityDescription()` 为 spinner 提供活动描述(如 "Reading src/foo.ts"、"Running bun test"),替代默认的工具名显示。
|
||||
- **文件操作** — Read/Write/Edit 的设计和安全机制
|
||||
- **搜索与导航** — Glob/Grep 的搜索策略
|
||||
- **Shell 执行** — Bash 的沙箱和超时控制
|
||||
|
||||
Reference in New Issue
Block a user