# MCP kit (TypeScript)

Reference for @omazyai/sdk/mcp. One MCP server per door, built from the capabilities registry, with every tool call through the guard. Spec 2026-07-28, and 2025 and 2024-11-05 clients served statelessly.

Source: https://docs.omazy.ai/build-on-omazy/kits/mcp/

:::caution[Preview]
The kit is a preview in `@omazyai/sdk` 0.5.3. Its interface may change before 1.0, so pin the exact version. It is TypeScript only.
:::

```ts
import { mcpDoors, mcpServer } from '@omazyai/sdk/mcp'
```

The kit serves your [capabilities](/build-on-omazy/kits/capabilities/) as MCP
tools, so claude.ai, ChatGPT, Cursor, Claude Code and Omazy's own agent can
call them. Each tool call goes through the guard, which decides whether it
runs, asks for a confirmation or holds it for an approval.

It is built on the official MCP TypeScript SDK v2. Install it beside the SDK,
at the version the kit is tested with:

```sh
npm i @omazyai/sdk @modelcontextprotocol/server@2.4.0
```

## A door

A door is one MCP server for one audience of your registry, at its own path.

```ts
import { createGuard } from '@omazyai/sdk/guard'
import { mcpServer } from '@omazyai/sdk/mcp'
import { reg } from './capabilities'

export default {
  async fetch(req: Request, env: Env, exec: ExecutionContext) {
    const guard = createGuard({ registry: reg, can, secret: env.GUARD_SECRET, store: guardStore(env) })
    const org = mcpServer({
      registry: reg,
      guard,
      door: 'org',                       // the audience; served at /org
      info: { name: 'acme-org', version: '1' },
      instructions: 'Tools for the people who run one Acme branch.',
      resolveSeat: (token) => keys.find(env, token),   // null for an unknown token
    })
    return org.fetch(req, env, exec)
  },
}
```

Pass the execution context: the guard writes its request log through
`waitUntil`, after the answer has gone.

### Options

| Option | What it is |
|---|---|
| `registry` | Your capabilities registry. Only the capabilities whose `audiences` name this door are listed or called. |
| `guard` | The guard every `tools/call` goes through. |
| `door` | The audience this server serves. |
| `path` | The resource path. Default `/<door>`. |
| `resolveSeat(token, req)` | Turns the bearer token into `{ principal, seat, maxTier?, tools?, confirm? }`, or null. |
| `ctx(base, grant, req)` | Builds your own ctx from the base one. Needed when your ctx has more fields than the base. |
| `info` | `name`, `version`, and optionally `title`, `description`, `websiteUrl`. |
| `instructions` | A string, or a function of the ctx. |
| `resources`, `prompts` | Plain lists; see below. |
| `pageSize` | Tools per `tools/list` page. Default 50. |
| `listTtlMs` | How long a 2026-07-28 client may cache `tools/list`. Default one minute, private. |
| `errorMessage` | What the model reads when a call fails inside. Default "That did not work. The team has been told." |
| `onError(failure)` | Your alert hook for those failures. Default `console.error`. |
| `resourceMetadataUrl` | The RFC 9728 metadata URL to name in the 401 challenge, once you serve one. |
| `bus` | Where `notifyToolsChanged()` publishes. Default: this isolate only. |
| `maxBodyBytes` | Largest request body read. Default 4 MiB. |
| `accept2024` | Answer 2024-11-05 clients, served like 2025-03-26. Default true. |

## Protocol versions

| Client | How it is served |
|---|---|
| 2026-07-28 | No session and no handshake. The client may call `server/discover` first, then sends its version and capabilities on every request. Results carry `resultType`, and `tools/list` a cache hint. |
| 2025-11-25, 2025-06-18, 2025-03-26 | `initialize` answers the client's version. Every later request is served by a fresh server with no session, answered as one JSON body. GET and DELETE are 405. |
| 2024-11-05 | Served like 2025-03-26, unless `accept2024: false`. |

JSON-RPC batches are accepted only on 2025-03-26 and 2024-11-05: later revisions removed them.

The 2025 and 2024 leg is the kit's own code, and it is lenient where old clients were: a request
without an `Accept` header, or with a body sent as `text/plain`, form data or no content type,
is served when the body is JSON. An `initialize` without `protocolVersion`, `capabilities` or
`clientInfo` gets `-32602` with one sentence naming what is missing. 2026-07-28 requests go to the
MCP SDK as they are, strict as the spec asks.

`capabilities.tools.listChanged` is true only for 2026-07-28 clients, the only ones with a stream
to hear the notice on.
Schemas are checked with the SDK's `cf-worker` validator, which compiles no
code at runtime, so the kit runs on Cloudflare Workers.

## Doors and tokens

Every request needs `Authorization: Bearer <token>`. `resolveSeat` decides who
it is:

```ts
resolveSeat: async (token) => {
  const key = await keys.lookup(token)          // your own key table, by hash
  if (!key) return null
  return {
    principal: { kind: 'member', id: key.personId },
    seat: { id: key.id, door: key.door, tenant: key.tenantId },
    maxTier: key.personal ? 'R2' : undefined,  // a personal key never sees R3 or R4 tools
    tools: key.allowList,                      // a service key sees only these
  }
}
```

