> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch22-tool-system-overview/22.1-tool-system-architecture.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 22.1 Tool System Architecture

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~900k tokens, Output \~85k tokens (Chapter total) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

In previous chapters, we deeply analyzed OpenClaw's channel layer—how messages enter the system, how they are routed to Agents, and how replies are distributed back to users. However, the true power of an Agent comes not just from conversation, but from **tool calling**. This chapter provides a comprehensive analysis of OpenClaw's tool system, from architectural design to runtime execution to permission control.

***

## 22.1.1 TypeBox Schema → JSON Schema Mapping

### Core Data Structure of Tools

In OpenClaw, each tool is an `AgentTool` object, defined by the underlying `pi-agent-core` library:

```typescript
// @mariozechner/pi-agent-core — AgentTool type (simplified)
type AgentTool<TParams = unknown, TResult = unknown> = {
  name: string;                        // Tool name (e.g., "web_search")
  label?: string;                      // Human-readable label
  description: string;                 // Description for LLM
  parameters: TParams;                 // Parameter Schema
  execute: (params, onUpdate?) => Promise<AgentToolResult<TResult>>;
};
```

The `parameters` field must be converted to JSON Schema format to be sent as the `tools` parameter to LLM APIs. OpenClaw uses the **TypeBox** library to define type-safe Schemas.

> **Sidebar**: **TypeBox** is a TypeScript JSON Schema builder. It generates JSON Schema using TypeScript functions while automatically inferring corresponding TypeScript types. For example, `Type.String()` generates `{ "type": "string" }` JSON Schema and infers the TypeScript type as `string`. This is much safer than manually writing JSON Schema and type definitions.

### TypeBox Definition Example

Taking the `message` tool's parameters as an example:

```typescript
// src/agents/tools/message-tool.ts
import { Type } from "@sinclair/typebox";

const schema = Type.Object({
  action: stringEnum(AllMessageActions, {
    description: "Message action type",
  }),
  channel: Type.Optional(Type.String()),
  target: Type.Optional(channelTargetSchema({
    description: "Target channel/user id or name.",
  })),
  message: Type.Optional(Type.String()),
  media: Type.Optional(Type.String({
    description: "Media URL or local path.",
  })),
  dryRun: Type.Optional(Type.Boolean()),
});
```

TypeBox's `Type.Object()` generates the following JSON Schema:

```json
{
  "type": "object",
  "properties": {
    "action": { "type": "string", "enum": ["send", "reply", ...] },
    "channel": { "type": "string" },
    "target": { "type": "string" },
    "message": { "type": "string" },
    "media": { "type": "string", "description": "Media URL or local path." },
    "dryRun": { "type": "boolean" }
  },
  "required": ["action"]
}
```

### Schema Normalization

Different LLM providers have varying levels of JSON Schema support. OpenClaw handles compatibility through functions like `normalizeToolParameters()` and `cleanToolSchemaForGemini()`:

```typescript
// src/agents/pi-tools.schema.ts
export function normalizeToolParameters(tool: AnyAgentTool): AnyAgentTool {
  // Ensure parameters is a valid JSON Schema object
  // Handle TypeBox internal properties like $id, $ref
  // Normalize enum values, etc.
}
```

For Google Gemini models, additional cleanup of unsupported Schema properties is needed (Gemini has more limited JSON Schema support).

***

## 22.1.2 Tool Registry (`src/agents/openclaw-tools.ts`)

### Tool Hierarchy

OpenClaw's tools are organized in three layers:

```
Layer 1: Base Coding Tools (provided by pi-coding-agent)
  ├── read     — Read files
  ├── write    — Write files
  ├── edit     — Edit files
  └── apply_patch — Apply diff patches

Layer 2: OpenClaw Native Tools (assembled in openclaw-tools.ts)
  ├── browser      — Browser control
  ├── canvas       — Canvas/UI rendering
  ├── nodes        — Node/device management
  ├── cron         — Scheduled tasks
  ├── message      — Send messages (cross-channel)
  ├── tts          — Text-to-speech
  ├── gateway      — Gateway management
  ├── agents_list  — Agent list query
  ├── sessions_*   — Session management (list/history/send/spawn)
  ├── session_status — Session status
  ├── web_search   — Web search
  ├── web_fetch    — Web fetch
  └── image        — Image processing

Layer 3: Plugin Tools (registered via registerTool())
  ├── memory_search — Memory search
  ├── memory_get    — Memory retrieval
  ├── zalouser      — Zalo operations
  ├── feishu_doc    — Feishu document
  └── ...           — Other plugin tools
```

