Skip to main content

MCP OAuth and dynamic client registration

OAuth shows up on both sides of the MCP gateway. Upstream, many hosted MCP servers want an OAuth token rather than a static key, and the gateway can hold the client identity, run the sign-in for each user, or mint a machine token. Downstream, MCP clients that only speak OAuth, such as desktop assistants and MCP inspectors, can treat the gateway as their authorization server, register themselves and sign in through the gateway's own login, so nobody pastes a virtual key into a desktop client.

A real-world scenario​

A product team wants its assistant to read Linear issues. Linear's hosted MCP server uses OAuth, and each person should only see the issues they can see in Linear. The admin registers the Linear server with auth_type: oauth2 and the interactive flow. Each developer clicks Connect on the server card once, signs in to Linear in the browser, and the gateway stores that person's token. From then on the developer's assistant reads Linear as that developer, the token is refreshed by the gateway before it expires, and when the developer leaves, revoking their stored credential cuts the access.

Connect to an OAuth server upstream​

  1. In the Admin UI, open MCP Servers, click + Add New MCP Server, pick the connector or + Custom Server, and set Authentication to OAuth. Keep OAuth Flow Type at Interactive (PKCE) for one token per user, or choose Machine-to-Machine (M2M) with a Client ID, Client Secret and Token URL for one token shared by every caller. Leave the client fields blank when the server supports dynamic client registration.

  2. Click Authorize & Fetch Token. The browser runs the sign-in and the form lists the server's tools once the token is back. Click Add MCP Server.

  3. Or register it with the API:

    curl -X POST http://localhost:4000/v1/mcp/server \
    -H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
    -d '{
    "server_name": "linear",
    "url": "https://mcp.linear.app/mcp",
    "transport": "http",
    "auth_type": "oauth2",
    "issuer": "https://auth.linear.app",
    "credentials": {"client_id": "os.environ/LINEAR_CLIENT_ID", "client_secret": "os.environ/LINEAR_CLIENT_SECRET", "scopes": ["read", "write"]}
    }'

    Expected result, with status 201, is the stored server with auth_type oauth2 and the client secret masked.

  4. Each user connects once. On MCP Servers the card shows Connect, which opens the sign-in in the browser. Afterwards the card reads Connected, and GET /v1/mcp/server/{server_id}/oauth-user-credential/status answers this for that user:

    {"server_id": "8f1c2d3e-4b5a-4c6d-9e7f-0a1b2c3d4e5f", "has_credential": true, "expires_at": "2026-11-23T10:00:00Z", "is_expired": false, "connected_at": "2026-11-23T09:00:00Z"}

The same server in config.yaml:

mcp_servers:
linear:
url: https://mcp.linear.app/mcp
transport: http
auth_type: oauth2
issuer: https://auth.linear.app
credentials:
client_id: os.environ/LINEAR_CLIENT_ID
client_secret: os.environ/LINEAR_CLIENT_SECRET
scopes: ["read", "write"]
FieldMeaning
issuer, authorization_url, token_url, registration_urlOAuth endpoints. When only issuer or url is set the gateway discovers the rest from the server's protected resource and authorization server metadata.
credentials.client_id, credentials.client_secret, credentials.scopesThe gateway's client identity. client_secret may be omitted when the gateway registers itself dynamically.
credentials.token_endpoint_auth_methodclient_secret_basic or client_secret_post.
credentials.client_private_key, client_private_key_id, client_assertion_signing_algUse a signed client assertion instead of a secret.
credentials.redirect_urisRedirect URIs to register with the authorization server.
oauth2_flowauthorization_code (the default, one token per user) or client_credentials (one machine token for every caller). Machine to machine use must be opted into explicitly, having a client id and secret is not enough.
delegate_auth_to_upstreamLegacy flag for oauth2 servers that lets the upstream server own authentication while the gateway still admits the call. Prefer auth_type: oauth_delegate.
per_server_oauth_discoveryAdvertise this server's own OAuth relay in discovery instead of the aggregate gateway authorization server.
oauth_identity_bindingChecks that a person's upstream token really belongs to that person before the gateway stores or uses it, see OAuth identity binding. Requires gateway managed per-user tokens.

