Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 38 additions & 8 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,7 @@ explicitly to one of `http`, `sse`, or `streamable-http`.
"oauth": {
"client_id": "your-client-id",
"client_secret": "secret-reference",
"redirect_uri": "http://localhost:8080/oauth/callback",
"redirect_uri": "http://127.0.0.1:54108/oauth/callback",
"scopes": ["repo", "user"],
"pkce_enabled": true
}
Expand All @@ -546,10 +546,13 @@ explicitly to one of `http`, `sse`, or `streamable-http`.

#### Pinning the callback port with `redirect_uri`

By default mcpproxy allocates a fresh loopback port for the OAuth callback on
every login. Some providers — notably GitHub OAuth Apps — require the callback
URL to match the registered one **exactly** and reject wildcards, so the port
must not move.
By default mcpproxy asks the OS for a free loopback port on the first OAuth
login, then persists that port and tries to reuse it. If the saved port is taken
next time, a different one is allocated — so the callback URL is not guaranteed
to stay put. Some providers require the port to match the registered callback
URL exactly, so it must not move at all. GitHub OAuth Apps are the common case:
even with GitHub's wildcard matching enabled, that matching covers subdomains
and subdirectory paths only — the host and port must still match exactly.

Set `redirect_uri` to pin it. mcpproxy then binds that exact port and sends that
exact string to the provider as `redirect_uri`:
Expand All @@ -565,13 +568,40 @@ exact string to the provider as `redirect_uri`:

The value must be an RFC 8252 loopback redirect: `http` scheme, a loopback host
(`127.0.0.1`, `localhost` or `::1`), an explicit port, and the
`/oauth/callback` path. A malformed value, or a pinned port that is already in
use, fails the login with an explicit error in the logs rather than silently
falling back to a random port. Register the same URL with the provider.
`/oauth/callback` path. Register the same URL with the provider.

Prefer `127.0.0.1`. `localhost` is accepted, and the string is sent to the
provider exactly as written, but the listener binds `127.0.0.1` — on a host
whose browser resolves `localhost` to `::1` without falling back, the redirect
would reach a closed port. Write `http://[::1]:PORT/oauth/callback` if you want
the IPv6 loopback; mcpproxy then binds `::1` itself.

A malformed value, or a pinned port that is already in use, fails the login with
an explicit error rather than silently falling back to a random port. The error
appears in three places:

- the connection error and the server's `health.detail` (it names
`oauth.redirect_uri` and the reason),
- `mcpproxy upstream logs <name>` (the per-server log), and
- the main log (`~/Library/Logs/mcpproxy/main.log` on macOS,
`~/.mcpproxy/logs/main.log` on Linux), under the `oauth` logger name.

A malformed value is also rejected up front by the write surfaces — the REST
config API (`POST /api/v1/config/validate`, `POST /api/v1/config/apply`,
`PATCH /api/v1/config`), the Web UI that calls them, and the MCP
`upstream_servers` tool. Hand-editing `mcp_config.json` bypasses that check by
design: a bad value already on disk must not stop the daemon from booting, so it
is reported at connect time instead.

When `redirect_uri` is not set, mcpproxy persists the port used by the first
successful login and reuses it for subsequent logins.

If the server previously logged in without a pin, its client registration was
issued through Dynamic Client Registration against that old port. Adding a
`redirect_uri` with a different port clears that registration automatically so
the next login re-registers against the pinned URL; a statically configured
`client_id` is never cleared.

See [OAuth Documentation](mcp-go-oauth.md) for complete details.

---
Expand Down
20 changes: 13 additions & 7 deletions docs/errors/MCPX_OAUTH_CALLBACK_MISMATCH.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,25 +35,31 @@ persisted port). Add that exact URI to your OAuth client's allowed redirect
URIs in the provider's developer console.

For most providers wildcards aren't allowed; you'll need to register the exact
port. mcpproxy persists the port in the upstream config — see
[`oauth_redirect_port`](../configuration/upstream-servers.md) — so you can
register a stable URI.
port. When `oauth.redirect_uri` is not set, mcpproxy allocates a loopback port
on the first login and persists it, reusing it on subsequent logins — so the
callback URL is usually stable, but it is not guaranteed if that port is taken
later.

### Re-pin the redirect port
### Pin the redirect URI

If you previously used a different port and want to restore it, set
`oauth_redirect_port` explicitly:
If the provider requires an exact callback URL, pin it with `oauth.redirect_uri`:

```json
{
"name": "my-server",
"oauth": {
"client_id": "...",
"redirect_port": 53412
"redirect_uri": "http://127.0.0.1:53412/oauth/callback"
}
}
```

