Skip to content

feat(mcp): OAuth discovery, client registration, token and revoke endpoints - #2262

Merged
gkhngyk merged 2 commits into
ansvisor:mainfrom
cihan-gyk:feature/mcp-oauth-endpoints
Nov 10, 2026
Merged

gkhngyk merged 2 commits into
ansvisor:mainfrom
cihan-gyk:feature/mcp-oauth-endpoints

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

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:

  • PR 4: /api/oauth/authorize and 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.
  • PR 5: Client ID Metadata Documents (CIMD). The metadata doesn't advertise them yet.

Discovery (served at the root's /.well-known, through next.config.ts rewrites to /api/oauth/*; the proxy skips both)

  • /.well-known/oauth-protected-resource/api/mcp and /.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.
    • the registration and revocation endpoints, the service documentation, and the policy and terms URLs.
  • Both are served with CORS * (no cookies are read) and Cache-Control: public, max-age=300.

POST /api/oauth/register (RFC 7591, open registration as MCP clients expect)

  • Redirect URIs: 1 to 5, each https or loopback http (any port), with no fragment, credentials or wildcard. Anything else gets invalid_redirect_uri. Custom schemes are refused, as the owner decided.
  • Grants: grant_types must be authorization_code (+ refresh_token), and response_types must be code.
  • Client authentication: token_endpoint_auth_method is none (the default), client_secret_post or client_secret_basic. A confidential client gets an ans_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).
  • Everything else (logo_uri, client_uri, …) is kept in metadata, up to 4 KB, and never fetched or shown. The body is at most 10 KB.
  • Limits: 30 registrations an hour per address (IPv6 by /64) and 2,000 a day in all. A client nobody connected is removed after a day.
  • Answer: 201 with client_id (ansc_…), client_id_issued_at, redirect_uris, grant_types, response_types and token_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 is no-store)

  • Client: checked by id. A confidential client also needs its secret, in the body or by HTTP Basic; otherwise 401 invalid_client.
  • authorization_code:
    • The code is claimed by one request only (update … where used_at is null).
    • It must match the same client and still be fresh (5 minutes).
    • It must also match the identical redirect_uri, a code_verifier whose S256 is the stored challenge, and our resource. Otherwise the answer is invalid_target; no resource means ours.
    • It makes the connection (oauth_grants) and its first token pair.
    • A code used again ends the connection it made (OAuth 2.1 §4.1.2) and is logged (code_reuse).
  • refresh_token:
    • The token must be the client's, unexpired (30 days), and its connection still standing.
    • It is swapped once (rotated_at, atomic) for a new pair with its scopes or fewer: scope can narrow, never widen (invalid_scope).
    • Two refreshes racing (the old token again within 30 s) get invalid_grant and keep the connection.
    • An old refresh token presented later is a replay: the whole connection ends (refresh_reuse, logged).
    • Refresh works while a plan has ended, so the plan message reaches the app (owner, 2026-11-10).
  • Errors are RFC 6749 codes: invalid_grant for any dead code or refresh token (Claude needs exactly that), unsupported_grant_type, invalid_request.
  • Limits: 120 requests a minute per client and 600 per address. All of Claude's traffic comes from one /21, so the per-address limit is loose.

POST /api/oauth/revoke (RFC 7009)

  • Revoking any of a connection's tokens ends the connection, as Disconnect in Settings will (PR 6). It is logged (revoked_by_client).
  • An unknown token answers 200. A token of another client answers unauthorized_client.

How it's built

  • New files in 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_hit from 00510. If the count can't be read, the request goes through and the failure is logged.
  • Routes: web/src/app/api/oauth/{protected-resource,metadata,register,token,revoke}/route.ts.
  • No new migration (00510 has the tables), and no dependency change.
  • subscription-guard-coverage.test.ts names the three POST routes as open while a workspace is read-only:
    • registration happens before any workspace is known;
    • token requests are checked where the connection is used: on every MCP call (oauthMcpAccess) and at consent (PR 4);
    • revoking takes access back.

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:

  • the flag: 404 everywhere while it is off;
  • discovery: both documents, validated with the MCP SDK's own zod schemas;
  • registration: the good case, a confidential secret, name cleaning, 9 refused shapes, a body that isn't JSON or is too large, and the 30-an-hour limit;
  • codes:
  • refresh: rotation, a race, a replay ending the connection, narrowing but not widening, another client's token, an expired token, a revoked connection;
  • revocation: a token, an unknown token, and another client's token;
  • end to end: the MCP SDK's own client (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 feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

  1. cd web && npx vitest run src/app/api/oauth: 36 tests pass.
  2. Run yarn dev with MCP_OAUTH_ENABLED=true and NEXT_PUBLIC_APP_URL=http://localhost:3000:
    • curl -s localhost:3000/.well-known/oauth-protected-resource/api/mcp gives the resource document;
    • curl -s localhost:3000/.well-known/oauth-authorization-server gives the server's metadata;
    • curl -si -X POST localhost:3000/api/mcp gives a 401 whose WWW-Authenticate points to the first document.
  3. With a dev database that has 00510 applied, register a client. 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"]}' gives 201 with an ansc_ id.
  4. Unset MCP_OAUTH_ENABLED: all of the above answer 404, and /api/mcp answers 401 without WWW-Authenticate.

Checklist

  • Branch follows the naming convention (feature/mcp-oauth-endpoints, stacked on feature/mcp-oauth-tokens)
  • Commits follow Conventional Commits
  • yarn lint passes
  • yarn typecheck passes
  • yarn format:check passes
  • yarn build passes (with CI's placeholder env)
  • Tests: src/app/api/oauth, src/app/api/mcp, src/lib/mcp-oauth, src/lib/mcp, both mcp-auth tests, embed-hints and subscription-guard-coverage: 67 files, 576 tests passed
  • Checked in the running app (next dev, flag on): both .well-known documents are served through the rewrites, /api/mcp's 401 carries the challenge, and the token endpoint refuses a JSON body
  • Changes are focused — one concern per PR
  • Help article updated under help/ (or no user-visible change): nothing is switched on; Help comes with PR 7

Checked on 7824b51, which merges cleanly into current main.


Generated by Claude Code

…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
@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Nov 10, 2026

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@gkhngyk
gkhngyk merged commit 0a4a171 into ansvisor:main Nov 10, 2026
13 checks passed
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants