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

# 22.4 Tool and Agent Collaboration

> **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`)

***

Tools don't run in isolation—they deeply collaborate with the Agent's prompt system, conversation context, and multi-turn interactions. This section analyzes how tools integrate into the Agent's reasoning loop.

***

## 22.4.1 Tool Prompt Injection (tool description → system prompt)

### Dual Identity of Tool Description

Each tool's `description` field serves dual purposes: it's part of the JSON Schema sent to the LLM as a tool definition, and it's also a source of information for the system prompt. OpenClaw aggregates tool descriptions into a mapping table via `buildToolSummaryMap()`:

```typescript
// src/agents/tool-summaries.ts
export function buildToolSummaryMap(tools: AgentTool[]): Record<string, string> {
  const summaries: Record<string, string> = {};
  for (const tool of tools) {
    const summary = tool.description?.trim() || tool.label?.trim();
    if (summary) {
      summaries[tool.name.toLowerCase()] = summary;
    }
  }
  return summaries;
}
```

### Channel-Specific Tool Hints

Different channels provide additional usage hints for the same tool. For example, the MS Teams channel tells the Agent how to use the `message` tool to send Adaptive Cards:

```typescript
// extensions/msteams/src/channel.ts
agentPrompt: {
  messageToolHints: () => [
    "- Adaptive Cards supported. Use action=send with card={type,version,body}.",
    "- MSTeams targeting: omit target to reply to current conversation.",
  ],
},
```

These hints are injected into the system prompt, helping the Agent understand how to correctly use tools in the current channel.

### Tool Availability Affects System Prompt

The tool set after policy filtering directly impacts Agent behavior. If `web_search` is disabled, the Agent's system prompt won't include search-related guidance and won't attempt to call that tool. This "tool availability-driven prompt" mechanism ensures the Agent doesn't try to call non-existent tools.

The system prompt report (`system-prompt-report.ts`) records the currently available tool list:

```typescript
// src/agents/system-prompt-report.ts
function buildToolsEntries(tools: AgentTool[]) {
  return tools.map((tool) => ({
    name: tool.name,
    description: tool.description?.slice(0, 200),
  }));
}
```

***

## 22.4.2 Multi-Turn Tool Calling Patterns

### Single-Turn vs Multi-Turn

LLM tool calling has two modes:

**Single-turn calling**: The LLM calls one or more tools in a single response, waits for results, then generates the final reply.

```
User: "What's the weather today?"
Agent: → tool_use: web_search("today's weather")
       ← tool_result: "Beijing sunny 25°C"
       → "Today's weather in Beijing is sunny with 25°C."
```

**Multi-turn calling**: The LLM needs multiple tool calls to complete a task, with each call's result guiding the next.

```
User: "Create a project document in Feishu with recent meeting notes"
Agent: → tool_use: sessions_history(limit=5)
       ← tool_result: [{ ... meeting notes ... }]
       → tool_use: feishu_doc_create(title="Project Doc", content=...)
       ← tool_result: { docId: "abc123", url: "..." }
       → tool_use: message(action="send", message="Document created: ...")
       ← tool_result: { ok: true }
       → "Created project document and sent the link."
