# Adding MCP Tools

> Register your own MCP tools: add a scope, write an owner-filtered service, register the tool with translated metadata, and test it.

*Canonical: https://makerkit.dev/docs/void-cloudflare/mcp-server/adding-tools*

---

Tools live in `apps/web/config/mcp-tools.server.ts`. Each tool declares the scopes it needs. The server lists and runs it only for credentials that hold them, and checks again on every call. Your service must still check every resource against the verified account.

## Checklist

To add a read tool, in this order:

1. [Add a scope](#1-add-a-scope) in `apps/web/config/api-access.config.server.ts`.
2. [Write the query](#2-write-the-query-and-service), filtered by the verified account.
3. [Register the tool](#3-register-the-tool) in `apps/web/config/mcp-tools.server.ts`.
4. [Add its description](#4-add-the-description) as a translated server string.
5. [Check it](#5-check-it) with a real key.

A tool that changes data? Do the same, then read [Write Tools](#write-tools). A business rule such as "paid accounts only"? See [Gate Tools on Plans or Other Rules](#gate-tools-on-plans-or-other-rules).

The example below adds `projects_list`, which returns the account's projects. `project` stands for your own table.

## 1. Add a Scope

A scope is `resource:action`. Add it to `apiAccessScopes` in `apps/web/config/api-access.config.server.ts`:

```ts
export const apiAccessScopes = {
  'account:read': { personal: true, organization: { apiKey: ['read'] } },
  'projects:read': { personal: true, organization: { project: ['read'] } },
} satisfies ScopeCatalogue;
```

- `personal: true` lets personal keys carry it.
- `organization` is the RBAC statement a member must hold to put the scope on an organization key or approve it on consent. Add the `project` resource and its actions to `packages/rbac/src/rbac.config.ts` first ([Customizing Roles](../members-management/roles-permissions#customizing)): a scope name alone grants nothing.
- If you use browser OAuth, also add the scope to `mcpServer.scopes` in the same file, and to the clients you provision.

**It worked when** the scope shows up as a checkbox on the API keys pages.

## 2. Write the Query and Service

Read the owner from the verified account, never from tool input. **Why:** a client could send another account's id. Keep the query in a named function:

```ts
// apps/web/db/projects.server.ts
import { desc, eq } from 'drizzle-orm';
import { db } from 'void/db';
import type { McpPrincipal } from '@kit/api-access/mcp';

import { project } from '#/db/schema.ts';

const PROJECTS_PAGE_SIZE = 50;

export function findAccountProjects(account: McpPrincipal['account']) {
  const owner =
    account.kind === 'organization'
      ? eq(project.organizationId, account.id)
      : eq(project.userId, account.id);

  return db
    .select({ id: project.id, name: project.name })
    .from(project)
    .where(owner)
    .orderBy(desc(project.createdAt))
    .limit(PROJECTS_PAGE_SIZE);
}
```

A tool that takes a resource id (`projectId`) must filter by both the id and the owner, so another account's id finds nothing.

## 3. Register the Tool

Put the input schema in a `*.schema.ts` file. Inputs are strict objects. `account`, `accountId`, `organizationId`, `userId`, `keyId`, `scopes` and the other principal fields are reserved and can't be inputs.

```ts
// apps/web/config/mcp-tools.schema.ts
import * as z from 'zod';

export const projectsListInput = z.object({});

export const projectsListOutput = z.object({
  projects: z.array(z.object({ id: z.string(), name: z.string() })),
});
```

Register it next to `account_context`:

```ts
// apps/web/config/mcp-tools.server.ts
import {
  registerAccountContextTool,
  type RegisterScopedTool,
} from '@kit/api-access/mcp';

import { findMcpAccount } from '#/db/mcp-account.server.ts';
import { findAccountProjects } from '#/db/projects.server.ts';

import { projectsListInput, projectsListOutput } from './mcp-tools.schema.ts';

export function registerMcpTools({
  registerTool,
  accountContextDescription,
  projectsListDescription,
}: {
  registerTool: RegisterScopedTool;
  accountContextDescription: string;
  projectsListDescription: string;
}) {
  registerAccountContextTool({
    registerTool,
    description: accountContextDescription,
    findAccount: findMcpAccount,
  });

  registerTool(
    'projects_list',
    {
      description: projectsListDescription,
      inputSchema: projectsListInput,
      outputSchema: projectsListOutput,
      requiredScopes: ['projects:read'],
      annotations: {
        readOnlyHint: true,
        destructiveHint: false,
        idempotentHint: true,
        openWorldHint: false,
      },
    },
    async (_input, { account }) => {
      const result = { projects: await findAccountProjects(account) };

      return {
        content: [{ type: 'text', text: JSON.stringify(result) }],
        structuredContent: result,
      };
    },
  );
}
```

- **Names:** letters, digits, `_`, `.`, `-`; up to 128 characters; unique.
- **Annotations:** all four are required. They describe the tool to clients and grant nothing.
- **Handler context:** `account` (`kind`, `id`), `credential` (`kind`, `id`), `scopes` and `signal`. Pass `signal` to long work. No request, headers or session.
- **Errors:** a thrown error reaches the client as `TOOL_EXECUTION_UNAVAILABLE`, with no details.
- **Timing:** register synchronously. The registrar closes when `registerMcpTools` returns.

## 4. Add the Description

AI clients see the description, so it is a translated server string.

1. Add `projectsListDescription` to the app's `api-access` server namespace: `apps/web/messages/<locale>/api-access.server.json`. Ask your agent, which uses `app_translations_update`.
2. Pass it in `apps/web/lib/mcp.server.ts`:

```ts
registerTools: (registerTool) =>
  registerMcpTools({
    registerTool,
    accountContextDescription: t('accountContextDescription'),
    projectsListDescription: t('projectsListDescription'),
  }),
```

## 5. Check It

1. Restart the app.
2. Create a key with `projects:read`.
3. Run the [API-key client](./connecting-clients#connect-with-an-api-key) with `callTool({ name: 'projects_list', arguments: {} })`. It returns the projects.
4. Try a key without `projects:read`: it doesn't see the tool in `listTools`, and the server refuses a call to it.
5. Try both kinds of key: an organization key returns only that organization's projects, a personal key only the user's.
6. Add a test in `apps/web/tests/routes/` alongside `mcp.test.ts`, which drives `/api/mcp` through the real SDK client.

## Write Tools

A tool that changes data uses the same registrar, plus:

- A strict input with resource ids, checked against `account` **inside** the write transaction.
- A business-identity retry key, so a client retrying after a timeout doesn't write twice. A `503` doesn't prove nothing changed.
- Network calls outside the transaction; follow-up work through the [outbox](../outbox/overview).
- An audit event after commit with `recordSystemAudit`, attributed to the credential, not the member who made the key.

The full pattern, with a tested rename example: [Customer Write Tools](../authentication/api-access#customer-write-tools).

## Gate Tools on Plans or Other Rules

Scopes say what a credential may do. For a business rule ("only paid accounts get API access"), register an API-access policy. Don't check inside every tool: [Customer Policies](../authentication/api-access#customer-policies).
