Skip to content

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/mcp 1.7.18 and @better-auth/oauth-provider 1.7.18 as installed (type definitions and dist/ read 2026-11-09: mcp(), OAuthOptions, consentEndpoint, authorizeEndpoint, createJwtAccessToken, seedResourcesOnce), better-auth 1.7.18 jwt() (JwtOptions), jose 6.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

  1. Better Auth’s mcp() plugin plus jwt() in createInstance (packages/api/src/auth/oauth.ts), only when the runtime passes AuthOptions.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 plus offline_access, no openid. The AS metadata is served by createApi at /.well-known/oauth-authorization-server/api/auth and at the root alias (Decision 6).
  2. Tokens: RFC 9068 JWT access tokens (typ: at+jwt, EdDSA/Ed25519, 1 h), aud = the resource, iss = the issuer, and a private claim cloudhal_grant naming the grant they were issued for (a provider extension adds it from the live agent_grants row); refresh tokens for 30 d sliding, rotated on every use with mcp()’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. /mcp verifies signature, iss, aud, exp, typ and the grant claim with jose against the jwks table read through the instance (cached per isolate by kid, never fetched over HTTP), pinned to EdDSA. No DPoP in v1: a token request with a DPoP proof 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 /mcp refuses any token carrying cnf.
  3. One grant row per member and client (agent_grants, migration 0031_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’s cloudhal_grant (revoked, then connected again) or no membership is a 401 with the invalid_token challenge. 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 is narrow(narrow(token.scope, grant.scopes), roleScopes(role)) with the mode clamped like a key’s, grantId, keyScopes and person — the same Principal shape a key produces, so policy, audit, approvals, modes, elevations and forSite are unchanged.
  4. Consent is Cloudhal’s. The provider’s consentPage is 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_owner and the connect_agent audit 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 (an auto release approval, an elevation, an automation run) asks agentCredential() and never treats a connection as the person behind it. The provider’s own /oauth2/consent refuses HTTP callers (a per-instance server key) and is fenced in createApi with every other provider endpoint that is not authorize, token or revoke (client and consent CRUD, introspection, userinfo, registration, the jwt() plugin’s /token).
  5. No authorization server without a stable origin (mcpOauthFor): the admin Worker uses the request’s origin (as Better Auth’s baseURL already does); cloudhal studio needs --base-url / CLOUDHAL_BASE_URL and logs why OAuth is off otherwise; plain HTTP is accepted on loopback only; CLOUDHAL_MCP_OAUTH=off turns it off on both. The playground stays out (Decision 10).
  6. 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, and createClient is gone (the suites register through DCR or CIMD; clientPrivileges now admits nobody). See “Phase 3a” below.

Phase 3a: client registration (2026-11-09)

  1. CIMD is @better-auth/cimd 1.7.18’s discovery with the MCP 2026-07-28 profile, wrapped by Cloudhal (cimd-discovery.ts) and fetched through cimdFetch over the media import’s safeFetch (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 checks client_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’s updatedAt) 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 by LIKE over 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") (migration 0032) serves the count, the eviction and the prune. CLOUDHAL_MCP_CIMD=off turns it off and also ends existing document clients’ connections at their next refresh (they no longer resolve), the conservative choice.
  2. DCR is Cloudhal’s route POST /api/auth/oauth2/register (dcr.ts), mounted before Better Auth’s catch-all: rate limits in rate_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 becomes none; no secret is ever minted), client_name 1–100 characters, grant_types reduced to authorization_code/refresh_token, and every other field dropped before the provider’s registerOAuthClient runs server-side with empty headers. The provider’s own endpoint answers 404 to HTTP callers (the before hook and the fence, which opens exactly REGISTER_PATH only while DCR is on). Clients with no live connection and no connection activity for 30 days are deleted by the hourly oauth.clients.prune system job on both schedulers (document clients after a day), with every provider row of theirs in one batch per kind. CLOUDHAL_MCP_DCR=off removes the route and registration_endpoint, and /oauth2/authorize refuses the clients DCR stored earlier; connections they already have keep working until revoked or pruned.
  3. Redirect URIs (redirect-policy.ts): https on a non-loopback host; http on exactly localhost/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), never javascript/data/file/vbscript/about/blob and friends or an http look-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).
  4. 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 (localhost admits loopback; private-use redirects then need a known scheme). A value that does not parse turns registration off.
  5. AS metadata advertises client_id_metadata_document_supported with CIMD on, registration_endpoint with DCR on, and token_endpoint_auth_methods_supported: ["none", "private_key_jwt"] (the provider’s shared-secret methods are dropped: no client here holds a secret).
  6. set_embargo from a connection files the gate-only release as a schedule_release request (on-approval, bound to rl1:) 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-bound auto approval would need a contract change (the auto approval names a key) and is not taken.
  7. 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 oauthResource row at init; per request on Workers); a BETTER_AUTH_SECRET rotation invalidates the signing key and every token.
  • Risks: @better-auth/mcp is young (1.7.x); the family is pinned exactly and better-auth-pins.test.ts keeps 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.