> ## Documentation Index
> Fetch the complete documentation index at: https://trigger.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Tool permissions outside a chat

> Check the user's grants in a task, pause with a wait token when there's none, and resume once the user approves, even days later.

Scheduled jobs and background agents have no chat to show buttons in. This guide checks the user's grant in the task, pauses with a [wait token](https://trigger.dev/docs/wait-for-token.md) when there's none, and completes the token from your backend once the user answers. In a background agent, run the same check inside the tool's `execute`.

## Store grants

Give each tool a scope string, and store one row per grant. A scope ending in `:*` covers every tool in that integration.

```prisma prisma/schema.prisma theme={"theme":"css-variables"}
model ToolGrant {
  id        String    @id @default(cuid())
  userId    String
  scope     String    // "gmail:send", or "gmail:*" for every Gmail tool
  createdAt DateTime  @default(now())
  revokedAt DateTime?

  @@unique([userId, scope])
}
```

Run `npx prisma migrate dev` to create the table.

Keep the scope map in its own file with no database imports, so your approval buttons can import it in the browser:

```ts lib/tool-scopes.ts theme={"theme":"css-variables"}
// Maps each tool that asks for approval to the scope a grant must cover
export const toolScopes = {
  sendEmail: "gmail:send",
} as const;

export type ScopedTool = keyof typeof toolScopes;

// The scopes a user can grant: one tool, or every tool in its integration
export const grantableScopes = new Set<string>(
  Object.values(toolScopes).flatMap((scope) => [scope, `${scope.split(":")[0]}:*`])
);
```

```ts lib/permissions.ts theme={"theme":"css-variables"}
import { db } from "@/lib/db";

export async function hasGrant(userId: string, scope: string) {
  const [integration] = scope.split(":");
  const grant = await db.toolGrant.findFirst({
    where: { userId, scope: { in: [scope, `${integration}:*`] }, revokedAt: null },
  });
  return grant !== null;
}

// decidedAt is when the user chose "always allow". A revoke after that wins,
// so replaying an older answer can't restore a grant the user removed.
export async function addGrant(userId: string, scope: string, decidedAt: Date) {
  // The revoke check is part of the write, so a revoke that lands in between still wins
  const restored = await db.toolGrant.updateMany({
    where: { userId, scope, OR: [{ revokedAt: null }, { revokedAt: { lt: decidedAt } }] },
    data: { revokedAt: null },
  });
  if (restored.count === 0) {
    // No row yet, or one revoked after decidedAt, which skipDuplicates leaves alone
    await db.toolGrant.createMany({ data: [{ userId, scope }], skipDuplicates: true });
  }
}

export async function revokeGrant(userId: string, scope: string) {
  await db.toolGrant.updateMany({ where: { userId, scope }, data: { revokedAt: new Date() } });
}
```

The examples use Prisma with Postgres. On SQLite, which doesn't support `skipDuplicates`, catch the unique constraint error instead. They import your Prisma client from `@/lib/db`, a `gmail` wrapper around the user's Gmail connection from `@/lib/gmail`, and `requireUser` from `@/lib/auth`, which returns the signed-in user. Swap in your own.

## Check the grant and wait for an answer

If the user has no grant, create a wait token tagged with their ID, and tell the user what the task wants to do by email, Slack or your app. The run suspends until the token completes or times out. If the user chose "always allow", the task saves the grant from the answer it received.

```ts trigger/send-digest.ts theme={"theme":"css-variables"}
import { task, wait } from "@trigger.dev/sdk";
import { gmail } from "@/lib/gmail";
import { addGrant, hasGrant } from "@/lib/permissions";
import { toolScopes } from "@/lib/tool-scopes";
import { notifyUser } from "@/lib/notify";

type Approval = { approved: boolean; always: boolean; decidedAt: string };

export const sendDigest = task({
  id: "send-digest",
  run: async (payload: { userId: string; to: string; subject: string; body: string }, { ctx }) => {
    const scope = toolScopes.sendEmail;

    if (!(await hasGrant(payload.userId, scope))) {
      const token = await wait.createToken({
        timeout: "7d",
        tags: [`user:${payload.userId}`],
        // A retried attempt gets the same token back instead of asking again
        idempotencyKey: ctx.run.id,
      });
      // Link to your own approval page with the token ID, never the token's URL.
      // Skip a token ID you've already sent, so a retry can call this safely.
      await notifyUser(payload.userId, {
        action: `Send "${payload.subject}" to ${payload.to}`,
        tokenId: token.id,
      });

      // The run suspends here and uses no compute until the token completes or times out
      const result = await wait.forToken<Approval>(token);
      if (!result.ok || !result.output.approved) return { sent: false };

      // Uses the answer that completed the token, so a losing answer can't add a grant,
      // and its decision time, so a retry can't undo a revoke made after it
      if (result.output.always) await addGrant(payload.userId, scope, new Date(result.output.decidedAt));
    }

    // Your send function records this key and skips one it has already sent
    await gmail.send(payload.userId, payload, { idempotencyKey: ctx.run.id });
    return { sent: true };
  },
});
```

`wait.forToken` returns `ok: false` when the token times out, so a request nobody answers counts as not approved.

## Complete the token from your backend

Your approval page posts the user's answer to a route like this one. It checks that the token is waiting on the signed-in user, then completes it with the answer:

```ts app/api/approve/route.ts theme={"theme":"css-variables"}
import { wait } from "@trigger.dev/sdk";
import { requireUser } from "@/lib/auth";

export async function POST(req: Request) {
  const user = await requireUser();
  const { tokenId, approved, always } = await req.json();

  // Only the user the request went to can answer it, and only while the run is waiting
  const token = await wait.retrieveToken(tokenId).catch(() => null);
  if (!token || !token.tags.includes(`user:${user.id}`) || token.status !== "WAITING") {
    return Response.json({ error: "Not found" }, { status: 404 });
  }

  await wait.completeToken(tokenId, {
    approved: approved === true,
    always: always === true,
    decidedAt: new Date().toISOString(),
  });
  return Response.json({ ok: true });
}
```

> [!WARNING]
>
> The token's `url` completes it without an API key. Complete tokens from your authenticated backend, as above, and don't send the URL to anyone who shouldn't approve the action.

## Let users revoke grants

List the user's grants on a settings page, one row per grant, with a revoke button that calls `revokeGrant` for the signed-in user. Revoking `gmail:send` leaves a `gmail:*` grant in place, so show both. The next run after a revoke asks again.

## Verify it

1. Trigger `send-digest` for a user with no grant. Confirm the run waits and the user gets a request.
2. As that user, post `{ tokenId, approved: false }` to `/api/approve`. Confirm the run returns `{ sent: false }` and nothing is sent.
3. Trigger it again and post `{ tokenId, approved: true, always: true }`. Confirm a `gmail:send` row appears in `ToolGrant` and the email sends.
4. Trigger it once more. Confirm it sends without asking.
5. Revoke the grant and trigger it again. Post the new token ID as a different user, and confirm the route returns 404 and the run keeps waiting. Then post it as the owner and confirm the email sends.

## Common mistakes

* **Completing any token ID you're sent.** Check that the token is tagged for the signed-in user and still waiting, or one user can approve another user's action.
* **Sending the token URL in a notification.** Anyone with the URL can complete the token. Link to your own app instead.
* **An idempotency key your send function ignores.** A retried run can send the same email twice, and Gmail doesn't deduplicate sends. Key it on the run ID, and skip a key you've already sent.
* **Grants with no revoke path.** Give users a page where they can see and remove their grants.

## Next steps

> [card] [In a chat](https://trigger.dev/docs/ai-chat/patterns/tool-permissions-chat.md)
>
> Ask for permission inside a chat with approval buttons.

> [card] [Wait for token](https://trigger.dev/docs/wait-for-token.md)
>
> Pause any task until your app or an external service completes a token.

> [card] [Slack approvals](https://trigger.dev/docs/webhooks/human-in-the-loop.md#slack-approvals)
>
> Approve and Deny buttons for agents running in Slack.

> [card] [Tool permissions](https://trigger.dev/docs/ai-chat/patterns/tool-permissions.md)
>
> How connections, grants and approvals fit together.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.