Skip to content

feat(mcp): accept OAuth access tokens at /api/mcp, behind MCP_OAUTH_ENABLED (00510) - #2261

Merged
gkhngyk merged 1 commit into
ansvisor:mainfrom
cihan-gyk:feature/mcp-oauth-tokens
Nov 10, 2026
Merged

gkhngyk merged 1 commit into
ansvisor:mainfrom
cihan-gyk:feature/mcp-oauth-tokens

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

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.

  • Nothing issues tokens yet: the endpoints are PR 3, and the consent screen is PR 4.
  • All of it is off until MCP_OAUTH_ENABLED=true and NEXT_PUBLIC_APP_URL is https (or http on localhost) with no path. While it is off, /api/mcp and the REST routes behave exactly as on main.

Migration 00510_mcp_oauth.sql

Table / function What it holds
oauth_clients Apps. A self-registered app gets an ansc_ id; a secret, only for a confidential app, is stored hashed. client_name is the app's own word. metadata is the rest of the registration, never fetched or shown.
oauth_authorization_requests A request to connect, kept 10 minutes. The consent page's address holds only its id.
oauth_codes One-time codes (5 minutes), with what the token request must match. grant_id is set when the code is redeemed, so a second use can end that connection.
oauth_grants A connection: one person, the organization they approved in, one app, mcp:read and optionally mcp:write, and the MCP endpoint as resource. revoked_at and revoked_reason record when and why it ended.
oauth_tokens Access tokens (1 hour) and refresh tokens (30 days, rotated_at), as sha256 hashes only.
oauth_events The audit log. The IP address is cut to /24 (IPv4) or /48 (IPv6), and the user agent to 200 characters.
oauth_rate_limits, oauth_rate_hit() Fixed-window counters for PR 3's endpoints. security invoker; execute is revoked from public, anon and authenticated and granted to service_role.
  • Access: RLS is on with no policy, and anon and authenticated get nothing. Only the server reads these tables, with the service role. PR 6's Settings list will read them through an API route.
  • Brand access: the tables have no 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.
  • Tried on a scratch PostgreSQL 16 database, with stubs for auth.users, organizations and the three roles:
    • it applies cleanly;
    • the checks refuse a secret on a public client, and scopes without mcp:read;
    • oauth_rate_hit('k', 60, 2) gives true, true, false;
    • authenticated is refused on oauth_grants.
  • bash supabase/build-schema.sh was run, and schema.sql is committed. The number 00510 is from this work's reserved range (00510–00514).
  • web/src/types/supabase.ts isn'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: prefixes ans_oat_ (access), ans_ort_ (refresh), ans_oac_ (code), ans_ocs_ (client secret) and ansc_ (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, with localhost too 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, and callsWriteTool (uses isReadTool).
  • 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), createGrant and issueTokenPair (stores only hashes).

The MCP side

  • authenticateMcpRequest(req, { allowOAuth }):
    • Only /api/mcp passes allowOAuth: true, because the tokens' audience is the MCP endpoint. The REST routes answer an app token with 401 "This address takes an API key".
    • An 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.
    • If the person's organization is no longer the connection's, the connection is revoked (member_left, logged) and the answer is 401.
    • A read that fails answers 503, as for a key.
    • The context gains via, oauthGrantId, oauthScopes and oauthAccess. apiKeyId is oauth:<grant id>, so nothing that reads it breaks.
  • The 401s at /api/mcp carry the WWW-Authenticate challenge 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.
  • The plan gate (owner: all paid plans), oauthMcpAccess / oauthAccessFromFacts in subscription-gate.ts:
    • Self-hosted is always allowed.
    • A plan that isn't active is ended.
    • planGateLock(facts, { minPlan: 'starter' }), which locks only in the trial, gives trial.
    • Everything else is ok. An Enterprise trial counts as paid, as plan-facts already treats it.
    • On trial or ended, gateWriteTools answers every tool, reads too, with oauth_plan_required and 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 keys are unchanged.
  • /api/mcp/route.ts reads the JSON-RPC body once, from a copy, and passes it to the transport as parsedBody. A tools/call of a write tool on a connection without mcp:write answers 403 insufficient_scope before 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.example documents MCP_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 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/lib/mcp-oauth src/lib/mcp-auth.oauth.test.ts src/lib/mcp/oauth-gate.test.ts src/app/api/mcp/route.test.ts runs the new tests: helpers, connections, auth, plan gate and route.
  2. npx vitest run src/lib/mcp-auth.test.ts src/lib/mcp shows API keys behaving as before.
  3. With the flag off (the default), call /api/mcp without a key: 401 { "error": "Missing or malformed API key" }, no WWW-Authenticate.
  4. With MCP_OAUTH_ENABLED=true and NEXT_PUBLIC_APP_URL=http://localhost:3000, the same call carries WWW-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.
  5. Apply 00510 to a dev database: seven tables, RLS on, nothing granted to anon or authenticated.

Checklist

  • Branch follows the naming convention (feature/mcp-oauth-tokens)
  • Commits follow Conventional Commits
  • yarn lint passes (0 problems)
  • yarn typecheck passes (0 errors)
  • yarn format:check passes
  • yarn build passes (with CI's placeholder env)
  • Web tests:
    • src/lib/mcp, src/lib/mcp-oauth, both mcp-auth tests, src/app/api/mcp and src/lib/chat/registry;
    • the schema-scanning tests (brand-access-functions, embed-hints, subscription-guard-coverage, menu-access, topic-policies, organization-competitor-policies, account-time-zone, white-label/schema, chat/schema);
    • 77 files, 848 tests passed.
  • Server tests that read the migrations (brand-access-policies, -schema, -account-tables, -team, -integrations, organization-members-guard, demo/coverage, demo/write-guard): 8 files, 112 tests passed.
  • Migration: supabase/build-schema.sh run, schema.sql committed; no brand_id, so no demo coverage change; no security definer function.
  • 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 22b9e88, 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
@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.

@gkhngyk
gkhngyk merged commit 22b9e88 into ansvisor:main Nov 10, 2026
13 checks passed
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]>
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