Skip to content

工具调用

工具系统让 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
}

工具调用重复检测防止模型在循环中反复调用相同工具。

结果格式化

工具结果有两种格式:

格式说明使用场景
markdownMarkdown 格式化输出默认,适合文本回复
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)和 插件工具 共存
  • 工具策略 根据会话类型和沙箱模式控制权限
  • 重复检测 防止模型循环调用相同工具
  • 工具结果支持 markdownplain 两种格式

下一章:流式处理

OpenClaw 源码学习教程