Skip to content

feat: Make OAuth callback URIs configurable #585

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,37 @@ The MCP Inspector supports the following configuration settings. To change them,

These settings can be adjusted in real-time through the UI and will persist across sessions.

#### OAuth Callback Configuration

The MCP Inspector supports configurable OAuth callback URLs through environment variables. This allows you to run the inspector with custom OAuth callback endpoints that OAuth providers can redirect to:

| Environment Variable | Description | Default |
| ------------------------------------ | --------------------------------------------------- | ----------------------------------------------- |
| `OAUTH_MCP_INSPECTOR_CALLBACK` | OAuth callback URL for standard authentication flow | `{window.location.origin}/oauth/callback` |
| `OAUTH_MCP_INSPECTOR_DEBUG_CALLBACK` | OAuth callback URL for debug authentication flow | `{window.location.origin}/oauth/callback/debug` |

**How it works:**
1. MCP Inspector automatically starts HTTP servers on the ports specified in your OAuth callback URLs
2. When an OAuth provider redirects to your callback URL, these servers capture the authorization code
3. The servers then redirect the browser to the MCP Inspector UI to complete the OAuth flow

**Example usage:**

```bash
export OAUTH_MCP_INSPECTOR_CALLBACK="http://localhost:3060"
export OAUTH_MCP_INSPECTOR_DEBUG_CALLBACK="http://localhost:3061"
npx @modelcontextprotocol/inspector
```

**What happens:**
- MCP Inspector starts on `http://localhost:6274` (default)
- OAuth callback server starts on `http://localhost:3060`
- OAuth debug callback server starts on `http://localhost:3061`
- OAuth providers redirect to your configured URLs (3060/3061)
- These servers capture the authorization code and redirect to MCP Inspector (6274)

**Note:** The OAuth callback URLs are configured at runtime, so no rebuild is required when changing them.

The inspector also supports configuration files to store settings for different MCP servers. This is useful when working with multiple servers or complex configurations:

