> 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.2-tool-registration-and-policy.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 22.2 Tool Execution Runtime

> **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 the previous section, we learned how tools are defined, assembled, and filtered. This section delves into the complete lifecycle of a tool from being called by the LLM to returning results.

***

## 22.2.1 Tool Call Lifecycle

### Complete Call Chain

When an LLM decides to call a tool, the call goes through the following steps:

```
LLM output tool_use → pi-agent-core parses → tool dispatch
                                               │
                                     ┌─────────┴─────────┐
                                     │  before_tool_call  │ ← Plugin hook (can intercept/modify)
                                     └─────────┬─────────┘
                                               │ 
                                         ┌─────┴─────┐
                                         │ Tool exec  │ ← abort signal guard
                                         └─────┬─────┘
                                               │
                                     ┌─────────┴─────────┐
                                     │  after_tool_call   │ ← Plugin hook (notification)
                                     └─────────┬─────────┘
                                               │
                                     ┌─────────┴─────────┐
                                     │ Result format + persist │
                                     └─────────┬─────────┘
                                               │
                                     ┌─────────┴─────────┐
                                     │ tool_result_persist │ ← Plugin hook (can modify result)
                                     └─────────┬─────────┘
                                               │
                                       Return to LLM
```

### before\_tool\_call Hook Wrapping

Each tool is wrapped with `wrapToolWithBeforeToolCallHook()` after creation, injecting hook call logic:

```typescript
// src/agents/pi-tools.before-tool-call.ts
export function wrapToolWithBeforeToolCallHook(
  tool: AnyAgentTool,
  ctx?: { agentId?: string; sessionKey?: string },
): AnyAgentTool {
  const execute = tool.execute;
  return {
    ...tool,
    execute: async (toolCallId, params, signal, onUpdate) => {
      // 1. Run before_tool_call hook
      const outcome = await runBeforeToolCallHook({
        toolName: tool.name,
        params,
        toolCallId,
        ctx,
      });
      
      // 2. If blocked by hook, throw error
      if (outcome.blocked) {
        throw new Error(outcome.reason);
      }
      
      // 3. Execute tool with possibly modified parameters
      return await execute(toolCallId, outcome.params, signal, onUpdate);
    },
  };
}
```

The internal logic of `runBeforeToolCallHook()`:

```typescript
export async function runBeforeToolCallHook(args) {
  const hookRunner = getGlobalHookRunner();
  
  // Fast path: return directly when no hooks are registered
  if (!hookRunner?.hasHooks("before_tool_call")) {
    return { blocked: false, params: args.params };
  }
  
  const hookResult = await hookRunner.runBeforeToolCall(
    { toolName, params: normalizedParams },
    { toolName, agentId, sessionKey },
  );
  
  // Hook can block the call
  if (hookResult?.block) {
    return { blocked: true, reason: hookResult.blockReason || "Blocked by plugin" };
  }
  
  // Hook can modify parameters (shallow merge)
  if (hookResult?.params && isPlainObject(hookResult.params)) {
    return { blocked: false, params: { ...params, ...hookResult.params } };
  }
  
  return { blocked: false, params };
}
```

### Abort Signal Guard

Tools are also wrapped with `wrapToolWithAbortSignal()` to support canceling long-running tools when a session is interrupted:

```typescript
// src/agents/pi-tools.abort.ts (simplified)
export function wrapToolWithAbortSignal(
  tool: AnyAgentTool,
  signal?: AbortSignal,
): AnyAgentTool {
  return {
    ...tool,
    execute: async (toolCallId, params, existingSignal, onUpdate) => {
      // Combine session-level abort signal with tool-level signal
      return await tool.execute(toolCallId, params, signal, onUpdate);
    },
  };
}
```

### Wrapping Order

Tool wrapping follows an inside-out order:

```
Original tool → Parameter normalization → Schema normalization → before_tool_call hook → abort signal
```

This chain is clearly visible in `createOpenClawCodingTools()`:

```typescript
// src/agents/pi-tools.ts (end section)
const normalized = subagentFiltered.map(normalizeToolParameters);    // Schema normalization
const withHooks = normalized.map((tool) =>                           // Hook wrapping
  wrapToolWithBeforeToolCallHook(tool, { agentId, sessionKey })
);
const withAbort = options?.abortSignal                               // Abort wrapping
  ? withHooks.map((tool) => wrapToolWithAbortSignal(tool, options.abortSignal))
  : withHooks;
return withAbort;
```

