Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Ape Add Route?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/buffape-ape-add-route)
---
name: ape-add-route
description: "Add or change an HTTP route: the shared Zod route schema, roles, actions, audited sensitive reads, MCP exposure."
---
# Add a route
1. Declare the schema once with `route()` from `@buffcore/contracts`, in the module's `contract.ts` (`apps/api/src/modules/<key>/contract.ts`; the admin and the app import it from there by a relative path). In BuffCore: `packages/contracts/src/modules/<module>.ts`.
- Every route has an English AI `description` (outcome, input, answer and when to use it; one to three sentences, at least 40 characters), and either `mcp: true` or a short `closedBecause` reason, never both (CONNECT.md, The AI door).
- `method`, `path` (`/v1/…`; admin routes under `/v1/admin/…`), `params`, `query` (lists use `cursorQuery` and `page(item)`), `body`, `response`.
- Who may call it: `access: 'public'`, the default (signed in), or `roles` for an admin route: `roles: ['owner']` for what only the Owner does (the product's money, settings, whatever publishes to every member), `roles: ['support']` (or another role the product declares, below) for what staff the Owner appoints may do too. The Owner always may, so another role only widens a route; `owner` needs no declaration. A signed-in route passes for an operator too, but they act only for the accounts they belong to, usually none: `callerAccountId` gives nothing, so tasks' member list answers empty and its create is refused `403` (the route test shows both). What the console needs from every account (a picker, a list) is an admin route with `roles`, never the member's. Reuse a role when the same person does the job (whoever handles one thing also handles the next); declare a new one, named for the job, when another person does. A role other than the Owner is declared where the app is composed, `buffcoreModules(product, { identity: { roles: ['support'] } })`, and named in the admin catalog as `admin.roles.<role>`.
- `audit: 'sensitive-read'` when opening it reads something on the product's list of sensitive reads.
- `audit: 'none-for-machines'` only for routine machine reports: skips successful automatic machine rows, preserves people's audit behavior, failures and explicit `server.audit` entries; start refuses it with `action` or sensitive `carries` kinds, and `ape manifest` shows the mark.
- `actors: ['device', 'profile']` for a route a device in profile mode (or the profile it acts as) may call, including a live-session start route (`['profile']` when only a profile may). Those kinds are closed by default: they reach only routes that name them and public ones, never a member's, nor one with `roles`; a profile acts for `ctx.actor.accountId` (`callerAccountId(ctx)`) as `ctx.actor.id`, a device for no account (`deviceOf(ctx.actor)` from `@buffcore/modules/devices` gives its grant), never `accountIds`.
- `part: { type: 'project', param: 'projectId' }` when it acts on one part of an account (its module declares the type with identity's `parts`, the `ape-add-module` skill), or `{ type: 'account', param: 'accountId' }` when it acts on the account itself: the caller then needs the right to its key there, through their role in that account or a right given to them (an account's Owner, and a person alone in one, hold every right); otherwise `403 forbidden` with `{ right }`, at every door. It needs no account check of its own. Without `part`, a member route checks the account in its path or needs the route's account right when `X-Account-Id` selects a non-default account. Add the key to the presets that should give it (`identity: { accountRoles }`); `can(ctx, key, part)` from `@buffcore/server` asks first, for a button to show or hide (`docs/IDENTITY_ACCESS.md`, rights).
- `preview: true` only for a write the admin's embedded app must make (e.g. starting a live session); the handler then keeps a preview (`ctx.actor.preview`) to its test profile, and checks no operator roles (a preview token carries none).
- A `name` on every route: snake_case, unique in the module, verb first, without the module's own word (`publish_set` in `content`; tasks' `create_task`). Its key, `content.publish_set`, names it everywhere: the audit row, its rules, `runAction`, an agent's tool and the MCP tool (`content_publish_set`). The app won't start without it.
- `action: { risk: 'low' | 'high', alwaysHuman? }` on every write an operator makes (an admin route with `roles`): it is a business action, one function behind the admin button, the API, MCP and agents (`docs/CONNECT.md`, `docs/AUTOMATION.md`). A member's own write is no action (tasks' `createTask`). Every call to an action meets its rules: with none, a person runs it and a machine or an agent waits for a person (a high-risk one as a Draft to edit, a low-risk one as Ask first). `risk: 'high'` for what is hard to undo or reaches other people (publishing a post every member can read, sending a message, a refund, a deletion), `'low'` for what stays inside the account and one click undoes (the `archive_entry` example below); when unsure, `high`, which only makes a machine's call a Draft for a person to edit instead of Ask first; `alwaysHuman: true` when only a person may run it, never a machine (credentials, access, deleting data, money): it then never runs at once for a machine or an agent, whatever the rules say. Add a `description` the AI reads. See the first example below.
- Default rules, when the action needs one (a large amount waits for a person, say): `contributes: [defaultRules.add({ action: 'notes.share', when: [['body.people', '>', 10]], do: 'approve' })]` in the manifest, from `@buffcore/modules/rules`; the first rule that matches decides, and an Owner's rules replace them (`docs/AUTOMATION.md`).
- `mcp: true` to offer it to machines (API keys, MCP clients) and agents; an offered write must be an action. `carries: ['contact']` lists the sensitive kinds it holds: it stays closed to machines unless the product lets every one out (`connect.allowOut`, none by default). A call its rules hold waits for a person in AI drafts (202 `{ waiting: { itemId, displayId } }`); one they refuse is 403 `rule_refused`; reads run as usual, so a read's handler may see a `client` or `agent` actor.
- For an offered action, bind it with `handle(route, handler, { describe })` so its AI draft says what it changes and how to undo it, and add its title to the module's catalogs as `<module>.actions.<name>`, in English and Spanish (`docs/AUTOMATION.md`). In BuffCore, a route it offers also goes in the test that lists them (`packages/modules/src/offered.test.ts`) and in `docs/CONNECT.md`.
- Nothing to declare for maintenance mode: while the kill switch `apps` is off, every route answers 503 `maintenance` except `/v1/admin/…`, `/v1/auth/…`, `/v1/webhooks/…`, health and `GET /v1/maintenance`, and operators and API keys keep working. Put a route the console needs under `/v1/admin/`.
2. Implement it in the module with `handle(route, async ({ params, query, body }, ctx) => …)` and list it in the manifest's `routes`. Use `ctx.em` for data, `ctx.actor` for who, `ctx.t` for words and `ctx.locale` for the language.
- Use `callerAccountId(ctx)` from `@buffcore/server` for the selected or default account. A route with an explicit path account keeps its own account and access checks. For a route about the signed-in person, declare `person: true` and use the caller's identity. The acting-account header still validates the selection and never needs a route right here.
- A list fetches `limit + 1` rows and answers with `pageOf` from `@buffcore/server`, which cuts the page and names the next cursor: `return pageOf(rows.map(toNote), query.limit)`. The cursor is the row's `id`; a list ordered by something else gives the cursor as a third argument (the third example below).
- A list that shows a second table of the module: the page, then that table's rows in one more lookup, joined in code (the second example below).
3. Throw `new AppError('not_found')` (or another code) for expected failures; clients show `error.text(t)` (the message key, else the server's `message`). A row a unique index refuses is `409 conflict`: `flushOrConflict` from `@buffcore/server` (the fourth example below). A rule of the module's own refusing a write (a day already closed, say) is `409` too, with its own sentence: `throw new AppError({ code: 'conflict', status: 409, messageKey: '<module>.errors.<what>' })`. To catch one, ask `isAppError(error)`, never `instanceof AppError`: an extension may have resolved another copy of `@buffcore/server`. Never return stack traces or raw AI output.
4. Operator writes, writes through a machine door or by an agent, and sensitive reads are audited automatically, as `action: '<module>.<name>'`. Code that calls a route outside HTTP (an agent's tool, an approval) uses `runAction(ctx, '<module>.<name>', input)` (or the route, for a typed answer), never the handler, so the same rules apply. Writes accept an `Idempotency-Key`; the SDK sends one.
5. Test with `server.inject()`, acting as someone with `actAs(owner)` or `actAs(member)` from `@buffcore/modules/testing` (the `ape-add-module` skill's test kit): allowed and refused roles, validation in English and Spanish, the audit row. For an offered route, also that a machine caller meets the door rules (403 `forbidden` when it isn't offered or carries a kind not let out) and that an action waits (202) or runs as its rules say.
6. Call it from clients with the SDK: `api.call(route, { params, query, body })`.
## Examples
An operator's write, a business action (`ok` is `{ ok: true }`):
```ts
export const archiveEntry = route({
method: 'POST',
path: '/v1/admin/entries/:entryId/archive',
params: z.object({ entryId: zId }),
response: ok,
roles: ['support'],
name: 'archive_entry',
action: { risk: 'low' },
description: 'Archive an entry so its account no longer sees it.',
});
```
A list over two of the module's tables. BuffCore's modules keep the other row's ID in a plain `uuid` column (no relations) and fetch those rows with one `$in` lookup, never one query per row. Only when a filter or the order is on the other table's column, write that one join as SQL, `ctx.em.execute<Row[]>(sql, [values])` with a `?` for every value (in BuffCore, `packages/modules/src/content/drafts.ts`). Another module's tables are never joined: call its functions. (`after` is the cursor filter of tasks' `routes.ts`.)
```ts
const rows = await ctx.em.find(Entry, { accountId, ...after(query.cursor) }, { orderBy: { id: 'desc' }, limit: query.limit + 1 });
const groups = await ctx.em.find(Group, { id: { $in: [...new Set(rows.map((r) => r.groupId))] } });
const names = new Map(groups.map((g) => [g.id, g.name]));
return pageOf(rows.map((r) => ({ ...toEntry(r), groupName: names.get(r.groupId) ?? null })), query.limit);
```
A list ordered by a column other than `id`: add `id` to the order (rows share a moment), and make the cursor hold both (`toEntry` gives `startsAt` as an ISO string):
```ts
const [at, id] = query.cursor?.split('|') ?? [];
const after = at && id ? { $or: [{ startsAt: { $gt: new Date(at) } }, { startsAt: new Date(at), id: { $gt: id } }] } : {};
const rows = await ctx.em.find(Entry, { accountId, ...after }, { orderBy: { startsAt: 'asc', id: 'asc' }, limit: query.limit + 1 });
return pageOf(rows.map(toEntry), query.limit, (e) => `${e.startsAt}|${e.id}`);
```
A clash with a unique index. Declare the index on the entity, `uniques: [{ properties: ['accountId', 'name'] }]` (`ape migrate create` writes it), and let it decide: no `count` first, which two requests at once both pass. The key is the module's own sentence for the clash (in its `catalog`, the ape-add-translations skill); without one, clients read core's "That changed while you were working".
```ts
ctx.em.create(Group, { accountId, name: body.name });
await flushOrConflict(ctx.em, 'groups.errors.nameTaken');
```