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

# 22.3 Tool Permissions and Policy

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

***

OpenClaw's tool permission system is a key component of its security architecture. Different users, different scenarios, and different Agents may require completely different tool sets. This section details the `ToolPolicy` configuration system and its hierarchical filtering mechanism.

***

## 22.3.1 `ToolPolicy` Configuration System

### Basic Structure of Policy

Tool policy consists of two dimensions: `allow` (allowlist) and `deny` (denylist):

```typescript
// src/agents/pi-tools.policy.ts
type SandboxToolPolicy = {
  allow?: string[];    // Allowed tools (whitelist mode)
  deny?: string[];     // Denied tools (blacklist mode)
};
```

Evaluation rules:

1. If tool name is in `deny` → **Deny**
2. If `allow` is empty → **Allow** (no whitelist means allow all)
3. If tool name is in `allow` → **Allow**
4. Otherwise → **Deny**

```typescript
function makeToolPolicyMatcher(policy: SandboxToolPolicy) {
  const deny = compilePatterns(policy.deny);
  const allow = compilePatterns(policy.allow);
  return (name: string) => {
    const normalized = normalizeToolName(name);
    if (matchesAny(normalized, deny)) return false;   // deny takes priority
    if (allow.length === 0) return true;               // no allow = pass all
    return matchesAny(normalized, allow);              // pass only if in allow
  };
}
```

### Tool Groups

To simplify configuration, OpenClaw defines a set of **tool groups** that can be referenced by group name in `allow`/`deny`:

```typescript
// src/agents/tool-policy.ts
export const TOOL_GROUPS: Record<string, string[]> = {
  "group:memory":     ["memory_search", "memory_get"],
  "group:web":        ["web_search", "web_fetch"],
  "group:fs":         ["read", "write", "edit", "apply_patch"],
  "group:runtime":    ["exec", "process"],
  "group:sessions":   ["sessions_list", "sessions_history", "sessions_send",
                        "sessions_spawn", "session_status"],
  "group:ui":         ["browser", "canvas"],
  "group:automation": ["cron", "gateway"],
  "group:messaging":  ["message"],
  "group:nodes":      ["nodes"],
  "group:openclaw":   [/* all OpenClaw native tools */],
};
```

Configuration example:

```yaml
# Allow only filesystem and execution tools
tools:
  allow:
    - "group:fs"
    - "group:runtime"
```

### Tool Profiles

OpenClaw predefines four profiles covering common use cases:

```typescript
const TOOL_PROFILES: Record<ToolProfileId, ToolProfilePolicy> = {
  minimal: {
    allow: ["session_status"],          // Status viewing only
  },
  coding: {
    allow: ["group:fs", "group:runtime", "group:sessions",
            "group:memory", "image"],   // Development scenario
  },
  messaging: {
    allow: ["group:messaging", "sessions_list", "sessions_history",
            "sessions_send", "session_status"],  // Pure messaging scenario
  },
  full: {},                             // Unrestricted
};
```

Usage:

```yaml
tools:
  profile: coding      # Use coding preset
  alsoAllow:
    - web_search        # Additionally allow web_search on top of coding
```

`alsoAllow` is a clever design—it allows **appending** tools on top of a profile without needing to completely override the `allow` list.

### Pattern Matching

Tool names support `*` wildcards, matched by compiled regular expressions:

```typescript
function compilePattern(pattern: string): CompiledPattern {
  const normalized = normalizeToolName(pattern);
  if (normalized === "*") return { kind: "all" };           // Match all
  if (!normalized.includes("*")) return { kind: "exact", value: normalized };
  // discord_* → matches all tools starting with discord
  const escaped = normalized.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  return { kind: "regex", value: new RegExp(`^${escaped.replaceAll("\\*", ".*")}$`) };
}
```

This makes configuration very flexible:

```yaml
tools:
  deny:
    - "discord_*"       # Disable all Discord-related tools
    - "sessions_*"      # Disable all session management tools
```

***

## 22.3.2 Tool Permission Control by Sender Identity

### Owner-Only Tools

Certain sensitive tools are only allowed for "owners":

```typescript
// src/agents/tool-policy.ts
const OWNER_ONLY_TOOL_NAMES = new Set<string>(["whatsapp_login"]);

export function applyOwnerOnlyToolPolicy(tools, senderIsOwner) {
  if (senderIsOwner) return tools;  // Owner has no restrictions
  
  return tools
    .map((tool) => {
      if (!isOwnerOnlyToolName(tool.name)) return tool;
      // Non-owner: replace execute with error function
      return {
        ...tool,
        execute: async () => { throw new Error("Tool restricted to owner senders."); },
      };
    })
    // Non-owner: completely remove Owner-Only tools
    .filter((tool) => !isOwnerOnlyToolName(tool.name));
}
```

This uses **dual protection**: even if a tool somehow isn't filtered (e.g., LLM cached an old tool list), execute will refuse to run.

### Sender Control in Group Scenarios

In group chats, different senders may have different tool permissions. This is implemented via `resolveChannelGroupToolsPolicy()`:

```typescript
// src/config/group-policy.ts (conceptual)
export function resolveChannelGroupToolsPolicy(params) {
  const { cfg, channel, groupId, senderId, senderName } = params;
  
  // Look up group-specific tool policy
  const groupConfig = cfg.channels?.[channel]?.groups?.[groupId];
  
  // Check bySender configuration
  const bySender = groupConfig?.tools?.bySender;
  if (bySender) {
    // Match policy by sender ID or name
    for (const [pattern, policy] of Object.entries(bySender)) {
      if (matchesSender(pattern, { senderId, senderName })) {
        return policy;
      }
    }
  }
  
  return groupConfig?.tools;
}
```

