工具调用
工具系统让 AI Agent 能执行实际操作——运行命令、读写文件、调用 API、控制浏览器等。OpenClaw 支持内置工具和插件贡献的工具。
工具定义
Source: src/agents/pi-tools.ts
工具通过 factory 模式注册,每次 Agent 会话创建时实例化可用工具:
typescript
// src/agents/pi-tools.ts (simplified)
// OpenClaw built-in tools
// - exec: Execute shell commands
// - read: Read files
// - write: Write files
// - bash: Run bash scripts
// - node-invoke: Invoke remote node capabilities
// Plugin-contributed tools
// via ChannelAgentToolFactory内置工具
| 工具 | 说明 | 安全级别 |
|---|---|---|
exec | 执行 Shell 命令 | 需要审批(非 main 会话) |
read | 读取文件 | 受路径限制 |
write | 写入文件 | 受路径限制 |
bash | 运行 Bash 脚本 | 需要审批 |
node-invoke | 调用远程节点能力 | 受节点策略限制 |
插件工具
插件通过 PluginToolRegistration 注册工具:
typescript
// Plugin tool registration
interface PluginToolRegistration {
factory: OpenClawPluginToolFactory; // Tool factory function
names: string[]; // Tool names provided
optional?: boolean; // Can be disabled
}
// Tool factory receives context
type OpenClawPluginToolFactory = (
ctx: OpenClawPluginToolContext
) => AnyAgentTool | AnyAgentTool[] | null;工具工厂接收上下文信息:
typescript
interface OpenClawPluginToolContext {
config: PluginConfig;
workspaceDir: string; // Agent workspace directory
agentDir: string; // Agent-specific directory
agentId: string; // Current agent ID
sessionKey: string; // Current session key
messageChannel: string; // Message source channel
sandboxed: boolean; // Is sandbox mode active
}工具策略
Source: src/agents/pi-tool-policy.ts
工具策略控制在不同上下文中工具的可用性和权限:
安全边界
| 上下文 | 执行环境 | 说明 |
|---|---|---|
| main 会话 | 宿主机 | 1:1 私聊,完全信任 |
| group(无沙箱) | 宿主机 | 受工具策略限制 |
| group(沙箱) | Docker 容器 | 隔离执行,无法访问宿主机文件 |
工具调用处理
Source: src/agents/pi-embedded-subscribe.handlers.tools.ts
当模型请求工具调用时,处理流程为:
重复检测
typescript
// Duplicate detection
function isMessagingToolDuplicateNormalized(
toolName: string,
args: unknown,
previousCalls: ToolMeta[]
): boolean {
// Normalize arguments
// Compare with previous calls
// Return true if duplicate found
}工具调用重复检测防止模型在循环中反复调用相同工具。
结果格式化
工具结果有两种格式:
| 格式 | 说明 | 使用场景 |
|---|---|---|
markdown | Markdown 格式化输出 | 默认,适合文本回复 |
plain | 纯文本输出 | 简单数据返回 |
Pending Tool 追踪
运行时通过 toolMetas 数组追踪所有待处理和已完成的工具调用:
typescript
// Tool tracking metadata
interface ToolMeta {
toolCallId: string;
toolName: string;
args: unknown;
status: "pending" | "executing" | "completed" | "failed";
result?: unknown;
}小结
- 工具通过 factory 模式 注册,每次会话实例化
- 内置工具(exec, read, write, bash)和 插件工具 共存
- 工具策略 根据会话类型和沙箱模式控制权限
- 重复检测 防止模型循环调用相同工具
- 工具结果支持 markdown 和 plain 两种格式
下一章:流式处理