- No token, or one `resolveSeat` does not know: 401 with a `Bearer` challenge.
- A token whose seat belongs to another door: 401 `invalid_token`. A token for
  one door never works at another.
- A seat with `confirm: 'upstream'` confirms every change with the person before
  it calls (Omazy's agent with `write_mode: 'confirm'`). Its R2 calls run in one
  step: the guard mints, checks and logs its confirm inside the call
  ([guard](/build-on-omazy/kits/guard/#confirmed-upstream)). Its tools carry no
  `confirm_token` argument. R3 and above still wait for an approval.
- A tool of another door, or above the seat's `maxTier`, is not listed, and
  calling it is an unknown tool (a protocol error, -32602).

## The door switch

The kit reads the door's switch (`all` or `door:<door>`, through
`guard.doorSwitch`) on every request, whatever the method: `initialize`,
`tools/list`, `resources/read` and the rest, not only tool calls. It reads it
twice: at global scope before the token is looked at, then for the seat's
tenant and person once the token is known. A door that is off answers 503:

```json
{ "error": "door_off", "message": "The platform door is off for maintenance." }
```

The message is the switch's `reason`, else `doorOffMessage`, else "This door
is switched off right now." Switches that cannot be read count as off, with
"The switches could not be read, so nothing ran." and the error to `onError`.
Each 503 is a request-log row with the outcome `switched_off` and the code
`door_off` (`error` and `hook_failed` when unreadable): through `logAnonymous`
when the global switch stopped it, through `logRequest` with the seat when a
tenant or person switch did. A product needs no switch check of its own in
front of the door.

Several doors on one Worker, each at its own path:

```ts
const worker = mcpDoors(
  mcpServer({ ...common, door: 'platform', info: { name: 'acme-platform', version: '1' } }),
  mcpServer({ ...common, door: 'org', info: { name: 'acme-org', version: '1' } }),
)
export default { fetch: (req: Request, env: Env, exec: ExecutionContext) => worker.fetch(req, env, exec) }
```

OAuth for public clients comes with the `oauth` kit. Until then
`resolveSeat` is your own key check.

## Tools

`tools/list` comes from `registry.mcpTools(door)`, in registry order:

- `inputSchema` and `outputSchema` from the capability's schemas, closed.
- Annotations from the tier: R0 and R1 read only and idempotent, R2 a write,
  R3 and R4 destructive. `openWorldHint` from `openWorld`.
- Every tool at R2 and above also takes an optional `confirm_token` argument
  (below), except for a seat that confirms upstream.
- Cursor paging. A cursor the server did not give is a protocol error.

## What a call returns

| Guard outcome | Tool result |
|---|---|
| `ok` | The capability's `say(output)` as text, or the result as JSON text without one, and the result as `structuredContent` when it is an object. A result that does not match the output schema counts as a failure. A `say` that throws falls back to the JSON text and goes to `onError`. |
| `confirm_required` | On a 2026-07-28 client that declared elicitation: `input_required` with a yes or no form showing the preview. The client retries with the answer, and the call runs. Otherwise: a result with the preview and a `token`, and a sentence telling the model to ask the person and call again with the token. |
| `pending_approval` | A result with who decides, by when, and the review link. Nothing has changed, and the sentence tells the model not to call again. |
| `invalid` | `isError`, with each problem and its field, so the model can fix its arguments. With `invalidMessage` on the capability, only its sentence. |
| `not_found` | `isError`, with the sentence from `run`. |
| Other refusals | `isError`, with the guard's sentence. |
| `error`, or anything thrown | `isError`, with `errorMessage` and a reference. Your `onError` hook gets the real error. The model never sees it. |
| `switched_off` for the door (`door:<door>` or `all`) | HTTP 503 at the door. The kit reads the door switch before every request too (below), so this happens only when the switch went off between the two reads. |

A confirm or approval is not the tool's output. On a tool with an output
schema, it rides in `_meta["ai.omazy/outcome"]` with `isError: true`, so no
client rejects it for not matching the schema. On a tool without one, it is
the `structuredContent`. Every result carries the outcome in that `_meta` key.

The outcome uses the guard's names, so code that reads `guard.call` reads a
tool result the same way:

| Outcome | Fields |
|---|---|
| `confirm_required` | `outcome`, `token`, `expiresAt`, `preview` |
| `pending_approval` | `outcome`, `approval` (`id`, `decider`, `expiresAt`, `preview`, `reviewUrl?`), `expiresAt`, `preview` |
| A refusal | `outcome`, `code`, `retryAfter?`, `issues?` |
| `declined` | `outcome` |
| `ok` after an approval | `outcome`, `approvalId` |

```json
{ "outcome": "confirm_required", "token": "…", "expiresAt": "2026-11-24T10:05:00Z", "preview": { "summary": "Add the note \"Call the plumber\"." } }
```

The old snake_case keys (`status`, `confirm_token`, `expires_at`,
`approval_id`, `decider`, `review_url`, `retry_after`) are still sent beside
them. They are deprecated and go in the next release. The argument a client
sends back is still `confirm_token`.

A client that cannot add arguments may send the token as
`_meta["ai.omazy/confirm_token"]` instead.

## Resources and prompts

```ts
mcpServer({
  ...,
  resources: [
    { uri: 'acme://docs/tiers', name: 'tiers', mimeType: 'text/markdown', read: () => tiersMarkdown },
    { uri: 'acme://branch/brief', name: 'brief', read: (ctx) => briefs.get(ctx.tenant) },
  ],
  prompts: [
    {
      name: 'weekly_review',
      description: 'Review the branch week.',
      arguments: [{ name: 'week', required: true }],
      get: (args, ctx) => `Review week ${args.week} for ${ctx.tenant}.`,
    },
  ],
})
```

`read` and `get` run with the caller's ctx, so they can read only what the seat
may see.

## The request log

The guard logs every tool call. The kit logs every other request through the
guard's `logRequest` (sampled by the guard), with its method and time. A
request refused before it has a seat goes through `logAnonymous`, never
sampled, with the code `no_token`, `bad_token` or `wrong_door`.

A call to a tool the seat cannot see never reaches `guard.call`, so the kit
writes its row through `logRequest`: method `tools/call`, the tool name, the
outcome `invalid` (the outcome the guard gives an unknown tool), and the code
`unknown_tool` (not on this door), `tier_above_seat` (above the seat's
`maxTier`) or `not_in_allow_list` (outside a service key's `tools`). The
client sees the same protocol error in all three cases. Every
answer carries `X-Omazy-Request-Id`: the one the request sent, or a new one,
which is also the ctx's `requestId`.

## List changes

`door.notifyToolsChanged()` sends `notifications/tools/list_changed` to
2026-07-28 clients listening on this isolate. A Worker has many isolates: pass
a `bus` over a Durable Object to reach all of them. 2025 clients served
statelessly have no stream to receive it, and see the change on their next
`tools/list`.

## Size

The kit's weight is the MCP SDK and the zod it needs. A product on Workers that measured it
(four tools, the guard, the request log in D1) bundles to 769 KB, 162 KB gzipped, of which the
MCP SDK and zod are about 627 KB. It loads in about 17 ms on a cold isolate and adds about
0.15 ms of CPU to a tool call. The kit does not offer a lighter entry without the SDK: it would
save those milliseconds and lose 2026-07-28, elicitation and the output check.

A minimal Worker with one capability and the kit is about 348 KB minified,
95 KB gzipped. The MCP SDK is about 215 KB of that and zod, which it needs,
about 106 KB. The example Worker below, with the guard and its memory
adapters, is 373 KB minified and 103 KB gzipped. Workers allow 3 MB compressed
on the free plan.

## Example

`examples/mcp-worker.ts` in the SDK repository is a notes product on one
Worker: three capabilities (a read, a write that confirms, a purge that needs
an owner's approval), the guard on its memory adapters, and an `org` door with
a resource and a prompt. Run it with `npx wrangler dev examples/mcp-worker.ts`
and connect with the bearer `demo-org-key`.

## Moving from `@omazyai/sdk/server`

`serveMcp` stays as it is in `@omazyai/sdk/server`, with no dependency, so a
server written against 0.4.0 keeps working. To move a server onto the kit:

1. Turn each entry of your `tools` list into a `capability()`: its
   `inputSchema` becomes `input`, the branch of `call` for it becomes `run`,
   and `READ`, `WRITE` or `DESTRUCTIVE` becomes a tier: R0 or R1, R2, R3 or R4.
2. Put the check your `call` made (who may do what) into the guard's `can`.
3. Replace `serveMcp(req, token, registry, makeCtx)` with `mcpServer` and a
   `resolveSeat` that accepts the same token:

   ```ts
   resolveSeat: (t) => (timingSafeEqual(t, env.MCP_TOKEN)
     ? { principal: { kind: 'service', id: 'omazy' }, seat: { id: 'omazy', door: 'agent', tenant: null } }
     : null)
   ```

4. The path moves from `/mcp` to `/<door>`; set `path: '/mcp'` to keep the URL
   you gave Omazy. `/health` is not served by the kit; answer it in your own
   `fetch` before the door.
5. An R2 write now asks for the guard's confirm: the model gets the preview,
   asks the person, and calls again with the token. Connected to Omazy with
   `write_mode: 'confirm'`, the visitor would also see Omazy's card first and
   be asked twice. Fix the double confirm by giving Omazy's seat
   `confirm: 'upstream'` in `resolveSeat`: Omazy's card is the confirmation,
   and the guard checks and logs its own inside the one call. If the door
   keeps no other state, `createGuard({ ..., ephemeral: true })` needs no store
   or secret.
6. Old clients that sent fields your schema does not name: set
   `unknownFields: 'strip'` on those capabilities rather than loosening the
   schema.
