vault backup: 2026-06-09 23:15:17

This commit is contained in:
2026-06-09 23:15:17 +08:00
parent 31fd89aafe
commit e92c0327d9
111 changed files with 7276 additions and 8846 deletions
+52 -59
View File
@@ -1,12 +1,17 @@
---
title: "工具系统设计 - AI 如何从说到做"
description: "深入理解 Claude Code 的 Tool 抽象设计:从类型定义、注册机制、调用链路到渲染系统,揭示 50+ 内置工具如何通过统一的 Tool 接口协同工作。"
keywords: ["工具系统", "Tool 抽象", "AI 工具", "function calling", "buildTool", "getTools"]
tags: [claude-code, tool-system, architecture, function-calling]
create time: 2026-06-09 22:30
---
{/* 本章目标:基于 src/Tool.ts 和 src/tools.ts 揭示工具系统的完整架构 */}
# 工具系统设计 - AI 如何从说到做
## AI 为什么需要工具
## 概述
Claude Code 通过统一的 `Tool` 接口将 50+ 内置工具串联起来,让大语言模型从"只能说话"进化为"能真正动手"。本文从类型定义、注册机制、调用链路到渲染系统,完整揭示这套工具抽象的设计哲学。
## 正文
### AI 为什么需要工具
大语言模型本质上只能做一件事:**根据输入文本,生成输出文本**。
@@ -14,11 +19,11 @@ keywords: ["工具系统", "Tool 抽象", "AI 工具", "function calling", "buil
工具是 AI 的双手。AI 说"我想读这个文件",工具系统替它真正去读;AI 说"我想执行这条命令",工具系统替它真正去跑。
## Tool 类型:35 个字段的统一接口
### Tool 类型:35 个字段的统一接口
所有工具都实现 `src/Tool.ts:368` 的 `Tool<Input, Output, Progress>` 类型。这不是一个 class,而是一个包含 35+ 字段的**结构化类型**(structural typing),任何满足该接口的对象就是一个工具:
### 核心四要素
#### 核心四要素
| 字段 | 类型 | 说明 |
|------|------|------|
@@ -27,7 +32,7 @@ keywords: ["工具系统", "Tool 抽象", "AI 工具", "function calling", "buil
| `inputSchema` | `z.ZodType` | Zod schema,定义参数类型和校验规则 |
| `call()` | `(args, context, canUseTool, parentMessage, onProgress?) => Promise<ToolResult<Output>>` | 执行函数 |
### 注册与发现
#### 注册与发现
| 字段 | 说明 |
|------|------|
@@ -37,7 +42,7 @@ keywords: ["工具系统", "Tool 抽象", "AI 工具", "function calling", "buil
| `alwaysLoad` | 永不延迟加载(如 SkillTool 必须在 turn 1 可见) |
| `isEnabled()` | 运行时开关(如 PowerShellTool 检查平台) |
### 安全与权限
#### 安全与权限
| 字段 | 说明 |
|------|------|
@@ -49,7 +54,7 @@ keywords: ["工具系统", "Tool 抽象", "AI 工具", "function calling", "buil
| `preparePermissionMatcher()` | 为 Hook 的 `if` 条件准备模式匹配器 |
| `interruptBehavior()` | 用户中断时的行为:`'cancel'` 或 `'block'` |
### 输出与渲染
#### 输出与渲染
| 字段 | 说明 |
|------|------|
@@ -59,7 +64,7 @@ keywords: ["工具系统", "Tool 抽象", "AI 工具", "function calling", "buil
| `renderToolUseMessage()` | React 组件渲染工具调用过程 |
| `backfillObservableInput()` | 在不破坏 prompt cache 的前提下回填可观察字段 |
### 上下文与 Prompt
#### 上下文与 Prompt
| 字段 | 说明 |
|------|------|
@@ -67,7 +72,7 @@ keywords: ["工具系统", "Tool 抽象", "AI 工具", "function calling", "buil
| `outputSchema` | 输出 Zod schema(用于类型安全的结果处理) |
| `getPath()` | 提取操作的文件路径(用于权限匹配和 UI 显示) |
## 工具注册:`getTools()` 的分层组装
### 工具注册:`getTools()` 的分层组装
`src/tools.ts` 的 `getAllBaseTools()`(第 195 行)是工具注册的核心:
@@ -106,9 +111,10 @@ export const getTools = (permissionContext): Tools => {
}
```
**关键设计**:工具列表在每次 API 调用时组装(而非全局缓存),因为 `isEnabled()` 的结果可能随运行时状态变化。
> [!info] 关键设计
> 工具列表在每次 API 调用时组装(而非全局缓存),因为 `isEnabled()` 的结果可能随运行时状态变化。
## `buildTool()` 工厂函数
### `buildTool()` 工厂函数
大多数工具通过 `buildTool()` 创建(`src/Tool.ts:789`),它是一个类型安全的构造器:
@@ -122,33 +128,27 @@ export const BashTool: Tool<...> = buildTool({
`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. 新消息追加到对话 → 进入下一轮迭代
```mermaid
flowchart TD
A["API 返回 tool_use block"] --> B["StreamingToolExecutor.addTool() / runTools()"]
B --> C["findToolByName() 查找工具"]
C --> D["validateInput() 输入校验"]
D -->|失败| E["返回错误 tool_result"]
D -->|通过| F["canUseTool() 权限 UI"]
F -->|拒绝| G["返回拒绝 tool_result"]
F -->|通过| H["checkPermissions() 规则匹配"]
H --> I["call() 执行实际操作"]
I --> J["onProgress() 回调实时更新 UI"]
J --> K["返回 ToolResult"]
K --> L["mapToolResultToToolResultBlockParam() 转为 API 格式"]
L --> M["新消息追加到对话, 进入下一轮迭代"]
```
## 工具结果的预算控制
### 工具结果的预算控制
每个工具通过 `maxResultSizeChars` 声明输出上限:
@@ -158,7 +158,7 @@ export const BashTool: Tool<...> = buildTool({
超出上限的结果被 `applyToolResultBudget()`(`src/utils/toolResultStorage.ts`)持久化到磁盘,AI 只收到预览 + 文件路径。
## MCP 工具的扩展
### MCP 工具的扩展
MCP Server 提供的工具通过 `mcpInfo` 字段标记来源:
@@ -168,30 +168,16 @@ mcpInfo?: { serverName: string; toolName: string }
MCP 工具的 `inputJSONSchema` 直接使用 JSON Schema(而非 Zod),因为 schema 来自远程协议。它们通过 `filterToolsByDenyRules()` 支持 `mcp__server` 前缀的 blanket deny 规则。
## 50+ 内置工具全景
### 50+ 内置工具全景
<CardGroup cols={3}>
<Card title="文件操作" icon="file">
Read / Write / Edit / Glob / Grep / NotebookEdit
</Card>
<Card title="命令执行" icon="terminal">
Bash / PowerShell
</Card>
<Card title="对话管理" icon="comments">
Agent / SendMessage / AskUserQuestion
</Card>
<Card title="任务追踪" icon="list-check">
TaskCreate / TaskUpdate / TaskList / TaskGet / TaskOutput / TaskStop
</Card>
<Card title="Web 能力" icon="globe">
WebFetch / WebSearch / WebBrowser
</Card>
<Card title="规划与版本" icon="map">
EnterPlanMode / ExitPlanMode / Worktree / TodoWrite / ToolSearch
</Card>
</CardGroup>
- **文件操作**:Read / Write / Edit / Glob / Grep / NotebookEdit
- **命令执行**:Bash / PowerShell
- **对话管理**:Agent / SendMessage / AskUserQuestion
- **任务追踪**:TaskCreate / TaskUpdate / TaskList / TaskGet / TaskOutput / TaskStop
- **Web 能力**:WebFetch / WebSearch / WebBrowser
- **规划与版本**:EnterPlanMode / ExitPlanMode / Worktree / TodoWrite / ToolSearch
## 工具的可视化渲染
### 工具的可视化渲染
工具不仅能"做事",还能"展示"。每个工具通过 React 组件定义 UI 渲染:
@@ -204,3 +190,10 @@ MCP 工具的 `inputJSONSchema` 直接使用 JSON Schema(而非 Zod),因
`isSearchOrReadCommand()` 允许工具声明自己是搜索/读取操作,触发 UI 的折叠显示模式(避免大量搜索结果占满屏幕)。
`getActivityDescription()` 为 spinner 提供活动描述(如 "Reading src/foo.ts"、"Running bun test"),替代默认的工具名显示。
## 关联笔记
- [[file-operations]]
- [[shell-execution]]
- [[search-and-navigation]]
- [[task-management]]