### Tool Assembly Process

`createOpenClawTools()` is the factory function for OpenClaw native tools, assembling the tool set based on context parameters:

```typescript
// src/agents/openclaw-tools.ts (simplified)
export function createOpenClawTools(options?): AnyAgentTool[] {
  // Conditional creation: some tools require specific conditions to be available
  const imageTool = options?.agentDir?.trim()
    ? createImageTool({ config, agentDir, modelHasVision })
    : null;
  const webSearchTool = createWebSearchTool({ config, sandboxed });
  const webFetchTool = createWebFetchTool({ config, sandboxed });
  const messageTool = options?.disableMessageTool
    ? null
    : createMessageTool({ /* channel context parameters */ });
  
  // Assemble tool list
  const tools: AnyAgentTool[] = [
    createBrowserTool({ ... }),
    createCanvasTool(),
    createNodesTool({ ... }),
    createCronTool({ ... }),
    ...(messageTool ? [messageTool] : []),
    createTtsTool({ ... }),
    createGatewayTool({ ... }),
    createAgentsListTool({ ... }),
    createSessionsListTool({ ... }),
    createSessionsHistoryTool({ ... }),
    createSessionsSendTool({ ... }),
    createSessionsSpawnTool({ ... }),
    createSessionStatusTool({ ... }),
    ...(webSearchTool ? [webSearchTool] : []),
    ...(webFetchTool ? [webFetchTool] : []),
    ...(imageTool ? [imageTool] : []),
  ];
  
  // Merge plugin tools
  const pluginTools = resolvePluginTools({
    context: { config, workspaceDir, agentDir, sessionKey, ... },
    existingToolNames: new Set(tools.map(t => t.name)),
    toolAllowlist: options?.pluginToolAllowlist,
  });
  
  return [...tools, ...pluginTools];
}
```

Note the following design points:

1. **Conditional Creation**: `imageTool` requires `agentDir`, `webSearchTool` may be disabled by configuration
2. **Context Injection**: `messageTool` needs to know the current channel, thread, and other context
3. **Deduplication Merge**: Plugin tools avoid naming conflicts with built-in tools via `existingToolNames`

### Complete Tool Assembly Chain

From a top-level perspective, tool assembly goes through multiple processing steps:

```typescript
// src/agents/pi-tools.ts (simplified)
export function createPiTools(options) {
  // 1. Base coding tools
  const base = codingTools.flatMap((tool) => [...]);
  
  // 2. OpenClaw native tools + plugin tools
  const openclawTools = createOpenClawTools({ ...options });
  
  // 3. Channel-specific tools
  const channelTools = listChannelAgentTools({ cfg: config });
  
  // 4. Merge
  const tools = [...base, ...openclawTools, ...channelTools];
  
  // 5. Apply tool policy filtering
  const filtered = filterToolsByPolicy(tools, effectivePolicy);
  
  // 6. Schema normalization (adapt to different LLMs)
  return filtered.map(normalizeToolParameters);
}
```

***

## 22.1.3 Sandbox-Aware Tool Filtering

### The Concept of Sandbox

OpenClaw supports running Agents in **sandbox mode**, restricting their access to the file system and command execution. The sandbox specifies a root directory via the `sandboxRoot` parameter, with all file operations limited to this directory:

```typescript
// src/agents/pi-tools.read.ts — Sandboxed edit tool
function wrapSandboxPathGuard(tool: AnyAgentTool, root: string): AnyAgentTool {
  return {
    ...tool,
    execute: async (params, onUpdate) => {
      // Check if path is within sandbox directory
      const resolvedPath = path.resolve(root, params.path);
      if (!resolvedPath.startsWith(root)) {
        throw new Error(`Path escapes sandbox: ${params.path}`);
      }
      return tool.execute(params, onUpdate);
    },
  };
}
```

### Impact of Sandbox on Tools