```bash
Expand Down
30 changes: 30 additions & 0 deletions client/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,36 @@ const App = () => {
saveInspectorConfig(CONFIG_LOCAL_STORAGE_KEY, config);
}, [config]);

// Load OAuth configuration from server
useEffect(() => {
const loadOAuthConfig = async () => {
try {
const proxyUrl = getMCPProxyAddress(config);
const authConfig = getMCPProxyAuthToken(config);
const headers: Record<string, string> = {};

if (authConfig.token) {
headers[authConfig.header] = `Bearer ${authConfig.token}`;
}

const response = await fetch(`${proxyUrl}/config`, { headers });
if (response.ok) {
const serverConfig = await response.json();
if (serverConfig.oauthCallback) {
sessionStorage.setItem('OAUTH_MCP_INSPECTOR_CALLBACK', serverConfig.oauthCallback);
}
if (serverConfig.oauthDebugCallback) {
sessionStorage.setItem('OAUTH_MCP_INSPECTOR_DEBUG_CALLBACK', serverConfig.oauthDebugCallback);
}
}
} catch (error) {
// Silently fail - OAuth config is optional
console.debug('Failed to load OAuth configuration:', error);
}
};
loadOAuthConfig();
}, [config]);

// Auto-connect to previously saved serverURL after OAuth callback
const onOAuthConnect = useCallback(
(serverUrl: string) => {
Expand Down
10 changes: 10 additions & 0 deletions client/src/lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ export class InspectorOAuthClientProvider implements OAuthClientProvider {
}

get redirectUrl() {
// Check for runtime configuration
const configuredCallback = sessionStorage.getItem('OAUTH_MCP_INSPECTOR_CALLBACK');
if (configuredCallback) {
return configuredCallback;
}
return window.location.origin + "/oauth/callback";
}

Expand Down Expand Up @@ -108,6 +113,11 @@ export class InspectorOAuthClientProvider implements OAuthClientProvider {
// display in debug UI.
export class DebugInspectorOAuthClientProvider extends InspectorOAuthClientProvider {
get redirectUrl(): string {
// Check for runtime configuration
const configuredDebugCallback = sessionStorage.getItem('OAUTH_MCP_INSPECTOR_DEBUG_CALLBACK');
if (configuredDebugCallback) {
return configuredDebugCallback;
}
return `${window.location.origin}/oauth/callback/debug`;
}

Expand Down
6 changes: 6 additions & 0 deletions client/src/utils/configUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,12 @@ export const initializeInspectorConfig = (

// Ensure all config items have the latest labels/descriptions from defaults
for (const [key, value] of Object.entries(baseConfig)) {
// Skip if key doesn't exist in DEFAULT_INSPECTOR_CONFIG
if (!(key in DEFAULT_INSPECTOR_CONFIG)) {
delete baseConfig[key as keyof InspectorConfig];
continue;
}

baseConfig[key as keyof InspectorConfig] = {
...value,
label: DEFAULT_INSPECTOR_CONFIG[key as keyof InspectorConfig].label,
Expand Down
28 changes: 28 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,4 @@
"engines": {
"node": ">=22.7.5"
}
}
}
30 changes: 30 additions & 0 deletions server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import express from "express";
import { findActualExecutable } from "spawn-rx";
import mcpProxy from "./mcpProxy.js";
import { randomUUID, randomBytes, timingSafeEqual } from "node:crypto";
import { OAuthCallbackManager } from "./oauthCallbacks.js";

const DEFAULT_MCP_PROXY_LISTEN_PORT = "6277";
const SSE_HEADERS_PASSTHROUGH = ["authorization"];
Expand Down Expand Up @@ -522,6 +523,8 @@ app.get("/config", originValidationMiddleware, authMiddleware, (req, res) => {
defaultEnvironment,
defaultCommand: values.env,
defaultArgs: values.args,
oauthCallback: process.env.OAUTH_MCP_INSPECTOR_CALLBACK || null,
oauthDebugCallback: process.env.OAUTH_MCP_INSPECTOR_DEBUG_CALLBACK || null,
});
} catch (error) {
console.error("Error in /config route:", error);
Expand All @@ -534,6 +537,11 @@ const PORT = parseInt(
10,
);
const HOST = process.env.HOST || "localhost";
const CLIENT_PORT = process.env.CLIENT_PORT || "6274";

// Initialize OAuth callback manager
const mcpInspectorUrl = `http://${HOST}:${CLIENT_PORT}`;
const oauthCallbackManager = new OAuthCallbackManager(mcpInspectorUrl);

