ADR-0045: The MCP authorization server (RFC-0044 Phase 2)
- Status: Accepted
- Date: 2026-11-09
- Related: RFC-0044 (Decisions 2026-11-08), ADR-0004 (addendum “No OAuth provider”, superseded), ADR-0010 (Better Auth; MCP authorization amended), ADR-0011 §5–6, ADR-0015 / ADR-0016 (modes, elevations), RFC-0005 (I1, I5, I7), RFC-0034 A2 (site roles), RFC-0036 (playground)
- Sources:
@better-auth/mcp1.7.18 and@better-auth/oauth-provider1.7.18 as installed (type definitions anddist/read 2026-11-09:mcp(),OAuthOptions,consentEndpoint,authorizeEndpoint,createJwtAccessToken,seedResourcesOnce),better-auth1.7.18jwt()(JwtOptions),jose6.2.12, MCP Authorization 2026-07-28, RFC 9068, RFC 8707, RFC 8414, RFC 9207
Context
RFC-0044 Phase 1 made /mcp a resource server that names an authorization server nobody ran. Phase 2 runs it, on Cloudflare (D1) and self-hosted Node (SQLite), without a second account store and without a second authorization path next to agent keys.
Decision
- Better Auth’s
mcp()plugin plusjwt()increateInstance(packages/api/src/auth/oauth.ts), only when the runtime passesAuthOptions.mcpOauth. The issuer is Better Auth’s base URL on the public origin,<origin>/api/auth; the resource is<origin>/mcp. Grants: authorization code with PKCE (S256 only) and refresh token; scopes are key scopes plusoffline_access, noopenid. The AS metadata is served bycreateApiat/.well-known/oauth-authorization-server/api/authand at the root alias (Decision 6). - Tokens: RFC 9068 JWT access tokens (
typ: at+jwt, EdDSA/Ed25519, 1 h),aud= the resource,iss= the issuer, and a private claimcloudhal_grantnaming the grant they were issued for (a provider extension adds it from the liveagent_grantsrow); refresh tokens for 30 d sliding, rotated on every use withmcp()’s 30 s reuse window (Decision 2), and refused 90 d after the family’s first refresh token (oauth-hooks.ts, §2 “90 d absolute”; a family is every refresh token of one authorization code, never anchored to the Studio session, which slides) or when the family began before the live grant (a revoke, then a reconnect); authorization codes 5 min./mcpverifies signature,iss,aud,exp,typand the grant claim withjoseagainst thejwkstable read through the instance (cached per isolate bykid, never fetched over HTTP), pinned to EdDSA. No DPoP in v1: a token request with aDPoPproof gets a 400 (invalid_dpop_proof) rather than a fallback to Bearer, the metadata does not advertise DPoP algorithms (the provider’s own issuer-appended document under/api/auth/.well-known/is not served), and/mcprefuses any token carryingcnf. - One grant row per member and client (
agent_grants, migration0031_oauth): the scopes after narrowing at consent, the mode, an elevation,last_used_at(written at most every 5 min) and the revocation. Every token call reads it; no row, a revoked row, a row of a later grant than the token’scloudhal_grant(revoked, then connected again) or no membership is a 401 with theinvalid_tokenchallenge. Ending a connection (Studio’s revoke, or removing the member, where it shares the membership’s batch) revokes the grant, deletes the provider’s stored consent and pending authorization codes and revokes its refresh tokens in one SQL batch. The principal isnarrow(narrow(token.scope, grant.scopes), roleScopes(role))with the mode clamped like a key’s,grantId,keyScopesandperson— the samePrincipalshape a key produces, so policy, audit, approvals, modes, elevations andforSiteare unchanged. - Consent is Cloudhal’s. The provider’s
consentPageis Studio’s/oauth/consent; the screen posts to/api/agent-grants/consent, which verifies the signed request, narrows the requested scopes by the member’s installation role (the cap #173’s step-up relies on), caps the mode, calls the provider’s consent endpoint with the scopes kept (a subset of the request, as the provider requires), writing the grant,agent_ownerand theconnect_agentaudit row in one batch before it calls the provider. Before the provider’s authorize step, Cloudhal deletes the provider’s stored consent for the member and client when no live grant exists, or when the member’s current role would give a requested scope the grant does not hold (a promotion followed by a step-up), so the provider’s consent memory (Decision 8) never skips Studio’s screen when the grant would change. Agent code that gives a key something of its own (anautorelease approval, an elevation, an automation run) asksagentCredential()and never treats a connection as the person behind it. The provider’s own/oauth2/consentrefuses HTTP callers (a per-instance server key) and is fenced increateApiwith every other provider endpoint that is not authorize, token or revoke (client and consent CRUD, introspection, userinfo, registration, thejwt()plugin’s/token). - No authorization server without a stable origin (
mcpOauthFor): the admin Worker uses the request’s origin (as Better Auth’sbaseURLalready does);cloudhal studioneeds--base-url/CLOUDHAL_BASE_URLand logs why OAuth is off otherwise; plain HTTP is accepted on loopback only;CLOUDHAL_MCP_OAUTH=offturns it off on both. The playground stays out (Decision 10). - Registration (Phase 3a, amended 2026-11-09). Phase 2 had none and a server-side test client (
OauthServer.createClient); Phase 3a replaces it with the two paths of RFC-0044 §3, andcreateClientis gone (the suites register through DCR or CIMD;clientPrivilegesnow admits nobody). See “Phase 3a” below.
Phase 3a: client registration (2026-11-09)
- CIMD is
@better-auth/cimd1.7.18’s discovery with the MCP 2026-07-28 profile, wrapped by Cloudhal (cimd-discovery.ts) and fetched throughcimdFetchover the media import’ssafeFetch(RFC-0004 §5.7):nodeTransport()on Node (every address public, connection pinned),workersTransport()on the admin Worker (DoH checks); https on 443, DNS names only, no redirects, 5 KB, 5 s, never the deployment’s own host or a site’s domain. The plugin checksclient_id= URL, the JSON media type and the profile; its own cache is off and its fetch windows and state capacity (10,000) are set out of reach, so the stored row is the only cache and Cloudhal’s budgets the only budgets, on Workers (instance per request) and Node (instance per process) alike. A stored client validated within 60 min (its row’supdatedAt) is used without a fetch. Every fetch spends the caller’s budget (20 per address per minute, past which that caller gets 429); a document not stored yet also spends 30 per origin and 120 in all per minute, and needs room under the cap of 5,000 (the oldest grantless client not fetched for 10 min is evicted, else 503; the well-known clients’ document hosts and the host list are exempt from the cap and never evicted, judged on the URL’s host name in code, never byLIKEover the URL, whose%spans/). A failed refetch is recorded on the row (its validation time cleared) and refuses the client until a fetch succeeds; a stored row is served as it is only when the plugin itself declines to fetch, and only within 24 h of its last good fetch. Unused document clients are pruned after three hours, up to four batches of 50 an hour; an index on("clientDiscoveryId", "updatedAt")(migration0032) serves the count, the eviction and the prune.CLOUDHAL_MCP_CIMD=offturns it off and also ends existing document clients’ connections at their next refresh (they no longer resolve), the conservative choice. - DCR is Cloudhal’s route
POST /api/auth/oauth2/register(dcr.ts), mounted before Better Auth’s catch-all: rate limits inrate_limits(10 per address per hour, 300 per day, every attempt counted), a 5 KB body, a cap of 5,000 clients (503), public clients only (an absent method becomesnone; no secret is ever minted),client_name1–100 characters,grant_typesreduced toauthorization_code/refresh_token, and every other field dropped before the provider’sregisterOAuthClientruns server-side with empty headers. The provider’s own endpoint answers 404 to HTTP callers (thebeforehook and the fence, which opens exactlyREGISTER_PATHonly while DCR is on). Clients with no live connection and no connection activity for 30 days are deleted by the hourlyoauth.clients.prunesystem job on both schedulers (document clients after a day), with every provider row of theirs in one batch per kind.CLOUDHAL_MCP_DCR=offremoves the route andregistration_endpoint, and/oauth2/authorizerefuses the clients DCR stored earlier; connections they already have keep working until revoked or pruned. - Redirect URIs (
redirect-policy.ts): https on a non-loopback host; http on exactlylocalhost/127.0.0.1/[::1]with any port (the provider’s RFC 8252 matching); or a native app’s private-use scheme (scheme:/…, matched exactly) that is reverse-domain or a known app’s (cursor,vscode,CLOUDHAL_MCP_REDIRECT_SCHEMES), neverjavascript/data/file/vbscript/about/bloband friends or anhttplook-alike; at most 10, one refused entry refusing the registration. The rules and the host list run at registration (DCR) and at every authorization (validateRedirectUri). CLOUDHAL_MCP_CLIENT_HOSTS(opt-in, Decision 9): the hosts a metadata document may come from (stored clients included) and every client may redirect to (localhostadmits loopback; private-use redirects then need a known scheme). A value that does not parse turns registration off.- AS metadata advertises
client_id_metadata_document_supportedwith CIMD on,registration_endpointwith DCR on, andtoken_endpoint_auth_methods_supported: ["none", "private_key_jwt"](the provider’s shared-secret methods are dropped: no client here holds a secret). set_embargofrom a connection files the gate-only release as aschedule_releaserequest (on-approval, bound torl1:) instead of saving the gate without effect; it is notified (schedule-approval-due) while its request is pending and unexpired, and a person approves it in Studio with their own approval. A grant-boundautoapproval would need a contract change (theautoapproval names a key) and is not taken.- Consent identity (
client-identity.ts): a client name is shown plain (control, bidi, zero-width and format characters removed, at most two combining marks per character, spaces collapsed) and at most 100 characters; a document client leads with its host, first in the title; a DCR client is “self-registered, not verified”; a name that looks like a well-known document client’s (Claude, Claude Code, ChatGPT, Codex, VS Code, compared after NFKC and a small confusable map) is flagged unless the client is that client’s document on its real host. A UTS #39 confusable skeleton is a follow-up. A private-use redirect is shown as an app on this computer.
Alternatives considered
| Alternative | Pros | Cons | Why not |
|---|---|---|---|
Let Studio call the provider’s /oauth2/consent directly, with a hook writing the grant |
One request | The provider requires consent scopes ⊆ requested, so :own narrowing could not be expressed; a hook could not refuse cleanly |
Cloudhal’s endpoint narrows, the grant caps the token |
requireMcpAuth / createMcpProtectedRequestHandler from @better-auth/mcp |
Ready-made verifier | Fetches JWKS over HTTP from the deployment itself; its own challenge format; no grant read | Local jose verification against the instance’s keys (RFC-0044 §2) |
| Opaque tokens + introspection | Instant revocation | A Better Auth read per call anyway, no mode or elevation | The grant read gives both |
| Issuer per request without a configured origin on Node | Works on any address | Tokens and iss change with the address a client used |
An issuer must be stable (§10) |
Consequences
- Positive: Claude, ChatGPT, Cursor and other remote MCP clients can connect by URL (Phase 3a: CIMD, and DCR for clients without a document); a token is never more than a key of the same member; revoking a connection or removing a member takes effect on the next call.
- Negative: one extra indexed read per Better Auth instance (the plugin seeds the
oauthResourcerow at init; per request on Workers); aBETTER_AUTH_SECRETrotation invalidates the signing key and every token. - Risks:
@better-auth/mcpis young (1.7.x); the family is pinned exactly andbetter-auth-pins.test.tskeeps it in step. Consent memory (Decision 8) is the provider’s: a subset of granted scopes skips the screen and writes no audit row in Phase 2.