# Accepting Buun Identity tokens

What a Buun product's MCP server (Plotwork, Flung, and the next one) adds so the Buun MCP gateway can call it for
anyone on its plan, with no second sign-in. The gateway trades the agent's token at Buun Identity for a token meant
for your server (RFC 8693, see [Token exchange](https://developers.buungroup.com/mcp/token-exchange)). Your server checks that token
like any other access token, learns who the person is, and answers.

## TL;DR

| Step | What your server does |
|---|---|
| 1. Take the token | `Authorization: Bearer <jwt>` on the MCP endpoint you already have, such as `/mcp-oauth` |
| 2. Check it | ES256 signature from the issuer's JWKS, `typ: at+jwt`, `iss` is the issuer, `aud` is exactly your endpoint, not expired |
| 3. Know who it is | `sub` is the Buun account id. Read the address once from `/oauth/userinfo` to link an existing account |
| 4. Answer 401 when it fails | With `WWW-Authenticate: Bearer error="invalid_token"`. The gateway trades once more, then stops |
| 5. Keep your own sign-in | A token your own server issued still works. Tell the two apart by `iss` |
| 6. Ask for the switch | A gateway change marks your product `acceptsIdentityTokens`, and staff add your MCP server in the console |

## What arrives

Every MCP request from the gateway carries one bearer token. It is a JWT signed by Buun Identity:

| Part | Value |
|---|---|
| Header `alg` | `ES256` |
| Header `typ` | `at+jwt` |
| Header `kid` | Which key of the issuer's JWKS signed it |
| `iss` | The issuer of your environment, below |
| `aud` | Your MCP endpoint, exactly as staff registered it, path included |
| `sub` | The person's Buun account id, `usr_...` |
| `client_id` | The gateway's exchange client |
| `act` | `{ "sub": "<the gateway's exchange client>" }`: the gateway is acting for the person |
| `scope` | Some of `openid profile email orgs`, space separated |
| `iat`, `exp` | Seconds. It lasts 15 minutes at most, and never longer than the agent's own token |
| `jti` | A random id, unique per token |

There is no refresh token. When one ends, the gateway trades again.

The gateway trades only for a person who is not suspended, whose agent is still allowed in the account portal, and who
holds an active plan for your product right now. Your server does not check the plan for this; it was checked a
moment ago and the token is short. Never read a plan from the token: it holds none.

## The environments

| Environment | `iss` and where the keys are | Your `aud` |
|---|---|---|
| Local development | `http://localhost:28500`, keys at `http://localhost:28500/.well-known/jwks.json` | `http://localhost:<your MCP port>/mcp-oauth`: Plotwork `3102`, Flung `3020` |
| Preview | `https://id-preview.buungroup.com`, keys at `/.well-known/jwks.json` | Your preview MCP endpoint, such as `https://mcp-preview.plotwork.dev/mcp-oauth` |
| Production | `https://id.buungroup.com`, keys at `/.well-known/jwks.json` | Your production MCP endpoint, such as `https://mcp.plotwork.dev/mcp-oauth` |

Put the issuer and your own endpoint in `wrangler.jsonc` vars, one pair per environment. Never take either from the
token or the request.

## Checking a token

Any JOSE library that verifies ES256 against a remote JWKS does it. With `jose`, which runs on Workers:

```ts
import { createRemoteJWKSet, jwtVerify } from 'jose'

// One key set per isolate. jose keeps the keys and reads them again when it meets a `kid` it does not know, so a
// key rotation at the issuer needs nothing from you.
let keys: ReturnType<typeof createRemoteJWKSet> | undefined

/** The Buun account id a token proves, or null. `issuer` and `audience` come from your own settings. */
export async function buunSubject(token: string, issuer: string, audience: string): Promise<string | null> {
  keys ??= createRemoteJWKSet(new URL('/.well-known/jwks.json', issuer), { timeoutDuration: 5000 })
  try {
    const { payload } = await jwtVerify(token, keys, { issuer, audience, typ: 'at+jwt', algorithms: ['ES256'], clockTolerance: 30 })
    return typeof payload.sub === 'string' ? payload.sub : null
  } catch {
    return null
  }
}
```

Check all of these, and refuse on any one:

| Check | Why |
|---|---|
| Signature with a key from the issuer's JWKS, `alg` ES256 only | Anything else could be made by anyone |
| `typ` is `at+jwt` | An ID token is not an access token, even from the same issuer |
| `iss` is your environment's issuer, exactly | A preview token never works in production |
| `aud` is your MCP endpoint, exactly | A token for the gateway, or for another product, must not work here. This is what keeps one product's token from opening another |
| `exp` has not passed, with at most 30 seconds of tolerance | Tokens are short on purpose |

Never pass the token on to another service, and never write it to a log.

## Knowing who it is

`sub` is the person. Keep it on your own user as the Buun account id and find them by it from then on.

The first time you see a `sub`, read the person's address with the same token:

| Request | Answer |
|---|---|
| `GET <issuer>/oauth/userinfo` with `Authorization: Bearer <the token>` | `{ "sub": "usr_...", "email": "ada@example.com", "email_verified": true, "name": "Ada" }` |

Then, in this order:

1. A user of yours already has this `sub`: that is them.
2. A user of yours has this address, it was verified on your side, and `email_verified` is true: link the `sub` to
   them.
3. Neither: make a new user with the `sub` and the address, as your own sign-up would.

Never link by an address that is not verified on both sides. Someone could sign up at Buun with another person's
address before verifying it, and linking would hand them that person's account.

## Answering a failed token

Answer `401` with:

```http
WWW-Authenticate: Bearer error="invalid_token", resource_metadata="<your protected resource metadata address>"
```

The gateway reads a 401 as "trade again". It trades once more, calls you once more, and if that fails too it tells
the agent the product is not on the account's plan. A 403 or 500 is shown to the agent as a failure of your product,
so keep 401 for a token that does not pass.

## Keeping your own sign-in

Your MCP server keeps taking the tokens it issues itself, for agents that connect to it directly. Tell the two apart
by the token's `iss` before checking it, without trusting anything else in it yet:

```ts
const unverified = JSON.parse(atob(token.split('.')[1]?.replace(/-/g, '+').replace(/_/g, '/') ?? '')) as { iss?: unknown }
const person = unverified.iss === env.BUUN_ISSUER ? await buunSubject(token, env.BUUN_ISSUER, env.MCP_RESOURCE) : await yourOwnCheck(token)
```

The `iss` only picks which check runs; the check itself still verifies everything. A token that is not a JWT at all
goes to your own check.

## Turning it on

Once your server ships the above in an environment:

| Who | What |
|---|---|
| A staff member with manage rights | Staff console, Clients, Resource servers: add your MCP endpoint, exactly, with your product chosen ([Staff console](https://developers.buungroup.com/staff-console)) |
| Whoever changes the gateway | In `src/upstreams/catalogue.ts` of `buun-group/buungroup-gateway`, add `acceptsIdentityTokens: true` to your product in that environment's list, in a reviewed change |
| Nobody | No secret is shared with your product. It only reads public keys |

From then on, anyone on your plan sees your tools in their agent through the gateway, once staff approve each tool
under Gateway tools in the console.

## Testing it on one machine

The full steps are on [Local development](https://developers.buungroup.com/local-development); in short:

The gateway's half is already switched on in local development: its local list marks Plotwork and Flung as taking
Buun Identity tokens, at the ports above.

1. In this repository: `pnpm dev:identity`, then `pnpm dev:exchange`. That registers the gateway's exchange client,
   adds `http://localhost:28502` as the gateway agents sign in for, adds both products' local MCP servers, and writes
   the exchange client's id and secret into the gateway's `.dev.vars`. Stop the issuer again, or leave it running.
2. `pnpm dev` here: the issuer, portal, gateway and staff console.
3. In the staff console at `http://localhost:28503`, open yourself under People and give yourself a Plotwork or Flung
   plan.
4. In the product's repository, run its MCP server with its issuer set to `http://localhost:28500` and its resource to
   its own local endpoint.
5. Point an agent at `http://localhost:28502/mcp`. For Claude Code:
   `claude mcp add --transport http buun-local http://localhost:28502/mcp`, then sign in when it asks.
6. List the tools. A product's tools show once staff approve them under Gateway tools in the console, as they do in
   production. Call one.

If no tools show, the gateway's log says why: `gateway.exchange_refused` with the status Buun Identity answered, and
the issuer's log says which check failed as `oauth.exchange_refused` with a `reason` of `client`, `subject`,
`account`, `grant` or `plan`.

Source: https://developers.buungroup.com/mcp/accepting-tokens
