skip to content

In an OpenClaw plugin, how does a `before_tool_call` hook registered with `api.on` block a tool call or require approval?

level: seniorimportance: nice to knowfreq 4%

answer

  1. typed hooks, not internal hooks
  2. return block or requireApproval
  3. higher priority runs first
  4. matcher narrows to tool ids
  5. errors and timeouts fail closed

basics

~20 s

In an OpenClaw plugin, api.on("before_tool_call", handler, { matcher, priority }) gates tool calls. Returning { block: true } stops the call and skips lower-priority handlers; returning requireApproval pauses the run for a user decision; a handler that throws or times out blocks it.

solid answer

~40 s

Typed plugin hooks are registered with `api.on(name, handler, opts)`. For `before_tool_call` the handler gets `event.toolName`, `event.params` and context such as `ctx.agentId` and `ctx.requester`, and the `matcher` option can limit it to canonical tool ids like `exec`. It can return `params` to rewrite the call, `block: true` with a `blockReason`, which is terminal and skips lower-priority handlers, or `requireApproval` with a title and description, which pauses the run until the user decides, for example with `/approve`; an unresolved approval denies. Handlers run in priority order, higher first, and a thrown error or timeout fails closed by blocking the call. `api.registerHook` is a different API: it feeds the internal hook system for coarse events like `command:new`, and a typed name registered there never fires.

code

typescript · 26 lines
typescript
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";

export default definePluginEntry({
  id: "exec-guard",
  name: "Exec guard",
  description: "Ask before exec runs for anyone but the owner.",
  register(api) {
    api.on(
      "before_tool_call",
      (event, ctx) => {
        if (ctx.requester?.senderIsOwner === true) {
          return;
        }
        return {
          requireApproval: {
            title: "Run command",
            description: `Allow ${event.toolName} for a non-owner sender?`,
            severity: "warning",
            timeoutMs: 60_000,
          },
        };
      },
      { matcher: ["exec"], priority: 50 },
    );
  },
});

go deeper

for a junior

Recall that plugins gate tool calls with api.on("before_tool_call", ...) and that returning a block or an approval request is how they stop one.

for a middle

Explain the return shapes, params, block and requireApproval, how matcher and priority select and order handlers, and why api.registerHook is a different system.

for a senior

Show the edge semantics: terminal blocks, first approval wins but can still be blocked, fail-closed errors and timeouts, and requester fields treated as unproven when missing.

for a principal

Decide when a team encodes policy as a hook plugin versus tool policy and approvals in config, weighing auditability, review cost and the plugin's own in-process trust.

## Two hook APIs inside one plugin A native OpenClaw plugin can register hooks in two ways, and mixing them up is the most common reason a guard never runs. | API | Event names | Used for | | --- | --- | --- | | `api.on(name, handler, opts)` | typed names such as `before_tool_call`, `message_sending`, `agent_end` | middleware, policy, rewriting, blocking, approvals | | `api.registerHook(...)` | internal colon names such as `command:new`, `message:sent` | coarse side effects alongside HOOK.md-style automation | Typed names are dispatched only by the typed hook runner. Passing `before_tool_call` to `api.registerHook` produces a registration warning and the handler is never invoked. Internal hooks registered by a plugin appear in `openclaw hooks list` as `plugin:<id>` and are enabled or disabled with the plugin, not with `openclaw hooks`. ## The before_tool_call contract The handler receives the event and a context object: - `event.toolName` and `event.params`, plus optional `event.toolCallId` and `event.runId`; - `ctx.agentId`, `ctx.sessionKey` and, when the host knows it, `ctx.requester` with fields such as `channel`, `senderId` and `senderIsOwner`; - `ctx.abortSignal`, which fires if the owning tool call is cancelled. It can return any of: - `params`: a rewritten parameter object; the last returned `params` wins until an approval is requested; - `block: true` with an optional `blockReason`: terminal, lower-priority handlers are skipped; `block: false` counts as no decision; - `requireApproval`: a `title`, `description` and optional `severity`, `timeoutMs` and `allowedDecisions`. The run pauses and the user answers through plugin approvals; `/approve` handles both exec and plugin approvals. Returning nothing makes no decision, leaving the call to other handlers and to policy. ## Ordering and merge rules - `priority` orders handlers: **higher runs first**. - `matcher` takes a non-empty list of canonical OpenClaw tool ids such as `exec` or `apply_patch`; omit it to match every tool. Wildcards and empty lists are invalid. - The **first** `requireApproval` wins and freezes the parameter snapshot, so later handlers cannot change what is being approved, but a lower-priority handler can still return `block: true`. - Each handler sees an isolated copy of the original event, not the rewrites of earlier handlers. ## Failure behaviour `before_tool_call` is a gate, so the runner fails closed: if a handler throws or exceeds its timeout, the tool call is blocked. An approval that is never answered is denied. A timeout only ends the Gateway's wait, so pass `ctx.abortSignal` into any I/O and bound your own work. ## Permissions and limits `before_tool_call` needs no conversation-access opt-in. Hooks that see conversation content, such as `before_agent_reply`, `before_prompt_build`, `llm_input` and `agent_end`, require `plugins.entries.<id>.hooks.allowConversationAccess: true` for non-bundled plugins. These are registration gates, not a sandbox: every native plugin runs in the Gateway process, so a hook constrains the agent's tool calls, not other installed plugins. Missing requester fields are unproven rather than false, so a policy that depends on them should fail closed, as the example does. ## The wider typed-hook family `before_tool_call` is one of several typed hooks, and each has an execution kind that decides how results combine. **Gate** and **modify** hooks run sequentially and can change or stop the operation; **claim** hooks stop at the first handler that returns `{ handled: true }`; **observe** hooks run concurrently and their return values are ignored. Neighbours worth knowing: - `after_tool_call` observes results, errors and duration, but cannot undo the call; - `before_agent_reply` can answer a message without a model call by returning `{ handled: true, reply }`; - `message_sending` rewrites outgoing text or cancels delivery; - `gateway_start` and `gateway_stop` start and stop plugin-owned services with the Gateway. Pick the hook whose kind matches the job: a guard belongs on a gate hook, because an observe hook's return value is never read. ## Proving it works 1. Enable the plugin and, for a hook-only plugin, declare `activation.onCapabilities: ["hook"]` in the manifest. 2. Run `openclaw plugins inspect <id> --runtime --json` and confirm the hook is listed with no blocked-registration diagnostics. 3. Ask the agent to run a matching tool and confirm the approval prompt or block actually appears.

  • One handler requests approval and a lower-priority handler returns `block: true`. What wins?
    The block. The first `requireApproval` wins and freezes the parameter snapshot, so later handlers cannot change the approved parameters, but a lower-priority handler can still block the call after a higher-priority one asked for approval.
  • Is a `before_tool_call` hook a security boundary against a hostile plugin?
    No. Every native plugin runs in the Gateway process with the same trust as core code, so another installed plugin is not constrained by your hook. It is a policy layer over tool calls the agent makes; the trust decision is which plugins are allowed to load at all.

  • Typed hooks like before_tool_call can be registered with api.registerHook.
  • A later handler returning block: false overrides an earlier block.
  • If a before_tool_call handler crashes, the tool call goes ahead.
  • Lower priority numbers run first in OpenClaw plugin hooks.
  • An unanswered approval request eventually lets the tool call proceed.