S02: Tool System 工具系统
"Tools are the hands of the Agent" -- 工具是 Agent 与真实世界交互的接口。
Harness 层: Tools -- 将模型能力转化为真实世界操作。
🎯 问题
Agent Loop 提供了循环框架,但没有工具,Agent 只能"思考"不能"行动"。需要定义:
- 工具如何描述自己 (让模型理解)
- 工具如何验证输入 (防止错误)
- 工具如何执行操作 (产生结果)
- 工具如何报告状态 (给用户反馈)
💡 解决方案
Claude Code 使用统一的工具构建系统:
+------------+ +-------------+ +----------+
| Tool Def | --> | Permission | --> | Execute |
| (schema) | | (check) | | (action) |
+------------+ +-------------+ +----------+
| | |
v v v
Model knows User confirms Result back
how to call if needed to loop
🔍 源码分析
Tool.ts 核心结构
// 源码位置: src/Tool.ts
import { z } from 'zod'
export type ToolDef = {
name: string // 工具名称
inputSchema: z.ZodSchema // 输入验证
description: string // 工具描述
// 权限检查
hasPermission?: (
params: TInput,
context: TContext
) => Promise
// 执行逻辑
execute: (
params: TInput,
context: TContext
) => Promise
// UI 渲染
renderToolUseMessage?: (params: TInput) => React.ReactNode
renderToolResultMessage?: (result: ToolResult) => React.ReactNode
}
🔑 内置工具
Read
读取文件内容
Edit
编辑文件内容
Write
写入新文件
Bash
执行 shell 命令
Grep
搜索文件内容
WebSearch
网络搜索