With the authorization code flow each user authorises the server once. The Admin UI and the Chat UI start the flow at GET /v1/mcp/server/oauth/{server_id}/authorize, the gateway completes it at /callback, exchanges the code at POST /v1/mcp/server/oauth/{server_id}/token and stores the token for that user. Refresh happens at egress, MCP_PER_USER_TOKEN_EXPIRY_BUFFER_SECONDS (60 by default) before the token expires, coordinated through Redis when several instances run so only one of them refreshes a given token. See per-user credentials for the routes that inspect and delete stored tokens. With client_credentials the gateway fetches a token for the server itself and caches it until it expires.

The /v1/mcp/server/oauth/{server_id}/authorize, /callback, /token and /register routes are used by the Admin UI and the Chat UI while a person connects. They are not part of the published API and you never call them yourself. If a server has no client id and the authorization server offers no registration, they answer 400 missing_client_id with "No client_id available for this MCP server. Either configure the server with a client_id or supply one in the request.".

OAuth identity binding​

Identity binding stops one person from storing or using another person's upstream token. When it is on, the gateway checks the OpenID id_token the upstream returns, its signature, issuer, audience and expiry, and compares the person it names with the person signed in to the gateway before the token is stored or sent upstream.

FieldDefaultMeaning
modedisableddisabled does no check. audit checks and logs a mismatch but lets the token through, which is how you try it out. enforce refuses a mismatch with 403 oauth_principal_mismatch and also turns off the direct POST /v1/mcp/server/{server_id}/oauth-user-credential, because that route cannot check whose token it gets.
issuernone, requiredThe OpenID issuer whose id_token the upstream returns.
jwks_urldiscovered from the issuerWhere the issuer's signing keys are.
audiencesnone, at least oneThe audiences the id_token may carry.
principal_claimemailThe id_token claim that names the person.
caller_fielduser_emailWhat the claim is compared with on the gateway side, user_email or user_id.
require_email_verifiedtrueRefuse an id_token whose email_verified is not true.
mcp_servers:
linear:
url: https://mcp.linear.app/mcp
auth_type: oauth2
oauth_identity_binding:
mode: enforce
issuer: https://accounts.example.com
audiences: ["spanway-linear"]

The setting lives in config.yaml or the server's JSON through the API. The Admin UI server form has no control for it yet.

Dynamic client registration upstream​

When a server's authorization server offers dynamic client registration and no client id is configured, the gateway registers itself at registration_url the first time it needs a token and stores the resulting client in the database next to the server. If the authorization server advertises support for client id metadata documents instead, the gateway identifies itself with its own public metadata document, served at a fixed path under PROXY_BASE_URL. general_settings.mcp_prefer_client_id_metadata_document: true prefers the metadata document even when dynamic registration is also offered. Both need a public PROXY_BASE_URL the authorization server can reach.

Token exchange and identity assertion​

auth_type: oauth2_token_exchange swaps the caller's own bearer token for an upstream token at token_exchange_endpoint (RFC 8693) using audience, subject_token_type and token_exchange_profile. auth_type: oauth2_id_jag performs an identity assertion grant against id_jag_resource_token_endpoint for id_jag_resource. auth_type: true_passthrough forwards the client's x-mcp-auth header unchanged, and auth_type: oauth_delegate forwards the caller's bearer token as the upstream credential. For the two forwarded token modes dcr_bridge: true makes the gateway serve the OAuth front door for the server (metadata, register, authorize and token relays) instead of relaying the upstream's discovery verbatim, which is the Gateway-hosted sign-in (DCR bridge) switch of the server form. dcr_bridge is rejected on every other auth type.

Forwarding OAuth for plain servers​

A server with no auth_type whose extra_headers includes Authorization can set oauth_passthrough: true. The gateway then proxies the upstream /.well-known/oauth-protected-resource document, answers an unauthenticated call with a standard 401 challenge, and passes upstream 401 and 403 responses back to the client instead of swallowing them.

Gateway hosted authorization server​

