DEV Community

Adding OAuth to a remote MCP server with Supabase Auth: what tripped us up with Claude and ChatGPT

I build Candidate Falcon, a practice site for hiring assessments and one-way video interviews. This autumn we added a remote MCP server so people can use parts of it from Claude and ChatGPT.

Some tools are public (searching and reading free guides). Others act on the user's account (playing the practice games and reading past results), so the server needs OAuth. Our stack: the MCP endpoint runs on a Cloudflare Worker, accounts live in Supabase, and Supabase Auth can act as an OAuth 2.1 authorization server.

So the plan was simple: Supabase issues the tokens, the Worker checks them. This is what tripped us up on the way.

How the flow works

The client calls a tool that needs an account, without a token.

The Worker answers with HTTP 401 and a WWW-Authenticate header that points to its protected resource metadata:

WWW-Authenticate: Bearer resource_metadata = "https://example.com/.well-known/oauth-protected-resource/mcp" , error = "invalid_token" , error_description = "Connect your account to continue."

The metadata names the authorization server (trimmed):

export function protectedResourceMetadata ( request , env ) {
  const site = env . MCP_PUBLIC_ORIGIN || new URL ( request . url ) . origin ;
  return {
    resource : `${site}/mcp` ,
    authorization_servers : [ `${env.SUPABASE_URL}/auth/v1` ] ,
    scopes_supported : [ 'openid' ] ,
    bearer_methods_supported : [ 'header' ] ,
  } ;
}

The client discovers Supabase's endpoints, sends the user to our consent page, exchanges the code (with PKCE) and retries the call with a bearer token.

We serve the metadata at /.well-known/oauth-protected-resource/mcp and also at the root /.well-known/oauth-protected-resource, as a fallback for clients that ignore the resource_metadata pointer. The same challenge also goes into the tool result's _meta (mcp/www_authenticate), for hosts that read it from there.

Checking the token

Website sessions and OAuth grants come from the same Supabase project, so "is this token valid?" isn't the right question. The right one is "is this a valid token issued to one of the OAuth clients we approved?".

The Worker answers it in two steps (trimmed):

// 1. Let Supabase verify the token.
const userResponse = await fetch ( `${authUrl}/auth/v1/user` , {
  headers : {
    apikey : env . SUPABASE_ANON_KEY ,
    Authorization : `Bearer ${token}`
  } ,
  signal : AbortSignal . timeout ( 10000 ) ,
} ) ;
if ( userResponse . status === 401 || userResponse . status === 403 ) return login ( ) ;
const user = await userResponse . json ( ) ;
// 2. Decode only after the Auth service has verified the token; never trust unsigned claims.
const claims = JSON . parse ( atob ( token . split ( '.' ) [ 1 ] . replaceAll ( '-' , '+' ) . replaceAll ( '_' , '/' ) ) ) ;
const approved = env . MCP_OAUTH_CLIENT_IDS . split ( ',' ) . map ( ( value ) => value . trim ( ) ) ;
if ( ! approved . includes ( claims . client_id ) || claims . iss !== `${authUrl}/auth/v1` || claims . sub !== user . id || claims . aud !== 'authenticated' || claims . exp * 1000 <= Date . now ( ) ) return login ( ) ;

Unknown clients fail closed. A token from a normal website session doesn't carry one of the approved client IDs, so it can't be used against the MCP endpoint.

