# Protect an MCP server with Pontive (TypeScript)

> Protect an MCP server or any HTTP API with Pontive access tokens in TypeScript: verification, challenges, protected resource metadata and per-tool scopes.

Source: https://www.pontive.com/docs/sdk/mcp-server

For an MCP server, or any HTTP API, that accepts tokens a Pontive instance
issued for it. Register the API in the dashboard first (*APIs*, with its
identifier and scopes). Its identifier is the server's URL, e.g.
`https://mcp.acme.com/mcp`.

`@pontive/pontkit-server/resource-server` then does the rest:

- verifies each request's bearer token on your server, against the issuer's
  keys (fetched once and cached, so no network call per request);
- answers a missing or failing token with the `401` and `WWW-Authenticate`
  challenge an MCP client follows to sign the user in;
- serves your server's protected resource metadata (RFC 9728), which tells the
  client which authorization server to use;
- hands your handler the verified caller as a `Principal`.

```sh
npm install @pontive/pontkit-server
```

## Configure [#configure]

```ts
// pontive.ts
import { createResourceServer } from "@pontive/pontkit-server/resource-server";

export const rs = createResourceServer({
  issuer: process.env.PONTIVE_ISSUER!,     // your auth domain, e.g. https://acme.auth.us.pontive.app
  resource: "https://mcp.acme.com/mcp",    // the API's identifier, exactly as registered
  scopes: ["files:read", "files:write"],   // the API's scopes
  resourceName: "Acme Files",              // optional display fields
});
```