mcpproxy binds that exact port and sends that exact string to the provider. The
value must be an RFC 8252 loopback redirect: `http` scheme, a loopback host, an
explicit port, and the `/oauth/callback` path. A malformed value, or a pinned
port already in use, fails the login with an explicit error naming
`redirect_uri` rather than falling back to a random port.

Then re-register that exact URI on the provider side.

### If a reverse proxy is in front
Expand Down
2 changes: 1 addition & 1 deletion docs/features/oauth-authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ OAuth authentication is used when connecting to MCP servers that require authori
|--------|------|-------------|
| `client_id` | string | OAuth client identifier (uses Dynamic Client Registration if empty) |
| `client_secret` | string | OAuth client secret (optional, can reference secure storage) |
| `redirect_uri` | string | OAuth redirect URI (auto-generated if not provided) |
| `redirect_uri` | string | Pins the loopback callback URL. Must be `http`, a loopback host, an explicit port and the `/oauth/callback` path (e.g. `http://127.0.0.1:54108/oauth/callback`); register the identical URL with the provider. Omit it to let mcpproxy allocate a port and persist it. See [Pinning the callback port](../configuration.md#pinning-the-callback-port-with-redirect_uri). |
| `scopes` | array | Requested OAuth scopes |
| `pkce_enabled` | boolean | PKCE is always enabled for security; this flag is currently ignored |
| `extra_params` | object | Additional authorization parameters (e.g., RFC 8707 resource) |
Expand Down
68 changes: 40 additions & 28 deletions docs/mcp-go-oauth.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ RFC 7591-compliant DCR enables MCP clients to self-register with authorization s

To prevent malicious registrations, MCP servers should require initial access tokens during registration, issued through out-of-band mechanisms. Metadata validation must enforce:
- Scope restrictions limiting client permissions
- Redirect URI pattern whitelisting
- Redirect URI pattern whitelisting
- Software statement assertions for authenticity

The `godoc-mcp` server exemplifies this by binding client registrations to PKCE-enhanced OAuth flows, ensuring only user-authorized agents gain access.
Expand All @@ -51,7 +51,7 @@ Post-registration, the client uses issued credentials for subsequent OAuth flows

For local callback servers, Go implementations should:
1. Bind to `localhost:0` to auto-assign ports
2. Pass the derived port to redirect URIs
2. Pass the derived port to redirect URIs
3. Handle OS port conflicts via retries

As RFC 8252 notes, servers must accept any loopback port, requiring MCP servers to validate URIs using pattern matching (e.g., `http://127.0.0.1:*`) rather than exact matches.
Expand Down Expand Up @@ -86,7 +86,7 @@ This dynamically assigns ports, passing the URI to OAuth requests while handling

RFC 8414 defines the `/.well-known/oauth-authorization-server` endpoint for disclosing OAuth configuration. MCP servers must publish:
- `authorization_endpoint`
- `token_endpoint`
- `token_endpoint`
- `registration_endpoint`
- `jwks_uri`

Expand Down Expand Up @@ -203,16 +203,28 @@ This enables runtime onboarding of AI agents.

**Problem**: Authorization servers reject dynamically generated URIs.

**Solution**:
- Configure auth servers with wildcard redirect patterns (`http://127.0.0.1:*`)
- Use Cloudflare Workers for fixed-domain callbacks
**Solution** depends on what the provider accepts:

- Providers that allow a loopback wildcard or prefix match (some self-hosted
authorization servers, and the pattern RFC 8252 §7.3 recommends) can register
`http://127.0.0.1:*` and let mcpproxy allocate a port per login.
- Providers that require an **exact** port. GitHub OAuth Apps are the common
case: GitHub's wildcard matching covers subdomains and subdirectory paths, but
the host and port must still match the registered callback exactly, and
`http://127.0.0.1:*` is not valid syntax there. For those, pin the port with the per-server
`oauth.redirect_uri` setting and register that exact string with the provider.
See [Pinning the callback port](configuration.md#pinning-the-callback-port-with-redirect_uri).
- Use Cloudflare Workers for fixed-domain callbacks.

**Go Code**:
**Go Code** (authorization-server side, only for servers that permit wildcards):
```go
// Auth server config
AllowedRedirectURIs: []string{"http://127.0.0.1:*", "http://[::1]:*"}
```

> Do not assume a wildcard registration will work against a public provider —
> verify it in that provider's developer console first.

### 7.2 Token Management Failures

**Problem**: Access token expiration disrupts MCP sessions.
Expand Down Expand Up @@ -292,19 +304,19 @@ func (m *CallbackServerManager) StartCallbackServer(serverName string) (*Callbac
if err != nil {
return nil, fmt.Errorf("failed to allocate dynamic port: %w", err)
}

// Extract port and create redirect URI
addr := listener.Addr().(*net.TCPAddr)
port := addr.Port
redirectURI := fmt.Sprintf("http://127.0.0.1:%d/oauth/callback", port)

// Create dedicated HTTP server for this callback
mux := http.NewServeMux()
server := &http.Server{
Addr: fmt.Sprintf("127.0.0.1:%d", port),
Handler: mux,
}

// Start server with proper callback handling
callbackServer := &CallbackServer{
Port: port,
Expand All @@ -313,13 +325,13 @@ func (m *CallbackServerManager) StartCallbackServer(serverName string) (*Callbac
CallbackChan: make(chan map[string]string, 1),
logger: m.logger.With(zap.String("server", serverName)),
}

// Set up callback handler
mux.HandleFunc("/oauth/callback", callbackServer.handleCallback)

// Start server on the allocated port
go server.Serve(listener)

return callbackServer, nil
}
```
Expand All @@ -333,7 +345,7 @@ func CreateOAuthConfig(serverConfig *config.ServerConfig) *client.OAuthConfig {
logger.Error("Failed to start OAuth callback server", zap.Error(err))
return nil
}

// Use the exact redirect URI in OAuth config
return &client.OAuthConfig{
ClientID: "", // Dynamic Client Registration
Expand All @@ -354,29 +366,29 @@ func (c *Client) handleOAuthFlow(oauthHandler *client.OAuthHandler) error {
if err := oauthHandler.RegisterClient(ctx, "mcpproxy-go"); err != nil {
return fmt.Errorf("DCR failed: %w", err)
}

// Step 2: Generate PKCE and state parameters
codeVerifier, _ := client.GenerateCodeVerifier()
codeChallenge := client.GenerateCodeChallenge(codeVerifier)
state, _ := client.GenerateState()

// Step 3: Get authorization URL (uses exact redirect URI from DCR)
authURL, _ := oauthHandler.GetAuthorizationURL(ctx, state, codeChallenge)

// Step 4: Open browser and wait for callback
openBrowser(authURL)

callbackServer, _ := oauth.GetGlobalCallbackManager().GetCallbackServer(c.config.Name)

// Step 5: Wait for authorization code on our callback server
select {
case authParams := <-callbackServer.CallbackChan:
// Step 6: Validate state and exchange code for tokens
if authParams["state"] != state {
return fmt.Errorf("OAuth state mismatch")
}
return oauthHandler.ProcessAuthorizationResponse(ctx,

return oauthHandler.ProcessAuthorizationResponse(ctx,
authParams["code"], state, codeVerifier)
case <-time.After(5 * time.Minute):
return fmt.Errorf("OAuth authorization timeout")
Expand Down Expand Up @@ -405,11 +417,11 @@ MCPProxy's implementation successfully handles:

**Example Log Output:**
```
2025-07-13T09:30:07.119 | INFO | OAuth callback server started successfully |
2025-07-13T09:30:07.119 | INFO | OAuth callback server started successfully |
{"server": "cloudflare_autorag", "redirect_uri": "http://127.0.0.1:64020/oauth/callback", "port": 64020}
2025-07-13T09:30:07.119 | INFO | Opening browser for OAuth authentication |
2025-07-13T09:30:07.119 | INFO | Opening browser for OAuth authentication |
{"auth_url": "https://autorag.mcp.cloudflare.com/oauth/authorize?...&redirect_uri=http%3A%2F%2F127.0.0.1%3A64020%2Foauth%2Fcallback..."}
2025-07-13T09:30:56.674 | INFO | OAuth callback received |
2025-07-13T09:30:56.674 | INFO | OAuth callback received |
{"params": {"code": "...", "state": "..."}}
2025-07-13T09:30:57.507 | INFO | OAuth authentication completed successfully
```
Expand All @@ -421,7 +433,7 @@ The integration of OAuth 2.1 with MCP servers in Go requires strict adherence to
### ✅ **Successfully Implemented Solutions**

1. **Redirect URI Exact Matching**: **SOLVED** through our Global Callback Server Manager with dynamic port allocation and perfect URI consistency
2. **RFC 8252 Compliance**: **ACHIEVED** with `127.0.0.1` loopback interface and OS-assigned ephemeral ports
2. **RFC 8252 Compliance**: **ACHIEVED** with `127.0.0.1` loopback interface and OS-assigned ephemeral ports
3. **PKCE Security**: **IMPLEMENTED** with mandatory PKCE-S256 for all OAuth flows
4. **Dynamic Client Registration**: **WORKING** seamlessly with Cloudflare and other OAuth providers
5. **Token Management**: **AUTOMATED** with refresh token handling and secure storage
Expand All @@ -430,7 +442,7 @@ The integration of OAuth 2.1 with MCP servers in Go requires strict adherence to

**For Cloudflare MCP OAuth** (and other strict providers):
- ✅ **Perfect URI matching** with callback server coordination
- ✅ **Zero port conflicts** through dedicated servers per OAuth flow
- ✅ **Zero port conflicts** through dedicated servers per OAuth flow
- ✅ **Automatic retry** post-OAuth for seamless MCP connection
- ✅ **Production-tested** with Cloudflare AutoRAG OAuth flows
- ✅ **RFC 8252 compliant** with enhanced security
Expand Down Expand Up @@ -459,8 +471,8 @@ MCPProxy's architecture enables future enhancements:

MCPProxy serves as a **reference implementation** for OAuth 2.1 with MCP servers, demonstrating:
- How to solve the critical redirect URI exact matching challenge
- Production-ready callback server coordination patterns
- Production-ready callback server coordination patterns
- Seamless integration with the `mcp-go` library's OAuth capabilities
- RFC 8252 compliance in real-world deployment scenarios

The patterns documented and implemented in MCPProxy establish **secure, scalable MCP-OAuth integrations** for Go-based AI agent ecosystems, successfully balancing user consent with operational security while meeting the strict requirements of modern OAuth providers like Cloudflare.
The patterns documented and implemented in MCPProxy establish **secure, scalable MCP-OAuth integrations** for Go-based AI agent ecosystems, successfully balancing user consent with operational security while meeting the strict requirements of modern OAuth providers like Cloudflare.
55 changes: 52 additions & 3 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2100,8 +2100,49 @@ func (v ValidationError) Error() string {
return fmt.Sprintf("%s: %s", v.Field, v.Message)
}

// ValidateDetailed performs detailed validation and returns all errors
// ValidateDetailed performs detailed validation and returns all errors.
//
// It is the shared gate for every *write* surface: the REST config API
// (POST /api/v1/config/validate, POST /api/v1/config/apply, PATCH /api/v1/config
// all funnel through Runtime.ValidateConfig / Runtime.ApplyConfig) and the MCP
// `upstream_servers` tool. Anything appended here is therefore rejected before
// it is persisted.
//
// The boot path is deliberately NOT this function — see Validate(), which runs
// validateDetailedCore() so that a pre-existing bad value on disk cannot brick
// a load that has nothing to do with the offending server.
func (c *Config) ValidateDetailed() []ValidationError {
return append(c.validateDetailedCore(), c.oauthRedirectURIErrors()...)
}

// oauthRedirectURIErrors reports every per-server `oauth.redirect_uri` that the
// loopback callback listener cannot honor.
//
// Kept separate from validateDetailedCore because the two callers want opposite
// behavior: a write surface must reject the value (it is a permanent connect
// failure otherwise, with an error that never names redirect_uri), while
// config.Load must tolerate one already on disk and let it fail loudly at
// connect time instead.
func (c *Config) oauthRedirectURIErrors() []ValidationError {
var errors []ValidationError
for i, server := range c.Servers {
if server == nil || server.OAuth == nil {
continue
}
if strings.TrimSpace(server.OAuth.RedirectURI) == "" {
continue
}
if _, _, err := ParseLoopbackRedirectURI(server.OAuth.RedirectURI); err != nil {
errors = append(errors, ValidationError{
Field: fmt.Sprintf("mcpServers[%d].oauth.redirect_uri", i),
Message: err.Error(),
})
}
}
return errors
}

func (c *Config) validateDetailedCore() []ValidationError {
var errors []ValidationError

// Validate listen address format
Expand Down Expand Up @@ -2482,8 +2523,16 @@ func (c *Config) Validate() error {
c.RoutingMode = RoutingModeRetrieveTools
}

// Then perform detailed validation
errors := c.ValidateDetailed()
// Then perform detailed validation.
//
// validateDetailedCore(), NOT ValidateDetailed(): a malformed per-server
// `oauth.redirect_uri` must not brick the boot. Failing the load would take
// every other server down with it over a field only one server uses, and the
// value is already surfaced loudly at connect time (internal/oauth returns an
// explicit "invalid oauth.redirect_uri for server X" error). The write
// surfaces reject it via ValidateDetailed() instead — that is where the
// operator is actually typing it.
errors := c.validateDetailedCore()
if len(errors) > 0 {
// Return first error for backward compatibility
return fmt.Errorf("%s", errors[0].Error())
Expand Down
Loading
Loading