Claude Code Harness Chapter 2: 工具系统:40+ 工具如何让 AI 拥有编程能力
Claude Code Harness Chapter 2: 工具系统:40+ 工具如何让 AI 拥有编程能力
引言:给语言模型一双双手
一个纯粹的语言模型就像一个被困在无窗房间里的聪明头脑——它可以思考和推理,但无法与世界互动。工具是让 AI Agents 能够操控环境、读取文件、运行命令和创建软件的双手。
本章将探讨 Claude Code 复杂的工具系统:它是如何设计的、单个工具如何工作,以及 40+ 专门工具如何协作,为 AI Agent 提供真正的软件工程能力。
到本章结束时,你将理解使工具安全、可组合和强大的架构,以及这个系统如何实现从简单文件编辑到复杂多步骤部署的所有功能。
为什么工具重要:连接思维与世界的桥梁
问题:纯 LLM 的局限性
考虑一下语言模型无法独自做什么:
| 能力 | 为什么 LLM 做不到 |
|---|---|
| 读取你的文件 | 没有文件系统访问权限 |
| 运行测试 | 没有执行环境 |
| 检查 git 状态 | 无法生成进程 |
| 浏览网页 | 没有网络连接 |
| 编辑代码 | 没有文件修改能力 |
LLM 本质上是一个复杂的文本预测引擎。给它一个 prompt,它预测接下来会发生什么。但如果没有工具,它就无法行动于这些预测——它只能建议人类执行某些操作。
解决方案:工具作为行动
工具通过提供结构化的行动接口来弥合这一差距:
flowchart LR
A[LM Reasoning] --> B{Need action?}
B -->|Yes| C[Select tool]
B -->|No| D[Generate text]
C --> E[Prepare parameters]
E --> F[Execute tool]
F --> G[Get result]
G --> A
D --> H[Output to user]
style C fill:#e1f5ff
style F fill:#e1f5ff这创建了一个强大的反馈循环:模型可以推理、行动、观察结果并进一步推理——使复杂的多步骤问题解决成为可能。
图:工具执行循环示意图
工具架构:核心接口
工具契约
Claude Code 中的每个工具都实现相同的基本契约:
interface Tool, TOutput = unknown> {
// 唯一标识符
name: string
// 基于输入的动态描述
description: (input: TInput, options: ToolDescriptionOptions) => string
// JSON Schema 用于验证
inputSchema: JSONSchema
// 执行处理器
handler: (input: TInput, context: ToolHandlerContext) => Promise>
// UI 的人类可读名称
userFacingName: (input: TInput) => string
} 这个简单的接口在保持一致性和安全性的同时实现了卓越的能力。
工具生命周期
每个工具执行遵循相同的生命周期:
stateDiagram-v2
[*] --> Validating: Model selects tool
Validating --> Validating: Check input schema
Validating --> Executing: Input valid
Validating --> Failed: Input invalid
Executing --> Streaming: Tool running
Executing --> Failed: Execution error
Streaming --> Completed: Tool finished
Streaming --> Failed: Tool aborted
Completed --> [*]
Failed --> [*]
note right of Validating
JSON Schema validation
Type checking
Permission checking
end note
note right of Executing
Run handler function
Stream output
Track status
end note图:工具生命周期状态机
工具分类学:40+ 专门能力
Claude Code 的工具分为不同的类别,每个类别服务特定需求:
文件系统工具
基础——读取和写入文件:
| 工具 | 目的 | 关键特性 |
|---|---|---|
| FileReadTool | 读取文件内容 | 行范围、编码检测 |
| FileWriteTool | 创建/覆盖文件 | 原子写入、目录创建 |
| FileEditTool | 精确文本替换 | 基于字符串、context 感知 |
| GlobTool | 按模式查找文件 | 递归模式、排序 |
| GrepTool | 搜索文件内容 | Regex 支持、多文件 |
实战:文件编辑
当模型需要修复 bug 时:
sequenceDiagram
participant Model
participant FileEditTool
participant FileSystem
participant User
Model->>FileEditTool: Edit file, line 42
Note over Model,FileEditTool: Replace "console.log"
with "logger.info"
FileEditTool->>FileSystem: Read file
FileSystem-->>FileEditTool: File content
FileEditTool->>FileEditTool: Verify match
FileEditTool->>FileSystem: Write modified file
FileEditTool-->>Model: Success
Model->>User: Fixed bug in auth.ts图:文件编辑工具执行流程
开发工具
运行命令和与开发环境交互:
| 工具 | 目的 | 关键特性 |
|---|---|---|
| BashTool | 执行 shell 命令 | 超时、后台执行 |
| PowerShellTool | Windows 命令 | PowerShell 特定功能 |
| REPLTool | 交互式评估 | 多语言支持 |
| LSPTool | Language Server Protocol | 代码智能、重构 |
实战:运行测试
修复失败的测试时:
flowchart TD
A[Model: Fix test] --> B[BashTool: npm test]
B --> C{Tests pass?}
C -->|No| D[Analyze failure]
D --> E[Identify issue]
E --> F[Edit test file]
F --> B
C -->|Yes| G[Commit changes]
style B fill:#e1f5ff
style F fill:#e1f5ff图:测试驱动修复循环
这个迭代循环——运行测试、分析失败、修复、重复——展示了工具如何实现真正的问题解决。
AI 和 Agent 工具
扩展 AI 能力的元工具:
| 工具 | 目的 | 关键特性 |
|---|---|---|
| AgentTool | 生成子 Agent | 专门化 Agent、并行执行 |
| SkillTool | 执行用户技能 | 参数化 prompts、可重用工作流 |
| MCPTool | Model Context Protocol | 外部工具集成 |
Agent Tool:委派和并行
AgentTool 启用了强大的模式:
graph TD
A[Main Agent] --> B[Task: Analyze codebase]
B --> C1[Agent 1: Analyze frontend/]
B --> C2[Agent 2: Analyze backend/]
B --> C3[Agent 3: Analyze infrastructure/]
C1 --> D1[Report: Frontend findings]
C2 --> D2[Report: Backend findings]
C3 --> D3[Report: Infrastructure findings]
D1 --> E[Synthesize results]
D2 --> E
D3 --> E
style A fill:#f9f,stroke:#333,stroke-width:2px
style E fill:#f9f,stroke:#333,stroke-width:2px图:Agent 并行分析模式
这种并行分析对于单个 Agent 来说在合理的时间限制内是不可能的。
协作工具
与团队和外部系统合作:
| 工具 | 目的 | 关键特性 |
|---|---|---|
| TaskCreateTool | 创建后台任务 | 长时间运行的操作 |
| SendMessageTool | 团队通信 | 通知、更新 |
| TeamCreateTool | 多 Agent 团队 | 专门化的 Agent 组 |
Web 工具
访问外部信息:
| 工具 | 目的 | 关键特性 |
|---|---|---|
| WebFetchTool | 获取网页内容 | HTML 解析、超时处理 |
| WebSearchTool | 搜索网络 | 当前信息、文档 |
系统和实用工具
支持操作:
| 工具 | 目的 | 关键特性 |
|---|---|---|
| ConfigTool | 管理配置 | 设置、偏好 |
| ScheduleCronTool | 定时任务 | 周期性操作 |
| SleepTool | 延迟 | 速率限制、协调 |
工具设计原则
1. 单一职责
每个工具做好一件事:
❌ 坏: FileTool (处理 read, write, edit, search, glob...)
✅ 好: FileReadTool, FileWriteTool, FileEditTool, GrepTool, GlobTool这使工具:
- 更易理解:目的清晰
- 更易测试:功能专注
- 更易组合:按需组合
- 更安全:有限的攻击面
2. 自文档化
工具通过 schemas 自我描述:
{
"name": "FileEditTool",
"description": "Edit files by replacing text",
"inputSchema": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Absolute path to the file"
},
"old_string": {
"type": "string",
"description": "Text to replace"
},
"new_string": {
"type": "string",
"description": "Replacement text"
}
},
"required": ["file_path", "old_string", "new_string"]
}
}这个 schema:
- 验证输入:在执行前捕获错误
- 生成 UI:在 web 界面中自动填充表单
- 引导模型:清晰的参数期望
- 记录行为:不言自明的接口
3. 显式优于隐式
工具需要显式参数:
// ❌ 隐式: 工具猜测当前目录
bash("ls")
// ✅ 显式: 工具确切知道在哪里运行
bash("ls", { cwd: "/Users/yaya/itech/github/theaiera" })这防止了:
- 歧义:清楚会发生什么
- 错误:没有猜测游戏
- 安全:显式是可审计的
4. 优雅失败
工具信息丰富地失败:
flowchart TD
A[Tool execution] --> B{Success?}
B -->|Yes| C[Return result]
B -->|No| D[Error handler]
D --> E{Recoverable?}
E -->|Yes| F[Return error and recovery hint]
E -->|No| G[Return fatal error and context]
style C fill:#6f6
style F fill:#fc6
style G fill:#f66图:工具错误处理流程
5. 流式输出
长时间运行的工具流式传输进度:
sequenceDiagram
participant Model
participant Tool
participant User
Model->>Tool: Execute long operation
loop Progress
Tool->>User: [========= ] 45%
Tool->>Model: Stream update
end
Tool->>User: [============ ] 100%
Tool-->>Model: Final result图:工具流式输出示例
这保持用户知情并启用实时反馈。
工具组合:构建复杂工作流
工具 individually 很强大,但在组合时才能真正发挥作用:
实战:修复 Bug 并部署
flowchart TD
A[User: Fix auth bug] --> B[Read: auth.ts]
B --> C[Grep: Find related tests]
C --> D[Bash: Run tests]
D --> E{Tests pass?}
E -->|No| F[Edit: Fix code]
F --> D
E -->|Yes| G[Git: Commit changes]
G --> H[Git: Create PR]
H --> I[WebFetch: Check CI status]
I --> J{CI passes?}
J -->|No| K[Analyze logs]
J -->|Yes| L[Git: Merge PR]
L --> M[Bash: Deploy to production]
style B fill:#e1f5ff
style F fill:#e1f5ff
style M fill:#e1f5ff图:Bug 修复和部署工作流
这个工作流使用 7 个不同的工具,每个都做它最擅长的,由模型的推理编排。
实战:数据库迁移
flowchart LR
A[Plan migration] --> B[Read: schema.sql]
B --> C[Create: migration.sql]
C --> D[Bash: Test migration locally]
D --> E{Success?}
E -->|No| F[Edit: Fix migration]
F --> D
E -->|Yes| G[Grep: Find dependent code]
G --> H[Edit: Update queries]
H --> I[Bash: Run full tests]
I --> J{Tests pass?}
J -->|No| K[Analyze failures]
K --> H
J -->|Yes| L[Git: Commit and PR]
style D fill:#e1f5ff
style H fill:#e1f5ff图:数据库迁移工作流
工具安全:权限和执行控制
工具很强大,这也使它们可能很危险。Claude Code 实现多层安全:
权限系统集成
每个工具执行检查权限:
flowchart TD
A[Tool execution request] --> B{Permission mode}
B -->|auto| C{YOLO check}
B -->|ask| D[Prompt user]
B -->|deny| E[Block execution]
C -->|Safe| F[Execute tool]
C -->|Risky| D
D -->|User allows| F
D -->|User denies| E
F --> G[Run pre-hooks]
G --> H[Execute]
H --> I[Run post-hooks]
I --> J[Return result]
style E fill:#f66,stroke:#333,stroke-width:2px
style J fill:#6f6,stroke:#333,stroke-width:2px图:工具权限检查流程
工具特定风险级别
不同工具有不同的风险概况:
| 风险级别 | 工具 | 示例 |
|---|---|---|
| 安全 | 只读工具 | FileRead, Glob, Grep |
| 低风险 | 非破坏性写入 | FileWrite 到新文件 |
| 中风险 | 破坏性操作 | FileEdit, Git 提交 |
| 高风险 | 外部效果 | Bash 部署、数据库更改 |
权限系统根据这些风险级别进行调整。
高级工具特性
Abort Controllers
每个工具都可以独立取消:
flowchart LR
A[User: Ctrl+C] --> B[Cancel signal]
B --> C1[Cancel tool 1]
B --> C2[Cancel tool 2]
B --> C3[Cancel tool 3]
C1 --> D1[Cleanup resources]
C2 --> D2[Cleanup resources]
C3 --> D3[Cleanup resources]
D1 --> E[Report cancellation]
D2 --> E
D3 --> E图:工具取消机制
这在并发操作期间启用细粒度控制。
结果缓冲
工具结果被收集和排序:
sequenceDiagram
participant Model
participant Executor
par Concurrent execution
Model->>Executor: Tool 1 (slow)
Model->>Executor: Tool 2 (fast)
Model->>Executor: Tool 3 (medium)
end
Executor-->>Model: Tool 2 result (1st)
Executor-->>Model: Tool 3 result (2nd)
Executor-->>Model: Tool 1 result (3rd)图:工具结果排序
这确保一致、可预测的输出,无论执行时间如何。
工具注册表:发现和管理
动态工具加载
工具被动态发现和注册:
flowchart TD
A[App startup] --> B[Scan tool directory]
B --> C[Load tool definitions]
C --> D[Validate schemas]
D --> E{All valid?}
E -->|No| F[Log error and skip]
E -->|Yes| G[Register tool]
F --> H{More tools?}
G --> H
H -->|Yes| C
H -->|No| I[Tool registration complete]
style F fill:#fc6
style G fill:#6f6图:工具注册流程
Feature Flag 集成
工具可以实验性地启用/禁用:
| 工具 | 状态 | Feature Flag |
|---|---|---|
| AgentTool | 稳定 | 无 |
| LSPTool | Beta | enableLsp |
| NewFeatureTool | 实验 | enableNewFeature |
这允许新功能的安全推出。
测量工具效果
Claude Code 跟踪工具使用以优化性能:
pie title Tool usage distribution
"File operations" : 35
"Bash/commands" : 25
"Search/find" : 15
"AI/Agent" : 10
"Web access" : 8
"Git/version control" : 7图:工具使用分布统计
这些数据指导:
- 工具优化:专注于频繁使用的工具
- 用户体验:简化常见工作流
- 资源分配:在重要的地方优先考虑性能
常见工具模式
模式 1:读取-修改-写入
代码更改的最常见模式:
flowchart LR
A[Read file] --> B[Parse content]
B --> C[Identify changes]
C --> D[Modify content]
D --> E[Write file]
E --> F[Verify changes]
style A fill:#e1f5ff
style D fill:#e1f5ff
style E fill:#e1f5ff图:读取-修改-写入模式
模式 2:测试驱动变更
使用测试指导修改:
flowchart TD
A[Read tests] --> B[Run tests]
B --> C{Tests pass?}
C -->|Yes| D[Feature complete]
C -->|No| E[Analyze failures]
E --> F[Plan fixes]
F --> G[Implement fixes]
G --> B
style B fill:#e1f5ff
style G fill:#e1f5ff图:测试驱动开发模式
模式 3:搜索-分析-转换
大规模重构:
flowchart LR
A[Grep: Find all occurrences] --> B[Read each file]
B --> C[Analyze context]
C --> D[Plan transformation]
D --> E[Edit files]
E --> F[Run tests]
F --> G{All pass?}
G -->|No| H[Analyze failures]
G -->|Yes| I[Complete]
H --> C
style A fill:#e1f5ff
style E fill:#e1f5ff图:搜索-分析-转换模式
工具局限性和权衡
没有工具系统是完美的。Claude Code 做出了有意识的权衡:
局限性
| 局限性 | 影响 | 缓解措施 |
|---|---|---|
| 无真正并行 | 工具串行运行 | 仔细协调的并发执行 |
| Token 成本 | 大工具结果消耗 context | 流式、截断、智能缓冲 |
| 无状态性 | 工具不记得之前的运行 | 显式状态管理 |
| 文件系统限制 | 无法有效读取二进制文件 | 专门的二进制处理工具 |
设计权衡
graph TD
A[Safety] --> B[Permission checks]
B --> C[User friction]
D[Power] --> E[More tools]
E --> F[Complexity]
G[Simplicity] --> H[Fewer abstractions]
H --> I[More repetition]
J[Performance] --> K[Caching and optimization]
K --> L[Implementation complexity]
style C fill:#fc6
style F fill:#fc6
style I fill:#fc6
style L fill:#fc6图:工具设计权衡
工具的未来
工具系统继续演进:
新兴能力
- MCP (Model Context Protocol):标准化工具接口
- 用户定义工具:自定义工具无需修改核心
- 工具组合宏:可重用的工具序列
- 性能分析:识别瓶颈
社区工具
开源生态系统扩展:
mindmap
root((Community Tools))
Testing
E2E test runner
Performance profiler
Documentation
API doc generator
Changelog builder
Deployment
Multi-cloud deployer
Rollback manager
Development
Code snippet extractor
Dependency visualizer图:社区工具生态系统
结论:工具作为 Agent 的基础
工具是将语言模型从复杂的文本预测器转变为真正的软件工程 Agent 的关键。它们提供:
- Agent:行动而不仅仅是建议的能力
- 广度:40+ 涵盖多样化需求的能力
- 深度:特定领域的专门工具
- 安全性:多层保护
- 可组合性:工具组合成复杂工作流
- 可扩展性:新工具添加新能力
工具系统展示了 Harness Engineering 的核心原则:设计 AI 智能与实际能力无缝协作的系统。工具给模型双手;模型提供有效使用这些双手的智能。
在下一章中,我们将探讨 Agent Loop——编排层,决定使用哪些工具、何时使用以及如何将它们链接起来以完成复杂任务。
关键要点
- 工具弥合差距:它们将 LLM 推理转化为行动
- 一致的接口:所有工具遵循相同的架构契约
- 专门能力:40+ 工具按目的组织
- 安全第一:多层保护防止滥用
- 可组合性是关键:工具组合成强大的工作流
- 自文档化:Schemas 使工具可发现且安全
延伸阅读
- 第 3 章:Agent Loop——如何编排工具
- 第 4 章:工具执行——并发、流式和中断
- 第 8 章:工具提示词作为微型 Harness
- MCP 规范:Model Context Protocol 文档