Buun Group Developers
Pages

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). Your server checks that token like any other access token, learns who the person is, and answers.

Markdown

TL;DR

StepWhat your server does
1. Take the tokenAuthorization: Bearer <jwt> on the MCP endpoint you already have, such as /mcp-oauth
2. Check itES256 signature from the issuer's JWKS, typ: at+jwt, iss is the issuer, aud is exactly your endpoint, not expired
3. Know who it issub is the Buun account id. Read the address once from /oauth/userinfo to link an existing account
4. Answer 401 when it failsWith WWW-Authenticate: Bearer error="invalid_token". The gateway trades once more, then stops
5. Keep your own sign-inA token your own server issued still works. Tell the two apart by iss
6. Ask for the switchA 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:

PartValue
Header algES256
Header typat+jwt
Header kidWhich key of the issuer's JWKS signed it
issThe issuer of your environment, below
audYour MCP endpoint, exactly as staff registered it, path included
subThe person's Buun account id, usr_...
client_idThe gateway's exchange client
act{ "sub": "<the gateway's exchange client>" }: the gateway is acting for the person
scopeSome of openid profile email orgs, space separated
iat, expSeconds. It lasts 15 minutes at most, and never longer than the agent's own token
jtiA 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

Environmentiss and where the keys areYour aud
Local developmenthttp://localhost:28500, keys at http://localhost:28500/.well-known/jwks.jsonhttp://localhost:<your MCP port>/mcp-oauth: Plotwork 3102, Flung 3020
Previewhttps://id-preview.buungroup.com, keys at /.well-known/jwks.jsonYour preview MCP endpoint, such as https://mcp-preview.plotwork.dev/mcp-oauth
Productionhttps://id.buungroup.com, keys at /.well-known/jwks.jsonYour 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:

CheckWhy
Signature with a key from the issuer's JWKS, alg ES256 onlyAnything else could be made by anyone
typ is at+jwtAn ID token is not an access token, even from the same issuer
iss is your environment's issuer, exactlyA preview token never works in production
aud is your MCP endpoint, exactlyA 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 toleranceTokens 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:

RequestAnswer
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:

WhoWhat
A staff member with manage rightsStaff console, Clients, Resource servers: add your MCP endpoint, exactly, with your product chosen (Staff console)
Whoever changes the gatewayIn src/upstreams/catalogue.ts of buun-group/buungroup-gateway, add acceptsIdentityTokens: true to your product in that environment's list, in a reviewed change
NobodyNo 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; 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.