An OAuth only client pointed at /mcp walks the gateway's own flow and never sees a virtual key.

  1. In the client, add the gateway's MCP address, https://gateway.example.com/mcp, with no key. The client fetches GET /.well-known/oauth-protected-resource/mcp and learns that the gateway is its authorization server.

  2. The client registers itself:

    curl -X POST https://gateway.example.com/register \
    -H "Content-Type: application/json" \
    -d '{"client_name": "Local MCP inspector", "redirect_uris": ["http://127.0.0.1:52341/callback"], "grant_types": ["authorization_code", "refresh_token"], "response_types": ["code"], "token_endpoint_auth_method": "none"}'

    Expected result, with status 201:

    {"client_id": "llm_dcrc_eyJyZWRpcmVjdF91cmlzIjpbImh0dHA6Ly8xMjcuMC4wLjE6NTIzNDEvY2FsbGJhY2siXX0", "client_id_issued_at": 1763888400, "redirect_uris": ["http://127.0.0.1:52341/callback"], "token_endpoint_auth_method": "none", "grant_types": ["authorization_code", "refresh_token"], "response_types": ["code"]}

    The client_id is sealed by the gateway and carries the redirect URIs, so nothing is stored. A redirect URI that is not https, http on a loopback host or a registered native callback answers 400 invalid_redirect_uri.

  3. The client opens GET /authorize in the browser. The person signs in through the gateway's normal login, lands on the connect page, authorises the servers they want and clicks through. The browser returns to the client with a short lived code.

  4. The client exchanges the code at POST /token and receives an access token, a refresh token and expires_in. It now connects to /mcp with that access token and sees the servers the signed-in user may use. On MCP Servers, the Live Connections tab shows the session under that user.

StepRouteWhat happens
DiscoveryGET /.well-known/oauth-protected-resource/mcp, GET /.well-known/oauth-authorization-server/mcpThe gateway names itself as the authorization server for the aggregate endpoint. Per-server variants exist under /mcp/{server_name} and /{server_name}/mcp.
RegistrationPOST /registerStateless dynamic client registration. The returned client_id seals the client's redirect URIs, nothing is stored, and clients are always public with PKCE S256 required.
AuthorizationGET /authorizeValidates the client and redirect URI, then sends the browser through the gateway login (/sso/key/generate with a same origin return path). Once signed in the user lands on the connect page and authorises individual servers, whose tokens are vaulted server side.
CompletionPOST /authorize/completeA deliberate POST bound to a same site flow cookie mints a short lived single use authorization code and redirects to the client.
TokenPOST /tokenExchanges the code, PKCE verified, for identity only session tokens. The refresh_token grant rotates the pair after re-checking that the user is still active.
Revocation and introspectionPOST /revoke, POST /introspectStandard RFC 7009 and RFC 7662 endpoints for the tokens the gateway issued.
KeysGET /.well-known/jwks.json, GET /.well-known/openid-configurationPublic keys for tokens the gateway signs, also used by the JWT signer guardrail.

Upstream server credentials never appear in this flow. They are vaulted per user by the /v1/mcp/server/oauth routes and resolved at egress by user id, so a session token proves who the user is and the gateway decides what they may reach.

Session token signing​

By default the session tokens this authorization server issues are signed with HS256 and a key derived from master_key. Set general_settings.mcp_session_token_signing to sign them with your own RSA key instead, so other services can check them with the public keys at /.well-known/jwks.json.

general_settings:
mcp_session_token_signing:
algorithm: RS256
kid: mcp-2026-11
private_key: os.environ/MCP_SESSION_SIGNING_KEY
previous_public_keys:
- kid: mcp-2026-05
public_key: os.environ/MCP_SESSION_SIGNING_KEY_PREVIOUS_PUBLIC

To rotate, move the current public key into previous_public_keys with its kid, set the new kid and private_key, and restart. Tokens signed with the old key keep working until they expire. A block that cannot be loaded, for example a reference that does not resolve or a key that is not an RSA PEM, makes /mcp answer 500 "Server misconfigured: mcp_session_token_signing is invalid" instead of falling back to HS256.

general_settings.use_x_forwarded_for with trusted_proxy_ranges tells the OAuth routes which X-Forwarded-* headers to trust when building redirect and metadata URLs behind a load balancer. The older mcp_trusted_proxy_ranges is still read, and when both are set only proxies inside both lists are trusted, so adding a wider trusted_proxy_ranges on upgrade never widens what MCP trusts.

OAuth routes​

{{ops:^/v1/mcp/server/oauth/session$|^/{mcp_server_name}/(authorize|register|token)$|^/authorize/mcp-session$|^/.well-known/(oauth-authorization-server|oauth-protected-resource|openid-configuration)}}

POST /v1/mcp/server/oauth/session caches a server definition in memory for about five minutes without writing it to the database, which the Admin UI uses to run an OAuth flow against a server before saving it.

Troubleshoot which credential was sent​

Send x-spanway-mcp-debug: true with an MCP request and the gateway answers with masked diagnostic headers that say which credential it used. Values are always masked.

