Skip to main content

OAuth Authentication

MCPProxy supports OAuth 2.1 authentication with PKCE for secure authentication to remote MCP servers.

Overview​

OAuth authentication is used when connecting to MCP servers that require authorization, such as:

  • GitHub MCP servers
  • Enterprise API gateways
  • Third-party service integrations

Configuration​

Basic OAuth Setup​

{
"mcpServers": [
{
"name": "github-server",
"url": "https://api.github.com/mcp",
"protocol": "http",
"oauth": {
"client_id": "your-client-id",
"scopes": ["repo", "user"]
},
"enabled": true
}
]
}

OAuth Configuration Options​

OptionTypeDescription
client_idstringOAuth client identifier (uses Dynamic Client Registration if empty)
client_secretstringOAuth client secret (optional, can reference secure storage)
redirect_uristringPins the loopback callback URL. Must be http, a loopback host and an explicit port (e.g. http://127.0.0.1:54108/oauth/callback); the path can be anything the provider requires — a pin with no path at all binds /, not /oauth/callback (that remains the default only when redirect_uri is omitted entirely). Register the identical URL with the provider. Omit it to let mcpproxy allocate a port and persist it. See Pinning the callback port.
scopesarrayRequested OAuth scopes
pkce_enabledbooleanPKCE is always enabled for security; this flag is currently ignored
extra_paramsobjectAdditional authorization parameters (e.g., RFC 8707 resource)
skip_issuer_validationbooleanDefault false. Accepts a sign-in response whose RFC 9207 iss is wrong or missing, for a provider known to misreport it; such sign-ins are not protected against mix-up. See Which authorization server answered

Note: OAuth authorization and token endpoints are discovered by default from the server's OAuth metadata (RFC 8414 .well-known/oauth-authorization-server). They can be overridden explicitly with authorization_endpoint and token_endpoint (and registration_endpoint); if metadata discovery fails and both authorization and token overrides are set, MCPProxy builds the metadata from them.

Advanced Configuration​

For OAuth providers that require additional parameters (like RFC 8707 resource indicators):

{
"oauth": {
"client_id": "your-client-id",
"client_secret": "your-client-secret",
"scopes": ["read", "write"],
"extra_params": {
"audience": "https://api.example.com",
"resource": "https://api.example.com"
}
}
}

Viewing and editing a server's OAuth settings​

The server detail page's Configuration tab has an OAuth card for every HTTP/SSE server. It shows the configured block (the client secret is shown masked, or as its ${keyring:…} reference) and Edit / Configure opens a form for the client ID, secret, scopes, redirect URI and extra parameters, with the callback base URL, endpoint overrides, PKCE and the two policy switches under Advanced. The secret field is a password input with a Show toggle. Leave the masked secret as it is to keep it; clear the field to remove it. If you move an endpoint override to another host, type the secret again: the stored secret is never sent to a new host. With reveal_secret_headers: true the card (and GET /api/v1/servers) shows an admin the secret in clear. Fields you don't touch are saved exactly as stored. An extra parameter whose value has line breaks or leading or trailing spaces is shown as a JSON string (claims="{\n ...}"), and you can type one the same way.

Save never deletes the block: clearing every field saves an empty block, and turning a switch off saves it as false. An empty block is not the same as no block: it still makes the server use OAuth, and the card says so. To delete the block, use Remove settings, which asks you to confirm first.

Saving writes the whole block through PATCH /api/v1/servers/{name} (see the REST API). Changing anything but Refresh replay and Skip issuer validation signs the server out, and so does removing a block that holds anything else: its stored tokens and dynamic client registration are cleared, and you sign in again. An edit made in mcp_config.json while mcpproxy runs (or while it is stopped) is applied the same way when the file is reloaded.

Authentication Flow​

Initial Authentication​

  1. MCPProxy detects OAuth requirement on first connection
  2. Opens browser to authorization URL
  3. User completes authentication
  4. MCPProxy receives callback with authorization code
  5. Exchanges code for access token
  6. Stores the tokens in config.db in the data directory (encrypted when oauth_token_encryption_key is set)

What the callback accepts​

The provider sends you back to MCPProxy's callback address with the result of the sign-in in the query string. MCPProxy reads that query once and refuses it, before it exchanges a code or shows a result page, when:

  • code, state, iss or error appears more than once;
  • both code and error are present, or neither is;
  • code or error is present but empty;
  • state is missing or empty;
  • the query cannot be parsed (a bad % escape, ; used as a separator).

Nothing is signed in, and a refused response does not cancel the sign-in: if the provider then sends a correct response for the same sign-in, it still completes. What the browser shows depends on the callback:

  • the local callback shows Authorization Failed ("The sign-in response was malformed (…)", naming the rule);
  • the callback behind a remote Web UI (oauth.callback_base_url) answers a plain HTTP 400 invalid OAuth callback;
  • in the server edition, the brokered credential connect callback redirects to the Web UI with connect_failed.

Which authorization server answered (RFC 9207 iss)​

When MCPProxy builds the authorization URL it records the issuer of the authorization server metadata that URL came from, and whether that metadata says the server always sends iss (authorization_response_iss_parameter_supported). When the browser comes back, the callback compares the response's iss with that record before the page is chosen and before anything is exchanged. This covers the local and the remote (oauth.callback_base_url) callback; the server edition's brokered credential connect callback does not check iss yet:

ResponseResult
iss equal to the recorded issuer (exact match)accepted
iss names another issuer, or is present and emptyrefused
no iss, and the metadata advertises itrefused
no iss, and the metadata does not advertise itaccepted; this sign-in is not protected against mix-up

A refused response shows Authorization Failed ("The sign-in response could not be confirmed as coming from the expected authorization server"), names the expected server by its origin only, and is reported as MCPX_OAUTH_ISSUER_MISMATCH. The authorization code is never sent to the token endpoint. An error response (error=...) gets the same check first, so a refused one is reported as the issuer mismatch, not as the provider's error. The value the response carried is never shown, only logged after scrubbing.

The same rules apply when oauth.auth_server_metadata_url is configured: the recorded issuer is the issuer in that document. When endpoint overrides make MCPProxy serve metadata built from them (the real document could not be fetched), the overrides are the trust anchor and any iss is accepted, with a warning in the log when it differs.

For a provider that is known to send a wrong iss, or to advertise iss and then omit it, the check can be turned off for that one server:

{
"name": "legacy-provider",
"url": "https://mcp.legacy.example/mcp",
"oauth": { "skip_issuer_validation": true }
}

With it on, a wrong iss, or a missing one the metadata advertises, is accepted with a warning, and the sign-in is not protected against mix-up. The strict parse above is still applied. Changing the setting does not sign the server out.

The issuer of metadata that mcpproxy discovers is not yet checked against the address it was discovered from, and stored tokens are not yet bound to their issuer; both follow in later changes (#2044).

Client registration type​

When MCPProxy registers itself with Dynamic Client Registration it sends application_type (OpenID Connect Dynamic Client Registration 1.0, section 2):

Redirect URIapplication_type
http:// on a loopback host: any 127.x.x.x address, [::1] or localhostnative
anything else, including https://127.0.0.1 and a oauth.callback_base_url addressweb

native tells an OpenID provider that a loopback redirect URI is expected; a provider that assumes web may refuse one. A provider that refuses the field gets no second registration without it; the sign-in fails with the provider's error.

Reused client registrations​

When a server has no static oauth.client_id, MCPProxy registers a client with Dynamic Client Registration on the first sign-in and reuses that client_id on later sign-ins. Some providers delete these registrations after a while (Cloudflare's MCP servers do). The provider then answers the authorization URL with HTTP 400 {"error":"invalid_request","error_description":"Invalid client_id"} and never redirects back to MCPProxy.

Before handing out an authorization URL that uses a reused registration, MCPProxy sends one request to that URL (no redirects followed, 5 s timeout). If the response says the client is unknown (invalid_client, or invalid_request with a description such as "Invalid client_id" or "Client not found"), MCPProxy:

  1. clears the stored registration, but only if it still holds that same client_id (if another sign-in has already replaced it, this sign-in stops and asks you to sign in again rather than registering yet another client);
  2. registers a new client once and stores it, unless another sign-in stored one in the meantime (then this sign-in stops and asks you to sign in again). A rejected registration that had a client_secret is removed and you are asked to sign in again, so the new client is registered without the old secret;
  3. builds the authorization URL again with the new client_id.

If the provider also rejects the new client, sign-in stops with an error instead of registering again; configure a static oauth.client_id in that case. A static oauth.client_id, a client registered during the same sign-in, and a client_id set through oauth.extra_params are never checked or cleared. If the check itself fails (network error, timeout, 5xx, a redirect, a login page or an unrecognised error), sign-in continues as before.

Token Refresh​

MCPProxy automatically refreshes tokens before expiration:

  1. Checks token expiration before each request
  2. Uses refresh token to get new access token
  3. Falls back to browser re-authentication if refresh fails

Refreshes are serialized per server. Whether a refresh is triggered by a request that finds the token about to expire or by the background refresh schedule, at most one refresh request is sent to the authorization server per expiry; every caller waiting at that moment receives the same new token (or the same error). This matters for providers that rotate refresh tokens and revoke the whole grant when an old refresh token is reused. A scheduled refresh that fires within 5 seconds of a token being saved (by another refresh or a sign-in) uses that token instead of rotating it again.

Refresh failures are classified from the RFC 6749 §5.2 error code and the HTTP status of the token endpoint response:

ResponseBehaviour
invalid_grantStops retrying; sign in again.
invalid_client, dynamically registered clientThe stored client registration is cleared; sign in again to register a new client. If the provider rejects the new registration too, configure a static oauth.client_id.
invalid_client, static oauth.client_idStops retrying; fix oauth.client_id / oauth.client_secret.
unauthorized_client, unsupported_grant_type, invalid_scopeStops retrying; the code is shown in the error.
server_error, temporarily_unavailable, HTTP 5xx or 429, network errorsRetried with exponential backoff (10 s doubling to 5 min).
Anything elseRetried with backoff, then marked failed after the retry limit.

The mcpproxy_oauth_refresh_total metric labels these as failed_invalid_grant, failed_invalid_client, failed_server_error, failed_network, failed_server_gone and failed_other.

Signing in from the Web UI​

When an OAuth-protected server has no usable token, the Web UI does not render it as a generic red "Server Error". Instead it surfaces a calm, actionable Sign-in state:

  • The server's status chip reads an amber "Sign-in required" (rather than a red "Disconnected"/"Unhealthy"), on both the Servers list and the server detail page.
  • The server detail page shows a calm amber "🔑 Sign in to {server}" panel with a primary Log in button (it triggers the same browser OAuth flow as mcpproxy auth login) and a link to this page. No "file a bug" prompt is shown for OAuth states — signing in is the fix.
  • If a prior session expired or was revoked, the panel keeps an error tone and leads with a Re-login button.
  • A server can be both quarantined and login-required: you may sign in while it is quarantined, but its tools stay blocked until you Approve the server. The panel makes both gates explicit.

Switching accounts and retrying sign-in​

To switch accounts or recover an OAuth error, use Sign in again in the server card’s More actions menu or the detail page’s Actions menu. For an OAuth-capable upstream this remains available during reconnect attempts and generic timeout errors, even when the health panel does not suggest login. After logout it is labelled Sign in. Select the intended account/workspace at the provider; if the provider reuses its own browser session, switch that account before starting sign-in again.

CLI Commands​

Start Authentication​

mcpproxy auth login --server=github-server

Check Status​

mcpproxy auth status

Debug Authentication​

mcpproxy auth login --server=github-server --log-level=debug

RFC 8707 Resource Parameter​

MCPProxy supports automatic RFC 8707 resource parameter detection for OAuth providers that require it:

{
"oauth": {
"client_id": "your-client-id",
"extra_params": {
"resource": "https://api.example.com"
}
}
}

For providers like Runlayer, MCPProxy can auto-detect the resource parameter from the server's OAuth metadata.

Token Storage​

MCPProxy stores upstream OAuth credentials in the oauth_tokens bucket of config.db in the data directory (default ~/.mcpproxy/). For each server that is stored: the access token, the refresh token, and the client secret from dynamic client registration (DCR), if there is one.

By default these values are not encrypted, and they are never kept in the operating system keyring. They are stored as readable JSON. What protects them is file permissions: on macOS and Linux the data directory is created 0700 and config.db 0600 (POSIX creation modes; tightening an already-existing file is best-effort and a failure is only logged), so other users cannot read them. On Windows these mode bits have no meaning, and protection is the ACL of the data directory, which it inherits from its parent: the user profile for the default location. A custom data directory (--data-dir, data_dir) gets whatever ACL its location has, so secure it yourself. Anyone or anything that can read config.db as that user, or that obtains a copy of the file (a backup, a disk or VM snapshot), can read the tokens. This includes a stdio upstream server that runs outside Docker isolation, because it runs as the same user.

With oauth_token_encryption_key set, the rows are encrypted with AES-256-GCM. A copy of config.db made without the key yields no tokens only after the startup migration has encrypted the existing rows and the database file has been compacted (otherwise old plaintext pages remain in the file), and not for any row the migration skipped (a row that is not a valid token record, or is larger than 1 MiB, is logged and left as it was). This does not protect against a process running as the same user as mcpproxy, which can read the key from the same place. See OAuth Token Encryption for key delivery, the threat model and recovery.

The system keyring is used only for secrets you reference from configuration with ${keyring:NAME} (see Keyring Integration); it is not used for upstream OAuth tokens.

Error Handling​

MCPProxy provides structured error responses for OAuth failures, making it easier to diagnose and fix authentication issues.

Error Types​

Error TypeDescriptionCommon Causes
client_id_requiredOAuth client ID is missingServer requires pre-registered client, DCR not supported
dcr_failedDynamic Client Registration failedServer rejected registration, permission denied
metadata_discovery_failedCould not discover OAuth metadataServer unreachable, missing .well-known endpoints
code_flow_failedAuthorization code flow failedUser denied, invalid redirect, network issues

CLI Error Output​

When OAuth fails, the CLI displays rich error information:

❌ OAuth Error: dcr_failed

Server: github-server
Message: Dynamic Client Registration failed: 403 Forbidden
Suggestion: Check if the OAuth server requires pre-registered clients

🔍 Debug:
Server logs: mcpproxy upstream logs github-server
Activity log: mcpproxy activity list --request-id req-xyz-123
Request ID: req-xyz-123
Correlation ID: a1b2c3d4e5f6789012345678

API Error Response​

The REST API returns structured OAuthFlowError responses:

{
"success": false,
"error_type": "dcr_failed",
"server_name": "github-server",
"message": "Dynamic Client Registration failed: 403 Forbidden",
"suggestion": "Check if the OAuth server requires pre-registered clients",
"correlation_id": "a1b2c3d4e5f6789012345678",
"request_id": "req-xyz-123",
"details": {
"metadata": {
"status": "ok",
"protected_resource_url": "https://api.example.com/.well-known/oauth-protected-resource"
},
"dcr": {
"attempted": true,
"status": "failed",
"error": "403 Forbidden"
}
}
}

Log Correlation​

Use the request_id from error responses to find related logs:

# Find activity records for a specific request
mcpproxy activity list --request-id req-xyz-123

# View server-specific logs
mcpproxy upstream logs github-server --tail 50

Troubleshooting​

Signing in through a remote Web UI​

When MCPProxy runs on a headless host, the Web UI opens the authorization URL in the browser where you clicked Log in. A blocked popup leaves a clickable sign-in link; the proxy's API key is never placed in that URL.

OAuth's default loopback callback reaches the browser's machine, which may be different from the proxy host. To finish sign-in without an SSH port forward, serve MCPProxy's HTTP listener through an HTTPS reverse proxy (including Tailscale Serve), and set the upstream's oauth.callback_base_url to that external origin:

{
"name": "linear",
"url": "https://mcp.linear.app/mcp",
"protocol": "http",
"oauth": {
"callback_base_url": "https://proxy.example.ts.net:8447"
}
}

The provider receives https://proxy.example.ts.net:8447/oauth/callback/linear as its redirect URI. Forward that path to the main MCPProxy HTTP listener, just like /ui/ and /api/. Static OAuth clients must register this exact callback URL with their provider; dynamically registered clients are re-registered when their saved redirect URI changes. The provider must permit HTTPS callbacks.

callback_base_url accepts an HTTPS origin with no credentials, path, query or fragment. It is explicit configuration, never inferred from request headers. Only upstreams opting into it accept remote callbacks, validated against their existing single-use state and PKCE flow. The callback needs no API key and does not start an OAuth flow; missing, expired, reused and cross-server states fail. Callback responses disable caching and referrer disclosure.

Leave HEADLESS=true on a remote host: the Web UI opens the user's browser; turning off headless mode only attempts to open a browser on the proxy host. Without callback_base_url, loopback callbacks behave as before. A configured redirect_uri continues to pin the private loopback listener; the external callback takes precedence for provider registration and token exchange.

The browser says the sign-in response was malformed​

The local callback page reports Authorization Failed with "The sign-in response was malformed (…)" (a remote callback answers HTTP 400 invalid OAuth callback) when the provider's redirect broke one of the rules in What the callback accepts; the text in parentheses names the rule, for example repeated iss parameter. MCPProxy did not exchange anything. Start the login again; if the provider keeps sending such a response, report it to the provider, since a repeated or conflicting parameter is not a valid OAuth authorization response.

The browser says the sign-in response could not be confirmed​

The callback page reports Authorization Failed with "The sign-in response could not be confirmed as coming from the expected authorization server" when the response's iss did not match the authorization server the sign-in started with (see Which authorization server answered). Nothing was exchanged or stored. Start the sign-in again. If it fails every time, see MCPX_OAUTH_ISSUER_MISMATCH.

The browser says the sign-in was invalidated​

The callback page reports Authorization Failed with "This sign-in was invalidated before it could finish: the server's connection was retired (restarted, replaced, removed or quarantined) while the sign-in was in progress" when the upstream's instance was torn down between the moment you started the login and the moment the provider redirected back. The code it delivered belongs to a flow that no longer exists, so nothing was signed in; start the login again and approve it.

Two background paths used to cause this on their own (GH #1722) and no longer do:

  • A security scan (the admission scan, the informational rescan after a tool change, or a manual scan) does not restart a server that is waiting on your OAuth login — a login flow in flight, or a server parked in Pending Auth — because the restart would retire the pending flow. The scan runs with what it can export without a reconnect and logs Server is waiting on an OAuth login; scanning without reconnecting it.
  • A new server starts quarantined with a temporary review connection. That connection window is held open while a login for the server is in flight (it is extended in 5-minute steps and outlives the login by at most that grace), and a later, shorter grant never cuts an earlier one short. The log line is Inspection exemption held: an OAuth login for the server is in flight.

An operator action that retires the instance during the login — removing or restarting the server by hand, or quarantining it — still invalidates the flow; the page above is how you learn about it.

Browser Doesn't Open​

# Run in headless mode with manual URL copy
HEADLESS=true mcpproxy auth login --server=github-server

Token Refresh Fails​

  1. Check token expiration in auth status
  2. Verify refresh token is stored
  3. Re-authenticate if needed

Invalid Scope Errors​

Verify the requested scopes are valid for the OAuth provider:

mcpproxy auth login --server=github-server --log-level=debug

Connection Errors​

Ensure the OAuth server URLs are accessible:

curl -I https://auth.example.com/.well-known/oauth-authorization-server

Security Best Practices​

  1. Use PKCE: MCPProxy uses PKCE by default for public clients
  2. Minimal Scopes: Request only necessary permissions
  3. Token Storage: Tokens are stored as readable JSON in config.db, protected only by file permissions (0600/0700 creation modes on macOS and Linux, best-effort on existing files; the data directory's inherited ACL on Windows); keep the data directory and any backups of config.db private; set oauth_token_encryption_key to encrypt them (same-user processes can still read the key; a copy of config.db is protected only after migration and compaction, see that page)
  4. Callback Security: Uses dynamic port allocation to prevent port conflicts