diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..a3e960e3 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,35 @@ +# Version control +.git +.gitignore + +# Node.js +node_modules +npm-debug.log + +# Build artifacts +client/dist +client/build +server/dist +server/build + +# Environment variables +.env +.env.local +.env.development +.env.test +.env.production + +# Editor files +.vscode +.idea + +# Logs +logs +*.log + +# Testing +coverage + +# Docker +Dockerfile +.dockerignore \ No newline at end of file diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 00000000..e69de29b diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 8efb6773..65e98fa4 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -26,6 +26,9 @@ jobs: # - run: npm ci - run: npm install --no-package-lock + - name: Check version consistency + run: npm run check-version + - name: Check linting working-directory: ./client run: npm run lint @@ -62,3 +65,52 @@ jobs: - run: npm run publish-all env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + + publish-github-container-registry: + runs-on: ubuntu-latest + if: github.event_name == 'release' + environment: release + needs: build + permissions: + contents: read + packages: write + attestations: write + id-token: write + steps: + - uses: actions/checkout@v4 + + - name: Log in to the Container registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata (tags, labels) for Docker + id: meta + uses: docker/metadata-action@v5 + with: + images: ghcr.io/${{ github.repository }} + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Build and push Docker image + id: push + uses: docker/build-push-action@v6 + with: + context: . + push: true + platforms: linux/amd64,linux/arm64 + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + + - name: Generate artifact attestation + uses: actions/attest-build-provenance@v2 + with: + subject-name: ghcr.io/${{ github.repository }} + subject-digest: ${{ steps.push.outputs.digest }} + push-to-registry: true diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..f36fb8bb --- /dev/null +++ b/Dockerfile @@ -0,0 +1,52 @@ +# Build stage +FROM node:24-slim AS builder + +# Set working directory +WORKDIR /app + +# Copy package files for installation +COPY package*.json ./ +COPY .npmrc ./ +COPY client/package*.json ./client/ +COPY server/package*.json ./server/ +COPY cli/package*.json ./cli/ + +# Install dependencies +RUN npm ci --ignore-scripts + +# Copy source files +COPY . . + +# Build the application +RUN npm run build + +# Production stage +FROM node:24-slim + +WORKDIR /app + +# Copy package files for production +COPY package*.json ./ +COPY .npmrc ./ +COPY client/package*.json ./client/ +COPY server/package*.json ./server/ +COPY cli/package*.json ./cli/ + +# Install only production dependencies +RUN npm ci --omit=dev --ignore-scripts + +# Copy built files from builder stage +COPY --from=builder /app/client/dist ./client/dist +COPY --from=builder /app/client/bin ./client/bin +COPY --from=builder /app/server/build ./server/build +COPY --from=builder /app/cli/build ./cli/build + +# Set default port values as environment variables +ENV CLIENT_PORT=6274 +ENV SERVER_PORT=6277 + +# Document which ports the application uses internally +EXPOSE ${CLIENT_PORT} ${SERVER_PORT} + +# Use ENTRYPOINT with CMD for arguments +ENTRYPOINT ["npm", "start"] \ No newline at end of file diff --git a/README.md b/README.md index 9d5017dc..94efe83c 100644 --- a/README.md +++ b/README.md @@ -137,17 +137,64 @@ The inspector supports bearer token authentication for SSE connections. Enter yo The MCP Inspector includes a proxy server that can run and communicate with local MCP processes. The proxy server should not be exposed to untrusted networks as it has permissions to spawn local processes and can connect to any specified MCP server. +#### Authentication + +The MCP Inspector proxy server requires authentication by default. When starting the server, a random session token is generated and printed to the console: + +``` +šŸ”‘ Session token: 3a1c267fad21f7150b7d624c160b7f09b0b8c4f623c7107bbf13378f051538d4 + +šŸ”— Open inspector with token pre-filled: + http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=3a1c267fad21f7150b7d624c160b7f09b0b8c4f623c7107bbf13378f051538d4 +``` + +This token must be included as a Bearer token in the Authorization header for all requests to the server. The inspector will automatically open your browser with the token pre-filled in the URL. + +**Automatic browser opening** - The inspector now automatically opens your browser with the token pre-filled in the URL when authentication is enabled. + +**Alternative: Manual configuration** - If you already have the inspector open: + +1. Click the "Configuration" button in the sidebar +2. Find "Proxy Session Token" and enter the token displayed in the proxy console +3. Click "Save" to apply the configuration + +The token will be saved in your browser's local storage for future use. + +If you need to disable authentication (NOT RECOMMENDED), you can set the `DANGEROUSLY_OMIT_AUTH` environment variable: + +```bash +DANGEROUSLY_OMIT_AUTH=true npm start +``` + +#### Local-only Binding + +By default, the MCP Inspector proxy server binds only to `127.0.0.1` (localhost) to prevent network access. This ensures the server is not accessible from other devices on the network. If you need to bind to all interfaces for development purposes, you can override this with the `HOST` environment variable: + +```bash +HOST=0.0.0.0 npm start +``` + +**Warning:** Only bind to all interfaces in trusted network environments, as this exposes the proxy server's ability to execute local processes. + +#### DNS Rebinding Protection + +To prevent DNS rebinding attacks, the MCP Inspector validates the `Origin` header on incoming requests. By default, only requests from the client origin are allowed (respects `CLIENT_PORT` if set, defaulting to port 6274). You can configure additional allowed origins by setting the `ALLOWED_ORIGINS` environment variable (comma-separated list): + +```bash +ALLOWED_ORIGINS=http://localhost:6274,http://127.0.0.1:6274,http://localhost:8000 npm start +``` + ### Configuration The MCP Inspector supports the following configuration settings. To change them, click on the `Configuration` button in the MCP Inspector UI: -| Setting | Description | Default | -| --------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ------- | -| `MCP_SERVER_REQUEST_TIMEOUT` | Timeout for requests to the MCP server (ms) | 10000 | -| `MCP_REQUEST_TIMEOUT_RESET_ON_PROGRESS` | Reset timeout on progress notifications | true | -| `MCP_REQUEST_MAX_TOTAL_TIMEOUT` | Maximum total timeout for requests sent to the MCP server (ms) (Use with progress notifications) | 60000 | -| `MCP_PROXY_FULL_ADDRESS` | Set this if you are running the MCP Inspector Proxy on a non-default address. Example: http://10.1.1.22:5577 | "" | -| `MCP_AUTO_OPEN_ENABLED` | Enable automatic browser opening when inspector starts. Only as environment var, not configurable in browser. | true | +| Setting | Description | Default | +| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `MCP_SERVER_REQUEST_TIMEOUT` | Timeout for requests to the MCP server (ms) | 10000 | +| `MCP_REQUEST_TIMEOUT_RESET_ON_PROGRESS` | Reset timeout on progress notifications | true | +| `MCP_REQUEST_MAX_TOTAL_TIMEOUT` | Maximum total timeout for requests sent to the MCP server (ms) (Use with progress notifications) | 60000 | +| `MCP_PROXY_FULL_ADDRESS` | Set this if you are running the MCP Inspector Proxy on a non-default address. Example: http://10.1.1.22:5577 | "" | +| `MCP_AUTO_OPEN_ENABLED` | Enable automatic browser opening when inspector starts (works with authentication enabled). Only as environment var, not configurable in browser. | true | These settings can be adjusted in real-time through the UI and will persist across sessions. diff --git a/cli/package.json b/cli/package.json index bd027bfe..f1ff1c33 100644 --- a/cli/package.json +++ b/cli/package.json @@ -1,6 +1,6 @@ { "name": "@modelcontextprotocol/inspector-cli", - "version": "0.14.0", + "version": "0.14.3", "description": "CLI for the Model Context Protocol inspector", "license": "MIT", "author": "Anthropic, PBC (https://anthropic.com)", diff --git a/client/bin/start.js b/client/bin/start.js index 8e383b38..ad75078a 100755 --- a/client/bin/start.js +++ b/client/bin/start.js @@ -2,8 +2,9 @@ import open from "open"; import { resolve, dirname } from "path"; -import { spawnPromise } from "spawn-rx"; +import { spawnPromise, spawn } from "spawn-rx"; import { fileURLToPath } from "url"; +import { randomBytes } from "crypto"; const __dirname = dirname(fileURLToPath(import.meta.url)); @@ -11,6 +12,157 @@ function delay(ms) { return new Promise((resolve) => setTimeout(resolve, ms, true)); } +async function startDevServer(serverOptions) { + const { SERVER_PORT, CLIENT_PORT, sessionToken, envVars, abort } = + serverOptions; + const serverCommand = "npx"; + const serverArgs = ["tsx", "watch", "--clear-screen=false", "src/index.ts"]; + const isWindows = process.platform === "win32"; + + const spawnOptions = { + cwd: resolve(__dirname, "../..", "server"), + env: { + ...process.env, + PORT: SERVER_PORT, + CLIENT_PORT: CLIENT_PORT, + MCP_PROXY_TOKEN: sessionToken, + MCP_ENV_VARS: JSON.stringify(envVars), + }, + signal: abort.signal, + echoOutput: true, + }; + + // For Windows, we need to use stdin: 'ignore' to simulate < NUL + if (isWindows) { + spawnOptions.stdin = "ignore"; + } + + const server = spawn(serverCommand, serverArgs, spawnOptions); + + // Give server time to start + const serverOk = await Promise.race([ + new Promise((resolve) => { + server.subscribe({ + complete: () => resolve(false), + error: () => resolve(false), + next: () => {}, // We're using echoOutput + }); + }), + delay(3000).then(() => true), + ]); + + return { server, serverOk }; +} + +async function startProdServer(serverOptions) { + const { + SERVER_PORT, + CLIENT_PORT, + sessionToken, + envVars, + abort, + command, + mcpServerArgs, + } = serverOptions; + const inspectorServerPath = resolve( + __dirname, + "../..", + "server", + "build", + "index.js", + ); + + const server = spawnPromise( + "node", + [ + inspectorServerPath, + ...(command ? [`--env`, command] : []), + ...(mcpServerArgs ? [`--args=${mcpServerArgs.join(" ")}`] : []), + ], + { + env: { + ...process.env, + PORT: SERVER_PORT, + CLIENT_PORT: CLIENT_PORT, + MCP_PROXY_TOKEN: sessionToken, + MCP_ENV_VARS: JSON.stringify(envVars), + }, + signal: abort.signal, + echoOutput: true, + }, + ); + + // Make sure server started before starting client + const serverOk = await Promise.race([server, delay(2 * 1000)]); + + return { server, serverOk }; +} + +async function startDevClient(clientOptions) { + const { CLIENT_PORT, authDisabled, sessionToken, abort, cancelled } = + clientOptions; + const clientCommand = "npx"; + const clientArgs = ["vite", "--port", CLIENT_PORT]; + + const client = spawn(clientCommand, clientArgs, { + cwd: resolve(__dirname, ".."), + env: { ...process.env, PORT: CLIENT_PORT }, + signal: abort.signal, + echoOutput: true, + }); + + // Auto-open browser after vite starts + if (process.env.MCP_AUTO_OPEN_ENABLED !== "false") { + const url = authDisabled + ? `http://127.0.0.1:${CLIENT_PORT}` + : `http://127.0.0.1:${CLIENT_PORT}/?MCP_PROXY_AUTH_TOKEN=${sessionToken}`; + + // Give vite time to start before opening browser + setTimeout(() => { + open(url); + console.log(`\nšŸ”— Opening browser at: ${url}\n`); + }, 3000); + } + + await new Promise((resolve) => { + client.subscribe({ + complete: resolve, + error: (err) => { + if (!cancelled || process.env.DEBUG) { + console.error("Client error:", err); + } + resolve(null); + }, + next: () => {}, // We're using echoOutput + }); + }); +} + +async function startProdClient(clientOptions) { + const { CLIENT_PORT, authDisabled, sessionToken, abort } = clientOptions; + const inspectorClientPath = resolve( + __dirname, + "../..", + "client", + "bin", + "client.js", + ); + + // Auto-open browser with token + if (process.env.MCP_AUTO_OPEN_ENABLED !== "false") { + const url = authDisabled + ? `http://127.0.0.1:${CLIENT_PORT}` + : `http://127.0.0.1:${CLIENT_PORT}/?MCP_PROXY_AUTH_TOKEN=${sessionToken}`; + open(url); + } + + await spawnPromise("node", [inspectorClientPath], { + env: { ...process.env, PORT: CLIENT_PORT }, + signal: abort.signal, + echoOutput: true, + }); +} + async function main() { // Parse command line arguments const args = process.argv.slice(2); @@ -18,6 +170,7 @@ async function main() { const mcpServerArgs = []; let command = null; let parsingFlags = true; + let isDev = false; for (let i = 0; i < args.length; i++) { const arg = args[i]; @@ -27,6 +180,11 @@ async function main() { continue; } + if (parsingFlags && arg === "--dev") { + isDev = true; + continue; + } + if (parsingFlags && arg === "-e" && i + 1 < args.length) { const envVar = args[++i]; const equalsIndex = envVar.indexOf("="); @@ -38,34 +196,25 @@ async function main() { } else { envVars[envVar] = ""; } - } else if (!command) { + } else if (!command && !isDev) { command = arg; - } else { + } else if (!isDev) { mcpServerArgs.push(arg); } } - const inspectorServerPath = resolve( - __dirname, - "../..", - "server", - "build", - "index.js", - ); - - // Path to the client entry point - const inspectorClientPath = resolve( - __dirname, - "../..", - "client", - "bin", - "client.js", - ); - const CLIENT_PORT = process.env.CLIENT_PORT ?? "6274"; const SERVER_PORT = process.env.SERVER_PORT ?? "6277"; - console.log("Starting MCP inspector..."); + console.log( + isDev + ? "Starting MCP inspector in development mode..." + : "Starting MCP inspector...", + ); + + // Generate session token for authentication + const sessionToken = randomBytes(32).toString("hex"); + const authDisabled = !!process.env.DANGEROUSLY_OMIT_AUTH; const abort = new AbortController(); @@ -74,40 +223,41 @@ async function main() { cancelled = true; abort.abort(); }); - let server, serverOk; - try { - server = spawnPromise( - "node", - [ - inspectorServerPath, - ...(command ? [`--env`, command] : []), - ...(mcpServerArgs ? [`--args=${mcpServerArgs.join(" ")}`] : []), - ], - { - env: { - ...process.env, - PORT: SERVER_PORT, - MCP_ENV_VARS: JSON.stringify(envVars), - }, - signal: abort.signal, - echoOutput: true, - }, - ); - // Make sure server started before starting client - serverOk = await Promise.race([server, delay(2 * 1000)]); + let server, serverOk; + + try { + const serverOptions = { + SERVER_PORT, + CLIENT_PORT, + sessionToken, + envVars, + abort, + command, + mcpServerArgs, + }; + + const result = isDev + ? await startDevServer(serverOptions) + : await startProdServer(serverOptions); + + server = result.server; + serverOk = result.serverOk; } catch (error) {} if (serverOk) { try { - if (process.env.MCP_AUTO_OPEN_ENABLED !== "false") { - open(`http://127.0.0.1:${CLIENT_PORT}`); - } - await spawnPromise("node", [inspectorClientPath], { - env: { ...process.env, PORT: CLIENT_PORT }, - signal: abort.signal, - echoOutput: true, - }); + const clientOptions = { + CLIENT_PORT, + authDisabled, + sessionToken, + abort, + cancelled, + }; + + await (isDev + ? startDevClient(clientOptions) + : startProdClient(clientOptions)); } catch (e) { if (!cancelled || process.env.DEBUG) throw e; } diff --git a/client/package.json b/client/package.json index 9eb49574..a34ecbc4 100644 --- a/client/package.json +++ b/client/package.json @@ -1,6 +1,6 @@ { "name": "@modelcontextprotocol/inspector-client", - "version": "0.14.0", + "version": "0.14.3", "description": "Client-side application for the Model Context Protocol inspector", "license": "MIT", "author": "Anthropic, PBC (https://anthropic.com)", diff --git a/client/src/App.tsx b/client/src/App.tsx index d264a8fa..26eb44c5 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -63,11 +63,13 @@ import ToolsTab from "./components/ToolsTab"; import { InspectorConfig } from "./lib/configurationTypes"; import { getMCPProxyAddress, + getMCPProxyAuthToken, getInitialSseUrl, getInitialTransportType, getInitialCommand, getInitialArgs, initializeInspectorConfig, + saveInspectorConfig, } from "./utils/configUtils"; const CONFIG_LOCAL_STORAGE_KEY = "inspectorConfig_v1"; @@ -226,7 +228,7 @@ const App = () => { }, [headerName]); useEffect(() => { - localStorage.setItem(CONFIG_LOCAL_STORAGE_KEY, JSON.stringify(config)); + saveInspectorConfig(CONFIG_LOCAL_STORAGE_KEY, config); }, [config]); // Auto-connect to previously saved serverURL after OAuth callback @@ -344,7 +346,14 @@ const App = () => { }, [sseUrl]); useEffect(() => { - fetch(`${getMCPProxyAddress(config)}/config`) + const headers: HeadersInit = {}; + const { token: proxyAuthToken, header: proxyAuthTokenHeader } = + getMCPProxyAuthToken(config); + if (proxyAuthToken) { + headers[proxyAuthTokenHeader] = `Bearer ${proxyAuthToken}`; + } + + fetch(`${getMCPProxyAddress(config)}/config`, { headers }) .then((response) => response.json()) .then((data) => { setEnv(data.defaultEnvironment); @@ -358,8 +367,7 @@ const App = () => { .catch((error) => console.error("Error fetching default environment:", error), ); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); + }, [config]); useEffect(() => { rootsRef.current = roots; diff --git a/client/src/__tests__/App.config.test.tsx b/client/src/__tests__/App.config.test.tsx new file mode 100644 index 00000000..b2e03d36 --- /dev/null +++ b/client/src/__tests__/App.config.test.tsx @@ -0,0 +1,240 @@ +import { render, waitFor } from "@testing-library/react"; +import App from "../App"; +import { DEFAULT_INSPECTOR_CONFIG } from "../lib/constants"; +import { InspectorConfig } from "../lib/configurationTypes"; +import * as configUtils from "../utils/configUtils"; + +// Mock auth dependencies first +jest.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({ + auth: jest.fn(), +})); + +jest.mock("../lib/oauth-state-machine", () => ({ + OAuthStateMachine: jest.fn(), +})); + +jest.mock("../lib/auth", () => ({ + InspectorOAuthClientProvider: jest.fn().mockImplementation(() => ({ + tokens: jest.fn().mockResolvedValue(null), + clear: jest.fn(), + })), + DebugInspectorOAuthClientProvider: jest.fn(), +})); + +// Mock the config utils +jest.mock("../utils/configUtils", () => ({ + ...jest.requireActual("../utils/configUtils"), + getMCPProxyAddress: jest.fn(() => "http://localhost:6277"), + getMCPProxyAuthToken: jest.fn((config: InspectorConfig) => ({ + token: config.MCP_PROXY_AUTH_TOKEN.value, + header: "X-MCP-Proxy-Auth", + })), + getInitialTransportType: jest.fn(() => "stdio"), + getInitialSseUrl: jest.fn(() => "http://localhost:3001/sse"), + getInitialCommand: jest.fn(() => "mcp-server-everything"), + getInitialArgs: jest.fn(() => ""), + initializeInspectorConfig: jest.fn(() => DEFAULT_INSPECTOR_CONFIG), + saveInspectorConfig: jest.fn(), +})); + +// Get references to the mocked functions +const mockGetMCPProxyAuthToken = configUtils.getMCPProxyAuthToken as jest.Mock; +const mockInitializeInspectorConfig = + configUtils.initializeInspectorConfig as jest.Mock; + +// Mock other dependencies +jest.mock("../lib/hooks/useConnection", () => ({ + useConnection: () => ({ + connectionStatus: "disconnected", + serverCapabilities: null, + mcpClient: null, + requestHistory: [], + makeRequest: jest.fn(), + sendNotification: jest.fn(), + handleCompletion: jest.fn(), + completionsSupported: false, + connect: jest.fn(), + disconnect: jest.fn(), + }), +})); + +jest.mock("../lib/hooks/useDraggablePane", () => ({ + useDraggablePane: () => ({ + height: 300, + handleDragStart: jest.fn(), + }), + useDraggableSidebar: () => ({ + width: 320, + isDragging: false, + handleDragStart: jest.fn(), + }), +})); + +jest.mock("../components/Sidebar", () => ({ + __esModule: true, + default: () =>
Sidebar
, +})); + +// Mock fetch +global.fetch = jest.fn(); + +describe("App - Config Endpoint", () => { + beforeEach(() => { + jest.clearAllMocks(); + (global.fetch as jest.Mock).mockResolvedValue({ + json: () => + Promise.resolve({ + defaultEnvironment: { TEST_ENV: "test" }, + defaultCommand: "test-command", + defaultArgs: "test-args", + }), + }); + }); + + afterEach(() => { + jest.clearAllMocks(); + + // Reset getMCPProxyAuthToken to default behavior + mockGetMCPProxyAuthToken.mockImplementation((config: InspectorConfig) => ({ + token: config.MCP_PROXY_AUTH_TOKEN.value, + header: "X-MCP-Proxy-Auth", + })); + }); + + test("sends X-MCP-Proxy-Auth header when fetching config with proxy auth token", async () => { + const mockConfig = { + ...DEFAULT_INSPECTOR_CONFIG, + MCP_PROXY_AUTH_TOKEN: { + ...DEFAULT_INSPECTOR_CONFIG.MCP_PROXY_AUTH_TOKEN, + value: "test-proxy-token", + }, + }; + + // Mock initializeInspectorConfig to return our test config + mockInitializeInspectorConfig.mockReturnValue(mockConfig); + + render(); + + await waitFor(() => { + expect(global.fetch).toHaveBeenCalledWith( + "http://localhost:6277/config", + { + headers: { + "X-MCP-Proxy-Auth": "Bearer test-proxy-token", + }, + }, + ); + }); + }); + + test("does not send auth header when proxy auth token is empty", async () => { + const mockConfig = { + ...DEFAULT_INSPECTOR_CONFIG, + MCP_PROXY_AUTH_TOKEN: { + ...DEFAULT_INSPECTOR_CONFIG.MCP_PROXY_AUTH_TOKEN, + value: "", + }, + }; + + // Mock initializeInspectorConfig to return our test config + mockInitializeInspectorConfig.mockReturnValue(mockConfig); + + render(); + + await waitFor(() => { + expect(global.fetch).toHaveBeenCalledWith( + "http://localhost:6277/config", + { + headers: {}, + }, + ); + }); + }); + + test("uses custom header name if getMCPProxyAuthToken returns different header", async () => { + const mockConfig = { + ...DEFAULT_INSPECTOR_CONFIG, + MCP_PROXY_AUTH_TOKEN: { + ...DEFAULT_INSPECTOR_CONFIG.MCP_PROXY_AUTH_TOKEN, + value: "test-proxy-token", + }, + }; + + // Mock to return a custom header name + mockGetMCPProxyAuthToken.mockReturnValue({ + token: "test-proxy-token", + header: "X-Custom-Auth", + }); + mockInitializeInspectorConfig.mockReturnValue(mockConfig); + + render(); + + await waitFor(() => { + expect(global.fetch).toHaveBeenCalledWith( + "http://localhost:6277/config", + { + headers: { + "X-Custom-Auth": "Bearer test-proxy-token", + }, + }, + ); + }); + }); + + test("config endpoint response updates app state", async () => { + const mockConfig = { + ...DEFAULT_INSPECTOR_CONFIG, + MCP_PROXY_AUTH_TOKEN: { + ...DEFAULT_INSPECTOR_CONFIG.MCP_PROXY_AUTH_TOKEN, + value: "test-proxy-token", + }, + }; + + mockInitializeInspectorConfig.mockReturnValue(mockConfig); + + render(); + + await waitFor(() => { + expect(global.fetch).toHaveBeenCalledTimes(1); + }); + + // Verify the fetch was called with correct parameters + expect(global.fetch).toHaveBeenCalledWith( + "http://localhost:6277/config", + expect.objectContaining({ + headers: expect.objectContaining({ + "X-MCP-Proxy-Auth": "Bearer test-proxy-token", + }), + }), + ); + }); + + test("handles config endpoint errors gracefully", async () => { + const mockConfig = { + ...DEFAULT_INSPECTOR_CONFIG, + MCP_PROXY_AUTH_TOKEN: { + ...DEFAULT_INSPECTOR_CONFIG.MCP_PROXY_AUTH_TOKEN, + value: "test-proxy-token", + }, + }; + + mockInitializeInspectorConfig.mockReturnValue(mockConfig); + + // Mock fetch to reject + (global.fetch as jest.Mock).mockRejectedValue(new Error("Network error")); + + // Spy on console.error + const consoleErrorSpy = jest.spyOn(console, "error").mockImplementation(); + + render(); + + await waitFor(() => { + expect(consoleErrorSpy).toHaveBeenCalledWith( + "Error fetching default environment:", + expect.any(Error), + ); + }); + + consoleErrorSpy.mockRestore(); + }); +}); diff --git a/client/src/components/Sidebar.tsx b/client/src/components/Sidebar.tsx index 3985eb48..938e5b5a 100644 --- a/client/src/components/Sidebar.tsx +++ b/client/src/components/Sidebar.tsx @@ -666,8 +666,13 @@ const Sidebar = ({ switch (connectionStatus) { case "connected": return "Connected"; - case "error": - return "Connection Error, is your MCP server running?"; + case "error": { + const hasProxyToken = config.MCP_PROXY_AUTH_TOKEN?.value; + if (!hasProxyToken) { + return "Connection Error - Did you add the proxy session token in Configuration?"; + } + return "Connection Error - Check if your MCP server is running and proxy token is correct"; + } case "error-connecting-to-proxy": return "Error Connecting to MCP Inspector Proxy - Check Console logs"; default: diff --git a/client/src/components/__tests__/AuthDebugger.test.tsx b/client/src/components/__tests__/AuthDebugger.test.tsx index 2130e68b..eb7ff3ba 100644 --- a/client/src/components/__tests__/AuthDebugger.test.tsx +++ b/client/src/components/__tests__/AuthDebugger.test.tsx @@ -84,12 +84,6 @@ Object.defineProperty(window, "sessionStorage", { value: sessionStorageMock, }); -Object.defineProperty(window, "location", { - value: { - origin: "http://localhost:3000", - }, -}); - describe("AuthDebugger", () => { const defaultAuthState = EMPTY_DEBUGGER_STATE; @@ -104,7 +98,7 @@ describe("AuthDebugger", () => { jest.clearAllMocks(); sessionStorageMock.getItem.mockReturnValue(null); - // Supress + // Suppress console errors in tests to avoid JSDOM navigation noise jest.spyOn(console, "error").mockImplementation(() => {}); mockDiscoverOAuthMetadata.mockResolvedValue(mockOAuthMetadata); @@ -447,18 +441,6 @@ describe("AuthDebugger", () => { it("should store auth state to sessionStorage before redirect in Quick OAuth Flow", async () => { const updateAuthState = jest.fn(); - // Mock window.location.href setter - const originalLocation = window.location; - const locationMock = { - ...originalLocation, - href: "", - origin: "http://localhost:3000", - }; - Object.defineProperty(window, "location", { - writable: true, - value: locationMock, - }); - // Setup mocks for OAuth flow mockStartAuthorization.mockResolvedValue({ authorizationUrl: new URL( diff --git a/client/src/components/__tests__/Sidebar.test.tsx b/client/src/components/__tests__/Sidebar.test.tsx index ba03d180..d818bdbb 100644 --- a/client/src/components/__tests__/Sidebar.test.tsx +++ b/client/src/components/__tests__/Sidebar.test.tsx @@ -519,6 +519,7 @@ describe("Sidebar Environment Variables", () => { label: "Request Timeout", description: "Timeout for requests to the MCP server (ms)", value: 5000, + is_session_item: false, }, }), ); @@ -544,6 +545,7 @@ describe("Sidebar Environment Variables", () => { description: "Set this if you are running the MCP Inspector Proxy on a non-default address. Example: http://10.1.1.22:5577", value: "http://localhost:8080", + is_session_item: false, }, }), ); @@ -569,6 +571,7 @@ describe("Sidebar Environment Variables", () => { description: "Maximum total timeout for requests sent to the MCP server (ms) (Use with progress notifications)", value: 10000, + is_session_item: false, }, }), ); @@ -591,6 +594,7 @@ describe("Sidebar Environment Variables", () => { label: "Request Timeout", description: "Timeout for requests to the MCP server (ms)", value: 0, + is_session_item: false, }, }), ); @@ -637,6 +641,7 @@ describe("Sidebar Environment Variables", () => { label: "Request Timeout", description: "Timeout for requests to the MCP server (ms)", value: 3000, + is_session_item: false, }, }), ); diff --git a/client/src/lib/configurationTypes.ts b/client/src/lib/configurationTypes.ts index 7c74bb71..263b2cf2 100644 --- a/client/src/lib/configurationTypes.ts +++ b/client/src/lib/configurationTypes.ts @@ -2,6 +2,7 @@ export type ConfigItem = { label: string; description: string; value: string | number | boolean; + is_session_item: boolean; }; /** @@ -33,4 +34,9 @@ export type InspectorConfig = { * The full address of the MCP Proxy Server, in case it is running on a non-default address. Example: http://10.1.1.22:5577 */ MCP_PROXY_FULL_ADDRESS: ConfigItem; + + /** + * Session token for authenticating with the MCP Proxy Server. This token is displayed in the proxy server console on startup. + */ + MCP_PROXY_AUTH_TOKEN: ConfigItem; }; diff --git a/client/src/lib/constants.ts b/client/src/lib/constants.ts index 3acbda91..922f1943 100644 --- a/client/src/lib/constants.ts +++ b/client/src/lib/constants.ts @@ -36,22 +36,33 @@ export const DEFAULT_INSPECTOR_CONFIG: InspectorConfig = { label: "Request Timeout", description: "Timeout for requests to the MCP server (ms)", value: 10000, + is_session_item: false, }, MCP_REQUEST_TIMEOUT_RESET_ON_PROGRESS: { label: "Reset Timeout on Progress", description: "Reset timeout on progress notifications", value: true, + is_session_item: false, }, MCP_REQUEST_MAX_TOTAL_TIMEOUT: { label: "Maximum Total Timeout", description: "Maximum total timeout for requests sent to the MCP server (ms) (Use with progress notifications)", value: 60000, + is_session_item: false, }, MCP_PROXY_FULL_ADDRESS: { label: "Inspector Proxy Address", description: "Set this if you are running the MCP Inspector Proxy on a non-default address. Example: http://10.1.1.22:5577", value: "", + is_session_item: false, + }, + MCP_PROXY_AUTH_TOKEN: { + label: "Proxy Session Token", + description: + "Session token for authenticating with the MCP Proxy Server (displayed in proxy console on startup)", + value: "", + is_session_item: true, }, } as const; diff --git a/client/src/lib/hooks/__tests__/useConnection.test.tsx b/client/src/lib/hooks/__tests__/useConnection.test.tsx index 6e5748d7..676ae87d 100644 --- a/client/src/lib/hooks/__tests__/useConnection.test.tsx +++ b/client/src/lib/hooks/__tests__/useConnection.test.tsx @@ -3,6 +3,7 @@ import { useConnection } from "../useConnection"; import { z } from "zod"; import { ClientRequest } from "@modelcontextprotocol/sdk/types.js"; import { DEFAULT_INSPECTOR_CONFIG } from "../../constants"; +import { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js"; // Mock fetch global.fetch = jest.fn().mockResolvedValue({ @@ -23,21 +24,46 @@ const mockClient = { setRequestHandler: jest.fn(), }; +// Mock transport instances +const mockSSETransport: { + start: jest.Mock; + url: URL | undefined; + options: SSEClientTransportOptions | undefined; +} = { + start: jest.fn(), + url: undefined, + options: undefined, +}; + +const mockStreamableHTTPTransport: { + start: jest.Mock; + url: URL | undefined; + options: SSEClientTransportOptions | undefined; +} = { + start: jest.fn(), + url: undefined, + options: undefined, +}; + jest.mock("@modelcontextprotocol/sdk/client/index.js", () => ({ Client: jest.fn().mockImplementation(() => mockClient), })); jest.mock("@modelcontextprotocol/sdk/client/sse.js", () => ({ - SSEClientTransport: jest.fn((url) => ({ - toString: () => url, - })), + SSEClientTransport: jest.fn((url, options) => { + mockSSETransport.url = url; + mockSSETransport.options = options; + return mockSSETransport; + }), SseError: jest.fn(), })); jest.mock("@modelcontextprotocol/sdk/client/streamableHttp.js", () => ({ - StreamableHTTPClientTransport: jest.fn((url) => ({ - toString: () => url, - })), + StreamableHTTPClientTransport: jest.fn((url, options) => { + mockStreamableHTTPTransport.url = url; + mockStreamableHTTPTransport.options = options; + return mockStreamableHTTPTransport; + }), })); jest.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({ @@ -259,4 +285,181 @@ describe("useConnection", () => { ); }); }); + + describe("Proxy Authentication Headers", () => { + beforeEach(() => { + jest.clearAllMocks(); + // Reset the mock transport objects + mockSSETransport.url = undefined; + mockSSETransport.options = undefined; + mockStreamableHTTPTransport.url = undefined; + mockStreamableHTTPTransport.options = undefined; + }); + + test("sends X-MCP-Proxy-Auth header when proxy auth token is configured", async () => { + const propsWithProxyAuth = { + ...defaultProps, + config: { + ...DEFAULT_INSPECTOR_CONFIG, + MCP_PROXY_AUTH_TOKEN: { + ...DEFAULT_INSPECTOR_CONFIG.MCP_PROXY_AUTH_TOKEN, + value: "test-proxy-token", + }, + }, + }; + + const { result } = renderHook(() => useConnection(propsWithProxyAuth)); + + await act(async () => { + await result.current.connect(); + }); + + // Check that the transport was created with the correct headers + expect(mockSSETransport.options).toBeDefined(); + expect(mockSSETransport.options?.requestInit).toBeDefined(); + + expect(mockSSETransport.options?.requestInit?.headers).toHaveProperty( + "X-MCP-Proxy-Auth", + "Bearer test-proxy-token", + ); + expect(mockSSETransport?.options?.eventSourceInit?.fetch).toBeDefined(); + + // Verify the fetch function includes the proxy auth header + const mockFetch = mockSSETransport.options?.eventSourceInit?.fetch; + const testUrl = "http://test.com"; + await mockFetch?.(testUrl, { + headers: { + Accept: "text/event-stream", + }, + cache: "no-store", + mode: "cors", + signal: new AbortController().signal, + redirect: "follow", + credentials: "include", + }); + + expect(global.fetch).toHaveBeenCalledTimes(2); + expect( + (global.fetch as jest.Mock).mock.calls[0][1].headers, + ).toHaveProperty("X-MCP-Proxy-Auth", "Bearer test-proxy-token"); + expect((global.fetch as jest.Mock).mock.calls[1][0]).toBe(testUrl); + expect( + (global.fetch as jest.Mock).mock.calls[1][1].headers, + ).toHaveProperty("X-MCP-Proxy-Auth", "Bearer test-proxy-token"); + }); + + test("does NOT send Authorization header for proxy auth", async () => { + const propsWithProxyAuth = { + ...defaultProps, + config: { + ...DEFAULT_INSPECTOR_CONFIG, + proxyAuthToken: "test-proxy-token", + }, + }; + + const { result } = renderHook(() => useConnection(propsWithProxyAuth)); + + await act(async () => { + await result.current.connect(); + }); + + // Check that Authorization header is NOT used for proxy auth + expect(mockSSETransport.options?.requestInit?.headers).not.toHaveProperty( + "Authorization", + "Bearer test-proxy-token", + ); + }); + + test("preserves server Authorization header when proxy auth is configured", async () => { + const propsWithBothAuth = { + ...defaultProps, + bearerToken: "server-auth-token", + config: { + ...DEFAULT_INSPECTOR_CONFIG, + MCP_PROXY_AUTH_TOKEN: { + ...DEFAULT_INSPECTOR_CONFIG.MCP_PROXY_AUTH_TOKEN, + value: "test-proxy-token", + }, + }, + }; + + const { result } = renderHook(() => useConnection(propsWithBothAuth)); + + await act(async () => { + await result.current.connect(); + }); + + // Check that both headers are present and distinct + const headers = mockSSETransport.options?.requestInit?.headers; + expect(headers).toHaveProperty( + "Authorization", + "Bearer server-auth-token", + ); + expect(headers).toHaveProperty( + "X-MCP-Proxy-Auth", + "Bearer test-proxy-token", + ); + }); + + test("sends X-MCP-Proxy-Auth in health check requests", async () => { + const fetchMock = global.fetch as jest.Mock; + fetchMock.mockClear(); + + const propsWithProxyAuth = { + ...defaultProps, + config: { + ...DEFAULT_INSPECTOR_CONFIG, + MCP_PROXY_AUTH_TOKEN: { + ...DEFAULT_INSPECTOR_CONFIG.MCP_PROXY_AUTH_TOKEN, + value: "test-proxy-token", + }, + }, + }; + + const { result } = renderHook(() => useConnection(propsWithProxyAuth)); + + await act(async () => { + await result.current.connect(); + }); + + // Find the health check call + const healthCheckCall = fetchMock.mock.calls.find( + (call) => call[0].pathname === "/health", + ); + + expect(healthCheckCall).toBeDefined(); + expect(healthCheckCall[1].headers).toHaveProperty( + "X-MCP-Proxy-Auth", + "Bearer test-proxy-token", + ); + }); + + test("works correctly with streamable-http transport", async () => { + const propsWithStreamableHttp = { + ...defaultProps, + transportType: "streamable-http" as const, + config: { + ...DEFAULT_INSPECTOR_CONFIG, + MCP_PROXY_AUTH_TOKEN: { + ...DEFAULT_INSPECTOR_CONFIG.MCP_PROXY_AUTH_TOKEN, + value: "test-proxy-token", + }, + }, + }; + + const { result } = renderHook(() => + useConnection(propsWithStreamableHttp), + ); + + await act(async () => { + await result.current.connect(); + }); + + // Check that the streamable HTTP transport was created with the correct headers + expect(mockStreamableHTTPTransport.options).toBeDefined(); + expect( + mockStreamableHTTPTransport.options?.requestInit?.headers, + ).toHaveProperty("X-MCP-Proxy-Auth", "Bearer test-proxy-token"); + }); + }); }); diff --git a/client/src/lib/hooks/useConnection.ts b/client/src/lib/hooks/useConnection.ts index d42b8d38..9009e698 100644 --- a/client/src/lib/hooks/useConnection.ts +++ b/client/src/lib/hooks/useConnection.ts @@ -42,6 +42,7 @@ import { getMCPProxyAddress, getMCPServerRequestMaxTotalTimeout, resetRequestTimeoutOnProgress, + getMCPProxyAuthToken, } from "@/utils/configUtils"; import { getMCPServerRequestTimeout } from "@/utils/configUtils"; import { InspectorConfig } from "../configurationTypes"; @@ -242,7 +243,13 @@ export function useConnection({ const checkProxyHealth = async () => { try { const proxyHealthUrl = new URL(`${getMCPProxyAddress(config)}/health`); - const proxyHealthResponse = await fetch(proxyHealthUrl); + const { token: proxyAuthToken, header: proxyAuthTokenHeader } = + getMCPProxyAuthToken(config); + const headers: HeadersInit = {}; + if (proxyAuthToken) { + headers[proxyAuthTokenHeader] = `Bearer ${proxyAuthToken}`; + } + const proxyHealthResponse = await fetch(proxyHealthUrl, { headers }); const proxyHealth = await proxyHealthResponse.json(); if (proxyHealth?.status !== "ok") { throw new Error("MCP Proxy Server is not healthy"); @@ -261,6 +268,13 @@ export function useConnection({ ); }; + const isProxyAuthError = (error: unknown): boolean => { + return ( + error instanceof Error && + error.message.includes("Authentication required. Use the session token") + ); + }; + const handleAuthError = async (error: unknown) => { if (is401Error(error)) { const serverAuthProvider = new InspectorOAuthClientProvider(sseUrl); @@ -318,6 +332,14 @@ export function useConnection({ } } + // Add proxy authentication + const { token: proxyAuthToken, header: proxyAuthTokenHeader } = + getMCPProxyAuthToken(config); + const proxyHeaders: HeadersInit = {}; + if (proxyAuthToken) { + proxyHeaders[proxyAuthTokenHeader] = `Bearer ${proxyAuthToken}`; + } + // Create appropriate transport let transportOptions: | StreamableHTTPClientTransportOptions @@ -335,11 +357,15 @@ export function useConnection({ eventSourceInit: { fetch: ( url: string | URL | globalThis.Request, - init: RequestInit | undefined, - ) => fetch(url, { ...init, headers }), + init?: RequestInit, + ) => + fetch(url, { + ...init, + headers: { ...headers, ...proxyHeaders }, + }), }, requestInit: { - headers, + headers: { ...headers, ...proxyHeaders }, }, }; break; @@ -351,11 +377,15 @@ export function useConnection({ eventSourceInit: { fetch: ( url: string | URL | globalThis.Request, - init: RequestInit | undefined, - ) => fetch(url, { ...init, headers }), + init?: RequestInit, + ) => + fetch(url, { + ...init, + headers: { ...headers, ...proxyHeaders }, + }), }, requestInit: { - headers, + headers: { ...headers, ...proxyHeaders }, }, }; break; @@ -367,11 +397,15 @@ export function useConnection({ eventSourceInit: { fetch: ( url: string | URL | globalThis.Request, - init: RequestInit | undefined, - ) => fetch(url, { ...init, headers }), + init?: RequestInit, + ) => + fetch(url, { + ...init, + headers: { ...headers, ...proxyHeaders }, + }), }, requestInit: { - headers, + headers: { ...headers, ...proxyHeaders }, }, // TODO these should be configurable... reconnectionOptions: { @@ -447,6 +481,18 @@ export function useConnection({ error, ); + // Check if it's a proxy auth error + if (isProxyAuthError(error)) { + toast({ + title: "Proxy Authentication Required", + description: + "Please enter the session token from the proxy server console in the Configuration settings.", + variant: "destructive", + }); + setConnectionStatus("error"); + return; + } + const shouldRetry = await handleAuthError(error); if (shouldRetry) { return connect(undefined, retryCount + 1); diff --git a/client/src/utils/__tests__/configUtils.test.ts b/client/src/utils/__tests__/configUtils.test.ts new file mode 100644 index 00000000..86dccbdf --- /dev/null +++ b/client/src/utils/__tests__/configUtils.test.ts @@ -0,0 +1,72 @@ +import { getMCPProxyAuthToken } from "../configUtils"; +import { DEFAULT_INSPECTOR_CONFIG } from "../../lib/constants"; +import { InspectorConfig } from "../../lib/configurationTypes"; + +describe("configUtils", () => { + describe("getMCPProxyAuthToken", () => { + test("returns token and default header name", () => { + const config: InspectorConfig = { + ...DEFAULT_INSPECTOR_CONFIG, + MCP_PROXY_AUTH_TOKEN: { + ...DEFAULT_INSPECTOR_CONFIG.MCP_PROXY_AUTH_TOKEN, + value: "test-token-123", + }, + }; + + const result = getMCPProxyAuthToken(config); + + expect(result).toEqual({ + token: "test-token-123", + header: "X-MCP-Proxy-Auth", + }); + }); + + test("returns empty token when not configured", () => { + const config: InspectorConfig = { + ...DEFAULT_INSPECTOR_CONFIG, + MCP_PROXY_AUTH_TOKEN: { + ...DEFAULT_INSPECTOR_CONFIG.MCP_PROXY_AUTH_TOKEN, + value: "", + }, + }; + + const result = getMCPProxyAuthToken(config); + + expect(result).toEqual({ + token: "", + header: "X-MCP-Proxy-Auth", + }); + }); + + test("always returns X-MCP-Proxy-Auth as header name", () => { + const config: InspectorConfig = { + ...DEFAULT_INSPECTOR_CONFIG, + MCP_PROXY_AUTH_TOKEN: { + ...DEFAULT_INSPECTOR_CONFIG.MCP_PROXY_AUTH_TOKEN, + value: "any-token", + }, + }; + + const result = getMCPProxyAuthToken(config); + + expect(result.header).toBe("X-MCP-Proxy-Auth"); + }); + + test("handles null/undefined value gracefully", () => { + const config: InspectorConfig = { + ...DEFAULT_INSPECTOR_CONFIG, + MCP_PROXY_AUTH_TOKEN: { + ...DEFAULT_INSPECTOR_CONFIG.MCP_PROXY_AUTH_TOKEN, + value: null as unknown as string, + }, + }; + + const result = getMCPProxyAuthToken(config); + + expect(result).toEqual({ + token: null, + header: "X-MCP-Proxy-Auth", + }); + }); + }); +}); diff --git a/client/src/utils/configUtils.ts b/client/src/utils/configUtils.ts index ae404d65..40e47a94 100644 --- a/client/src/utils/configUtils.ts +++ b/client/src/utils/configUtils.ts @@ -28,6 +28,18 @@ export const getMCPServerRequestMaxTotalTimeout = ( return config.MCP_REQUEST_MAX_TOTAL_TIMEOUT.value as number; }; +export const getMCPProxyAuthToken = ( + config: InspectorConfig, +): { + token: string; + header: string; +} => { + return { + token: config.MCP_PROXY_AUTH_TOKEN.value as string, + header: "X-MCP-Proxy-Auth", + }; +}; + const getSearchParam = (key: string): string | null => { try { const url = new URL(window.location.href); @@ -100,27 +112,67 @@ export const getConfigOverridesFromQueryParams = ( export const initializeInspectorConfig = ( localStorageKey: string, ): InspectorConfig => { - const savedConfig = localStorage.getItem(localStorageKey); - let baseConfig: InspectorConfig; - if (savedConfig) { - // merge default config with saved config - const mergedConfig = { - ...DEFAULT_INSPECTOR_CONFIG, - ...JSON.parse(savedConfig), - } as InspectorConfig; + // Read persistent config from localStorage + const savedPersistentConfig = localStorage.getItem(localStorageKey); + // Read ephemeral config from sessionStorage + const savedEphemeralConfig = sessionStorage.getItem( + `${localStorageKey}_ephemeral`, + ); - // update description of keys to match the new description (in case of any updates to the default config description) - for (const [key, value] of Object.entries(mergedConfig)) { - mergedConfig[key as keyof InspectorConfig] = { - ...value, - label: DEFAULT_INSPECTOR_CONFIG[key as keyof InspectorConfig].label, - }; - } - baseConfig = mergedConfig; - } else { - baseConfig = DEFAULT_INSPECTOR_CONFIG; + // Start with default config + let baseConfig = { ...DEFAULT_INSPECTOR_CONFIG }; + + // Apply saved persistent config + if (savedPersistentConfig) { + const parsedPersistentConfig = JSON.parse(savedPersistentConfig); + baseConfig = { ...baseConfig, ...parsedPersistentConfig }; } + + // Apply saved ephemeral config + if (savedEphemeralConfig) { + const parsedEphemeralConfig = JSON.parse(savedEphemeralConfig); + baseConfig = { ...baseConfig, ...parsedEphemeralConfig }; + } + + // Ensure all config items have the latest labels/descriptions from defaults + for (const [key, value] of Object.entries(baseConfig)) { + baseConfig[key as keyof InspectorConfig] = { + ...value, + label: DEFAULT_INSPECTOR_CONFIG[key as keyof InspectorConfig].label, + description: + DEFAULT_INSPECTOR_CONFIG[key as keyof InspectorConfig].description, + is_session_item: + DEFAULT_INSPECTOR_CONFIG[key as keyof InspectorConfig].is_session_item, + }; + } + // Apply query param overrides const overrides = getConfigOverridesFromQueryParams(DEFAULT_INSPECTOR_CONFIG); return { ...baseConfig, ...overrides }; }; + +export const saveInspectorConfig = ( + localStorageKey: string, + config: InspectorConfig, +): void => { + const persistentConfig: Partial = {}; + const ephemeralConfig: Partial = {}; + + // Split config based on is_session_item flag + for (const [key, value] of Object.entries(config)) { + if (value.is_session_item) { + ephemeralConfig[key as keyof InspectorConfig] = value; + } else { + persistentConfig[key as keyof InspectorConfig] = value; + } + } + + // Save persistent config to localStorage + localStorage.setItem(localStorageKey, JSON.stringify(persistentConfig)); + + // Save ephemeral config to sessionStorage + sessionStorage.setItem( + `${localStorageKey}_ephemeral`, + JSON.stringify(ephemeralConfig), + ); +}; diff --git a/package-lock.json b/package-lock.json index 25a242fc..cf561a99 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@modelcontextprotocol/inspector", - "version": "0.14.0", + "version": "0.14.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@modelcontextprotocol/inspector", - "version": "0.14.0", + "version": "0.14.3", "license": "MIT", "workspaces": [ "client", @@ -14,9 +14,9 @@ "cli" ], "dependencies": { - "@modelcontextprotocol/inspector-cli": "^0.14.0", - "@modelcontextprotocol/inspector-client": "^0.14.0", - "@modelcontextprotocol/inspector-server": "^0.14.0", + "@modelcontextprotocol/inspector-cli": "^0.14.3", + "@modelcontextprotocol/inspector-client": "^0.14.3", + "@modelcontextprotocol/inspector-server": "^0.14.3", "@modelcontextprotocol/sdk": "^1.12.1", "concurrently": "^9.0.1", "open": "^10.1.0", @@ -41,7 +41,7 @@ }, "cli": { "name": "@modelcontextprotocol/inspector-cli", - "version": "0.14.0", + "version": "0.14.3", "license": "MIT", "dependencies": { "@modelcontextprotocol/sdk": "^1.12.1", @@ -64,7 +64,7 @@ }, "client": { "name": "@modelcontextprotocol/inspector-client", - "version": "0.14.0", + "version": "0.14.3", "license": "MIT", "dependencies": { "@modelcontextprotocol/sdk": "^1.12.1", @@ -10984,7 +10984,7 @@ }, "server": { "name": "@modelcontextprotocol/inspector-server", - "version": "0.14.0", + "version": "0.14.3", "license": "MIT", "dependencies": { "@modelcontextprotocol/sdk": "^1.12.1", diff --git a/package.json b/package.json index 9108e3e3..f333ef9e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@modelcontextprotocol/inspector", - "version": "0.14.0", + "version": "0.14.3", "description": "Model Context Protocol inspector", "license": "MIT", "author": "Anthropic, PBC (https://anthropic.com)", @@ -26,9 +26,9 @@ "build-server": "cd server && npm run build", "build-client": "cd client && npm run build", "build-cli": "cd cli && npm run build", - "clean": "rimraf ./node_modules ./client/node_modules ./cli/node_modules ./build ./client/dist ./server/build ./cli/build ./package-lock.json client/playwright-report client/results.json client/test-results && npm install", - "dev": "concurrently \"cd client && npm run dev\" \"cd server && npm run dev\"", - "dev:windows": "concurrently \"cd client && npm run dev\" \"cd server && npm run dev:windows\"", + "clean": "rimraf ./node_modules ./client/node_modules ./cli/node_modules ./build ./client/dist ./server/build ./cli/build ./package-lock.json && npm install", + "dev": "node client/bin/start.js --dev", + "dev:windows": "node client/bin/start.js --dev", "start": "node client/bin/start.js", "start-server": "cd server && npm run start", "start-client": "cd client && npm run preview", @@ -39,12 +39,14 @@ "prettier-check": "prettier --check .", "lint": "prettier --check . && cd client && npm run lint", "prepare": "npm run build", - "publish-all": "npm publish --workspaces --access public && npm publish --access public" + "publish-all": "npm publish --workspaces --access public && npm publish --access public", + "update-version": "node scripts/update-version.js", + "check-version": "node scripts/check-version-consistency.js" }, "dependencies": { - "@modelcontextprotocol/inspector-cli": "^0.14.0", - "@modelcontextprotocol/inspector-client": "^0.14.0", - "@modelcontextprotocol/inspector-server": "^0.14.0", + "@modelcontextprotocol/inspector-cli": "^0.14.3", + "@modelcontextprotocol/inspector-client": "^0.14.3", + "@modelcontextprotocol/inspector-server": "^0.14.3", "@modelcontextprotocol/sdk": "^1.12.1", "concurrently": "^9.0.1", "open": "^10.1.0", diff --git a/scripts/README.md b/scripts/README.md new file mode 100644 index 00000000..d6887faf --- /dev/null +++ b/scripts/README.md @@ -0,0 +1,72 @@ +# Version Management Scripts + +This directory contains scripts for managing version consistency across the monorepo. + +## Scripts + +### update-version.js + +Updates the version across all package.json files in the monorepo and updates package-lock.json. + +**Usage:** + +```bash +npm run update-version +# Example: +npm run update-version 0.14.3 +``` + +This script will: + +1. Update the version in all package.json files (root, client, server, cli) +2. Update workspace dependencies in the root package.json +3. Run `npm install` to update package-lock.json +4. Provide next steps for committing and tagging + +### check-version-consistency.js + +Checks that all packages have consistent versions and that package-lock.json is up to date. + +**Usage:** + +```bash +npm run check-version +``` + +This script checks: + +1. All package.json files have the same version +2. Workspace dependencies in root package.json match the current version +3. package-lock.json version matches package.json +4. Workspace packages in package-lock.json have the correct versions + +This check runs automatically in CI on every PR and push to main. + +## CI Integration + +The version consistency check is integrated into the GitHub Actions workflow (`.github/workflows/main.yml`) and will fail the build if: + +- Package versions are inconsistent +- package-lock.json is out of sync + +## Common Workflows + +### Bumping version for a release: + +```bash +# Update to new version +npm run update-version 0.15.0 + +# Verify everything is correct +npm run check-version + +# Commit the changes +git add -A +git commit -m "chore: bump version to 0.15.0" + +# Create a tag +git tag 0.15.0 + +# Push changes and tag +git push && git push --tags +``` diff --git a/scripts/check-version-consistency.js b/scripts/check-version-consistency.js new file mode 100755 index 00000000..379931de --- /dev/null +++ b/scripts/check-version-consistency.js @@ -0,0 +1,177 @@ +#!/usr/bin/env node + +import fs from "fs"; +import path from "path"; +import { fileURLToPath } from "url"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +/** + * Checks version consistency across all package.json files in the monorepo + * Exits with code 1 if versions are inconsistent + * Usage: node scripts/check-version-consistency.js + */ + +console.log("šŸ” Checking version consistency across packages...\n"); + +// List of package.json files to check +const packagePaths = [ + "package.json", + "client/package.json", + "server/package.json", + "cli/package.json", +]; + +const versions = new Map(); +const errors = []; + +// Read version from each package.json +packagePaths.forEach((packagePath) => { + const fullPath = path.join(__dirname, "..", packagePath); + + if (!fs.existsSync(fullPath)) { + console.warn(`āš ļø Skipping ${packagePath} - file not found`); + return; + } + + try { + const packageJson = JSON.parse(fs.readFileSync(fullPath, "utf8")); + const version = packageJson.version; + const packageName = packageJson.name || packagePath; + + versions.set(packagePath, { + name: packageName, + version: version, + dependencies: packageJson.dependencies || {}, + }); + + console.log(`šŸ“¦ ${packagePath}:`); + console.log(` Name: ${packageName}`); + console.log(` Version: ${version}`); + } catch (error) { + errors.push(`Failed to read ${packagePath}: ${error.message}`); + } +}); + +if (errors.length > 0) { + console.error("\nāŒ Errors occurred while reading package files:"); + errors.forEach((error) => console.error(` - ${error}`)); + process.exit(1); +} + +// Check if all versions match +const allVersions = Array.from(versions.values()).map((v) => v.version); +const uniqueVersions = [...new Set(allVersions)]; + +console.log("\nšŸ“Š Version Summary:"); +console.log(` Total packages: ${versions.size}`); +console.log(` Unique versions: ${uniqueVersions.length}`); + +if (uniqueVersions.length > 1) { + console.error("\nāŒ Version mismatch detected!"); + console.error(" Found versions: " + uniqueVersions.join(", ")); + + console.error("\n Package versions:"); + versions.forEach((info, path) => { + console.error(` - ${path}: ${info.version}`); + }); +} else { + console.log(` āœ… All packages are at version: ${uniqueVersions[0]}`); +} + +// Check workspace dependencies in root package.json +const rootPackage = versions.get("package.json"); +if (rootPackage) { + console.log("\nšŸ”— Checking workspace dependencies..."); + const expectedVersion = rootPackage.version; + let dependencyErrors = false; + + Object.entries(rootPackage.dependencies).forEach(([dep, version]) => { + if (dep.startsWith("@modelcontextprotocol/inspector-")) { + const expectedDepVersion = `^${expectedVersion}`; + if (version !== expectedDepVersion) { + console.error( + ` āŒ ${dep}: ${version} (expected ${expectedDepVersion})`, + ); + dependencyErrors = true; + } else { + console.log(` āœ… ${dep}: ${version}`); + } + } + }); + + if (dependencyErrors) { + errors.push("Workspace dependency versions do not match package versions"); + } +} + +// Check if package-lock.json is up to date +console.log("\nšŸ”’ Checking package-lock.json..."); +const lockPath = path.join(__dirname, "..", "package-lock.json"); +let lockFileError = false; + +if (!fs.existsSync(lockPath)) { + console.error(" āŒ package-lock.json not found"); + lockFileError = true; +} else { + try { + const lockFile = JSON.parse(fs.readFileSync(lockPath, "utf8")); + const lockVersion = lockFile.version; + const expectedVersion = rootPackage?.version || uniqueVersions[0]; + + if (lockVersion !== expectedVersion) { + console.error( + ` āŒ package-lock.json version (${lockVersion}) does not match package.json version (${expectedVersion})`, + ); + lockFileError = true; + } else { + console.log(` āœ… package-lock.json version matches: ${lockVersion}`); + } + + // Check workspace package versions in lock file + if (lockFile.packages) { + const workspacePackages = [ + { path: "client", name: "@modelcontextprotocol/inspector-client" }, + { path: "server", name: "@modelcontextprotocol/inspector-server" }, + { path: "cli", name: "@modelcontextprotocol/inspector-cli" }, + ]; + + workspacePackages.forEach(({ path, name }) => { + const lockPkgPath = lockFile.packages[path]; + if (lockPkgPath && lockPkgPath.version !== expectedVersion) { + console.error( + ` āŒ ${name} in lock file: ${lockPkgPath.version} (expected ${expectedVersion})`, + ); + lockFileError = true; + } + }); + } + } catch (error) { + console.error(` āŒ Failed to parse package-lock.json: ${error.message}`); + lockFileError = true; + } +} + +// Final result +console.log("\nšŸŽÆ Result:"); +if (uniqueVersions.length === 1 && errors.length === 0 && !lockFileError) { + console.log(" āœ… Version consistency check passed!"); + process.exit(0); +} else { + console.error(" āŒ Version consistency check failed!"); + if (uniqueVersions.length > 1) { + console.error(" - Package versions are not consistent"); + } + if (errors.length > 0) { + console.error(" - " + errors.join("\n - ")); + } + if (lockFileError) { + console.error(" - package-lock.json is out of sync"); + } + console.error( + '\nšŸ’” Run "npm run update-version " to fix version inconsistencies', + ); + console.error(' or run "npm install" to update package-lock.json'); + process.exit(1); +} diff --git a/scripts/update-version.js b/scripts/update-version.js new file mode 100755 index 00000000..91b69f3b --- /dev/null +++ b/scripts/update-version.js @@ -0,0 +1,104 @@ +#!/usr/bin/env node + +import fs from "fs"; +import path from "path"; +import { execSync } from "child_process"; +import { fileURLToPath } from "url"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +/** + * Updates version across all package.json files in the monorepo + * Usage: node scripts/update-version.js + * Example: node scripts/update-version.js 0.14.2 + */ + +const newVersion = process.argv[2]; + +if (!newVersion) { + console.error("āŒ Please provide a version number"); + console.error("Usage: node scripts/update-version.js "); + console.error("Example: node scripts/update-version.js 0.14.2"); + process.exit(1); +} + +// Validate version format +const versionRegex = /^\d+\.\d+\.\d+(-[\w.]+)?$/; +if (!versionRegex.test(newVersion)) { + console.error( + "āŒ Invalid version format. Please use semantic versioning (e.g., 1.2.3 or 1.2.3-beta.1)", + ); + process.exit(1); +} + +console.log(`šŸ”„ Updating all packages to version ${newVersion}...`); + +// List of package.json files to update +const packagePaths = [ + "package.json", + "client/package.json", + "server/package.json", + "cli/package.json", +]; + +const updatedFiles = []; + +// Update version in each package.json +packagePaths.forEach((packagePath) => { + const fullPath = path.join(__dirname, "..", packagePath); + + if (!fs.existsSync(fullPath)) { + console.warn(`āš ļø Skipping ${packagePath} - file not found`); + return; + } + + try { + const packageJson = JSON.parse(fs.readFileSync(fullPath, "utf8")); + const oldVersion = packageJson.version; + packageJson.version = newVersion; + + // Update workspace dependencies in root package.json + if (packagePath === "package.json" && packageJson.dependencies) { + Object.keys(packageJson.dependencies).forEach((dep) => { + if (dep.startsWith("@modelcontextprotocol/inspector-")) { + packageJson.dependencies[dep] = `^${newVersion}`; + } + }); + } + + fs.writeFileSync(fullPath, JSON.stringify(packageJson, null, 2) + "\n"); + updatedFiles.push(packagePath); + console.log( + `āœ… Updated ${packagePath} from ${oldVersion} to ${newVersion}`, + ); + } catch (error) { + console.error(`āŒ Failed to update ${packagePath}:`, error.message); + process.exit(1); + } +}); + +console.log("\nšŸ“ Summary:"); +console.log(`Updated ${updatedFiles.length} files to version ${newVersion}`); + +// Update package-lock.json +console.log("\nšŸ”’ Updating package-lock.json..."); +try { + execSync("npm install", { stdio: "inherit" }); + console.log("āœ… package-lock.json updated successfully"); +} catch (error) { + console.error("āŒ Failed to update package-lock.json:", error.message); + console.error('Please run "npm install" manually'); + process.exit(1); +} + +console.log("\n✨ Version update complete!"); +console.log("\nNext steps:"); +console.log("1. Review the changes: git diff"); +console.log( + '2. Commit the changes: git add -A && git commit -m "chore: bump version to ' + + newVersion + + '"', +); +console.log("3. Create a git tag: git tag v" + newVersion); +console.log("4. Push changes and tag: git push && git push --tags"); diff --git a/server/package.json b/server/package.json index 50d74cfc..8f81a9df 100644 --- a/server/package.json +++ b/server/package.json @@ -1,6 +1,6 @@ { "name": "@modelcontextprotocol/inspector-server", - "version": "0.14.0", + "version": "0.14.3", "description": "Server-side application for the Model Context Protocol inspector", "license": "MIT", "author": "Anthropic, PBC (https://anthropic.com)", diff --git a/server/src/index.ts b/server/src/index.ts index 37327fa2..7653597a 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -19,7 +19,7 @@ import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; import express from "express"; import { findActualExecutable } from "spawn-rx"; import mcpProxy from "./mcpProxy.js"; -import { randomUUID } from "node:crypto"; +import { randomUUID, randomBytes, timingSafeEqual } from "node:crypto"; const SSE_HEADERS_PASSTHROUGH = ["authorization"]; const STREAMABLE_HTTP_HEADERS_PASSTHROUGH = [ @@ -89,6 +89,89 @@ app.use((req, res, next) => { const webAppTransports: Map = new Map(); // Web app transports by web app sessionId const serverTransports: Map = new Map(); // Server Transports by web app sessionId +// Use provided token from environment or generate a new one +const sessionToken = + process.env.MCP_PROXY_TOKEN || randomBytes(32).toString("hex"); +const authDisabled = !!process.env.DANGEROUSLY_OMIT_AUTH; + +// Origin validation middleware to prevent DNS rebinding attacks +const originValidationMiddleware = ( + req: express.Request, + res: express.Response, + next: express.NextFunction, +) => { + const origin = req.headers.origin; + + // Default origins based on CLIENT_PORT or use environment variable + const clientPort = process.env.CLIENT_PORT || "6274"; + const defaultOrigins = [ + `http://localhost:${clientPort}`, + `http://127.0.0.1:${clientPort}`, + ]; + const allowedOrigins = + process.env.ALLOWED_ORIGINS?.split(",") || defaultOrigins; + + if (origin && !allowedOrigins.includes(origin)) { + console.error(`Invalid origin: ${origin}`); + res.status(403).json({ + error: "Forbidden - invalid origin", + message: + "Request blocked to prevent DNS rebinding attacks. Configure allowed origins via environment variable.", + }); + return; + } + next(); +}; + +const authMiddleware = ( + req: express.Request, + res: express.Response, + next: express.NextFunction, +) => { + if (authDisabled) { + return next(); + } + + const sendUnauthorized = () => { + res.status(401).json({ + error: "Unauthorized", + message: + "Authentication required. Use the session token shown in the console when starting the server.", + }); + }; + + const authHeader = req.headers["x-mcp-proxy-auth"]; + const authHeaderValue = Array.isArray(authHeader) + ? authHeader[0] + : authHeader; + + if (!authHeaderValue || !authHeaderValue.startsWith("Bearer ")) { + sendUnauthorized(); + return; + } + + const providedToken = authHeaderValue.substring(7); // Remove 'Bearer ' prefix + const expectedToken = sessionToken; + + // Convert to buffers for timing-safe comparison + const providedBuffer = Buffer.from(providedToken); + const expectedBuffer = Buffer.from(expectedToken); + + // Check length first to prevent timing attacks + if (providedBuffer.length !== expectedBuffer.length) { + sendUnauthorized(); + return; + } + + // Perform timing-safe comparison + if (!timingSafeEqual(providedBuffer, expectedBuffer)) { + sendUnauthorized(); + return; + } + + next(); +}; + const createTransport = async (req: express.Request): Promise => { const query = req.query; console.log("Query parameters:", JSON.stringify(query)); @@ -119,7 +202,9 @@ const createTransport = async (req: express.Request): Promise => { const headers = getHttpHeaders(req, transportType); - console.log(`SSE transport: url=${url}, headers=${Object.keys(headers)}`); + console.log( + `SSE transport: url=${url}, headers=${JSON.stringify(headers)}`, + ); const transport = new SSEClientTransport(new URL(url), { eventSourceInit: { @@ -150,38 +235,152 @@ const createTransport = async (req: express.Request): Promise => { } }; -app.get("/mcp", async (req, res) => { - const sessionId = req.headers["mcp-session-id"] as string; - console.log(`Received GET message for sessionId ${sessionId}`); - try { - const transport = webAppTransports.get( - sessionId, - ) as StreamableHTTPServerTransport; - if (!transport) { - res.status(404).end("Session not found"); - return; - } else { - await transport.handleRequest(req, res); - } - } catch (error) { - console.error("Error in /mcp route:", error); - res.status(500).json(error); - } -}); - -app.post("/mcp", async (req, res) => { - const sessionId = req.headers["mcp-session-id"] as string | undefined; - let serverTransport: Transport | undefined; - if (!sessionId) { +app.get( + "/mcp", + originValidationMiddleware, + authMiddleware, + async (req, res) => { + const sessionId = req.headers["mcp-session-id"] as string; + console.log(`Received GET message for sessionId ${sessionId}`); try { - console.log("New StreamableHttp connection request"); + const transport = webAppTransports.get( + sessionId, + ) as StreamableHTTPServerTransport; + if (!transport) { + res.status(404).end("Session not found"); + return; + } else { + await transport.handleRequest(req, res); + } + } catch (error) { + console.error("Error in /mcp route:", error); + res.status(500).json(error); + } + }, +); + +app.post( + "/mcp", + originValidationMiddleware, + authMiddleware, + async (req, res) => { + const sessionId = req.headers["mcp-session-id"] as string | undefined; + let serverTransport: Transport | undefined; + if (!sessionId) { + try { + console.log("New StreamableHttp connection request"); + try { + serverTransport = await createTransport(req); + } catch (error) { + if (error instanceof SseError && error.code === 401) { + console.error( + "Received 401 Unauthorized from MCP server:", + error.message, + ); + res.status(401).json(error); + return; + } + + throw error; + } + + console.log("Created StreamableHttp server transport"); + + const webAppTransport = new StreamableHTTPServerTransport({ + sessionIdGenerator: randomUUID, + onsessioninitialized: (sessionId) => { + webAppTransports.set(sessionId, webAppTransport); + serverTransports.set(sessionId, serverTransport!); + console.log("Client <-> Proxy sessionId: " + sessionId); + }, + }); + console.log("Created StreamableHttp client transport"); + + await webAppTransport.start(); + + mcpProxy({ + transportToClient: webAppTransport, + transportToServer: serverTransport, + }); + + await (webAppTransport as StreamableHTTPServerTransport).handleRequest( + req, + res, + req.body, + ); + } catch (error) { + console.error("Error in /mcp POST route:", error); + res.status(500).json(error); + } + } else { + console.log(`Received POST message for sessionId ${sessionId}`); + try { + const transport = webAppTransports.get( + sessionId, + ) as StreamableHTTPServerTransport; + if (!transport) { + res.status(404).end("Transport not found for sessionId " + sessionId); + } else { + await (transport as StreamableHTTPServerTransport).handleRequest( + req, + res, + ); + } + } catch (error) { + console.error("Error in /mcp route:", error); + res.status(500).json(error); + } + } + }, +); + +app.delete( + "/mcp", + originValidationMiddleware, + authMiddleware, + async (req, res) => { + const sessionId = req.headers["mcp-session-id"] as string | undefined; + console.log(`Received DELETE message for sessionId ${sessionId}`); + let serverTransport: Transport | undefined; + if (sessionId) { + try { + serverTransport = serverTransports.get( + sessionId, + ) as StreamableHTTPClientTransport; + if (!serverTransport) { + res.status(404).end("Transport not found for sessionId " + sessionId); + } else { + await ( + serverTransport as StreamableHTTPClientTransport + ).terminateSession(); + webAppTransports.delete(sessionId); + serverTransports.delete(sessionId); + console.log(`Transports removed for sessionId ${sessionId}`); + } + res.status(200).end(); + } catch (error) { + console.error("Error in /mcp route:", error); + res.status(500).json(error); + } + } + }, +); + +app.get( + "/stdio", + originValidationMiddleware, + authMiddleware, + async (req, res) => { + try { + console.log("New STDIO connection request"); + let serverTransport: Transport | undefined; try { serverTransport = await createTransport(req); + console.log("Created server transport"); } catch (error) { if (error instanceof SseError && error.code === 401) { console.error( - "Received 401 Unauthorized from MCP server:", - error.message, + "Received 401 Unauthorized from MCP server. Authentication failure.", ); res.status(401).json(error); return; @@ -190,211 +389,127 @@ app.post("/mcp", async (req, res) => { throw error; } - console.log("Created StreamableHttp server transport"); - - const webAppTransport = new StreamableHTTPServerTransport({ - sessionIdGenerator: randomUUID, - onsessioninitialized: (sessionId) => { - webAppTransports.set(sessionId, webAppTransport); - serverTransports.set(sessionId, serverTransport!); - console.log("Client <-> Proxy sessionId: " + sessionId); - }, - }); - console.log("Created StreamableHttp client transport"); - - await webAppTransport.start(); - - mcpProxy({ - transportToClient: webAppTransport, - transportToServer: serverTransport, - }); - - await (webAppTransport as StreamableHTTPServerTransport).handleRequest( - req, - res, - req.body, - ); - } catch (error) { - console.error("Error in /mcp POST route:", error); - res.status(500).json(error); - } - } else { - console.log(`Received POST message for sessionId ${sessionId}`); - try { - const transport = webAppTransports.get( - sessionId, - ) as StreamableHTTPServerTransport; - if (!transport) { - res.status(404).end("Transport not found for sessionId " + sessionId); - } else { - await (transport as StreamableHTTPServerTransport).handleRequest( - req, - res, - ); - } - } catch (error) { - console.error("Error in /mcp route:", error); - res.status(500).json(error); - } - } -}); - -app.delete("/mcp", async (req, res) => { - const sessionId = req.headers["mcp-session-id"] as string | undefined; - console.log(`Received DELETE message for sessionId ${sessionId}`); - let serverTransport: Transport | undefined; - if (sessionId) { - try { - serverTransport = serverTransports.get( - sessionId, - ) as StreamableHTTPClientTransport; - if (!serverTransport) { - res.status(404).end("Transport not found for sessionId " + sessionId); - } else { - await ( - serverTransport as StreamableHTTPClientTransport - ).terminateSession(); - webAppTransports.delete(sessionId); - serverTransports.delete(sessionId); - console.log(`Transports removed for sessionId ${sessionId}`); - } - res.status(200).end(); - } catch (error) { - console.error("Error in /mcp route:", error); - res.status(500).json(error); - } - } -}); - -app.get("/stdio", async (req, res) => { - try { - console.log("New STDIO connection request"); - let serverTransport: Transport | undefined; - try { - serverTransport = await createTransport(req); - console.log("Created server transport"); - } catch (error) { - if (error instanceof SseError && error.code === 401) { - console.error( - "Received 401 Unauthorized from MCP server. Authentication failure.", - ); - res.status(401).json(error); - return; - } - - throw error; - } - - const webAppTransport = new SSEServerTransport("/message", res); - console.log("Created client transport"); - - webAppTransports.set(webAppTransport.sessionId, webAppTransport); - serverTransports.set(webAppTransport.sessionId, serverTransport); - - await webAppTransport.start(); - - (serverTransport as StdioClientTransport).stderr!.on("data", (chunk) => { - if (chunk.toString().includes("MODULE_NOT_FOUND")) { - webAppTransport.send({ - jsonrpc: "2.0", - method: "notifications/stderr", - params: { - content: "Command not found, transports removed", - }, - }); - webAppTransport.close(); - serverTransport.close(); - webAppTransports.delete(webAppTransport.sessionId); - serverTransports.delete(webAppTransport.sessionId); - console.error("Command not found, transports removed"); - } else { - webAppTransport.send({ - jsonrpc: "2.0", - method: "notifications/stderr", - params: { - content: chunk.toString(), - }, - }); - } - }); - - mcpProxy({ - transportToClient: webAppTransport, - transportToServer: serverTransport, - }); - } catch (error) { - console.error("Error in /stdio route:", error); - res.status(500).json(error); - } -}); - -app.get("/sse", async (req, res) => { - try { - console.log( - "New SSE connection request. NOTE: The sse transport is deprecated and has been replaced by StreamableHttp", - ); - let serverTransport: Transport | undefined; - try { - serverTransport = await createTransport(req); - } catch (error) { - if (error instanceof SseError && error.code === 401) { - console.error( - "Received 401 Unauthorized from MCP server. Authentication failure.", - ); - res.status(401).json(error); - return; - } else if (error instanceof SseError && error.code === 404) { - console.error( - "Received 404 not found from MCP server. Does the MCP server support SSE?", - ); - res.status(404).json(error); - return; - } else if (JSON.stringify(error).includes("ECONNREFUSED")) { - console.error("Connection refused. Is the MCP server running?"); - res.status(500).json(error); - } else { - throw error; - } - } - - if (serverTransport) { const webAppTransport = new SSEServerTransport("/message", res); - webAppTransports.set(webAppTransport.sessionId, webAppTransport); console.log("Created client transport"); - serverTransports.set(webAppTransport.sessionId, serverTransport!); - console.log("Created server transport"); + + webAppTransports.set(webAppTransport.sessionId, webAppTransport); + serverTransports.set(webAppTransport.sessionId, serverTransport); await webAppTransport.start(); + (serverTransport as StdioClientTransport).stderr!.on("data", (chunk) => { + if (chunk.toString().includes("MODULE_NOT_FOUND")) { + webAppTransport.send({ + jsonrpc: "2.0", + method: "notifications/stderr", + params: { + content: "Command not found, transports removed", + }, + }); + webAppTransport.close(); + serverTransport.close(); + webAppTransports.delete(webAppTransport.sessionId); + serverTransports.delete(webAppTransport.sessionId); + console.error("Command not found, transports removed"); + } else { + webAppTransport.send({ + jsonrpc: "2.0", + method: "notifications/stderr", + params: { + content: chunk.toString(), + }, + }); + } + }); + mcpProxy({ transportToClient: webAppTransport, transportToServer: serverTransport, }); + } catch (error) { + console.error("Error in /stdio route:", error); + res.status(500).json(error); } - } catch (error) { - console.error("Error in /sse route:", error); - res.status(500).json(error); - } -}); + }, +); -app.post("/message", async (req, res) => { - try { - const sessionId = req.query.sessionId; - console.log(`Received POST message for sessionId ${sessionId}`); +app.get( + "/sse", + originValidationMiddleware, + authMiddleware, + async (req, res) => { + try { + console.log( + "New SSE connection request. NOTE: The sse transport is deprecated and has been replaced by StreamableHttp", + ); + let serverTransport: Transport | undefined; + try { + serverTransport = await createTransport(req); + } catch (error) { + if (error instanceof SseError && error.code === 401) { + console.error( + "Received 401 Unauthorized from MCP server. Authentication failure.", + ); + res.status(401).json(error); + return; + } else if (error instanceof SseError && error.code === 404) { + console.error( + "Received 404 not found from MCP server. Does the MCP server support SSE?", + ); + res.status(404).json(error); + return; + } else if (JSON.stringify(error).includes("ECONNREFUSED")) { + console.error("Connection refused. Is the MCP server running?"); + res.status(500).json(error); + } else { + throw error; + } + } - const transport = webAppTransports.get( - sessionId as string, - ) as SSEServerTransport; - if (!transport) { - res.status(404).end("Session not found"); - return; + if (serverTransport) { + const webAppTransport = new SSEServerTransport("/message", res); + webAppTransports.set(webAppTransport.sessionId, webAppTransport); + console.log("Created client transport"); + serverTransports.set(webAppTransport.sessionId, serverTransport!); + console.log("Created server transport"); + + await webAppTransport.start(); + + mcpProxy({ + transportToClient: webAppTransport, + transportToServer: serverTransport, + }); + } + } catch (error) { + console.error("Error in /sse route:", error); + res.status(500).json(error); } - await transport.handlePostMessage(req, res); - } catch (error) { - console.error("Error in /message route:", error); - res.status(500).json(error); - } -}); + }, +); + +app.post( + "/message", + originValidationMiddleware, + authMiddleware, + async (req, res) => { + try { + const sessionId = req.query.sessionId; + console.log(`Received POST message for sessionId ${sessionId}`); + + const transport = webAppTransports.get( + sessionId as string, + ) as SSEServerTransport; + if (!transport) { + res.status(404).end("Session not found"); + return; + } + await transport.handlePostMessage(req, res); + } catch (error) { + console.error("Error in /message route:", error); + res.status(500).json(error); + } + }, +); app.get("/health", (req, res) => { res.json({ @@ -402,7 +517,7 @@ app.get("/health", (req, res) => { }); }); -app.get("/config", (req, res) => { +app.get("/config", originValidationMiddleware, authMiddleware, (req, res) => { try { res.json({ defaultEnvironment, @@ -415,11 +530,29 @@ app.get("/config", (req, res) => { } }); -const PORT = process.env.PORT || 6277; +const PORT = parseInt(process.env.PORT || "6277", 10); +const HOST = process.env.HOST || "127.0.0.1"; -const server = app.listen(PORT); +const server = app.listen(PORT, HOST); server.on("listening", () => { - console.log(`āš™ļø Proxy server listening on port ${PORT}`); + console.log(`āš™ļø Proxy server listening on ${HOST}:${PORT}`); + if (!authDisabled) { + console.log(`šŸ”‘ Session token: ${sessionToken}`); + console.log( + `Use this token to authenticate requests or set DANGEROUSLY_OMIT_AUTH=true to disable auth`, + ); + + // Display clickable URL with pre-filled token + const clientPort = process.env.CLIENT_PORT || "6274"; + const clientUrl = `http://localhost:${clientPort}/?MCP_PROXY_AUTH_TOKEN=${sessionToken}`; + console.log( + `\nšŸ”— Open inspector with token pre-filled:\n ${clientUrl}\n`, + ); + } else { + console.log( + `āš ļø WARNING: Authentication is disabled. This is not recommended.`, + ); + } }); server.on("error", (err) => { if (err.message.includes(`EADDRINUSE`)) {