# Build on Buun Identity One Buun Group account for every product, and one MCP endpoint in front of all of them. These pages say how a product signs people in with Buun Identity, reads what they pay for, and takes the tokens the Buun MCP gateway sends, so an agent reaches the product with no second sign-in. ## Who this is for | You are | Start with | |---|---| | Building a new Buun Group product | [Quick start](https://developers.buungroup.com/quick-start), then [Building a product, for agents](https://developers.buungroup.com/agents/building-a-product) | | Adding "Sign in with Buun" to a product's website | [The sign-in flow](https://developers.buungroup.com/sign-in/flow) | | Making a product's MCP server reachable through `mcp.buungroup.com` | [Accepting Buun Identity tokens](https://developers.buungroup.com/mcp/accepting-tokens) | | Testing several products together on one machine | [Local development](https://developers.buungroup.com/local-development) | | An agent reading these pages | [llms.txt](https://developers.buungroup.com/llms.txt) lists every page as Markdown; [llms-full.txt](https://developers.buungroup.com/llms-full.txt) is all of them in one file | ## The parts | Part | Address | What it does | |---|---|---| | Buun Identity | `id.buungroup.com` | The OpenID Connect issuer. The only thing that signs a token or keeps a credential | | Account portal | `account.buungroup.com` | Where a person signs in, approves a product, and sees their products and plans | | MCP gateway | `mcp.buungroup.com` | One MCP endpoint in front of every product. An agent connects once | | Staff console | `staff.buungroup.com` | Where staff manage people, plans, clients, resource servers and gateway tools | | A product | Its own domain | Plotwork, Flung, GunSpec, Destroy Network, CryptFlare, and the next one | ![How Buun Identity, the gateway and the products talk to each other](https://developers.buungroup.com/diagrams/buun-group-today-who-talks-to-whom.svg "themed") ## Three rules that hold everywhere 1. **A token has one audience.** A product accepts only a token whose `aud` is its own address. A token for the gateway does not open Plotwork, and one for Plotwork does not open Flung. 2. **A token never travels on.** Nothing forwards the token it was sent. The gateway trades it at Buun Identity for one meant for the product, or uses the person's own connection to the product. 3. **A plan is never in a token.** A product asks Buun Identity what the person pays for each time it matters, so a cancelled plan is gone at once. Source: https://developers.buungroup.com/ --- # Quick start What a new Buun Group product does to sign people in with Buun Identity and to be reachable through the MCP gateway, in the order it does it. ## The checklist | Step | What | Page | |---|---|---| | 1 | Add the product to `PRODUCTS` in `@buun-group/core`, with its id, name and home page | [Building a product](https://developers.buungroup.com/agents/building-a-product) | | 2 | Register the product's own client in the staff console: a Buun Group product, its redirect addresses, its scopes | [Clients](https://developers.buungroup.com/sign-in/clients) | | 3 | Send people to `/oauth/authorize` with PKCE, trade the code at `/oauth/token`, and check the tokens | [The sign-in flow](https://developers.buungroup.com/sign-in/flow) | | 4 | Read the person's plan from `/oauth/plans` whenever it matters | [Plans](https://developers.buungroup.com/sign-in/plans) | | 5 | Make the product's MCP server accept Buun Identity tokens whose `aud` is its own MCP address | [Accepting Buun Identity tokens](https://developers.buungroup.com/mcp/accepting-tokens) | | 6 | Add the product to the gateway's catalogue, marked `acceptsIdentityTokens`, and its MCP server as a resource server | [How the gateway works](https://developers.buungroup.com/mcp/how-it-works) | | 7 | Approve the product's tools in the staff console | [Tool review](https://developers.buungroup.com/mcp/tool-review) | | 8 | Test the whole path on one machine | [Local development](https://developers.buungroup.com/local-development) | ## The smallest working sign-in ```ts const base64url = (bytes: Uint8Array): string => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') // 1. Send the browser to Buun Identity. const verifier = base64url(crypto.getRandomValues(new Uint8Array(32))) const challenge = base64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)))) const state = base64url(crypto.getRandomValues(new Uint8Array(16))) const authorize = new URL('https://id.buungroup.com/oauth/authorize') authorize.search = new URLSearchParams({ response_type: 'code', client_id: 'cli_your_product', redirect_uri: 'https://app.your-product.dev/auth/callback', scope: 'openid profile email offline_access', state, code_challenge: challenge, code_challenge_method: 'S256', }).toString() // 2. On the way back, check `state` and `iss`, then trade the code. const tokens = await fetch('https://id.buungroup.com/oauth/token', { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'authorization_code', client_id: 'cli_your_product', code, redirect_uri: 'https://app.your-product.dev/auth/callback', code_verifier: verifier }), }).then((response) => response.json()) ``` Keep the verifier and the state in a cookie of your own, for one sign-in, and refuse a return whose `state` does not match. Source: https://developers.buungroup.com/quick-start --- # Architecture What runs where, what each part may do, and which repository holds it. ## The picture ![Buun Identity, the account portal, the gateway, the staff console and the products](https://developers.buungroup.com/diagrams/buun-identity-and-the-products-around-it.svg "themed") ## The parts | Part | Host | Repository | Runs on | |---|---|---|---| | Identity Worker, the issuer | `id.buungroup.com` | `buun-group/buungroup-app`, `apps/identity` | Cloudflare Workers and D1 | | Account portal | `account.buungroup.com` | `buun-group/buungroup-app`, `apps/account` | A static page on Workers | | Developer docs, this site | `developers.buungroup.com` | `buun-group/buungroup-app`, `apps/developers` | A static site on Workers | | MCP gateway | `mcp.buungroup.com` | `buun-group/buungroup-gateway` | Cloudflare Workers and D1 | | Staff console | `staff.buungroup.com` | `buun-group/buungroup-staff` | Cloudflare Workers and D1 | Shared code is published privately on GitHub Packages under `@buun-group`: `core` (products, scopes, roles, the client schema), `crypto` (Web Crypto helpers) and `ui` (the design system). A product installs them at a pinned version. ## Who may do what | Part | May | Never | |---|---|---| | Identity Worker | Sign tokens, keep accounts, sessions, grants and hashed secrets | Show a page: the portal does that | | Account portal | Call the issuer with the person's session | Hold a token for a product | | Gateway | Check an agent's token, trade it for a product's, call the product | Pass the agent's token on, or log one | | Staff console | Read and change through the issuer's `/admin` and the gateway's `/admin`, naming the member of staff | Reach a customer session or cookie | | A product | Check tokens with the published keys, ask for the person's plan | Accept a token whose `aud` is not its own | ## Why it is built this way | Decision | Why | |---|---| | ES256 access tokens with one audience, 15 minutes | A product checks a token without calling the issuer, and a token for one service opens nothing else | | PKCE S256 for every client | A stolen code is useless without the verifier | | Plans read live from `/oauth/plans` | A cancelled plan stops at once | | Token exchange at the gateway (RFC 8693) | A person on a plan reaches the product through the gateway without a second sign-in, and the agent's token stays with the gateway | | Tools reviewed by staff before an agent sees them | A product's tool description is text an agent obeys; a change waits for review again | Source: https://developers.buungroup.com/architecture --- # The sign-in flow Sign in with Buun is OAuth 2.1 with OpenID Connect: an authorization code with PKCE S256, traded at the token endpoint for an access token, an ID token and, when asked for, a refresh token. ## The steps 1. Send the browser to `GET /oauth/authorize` with the parameters below. 2. Buun Identity signs the person in at the account portal, by an emailed code and their second step when they have one. A Buun Group product's own client skips the consent page; another company's client shows it. 3. The browser comes back to your `redirect_uri` with `code`, `state` and `iss`. Check `state` is yours and `iss` is the issuer. 4. Post the code to `POST /oauth/token` with the PKCE verifier. 5. Check the access token and the ID token, then find or make your own user by `sub`. ## Authorize parameters | Parameter | Required | Value | |---|---|---| | `response_type` | Yes | `code`. Nothing else is supported | | `client_id` | Yes | Your client's id, `cli_...` | | `redirect_uri` | Yes | One of your registered addresses, exactly. Checked before anything else | | `scope` | Yes | Space separated, from `openid profile email orgs offline_access`, within what your client may ask for | | `state` | Recommended | A random value you check on return | | `code_challenge` | Yes | The SHA-256 of your verifier, base64url, no padding | | `code_challenge_method` | Yes | `S256` | | `nonce` | No | Repeated in the ID token | | `resource` | No | The API the access token is for (RFC 8707). Must be in your client's `resources`. Without it, the token's audience is your client | | `prompt` | No | `none` never shows a page and answers `login_required` or `consent_required`. `login` and `consent` always show the portal | A client or redirect address that cannot be trusted gets a page at Buun Identity, never a redirect. Every other mistake goes back to your `redirect_uri` as `error` and `error_description`. ## The token request ```http POST /oauth/token Content-Type: application/x-www-form-urlencoded grant_type=authorization_code&client_id=cli_your_product&code=buun_ac_...&redirect_uri=https%3A%2F%2Fapp.your-product.dev%2Fauth%2Fcallback&code_verifier=... ``` A confidential client also proves itself, with HTTP Basic (`client_secret_basic`) or `client_secret` in the body (`client_secret_post`). A public client sends no secret: PKCE is its proof. ```json { "access_token": "eyJ...", "token_type": "Bearer", "expires_in": 900, "id_token": "eyJ...", "refresh_token": "buun_rt_...", "scope": "openid profile email offline_access" } ``` ## Refreshing `grant_type=refresh_token&refresh_token=buun_rt_...&client_id=...` answers new tokens and a new refresh token. The old one is spent: use it again and the whole family ends, because a refresh token used twice was stolen. A refresh token lasts 30 days. ## Signing out `POST /oauth/revoke` with `token=buun_rt_...` ends the refresh token and its family. It always answers 200 for a known client (RFC 7009). ## Linking a person to your own user 1. A user of yours already has this `sub`: that is them. 2. A user of yours has the same address, verified on your side, and the ID token says `email_verified: true`: link them. 3. Neither: make a new user. Never link by an address that is not verified on both sides. Source: https://developers.buungroup.com/sign-in/flow --- # Tokens and keys Every access token and ID token is a JWT signed with ES256 by Buun Identity. A product checks one with the published keys, without calling the issuer. ## What each token is | Token | Form | Lifetime | Kept by Buun Identity | |---|---|---|---| | Access token | ES256 JWT, header `typ: at+jwt`, one `aud` | 15 minutes | No | | ID token | ES256 JWT, header `typ: JWT`, `aud` is your client | 5 minutes | No | | Refresh token | Opaque, `buun_rt_` prefix | 30 days, a new one on every use | Its SHA-256 only | | Authorization code | Opaque, `buun_ac_` prefix | 60 seconds, used once | Its SHA-256 only | ## Checking an access token ```ts import { createRemoteJWKSet, jwtVerify } from 'jose' const issuer = 'https://id.buungroup.com' const keys = createRemoteJWKSet(new URL('/.well-known/jwks.json', issuer), { timeoutDuration: 5000 }) export async function verify(token: string, audience: string) { const { payload } = await jwtVerify(token, keys, { issuer, audience, typ: 'at+jwt', algorithms: ['ES256'], clockTolerance: 30 }) return payload } ``` | Check | Why | |---|---| | Signature by a key in the JWKS, ES256 only | Anything else could be made by anyone | | `typ` is `at+jwt` | An ID token is never an access token | | `iss` is the issuer of your environment | A preview token never works in production | | `aud` is your own address, exactly | A token for another service opens nothing here | | `exp` has not passed | Tokens are short on purpose | ## Keys and rotation The keys are at `/.well-known/jwks.json`, cached for a while by the issuer's headers. When the issuer rotates, the old key stays published until every token it signed has ended. `jose` reads the set again when it meets a `kid` it does not know, so a rotation needs nothing from you. ## What a token never holds A plan, a price, or anything about what the person pays. Ask [`/oauth/plans`](https://developers.buungroup.com/sign-in/plans) instead. Source: https://developers.buungroup.com/sign-in/tokens --- # Plans What a person pays for lives at Buun Identity, product by product. A product asks for it each time it matters, with the access token it already holds. ![How a plan set in the staff console reaches a product](https://developers.buungroup.com/diagrams/a-plan-from-the-console-to-the-product.svg "themed") ## Reading a plan ```http GET /oauth/plans Authorization: Bearer ``` ```json { "sub": "usr_...", "plans": [{ "product": "plotwork", "plan": "pro", "endsAt": null }] } ``` | Field | Meaning | |---|---| | `product` | A product id from `@buun-group/core`: `plotwork`, `flung`, `gunspec`, `destroy`, `cryptflare` | | `plan` | The plan's name, lower case, such as `pro` | | `endsAt` | When it ends, in milliseconds since the epoch, or null for no end | The address is also in the issuer's metadata as `buun_plans_endpoint`. ## Who is told what | Calling client | Told | |---|---| | A Buun Group product's own client | That product's plan, and no other | | Another company's client | None | Only a plan that is active and has not ended is listed. It is read at the moment of asking, so a plan staff cancel is gone at the next request. Never keep a plan in a token or a long cache. ## Setting a plan Until billing is built, staff set a plan by hand in the staff console: People, the person, Plans. The gateway's [token exchange](https://developers.buungroup.com/mcp/token-exchange) checks the same plan before it lets an agent reach a product. Source: https://developers.buungroup.com/sign-in/plans --- # Clients A client is anything that signs people in with Buun Identity: a product's website, the gateway, another company's app, or an agent. Staff register one in the staff console; an agent registers itself with a metadata document. ## Kinds of client | Kind | Consent page | Example | Registered by | |---|---|---|---| | A Buun Group product | Skipped | Plotwork's website | Staff, with the product chosen | | A Buun Group service | Skipped | The MCP gateway | Staff | | Another company | Shown | A partner's app | Staff | | An agent with a client ID metadata document | Shown | Claude Code, an editor | Itself: its `client_id` is an https address whose document says what it is | A person who arrives already signed in still presses Continue, so a link cannot sign them in silently. ## Fields | Field | Meaning | |---|---| | Name | 3 to 60 letters, digits, spaces, `-` and `_`. People see it on the consent page | | Whose it is | A Buun Group product, a Buun Group service, or another company | | Product | For a product's client: which product, from `@buun-group/core` `PRODUCTS` | | Redirect addresses | One to ten, matched exactly. `https`, or `http` on `localhost`, `127.0.0.1` or `[::1]`. No fragment | | Resource servers | Up to ten APIs it may ask a token for with `resource` | | Scopes | What it may ask for. `openid` is always needed | | Keeps a secret | On for a client with a server. Its secret is shown once and kept as a SHA-256 only | | Trades tokens for | For a confidential service only: the resource server it is, which lets it [trade tokens](https://developers.buungroup.com/mcp/token-exchange) | ## Registering one In the staff console, open Clients and fill in Register a client. The client id is shown at once, and for a client that keeps a secret, the secret, once. ![The Clients page of the staff console, with the register form](https://developers.buungroup.com/shots/staff-clients.png "themed") ## Resource servers A resource server is an API a token may name as its audience. The gateway is one, open to agents that register with a document. A product's MCP server is one with its product set, which the gateway may trade a token for. Staff add them on the same page. ![Resource servers in the staff console: the gateway and each product's MCP server](https://developers.buungroup.com/shots/staff-resource-servers.png "themed") Source: https://developers.buungroup.com/sign-in/clients --- # How the gateway works The Buun MCP gateway is one MCP endpoint, `https://mcp.buungroup.com/mcp`, in front of every Buun Group product. A person connects an agent to it once and reaches the tools of every product they use. ## What an agent sees | Tool | What it does | |---|---| | `buun_whoami` | Who the agent is signed in as | | `buun_products` | Every product the gateway offers, and whether this person can reach it | | `buun_connect` | A link that connects a product the old way, with the product's own sign-in, for ten minutes and once | | `buun_disconnect` | Disconnects a product | | `__` | Each product's own tools, approved by staff, such as `plotwork__draw_diagram` | ## Connecting an AI tool People connect from the account portal, under Connected products: one address, `https://mcp.buungroup.com/mcp`, and the steps for each tool, with its own command, config file or one-click install. Staff see the same panel on the console's Gateway page. Every tool signs in with Buun Group by OAuth the first time, so nobody pastes a key. | Tool | How | |---|---| | Claude Code | `claude mcp add --transport http buun-group https://mcp.buungroup.com/mcp`, then `/mcp` to sign in | | Claude | Settings, Connectors, Add custom connector, and paste the address | | ChatGPT | Settings, Apps & Connectors, Advanced settings, Developer mode; then Create, and paste the address | | Codex | `codex mcp add buun-group --url https://mcp.buungroup.com/mcp`, then `codex mcp login buun-group` | | Cursor | The one-click install link, or `~/.cursor/mcp.json` | | VS Code | The one-click install link, or `code --add-mcp` | | Windsurf | `~/.codeium/windsurf/mcp_config.json` with `serverUrl` | | Gemini CLI | `gemini mcp add --transport http buun-group https://mcp.buungroup.com/mcp`, then `/mcp auth buun-group` | | Zed | `context_servers` in its settings | | Roo Code, Kilo Code | `.roo/mcp.json` or `.kilocode/mcp.json`, type `streamable-http` | | Kiro, LM Studio | Their `mcp.json` with the address | | Amp | `amp mcp add buun-group https://mcp.buungroup.com/mcp` | | OpenCode | `opencode.json`, type `remote`, then `opencode mcp auth buun-group` | | Goose | `goose configure`, Add Extension, Remote Extension (Streamable HTTP) | | JetBrains AI, Le Chat, Cline, and any other MCP client | Their MCP or connector settings, and paste the address | ![Connecting an AI tool from the account portal: every tool with its steps](https://developers.buungroup.com/shots/portal-agents.png "themed") The list lives in `AGENT_CLIENTS` of `@buun-group/ui`, and the panel is its `AgentConnect` component. ## Signing in to the gateway The gateway is a resource server of Buun Identity (RFC 9728). Its metadata is at `/.well-known/oauth-protected-resource` and names Buun Identity as the authorization server. An agent such as Claude Code registers itself with a client ID metadata document, signs the person in, and sends the access token whose `aud` is the gateway on every MCP request. ## Reaching a product There are two ways, chosen per product in the gateway's catalogue: | Way | When | The person does | |---|---|---| | Token exchange | The product accepts Buun Identity tokens (`acceptsIdentityTokens`) | Nothing. Anyone on the product's plan sees its tools | | The product's own sign-in | Any other product | Calls `buun_connect` once and signs in to the product. The gateway keeps the product's tokens sealed for them | ![Connecting a product automatically once it trusts Buun Identity](https://developers.buungroup.com/diagrams/connecting-a-product-automatically-once-products-trust-buun-identity.svg "themed") Token exchange is the way every new product should take: see [Accepting Buun Identity tokens](https://developers.buungroup.com/mcp/accepting-tokens). ## The catalogue The products the gateway reaches are a closed list in code, `src/upstreams/catalogue.ts` of `buun-group/buungroup-gateway`, one list for each of production, preview and local development: ```ts { product: 'plotwork', endpoint: 'https://mcp.plotwork.dev/mcp-oauth', authorizationServer: 'https://mcp.plotwork.dev', acceptsIdentityTokens: true } ``` | Field | Meaning | |---|---| | `product` | The product id | | `endpoint` | The product's MCP endpoint. It is also the `aud` of every token traded for it | | `authorizationServer` | The one sign-in server the gateway trusts for the product's own sign-in | | `acceptsIdentityTokens` | Set once the product checks Buun Identity tokens. The gateway then trades instead of asking the person to connect | A product is added by a reviewed change, never by a row or a request. Staff can turn a product off at the gateway from the console at any time. Source: https://developers.buungroup.com/mcp/how-it-works --- # 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 ` 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 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:/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 | 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 { 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 /oauth/userinfo` with `Authorization: Bearer ` | `{ "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="" ``` 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 --- # Token exchange How the gateway turns the agent's token into one meant for a product (RFC 8693), and every check Buun Identity makes before it does. A product never takes part in the trade; it only checks the token it is sent. ## The request Only one client may trade: the gateway's own, confidential, a Buun Group service, with `acts_for` set to the gateway's address. ```http POST /oauth/token Authorization: Basic Content-Type: application/x-www-form-urlencoded grant_type=urn:ietf:params:oauth:grant-type:token-exchange &subject_token= &subject_token_type=urn:ietf:params:oauth:token-type:access_token &resource=https://mcp.plotwork.dev/mcp-oauth ``` ```json { "access_token": "eyJ...", "issued_token_type": "urn:ietf:params:oauth:token-type:access_token", "token_type": "Bearer", "expires_in": 900, "scope": "openid profile email" } ``` ## The checks, in order | Check | Refused with | |---|---| | The client is confidential, a Buun Group service, and has `acts_for` | `unauthorized_client` | | `subject_token` is there, of type `access_token` | `invalid_request` | | `resource` is a registered resource server with a product | `invalid_target` | | The subject token is signed by Buun Identity, not expired, and its `aud` is exactly the client's `acts_for` | `invalid_grant` | | The person exists and is not suspended | `invalid_grant` | | The agent's grant is still live: the person has not disconnected it in the portal | `invalid_grant` | | The person holds an active plan for that product now | `invalid_grant` | Every `invalid_grant` has the same message. Buun Identity logs which check failed as `oauth.exchange_refused` with a `reason` of `subject`, `account`, `grant` or `plan`, and never the token. ## The token it answers | Claim | Value | |---|---| | `aud` | The product's MCP endpoint, the `resource` asked for | | `sub` | The person | | `client_id` | The gateway's exchange client | | `act` | `{ "sub": "" }` | | `scope` | The agent's scopes among `openid profile email orgs`. Never `offline_access` | | `exp` | 15 minutes, or when the agent's own token ends, whichever is first | There is no refresh token and nothing is stored. The gateway keeps a traded token in memory until a minute before it ends, keyed by a hash of the agent's token and the product, and trades again after that, or at once when the product answers 401. ## Turning it on for a product | Where | What | |---|---| | The product | Accept the token: [Accepting Buun Identity tokens](https://developers.buungroup.com/mcp/accepting-tokens) | | Buun Identity | A resource server for the product's MCP endpoint, with the product set, from the staff console | | The gateway | `acceptsIdentityTokens: true` on the product in the catalogue, and `IDENTITY_EXCHANGE_CLIENT_ID` and `IDENTITY_EXCHANGE_SECRET` set on the Worker | Without the exchange client, every product keeps its own sign-in, whatever the catalogue says. Source: https://developers.buungroup.com/mcp/token-exchange --- # Tool review A product's tool reaches an agent only once staff approve that exact version. A tool's name, title, description, input schema and annotations are words an agent reads and acts on, so a change to any of them waits for review again. ## How a tool is reviewed 1. The gateway lists the product's tools and hashes every word an agent would read of each one. 2. A version it has not seen is recorded as waiting for review. It is not listed to any agent. 3. Staff read it in the staff console, under Gateway tools, and approve or block it, with a reason. 4. An approved version is listed from the next read, named `__`. A blocked one is never listed, and a call to it is refused. 5. If the product changes a word, that is a new version and it waits again. The last approved version is not listed in its place. ![Gateway tools in the staff console: each tool version waiting, approved or blocked](https://developers.buungroup.com/shots/staff-gateway-tools.png "themed") ## What this means for a product | Do | Why | |---|---| | Keep tool descriptions stable between releases | Each change hides the tool until staff approve it again | | Tell staff before a release that changes a tool | So the review is ready when it ships | | Keep an input schema under 32 KB and annotations under 4 KB | A tool that does not fit is left out, not passed through | | Name tools with letters, digits, `_`, `.` and `-`, up to 96 | Any other name is left out | | Set `readOnlyHint` and `destructiveHint` honestly | Agents and staff both read them | ## Turning a product off Staff can turn a product off at the gateway at once, from Gateway in the console. Its tools stop being listed for everybody; nothing is disconnected, and turning it on brings them back. Source: https://developers.buungroup.com/mcp/tool-review --- # Local development How to run Buun Identity, the portal, the gateway and the staff console on one machine, and test a product through the gateway over `localhost`. ## Ports | App | Address | Repository | |---|---|---| | Identity Worker | `http://localhost:28500` | `buungroup-app` | | Account portal | `http://localhost:28501` | `buungroup-app` | | MCP gateway | `http://localhost:28502` | `buungroup-gateway` | | Staff console | `http://localhost:28503` | `buungroup-staff` | | These docs | `http://localhost:28504` | `buungroup-app` | | Status page | `http://localhost:28505` | `buungroup-app` | | Plotwork MCP server | `http://localhost:3102/mcp-oauth` | `plotwork-app`, `apps/mcp` | | Flung MCP server, and its API | `http://localhost:3020/mcp-oauth`, `http://localhost:3010` | `flung-app`, `apps/mcp` and `apps/api` | The Buun Group ports are fixed in `tools/dev-ports.json` of `buungroup-app`, all in 285xx, so every product can run at once. A port that is taken stops the app instead of moving it. ## First time ```sh git clone --recurse-submodules git@github.com:buun-group/buungroup-app.git cd buungroup-app NODE_AUTH_TOKEN=$(gh auth token) pnpm install cp apps/identity/.dev.vars.example apps/identity/.dev.vars # fill in each value as its comment says cp repositories/buungroup-gateway/.dev.vars.example repositories/buungroup-gateway/.dev.vars cp repositories/buungroup-staff/.dev.vars.example repositories/buungroup-staff/.dev.vars ``` Without a mail key, a sign-in code is written to the Worker's log as `auth.code.dev`, and a staff code as `staff.code.dev`. ## Every day | Command | What it does | |---|---| | `pnpm dev` | Frees the dev ports, then runs the issuer, portal, gateway, staff console and status page together | | `pnpm dev:core` | The issuer and the portal only | | `pnpm --filter @buun-group/developers dev` | These docs | | `pnpm check` | Type check and every test | | `pnpm kill:ports` | Stops whatever holds a dev port | | `pnpm demo` | The staff console, the portal and these docs with made-up data, no Worker or database, on ports 28591 to 28593 | | `pnpm demo:shot [path...]` | Screenshots of a demo app in both themes, such as `pnpm demo:shot staff /clients` | ## Testing a product through the gateway In local development the gateway reaches the products on the same machine, and both Plotwork and Flung are marked as accepting Buun Identity tokens. Once a product's MCP server accepts them: 1. Start the issuer: `pnpm dev:identity`. 2. Run `pnpm dev:exchange` once. Through the issuer's `/admin`, it adds `http://localhost:28502` as the gateway agents sign in for, adds both products' local MCP servers as resource servers, registers the gateway's exchange client, and writes the client's id and secret into the gateway's `.dev.vars`. The secret is never printed. Running it again replaces the client. 3. `pnpm dev` for everything else. 4. In the staff console at `http://localhost:28503`, give yourself a Plotwork or Flung plan under People. 5. Run the product's MCP server with its issuer `http://localhost:28500` and its resource its own local endpoint. 6. Connect an agent: `claude mcp add --transport http buun-local http://localhost:28502/mcp`, and sign in when it asks. 7. Approve the product's tools under Gateway tools in the console, then list and call them. | Something is wrong | Look at | |---|---| | No product tools listed | The gateway's log, `gateway.exchange_refused` with the status the issuer answered | | The issuer refused the trade | The issuer's log, `oauth.exchange_refused` and its `reason`: `client`, `subject`, `account`, `grant` or `plan` | | `plan` | Give yourself a plan for that product in the console | | `grant` | The agent was disconnected in the portal. Connect it again | | The product answers 401 | Its issuer or its own resource address is not the local one | Source: https://developers.buungroup.com/local-development --- # Staff console Where staff set up what a product needs at Buun Identity and the gateway. Every change asks for a reason and is written to the console's audit trail and to the service's own. ## What a product needs from staff | Need | Where in the console | |---|---| | The product's own client for its website | Clients, Register a client, a Buun Group product | | The product's MCP server as a resource server, with its product | Clients, Resource servers | | A plan for a person, until billing is built | People, the person, Plans | | The product's tools approved | Gateway tools | | The product on or off at the gateway | Gateway | ## Clients and resource servers ![The Clients page: every client by whose it is, and the register form](https://developers.buungroup.com/shots/staff-clients.png "themed") A resource server is added with its exact address, a name, and the product it belongs to. Removing one takes its address typed again. The gateway, which agents sign in for, cannot be removed here. ![Resource servers: the gateway, open to agents, and a product MCP server](https://developers.buungroup.com/shots/staff-resource-servers.png "themed") ## Registering the gateway's exchange client Register a client with Whose it is set to A Buun Group service, the gateway's callback as its redirect address, Keeps a secret on, and Trades tokens for set to the gateway's own address, such as `https://mcp.buungroup.com`. Put the id and the secret it shows once into the gateway Worker's `IDENTITY_EXCHANGE_CLIENT_ID` and `IDENTITY_EXCHANGE_SECRET`. ## Gateway tools ![Gateway tools: each tool version waiting for review, approved or blocked](https://developers.buungroup.com/shots/staff-gateway-tools.png "themed") ## What a person sees The account portal shows each product with the person's plan and whether their agents reach it through the gateway. ![The products page of the account portal](https://developers.buungroup.com/shots/portal-products.png "themed") Source: https://developers.buungroup.com/staff-console --- # Endpoints Every address of Buun Identity a product, an agent or the gateway calls. Paths are on the issuer of each environment, such as `https://id.buungroup.com`. ## Discovery | Method and path | Answers | |---|---| | `GET /.well-known/openid-configuration` | OpenID Connect provider metadata | | `GET /.well-known/oauth-authorization-server` | The same, for OAuth 2.1 and MCP clients (RFC 8414) | | `GET /.well-known/jwks.json` | The public keys that verify every token | The metadata names `buun_plans_endpoint` as well as the standard endpoints, and says `client_id_metadata_document_supported` and `resource_indicators_supported` are true. ## OAuth and OpenID Connect | Method and path | Who calls it | What it does | |---|---|---| | `GET /oauth/authorize` | A browser, sent by a client | Starts a sign-in. Answers a redirect to the client with a code, or to the portal | | `POST /oauth/token` | A client | Trades a code, a refresh token, or for the gateway an access token, for tokens | | `POST /oauth/revoke` | A client | Ends a refresh token and its family. Always 200 for a known client | | `GET /oauth/userinfo` | A client with an access token holding `openid` | `sub`, and `email`, `email_verified`, `name` and `orgs` as the scopes allow | | `GET /oauth/plans` | A product with an access token | The person's active plans, as far as that client may know | `/oauth/token`, `/oauth/revoke`, `/oauth/userinfo`, `/oauth/plans` and the discovery addresses answer any origin, so a page or a tool may call them. ## Grant types | `grant_type` | For | |---|---| | `authorization_code` | Every client, with PKCE S256 | | `refresh_token` | A client that asked for `offline_access` | | `urn:ietf:params:oauth:grant-type:token-exchange` | The gateway's exchange client only. See [Token exchange](https://developers.buungroup.com/mcp/token-exchange) | ## The gateway | Method and path | What it does | |---|---| | `POST /mcp` | The MCP endpoint, stateless over HTTP: `initialize`, `ping`, `tools/list`, `tools/call` | | `GET /.well-known/oauth-protected-resource` | The gateway's resource metadata (RFC 9728): its address and Buun Identity as the authorization server | | `GET /health` | Says the Worker is up | ## Staff only The issuer's `/admin` and the gateway's `/admin` are called by the staff console alone, with its own token and the acting member of staff named on every call. The issuer's admin API is described as OpenAPI 3.1 at `/admin/openapi.json`. A product never calls either. Source: https://developers.buungroup.com/reference/endpoints --- # Scopes and claims What a client may ask for, and what each token says about the person. ## Scopes | Scope | Gives | |---|---| | `openid` | Who signed in: `sub`. Always needed | | `profile` | `name` | | `email` | `email` and `email_verified` | | `orgs` | The organisations the person is in, and their role in each | | `offline_access` | A refresh token, so the client stays signed in | ## Access token claims | Claim | Value | |---|---| | `iss` | The issuer | | `sub` | The person's Buun account id, `usr_...` | | `aud` | One audience: the `resource` asked for, or the client itself | | `iat`, `exp` | Seconds since the epoch. 15 minutes apart at most | | `jti` | A random id | | `client_id` | The client the token was issued to | | `scope` | The granted scopes, space separated | | `act` | Only on a traded token: `{ "sub": "" }` | ## ID token claims | Claim | Value | |---|---| | `iss`, `sub`, `aud`, `iat`, `exp` | As above; `aud` is the client, and it lasts 5 minutes | | `auth_time` | When the person signed in | | `amr` | How they signed in | | `nonce` | The `nonce` the client sent, when it sent one | | `sid` | The session | | `email`, `email_verified`, `name` | As the scopes allow | ## Ids | Prefix | What | |---|---| | `usr_` | A person | | `cli_` | A client | | `buun_ac_` | An authorization code | | `buun_rt_` | A refresh token | ## Products | Id | Name | Home | |---|---|---| | `plotwork` | Plotwork | `https://plotwork.dev` | | `flung` | Flung | `https://flung.dev` | | `gunspec` | GunSpec | `https://gunspec.io` | | `destroy` | Destroy Network | `https://destroy.network` | | `cryptflare` | CryptFlare | `https://cryptflare.com` | The list lives in `PRODUCTS` of `@buun-group/core`. A new product is added there first. Source: https://developers.buungroup.com/reference/claims --- # Errors How Buun Identity says no. The OAuth endpoints answer in the protocol's own shape; everything else in one envelope of its own. ## OAuth endpoints `/oauth/token` and `/oauth/revoke` answer `400` or `401` with `{ "error": "...", "error_description": "..." }`. | `error` | Means | |---|---| | `invalid_request` | A field is missing or malformed | | `invalid_client` | The client is unknown, disabled, or did not prove itself | | `invalid_grant` | The code, refresh token or subject token is wrong, spent, expired, or not this client's. One message for every cause | | `unauthorized_client` | This client may not use this grant | | `unsupported_grant_type` | The grant type is not one Buun Identity supports | | `invalid_scope` | A scope is unknown or not allowed for this client | | `invalid_target` | The `resource` is not one this client may ask for, or not one a token can be traded for | `/oauth/authorize` sends the same names back to the client's `redirect_uri`, with `state`, except when the client or its redirect address cannot be trusted: then it shows a page and sends nothing. `/oauth/userinfo` and `/oauth/plans` answer `401` with `WWW-Authenticate: Bearer error="invalid_token"` for a token that does not pass. ## Everything else ```json { "error": true, "errorCode": "validation.failed", "message": "The request is not valid", "issues": { "name": "name.short" }, "requestId": "..." } ``` | `errorCode` | Means | |---|---| | `validation.failed` | The body or query is not valid. `issues` names each field by a code | | `not_found` | No such thing | | `auth.missing` | Not signed in, or the caller did not prove itself | | `auth.code_invalid` | The sign-in code is wrong or has expired | | `account.suspended` | The account is suspended | | `rate_limited` | Too many requests. Wait and try again | | `oauth.client_invalid` | The client or its redirect address cannot be trusted | | `oauth.unavailable` | Signing is not set up on this server | ## A product's own answers A product's MCP server answers `401` with `WWW-Authenticate: Bearer error="invalid_token"` for a token that does not pass. The gateway reads a 401 as "trade again" and tries once more; anything else it shows the agent as the product failing. Source: https://developers.buungroup.com/reference/errors --- # Environments Every address of every environment. Put them in each Worker's `wrangler.jsonc` vars, one set per environment, and never read them from a token or a request. ## Buun Group | Part | Local | Preview | Production | |---|---|---|---| | Issuer | `http://localhost:28500` | `https://id-preview.buungroup.com` | `https://id.buungroup.com` | | Account portal | `http://localhost:28501` | `https://account-preview.buungroup.com` | `https://account.buungroup.com` | | MCP gateway | `http://localhost:28502` | `https://mcp-preview.buungroup.com` | `https://mcp.buungroup.com` | | Staff console | `http://localhost:28503` | `https://staff-preview.buungroup.com` | `https://staff.buungroup.com` | | These docs | `http://localhost:28504` | `https://developers-preview.buungroup.com` | `https://developers.buungroup.com` | | Status page | `http://localhost:28505` | `https://status-preview.buungroup.com` | `https://status.buungroup.com` | ## Product MCP servers the gateway reaches | Product | Local | Preview | Production | |---|---|---|---| | Plotwork | `http://localhost:3102/mcp-oauth` | `https://mcp-preview.plotwork.dev/mcp-oauth` | `https://mcp.plotwork.dev/mcp-oauth` | | Flung | `http://localhost:3020/mcp-oauth` | `https://mcp-preview.flung.dev/mcp-oauth` | `https://mcp.flung.dev/mcp-oauth` | A product's MCP address is its `aud` in every traded token. It must match, character for character, the resource server staff register and the gateway's catalogue. ## What differs | Setting | Local | Preview | Production | |---|---|---|---| | `http://localhost` resource servers | Taken | Refused | Refused | | Sign-in codes | Written to the log without a mail key | Emailed | Emailed | | Search engines | Turned away | Turned away | Allowed on these docs only | Source: https://developers.buungroup.com/reference/environments --- # Building a product, for agents The brief an agent follows when it builds a new Buun Group product, or adds Buun Identity to one, without reading the Buun Group repositories. Each step is something to do, then something to check. ## Before writing code - Read [llms-full.txt](https://developers.buungroup.com/llms-full.txt) once: it is every page here in one file. - The product runs on Cloudflare Workers. Its MCP server is a Worker of its own, on `mcp.`, with its MCP endpoint at `/mcp-oauth`. - Pick the product id: lower case letters, one word, such as `plotwork`. It must be added to `PRODUCTS` in `@buun-group/core` by a change to `buun-group/buungroup-app`, and the package published, before anything else names it. ## The rules that are easy to get wrong | Rule | Check | |---|---| | Accept a token only when `aud` is exactly your own address | A token for the gateway or another product is refused, with a test | | Insist on `typ: at+jwt` and `alg: ES256` | An ID token sent as an access token is refused, with a test | | Take the issuer and your own address from `wrangler.jsonc` vars, per environment | No address is read from a token or a request | | Link an existing user by address only when it is verified on both sides | An unverified address makes a new user, with a test | | Answer 401 with `WWW-Authenticate: Bearer error="invalid_token"` for any token that fails | The gateway trades again on a 401 and on nothing else | | Never log a token, and never forward one | Search the code for the header name before shipping | | Never keep a plan in a token or a long cache | Ask `/oauth/plans` each time it matters | | Keep your own sign-in working beside Buun Identity's | Pick the check by the token's `iss`, then verify everything | ## The steps 1. **Sign-in on the website.** Ask staff for a Buun Group product client with your redirect addresses. Build [the sign-in flow](https://developers.buungroup.com/sign-in/flow): PKCE S256, `state`, `iss` checked on return, tokens checked as on [Tokens and keys](https://developers.buungroup.com/sign-in/tokens). Test: a wrong `state` is refused; a wrong `iss` is refused. 2. **Plans.** Read [`/oauth/plans`](https://developers.buungroup.com/sign-in/plans) where the product decides what a person may do. Test: a cancelled plan stops access at the next request. 3. **The MCP server.** Make it accept Buun Identity tokens as on [Accepting Buun Identity tokens](https://developers.buungroup.com/mcp/accepting-tokens). Test every refusal in the table there. 4. **Tools.** Give each tool a stable name, an honest description, `readOnlyHint` or `destructiveHint`, and an input schema under 32 KB. Staff approve each version before an agent sees it: [Tool review](https://developers.buungroup.com/mcp/tool-review). 5. **The gateway.** Ask for, or make as a reviewed change to `buun-group/buungroup-gateway`, a catalogue entry for each environment with `acceptsIdentityTokens: true`, and a resource server in the staff console for each MCP address: [How the gateway works](https://developers.buungroup.com/mcp/how-it-works). 6. **Test on one machine** as on [Local development](https://developers.buungroup.com/local-development): `pnpm dev:exchange`, a plan for yourself, `claude mcp add --transport http buun-local http://localhost:28502/mcp`, approve the tools, call one. ## Asking the person Stop and ask before anything outward-facing: deploying, setting a secret, applying a remote migration, publishing a package, or registering a client or resource server in a deployed environment. Everything on a developer's machine is safe to do. ## Where things are | Thing | Where | |---|---| | Product ids, scopes, the client schema | `@buun-group/core` on GitHub Packages, `buun-group/buungroup-app` `packages/core` | | The design system | `@buun-group/ui`, the same repository, `packages/ui` | | The issuer and the portal | `buun-group/buungroup-app`, `apps/identity` and `apps/account` | | The gateway | `buun-group/buungroup-gateway` | | The staff console | `buun-group/buungroup-staff` | | These pages, as Markdown | `buun-group/buungroup-app`, `apps/developers/content`, and on this site at `/.md` | Source: https://developers.buungroup.com/agents/building-a-product