Configuration example:

```yaml
channels:
  telegram:
    groups:
      "-100123456":
        tools:
          allow: ["group:messaging"]          # Default: only messaging tools
          bySender:
            "admin_user":
              allow: ["*"]                     # Admin: allow all tools
            "intern_user":
              deny: ["exec", "process"]        # Intern: disable command execution
```

***

## 22.3.3 Multi-Layer Policy Cascade

### Policy Application Order

The most elegant design in OpenClaw's tool policy system is **multi-layer policy cascade**. Policies filter from top to bottom, each layer further narrowing the tool set:

```
All tools
  │
  ├── 1. Owner-Only filtering (non-owners remove sensitive tools)
  │
  ├── 2. Profile policy (tools.profile: coding/messaging/etc.)
  │
  ├── 3. Provider Profile policy (tools.byProvider.<provider>.profile)
  │
  ├── 4. Global policy (tools.allow / tools.deny)
  │
  ├── 5. Global Provider policy (tools.byProvider.<provider>.allow/deny)
  │
  ├── 6. Agent policy (agents.<id>.tools.allow/deny)
  │
  ├── 7. Agent Provider policy (agents.<id>.tools.byProvider.<provider>.allow/deny)
  │
  ├── 8. Group policy (channels.<ch>.groups.<gid>.tools.allow/deny)
  │
  ├── 9. Sandbox policy (sandbox.tools.allow/deny)
  │
  └── 10. Sub-Agent policy (DEFAULT_SUBAGENT_TOOL_DENY)
          │
          ▼
      Final tool set
```

In the source code, this cascade is clearly visible:

```typescript
// src/agents/pi-tools.ts (end)
const toolsByAuthorization = applyOwnerOnlyToolPolicy(tools, senderIsOwner);
const toolsFiltered = filterToolsByPolicy(toolsByAuthorization, profilePolicyExpanded);
const providerProfileFiltered = filterToolsByPolicy(toolsFiltered, providerProfileExpanded);
const globalFiltered = filterToolsByPolicy(providerProfileFiltered, globalPolicyExpanded);
const globalProviderFiltered = filterToolsByPolicy(globalFiltered, globalProviderExpanded);
const agentFiltered = filterToolsByPolicy(globalProviderFiltered, agentPolicyExpanded);
const agentProviderFiltered = filterToolsByPolicy(agentFiltered, agentProviderExpanded);
const groupFiltered = filterToolsByPolicy(agentProviderFiltered, groupPolicyExpanded);
const sandboxed = filterToolsByPolicy(groupFiltered, sandboxPolicyExpanded);
const subagentFiltered = filterToolsByPolicy(sandboxed, subagentPolicyExpanded);
```

### Differentiated Policy by Provider

Different model providers may have different tool requirements. For example, some tools are unavailable when using OpenAI models:

```yaml
tools:
  byProvider:
    openai:
      deny: ["browser"]           # OpenAI models disable browser tool
      profile: coding             # Restrict to coding tool set
    anthropic:
      profile: full               # Anthropic models use full tool set
    "openai/gpt-4":               # Can be precise to model level
      allow: ["group:fs", "exec"]
```

Policy resolution looks up matches in order of `provider/model` → `provider` for the most specific match:

```typescript
function resolveProviderToolPolicy(params) {
  const candidates = [
    fullModelId,        // "openai/gpt-4" (most specific)
    normalizedProvider,  // "openai" (general)
  ];
  for (const key of candidates) {
    const match = lookup.get(key);
    if (match) return match;
  }
  return undefined;
}
```

### Special Handling for Plugin Tools

When the `allow` list **contains only plugin tool names** (no core tool names), OpenClaw treats this as a configuration error—the user probably just wants to add plugin tools, not disable all core tools:

```typescript
// src/agents/tool-policy.ts
export function stripPluginOnlyAllowlist(policy, groups, coreTools) {
  // Check if allow contains any core tools
  let hasCoreEntry = false;
  for (const entry of normalized) {
    const expanded = expandToolGroups([entry]);
    if (expanded.some((tool) => coreTools.has(tool))) {
      hasCoreEntry = true;
    }
  }
  
  // If allow has no core tools, ignore this allow list
  if (!hasCoreEntry) {
    logWarn("allowlist contains only plugin tools. Use tools.alsoAllow for additive.");
    return { policy: { ...policy, allow: undefined }, strippedAllowlist: true };
  }
}
```

This protection mechanism avoids a common pitfall: a user writes only `["memory_search"]` in `tools.allow`, accidentally disabling all built-in tools. The correct approach is to use `tools.alsoAllow`:

```yaml
# Wrong: disables all built-in tools (corrected by safety protection)
tools:
  allow: ["memory_search"]

# Correct: append on top of default tools
tools:
  alsoAllow: ["memory_search"]
```

***

## Summary of This Section

1. **Tool policy consists of `allow` (whitelist) and `deny` (blacklist)**, with deny having higher priority than allow. Supports tool groups (`group:fs`) and wildcards (`discord_*`) to simplify configuration.
2. **Four predefined Profiles** cover common scenarios: `minimal` (status viewing only), `coding` (development), `messaging` (pure messaging), `full` (unrestricted). `alsoAllow` supports appending tools on top of a Profile.
3. **Owner-Only mechanism uses dual protection** (remove tool + replace execute), with sensitive tools available only to owners. Group scenarios support precise tool permission control by sender ID.
4. **10-layer policy cascade** filters from Owner-Only to sub-Agent policy, supporting differentiated configuration by Provider/Model. Plugin tools have special safety protection to prevent accidentally disabling core tools.
