Repository navigation
feat(mcp): accept OAuth access tokens at /api/mcp, behind MCP_OAUTH_ENABLED (00510) - #2261
Merged
Merged
Conversation
…NABLED (00510) PR 2 of MCP over OAuth (ansvisor#2141): the data model and the MCP side. Nothing issues tokens yet (the endpoints are PR 3, the consent page PR 4), and all of it stays off until MCP_OAUTH_ENABLED is "true" with an https app URL. - 00510_mcp_oauth.sql: apps (oauth_clients), requests to connect, one-time codes, connections (oauth_grants: one person, the organization they approved in, one app, mcp:read and optionally mcp:write, the MCP endpoint as resource), tokens kept only as sha256 hashes, the log (oauth_events) and Postgres rate-limit counters (oauth_rate_hit). RLS on with no policy: the service role only. - lib/mcp-oauth: the issuer and flag, token prefixes (ans_oat_, ans_ort_…), PKCE S256, redirect URIs (https or loopback on any port), the resource (RFC 8707), scopes, the WWW-Authenticate challenge, the log, and connections: check an access token, revoke, issue a pair. - authenticateMcpRequest takes an app's access token at the MCP endpoint only (allowOAuth): its connection, then its person read fresh, as for an API key. Someone no longer in the organization loses the connection. Its 401s carry WWW-Authenticate with resource_metadata and scope, which is what starts an app's sign-in. REST routes stay API-key only; API keys work as before. - Plan gate (owner, 2026-11-09): oauthMcpAccess, all paid plans; in the free trial or once the plan has ended every tool over a sign-in connection, reads too, answers oauth_plan_required with words the app can pass on. Self-hosted always. API keys unchanged. - /api/mcp answers a change on a read-only connection with 403 insufficient_scope before the SDK, so the app can ask for more. Part of ansvisor#2141. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01SvzkMf5TZg7yqwaSeMFba9
12 of 16 tasks
This was referenced Nov 10, 2026
gkhngyk
pushed a commit
that referenced
this pull request
Nov 10, 2026
PR 6 of MCP over OAuth (#2141), stacked on feature/mcp-oauth-tokens (#2261): it needs only the data model. Still behind MCP_OAUTH_ENABLED: while it is off the list answers 404 and the card doesn't show. - Settings › MCP & API Keys gets a Connected apps card above the keys (the approved mockup's screens 7 to 9): each app the person connected by signing in, Recognised (claude.ai, chatgpt.com, by where its code goes) or Not checked, Read and changes or Read only, where it goes back to, when it was connected and last used, and Disconnect behind a confirmation. The empty state says how to connect; in the free trial or on an ended plan a note says why connections don't work, with Choose a plan for an admin. While app sign-in is on, the endpoint box says Claude and ChatGPT connect by signing in. - GET /api/oauth/connections lists the signed-in person's own live connections (not revoked, used within 30 days) and their plan's access; DELETE /api/oauth/connections/[id] ends one of their own and every token it has, logged (revoked_by_person). Someone else's, or one already ended, is 404. The tables stay the server's (00510). - known-apps.ts holds the recognised apps, identical to the consent page's (PR 4), so the two branches merge cleanly. Part of #2141. Claude-Session: https://claude.ai/code/session_01SvzkMf5TZg7yqwaSeMFba9 Co-authored-by: Claude <[email protected]>
9 of 13 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
PR 2 of the MCP over OAuth plan (#2141, approved by the owner on 2026-11-10). This PR adds the data model and the MCP side.
MCP_OAUTH_ENABLED=trueandNEXT_PUBLIC_APP_URLis https (or http on localhost) with no path. While it is off,/api/mcpand the REST routes behave exactly as onmain.Migration
00510_mcp_oauth.sqloauth_clientsansc_id; a secret, only for a confidential app, is stored hashed.client_nameis the app's own word.metadatais the rest of the registration, never fetched or shown.oauth_authorization_requestsoauth_codesgrant_idis set when the code is redeemed, so a second use can end that connection.oauth_grantsmcp:readand optionallymcp:write, and the MCP endpoint asresource.revoked_atandrevoked_reasonrecord when and why it ended.oauth_tokensrotated_at), as sha256 hashes only.oauth_eventsoauth_rate_limits,oauth_rate_hit()security invoker; execute is revoked frompublic,anonandauthenticatedand granted toservice_role.anonandauthenticatedget nothing. Only the server reads these tables, with the service role. PR 6's Settings list will read them through an API route.brand_id. A connection carries its person's brand access, read again on every call (BRAND-ACCESS §5.3), as an API key does. So the brand-access policy tests need no new entry, and there is no demo coverage to add.auth.users,organizationsand the three roles:mcp:read;oauth_rate_hit('k', 60, 2)gives true, true, false;authenticatedis refused onoauth_grants.bash supabase/build-schema.shwas run, andschema.sqlis committed. The number 00510 is from this work's reserved range (00510–00514).web/src/types/supabase.tsisn't hand-updated: the service-role client is untyped, and nothing reads these tables through the typed client.web/src/lib/mcp-oauth/(new)config.ts: the issuer (the app's origin), the flag, the resource URL (<issuer>/api/mcp) and the lifetimes.tokens.ts: prefixesans_oat_(access),ans_ort_(refresh),ans_oac_(code),ans_ocs_(client secret) andansc_(client id); sha256 hashing; a timing-safe compare.pkce.ts: S256 only. It is checked against the RFC 7636 test vector.redirect-uris.ts: https, or loopback http on any port (RFC 8252 §7.3, withlocalhosttoo for Claude Code). Custom schemes are refused, as the owner decided on 2026-11-10.resource.ts: RFC 8707 comparison. Upper-case scheme and host, a default port and a trailing slash count as the same.scopes.ts:mcp:read/mcp:write, andcallsWriteTool(usesisReadTool).challenge.ts:WWW-Authenticate: Bearer error=…, resource_metadata="<issuer>/.well-known/oauth-protected-resource/api/mcp", scope="mcp:read mcp:write".events.ts: the log. It never fails the request it describes.grants.ts:checkAccessToken,revokeGrant,touchGrant(at most every 5 minutes),createGrantandissueTokenPair(stores only hashes).The MCP side
authenticateMcpRequest(req, { allowOAuth }):/api/mcppassesallowOAuth: true, because the tokens' audience is the MCP endpoint. The REST routes answer an app token with 401 "This address takes an API key".ans_oat_token is checked first, then its person is read fresh: role, brand access and plan. An app secret is never looked up as an API key.member_left, logged) and the answer is 401.via,oauthGrantId,oauthScopesandoauthAccess.apiKeyIdisoauth:<grant id>, so nothing that reads it breaks./api/mcpcarry theWWW-Authenticatechallenge while the flag is on. Claude starts sign-in only on a 401 with that header. The body keeps today's{ error }shape for API-key clients.oauthMcpAccess/oauthAccessFromFactsinsubscription-gate.ts:ended.planGateLock(facts, { minPlan: 'starter' }), which locks only in the trial, givestrial.ok. An Enterprise trial counts as paid, asplan-factsalready treats it.trialorended,gateWriteToolsanswers every tool, reads too, withoauth_plan_requiredand a message saying where to choose a plan and that an API key still reads. The tools stay listed. It is not a 401, which would send the person through sign-in again for nothing (BUG-001)./api/mcp/route.tsreads the JSON-RPC body once, from a copy, and passes it to the transport asparsedBody. Atools/callof a write tool on a connection withoutmcp:writeanswers 403insufficient_scopebefore the SDK runs, so the app can ask the person for more.MCP_INSTRUCTIONS: a change is "logged under the person the API key or the app's sign-in acts as".web/.env.exampledocumentsMCP_OAUTH_ENABLED, commented out, and says to leave it off for now.No Help or docs change: nothing a person can see is switched on. Help and docs come with PR 7, which turns the feature on.
Related issue
Part of #2141
Type of change
feat— New featurefix— Bug fixchore— Maintenance / dependenciesdocs— Documentation onlyrefactor— Code change that neither fixes a bug nor adds a featuretest— Adding or updating testsHow to test
cd web && npx vitest run src/lib/mcp-oauth src/lib/mcp-auth.oauth.test.ts src/lib/mcp/oauth-gate.test.ts src/app/api/mcp/route.test.tsruns the new tests: helpers, connections, auth, plan gate and route.npx vitest run src/lib/mcp-auth.test.ts src/lib/mcpshows API keys behaving as before./api/mcpwithout a key: 401{ "error": "Missing or malformed API key" }, noWWW-Authenticate.MCP_OAUTH_ENABLED=trueandNEXT_PUBLIC_APP_URL=http://localhost:3000, the same call carriesWWW-Authenticate: Bearer error_description="…", resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource/api/mcp", scope="mcp:read mcp:write". The metadata it points to arrives in PR 3.00510to a dev database: seven tables, RLS on, nothing granted toanonorauthenticated.Checklist
feature/mcp-oauth-tokens)yarn lintpasses (0 problems)yarn typecheckpasses (0 errors)yarn format:checkpassesyarn buildpasses (with CI's placeholder env)src/lib/mcp,src/lib/mcp-oauth, bothmcp-authtests,src/app/api/mcpandsrc/lib/chat/registry;brand-access-functions,embed-hints,subscription-guard-coverage,menu-access,topic-policies,organization-competitor-policies,account-time-zone,white-label/schema,chat/schema);brand-access-policies,-schema,-account-tables,-team,-integrations,organization-members-guard,demo/coverage,demo/write-guard): 8 files, 112 tests passed.supabase/build-schema.shrun,schema.sqlcommitted; nobrand_id, so no demo coverage change; nosecurity definerfunction.help/(or no user-visible change): nothing is switched on; Help comes with PR 7Checked on 22b9e88, which merges cleanly into current
main.Generated by Claude Code