curl -s -D - -o /dev/null https://gateway.example.com/mcp/linear \
-H "Authorization: Bearer $SPANWAY_API_KEY" -H "x-spanway-mcp-debug: true" \
-H "Content-Type: application/json" -d '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}'
HeaderWhat it tells you
x-mcp-debug-inbound-authWhich auth headers arrived and how the gateway read them, masked.
x-mcp-debug-oauth2-tokenThe OAuth token taken from Authorization, masked, (none), or SAME_AS_SPANWAY_KEY when the gateway key would have leaked upstream.
x-mcp-debug-auth-resolutionWhich credential went upstream: stored-user-token, m2m-client-credentials, token-exchange, id-jag, oauth2-passthrough, static-token, per-request-header, aws-sigv4, extra-headers, no-auth, or resolution-failed when the lookup failed.
x-mcp-debug-auth-resolutionsFor several servers, a JSON map of server id to the label above, at most 32 entries.

Errors​

StatusWhereMeaningFix
Card badge OAuth flow not setMCP ServersAn oauth2 server was never given a flow, so the gateway falls back to interactive per-user sign-in.Open the server, choose an OAuth Flow Type and save.
"Authentication required" with AuthorizeMCP Tools tabYou have no stored token for this interactive server, or the gateway rejected it.Click Authorize and sign in.
400, message naming token_url or authorization_urlPUT /v1/mcp/serverAn OAuth endpoint changed while the client secret was left out or sent masked.Enter the secret again in the same save.
422 "dcr_bridge is only supported for auth_type true_passthrough or oauth_delegate ..."POST /v1/mcp/server, or PUT with auth_typedcr_bridge is only valid with true_passthrough and oauth_delegate. A PUT that leaves out auth_type answers 400 with the same message.Remove it, or switch the auth type.
422 "per_server_oauth_discovery is only supported for auth_type oauth2 with oauth2_flow authorization_code and without delegate_auth_to_upstream."POST /v1/mcp/server, or PUT with auth_typePer-server discovery only works for interactive OAuth servers. A partial PUT answers 400.Remove it, or use oauth2 with authorization_code.
400 missing_client_idAdmin UI connectThe server has no client id and the authorization server offers no registration.Set credentials.client_id on the server.
403 oauth_identity_binding_enforcedPOST /v1/mcp/server/{server_id}/oauth-user-credentialThe server enforces identity binding, so a token cannot be stored directly.Connect through the gateway's OAuth flow.
403 oauth_principal_mismatchToken relay, /mcpWith identity binding on enforce, the upstream token belongs to a different person than the one signed in.Sign in upstream with your own account.
403 oauth_identity_binding_failedToken relayThe gateway could not check the identity, for example the id_token was missing or did not validate.Check issuer, audiences and jwks_url in oauth_identity_binding.
500 with the resolver's message/mcp, /mcp-rest/tools/callThe server's credential settings cannot be used, for example a token exchange setting is missing, or the auth mode is not supported.Fix the server's auth settings.
503 with the resolver's message/mcp, /mcp-rest/tools/callThe identity provider or token endpoint could not be reached.Check the network path to the token endpoint and retry.
412 or 501 with the resolver's message/mcp, /mcp-rest/tools/callA precondition for the credential is missing, or the auth mode is not available on this gateway.Follow the message.
500 "Server misconfigured: mcp_session_token_signing is invalid"/mcpThe session token signing block cannot be loaded.Fix the key or reference.
401 with WWW-Authenticate/mcpThe client sent no token or an expired one. This is the normal start of the OAuth flow.Let the client run discovery and sign in.
403 after a token exchangeUpstream serverA Token Validation Rules check failed.Review the rules on the server's Settings tab.
invalid_grant from POST /tokenGateway authorization serverThe code expired, was used already, or the PKCE verifier does not match.Start the flow again in the client.
403 You can only create temporary mcp servers if you are a PROXY_ADMIN.POST /v1/mcp/server/oauth/sessionThe key is not a proxy admin key.Use an admin key.

Logs​

LevelLineWhat it meansAction
WARNINGOAuth credential storage not authorized ...A token arrived for a person who may not use that server, so it was not stored.None unless it repeats for someone who should have access.
WARNINGexchange_token_with_server: could not resolve a Spanway user_id ... was NOT storedThe gateway could not tell who completed the sign-in, so the token was dropped.Ask the person to sign in to the gateway and connect again.

The log reference lists these with the other MCP lines.