What tripped us up

  1. Slashes in the Site URL and the authorization path

    Supabase's OAuth server combines the project's Site URL with the authorization path, which points to your consent page (ours is /oauth/consent). The Site URL must not end with a slash, and the authorization path must start with one. Both cost us a debugging round.

  2. client_secret_basic vs client_secret_post

    We first registered Claude's client as confidential with client_secret_basic. Login and consent worked, then the token exchange failed with invalid authentication method. Claude sends the client secret in the request body (client_secret_post). Registering the client with client_secret_post fixed it. Supabase's auth logs showed the reason.

  3. Logging out of the website disconnected Claude and ChatGPT

    After a logout on the website, the assistants' connections stopped working: their refresh failed with refresh_token_not_found. supabase.auth.signOut() defaults to the global scope, which ends every session of that user, and the OAuth grants are sessions too.

    const signOut = async ( ) => {
      // Sign out this browser only. The default "global" scope also revokes the user's other sessions,
      // including Claude and ChatGPT connections, which then fail to refresh and ask to sign in again.
      await supabase . auth . signOut ( { scope : 'local' } ) ;
      // ...clear local state
    } ;
    

    If your app adds OAuth clients on top of an existing login, check every signOut call.

  4. ChatGPT's redirect URI belongs to one app

    ChatGPT gives each app its own redirect URI, in the form https://chatgpt.com/connector/oauth/{callback_id}. The developer-mode connector you test with is a different app from the one you publish, so plan to add the published app's URI to the same OAuth client before launch, and to remove the test one afterwards. Keep a list of every redirect URI you register and why.

  5. Relative image paths in the embedded UI

    The account tools return an MCP App: one self-contained HTML file with our React games, which the chat host renders in a sandboxed iframe on its own origin. Every game image used a root-relative path like /images/..., so the browser asked the sandbox origin for them and got nothing. A base tag can't fix it: by default the MCP Apps CSP sets base-uri 'self'.

    So the build rewrites those paths and refuses to ship a bundle that still has one (trimmed):

    // Games reference site images by root-relative path (/images/...). Chat hosts render the app on
    // their own sandbox origin and block the base tag (default CSP base-uri 'self'), so make them absolute.
    const relativeSiteAsset = / ( [ "'`])\/images\//g;
    const js = rawJs.replace(relativeSiteAsset, '$1https://example.com/images/');
    if (/[" '`]\/images\//.test(inlined) || /url\(\s*["' ] ? \ / [ ^/ ] / . test ( css ) ) {
      throw new Error ( 'MCP App still references a root-relative site asset.' ) ;
    }
    

    The resource's CSP then allows images from our own domains only, and connectDomains is empty: the embedded app makes no network requests and never sees an access token.

  6. A router shim that caused an infinite render loop

    The games use our app's router, which doesn't exist inside the chat iframe, so the bundle swaps it for a small shim. The first version of the shim returned a new URLSearchParams object on every render. One game listed searchParams in a hook's dependency array, so every render produced a "new" dependency, re-ran the effect that shuffles the levels, and rendered again. Forever.

    The fix is the usual React rule for anything that ends up in a dependency array: return a stable reference. The UI test now counts DOM mutations per second for each game and fails above 200, which catches loops like this one.

  7. localStorage can be blocked

    Some games use localStorage so they don't repeat levels. Sandboxed hosts can block it, so the bundle falls back to in-memory storage for the session. Test the embedded UI with storage blocked and relative URLs failing, the way real hosts behave.

  8. Reviewers read descriptions and annotations together

    Two comments from the OpenAI review: Words like "free" and plan names in the listing description were flagged as pricing promotion. A tool annotated with readOnlyHint: true had a description that implied it saved data. It didn't (saving goes through separate tools that only the app can call), but the description had to say what the tool actually does. Annotations and descriptions are part of the contract, and they're checked against each other.

Bonus: strict pnpm on Cloudflare builds

We imported OAuth types from @supabase/auth-js, which is a dependency of @supabase/supabase-js, not of our app. Cloudflare's build installs with strict pnpm, where that import fails. Import from the package you actually depend on.

What I'd do again

Let the authorization server verify the token, then check client_id, iss, sub, aud and exp yourself, and fail closed. Return the 401 challenge both as a header and in the tool result's _meta. Build the embedded UI as if every relative URL and every storage API will fail, and test it that way. Write down every OAuth client, redirect URI and authentication method you register.

I wrote this with the help of an AI assistant, working from the project's commits, code and notes. The snippets come from the repository, trimmed for length, with our own URLs and IDs removed.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.