Repository navigation
feat(mcp): OAuth discovery, client registration, token and revoke endpoints - #2262
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
…points PR 3 of MCP over OAuth (ansvisor#2141), stacked on feature/mcp-oauth-tokens. Still behind MCP_OAUTH_ENABLED: every endpoint answers 404 while it is off. The authorize endpoint and the consent page are PR 4. - Discovery: /.well-known/oauth-protected-resource[/api/mcp] (RFC 9728: the MCP endpoint as resource, Ansvisor as its only authorization server) and /.well-known/oauth-authorization-server (RFC 8414: S256 only, public clients with PKCE, client_secret_post/basic for confidential ones, iss in authorization responses per RFC 9207), rewritten in next.config.ts to /api/oauth handlers. - /api/oauth/register (RFC 7591): open, as MCP clients expect; redirect URIs https or loopback, 1 to 5; names cleaned to one line of 100 characters; nothing a client says about itself is fetched; a secret only for a confidential client, shown once, kept hashed. 30 an hour per address, 2,000 a day; clients nobody connected go after a day. - /api/oauth/token: a code is claimed once, then checked (client, expiry, redirect_uri, PKCE S256, resource) and makes the connection; a code used again ends it. A refresh token is swapped once for a new pair with its scopes or fewer; one presented again more than 30 s after its swap ends the connection. Form posts only, no-store, RFC 6749 error codes (invalid_grant for a dead refresh token). - /api/oauth/revoke (RFC 7009): a client ends its connection; unknown tokens answer 200. - Rate limits counted in Postgres (oauth_rate_hit), per client and per address; CORS for browser clients; the log records registrations, reuse and revocations. - Tests run the endpoints on an in-memory database and drive them with the MCP SDK's own client: discovery, registration, code, refresh. Part of ansvisor#2141. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01SvzkMf5TZg7yqwaSeMFba9
gkhngyk
approved these changes
Nov 10, 2026
gkhngyk
left a comment
Contributor
There was a problem hiding this comment.
LGTM. Two follow-ups before MCP_OAUTH_ENABLED goes on: the global 2,000/day registration cap can be used up by a few IPs (30/h each), locking out new apps for the day; and the per-client token limit is counted before authenticateClient, so anyone who knows a client_id can lock it out.
This was referenced Nov 10, 2026
Merged
gkhngyk
pushed a commit
that referenced
this pull request
Nov 10, 2026
PR 4 of MCP over OAuth (#2141), stacked on feature/mcp-oauth-endpoints (#2262). Still behind MCP_OAUTH_ENABLED: the authorize endpoint and the page answer 404 while it is off. - /api/oauth/authorize checks the request: an unknown client or a redirect URI it never registered ends on Ansvisor's own page and is never redirected to; after that, errors go back to the app with state and iss (response_type code, PKCE S256, our resource). A good request is kept 10 minutes and the person goes on to /oauth/consent with its id alone. 60 requests an address in ten minutes. - /oauth/consent (the approved mockup's screens 1 to 6): sign in first, with a line naming the app on the sign-in page; then the app (a known one named by where its code goes, claude.ai or chatgpt.com; any other by its own name, marked not checked, with a warning when it runs on this computer), the person, workspace, plan and brands, and Read plus "Make changes you ask for". The free trial and an ended plan show why instead of Allow (an admin gets Choose a plan); no workspace yet says so; a request that can't be used is explained and goes nowhere. - Allow and Cancel are server actions: the request must still be pending and the person's who first opened it, and Allow reads the plan again. Allow writes a one-time code (5 minutes) for the client, redirect URI, PKCE challenge and resource, with the scopes left ticked, and sends the app code, state and iss; Cancel sends access_denied. Both use the request up and are logged. Switch account signs out and comes back. - The page is never framed (X-Frame-Options, frame-ancestors), cached or given as a referrer. AuthShell takes an aside and can drop its pitch. - The known apps' list moves to its own module, shared with Settings. Part of #2141. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01SvzkMf5TZg7yqwaSeMFba9
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 3 of the MCP over OAuth plan (#2141, approved by the owner on 2026-11-10). Stacked on #2261 (
feature/mcp-oauth-tokens): merge that first; until then this diff also shows its commits.It adds the authorization server's endpoints, all still behind
MCP_OAUTH_ENABLED: while the flag is off, each one answers 404. Two things are left for later PRs:/api/oauth/authorizeand the consent page. Until then, the authorization server metadata names an authorize endpoint that doesn't exist yet. That is harmless while the flag is off.Discovery (served at the root's
/.well-known, throughnext.config.tsrewrites to/api/oauth/*; the proxy skips both)/.well-known/oauth-protected-resource/api/mcpand/.well-known/oauth-protected-resource(RFC 9728) give:resource: <issuer>/api/mcp, exactly the URL a person types into Claude or ChatGPT;authorization_servers: [<issuer>](Claude uses only the first);scopes_supported: [mcp:read, mcp:write],bearer_methods_supported: [header], and the docs link./.well-known/oauth-authorization-server(RFC 8414):code_challenge_methods_supported: [S256];token_endpoint_auth_methods_supported: [none, client_secret_post, client_secret_basic];grant_types_supported: [authorization_code, refresh_token];authorization_response_iss_parameter_supported: true(RFC 9207). ChatGPT needs it for its stable redirect address, and MCP spec 2026-07-28 asks for it.*(no cookies are read) andCache-Control: public, max-age=300.POST /api/oauth/register(RFC 7591, open registration as MCP clients expect)invalid_redirect_uri. Custom schemes are refused, as the owner decided.grant_typesmust beauthorization_code(+refresh_token), andresponse_typesmust becode.token_endpoint_auth_methodisnone(the default),client_secret_postorclient_secret_basic. A confidential client gets anans_ocs_secret, shown once and stored as sha256.client_name: cut to one line of 100 characters, with control and bidi characters stripped. It is shown only as the app's own word (PR 4).logo_uri,client_uri, …) is kept inmetadata, up to 4 KB, and never fetched or shown. The body is at most 10 KB.201withclient_id(ansc_…),client_id_issued_at,redirect_uris,grant_types,response_typesandtoken_endpoint_auth_method. It is logged (client_registered).POST /api/oauth/token(form posts only, as RFC 6749 §4.1.3 and Claude require; every answer isno-store)401 invalid_client.authorization_code:update … where used_at is null).redirect_uri, acode_verifierwhose S256 is the stored challenge, and our resource. Otherwise the answer isinvalid_target; noresourcemeans ours.oauth_grants) and its first token pair.code_reuse).refresh_token:rotated_at, atomic) for a new pair with its scopes or fewer:scopecan narrow, never widen (invalid_scope).invalid_grantand keep the connection.refresh_reuse, logged).invalid_grantfor any dead code or refresh token (Claude needs exactly that),unsupported_grant_type,invalid_request.POST /api/oauth/revoke(RFC 7009)revoked_by_client).unauthorized_client.How it's built
web/src/lib/mcp-oauth/:metadata.ts: both documents;clients.ts: registration checks, client lookup and authentication;token-grants.ts: the two grants and revocation;http.ts: flag, CORS,no-store, errors, form parsing, rate limits;rate-limit.ts:oauth_rate_hitfrom 00510. If the count can't be read, the request goes through and the failure is logged.web/src/app/api/oauth/{protected-resource,metadata,register,token,revoke}/route.ts.subscription-guard-coverage.test.tsnames the three POST routes as open while a workspace is read-only:oauthMcpAccess) and at consent (PR 4);Tests (
web/src/app/api/oauth/oauth.test.ts, 36 tests) run every endpoint against an in-memory stand-in for the database (web/src/lib/mcp-oauth/__fixtures__/fake-db.ts). Codes are written the way PR 4's consent will write them. They cover:checkAccessToken;resource;redirect_urior resource; an expired code; another client's code;discoverOAuthProtectedResourceMetadata,discoverAuthorizationServerMetadata,registerClient,exchangeAuthorization,refreshAuthorization) driving the endpoints.A mutation check confirmed that a skipped PKCE check and a skipped replay check each fail a test.
No Help or docs change: nothing is switched on. Help and docs come with PR 7.
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/app/api/oauth: 36 tests pass.yarn devwithMCP_OAUTH_ENABLED=trueandNEXT_PUBLIC_APP_URL=http://localhost:3000:curl -s localhost:3000/.well-known/oauth-protected-resource/api/mcpgives the resource document;curl -s localhost:3000/.well-known/oauth-authorization-servergives the server's metadata;curl -si -X POST localhost:3000/api/mcpgives a 401 whoseWWW-Authenticatepoints to the first document.curl -s -X POST localhost:3000/api/oauth/register -H 'content-type: application/json' -d '{"client_name":"Test","redirect_uris":["http://127.0.0.1/callback"]}'gives201with anansc_id.MCP_OAUTH_ENABLED: all of the above answer 404, and/api/mcpanswers 401 withoutWWW-Authenticate.Checklist
feature/mcp-oauth-endpoints, stacked onfeature/mcp-oauth-tokens)yarn lintpassesyarn typecheckpassesyarn format:checkpassesyarn buildpasses (with CI's placeholder env)src/app/api/oauth,src/app/api/mcp,src/lib/mcp-oauth,src/lib/mcp, bothmcp-authtests,embed-hintsandsubscription-guard-coverage: 67 files, 576 tests passednext dev, flag on): both.well-knowndocuments are served through the rewrites,/api/mcp's 401 carries the challenge, and the token endpoint refuses a JSON bodyhelp/(or no user-visible change): nothing is switched on; Help comes with PR 7Checked on 7824b51, which merges cleanly into current
main.Generated by Claude Code