# Review tool calls with hooks

Let your own endpoint allow, ask about, or deny each integration tool call before it runs.

## How hooks work

A hook is an HTTPS endpoint of yours. Smallworld calls it before an integration tool call runs, and it answers `allow`, `ask`, or `deny`, optionally with a reason. Smallworld holds no rules of its own: it sends what the call does and what happened before it in the session, enforces the answer, and records it. Routing an approval to the right person stays in your product.

- Add hooks under [Hooks](https://app.smallworld.sh/app/hooks) in the dashboard or through the [public hook API](https://smallworld.sh/docs/create-tool-hook.md). You can add multiple global hooks for every tool call, and multiple hooks for each integration.

- Hooks check every integration with tools: hosted integrations such as Notion and GitHub, custom integrations, MCP servers, and Web Access. Python and JavaScript are runtimes, not tool calls. Hooks also check agents' changes to mounts; see [Mount changes](#mount-changes).

- All global hooks and all hooks for the call's integration run in parallel. The strictest answer wins, each hook's answer is recorded, and if any hook fails, the call is denied.

For each tool call, Smallworld checks, in this order:

- Whether the integration is on for the workspace and the World.

- The tool's policy. A Hidden or Deny tool is denied without calling a hook.

- The hooks.

- An approval, when the result is Ask.

- The provider call.

Hooks only tighten. The result is the strictest of the tool's policy and every hook's answer: deny beats ask, and ask beats allow.

| Tool policy | Strictest hook answer | Result |
| --- | --- | --- |
| Allow | `allow` | Runs |
| --- | --- | --- |
| Allow | `ask` | Pending approval, reason shown |
| --- | --- | --- |
| Ask | `allow` or `ask` | Pending approval, reason shown when given |
| --- | --- | --- |
| Allow or Ask | `deny` | Denied with `errorCode: "hook_denied"`, reason in the error |
| --- | --- | --- |
| Allow or Ask | Any hook failed | Denied with `errorCode: "hook_unavailable"` |
| --- | --- | --- |
| Deny, Hidden, or off | No hook is called | Denied by policy |
| --- | --- | --- |

## The request

Each hook receives one signed POST per tool call, in the custom integration envelope with `type: "tool_call.before"`. `user.id` is your application's user ID, from the `userId` your backend sent to execute.

Request headers

```http
POST https://api.example.com/smallworld/hooks
content-type: application/json
webhook-id: <tool call ID>
webhook-timestamp: <Unix seconds>
webhook-signature: v1,<base64 HMAC-SHA256 of "<id>.<timestamp>.<body>">
```

Request fields

```typescript
type ToolCallHookRequest = {
  type: "tool_call.before";
  id: string; // The tool call ID, also sent in webhook-id.
  integration: {
    key: string;
    name: string;
    account: string | null;
    connection: "personal" | "group" | "none"; // Whose connection the call uses.
  };
  tool: { name: string; description: string; label: "read" | "write" | "destructive" | "unknown" };
  arguments: Record<string, unknown>; // Always in full.
  policy: "allow" | "ask"; // The tool's own policy.
  user: { id: string; test: boolean; group: { id: string; name: string | null } | null };
  worldId: string | null;
  sessionId: string | null;
  executionId: string | null;
  command: string | null; // The whole command the agent ran.
  context?: Record<string, unknown>; // The execute request's context, when there is one.
  recentToolCalls: {
    integration: string;
    tool: string;
    description: string;
    arguments: unknown; // Cut to 16 KB of JSON text when longer.
    argumentsTruncated: boolean;
    outcome: "completed" | "failed" | "unknown" | "denied" | "in_progress";
  }[];
};
```

Request example

Request

```json
{
  "type": "tool_call.before",
  "id": "b5212df0-ea8b-4eb8-a7b1-057ff45b3044",
  "integration": {
    "key": "notion",
    "name": "Notion",
    "account": "Acme Workspace",
    "connection": "group"
  },
  "tool": {
    "name": "notion-update-page",
    "description": "Update a page's properties or content.",
    "label": "write"
  },
  "arguments": {
    "page_id": "1f2e…",
    "content": "Q3 notes"
  },
  "policy": "allow",
  "user": {
    "id": "customer_123",
    "test": false,
    "group": {
      "id": "team_42",
      "name": "Support team"
    }
  },
  "worldId": "01995e56-e2d4-7f19-b691-7bf9af6abdc8",
  "sessionId": "01995e57-0501-76b8-b797-5b24df5b307f",
  "executionId": "01995e57-3027-7557-a233-009ea3dcd8fc",
  "command": "notion update-page --json '{\"page_id\":\"1f2e…\",\"content\":\"Q3 notes\"}'",
  "context": {
    "tenantId": "t_9"
  },
  "recentToolCalls": [
    {
      "integration": "Notion",
      "tool": "notion-search",
      "description": "Search pages and databases.",
      "arguments": {
        "query": "Q3 planning"
      },
      "argumentsTruncated": false,
      "outcome": "completed"
    }
  ]
}
```

- `integration.key` is the integration's command. `account` is the connected account's name, or `null` without a connection, as for Web Access, custom integrations, and MCP servers without sign-in.

- `integration.connection` says whose connection the call uses: `personal` for the user's own, `group` for the session's group's, or `none`. `user.group` is the group the session acts for, with your `id` and its `name`, or `null` in a groupless session. See [Connect a group](https://smallworld.sh/docs/guides/connect-group.md).

- `tool.label` is the tool's mode from its annotations: `read`, `write`, `destructive`, or `unknown`.

- `policy` is the tool's own policy. With `ask`, an approval follows even when your hook answers `allow`.

- `recentToolCalls` lists the last 10 tool call attempts in the session, oldest first, including earlier calls in the same execution and denied calls. It is empty for the first call of a session. Entries carry no IDs. Expired approvals count as `denied` and interrupted calls as `failed`.

- `context` is left out when the execute request has none. It is never stored.

## The answer

Answer with a `2xx` status and a JSON body, sent with `content-type: application/json`. `reason` is optional and at most 1,000 characters. Other fields are ignored.

Response

```json
{
  "status": "ask",
  "reason": "Changes a page under Engineering / Tech Docs"
}
```

A hook that times out, can't be reached, answers with another status, or sends anything else fails, and a failing hook denies the call with `errorCode: "hook_unavailable"`. Hook calls are never retried. The timeout is 30 seconds by default, and can be set from 1 to 60 seconds per hook. Redirects are not followed.

A denial reaches the agent as a tool error with the reason: `Tool call denied by hook: <reason>`, or `Tool call denied by hook` without one. A failure reads `Tool call denied: the hook gave no valid answer`, and the call's `reason` says what went wrong.

Waiting for hooks doesn't count against the workspace's active-time limit, like provider calls, but it counts toward the command's one-hour total. A call whose execution ends while its hooks run leaves no record.

## Ask for approval

An `ask` creates a normal pending approval using the workspace's approval timeout (15 minutes by default, configurable from 5 minutes to 1 month (30 days)). Approve or deny it as in [Approve a tool call](https://smallworld.sh/docs/guides/approve-tool-call.md). Approvals carry what your product needs to route them: your `userId`, `worldId`, `integrationName`, `account`, `connectionSource`, the session's `group`, `toolDescription`, `toolLabel`, and the hooks' `reason`.

Answer within the timeout, also when your hook routes the approval to someone. A hook that waits for a person is denied with `hook_unavailable` once its timeout passes. The tool call is recorded only after the hooks answer: approving it before then returns 404, and approving it after a timeout returns 409.

Approving with `remember: true` saves an Allow override for that user and tool. It changes the tool's policy, never the hooks: they still run on every call, so a hook that asks keeps asking.

## Mount changes

Hooks also check agents' changes to [mounts](https://smallworld.sh/docs/guides/mounts.md), the folders you mount under `/workspace`. At the end of a command, before anything is saved, each mount the command changed gets one `tool_call.before` request, as if the mount were an integration and its changes one tool call. Hooks are called even when every change is allowed, so a hook can still ask for approval or deny. A hook can't stop an operation while the command runs: its `deny` discards all of that mount's changes from the command at the end, and the command's stderr says so.

- Every global hook receives mount changes. To check only mount changes, create a hook with `providerKey: "mounts"`, and add a `mountId` to check one mount only. A hook scoped to a mount is deleted with the mount.

- `integration` is `{ "key": "mounts", "name": "Mounts", "account": null, "connection": "none" }` for every mount. `tool.name` is the mount's ID, and `tool.description` is its path, followed by `—` and its description when it has one. `tool.label` is `destructive` when a change deletes or replaces something, and `write` otherwise.

- `policy` is the strictest of the mount's settings for these changes, `allow` or `ask`. Hooks aren't called for changes the mount's settings deny.

- `arguments` holds the mount's path and its changes, counted by their net effect. Text files carry a unified diff, cut at 16 KB per file and 256 KB per request; binary files are shown only by their size. Folders have a summary with their file count. Every created file is also listed with its path, size, and text diff, including files inside a new folder. Diffs omitted or shortened by these limits are marked as truncated. A moved or deleted folder is summarized as one change.

- A move between two mounts is checked once for both, with the other mount in `linkedMounts`, and uses the stricter of the two mounts' Move settings.

- `recentToolCalls` includes earlier mount checks of the session, as calls of the Mounts integration.

Mount change arguments

```typescript
type MountChange = {
  operation: "create" | "update" | "delete" | "move" | "rename";
  kind: "file" | "directory";
  path?: string; // Created, updated, and deleted entries, as the terminal sees them.
  from?: string; // Moves and renames.
  to?: string;
  files?: number; // Files inside a created, deleted, or moved folder, which is one change.
  replaces?: boolean; // A move or rename onto an existing entry.
  size?: number; // Bytes of a created, updated, or deleted file.
  diff?: string; // Unified diff of a text file.
  diffTruncated?: boolean; // The diff was cut or left out to stay within the size limit.
  binary?: boolean; // A binary file: only its size is sent.
};

type MountCheckArguments = {
  path: string; // The mount's path, such as /workspace/docs.
  changes: MountChange[];
  // A move between two mounts checks both mounts together; these are the other mount's changes.
  linkedMounts?: { mountId: string; path: string; changes: MountChange[] }[];
};
```

Mount request example

Request

```json
{
  "type": "tool_call.before",
  "id": "c3e1a9f2-4b7d-4e8a-9f10-2a3b4c5d6e7f",
  "integration": {
    "key": "mounts",
    "name": "Mounts",
    "account": null,
    "connection": "none"
  },
  "tool": {
    "name": "0199a1c4-5b6e-7a10-9c2d-3e4f5a6b7c8d",
    "description": "/workspace/docs — Product documentation. Answers to customer questions go in faq.md.",
    "label": "write"
  },
  "arguments": {
    "path": "/workspace/docs",
    "changes": [
      {
        "operation": "update",
        "kind": "file",
        "path": "/workspace/docs/faq.md",
        "size": 37,
        "diff": "--- /workspace/docs/faq.md\n+++ /workspace/docs/faq.md\n@@ -1,3 +1,3 @@\n # FAQ\n \n-Refunds take 5 business days.\n+Refunds take 3 business days.\n"
      }
    ]
  },
  "policy": "ask",
  "user": {
    "id": "customer_123",
    "test": false,
    "group": {
      "id": "team_42",
      "name": "Support team"
    }
  },
  "worldId": "01995e56-e2d4-7f19-b691-7bf9af6abdc8",
  "sessionId": "01995e57-0501-76b8-b797-5b24df5b307f",
  "executionId": "01995e57-3027-7557-a233-009ea3dcd8fc",
  "command": "sed -i 's/5 business days/3 business days/' /workspace/docs/faq.md",
  "context": {
    "tenantId": "t_9"
  },
  "recentToolCalls": [
    {
      "integration": "Notion",
      "tool": "notion-search",
      "description": "Search pages and databases.",
      "arguments": {
        "query": "Q3 planning"
      },
      "argumentsTruncated": false,
      "outcome": "completed"
    }
  ]
}
```

An `ask` creates one approval for the mount's changes, decided like any tool call; `remember` is ignored for it. When the changes are rejected, expire, or a hook denies them, all of that mount's changes from the command are discarded, also the allowed ones, and the execution's `mountChanges` says why. The session's `/workspace` files and other mounts are still saved.

## Verify and test

Requests are signed as Standard Webhooks messages, with `webhook-id` set to the tool call ID. Each hook has its own `whsec_…` signing secret, shown during setup. Save it in your endpoint’s environment before testing; the created hook keeps that secret. **Rotate secret** replaces it immediately, with no overlap: calls made before your endpoint uses the new secret fail your signature check, and a failing hook denies the call.

server.ts

```typescript
import { createHmac, timingSafeEqual } from "node:crypto";
import express from "express";

const secret = Buffer.from(process.env.SMALLWORLD_HOOK_SECRET!.slice("whsec_".length), "base64");
const app = express();

// Verify the raw bytes before parsing them.
app.post("/smallworld/hooks", express.raw({ type: "application/json" }), (request, response) => {
  const id = request.header("webhook-id") ?? "";
  const timestamp = request.header("webhook-timestamp") ?? "";
  const body = request.body.toString("utf8");
  const expected = Buffer.from("v1," + createHmac("sha256", secret).update(`${id}.${timestamp}.${body}`).digest("base64"));
  const signed = (request.header("webhook-signature") ?? "")
    .split(" ")
    .some((candidate) => candidate.length === expected.length && timingSafeEqual(Buffer.from(candidate), expected));
  if (!signed || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return response.status(401).end();

  const call = JSON.parse(body);
  // Your product holds the rules: look up the user's organization, its approvers, and the resource.
  if (call.tool.label === "destructive") return response.json({ status: "ask", reason: "Deletes data in " + call.integration.name });
  return response.json({ status: "allow" });
});

app.listen(4319);
```

Endpoints must use HTTPS at a public address. Development and test servers also accept plain HTTP on `localhost`.

Through the API, first [create draft credentials](https://smallworld.sh/docs/create-tool-hook-draft.md), then [test the draft](https://smallworld.sh/docs/test-tool-hook-draft.md). Pass its non-null verificationToken with the exact configuration to [create the hook](https://smallworld.sh/docs/create-tool-hook.md). The secret is preserved, and creation does not send another request. Saved configuration reads never return the signing secret.

Setup has two steps: configure the endpoint and signing secret, then send a test call. Before you can create the hook, the endpoint must return a 2xx HTTP status with a valid JSON answer matching the response schema. Any valid `allow`, `ask`, or `deny` answer passes the test. Changing its scope, URL, or timeout requires another test. Testing does not activate the hook.

**Send test call** on the Hooks page sends a sample request with `user.test: true` and `null` World, session, and execution IDs, and shows the response body and expandable request details. It records no tool call. Playground tool calls also reach your hooks, with `user.test: true`.

## Read more of the session

When your hook needs more than the request carries, read the session's history with your API key: [List a session's executions](https://smallworld.sh/docs/list-session-executions.md) and [List a session's tool calls](https://smallworld.sh/docs/list-session-tool-calls.md). Both list newest first, 20 items per page by default.