***

## 22.2.2 Tool Result Formatting

### AgentToolResult Structure

After tool execution, an `AgentToolResult` is returned with this core structure:

```typescript
type AgentToolResult<TResult> = {
  content: Array<
    | { type: "text"; text: string }
    | { type: "image"; data: string; mimeType: string }
  >;
  details?: TResult;
};
```

`content` is an array of content blocks sent to the LLM, supporting both text and image types. `details` is structured execution information not sent to the LLM but useful for logging and debugging.

### JSON Result Pattern

Most tools use `jsonResult()` to return structured data:

```typescript
// Example: cron tool return
return jsonResult({
  ok: true,
  id: "cron_abc123",
  schedule: "0 9 * * 1",
  nextRun: "2025-01-06T09:00:00Z",
  status: "created",
});

// jsonResult() serializes it to indented JSON text
// → content: [{ type: "text", text: "{\n  \"ok\": true,\n  ..." }]
```

### Image Result Pattern

Visual tools like `browser`, `image`, and `canvas` use `imageResult()` to return images:

```typescript
// Example: browser tool screenshot
return await imageResult({
  label: "browser",
  path: screenshotPath,
  base64: screenshotBuffer.toString("base64"),
  mimeType: "image/png",
  extraText: `Browser screenshot of ${url}`,
});
```

Image results go through `sanitizeToolResultImages()` processing to ensure images don't exceed the LLM's context limits.

### Tool Result Persistence Hook

Before tool results are written to the session transcript, the `tool_result_persist` hook is triggered (review section 13.2.3), allowing plugins to modify persisted content. Typical use cases:

* **Simplify large results**: Remove redundant data from tool results to reduce context usage
* **Sanitize sensitive data**: Remove sensitive information before persistence
* **Add metadata**: Add timestamps or labels

***

## 22.2.3 Error Handling and Retry Strategy

### Tool-Level Error Handling

Exceptions during tool execution are caught by pi-agent-core and converted to tool error results returned to the LLM:

```typescript
// Inside pi-agent-core (conceptual)
try {
  const result = await tool.execute(toolCallId, params, signal, onUpdate);
  return { type: "tool_result", content: result.content };
} catch (err) {
  return { type: "tool_result", is_error: true, 
           content: [{ type: "text", text: String(err) }] };
}
```

After seeing an error result, the LLM typically:

1. Analyzes the error cause
2. Retries with corrected parameters
3. If multiple failures occur, gives up and informs the user

### Hook Error Isolation

Errors in the `before_tool_call` hook don't prevent tool execution—hooks are designed as "best effort":

```typescript
// pi-tools.before-tool-call.ts
try {
  const hookResult = await hookRunner.runBeforeToolCall(...);
  // Process result
} catch (err) {
  // Hook failure only logs warning, doesn't prevent execution
  log.warn(`before_tool_call hook failed: ${String(err)}`);
}
return { blocked: false, params };  // Continue execution
```

### Timeout Control

The `exec` tool (command execution) has independent timeout configuration:

```typescript
# Configuration
tools:
  exec:
    timeoutSec: 120           # Single execution timeout
    backgroundMs: 30000       # Max wait for background commands
    approvalRunningNoticeMs: 5000  # Hint delay while waiting for approval
```

Tool execution is also controlled by the session-level `AbortSignal`—when a user sends the `/stop` command or the session times out, all running tools receive an interrupt signal.

***

## Summary of This Section

1. **Tool calls go through four layers of processing**: `before_tool_call` hook interception/modification → tool execution → `after_tool_call` notification → `tool_result_persist` persistence control.
2. **Tools are wrapped in three layers of wrappers**: Schema normalization → hook injection → Abort Signal guard, ensuring compatibility, extensibility, and interruptibility.
3. **Tool results support both text and image formats**, with `jsonResult()` and `imageResult()` used for structured data and visual content respectively. Image results go through sanitization.
4. **Error handling follows the "graceful degradation" principle**: hook failures don't prevent execution, tool exceptions are converted to error results for the LLM to self-correct, and session interruption is propagated via AbortSignal.