Different sandbox states result in different tool versions being used:

| Tool         | Non-Sandbox        | Sandbox Mode                         |
| ------------ | ------------------ | ------------------------------------ |
| `read`       | Can read any file  | Limited to sandbox directory         |
| `write`      | Can write any file | Limited to sandbox directory         |
| `edit`       | Can edit any file  | Limited to sandbox directory         |
| `exec`       | Full shell access  | Working directory limited to sandbox |
| `web_search` | Full access        | May be disabled by policy            |
| `browser`    | Full access        | Uses Bridge URL                      |

### Sub-Agent Tool Filtering

When an Agent spawns a sub-Agent (Subagent), the sub-Agent's tool set is further restricted:

```typescript
// src/agents/pi-tools.policy.ts
const DEFAULT_SUBAGENT_TOOL_DENY = [
  "sessions_list",    // Session management — coordinated by main Agent
  "sessions_history",
  "sessions_send",
  "sessions_spawn",
  "gateway",          // System management — sub-Agents should not operate
  "agents_list",
  "whatsapp_login",   // Interactive setup — not a task
  "session_status",
  "cron",             // Scheduling — coordinated by main Agent
  "memory_search",    // Memory — should be passed in spawn prompt
  "memory_get",
];
```

This design follows the **principle of least privilege**—sub-Agents only need the tools to complete their assigned tasks, not system-level operation permissions.

***

## 22.1.4 Tool Helper Functions

### Parameter Reading Tools

`common.ts` provides a set of type-safe parameter reading functions shared by all tools:

```typescript
// src/agents/tools/common.ts

// Read string parameter (supports required/optional/trim options)
function readStringParam(params, key, options?) {
  const raw = params[key];
  if (typeof raw !== "string") {
    if (required) throw new Error(`${label} required`);
    return undefined;
  }
  return trim ? raw.trim() : raw;
}

// Read numeric parameter (supports integer truncation)
function readNumberParam(params, key, options?) {
  // Supports reading from string or number type
  // When integer: true, automatically truncates decimal part
}

// Read string array parameter
function readStringArrayParam(params, key, options?) {
  // Supports string[] and string (automatically converts to array)
}

// Read reaction/emoji parameter
function readReactionParams(params, options?) {
  // Unified parsing of emoji + remove parameter
}
```

### Result Formatting Tools

```typescript
// JSON result — most commonly used return format
function jsonResult(payload: unknown): AgentToolResult<unknown> {
  return {
    content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
    details: payload,
  };
}

// Image result — used by image, browser and other tools
async function imageResult(params) {
  const content = [
    { type: "text", text: params.extraText ?? `MEDIA:${params.path}` },
    { type: "image", data: params.base64, mimeType: params.mimeType },
  ];
  return await sanitizeToolResultImages(result, params.label);
}
```

### Action Gate (Operation Control)

`createActionGate()` provides an elegant way to control partial functionality of tools:

```typescript
function createActionGate<T>(actions: T | undefined) {
  return (key, defaultValue = true) => {
    const value = actions?.[key];
    return value === undefined ? defaultValue : value !== false;
  };
}

// Usage example: Discord message operation gate
const gate = createActionGate(cfg.channels?.discord?.actions);
if (gate("send")) {       // Check if send operation is enabled by configuration
  // Handle send operation
}
```

This pattern makes configuration very flexible—administrators can precisely control whether each operation of each tool is available.

***

## Summary of This Section

1. **Tools use TypeBox to define parameter Schemas**, automatically generating JSON Schema to send to LLMs while maintaining TypeScript type safety. Schema compatibility differences across LLMs are handled by `normalizeToolParameters()`.
2. **Tools are assembled in three layers**: base coding tools (read/write/edit/exec) → OpenClaw native tools (15+ types) → plugin tools (registered via `registerTool()`). `createOpenClawTools()` is the core assembly entry point.
3. **Sandbox mode restricts file access through path guards**, and sub-Agents further restrict tool sets through default deny lists, following the principle of least privilege.
4. **`common.ts` provides a unified set of parameter reading and result formatting tools**, including `readStringParam()`, `jsonResult()`, `imageResult()`, and `createActionGate()`, shared by all tools.