| Option | |
| --- | --- |
| `issuer` | Your auth domain. A list when the instance has a custom auth domain beside its default one: a token from any is accepted, and each is listed in the metadata. |
| `resource` | The API's identifier. Tokens must carry it in `aud`; it is also the metadata's `resource`, so the two cannot differ. |
| `scopes` | The API's scopes, for `scopes_supported`: keys, or the scopes as the dashboard and `GET /v1/apis/{api_id}` give them (`{ key, description, tools, … }`), whose `tools` say which MCP tools each scope allows ([per tool](#per-tool-scopes)). A verified token carrying a scope not listed here is logged once, so configuration drift shows. |
| `unlistedTools` | `"deny"` (default) or `"allow"`: what `requireTool` does with a tool no scope lists ([per tool](#per-tool-scopes)). |
| `resourceName`, `resourceDocumentation`, `logoUri` | The metadata's display fields. |
| `metadata.fetch` | `{ apiId, credential, managementUrl }`: read the metadata from Pontive instead (below). |
| `authorizationServerMetadataProxy` | Also serve `/.well-known/oauth-authorization-server`, proxying the issuer's document, for older MCP clients that ask the resource server for it. Off by default. |
| `leewaySeconds` | Clock skew allowed on `exp` and `nbf`. Default 60. |

A token is accepted only when it is a Pontive access token (`typ: at+jwt`)
signed by one of the issuers' keys, its `iss` is one of the issuers, its `aud`
contains `resource`, and it has not expired. An ID token is never accepted.

## Serve it [#serve-it]

The metadata lives at `/.well-known/oauth-protected-resource` plus the
identifier's path (`https://mcp.acme.com/.well-known/oauth-protected-resource/mcp`),
and at the bare path too. Both answer CORS preflight, so a browser-based MCP
client can read them. `rs.metadataUrl` is the URL every challenge names.

### Express, with the MCP SDK [#express-with-the-mcp-sdk]

```ts
import express from "express";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { requireBearer, wellKnown } from "@pontive/pontkit-server/resource-server/express";
import { principalOf } from "@pontive/pontkit-server/resource-server/mcp";
import { rs } from "./pontive";

const app = express();
app.use(express.json());
app.use(wellKnown(rs)); // the metadata routes

app.post("/mcp", requireBearer(rs, { scopes: ["files:read"] }), async (req, res) => {
  const server = new McpServer({ name: "acme-files", version: "1.0.0" });
  server.registerTool("list_files", { description: "List your files" }, async (extra) => {
    const caller = principalOf(extra.authInfo)!; // usr_…, svc_… or agt_…
    return { content: [{ type: "text", text: `files of ${caller.sub}` }] };
  });

  const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
  await server.connect(transport);
  await transport.handleRequest(req, res, req.body);
});
```

`requireBearer` sets `req.principal`, and `req.auth`, the SDK's `AuthInfo` with
the principal in `extra.principal`, which the transport passes to every tool as
`extra.authInfo`.

If you already use the SDK's own `requireBearerAuth`, give it Pontive's
verifier instead (the SDK then writes the challenges):

```ts
import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";
import { bearerAuthOptions } from "@pontive/pontkit-server/resource-server/mcp";

app.post("/mcp", requireBearerAuth(bearerAuthOptions(rs, { scopes: ["files:read"] })), handler);
```

`@pontive/pontkit-server/resource-server/mcp` is the only entry that imports
`@modelcontextprotocol/sdk`, an optional peer dependency.

### Next.js route handlers [#nextjs-route-handlers]

```ts
// app/.well-known/oauth-protected-resource/mcp/route.ts
import { rs } from "@/pontive";

export const { GET, OPTIONS } = rs.metadataRoute;
```

```ts
// app/mcp/route.ts
import { rs } from "@/pontive";

const guard = rs.requireBearer({ scopes: ["files:read"] });

export async function POST(request: Request) {
  const caller = await guard(request);
  if (caller instanceof Response) return caller; // the 401 or 403

  // ... hand the request to your MCP transport, e.g.
  // transport.handleRequest(request, { authInfo: authInfo(rs, caller) })
}
```

### Hono, Workers, Bun, Deno [#hono-workers-bun-deno]

Anything that speaks Web `Request`/`Response`:

```ts
app.use("*", async (c, next) => (await rs.handleWellKnown(c.req.raw)) ?? next());

app.post("/mcp", async (c) => {
  const caller = await rs.requireBearer({ scopes: ["files:read"] })(c.req.raw);
  if (caller instanceof Response) return caller;
  // ...
});
```

`rs.verify(request, { scopes })` is the same check, throwing a `BearerError`
(`status`, `wwwAuthenticate`, `toResponse()`) instead of returning a response.

## What the client sees [#what-the-client-sees]

| Request | Answer |
| --- | --- |
| No token | `401`, `WWW-Authenticate: Bearer resource_metadata="<metadata URL>"`, plus `scope="<route scopes>"` when the route declares any |
| A token that fails (expired, another audience or issuer, an ID token, a bad signature) | the same `401`, plus `error="invalid_token"` |
| A valid token without a scope the route needs | `403`, `WWW-Authenticate: Bearer error="insufficient_scope", scope="<every scope the route needs>", resource_metadata="<metadata URL>"` |
| A `tools/call` for a tool whose scopes the token holds none of | `403`, `WWW-Authenticate: Bearer error="insufficient_scope", scope="<every scope listing the tool>", resource_metadata="<metadata URL>"`; any one of them would do |
| A `tools/call` for a tool no scope lists (`unlistedTools: "deny"`) | `403`, `WWW-Authenticate: Bearer resource_metadata="<metadata URL>"`: no scope could allow it, so the client is not asked to step up |

The MCP SDK's client answers a `403` with `error="insufficient_scope"` by
authorizing again for the scopes the challenge names (step-up), then retrying.

## Per-tool scopes [#per-tool-scopes]

Tool import (dashboard, *APIs → Scopes → Import MCP tools*) turns your
server's `tools/list` result into scopes: one `tool:<name>` scope per tool, or
groups you name (`files:write` for `write_file` and `move_file`), each listing
the tools it allows. A tool may sit in more than one scope; a token holding
**any** scope that lists a tool may call it.

**Where the map comes from.** Give the resource server the scopes with their
tools, as the dashboard shows them or `GET /v1/apis/{api_id}` returns
them, so the check needs no credential and no network call:

```ts
export const rs = createResourceServer({
  issuer: process.env.PONTIVE_ISSUER!,
  resource: "https://mcp.acme.com/mcp",
  scopes: [
    { key: "files:write", description: "Change your files", tools: [{ name: "write_file" }, { name: "move_file" }] },
    { key: "tool:list_files", description: "List your files", tools: [{ name: "list_files" }] },
  ],
});
```

With [`metadata.fetch`](#metadata-kept-in-the-dashboard) and no tools in
`scopes`, the map is read from the API in Pontive instead
(`GET /v1/apis/{api_id}`, the same credential, `sys:api:read`) on the
first tool call, and cached for five minutes like the metadata. A failed
refresh keeps the last map.

**Refuse at the HTTP layer,** before the MCP transport sees the call, so the
refusal is the `403` a client steps up from. A tool handler can only answer
inside a `200`. In Express, after `express.json()` and `requireBearer` (or the
SDK's `requireBearerAuth` with `bearerAuthOptions`):

```ts
import { requireBearer, requireToolScopes } from "@pontive/pontkit-server/resource-server/express";

app.post("/mcp", requireBearer(rs), requireToolScopes(rs), handler);
```

Anywhere else, check the parsed body yourself and hand the same body to the
transport:

```ts
const caller = await rs.requireBearer()(request);
if (caller instanceof Response) return caller;
const body = await request.json();
try {
  await rs.authorizeToolCalls(caller, body); // every tools/call in the message or batch
} catch (err) {
  if (err instanceof BearerError) return err.toResponse();
  throw err;
}
return transport.handleRequest(request, { authInfo: authInfo(rs, caller), parsedBody: body });
```

**Hold every handler to it too** with `withToolScopes`: every tool registered
on the server afterwards (`registerTool`, `tool`, and a later
`update({ callback })`) runs only for a principal holding one of its scopes,
and answers a tool error naming them otherwise. It is what holds when the
HTTP check is missed:

```ts
import { withToolScopes } from "@pontive/pontkit-server/resource-server/mcp";

const server = withToolScopes(new McpServer({ name: "acme-files", version: "1.0.0" }), rs);
server.registerTool("write_file", { description: "Write a file" }, handler);
```

| Call | |
| --- | --- |
| `rs.scopesForTool(name)` | The scopes listing the tool; empty when none does |
| `rs.authorizeTool(principal, name)` | Throws the `403` `BearerError` unless the principal holds one of them |
| `rs.authorizeToolCalls(principal, body)` | `authorizeTool` for every `tools/call` in a JSON-RPC message or batch; anything else passes |
| `rs.requireTool(name, { scopes }?)` | A guard for a Web-standard handler serving one tool: the principal, or the `401`/`403` response |

**A tool no scope lists** is refused by default, and logged once: a tool added
to the server after the last import stays uncallable until the import lists
it, rather than open to every token. `unlistedTools: "allow"` lets any valid
token call it.

## The principal [#the-principal]

```ts
type Principal = {
  sub: string;                   // usr_…, svc_… or agt_…: whom the token speaks for
  kind: "user" | "service_account" | "agent";   // from the sub's prefix
  clientId: string;
  orgId?: string;
  roles: string[];
  permissions: string[];
  scopes: string[];
  isDelegated: boolean;          // an agent acting for the user in sub
  actor?: {                      // who acts for the subject (the act claim)
    sub: string;                 // agt_… (delegated) or svc_… (an API calling downstream)
    kind: "agent" | "service_account";
    agentInstance?: string;
  };
  agentInstance?: string;        // when the subject itself is an agent
  token: string;                 // the raw token
};
```

**A delegated principal is not the user.** When an agent holds a token for a
user (`isDelegated: true`, `actor.kind: "agent"`), `sub` is the user and
`kind` is `"user"`, but the caller is the agent, and its authority is the
intersection of the user's and the agent's. A handler that reads or writes
by `principal.sub` alone would act with the user's full authority. Check with
the authorization client instead, which sends the token and lets Pontive
evaluate the pair, or branch on `principal.isDelegated`:

```ts
import { createAuthorizationClient } from "@pontive/pontkit-server/authorization";

const authz = createAuthorizationClient({
  managementUrl: "https://api.us.pontive.com",
  issuer: "https://acme.auth.us.pontive.app",
  credential: { clientId: process.env.PONTIVE_CLIENT_ID!, clientSecret: process.env.PONTIVE_CLIENT_SECRET! },
});

await authz.check(principal, "doc:write", { type: "doc", id: "doc_1" }, { scopes: ["files:write"] });
await authz.checkBatch(principal, docs.map((d) => ({ permission: "doc:read", resource: { type: "doc", id: d.id } })));
await authz.listAccessible(principal, { resourceType: "doc", permission: "doc:read" });
```

The credential must hold `sys:authz:check`. A token whose actor is neither an
agent nor a service account is refused as `invalid_token`. A `svc_` actor is a
registered API's backend calling downstream for the user: only the user is
evaluated, so it is not delegated.

**Scopes are consent, not permission.** A scope says the user let this client
do something on their behalf; whether the user may do it at all is your check,
on `roles` and `permissions` (or Pontive's authorization check). Refuse a write
the user holds no permission for, whatever scopes the token carries.

## Metadata kept in the dashboard [#metadata-kept-in-the-dashboard]

By default the metadata is built from your configuration and needs no
credential. To serve the scopes and display fields kept in the dashboard
instead, fetch it from Pontive; it is cached for five minutes:

```ts
createResourceServer({
  issuer: process.env.PONTIVE_ISSUER!,
  resource: "https://mcp.acme.com/mcp",
  metadata: {
    fetch: {
      apiId: "api_…",
      managementUrl: "https://api.us.pontive.com",   // your region's management API
      // The API's backend service account. A token, or a function returning one, works too.
      credential: { clientId: process.env.PONTIVE_SA_ID!, clientSecret: process.env.PONTIVE_SA_SECRET! },
    },
  },
});
```