const server = app.listen(PORT, HOST);
server.on("listening", () => {
Expand All @@ -548,6 +556,9 @@ server.on("listening", () => {
`⚠️ WARNING: Authentication is disabled. This is not recommended.`,
);
}

// Start OAuth callback servers
oauthCallbackManager.start();
});
server.on("error", (err) => {
if (err.message.includes(`EADDRINUSE`)) {
Expand All @@ -557,3 +568,22 @@ server.on("error", (err) => {
}
process.exit(1);
});

// Graceful shutdown
process.on("SIGINT", () => {
console.log("\nShutting down MCP Inspector...");
oauthCallbackManager.stop();
server.close(() => {
console.log("Server closed");
process.exit(0);
});
});

process.on("SIGTERM", () => {
console.log("\nShutting down MCP Inspector...");
oauthCallbackManager.stop();
server.close(() => {
console.log("Server closed");
process.exit(0);
});
});
145 changes: 145 additions & 0 deletions server/src/oauthCallbacks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import http from "http";
import { URL } from "url";

interface OAuthCallbackServer {
server: http.Server;
port: number;
url: string;
}

export class OAuthCallbackManager {
private servers: OAuthCallbackServer[] = [];
private mcpInspectorUrl: string;

constructor(mcpInspectorUrl: string) {
this.mcpInspectorUrl = mcpInspectorUrl;
}

private createCallbackServer(callbackUrl: string, isDebug: boolean = false): OAuthCallbackServer | null {
try {
const parsedUrl = new URL(callbackUrl);
const port = parseInt(parsedUrl.port, 10);

if (!port || isNaN(port)) {
console.warn(`Invalid port in OAuth callback URL: ${callbackUrl}`);
return null;
}

const server = http.createServer((req, res) => {
const reqUrl = new URL(req.url || "", `http://${req.headers.host}`);

// Get OAuth parameters from the query string
const code = reqUrl.searchParams.get("code");
const state = reqUrl.searchParams.get("state");
const error = reqUrl.searchParams.get("error");
const errorDescription = reqUrl.searchParams.get("error_description");

// Build redirect URL to MCP Inspector
const inspectorPath = isDebug ? "/oauth/callback/debug" : "/oauth/callback";
const redirectUrl = new URL(inspectorPath, this.mcpInspectorUrl);

// Forward all query parameters
reqUrl.searchParams.forEach((value, key) => {
redirectUrl.searchParams.set(key, value);
});

// Send redirect response
res.writeHead(302, {
"Location": redirectUrl.toString(),
"Content-Type": "text/html",
});

const redirectHtml = `
<!DOCTYPE html>
<html>
<head>
<title>OAuth Redirect</title>
<meta charset="utf-8">
</head>
<body>
<h2>OAuth Authentication</h2>
<p>Redirecting to MCP Inspector...</p>
<p>If you are not redirected automatically, <a href="${redirectUrl.toString()}">click here</a>.</p>
<script>
// Automatic redirect
window.location.href = "${redirectUrl.toString()}";
</script>
</body>
</html>
`;

res.end(redirectHtml);

console.log(`OAuth ${isDebug ? "debug " : ""}callback received on port ${port}`);
if (code) {
console.log(` Authorization code: ${code.substring(0, 10)}...`);
}
if (error) {
console.log(` Error: ${error} - ${errorDescription || "No description"}`);
}
console.log(` Redirecting to: ${redirectUrl.toString()}`);
});

return { server, port, url: callbackUrl };
} catch (error) {
console.error(`Failed to create OAuth callback server for ${callbackUrl}:`, error);
return null;
}
}

start(): void {
const oauthCallback = process.env.OAUTH_MCP_INSPECTOR_CALLBACK;
const oauthDebugCallback = process.env.OAUTH_MCP_INSPECTOR_DEBUG_CALLBACK;

if (oauthCallback) {
const callbackServer = this.createCallbackServer(oauthCallback, false);
if (callbackServer) {
callbackServer.server.listen(callbackServer.port, () => {
console.log(`🔗 OAuth callback server listening on ${callbackServer.url}`);
});

callbackServer.server.on("error", (err) => {
if ((err as any).code === "EADDRINUSE") {
console.warn(`⚠️ OAuth callback port ${callbackServer.port} is in use`);
} else {
console.error(`OAuth callback server error:`, err);
}
});

this.servers.push(callbackServer);
}
}

if (oauthDebugCallback) {
const debugCallbackServer = this.createCallbackServer(oauthDebugCallback, true);
if (debugCallbackServer) {
debugCallbackServer.server.listen(debugCallbackServer.port, () => {
console.log(`🔗 OAuth debug callback server listening on ${debugCallbackServer.url}`);
});

debugCallbackServer.server.on("error", (err) => {
if ((err as any).code === "EADDRINUSE") {
console.warn(`⚠️ OAuth debug callback port ${debugCallbackServer.port} is in use`);
} else {
console.error(`OAuth debug callback server error:`, err);
}
});

this.servers.push(debugCallbackServer);
}
}

if (this.servers.length === 0) {
console.log("No OAuth callback URLs configured");
}
}

stop(): void {
this.servers.forEach(({ server, port }) => {
server.close(() => {
console.log(`OAuth callback server on port ${port} stopped`);
});
});
this.servers = [];
}
}
Loading