```

### Maintaining Tool Call Context

In multi-turn calling, each tool result is appended to the conversation history, becoming context for subsequent reasoning:

```
messages: [
  { role: "user", content: "Check the project progress for me" },
  { role: "assistant", tool_calls: [{ name: "sessions_list", params: {} }] },
  { role: "tool", content: "[{ session_id: ... }]" },
  { role: "assistant", tool_calls: [{ name: "sessions_history", params: { id: "..." } }] },
  { role: "tool", content: "[{ message: ... }]" },
  { role: "assistant", content: "Based on recent session records, the project progress..." },
]
```

This means **tool results consume the conversation context window**. If a tool returns large amounts of data (like complete file contents or long lists), it quickly exhausts context capacity.

> **Sidebar**: **Context Window** is the limit on text length an LLM can process simultaneously, typically measured in tokens. Claude supports approximately 200k tokens of context window, GPT-4 supports 128k tokens. Every parameter and return result of tool calls counts toward context consumption. Therefore, tool design must balance information quantity with context efficiency.

### Parallel Tool Calling

Modern LLMs support initiating **multiple parallel** tool calls in a single response:

```
Agent: → tool_use: [
  { name: "web_search", params: { query: "Company A financial report" } },
  { name: "web_search", params: { query: "Company B financial report" } },
]
```

OpenClaw's pi-agent-core supports executing these calls in parallel and returning all results together.

***

## 22.4.3 Impact of Tool Results on Session Context

### Context Pressure

Tool results are one of the main sources of context consumption. Some typical tool result sizes:

| Tool                   | Typical Result Size               | Context Impact                 |
| ---------------------- | --------------------------------- | ------------------------------ |
| `web_search`           | 1-5k tokens                       | Medium                         |
| `web_fetch`            | 5-50k tokens                      | High (may trigger compression) |
| `read` (large file)    | 10-100k tokens                    | Very high                      |
| `exec` (long output)   | 1-50k tokens                      | High                           |
| `sessions_list`        | 0.5-2k tokens                     | Low                            |
| `browser` (screenshot) | Images don't count as text tokens | Special                        |

### Context Optimization via tool\_result\_persist

One of the core values of the `tool_result_persist` hook is **optimizing context usage**. Plugins can simplify tool result content before persistence:

```typescript
// A hypothetical plugin implementation
api.on("tool_result_persist", (event, ctx) => {
  if (ctx.toolName === "exec" && event.message.content?.length > 10000) {
    // Truncate overly long command output
    return {
      message: {
        ...event.message,
        content: event.message.content.slice(0, 5000) + "\n[... output truncated ...]",
      },
    };
  }
});
```

### Interaction with Context Compression

When tool calls cause context to approach the window limit, the context compression mechanism (Compaction) introduced in Chapter 17 is triggered. During compression, old tool calls and their results are summarized by the LLM into shorter summaries, freeing up context space.

This forms a cycle:

```
Tool call → Context growth → Trigger compression → Free space → Continue tool calls
```

Before and after compression, `before_compaction` and `after_compaction` hooks are triggered, giving plugins opportunities to save critical data before compression or restore state after.

### Feedback Loop Between Tools and Agent

In actual operation, the tool system and Agent form a **feedback loop**:

1. **Agent Planning**: Based on user request and current context, the Agent decides which tools to call
2. **Tool Execution**: Tool calls produce results, which are appended to context
3. **Agent Evaluation**: The Agent evaluates whether further operations are needed based on tool results
4. **Iterate or Complete**: If the task is incomplete, go back to step 1; otherwise generate final reply

This loop is managed by pi-agent-core's runtime until one of these conditions is met:

* Agent generates a reply without tool\_use (considers task complete)
* Reaches maximum tool call rounds limit
* Session is interrupted (AbortSignal)
* Context window exhausted and compression can't continue

***

## Summary of This Section

1. **Tool descriptions serve both LLM tool definitions and system prompts**, with channel-specific tool hints injected into the system prompt to guide the Agent in correctly using tools in specific channels.
2. **Multi-turn tool calling is the key pattern for Agents to complete complex tasks**, with each tool result becoming context for subsequent reasoning. Modern LLMs also support parallel tool calls in a single response.
3. **Tool results are a major source of context consumption**, with `tool_result_persist` hooks and context compression mechanisms jointly managing context pressure.
4. **Tools and Agent form a plan-execute-evaluate feedback loop**, managed by pi-agent-core runtime until task completion, limit reached, or interruption occurs.

***

> ### 🔬 Going Deeper: 22.5 Source Deep Dive
>
> That's the end of the chapter's main text. If you're going to **modify this code**, or reproduce it in your own project, read on: [**22.5 Source Deep Dive: The Tool Assembly Pipeline and the Sandbox**](https://www.openclawbook.xyz/en/ch22-tool-system-overview/22.5-source-deep-dive-tool-assembly-and-sandbox.md) traces the real implementation line by line along with the issues behind it, at a noticeably higher information density.
>
> **The main text is for understanding structure; the deep dive is for understanding trade-offs.**
