From 6ee7627ee975f5d566aac7713e2791756fb86096 Mon Sep 17 00:00:00 2001 From: Aaron Powell Date: Thu, 3 Apr 2025 14:17:19 +1100 Subject: [PATCH 001/177] Initial work for adding a Dockerfile and creating an image for inspector Fixes #237 --- .dockerignore | 35 +++++++++++++++++++++++++++++++++++ Dockerfile | 26 ++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 .dockerignore create mode 100644 Dockerfile 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/Dockerfile b/Dockerfile new file mode 100644 index 00000000..2d318a33 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,26 @@ +FROM node:22-slim + +# Set working directory +WORKDIR /app + +# Copy files +COPY . . + +# Install dependencies +# Working around https://github.com/npm/cli/issues/4828 +# RUN npm ci +RUN npm install --no-package-lock + +# Build the application +RUN npm run build + +ENV CLIENT_PORT=6274 +ENV SERVER_PORT=6277 + +# Expose the CLIENT_PORT and SERVER_PORT +EXPOSE $CLIENT_PORT +EXPOSE $SERVER_PORT + +# Use ENTRYPOINT with CMD for arguments +ENTRYPOINT ["npm", "start"] +CMD [] \ No newline at end of file From 6d561a0e0df804dfcf2b5b5c2c3909675846f5e4 Mon Sep 17 00:00:00 2001 From: Aaron Powell Date: Tue, 8 Apr 2025 11:45:39 +1000 Subject: [PATCH 002/177] Updating workflow to publish to GitHub Container Registry Using guide from https://docs.github.com/en/actions/use-cases-and-examples/publishing-packages/publishing-docker-images --- .github/workflows/main.yml | 40 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 1f134440..ad23a17a 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -58,3 +58,43 @@ 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: 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: Build and push Docker image + id: push + uses: docker/build-push-action@v6 + with: + context: . + push: true + 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 \ No newline at end of file From ad8d0579c4286c473c8c2a51edd2766f694d20be Mon Sep 17 00:00:00 2001 From: Aaron Powell Date: Thu, 24 Apr 2025 15:12:19 +1000 Subject: [PATCH 003/177] Fixing prettier error --- .github/workflows/main.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index d3a31bed..769f4197 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -99,4 +99,4 @@ jobs: with: subject-name: ghcr.io/${{ github.repository }} subject-digest: ${{ steps.push.outputs.digest }} - push-to-registry: true \ No newline at end of file + push-to-registry: true From 890f6fdba2b83aa5e49d0d6a91e4ff77b6f88d38 Mon Sep 17 00:00:00 2001 From: Aaron Powell Date: Thu, 24 Apr 2025 15:28:30 +1000 Subject: [PATCH 004/177] Dockerfile (#1) * Initial work for adding a Dockerfile and creating an image for inspector Fixes #237 * Updating workflow to publish to GitHub Container Registry Using guide from https://docs.github.com/en/actions/use-cases-and-examples/publishing-packages/publishing-docker-images --- .dockerignore | 35 +++++++++++++++++++++++++++++++++ .github/workflows/main.yml | 40 ++++++++++++++++++++++++++++++++++++++ Dockerfile | 26 +++++++++++++++++++++++++ 3 files changed, 101 insertions(+) create mode 100644 .dockerignore create mode 100644 Dockerfile 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/.github/workflows/main.yml b/.github/workflows/main.yml index 9621e313..d3a31bed 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -60,3 +60,43 @@ 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: 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: Build and push Docker image + id: push + uses: docker/build-push-action@v6 + with: + context: . + push: true + 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 \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..2d318a33 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,26 @@ +FROM node:22-slim + +# Set working directory +WORKDIR /app + +# Copy files +COPY . . + +# Install dependencies +# Working around https://github.com/npm/cli/issues/4828 +# RUN npm ci +RUN npm install --no-package-lock + +# Build the application +RUN npm run build + +ENV CLIENT_PORT=6274 +ENV SERVER_PORT=6277 + +# Expose the CLIENT_PORT and SERVER_PORT +EXPOSE $CLIENT_PORT +EXPOSE $SERVER_PORT + +# Use ENTRYPOINT with CMD for arguments +ENTRYPOINT ["npm", "start"] +CMD [] \ No newline at end of file From 9e186e3b1b76427fbf1d4b09cec450957f0c0a46 Mon Sep 17 00:00:00 2001 From: Aaron Powell Date: Thu, 24 Apr 2025 15:31:37 +1000 Subject: [PATCH 005/177] ci fix (#2) --- .github/workflows/main.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index d3a31bed..769f4197 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -99,4 +99,4 @@ jobs: with: subject-name: ghcr.io/${{ github.repository }} subject-digest: ${{ steps.push.outputs.digest }} - push-to-registry: true \ No newline at end of file + push-to-registry: true From b0031d0b6f705e465b196da89567a6572af78778 Mon Sep 17 00:00:00 2001 From: Aaron Powell Date: Thu, 24 Apr 2025 15:41:40 +1000 Subject: [PATCH 006/177] Fixing permissions (#3) --- .github/workflows/main.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 769f4197..3c9e08dc 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -67,7 +67,9 @@ jobs: environment: release needs: build permissions: - contents: write + contents: read + packages: write + attestations: write id-token: write steps: - uses: actions/checkout@v4 From 243fd1494e672df968321fe4f3bdf33185e37991 Mon Sep 17 00:00:00 2001 From: Aaron Powell Date: Thu, 24 Apr 2025 15:46:22 +1000 Subject: [PATCH 007/177] Fixing permissions --- .github/workflows/main.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 769f4197..3c9e08dc 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -67,7 +67,9 @@ jobs: environment: release needs: build permissions: - contents: write + contents: read + packages: write + attestations: write id-token: write steps: - uses: actions/checkout@v4 From 618f24a9acb25222b01dec19e773362bb36c7abb Mon Sep 17 00:00:00 2001 From: xiaoli Date: Tue, 13 May 2025 23:38:19 +0800 Subject: [PATCH 008/177] feat: support custom authorization headers, fix #395 --- client/src/lib/hooks/useConnection.ts | 7 ++++++- server/src/index.ts | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/client/src/lib/hooks/useConnection.ts b/client/src/lib/hooks/useConnection.ts index 4ced90e4..501c8359 100644 --- a/client/src/lib/hooks/useConnection.ts +++ b/client/src/lib/hooks/useConnection.ts @@ -297,7 +297,12 @@ export function useConnection({ bearerToken || (await serverAuthProvider.tokens())?.access_token; if (token) { const authHeaderName = headerName || "Authorization"; - headers[authHeaderName] = `Bearer ${token}`; + headers[authHeaderName] = token; + + // Add custom header name as a special request header to let the server know which header to pass through + if (headerName && headerName.toLowerCase() !== "authorization") { + headers["x-custom-auth-header"] = headerName; + } } // Create appropriate transport diff --git a/server/src/index.ts b/server/src/index.ts index c967b60c..766d2df4 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -91,6 +91,15 @@ const createTransport = async (req: express.Request): Promise => { const value = req.headers[key]; headers[key] = Array.isArray(value) ? value[value.length - 1] : value; } + + // If the header "x-custom-auth-header" is present, use its value as the custom header name. + if (req.headers["x-custom-auth-header"] !== undefined) { + const customHeaderName = req.headers["x-custom-auth-header"] as string; + if (req.headers[customHeaderName.toLowerCase()] !== undefined) { + const value = req.headers[customHeaderName.toLowerCase()]; + headers[customHeaderName] = Array.isArray(value) ? value[value.length - 1] : value as string; + } + } console.log(`SSE transport: url=${url}, headers=${Object.keys(headers)}`); @@ -119,6 +128,15 @@ const createTransport = async (req: express.Request): Promise => { const value = req.headers[key]; headers[key] = Array.isArray(value) ? value[value.length - 1] : value; } + + // If the header "x-custom-auth-header" is present, use its value as the custom header name. + if (req.headers["x-custom-auth-header"] !== undefined) { + const customHeaderName = req.headers["x-custom-auth-header"] as string; + if (req.headers[customHeaderName.toLowerCase()] !== undefined) { + const value = req.headers[customHeaderName.toLowerCase()]; + headers[customHeaderName] = Array.isArray(value) ? value[value.length - 1] : value as string; + } + } const transport = new StreamableHTTPClientTransport( new URL(query.url as string), From 13f736033a98b4502af2b7d47cf630fde1e72b3a Mon Sep 17 00:00:00 2001 From: xiaoli Date: Tue, 20 May 2025 13:10:55 +0800 Subject: [PATCH 009/177] fix: fix review comments - Avoid calling .lowerCase twice - Keep 'Bearer ' prefix when header equals 'Authorization' - Remove unnecessary Array type checks --- client/src/lib/hooks/useConnection.ts | 10 +++++++--- server/src/index.ts | 12 ++++++------ 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/client/src/lib/hooks/useConnection.ts b/client/src/lib/hooks/useConnection.ts index 501c8359..f1f7ab9e 100644 --- a/client/src/lib/hooks/useConnection.ts +++ b/client/src/lib/hooks/useConnection.ts @@ -297,11 +297,15 @@ export function useConnection({ bearerToken || (await serverAuthProvider.tokens())?.access_token; if (token) { const authHeaderName = headerName || "Authorization"; - headers[authHeaderName] = token; // Add custom header name as a special request header to let the server know which header to pass through - if (headerName && headerName.toLowerCase() !== "authorization") { - headers["x-custom-auth-header"] = headerName; + if (authHeaderName.toLowerCase() !== "authorization") { + headers[authHeaderName] = token; + if (headerName) { + headers["x-custom-auth-header"] = headerName; + } + } else { + headers[authHeaderName] = `Bearer ${token}`; } } diff --git a/server/src/index.ts b/server/src/index.ts index 766d2df4..fd28a807 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -95,9 +95,9 @@ const createTransport = async (req: express.Request): Promise => { // If the header "x-custom-auth-header" is present, use its value as the custom header name. if (req.headers["x-custom-auth-header"] !== undefined) { const customHeaderName = req.headers["x-custom-auth-header"] as string; - if (req.headers[customHeaderName.toLowerCase()] !== undefined) { - const value = req.headers[customHeaderName.toLowerCase()]; - headers[customHeaderName] = Array.isArray(value) ? value[value.length - 1] : value as string; + if (req.headers[customHeaderName] !== undefined) { + const value = req.headers[customHeaderName]; + headers[customHeaderName] = value as string; } } @@ -132,9 +132,9 @@ const createTransport = async (req: express.Request): Promise => { // If the header "x-custom-auth-header" is present, use its value as the custom header name. if (req.headers["x-custom-auth-header"] !== undefined) { const customHeaderName = req.headers["x-custom-auth-header"] as string; - if (req.headers[customHeaderName.toLowerCase()] !== undefined) { - const value = req.headers[customHeaderName.toLowerCase()]; - headers[customHeaderName] = Array.isArray(value) ? value[value.length - 1] : value as string; + if (req.headers[customHeaderName] !== undefined) { + const value = req.headers[customHeaderName]; + headers[customHeaderName] = value as string; } } From f04470ace7080f53233d1387e2dbb4d232bd5f7d Mon Sep 17 00:00:00 2001 From: cliffhall Date: Wed, 21 May 2025 17:45:19 -0400 Subject: [PATCH 010/177] Allow multiple client connections to the MCP server, by making a unique server tranpsort for each web app transport. * In server/src/index.ts - add serverTransports map - remove backingServerTransport var - in /mcp POST handler, when a new connection is being made - create a server transport - map the server transport using the session id from the web app connection - pass serverTransport to the mcpProxy instead of backingServerTransport - in /stdio GET handler, when a new connection is being made - create a server transport - map the server transport using the session id from the web app connection - pass serverTransport to the mcpProxy instead of backingServerTransport - in /sse GET handler, when a new connection is being made - create a server transport - map the server transport using the session id from the web app connection - pass serverTransport to the mcpProxy instead of backingServerTransport --- server/src/index.ts | 57 +++++++++++++++++++++------------------------ 1 file changed, 27 insertions(+), 30 deletions(-) diff --git a/server/src/index.ts b/server/src/index.ts index c967b60c..8bc8a53c 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -48,7 +48,8 @@ app.use((req, res, next) => { next(); }); -const webAppTransports: Map = new Map(); // Transports by sessionId +const webAppTransports: Map = new Map(); // Web app transports by web app sessionId +const serverTransports: Map = new Map(); // Server Transports by web app sessionId const createTransport = async (req: express.Request): Promise => { const query = req.query; @@ -137,8 +138,6 @@ const createTransport = async (req: express.Request): Promise => { } }; -let backingServerTransport: Transport | undefined; - app.get("/mcp", async (req, res) => { const sessionId = req.headers["mcp-session-id"] as string; console.log(`Received GET message for sessionId ${sessionId}`); @@ -161,12 +160,12 @@ app.get("/mcp", async (req, res) => { app.post("/mcp", async (req, res) => { const sessionId = req.headers["mcp-session-id"] as string | undefined; console.log(`Received POST message for sessionId ${sessionId}`); + let serverTransport: Transport | undefined; if (!sessionId) { try { console.log("New streamable-http connection"); try { - await backingServerTransport?.close(); - backingServerTransport = await createTransport(req); + serverTransport = await createTransport(req); } catch (error) { if (error instanceof SseError && error.code === 401) { console.error( @@ -180,12 +179,13 @@ app.post("/mcp", async (req, res) => { throw error; } - console.log("Connected MCP client to backing server transport"); + console.log("Connected MCP client to server transport"); const webAppTransport = new StreamableHTTPServerTransport({ sessionIdGenerator: randomUUID, onsessioninitialized: (sessionId) => { webAppTransports.set(sessionId, webAppTransport); + serverTransports.set(sessionId, serverTransport!); console.log("Created streamable web app transport " + sessionId); }, }); @@ -194,7 +194,7 @@ app.post("/mcp", async (req, res) => { mcpProxy({ transportToClient: webAppTransport, - transportToServer: backingServerTransport, + transportToServer: serverTransport, }); await (webAppTransport as StreamableHTTPServerTransport).handleRequest( @@ -229,10 +229,9 @@ app.post("/mcp", async (req, res) => { app.get("/stdio", async (req, res) => { try { console.log("New connection"); - + let serverTransport: Transport | undefined; try { - await backingServerTransport?.close(); - backingServerTransport = await createTransport(req); + serverTransport = await createTransport(req); } catch (error) { if (error instanceof SseError && error.code === 401) { console.error( @@ -250,26 +249,24 @@ app.get("/stdio", async (req, res) => { const webAppTransport = new SSEServerTransport("/message", res); webAppTransports.set(webAppTransport.sessionId, webAppTransport); - - console.log("Created web app transport"); + serverTransports.set(webAppTransport.sessionId, serverTransport); + console.log("Created client/server transports"); await webAppTransport.start(); - (backingServerTransport as StdioClientTransport).stderr!.on( - "data", - (chunk) => { - webAppTransport.send({ - jsonrpc: "2.0", - method: "notifications/stderr", - params: { - content: chunk.toString(), - }, - }); - }, - ); + + (serverTransport as StdioClientTransport).stderr!.on("data", (chunk) => { + webAppTransport.send({ + jsonrpc: "2.0", + method: "notifications/stderr", + params: { + content: chunk.toString(), + }, + }); + }); mcpProxy({ transportToClient: webAppTransport, - transportToServer: backingServerTransport, + transportToServer: serverTransport, }); console.log("Set up MCP proxy"); @@ -284,10 +281,9 @@ app.get("/sse", async (req, res) => { console.log( "New SSE connection. NOTE: The sse transport is deprecated and has been replaced by streamable-http", ); - + let serverTransport: SSEServerTransport | undefined; try { - await backingServerTransport?.close(); - backingServerTransport = await createTransport(req); + serverTransport = (await createTransport(req)) as SSEServerTransport; } catch (error) { if (error instanceof SseError && error.code === 401) { console.error( @@ -305,13 +301,14 @@ app.get("/sse", async (req, res) => { const webAppTransport = new SSEServerTransport("/message", res); webAppTransports.set(webAppTransport.sessionId, webAppTransport); - console.log("Created web app transport"); + serverTransports.set(webAppTransport.sessionId, serverTransport); + console.log("Created client/server transports"); await webAppTransport.start(); mcpProxy({ transportToClient: webAppTransport, - transportToServer: backingServerTransport, + transportToServer: serverTransport, }); console.log("Set up MCP proxy"); From 2870441fea8206625142f9d6b15ffe9904b82377 Mon Sep 17 00:00:00 2001 From: xiaoli Date: Sun, 25 May 2025 11:17:37 +0800 Subject: [PATCH 011/177] =?UTF-8?q?fix:=20fix=20review=20comments,=20again?= =?UTF-8?q?=F0=9F=98=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Remove unnecessary auth header name check - Extract operations on headers into a function --- client/src/lib/hooks/useConnection.ts | 3 - server/src/index.ts | 80 +++++++++++++-------------- 2 files changed, 39 insertions(+), 44 deletions(-) diff --git a/client/src/lib/hooks/useConnection.ts b/client/src/lib/hooks/useConnection.ts index f1f7ab9e..84956942 100644 --- a/client/src/lib/hooks/useConnection.ts +++ b/client/src/lib/hooks/useConnection.ts @@ -301,9 +301,6 @@ export function useConnection({ // Add custom header name as a special request header to let the server know which header to pass through if (authHeaderName.toLowerCase() !== "authorization") { headers[authHeaderName] = token; - if (headerName) { - headers["x-custom-auth-header"] = headerName; - } } else { headers[authHeaderName] = `Bearer ${token}`; } diff --git a/server/src/index.ts b/server/src/index.ts index fd28a807..de14e286 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -41,6 +41,43 @@ const { values } = parseArgs({ }, }); +// Function to get HTTP headers. +// Supports only "sse" and "streamable-http" transport types. +const getHttpHeaders = ( + req: express.Request, + transportType: string, +): HeadersInit => { + const headers: HeadersInit = { + Accept: + transportType === "sse" + ? "text/event-stream" + : "text/event-stream, application/json", + }; + const defaultHeaders = + transportType === "sse" + ? SSE_HEADERS_PASSTHROUGH + : STREAMABLE_HTTP_HEADERS_PASSTHROUGH; + + for (const key of defaultHeaders) { + if (req.headers[key] === undefined) { + continue; + } + + const value = req.headers[key]; + headers[key] = Array.isArray(value) ? value[value.length - 1] : value; + } + + // If the header "x-custom-auth-header" is present, use its value as the custom header name. + if (req.headers["x-custom-auth-header"] !== undefined) { + const customHeaderName = req.headers["x-custom-auth-header"] as string; + if (req.headers[customHeaderName] !== undefined) { + const value = req.headers[customHeaderName]; + headers[customHeaderName] = value as string; + } + } + return headers; +}; + const app = express(); app.use(cors()); app.use((req, res, next) => { @@ -79,27 +116,8 @@ const createTransport = async (req: express.Request): Promise => { return transport; } else if (transportType === "sse") { const url = query.url as string; - const headers: HeadersInit = { - Accept: "text/event-stream", - }; - for (const key of SSE_HEADERS_PASSTHROUGH) { - if (req.headers[key] === undefined) { - continue; - } - - const value = req.headers[key]; - headers[key] = Array.isArray(value) ? value[value.length - 1] : value; - } - - // If the header "x-custom-auth-header" is present, use its value as the custom header name. - if (req.headers["x-custom-auth-header"] !== undefined) { - const customHeaderName = req.headers["x-custom-auth-header"] as string; - if (req.headers[customHeaderName] !== undefined) { - const value = req.headers[customHeaderName]; - headers[customHeaderName] = value as string; - } - } + const headers = getHttpHeaders(req, transportType); console.log(`SSE transport: url=${url}, headers=${Object.keys(headers)}`); @@ -116,27 +134,7 @@ const createTransport = async (req: express.Request): Promise => { console.log("Connected to SSE transport"); return transport; } else if (transportType === "streamable-http") { - const headers: HeadersInit = { - Accept: "text/event-stream, application/json", - }; - - for (const key of STREAMABLE_HTTP_HEADERS_PASSTHROUGH) { - if (req.headers[key] === undefined) { - continue; - } - - const value = req.headers[key]; - headers[key] = Array.isArray(value) ? value[value.length - 1] : value; - } - - // If the header "x-custom-auth-header" is present, use its value as the custom header name. - if (req.headers["x-custom-auth-header"] !== undefined) { - const customHeaderName = req.headers["x-custom-auth-header"] as string; - if (req.headers[customHeaderName] !== undefined) { - const value = req.headers[customHeaderName]; - headers[customHeaderName] = value as string; - } - } + const headers = getHttpHeaders(req, transportType); const transport = new StreamableHTTPClientTransport( new URL(query.url as string), From bff09e04095b4b4ca9dc59eff79b617e99faf682 Mon Sep 17 00:00:00 2001 From: Marc Abramowitz Date: Tue, 27 May 2025 17:28:04 -0700 Subject: [PATCH 012/177] Resizable left sidebar Make left sidebar resizable so long URLs can be viewed in their entirety. Fixes https://github.com/modelcontextprotocol/inspector/issues/457 Vibe-coded with Cursor --- client/src/App.tsx | 67 ++++++++++++++---------- client/src/components/Sidebar.tsx | 2 +- client/src/lib/hooks/useDraggablePane.ts | 49 +++++++++++++++++ 3 files changed, 90 insertions(+), 28 deletions(-) diff --git a/client/src/App.tsx b/client/src/App.tsx index 68065e24..b57107d3 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -28,7 +28,7 @@ import React, { useState, } from "react"; import { useConnection } from "./lib/hooks/useConnection"; -import { useDraggablePane } from "./lib/hooks/useDraggablePane"; +import { useDraggablePane, useDraggableSidebar } from "./lib/hooks/useDraggablePane"; import { StdErrNotification } from "./lib/notificationTypes"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; @@ -163,6 +163,7 @@ const App = () => { const progressTokenRef = useRef(0); const { height: historyPaneHeight, handleDragStart } = useDraggablePane(300); + const { width: sidebarWidth, isDragging: isSidebarDragging, handleDragStart: handleSidebarDragStart } = useDraggableSidebar(320); const { connectionStatus, @@ -562,32 +563,44 @@ const App = () => { return (
- +
+ + {/* Drag handle for resizing sidebar */} +
+
{mcpClient ? ( diff --git a/client/src/components/Sidebar.tsx b/client/src/components/Sidebar.tsx index 516f48d5..2ae3f6b0 100644 --- a/client/src/components/Sidebar.tsx +++ b/client/src/components/Sidebar.tsx @@ -214,7 +214,7 @@ const Sidebar = ({ }, [generateMCPServerFile, toast, reportError]); return ( -
+

diff --git a/client/src/lib/hooks/useDraggablePane.ts b/client/src/lib/hooks/useDraggablePane.ts index 5c0e3573..77e19b8d 100644 --- a/client/src/lib/hooks/useDraggablePane.ts +++ b/client/src/lib/hooks/useDraggablePane.ts @@ -51,3 +51,52 @@ export function useDraggablePane(initialHeight: number) { handleDragStart, }; } + +export function useDraggableSidebar(initialWidth: number) { + const [width, setWidth] = useState(initialWidth); + const [isDragging, setIsDragging] = useState(false); + const dragStartX = useRef(0); + const dragStartWidth = useRef(0); + + const handleDragStart = useCallback( + (e: React.MouseEvent) => { + setIsDragging(true); + dragStartX.current = e.clientX; + dragStartWidth.current = width; + document.body.style.userSelect = "none"; + }, + [width], + ); + + const handleDragMove = useCallback( + (e: MouseEvent) => { + if (!isDragging) return; + const deltaX = e.clientX - dragStartX.current; + const newWidth = Math.max(200, Math.min(600, dragStartWidth.current + deltaX)); + setWidth(newWidth); + }, + [isDragging], + ); + + const handleDragEnd = useCallback(() => { + setIsDragging(false); + document.body.style.userSelect = ""; + }, []); + + useEffect(() => { + if (isDragging) { + window.addEventListener("mousemove", handleDragMove); + window.addEventListener("mouseup", handleDragEnd); + return () => { + window.removeEventListener("mousemove", handleDragMove); + window.removeEventListener("mouseup", handleDragEnd); + }; + } + }, [isDragging, handleDragMove, handleDragEnd]); + + return { + width, + isDragging, + handleDragStart, + }; +} From 0a3b994540273a3b5a2c1afef2430bb4516d0fec Mon Sep 17 00:00:00 2001 From: Marc Abramowitz Date: Tue, 27 May 2025 17:33:51 -0700 Subject: [PATCH 013/177] npm run prettier-fix --- client/src/App.tsx | 29 ++++++++++++++++++++---- client/src/lib/hooks/useDraggablePane.ts | 5 +++- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/client/src/App.tsx b/client/src/App.tsx index b57107d3..685bf50f 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -28,7 +28,10 @@ import React, { useState, } from "react"; import { useConnection } from "./lib/hooks/useConnection"; -import { useDraggablePane, useDraggableSidebar } from "./lib/hooks/useDraggablePane"; +import { + useDraggablePane, + useDraggableSidebar, +} from "./lib/hooks/useDraggablePane"; import { StdErrNotification } from "./lib/notificationTypes"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; @@ -163,7 +166,11 @@ const App = () => { const progressTokenRef = useRef(0); const { height: historyPaneHeight, handleDragStart } = useDraggablePane(300); - const { width: sidebarWidth, isDragging: isSidebarDragging, handleDragStart: handleSidebarDragStart } = useDraggableSidebar(320); + const { + width: sidebarWidth, + isDragging: isSidebarDragging, + handleDragStart: handleSidebarDragStart, + } = useDraggableSidebar(320); const { connectionStatus, @@ -564,7 +571,12 @@ const App = () => { return (
{ {/* Drag handle for resizing sidebar */}
diff --git a/client/src/lib/hooks/useDraggablePane.ts b/client/src/lib/hooks/useDraggablePane.ts index 77e19b8d..4ee5af54 100644 --- a/client/src/lib/hooks/useDraggablePane.ts +++ b/client/src/lib/hooks/useDraggablePane.ts @@ -72,7 +72,10 @@ export function useDraggableSidebar(initialWidth: number) { (e: MouseEvent) => { if (!isDragging) return; const deltaX = e.clientX - dragStartX.current; - const newWidth = Math.max(200, Math.min(600, dragStartWidth.current + deltaX)); + const newWidth = Math.max( + 200, + Math.min(600, dragStartWidth.current + deltaX), + ); setWidth(newWidth); }, [isDragging], From 0e5e94393a3bb7700d0abc8013988dc039cacda7 Mon Sep 17 00:00:00 2001 From: Marc Abramowitz Date: Tue, 27 May 2025 18:02:07 -0700 Subject: [PATCH 014/177] Add tip to README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index d7c34b97..baf9b322 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,9 @@ The MCP inspector is a developer tool for testing and debugging MCP servers. ![MCP Inspector Screenshot](https://raw.githubusercontent.com/modelcontextprotocol/inspector/main/mcp-inspector.png) +> **Tip:** +> You can resize the left sidebar by dragging its right edge. This allows you to adjust the space for server configuration, environment variables, and other controls to your preference. + ## Running the Inspector ### Requirements From 66bb9c896b0f3961d9edc88f845ccdd6b9d39cfb Mon Sep 17 00:00:00 2001 From: David Sanftenberg Date: Wed, 28 May 2025 12:22:22 +0100 Subject: [PATCH 015/177] Add quick start example --- README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/README.md b/README.md index d7c34b97..8d0de6f8 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,16 @@ The MCP inspector is a developer tool for testing and debugging MCP servers. - Node.js: ^22.7.5 +### Quick Start (UI mode) + +To get up and running right away with the UI, just execute the following: + +```bash +npx @modelcontextprotocol/inspector +``` + +The server will start up and the UI will be accessible at `http://localhost:6274`. + ### From an MCP server repository To inspect an MCP server implementation, there's no need to clone this repo. Instead, use `npx`. For example, if your server is built at `build/index.js`: From bc90f11dc88ae15de0adc059164ea35ed7f77d48 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Wed, 28 May 2025 13:44:55 -0400 Subject: [PATCH 016/177] Address [comment](https://github.com/modelcontextprotocol/inspector/pull/428/files/f04470ace7080f53233d1387e2dbb4d232bd5f7d#r2109509222) by @olaservo --- server/src/index.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/src/index.ts b/server/src/index.ts index 8bc8a53c..c4345ae6 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -281,9 +281,9 @@ app.get("/sse", async (req, res) => { console.log( "New SSE connection. NOTE: The sse transport is deprecated and has been replaced by streamable-http", ); - let serverTransport: SSEServerTransport | undefined; + let serverTransport: Transport | undefined; try { - serverTransport = (await createTransport(req)) as SSEServerTransport; + serverTransport = (await createTransport(req)); } catch (error) { if (error instanceof SseError && error.code === 401) { console.error( From 9bc6bd725ee5e974047d2949644355dac5615828 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Wed, 28 May 2025 13:46:58 -0400 Subject: [PATCH 017/177] Address [comment](https://github.com/modelcontextprotocol/inspector/pull/428/files/f04470ace7080f53233d1387e2dbb4d232bd5f7d#r2109509222) [by](https://github.com/modelcontextprotocol/inspector/pull/428/files/f04470ace7080f53233d1387e2dbb4d232bd5f7d#r2108137150) @olaservo --- server/src/index.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server/src/index.ts b/server/src/index.ts index c4345ae6..0b2aeec9 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -301,8 +301,9 @@ app.get("/sse", async (req, res) => { const webAppTransport = new SSEServerTransport("/message", res); webAppTransports.set(webAppTransport.sessionId, webAppTransport); + console.log("Created client transport"); serverTransports.set(webAppTransport.sessionId, serverTransport); - console.log("Created client/server transports"); + console.log("Created server transport"); await webAppTransport.start(); From 0c1962c2d06e11f7dab395a38c7104a9c0121640 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Wed, 28 May 2025 15:46:07 -0400 Subject: [PATCH 018/177] prettier --- server/src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/src/index.ts b/server/src/index.ts index 0b2aeec9..73288f67 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -283,7 +283,7 @@ app.get("/sse", async (req, res) => { ); let serverTransport: Transport | undefined; try { - serverTransport = (await createTransport(req)); + serverTransport = await createTransport(req); } catch (error) { if (error instanceof SseError && error.code === 401) { console.error( From 10e3202832c51add7e0fdb8ab16cecde2646c47e Mon Sep 17 00:00:00 2001 From: xiaoli Date: Thu, 29 May 2025 11:49:57 +0800 Subject: [PATCH 019/177] fix: Fix the issue of accidentally losing 'x-custom-auth-header' --- client/src/lib/hooks/useConnection.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/client/src/lib/hooks/useConnection.ts b/client/src/lib/hooks/useConnection.ts index 84956942..f1c29b2d 100644 --- a/client/src/lib/hooks/useConnection.ts +++ b/client/src/lib/hooks/useConnection.ts @@ -301,6 +301,7 @@ export function useConnection({ // Add custom header name as a special request header to let the server know which header to pass through if (authHeaderName.toLowerCase() !== "authorization") { headers[authHeaderName] = token; + headers["x-custom-auth-header"] = authHeaderName; } else { headers[authHeaderName] = `Bearer ${token}`; } From 46d3d844f8884f2099a5e3fb078b5bf337ab2a9f Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Fri, 16 May 2025 19:20:40 +0100 Subject: [PATCH 020/177] reset authorization url --- client/src/components/AuthDebugger.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/client/src/components/AuthDebugger.tsx b/client/src/components/AuthDebugger.tsx index d0b0432d..98d58e23 100644 --- a/client/src/components/AuthDebugger.tsx +++ b/client/src/components/AuthDebugger.tsx @@ -183,6 +183,7 @@ const AuthDebugger = ({ latestError: null, oauthClientInfo: null, authorizationCode: "", + authorizationUrl: "", validationError: null, oauthMetadata: null, statusMessage: { From befadc0042ac31ad649dca02f31097cb387541cd Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Fri, 16 May 2025 20:53:21 +0100 Subject: [PATCH 021/177] very wip draft auth spec support --- client/src/App.tsx | 3 +- client/src/components/AuthDebugger.tsx | 2 +- client/src/components/OAuthFlowProgress.tsx | 25 +++++++++++++++++ client/src/lib/auth-types.ts | 3 ++ client/src/lib/oauth-state-machine.ts | 31 +++++++++++++++------ 5 files changed, 53 insertions(+), 11 deletions(-) diff --git a/client/src/App.tsx b/client/src/App.tsx index cb411452..a30dcc9c 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -125,8 +125,9 @@ const App = () => { isInitiatingAuth: false, oauthTokens: null, loading: true, - oauthStep: "metadata_discovery", + oauthStep: "resource_metadata_discovery", oauthMetadata: null, + resourceMetadata: null, oauthClientInfo: null, authorizationUrl: null, authorizationCode: "", diff --git a/client/src/components/AuthDebugger.tsx b/client/src/components/AuthDebugger.tsx index 98d58e23..083fc39b 100644 --- a/client/src/components/AuthDebugger.tsx +++ b/client/src/components/AuthDebugger.tsx @@ -179,7 +179,7 @@ const AuthDebugger = ({ serverAuthProvider.clear(); updateAuthState({ oauthTokens: null, - oauthStep: "metadata_discovery", + oauthStep: "resource_metadata_discovery", latestError: null, oauthClientInfo: null, authorizationCode: "", diff --git a/client/src/components/OAuthFlowProgress.tsx b/client/src/components/OAuthFlowProgress.tsx index 396af142..8167afa6 100644 --- a/client/src/components/OAuthFlowProgress.tsx +++ b/client/src/components/OAuthFlowProgress.tsx @@ -79,6 +79,16 @@ export const OAuthFlowProgress = ({ null, ); + const steps: Array = [ + "resource_metadata_discovery", + "metadata_discovery", + "client_registration", + "authorization_redirect", + "authorization_code", + "token_request", + "complete", + ]; + const currentStepIdx = steps.findIndex((s) => s === authState.oauthStep); useEffect(() => { @@ -124,6 +134,21 @@ export const OAuthFlowProgress = ({

+ + {authState.resourceMetadata && ( +
+ + Retrieved OAuth Resource Metadata from {(new URL('/.well-known/oauth-protected-resource', serverUrl)).href} + +
+                {JSON.stringify(authState.resourceMetadata, null, 2)}
+              
+
+ )} +
Promise; execute: (context: StateMachineContext) => Promise; - nextStep: OAuthStep; } // State machine transitions export const oauthTransitions: Record = { - metadata_discovery: { + resource_metadata_discovery: { canTransition: async () => true, execute: async (context) => { - const metadata = await discoverOAuthMetadata(context.serverUrl); + // TODO: use sdk + const url = new URL("/.well-known/oauth-protected-resource", context.serverUrl); + const response = await fetch(url); + + const resourceMetadata = await response.json(); + context.updateState({ + resourceMetadata: resourceMetadata, + oauthStep: "metadata_discovery", + }); + }, + }, + + metadata_discovery: { + canTransition: async (context) => !!context.state.resourceMetadata, + execute: async (context) => { + // TODO: use sdk + let authServerUrl = context.serverUrl; + if (context.state.resourceMetadata?.authorization_servers?.[0]) { + authServerUrl = context.state.resourceMetadata.authorization_servers[0]; + } + const metadata = await discoverOAuthMetadata(authServerUrl); if (!metadata) { throw new Error("Failed to discover OAuth metadata"); } @@ -37,7 +56,6 @@ export const oauthTransitions: Record = { oauthStep: "client_registration", }); }, - nextStep: "client_registration", }, client_registration: { @@ -62,7 +80,6 @@ export const oauthTransitions: Record = { oauthStep: "authorization_redirect", }); }, - nextStep: "authorization_redirect", }, authorization_redirect: { @@ -93,7 +110,6 @@ export const oauthTransitions: Record = { oauthStep: "authorization_code", }); }, - nextStep: "authorization_code", }, authorization_code: { @@ -114,7 +130,6 @@ export const oauthTransitions: Record = { oauthStep: "token_request", }); }, - nextStep: "token_request", }, token_request: { @@ -144,7 +159,6 @@ export const oauthTransitions: Record = { oauthStep: "complete", }); }, - nextStep: "complete", }, complete: { @@ -152,7 +166,6 @@ export const oauthTransitions: Record = { execute: async () => { // No-op for complete state }, - nextStep: "complete", }, }; From 00893afc0be1577748cac65fc3f95cae2713051c Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Thu, 22 May 2025 18:36:48 +0100 Subject: [PATCH 022/177] wip new metadata --- client/src/App.tsx | 2 +- client/src/components/AuthDebugger.tsx | 2 +- client/src/components/OAuthFlowProgress.tsx | 20 ++----------- client/src/lib/auth-types.ts | 1 - client/src/lib/oauth-state-machine.ts | 32 +++++++++------------ 5 files changed, 19 insertions(+), 38 deletions(-) diff --git a/client/src/App.tsx b/client/src/App.tsx index a30dcc9c..4708f08e 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -125,7 +125,7 @@ const App = () => { isInitiatingAuth: false, oauthTokens: null, loading: true, - oauthStep: "resource_metadata_discovery", + oauthStep: "metadata_discovery", oauthMetadata: null, resourceMetadata: null, oauthClientInfo: null, diff --git a/client/src/components/AuthDebugger.tsx b/client/src/components/AuthDebugger.tsx index 083fc39b..98d58e23 100644 --- a/client/src/components/AuthDebugger.tsx +++ b/client/src/components/AuthDebugger.tsx @@ -179,7 +179,7 @@ const AuthDebugger = ({ serverAuthProvider.clear(); updateAuthState({ oauthTokens: null, - oauthStep: "resource_metadata_discovery", + oauthStep: "metadata_discovery", latestError: null, oauthClientInfo: null, authorizationCode: "", diff --git a/client/src/components/OAuthFlowProgress.tsx b/client/src/components/OAuthFlowProgress.tsx index 8167afa6..9f079dde 100644 --- a/client/src/components/OAuthFlowProgress.tsx +++ b/client/src/components/OAuthFlowProgress.tsx @@ -57,6 +57,7 @@ interface OAuthFlowProgressProps { } const steps: Array = [ + "resource_metadata_discovery", "metadata_discovery", "client_registration", "authorization_redirect", @@ -79,16 +80,6 @@ export const OAuthFlowProgress = ({ null, ); - const steps: Array = [ - "resource_metadata_discovery", - "metadata_discovery", - "client_registration", - "authorization_redirect", - "authorization_code", - "token_request", - "complete", - ]; - const currentStepIdx = steps.findIndex((s) => s === authState.oauthStep); useEffect(() => { @@ -135,8 +126,8 @@ export const OAuthFlowProgress = ({
{authState.resourceMetadata && (
@@ -148,11 +139,6 @@ export const OAuthFlowProgress = ({
)} -
- {provider.getServerMetadata() && (
diff --git a/client/src/lib/auth-types.ts b/client/src/lib/auth-types.ts index 87e8f8bc..2a9171f0 100644 --- a/client/src/lib/auth-types.ts +++ b/client/src/lib/auth-types.ts @@ -7,7 +7,6 @@ import { // OAuth flow steps export type OAuthStep = - | "resource_metadata_discovery" | "metadata_discovery" | "client_registration" | "authorization_redirect" diff --git a/client/src/lib/oauth-state-machine.ts b/client/src/lib/oauth-state-machine.ts index bef728d7..a48b32e1 100644 --- a/client/src/lib/oauth-state-machine.ts +++ b/client/src/lib/oauth-state-machine.ts @@ -20,31 +20,26 @@ export interface StateTransition { execute: (context: StateMachineContext) => Promise; } +const fetchProtectedResourceMetadata = async (serverUrl: string): Promise => { + // TODO: use sdk + const url = new URL("/.well-known/oauth-protected-resource", serverUrl); + const response = await fetch(url); + const resourceMetadata = await response.json(); + + return resourceMetadata; +} + // State machine transitions export const oauthTransitions: Record = { - resource_metadata_discovery: { + metadata_discovery: { canTransition: async () => true, execute: async (context) => { - // TODO: use sdk - const url = new URL("/.well-known/oauth-protected-resource", context.serverUrl); - const response = await fetch(url); - const resourceMetadata = await response.json(); - context.updateState({ - resourceMetadata: resourceMetadata, - oauthStep: "metadata_discovery", - }); - }, - }, + try { - metadata_discovery: { - canTransition: async (context) => !!context.state.resourceMetadata, - execute: async (context) => { - // TODO: use sdk - let authServerUrl = context.serverUrl; - if (context.state.resourceMetadata?.authorization_servers?.[0]) { - authServerUrl = context.state.resourceMetadata.authorization_servers[0]; } + const resourceMetadata = fetchProtectedResourceMetadata(serverUrl) + const metadata = await discoverOAuthMetadata(authServerUrl); if (!metadata) { throw new Error("Failed to discover OAuth metadata"); @@ -52,6 +47,7 @@ export const oauthTransitions: Record = { const parsedMetadata = await OAuthMetadataSchema.parseAsync(metadata); context.provider.saveServerMetadata(parsedMetadata); context.updateState({ + resourceMetadata, oauthMetadata: parsedMetadata, oauthStep: "client_registration", }); From c6ddcf4c90951319f9b6bce72c1d3b3ca72c9d9b Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Thu, 22 May 2025 18:40:27 +0100 Subject: [PATCH 023/177] fix --- client/src/lib/oauth-state-machine.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/client/src/lib/oauth-state-machine.ts b/client/src/lib/oauth-state-machine.ts index a48b32e1..ca473b49 100644 --- a/client/src/lib/oauth-state-machine.ts +++ b/client/src/lib/oauth-state-machine.ts @@ -34,11 +34,15 @@ export const oauthTransitions: Record = { metadata_discovery: { canTransition: async () => true, execute: async (context) => { - - try { - - } - const resourceMetadata = fetchProtectedResourceMetadata(serverUrl) + const authServerUrl = context.serverUrl; + // try { + // const resourceMetadata = await fetchProtectedResourceMetadata(context.serverUrl); + // if (resourceMetadata && resourceMetadata) { + // authServerUrl = resourceMetadata + // } + // } catch (_error) { + // // pass + // } const metadata = await discoverOAuthMetadata(authServerUrl); if (!metadata) { From b2fa99668efae6b1b0e82d3df854b6546755c765 Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Thu, 29 May 2025 10:19:39 +0100 Subject: [PATCH 024/177] bump typescript sdk --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index d46b3ef8..a5e09c6a 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,7 @@ "@modelcontextprotocol/inspector-cli": "^0.13.0", "@modelcontextprotocol/inspector-client": "^0.13.0", "@modelcontextprotocol/inspector-server": "^0.13.0", - "@modelcontextprotocol/sdk": "^1.11.5", + "@modelcontextprotocol/sdk": "^1.12.0", "concurrently": "^9.0.1", "open": "^10.1.0", "shell-quote": "^1.8.2", From 73fde03aa4e7d9f5b91bcc5c92d4fd9872b0158d Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Thu, 29 May 2025 10:56:09 +0100 Subject: [PATCH 025/177] working metadata fetch --- client/src/App.tsx | 17 +----- client/src/components/AuthDebugger.tsx | 11 +--- client/src/components/OAuthFlowProgress.tsx | 14 ++++- .../__tests__/AuthDebugger.test.tsx | 15 +---- client/src/lib/auth-types.ts | 21 ++++++- client/src/lib/oauth-state-machine.ts | 39 +++++++------ package-lock.json | 58 ++----------------- 7 files changed, 63 insertions(+), 112 deletions(-) diff --git a/client/src/App.tsx b/client/src/App.tsx index 4708f08e..55a4541e 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -19,7 +19,7 @@ import { } from "@modelcontextprotocol/sdk/types.js"; import { OAuthTokensSchema } from "@modelcontextprotocol/sdk/shared/auth.js"; import { SESSION_KEYS, getServerSpecificKey } from "./lib/constants"; -import { AuthDebuggerState } from "./lib/auth-types"; +import { AuthDebuggerState, EMPTY_DEBUGGER_STATE } from "./lib/auth-types"; import { cacheToolOutputSchemas } from "./utils/schemaUtils"; import React, { Suspense, @@ -121,20 +121,7 @@ const App = () => { const [isAuthDebuggerVisible, setIsAuthDebuggerVisible] = useState(false); // Auth debugger state - const [authState, setAuthState] = useState({ - isInitiatingAuth: false, - oauthTokens: null, - loading: true, - oauthStep: "metadata_discovery", - oauthMetadata: null, - resourceMetadata: null, - oauthClientInfo: null, - authorizationUrl: null, - authorizationCode: "", - latestError: null, - statusMessage: null, - validationError: null, - }); + const [authState, setAuthState] = useState(EMPTY_DEBUGGER_STATE); // Helper function to update specific auth state properties const updateAuthState = (updates: Partial) => { diff --git a/client/src/components/AuthDebugger.tsx b/client/src/components/AuthDebugger.tsx index 98d58e23..5565a77a 100644 --- a/client/src/components/AuthDebugger.tsx +++ b/client/src/components/AuthDebugger.tsx @@ -2,7 +2,7 @@ import { useCallback, useMemo } from "react"; import { Button } from "@/components/ui/button"; import { DebugInspectorOAuthClientProvider } from "../lib/auth"; import { AlertCircle } from "lucide-react"; -import { AuthDebuggerState } from "../lib/auth-types"; +import { AuthDebuggerState, EMPTY_DEBUGGER_STATE } from "../lib/auth-types"; import { OAuthFlowProgress } from "./OAuthFlowProgress"; import { OAuthStateMachine } from "../lib/oauth-state-machine"; @@ -178,14 +178,7 @@ const AuthDebugger = ({ ); serverAuthProvider.clear(); updateAuthState({ - oauthTokens: null, - oauthStep: "metadata_discovery", - latestError: null, - oauthClientInfo: null, - authorizationCode: "", - authorizationUrl: "", - validationError: null, - oauthMetadata: null, + ...EMPTY_DEBUGGER_STATE, statusMessage: { type: "success", message: "OAuth tokens cleared successfully", diff --git a/client/src/components/OAuthFlowProgress.tsx b/client/src/components/OAuthFlowProgress.tsx index 9f079dde..6bd50bcb 100644 --- a/client/src/components/OAuthFlowProgress.tsx +++ b/client/src/components/OAuthFlowProgress.tsx @@ -57,7 +57,6 @@ interface OAuthFlowProgressProps { } const steps: Array = [ - "resource_metadata_discovery", "metadata_discovery", "client_registration", "authorization_redirect", @@ -139,6 +138,19 @@ export const OAuthFlowProgress = ({ )} + {authState.resourceMetadataError && ( +
+

+ Failed to retrieve resource metadata, falling back to /.well-known/oauth-authorization-server: +

+

+ {authState.resourceMetadataError.message} + {authState.resourceMetadataError instanceof TypeError + ? " (This could indicate the endpoint doesn't exist or does not have CORS configured)" + : authState.resourceMetadataError['status'] && ` (${authState.resourceMetadataError['status']})`} +

+
+ )} {provider.getServerMetadata() && (
diff --git a/client/src/components/__tests__/AuthDebugger.test.tsx b/client/src/components/__tests__/AuthDebugger.test.tsx index 7c539661..42a289ff 100644 --- a/client/src/components/__tests__/AuthDebugger.test.tsx +++ b/client/src/components/__tests__/AuthDebugger.test.tsx @@ -51,6 +51,7 @@ import { auth, } from "@modelcontextprotocol/sdk/client/auth.js"; import { OAuthMetadata } from "@modelcontextprotocol/sdk/shared/auth.js"; +import { EMPTY_DEBUGGER_STATE } from "@/lib/auth-types"; // Type the mocked functions properly const mockDiscoverOAuthMetadata = discoverOAuthMetadata as jest.MockedFunction< @@ -84,19 +85,7 @@ Object.defineProperty(window, "location", { }); describe("AuthDebugger", () => { - const defaultAuthState = { - isInitiatingAuth: false, - oauthTokens: null, - loading: false, - oauthStep: "metadata_discovery" as const, - oauthMetadata: null, - oauthClientInfo: null, - authorizationUrl: null, - authorizationCode: "", - latestError: null, - statusMessage: null, - validationError: null, - }; + const defaultAuthState = EMPTY_DEBUGGER_STATE; const defaultProps = { serverUrl: "https://example.com", diff --git a/client/src/lib/auth-types.ts b/client/src/lib/auth-types.ts index 2a9171f0..40262601 100644 --- a/client/src/lib/auth-types.ts +++ b/client/src/lib/auth-types.ts @@ -3,6 +3,7 @@ import { OAuthClientInformationFull, OAuthClientInformation, OAuthTokens, + OAuthProtectedResourceMetadata, } from "@modelcontextprotocol/sdk/shared/auth.js"; // OAuth flow steps @@ -28,8 +29,8 @@ export interface AuthDebuggerState { oauthTokens: OAuthTokens | null; loading: boolean; oauthStep: OAuthStep; - // TODO: use sdk type - resourceMetadata: object | null; + resourceMetadata: OAuthProtectedResourceMetadata | null; + resourceMetadataError: Error | { status: number; statusText: string; message: string } | null; oauthMetadata: OAuthMetadata | null; oauthClientInfo: OAuthClientInformationFull | OAuthClientInformation | null; authorizationUrl: string | null; @@ -38,3 +39,19 @@ export interface AuthDebuggerState { statusMessage: StatusMessage | null; validationError: string | null; } + +export const EMPTY_DEBUGGER_STATE: AuthDebuggerState = { + isInitiatingAuth: false, + oauthTokens: null, + loading: true, + oauthStep: "metadata_discovery", + oauthMetadata: null, + resourceMetadata: null, + resourceMetadataError: null, + oauthClientInfo: null, + authorizationUrl: null, + authorizationCode: "", + latestError: null, + statusMessage: null, + validationError: null, +} diff --git a/client/src/lib/oauth-state-machine.ts b/client/src/lib/oauth-state-machine.ts index ca473b49..5b2925ac 100644 --- a/client/src/lib/oauth-state-machine.ts +++ b/client/src/lib/oauth-state-machine.ts @@ -5,8 +5,9 @@ import { registerClient, startAuthorization, exchangeAuthorization, + discoverOAuthProtectedResourceMetadata, } from "@modelcontextprotocol/sdk/client/auth.js"; -import { OAuthMetadataSchema } from "@modelcontextprotocol/sdk/shared/auth.js"; +import { OAuthMetadataSchema, OAuthProtectedResourceMetadata } from "@modelcontextprotocol/sdk/shared/auth.js"; export interface StateMachineContext { state: AuthDebuggerState; @@ -20,29 +21,28 @@ export interface StateTransition { execute: (context: StateMachineContext) => Promise; } -const fetchProtectedResourceMetadata = async (serverUrl: string): Promise => { - // TODO: use sdk - const url = new URL("/.well-known/oauth-protected-resource", serverUrl); - const response = await fetch(url); - const resourceMetadata = await response.json(); - - return resourceMetadata; -} - // State machine transitions export const oauthTransitions: Record = { metadata_discovery: { canTransition: async () => true, execute: async (context) => { - const authServerUrl = context.serverUrl; - // try { - // const resourceMetadata = await fetchProtectedResourceMetadata(context.serverUrl); - // if (resourceMetadata && resourceMetadata) { - // authServerUrl = resourceMetadata - // } - // } catch (_error) { - // // pass - // } + let authServerUrl = context.serverUrl; + let resourceMetadata: OAuthProtectedResourceMetadata | null = null; + let resourceMetadataError: Error | null = null; + try { + resourceMetadata = await discoverOAuthProtectedResourceMetadata(context.serverUrl); + if (resourceMetadata && resourceMetadata.authorization_servers?.length) { + authServerUrl = resourceMetadata.authorization_servers[0]; + } + } catch (e) { + console.info(`Failed to find protected resource metadata: ${e}`); + console.log(e); + if (e instanceof Error) { + resourceMetadataError = e; + } else { + resourceMetadataError = new Error(String(e)); + } + } const metadata = await discoverOAuthMetadata(authServerUrl); if (!metadata) { @@ -52,6 +52,7 @@ export const oauthTransitions: Record = { context.provider.saveServerMetadata(parsedMetadata); context.updateState({ resourceMetadata, + resourceMetadataError, oauthMetadata: parsedMetadata, oauthStep: "client_registration", }); diff --git a/package-lock.json b/package-lock.json index 2920ca59..6e5d73f0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,7 +17,7 @@ "@modelcontextprotocol/inspector-cli": "^0.13.0", "@modelcontextprotocol/inspector-client": "^0.13.0", "@modelcontextprotocol/inspector-server": "^0.13.0", - "@modelcontextprotocol/sdk": "^1.11.5", + "@modelcontextprotocol/sdk": "^1.12.0", "concurrently": "^9.0.1", "open": "^10.1.0", "shell-quote": "^1.8.2", @@ -2005,12 +2005,11 @@ "link": true }, "node_modules/@modelcontextprotocol/sdk": { - "version": "1.11.5", - "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.11.5.tgz", - "integrity": "sha512-gS7Q7IHpKxjVaNLMUZyTtatZ63ca3h418zPPntAhu/MvG5yfz/8HMcDAOpvpQfx3V3dsw9QQxk8RuFNrQhLlgA==", - "license": "MIT", + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.12.0.tgz", + "integrity": "sha512-m//7RlINx1F3sz3KqwY1WWzVgTcYX52HYk4bJ1hkBXV3zccAEth+jRvG8DBRrdaQuRsPAJOx2MH3zaHNCKL7Zg==", "dependencies": { - "ajv": "^8.17.1", + "ajv": "^6.12.6", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", @@ -2026,28 +2025,6 @@ "node": ">=18" } }, - "node_modules/@modelcontextprotocol/sdk/node_modules/ajv": { - "version": "8.17.1", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", - "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.3", - "fast-uri": "^3.0.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/@modelcontextprotocol/sdk/node_modules/json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "license": "MIT" - }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", @@ -5719,22 +5696,6 @@ "dev": true, "license": "MIT" }, - "node_modules/fast-uri": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.0.6.tgz", - "integrity": "sha512-Atfo14OibSv5wAp4VWNsFYE1AchQRTv9cBGWET4pZWHzYshFSS9NQI6I57rdKn9croWVMbYFbLhJ+yJvmZIIHw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "BSD-3-Clause" - }, "node_modules/fastq": { "version": "1.19.1", "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz", @@ -9064,15 +9025,6 @@ "node": ">=0.10.0" } }, - "node_modules/require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/requires-port": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", From 82858bed30fd5f93192f65c9dc7ea6e6deadbfdf Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Thu, 29 May 2025 11:17:21 +0100 Subject: [PATCH 026/177] show proper authserverurl --- client/src/components/OAuthFlowProgress.tsx | 72 +++++++++++++-------- client/src/lib/auth-types.ts | 2 + client/src/lib/oauth-state-machine.ts | 5 +- 3 files changed, 49 insertions(+), 30 deletions(-) diff --git a/client/src/components/OAuthFlowProgress.tsx b/client/src/components/OAuthFlowProgress.tsx index 6bd50bcb..2e74bf68 100644 --- a/client/src/components/OAuthFlowProgress.tsx +++ b/client/src/components/OAuthFlowProgress.tsx @@ -128,38 +128,54 @@ export const OAuthFlowProgress = ({ label="Metadata Discovery" {...getStepProps("metadata_discovery")} > - {authState.resourceMetadata && ( -
- - Retrieved OAuth Resource Metadata from {(new URL('/.well-known/oauth-protected-resource', serverUrl)).href} - -
-                {JSON.stringify(authState.resourceMetadata, null, 2)}
-              
-
- )} - {authState.resourceMetadataError && ( -
-

- Failed to retrieve resource metadata, falling back to /.well-known/oauth-authorization-server: -

-

- {authState.resourceMetadataError.message} - {authState.resourceMetadataError instanceof TypeError - ? " (This could indicate the endpoint doesn't exist or does not have CORS configured)" - : authState.resourceMetadataError['status'] && ` (${authState.resourceMetadataError['status']})`} -

-
- )} {provider.getServerMetadata() && (
- Retrieved OAuth Metadata from {serverUrl} - /.well-known/oauth-authorization-server + OAuth Metadata Sources + {!authState.resourceMetadata && " ā„¹ļø"} -
-                {JSON.stringify(provider.getServerMetadata(), null, 2)}
-              
+ + {authState.resourceMetadata && ( +
+

Resource Metadata:

+

+ From {new URL('/.well-known/oauth-protected-resource', serverUrl).href} +

+
+                    {JSON.stringify(authState.resourceMetadata, null, 2)}
+                  
+
+ )} + + {authState.resourceMetadataError && ( +
+

+ ā„¹ļø No resource metadata available from {' '} + + {new URL('/.well-known/oauth-protected-resource', serverUrl).href} + +

+

+ Resource metadata was added in the 2025-DRAFT-v2 specification update +
+ {authState.resourceMetadataError.message} + {authState.resourceMetadataError instanceof TypeError + && " (This could indicate the endpoint doesn't exist or does not have CORS configured)"} +

+
+ )} + + {provider.getServerMetadata() && ( +
+

Authorization Server Metadata:

+ {authState.authServerUrl &&

+ From {new URL('/.well-known/oauth-authorization-server', authState.authServerUrl).href} +

} +
+                    {JSON.stringify(provider.getServerMetadata(), null, 2)}
+                  
+
+ )}
)} diff --git a/client/src/lib/auth-types.ts b/client/src/lib/auth-types.ts index 40262601..2541e822 100644 --- a/client/src/lib/auth-types.ts +++ b/client/src/lib/auth-types.ts @@ -31,6 +31,7 @@ export interface AuthDebuggerState { oauthStep: OAuthStep; resourceMetadata: OAuthProtectedResourceMetadata | null; resourceMetadataError: Error | { status: number; statusText: string; message: string } | null; + authServerUrl: URL | null; oauthMetadata: OAuthMetadata | null; oauthClientInfo: OAuthClientInformationFull | OAuthClientInformation | null; authorizationUrl: string | null; @@ -48,6 +49,7 @@ export const EMPTY_DEBUGGER_STATE: AuthDebuggerState = { oauthMetadata: null, resourceMetadata: null, resourceMetadataError: null, + authServerUrl: null, oauthClientInfo: null, authorizationUrl: null, authorizationCode: "", diff --git a/client/src/lib/oauth-state-machine.ts b/client/src/lib/oauth-state-machine.ts index 5b2925ac..939e5d6c 100644 --- a/client/src/lib/oauth-state-machine.ts +++ b/client/src/lib/oauth-state-machine.ts @@ -26,13 +26,13 @@ export const oauthTransitions: Record = { metadata_discovery: { canTransition: async () => true, execute: async (context) => { - let authServerUrl = context.serverUrl; + let authServerUrl = new URL(context.serverUrl); let resourceMetadata: OAuthProtectedResourceMetadata | null = null; let resourceMetadataError: Error | null = null; try { resourceMetadata = await discoverOAuthProtectedResourceMetadata(context.serverUrl); if (resourceMetadata && resourceMetadata.authorization_servers?.length) { - authServerUrl = resourceMetadata.authorization_servers[0]; + authServerUrl = new URL(resourceMetadata.authorization_servers[0]); } } catch (e) { console.info(`Failed to find protected resource metadata: ${e}`); @@ -53,6 +53,7 @@ export const oauthTransitions: Record = { context.updateState({ resourceMetadata, resourceMetadataError, + authServerUrl, oauthMetadata: parsedMetadata, oauthStep: "client_registration", }); From 0dbf75a66427f1f430095d567595e373fcaf185b Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Thu, 29 May 2025 11:50:09 +0100 Subject: [PATCH 027/177] store state before redirect --- client/src/App.tsx | 31 +++++++++++++++----- client/src/components/AuthDebugger.tsx | 6 ++++ client/src/components/OAuthDebugCallback.tsx | 19 ++++++++++-- client/src/lib/constants.ts | 1 + 4 files changed, 47 insertions(+), 10 deletions(-) diff --git a/client/src/App.tsx b/client/src/App.tsx index 55a4541e..8be23a5b 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -234,21 +234,36 @@ const App = () => { ({ authorizationCode, errorMsg, + restoredState, }: { authorizationCode?: string; errorMsg?: string; + restoredState?: AuthDebuggerState; }) => { setIsAuthDebuggerVisible(true); - if (authorizationCode) { + + if (restoredState) { + // Restore the previous auth state updateAuthState({ - authorizationCode, - oauthStep: "token_request", - }); - } - if (errorMsg) { - updateAuthState({ - latestError: new Error(errorMsg), + ...restoredState, + // Update with the new authorization code if provided + authorizationCode: authorizationCode || restoredState.authorizationCode, + oauthStep: authorizationCode ? "token_request" : restoredState.oauthStep, + latestError: errorMsg ? new Error(errorMsg) : restoredState.latestError, }); + } else { + // Fallback to the original behavior if no state was restored + if (authorizationCode) { + updateAuthState({ + authorizationCode, + oauthStep: "token_request", + }); + } + if (errorMsg) { + updateAuthState({ + latestError: new Error(errorMsg), + }); + } } }, [], diff --git a/client/src/components/AuthDebugger.tsx b/client/src/components/AuthDebugger.tsx index 5565a77a..0ef8e70b 100644 --- a/client/src/components/AuthDebugger.tsx +++ b/client/src/components/AuthDebugger.tsx @@ -5,6 +5,7 @@ import { AlertCircle } from "lucide-react"; import { AuthDebuggerState, EMPTY_DEBUGGER_STATE } from "../lib/auth-types"; import { OAuthFlowProgress } from "./OAuthFlowProgress"; import { OAuthStateMachine } from "../lib/oauth-state-machine"; +import { SESSION_KEYS } from "../lib/constants"; export interface AuthDebuggerProps { serverUrl: string; @@ -141,6 +142,11 @@ const AuthDebugger = ({ currentState.oauthStep === "authorization_code" && currentState.authorizationUrl ) { + // Store the current auth state before redirecting + sessionStorage.setItem( + SESSION_KEYS.AUTH_DEBUGGER_STATE, + JSON.stringify(currentState) + ); // Open the authorization URL automatically window.location.href = currentState.authorizationUrl; break; diff --git a/client/src/components/OAuthDebugCallback.tsx b/client/src/components/OAuthDebugCallback.tsx index 88d931c0..af9944ac 100644 --- a/client/src/components/OAuthDebugCallback.tsx +++ b/client/src/components/OAuthDebugCallback.tsx @@ -9,9 +9,11 @@ interface OAuthCallbackProps { onConnect: ({ authorizationCode, errorMsg, + restoredState, }: { authorizationCode?: string; errorMsg?: string; + restoredState?: any; }) => void; } @@ -34,6 +36,19 @@ const OAuthDebugCallback = ({ onConnect }: OAuthCallbackProps) => { } const serverUrl = sessionStorage.getItem(SESSION_KEYS.SERVER_URL); + + // Try to restore the auth state + const storedState = sessionStorage.getItem(SESSION_KEYS.AUTH_DEBUGGER_STATE); + let restoredState = null; + if (storedState) { + try { + restoredState = JSON.parse(storedState); + // Clean up the stored state + sessionStorage.removeItem(SESSION_KEYS.AUTH_DEBUGGER_STATE); + } catch (e) { + console.error("Failed to parse stored auth state:", e); + } + } // ServerURL isn't set, this can happen if we've opened the // authentication request in a new tab, so we don't have the same @@ -50,8 +65,8 @@ const OAuthDebugCallback = ({ onConnect }: OAuthCallbackProps) => { } // Instead of storing in sessionStorage, pass the code directly - // to the auth state manager through onConnect - onConnect({ authorizationCode: params.code }); + // to the auth state manager through onConnect, along with restored state + onConnect({ authorizationCode: params.code, restoredState }); }; handleCallback().finally(() => { diff --git a/client/src/lib/constants.ts b/client/src/lib/constants.ts index 4c3e27aa..3acbda91 100644 --- a/client/src/lib/constants.ts +++ b/client/src/lib/constants.ts @@ -7,6 +7,7 @@ export const SESSION_KEYS = { TOKENS: "mcp_tokens", CLIENT_INFORMATION: "mcp_client_information", SERVER_METADATA: "mcp_server_metadata", + AUTH_DEBUGGER_STATE: "mcp_auth_debugger_state", } as const; // Generate server-specific session storage keys From 20e961ce5c2286de5eee0503a85cc8e0005547ff Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Thu, 29 May 2025 12:09:52 +0100 Subject: [PATCH 028/177] resumption working --- client/src/App.tsx | 78 +++++++++++++++++++++++++++++++++------------- 1 file changed, 57 insertions(+), 21 deletions(-) diff --git a/client/src/App.tsx b/client/src/App.tsx index 8be23a5b..f3f1180e 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -20,6 +20,7 @@ import { import { OAuthTokensSchema } from "@modelcontextprotocol/sdk/shared/auth.js"; import { SESSION_KEYS, getServerSpecificKey } from "./lib/constants"; import { AuthDebuggerState, EMPTY_DEBUGGER_STATE } from "./lib/auth-types"; +import { OAuthStateMachine } from "./lib/oauth-state-machine"; import { cacheToolOutputSchemas } from "./utils/schemaUtils"; import React, { Suspense, @@ -231,7 +232,7 @@ const App = () => { // Update OAuth debug state during debug callback const onOAuthDebugConnect = useCallback( - ({ + async ({ authorizationCode, errorMsg, restoredState, @@ -241,29 +242,64 @@ const App = () => { restoredState?: AuthDebuggerState; }) => { setIsAuthDebuggerVisible(true); - - if (restoredState) { - // Restore the previous auth state + + if (errorMsg) { updateAuthState({ - ...restoredState, - // Update with the new authorization code if provided - authorizationCode: authorizationCode || restoredState.authorizationCode, - oauthStep: authorizationCode ? "token_request" : restoredState.oauthStep, - latestError: errorMsg ? new Error(errorMsg) : restoredState.latestError, + latestError: new Error(errorMsg), }); - } else { + return; + } + + if (restoredState && authorizationCode) { + // Restore the previous auth state and continue the OAuth flow + let currentState: AuthDebuggerState = { + ...restoredState, + authorizationCode, + oauthStep: "token_request", + isInitiatingAuth: true, + statusMessage: null, + latestError: null, + }; + + try { + // Create a new state machine instance to continue the flow + const stateMachine = new OAuthStateMachine(sseUrl, (updates) => { + currentState = { ...currentState, ...updates }; + }); + + // Continue stepping through the OAuth flow from where we left off + while (currentState.oauthStep !== "complete" && currentState.oauthStep !== "authorization_code") { + await stateMachine.executeStep(currentState); + } + + if (currentState.oauthStep === "complete") { + // After the flow completes or reaches a user-input step, update the app state + updateAuthState({ + ...currentState, + statusMessage: { + type: "success", + message: "Authentication completed successfully", + }, + isInitiatingAuth: false, + }); + } + } catch (error) { + console.error("OAuth continuation error:", error); + updateAuthState({ + latestError: error instanceof Error ? error : new Error(String(error)), + statusMessage: { + type: "error", + message: `Failed to complete OAuth flow: ${error instanceof Error ? error.message : String(error)}`, + }, + isInitiatingAuth: false, + }); + } + } else if (authorizationCode) { // Fallback to the original behavior if no state was restored - if (authorizationCode) { - updateAuthState({ - authorizationCode, - oauthStep: "token_request", - }); - } - if (errorMsg) { - updateAuthState({ - latestError: new Error(errorMsg), - }); - } + updateAuthState({ + authorizationCode, + oauthStep: "token_request", + }); } }, [], From 35eab580efa9010c88ff43dd91b483e61bcc43a1 Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Thu, 29 May 2025 12:26:53 +0100 Subject: [PATCH 029/177] switch to metadata from state --- client/src/components/AuthDebugger.tsx | 19 ++++++++++++++++++- client/src/components/OAuthFlowProgress.tsx | 6 +++--- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/client/src/components/AuthDebugger.tsx b/client/src/components/AuthDebugger.tsx index 0ef8e70b..a90b1061 100644 --- a/client/src/components/AuthDebugger.tsx +++ b/client/src/components/AuthDebugger.tsx @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from "react"; +import { useCallback, useMemo, useEffect } from "react"; import { Button } from "@/components/ui/button"; import { DebugInspectorOAuthClientProvider } from "../lib/auth"; import { AlertCircle } from "lucide-react"; @@ -60,6 +60,23 @@ const AuthDebugger = ({ authState, updateAuthState, }: AuthDebuggerProps) => { + // Initialize loading state + useEffect(() => { + if (authState.loading && serverUrl) { + // Check if we have existing tokens + const checkTokens = async () => { + const provider = new DebugInspectorOAuthClientProvider(serverUrl); + const existingTokens = await provider.tokens(); + + updateAuthState({ + loading: false, + oauthTokens: existingTokens || null, + }); + }; + + checkTokens(); + } + }, [serverUrl, authState.loading, updateAuthState]); const startOAuthFlow = useCallback(() => { if (!serverUrl) { updateAuthState({ diff --git a/client/src/components/OAuthFlowProgress.tsx b/client/src/components/OAuthFlowProgress.tsx index 2e74bf68..f86ceec8 100644 --- a/client/src/components/OAuthFlowProgress.tsx +++ b/client/src/components/OAuthFlowProgress.tsx @@ -128,7 +128,7 @@ export const OAuthFlowProgress = ({ label="Metadata Discovery" {...getStepProps("metadata_discovery")} > - {provider.getServerMetadata() && ( + {authState.oauthMetadata && (
OAuth Metadata Sources @@ -165,14 +165,14 @@ export const OAuthFlowProgress = ({ )} - {provider.getServerMetadata() && ( + {authState.oauthMetadata && (

Authorization Server Metadata:

{authState.authServerUrl &&

From {new URL('/.well-known/oauth-authorization-server', authState.authServerUrl).href}

}
-                    {JSON.stringify(provider.getServerMetadata(), null, 2)}
+                    {JSON.stringify(authState.oauthMetadata, null, 2)}
                   
)} From cc49358f5ab7c037fd7349031512b4caac345795 Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Thu, 29 May 2025 13:42:54 +0100 Subject: [PATCH 030/177] add test + prettier --- client/src/App.tsx | 11 +++- client/src/components/AuthDebugger.tsx | 6 +- client/src/components/OAuthDebugCallback.tsx | 6 +- client/src/components/OAuthFlowProgress.tsx | 52 ++++++++++++--- .../__tests__/AuthDebugger.test.tsx | 66 +++++++++++++++++++ client/src/lib/auth-types.ts | 7 +- client/src/lib/oauth-state-machine.ts | 14 +++- 7 files changed, 139 insertions(+), 23 deletions(-) diff --git a/client/src/App.tsx b/client/src/App.tsx index f3f1180e..74cdca19 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -122,7 +122,8 @@ const App = () => { const [isAuthDebuggerVisible, setIsAuthDebuggerVisible] = useState(false); // Auth debugger state - const [authState, setAuthState] = useState(EMPTY_DEBUGGER_STATE); + const [authState, setAuthState] = + useState(EMPTY_DEBUGGER_STATE); // Helper function to update specific auth state properties const updateAuthState = (updates: Partial) => { @@ -268,7 +269,10 @@ const App = () => { }); // Continue stepping through the OAuth flow from where we left off - while (currentState.oauthStep !== "complete" && currentState.oauthStep !== "authorization_code") { + while ( + currentState.oauthStep !== "complete" && + currentState.oauthStep !== "authorization_code" + ) { await stateMachine.executeStep(currentState); } @@ -286,7 +290,8 @@ const App = () => { } catch (error) { console.error("OAuth continuation error:", error); updateAuthState({ - latestError: error instanceof Error ? error : new Error(String(error)), + latestError: + error instanceof Error ? error : new Error(String(error)), statusMessage: { type: "error", message: `Failed to complete OAuth flow: ${error instanceof Error ? error.message : String(error)}`, diff --git a/client/src/components/AuthDebugger.tsx b/client/src/components/AuthDebugger.tsx index a90b1061..b88758d4 100644 --- a/client/src/components/AuthDebugger.tsx +++ b/client/src/components/AuthDebugger.tsx @@ -67,13 +67,13 @@ const AuthDebugger = ({ const checkTokens = async () => { const provider = new DebugInspectorOAuthClientProvider(serverUrl); const existingTokens = await provider.tokens(); - + updateAuthState({ loading: false, oauthTokens: existingTokens || null, }); }; - + checkTokens(); } }, [serverUrl, authState.loading, updateAuthState]); @@ -162,7 +162,7 @@ const AuthDebugger = ({ // Store the current auth state before redirecting sessionStorage.setItem( SESSION_KEYS.AUTH_DEBUGGER_STATE, - JSON.stringify(currentState) + JSON.stringify(currentState), ); // Open the authorization URL automatically window.location.href = currentState.authorizationUrl; diff --git a/client/src/components/OAuthDebugCallback.tsx b/client/src/components/OAuthDebugCallback.tsx index af9944ac..17705abb 100644 --- a/client/src/components/OAuthDebugCallback.tsx +++ b/client/src/components/OAuthDebugCallback.tsx @@ -36,9 +36,11 @@ const OAuthDebugCallback = ({ onConnect }: OAuthCallbackProps) => { } const serverUrl = sessionStorage.getItem(SESSION_KEYS.SERVER_URL); - + // Try to restore the auth state - const storedState = sessionStorage.getItem(SESSION_KEYS.AUTH_DEBUGGER_STATE); + const storedState = sessionStorage.getItem( + SESSION_KEYS.AUTH_DEBUGGER_STATE, + ); let restoredState = null; if (storedState) { try { diff --git a/client/src/components/OAuthFlowProgress.tsx b/client/src/components/OAuthFlowProgress.tsx index f86ceec8..b9b67c6c 100644 --- a/client/src/components/OAuthFlowProgress.tsx +++ b/client/src/components/OAuthFlowProgress.tsx @@ -139,7 +139,13 @@ export const OAuthFlowProgress = ({

Resource Metadata:

- From {new URL('/.well-known/oauth-protected-resource', serverUrl).href} + From{" "} + { + new URL( + "/.well-known/oauth-protected-resource", + serverUrl, + ).href + }

                     {JSON.stringify(authState.resourceMetadata, null, 2)}
@@ -150,17 +156,35 @@ export const OAuthFlowProgress = ({
               {authState.resourceMetadataError && (
                 

- ā„¹ļø No resource metadata available from {' '} - - {new URL('/.well-known/oauth-protected-resource', serverUrl).href} + ā„¹ļø No resource metadata available from{" "} + + { + new URL( + "/.well-known/oauth-protected-resource", + serverUrl, + ).href + }

- Resource metadata was added in the 2025-DRAFT-v2 specification update + Resource metadata was added in the{" "} + + 2025-DRAFT-v2 specification update +
{authState.resourceMetadataError.message} - {authState.resourceMetadataError instanceof TypeError - && " (This could indicate the endpoint doesn't exist or does not have CORS configured)"} + {authState.resourceMetadataError instanceof TypeError && + " (This could indicate the endpoint doesn't exist or does not have CORS configured)"}

)} @@ -168,9 +192,17 @@ export const OAuthFlowProgress = ({ {authState.oauthMetadata && (

Authorization Server Metadata:

- {authState.authServerUrl &&

- From {new URL('/.well-known/oauth-authorization-server', authState.authServerUrl).href} -

} + {authState.authServerUrl && ( +

+ From{" "} + { + new URL( + "/.well-known/oauth-authorization-server", + authState.authServerUrl, + ).href + } +

+ )}
                     {JSON.stringify(authState.oauthMetadata, null, 2)}
                   
diff --git a/client/src/components/__tests__/AuthDebugger.test.tsx b/client/src/components/__tests__/AuthDebugger.test.tsx index 42a289ff..fe5a94f9 100644 --- a/client/src/components/__tests__/AuthDebugger.test.tsx +++ b/client/src/components/__tests__/AuthDebugger.test.tsx @@ -40,6 +40,7 @@ jest.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({ registerClient: jest.fn(), startAuthorization: jest.fn(), exchangeAuthorization: jest.fn(), + discoverOAuthProtectedResourceMetadata: jest.fn(), })); // Import the functions to get their types @@ -49,6 +50,7 @@ import { startAuthorization, exchangeAuthorization, auth, + discoverOAuthProtectedResourceMetadata, } from "@modelcontextprotocol/sdk/client/auth.js"; import { OAuthMetadata } from "@modelcontextprotocol/sdk/shared/auth.js"; import { EMPTY_DEBUGGER_STATE } from "@/lib/auth-types"; @@ -67,6 +69,10 @@ const mockExchangeAuthorization = exchangeAuthorization as jest.MockedFunction< typeof exchangeAuthorization >; const mockAuth = auth as jest.MockedFunction; +const mockDiscoverOAuthProtectedResourceMetadata = + discoverOAuthProtectedResourceMetadata as jest.MockedFunction< + typeof discoverOAuthProtectedResourceMetadata + >; const sessionStorageMock = { getItem: jest.fn(), @@ -100,6 +106,7 @@ describe("AuthDebugger", () => { mockDiscoverOAuthMetadata.mockResolvedValue(mockOAuthMetadata); mockRegisterClient.mockResolvedValue(mockOAuthClientInfo); + mockDiscoverOAuthProtectedResourceMetadata.mockResolvedValue(null); mockStartAuthorization.mockImplementation(async (_sseUrl, options) => { const authUrl = new URL("https://oauth.example.com/authorize"); @@ -421,4 +428,63 @@ describe("AuthDebugger", () => { }); }); }); + + describe("OAuth State Persistence", () => { + it("should store auth state to sessionStorage before redirect in Quick OAuth Flow", async () => { + const updateAuthState = jest.fn(); + + // Mock window.location.href setter + delete (window as any).location; + window.location = { href: "" } as any; + + // Setup mocks for OAuth flow + mockStartAuthorization.mockResolvedValue({ + authorizationUrl: new URL( + "https://oauth.example.com/authorize?client_id=test_client_id&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Foauth%2Fcallback%2Fdebug", + ), + codeVerifier: "test_verifier", + }); + + await act(async () => { + renderAuthDebugger({ + updateAuthState, + authState: { ...defaultAuthState, loading: false }, + }); + }); + + // Click Quick OAuth Flow + await act(async () => { + fireEvent.click(screen.getByText("Quick OAuth Flow")); + }); + + // Wait for the flow to reach the authorization step + await waitFor(() => { + expect(sessionStorage.setItem).toHaveBeenCalledWith( + SESSION_KEYS.AUTH_DEBUGGER_STATE, + expect.stringContaining('"oauthStep":"authorization_code"'), + ); + }); + + // Verify the stored state includes all the accumulated data + const storedStateCall = ( + sessionStorage.setItem as jest.Mock + ).mock.calls.find((call) => call[0] === SESSION_KEYS.AUTH_DEBUGGER_STATE); + + expect(storedStateCall).toBeDefined(); + const storedState = JSON.parse(storedStateCall![1]); + + expect(storedState).toMatchObject({ + oauthStep: "authorization_code", + authorizationUrl: expect.stringMatching( + /^https:\/\/oauth\.example\.com\/authorize/, + ), + oauthMetadata: expect.objectContaining({ + token_endpoint: "https://oauth.example.com/token", + }), + oauthClientInfo: expect.objectContaining({ + client_id: "test_client_id", + }), + }); + }); + }); }); diff --git a/client/src/lib/auth-types.ts b/client/src/lib/auth-types.ts index 2541e822..e69dcd12 100644 --- a/client/src/lib/auth-types.ts +++ b/client/src/lib/auth-types.ts @@ -30,7 +30,10 @@ export interface AuthDebuggerState { loading: boolean; oauthStep: OAuthStep; resourceMetadata: OAuthProtectedResourceMetadata | null; - resourceMetadataError: Error | { status: number; statusText: string; message: string } | null; + resourceMetadataError: + | Error + | { status: number; statusText: string; message: string } + | null; authServerUrl: URL | null; oauthMetadata: OAuthMetadata | null; oauthClientInfo: OAuthClientInformationFull | OAuthClientInformation | null; @@ -56,4 +59,4 @@ export const EMPTY_DEBUGGER_STATE: AuthDebuggerState = { latestError: null, statusMessage: null, validationError: null, -} +}; diff --git a/client/src/lib/oauth-state-machine.ts b/client/src/lib/oauth-state-machine.ts index 939e5d6c..d05369c4 100644 --- a/client/src/lib/oauth-state-machine.ts +++ b/client/src/lib/oauth-state-machine.ts @@ -7,7 +7,10 @@ import { exchangeAuthorization, discoverOAuthProtectedResourceMetadata, } from "@modelcontextprotocol/sdk/client/auth.js"; -import { OAuthMetadataSchema, OAuthProtectedResourceMetadata } from "@modelcontextprotocol/sdk/shared/auth.js"; +import { + OAuthMetadataSchema, + OAuthProtectedResourceMetadata, +} from "@modelcontextprotocol/sdk/shared/auth.js"; export interface StateMachineContext { state: AuthDebuggerState; @@ -30,8 +33,13 @@ export const oauthTransitions: Record = { let resourceMetadata: OAuthProtectedResourceMetadata | null = null; let resourceMetadataError: Error | null = null; try { - resourceMetadata = await discoverOAuthProtectedResourceMetadata(context.serverUrl); - if (resourceMetadata && resourceMetadata.authorization_servers?.length) { + resourceMetadata = await discoverOAuthProtectedResourceMetadata( + context.serverUrl, + ); + if ( + resourceMetadata && + resourceMetadata.authorization_servers?.length + ) { authServerUrl = new URL(resourceMetadata.authorization_servers[0]); } } catch (e) { From 03bb303bf9f1c07fba565c7771c5ad5d0c1ae70e Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Thu, 29 May 2025 14:10:32 +0100 Subject: [PATCH 031/177] rm loading, prm test --- client/src/App.tsx | 2 - client/src/components/AuthDebugger.tsx | 26 ++-- .../__tests__/AuthDebugger.test.tsx | 123 +++++++++++++++++- client/src/lib/auth-types.ts | 2 - 4 files changed, 131 insertions(+), 22 deletions(-) diff --git a/client/src/App.tsx b/client/src/App.tsx index 74cdca19..a332f9aa 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -329,8 +329,6 @@ const App = () => { } } catch (error) { console.error("Error loading OAuth tokens:", error); - } finally { - updateAuthState({ loading: false }); } }; diff --git a/client/src/components/AuthDebugger.tsx b/client/src/components/AuthDebugger.tsx index b88758d4..9757af95 100644 --- a/client/src/components/AuthDebugger.tsx +++ b/client/src/components/AuthDebugger.tsx @@ -60,23 +60,23 @@ const AuthDebugger = ({ authState, updateAuthState, }: AuthDebuggerProps) => { - // Initialize loading state + // Check for existing tokens on mount useEffect(() => { - if (authState.loading && serverUrl) { - // Check if we have existing tokens + if (serverUrl && !authState.oauthTokens) { const checkTokens = async () => { const provider = new DebugInspectorOAuthClientProvider(serverUrl); const existingTokens = await provider.tokens(); - - updateAuthState({ - loading: false, - oauthTokens: existingTokens || null, - }); + if (existingTokens) { + updateAuthState({ + oauthTokens: existingTokens, + oauthStep: "complete", + }); + } }; - checkTokens(); } - }, [serverUrl, authState.loading, updateAuthState]); + }, [serverUrl]); // Only run when serverUrl changes + const startOAuthFlow = useCallback(() => { if (!serverUrl) { updateAuthState({ @@ -241,10 +241,7 @@ const AuthDebugger = ({ )} - {authState.loading ? ( -

Loading authentication status...

- ) : ( -
+
{authState.oauthTokens && (

Access Token:

@@ -286,7 +283,6 @@ const AuthDebugger = ({ the standard automatic flow.

- )}
{ mockDiscoverOAuthMetadata.mockResolvedValue(mockOAuthMetadata); mockRegisterClient.mockResolvedValue(mockOAuthClientInfo); - mockDiscoverOAuthProtectedResourceMetadata.mockResolvedValue(null); + mockDiscoverOAuthProtectedResourceMetadata.mockRejectedValue( + new Error("No protected resource metadata found") + ); mockStartAuthorization.mockImplementation(async (_sseUrl, options) => { const authUrl = new URL("https://oauth.example.com/authorize"); @@ -448,7 +450,7 @@ describe("AuthDebugger", () => { await act(async () => { renderAuthDebugger({ updateAuthState, - authState: { ...defaultAuthState, loading: false }, + authState: { ...defaultAuthState }, }); }); @@ -471,7 +473,7 @@ describe("AuthDebugger", () => { ).mock.calls.find((call) => call[0] === SESSION_KEYS.AUTH_DEBUGGER_STATE); expect(storedStateCall).toBeDefined(); - const storedState = JSON.parse(storedStateCall![1]); + const storedState = JSON.parse(storedStateCall![1] as string); expect(storedState).toMatchObject({ oauthStep: "authorization_code", @@ -487,4 +489,119 @@ describe("AuthDebugger", () => { }); }); }); + + describe("OAuth Protected Resource Metadata", () => { + it("should successfully fetch and display protected resource metadata", async () => { + const updateAuthState = jest.fn(); + const mockResourceMetadata = { + resource: "https://example.com/api", + authorization_servers: ["https://custom-auth.example.com"], + bearer_methods_supported: ["header", "body"], + resource_documentation: "https://example.com/api/docs", + resource_policy_uri: "https://example.com/api/policy", + }; + + // Mock successful metadata discovery + mockDiscoverOAuthProtectedResourceMetadata.mockResolvedValue( + mockResourceMetadata + ); + mockDiscoverOAuthMetadata.mockResolvedValue(mockOAuthMetadata); + + await act(async () => { + renderAuthDebugger({ + updateAuthState, + authState: { ...defaultAuthState }, + }); + }); + + // Click Guided OAuth Flow to start the process + await act(async () => { + fireEvent.click(screen.getByText("Guided OAuth Flow")); + }); + + // Verify that the flow started with metadata discovery + expect(updateAuthState).toHaveBeenCalledWith({ + oauthStep: "metadata_discovery", + authorizationUrl: null, + statusMessage: null, + latestError: null, + }); + + // Click Continue to trigger metadata discovery + const continueButton = await screen.findByText("Continue"); + await act(async () => { + fireEvent.click(continueButton); + }); + + // Wait for the metadata to be fetched + await waitFor(() => { + expect(mockDiscoverOAuthProtectedResourceMetadata).toHaveBeenCalledWith( + "https://example.com" + ); + }); + + // Verify the state was updated with the resource metadata + await waitFor(() => { + expect(updateAuthState).toHaveBeenCalledWith( + expect.objectContaining({ + resourceMetadata: mockResourceMetadata, + authServerUrl: new URL("https://custom-auth.example.com"), + oauthStep: "client_registration", + }) + ); + }); + }); + + it("should handle protected resource metadata fetch failure gracefully", async () => { + const updateAuthState = jest.fn(); + const mockError = new Error("Failed to fetch resource metadata"); + + // Mock failed metadata discovery + mockDiscoverOAuthProtectedResourceMetadata.mockRejectedValue(mockError); + // But OAuth metadata should still work with the original URL + mockDiscoverOAuthMetadata.mockResolvedValue(mockOAuthMetadata); + + await act(async () => { + renderAuthDebugger({ + updateAuthState, + authState: { ...defaultAuthState }, + }); + }); + + // Click Guided OAuth Flow + await act(async () => { + fireEvent.click(screen.getByText("Guided OAuth Flow")); + }); + + // Click Continue to trigger metadata discovery + const continueButton = await screen.findByText("Continue"); + await act(async () => { + fireEvent.click(continueButton); + }); + + // Wait for the metadata fetch to fail + await waitFor(() => { + expect(mockDiscoverOAuthProtectedResourceMetadata).toHaveBeenCalledWith( + "https://example.com" + ); + }); + + // Verify the flow continues despite the error + await waitFor(() => { + expect(updateAuthState).toHaveBeenCalledWith( + expect.objectContaining({ + resourceMetadataError: mockError, + // Should use the original server URL as fallback + authServerUrl: new URL("https://example.com"), + oauthStep: "client_registration", + }) + ); + }); + + // Verify that regular OAuth metadata discovery was still called + expect(mockDiscoverOAuthMetadata).toHaveBeenCalledWith( + new URL("https://example.com") + ); + }); + }); }); diff --git a/client/src/lib/auth-types.ts b/client/src/lib/auth-types.ts index e69dcd12..daf1bc15 100644 --- a/client/src/lib/auth-types.ts +++ b/client/src/lib/auth-types.ts @@ -27,7 +27,6 @@ export interface StatusMessage { export interface AuthDebuggerState { isInitiatingAuth: boolean; oauthTokens: OAuthTokens | null; - loading: boolean; oauthStep: OAuthStep; resourceMetadata: OAuthProtectedResourceMetadata | null; resourceMetadataError: @@ -47,7 +46,6 @@ export interface AuthDebuggerState { export const EMPTY_DEBUGGER_STATE: AuthDebuggerState = { isInitiatingAuth: false, oauthTokens: null, - loading: true, oauthStep: "metadata_discovery", oauthMetadata: null, resourceMetadata: null, From 11bc04364bfc012b2170be97ce530af1c118e547 Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Thu, 29 May 2025 14:11:01 +0100 Subject: [PATCH 032/177] whitespace --- client/src/components/AuthDebugger.tsx | 74 +++++++++---------- .../__tests__/AuthDebugger.test.tsx | 14 ++-- 2 files changed, 44 insertions(+), 44 deletions(-) diff --git a/client/src/components/AuthDebugger.tsx b/client/src/components/AuthDebugger.tsx index 9757af95..48c9cb00 100644 --- a/client/src/components/AuthDebugger.tsx +++ b/client/src/components/AuthDebugger.tsx @@ -242,47 +242,47 @@ const AuthDebugger = ({ )}
- {authState.oauthTokens && ( -
-

Access Token:

-
- {authState.oauthTokens.access_token.substring(0, 25)}... -
+ {authState.oauthTokens && ( +
+

Access Token:

+
+ {authState.oauthTokens.access_token.substring(0, 25)}...
- )} - -
- - - - -
+ )} -

- Choose "Guided" for step-by-step instructions or "Quick" for - the standard automatic flow. -

+
+ + + + +
+ +

+ Choose "Guided" for step-by-step instructions or "Quick" for + the standard automatic flow. +

+
{ mockDiscoverOAuthMetadata.mockResolvedValue(mockOAuthMetadata); mockRegisterClient.mockResolvedValue(mockOAuthClientInfo); mockDiscoverOAuthProtectedResourceMetadata.mockRejectedValue( - new Error("No protected resource metadata found") + new Error("No protected resource metadata found"), ); mockStartAuthorization.mockImplementation(async (_sseUrl, options) => { const authUrl = new URL("https://oauth.example.com/authorize"); @@ -503,7 +503,7 @@ describe("AuthDebugger", () => { // Mock successful metadata discovery mockDiscoverOAuthProtectedResourceMetadata.mockResolvedValue( - mockResourceMetadata + mockResourceMetadata, ); mockDiscoverOAuthMetadata.mockResolvedValue(mockOAuthMetadata); @@ -536,7 +536,7 @@ describe("AuthDebugger", () => { // Wait for the metadata to be fetched await waitFor(() => { expect(mockDiscoverOAuthProtectedResourceMetadata).toHaveBeenCalledWith( - "https://example.com" + "https://example.com", ); }); @@ -547,7 +547,7 @@ describe("AuthDebugger", () => { resourceMetadata: mockResourceMetadata, authServerUrl: new URL("https://custom-auth.example.com"), oauthStep: "client_registration", - }) + }), ); }); }); @@ -582,7 +582,7 @@ describe("AuthDebugger", () => { // Wait for the metadata fetch to fail await waitFor(() => { expect(mockDiscoverOAuthProtectedResourceMetadata).toHaveBeenCalledWith( - "https://example.com" + "https://example.com", ); }); @@ -594,13 +594,13 @@ describe("AuthDebugger", () => { // Should use the original server URL as fallback authServerUrl: new URL("https://example.com"), oauthStep: "client_registration", - }) + }), ); }); // Verify that regular OAuth metadata discovery was still called expect(mockDiscoverOAuthMetadata).toHaveBeenCalledWith( - new URL("https://example.com") + new URL("https://example.com"), ); }); }); From e74f80db8591c288c394d7912b57e18bf93e4b78 Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Thu, 29 May 2025 14:26:29 +0100 Subject: [PATCH 033/177] fix tests --- client/src/components/AuthDebugger.tsx | 20 +++++++++++-------- .../__tests__/AuthDebugger.test.tsx | 9 +++++++-- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/client/src/components/AuthDebugger.tsx b/client/src/components/AuthDebugger.tsx index 48c9cb00..ec09963e 100644 --- a/client/src/components/AuthDebugger.tsx +++ b/client/src/components/AuthDebugger.tsx @@ -64,18 +64,22 @@ const AuthDebugger = ({ useEffect(() => { if (serverUrl && !authState.oauthTokens) { const checkTokens = async () => { - const provider = new DebugInspectorOAuthClientProvider(serverUrl); - const existingTokens = await provider.tokens(); - if (existingTokens) { - updateAuthState({ - oauthTokens: existingTokens, - oauthStep: "complete", - }); + try { + const provider = new DebugInspectorOAuthClientProvider(serverUrl); + const existingTokens = await provider.tokens(); + if (existingTokens) { + updateAuthState({ + oauthTokens: existingTokens, + oauthStep: "complete", + }); + } + } catch (error) { + console.error("Failed to load existing OAuth tokens:", error); } }; checkTokens(); } - }, [serverUrl]); // Only run when serverUrl changes + }, [serverUrl, updateAuthState, authState.oauthTokens]); const startOAuthFlow = useCallback(() => { if (!serverUrl) { diff --git a/client/src/components/__tests__/AuthDebugger.test.tsx b/client/src/components/__tests__/AuthDebugger.test.tsx index b0df65eb..b2fa4c61 100644 --- a/client/src/components/__tests__/AuthDebugger.test.tsx +++ b/client/src/components/__tests__/AuthDebugger.test.tsx @@ -202,7 +202,7 @@ describe("AuthDebugger", () => { // Should first discover and save OAuth metadata expect(mockDiscoverOAuthMetadata).toHaveBeenCalledWith( - "https://example.com", + new URL("https://example.com"), ); // Check that updateAuthState was called with the right info message @@ -314,6 +314,11 @@ describe("AuthDebugger", () => { }); expect(updateAuthState).toHaveBeenCalledWith({ + authServerUrl: null, + authorizationUrl: null, + isInitiatingAuth: false, + resourceMetadata: null, + resourceMetadataError: null, oauthTokens: null, oauthStep: "metadata_discovery", latestError: null, @@ -355,7 +360,7 @@ describe("AuthDebugger", () => { }); expect(mockDiscoverOAuthMetadata).toHaveBeenCalledWith( - "https://example.com", + new URL("https://example.com"), ); }); From 02aacb46a2851cf6c5066659f1bc3b56a44d3c76 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Thu, 29 May 2025 19:54:36 -0400 Subject: [PATCH 034/177] Send HTTP/DELETE when disconnecting client * In server/src/index.ts - add delete handler for /mcp endpoint - gets the server transport for the sessionId - calls terminateSession on it - removes the webapp and server transports for the sessionId from the maps - returns status 200 to the client. * In client/src/lib/hooks/useConnection.ts - import Transport - add useState for clientTransport, type Transport or null initialized to null - in connect() function - move creation of client transport down a ways, just before calling client.connect with it - immendiately efter calling client.connect, call setClientTransport with the connected transport (has to happen after, so that what's saved has the abort controller, etc. otherwise it doesn't work to save it prior. - in disconnect() function - immediately call clientTransport.terminateSession if transportType is "streamable-http" - setClientTransport to null --- client/src/lib/hooks/useConnection.ts | 32 +++++++++++++++++++-------- server/src/index.ts | 27 ++++++++++++++++++++++ 2 files changed, 50 insertions(+), 9 deletions(-) diff --git a/client/src/lib/hooks/useConnection.ts b/client/src/lib/hooks/useConnection.ts index 9c825318..39da55cb 100644 --- a/client/src/lib/hooks/useConnection.ts +++ b/client/src/lib/hooks/useConnection.ts @@ -45,6 +45,7 @@ import { } from "@/utils/configUtils"; import { getMCPServerRequestTimeout } from "@/utils/configUtils"; import { InspectorConfig } from "../configurationTypes"; +import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; interface UseConnectionOptions { transportType: "stdio" | "sse" | "streamable-http"; @@ -83,6 +84,9 @@ export function useConnection({ const [serverCapabilities, setServerCapabilities] = useState(null); const [mcpClient, setMcpClient] = useState(null); + const [clientTransport, setClientTransport] = useState( + null, + ); const [requestHistory, setRequestHistory] = useState< { request: string; response?: string }[] >([]); @@ -377,14 +381,6 @@ export function useConnection({ transportType, ); - const clientTransport = - transportType === "streamable-http" - ? new StreamableHTTPClientTransport(mcpProxyServerUrl as URL, { - sessionId: undefined, - ...transportOptions, - }) - : new SSEClientTransport(mcpProxyServerUrl as URL, transportOptions); - if (onNotification) { [ CancelledNotificationSchema, @@ -414,7 +410,20 @@ export function useConnection({ let capabilities; try { - await client.connect(clientTransport); + const transport = + transportType === "streamable-http" + ? new StreamableHTTPClientTransport(mcpProxyServerUrl as URL, { + sessionId: undefined, + ...transportOptions, + }) + : new SSEClientTransport( + mcpProxyServerUrl as URL, + transportOptions, + ); + + await client.connect(transport as Transport); + + setClientTransport(transport); capabilities = client.getServerCapabilities(); const initializeRequest = { @@ -468,10 +477,15 @@ export function useConnection({ }; const disconnect = async () => { + if (transportType === "streamable-http") + await ( + clientTransport as StreamableHTTPClientTransport + ).terminateSession(); await mcpClient?.close(); const authProvider = new InspectorOAuthClientProvider(sseUrl); authProvider.clear(); setMcpClient(null); + setClientTransport(null); setConnectionStatus("disconnected"); setCompletionsSupported(false); setServerCapabilities(null); diff --git a/server/src/index.ts b/server/src/index.ts index 73288f67..1586d0a0 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -226,6 +226,33 @@ app.post("/mcp", async (req, res) => { } }); +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 connection"); From b51ee625cddcf76608873c381c069a07195ace73 Mon Sep 17 00:00:00 2001 From: xiaoli Date: Fri, 30 May 2025 10:14:03 +0800 Subject: [PATCH 035/177] style: fix code style to pass CI checks --- client/src/lib/hooks/useConnection.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/src/lib/hooks/useConnection.ts b/client/src/lib/hooks/useConnection.ts index fae904da..e4f1bc50 100644 --- a/client/src/lib/hooks/useConnection.ts +++ b/client/src/lib/hooks/useConnection.ts @@ -304,8 +304,8 @@ export function useConnection({ bearerToken || (await serverAuthProvider.tokens())?.access_token; if (token) { const authHeaderName = headerName || "Authorization"; - - // Add custom header name as a special request header to let the server know which header to pass through + + // Add custom header name as a special request header to let the server know which header to pass through if (authHeaderName.toLowerCase() !== "authorization") { headers[authHeaderName] = token; headers["x-custom-auth-header"] = authHeaderName; From 3510e1a56128a094638290531fec59fc820ffa2e Mon Sep 17 00:00:00 2001 From: xiaoli Date: Fri, 30 May 2025 14:43:09 +0800 Subject: [PATCH 036/177] fix: preserve capitalization in custom headers Express converts all header names to lowercase, which prevents custom headers with uppercase characters from being properly passed to the target service. This fix ensures that custom headers preserve their original capitalization when forwarded through the proxy. --- server/src/index.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/server/src/index.ts b/server/src/index.ts index de14e286..962c90e8 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -70,8 +70,9 @@ const getHttpHeaders = ( // If the header "x-custom-auth-header" is present, use its value as the custom header name. if (req.headers["x-custom-auth-header"] !== undefined) { const customHeaderName = req.headers["x-custom-auth-header"] as string; - if (req.headers[customHeaderName] !== undefined) { - const value = req.headers[customHeaderName]; + const lowerCaseHeaderName = customHeaderName.toLowerCase(); + if (req.headers[lowerCaseHeaderName] !== undefined) { + const value = req.headers[lowerCaseHeaderName]; headers[customHeaderName] = value as string; } } From 11757ef6154283a0e5bacf04b61dfeda5d9e4cfe Mon Sep 17 00:00:00 2001 From: olaservo Date: Fri, 30 May 2025 07:46:28 -0700 Subject: [PATCH 037/177] Add simple architecture overview --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/README.md b/README.md index d7c34b97..99356536 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,15 @@ The MCP inspector is a developer tool for testing and debugging MCP servers. ![MCP Inspector Screenshot](https://raw.githubusercontent.com/modelcontextprotocol/inspector/main/mcp-inspector.png) +## Architecture Overview + +The MCP Inspector consists of two main components that work together: + +- **MCP Inspector Client (MCPI)**: A React-based web UI that provides an interactive interface for testing and debugging MCP servers +- **MCP Proxy (MCPP)**: A Node.js server that acts as a protocol bridge, connecting the web UI to MCP servers via various transport methods (stdio, SSE, streamable-http) + +Note that the proxy is not a network proxy for intercepting traffic. Instead, it functions as both an MCP client (connecting to your MCP server) and an HTTP server (serving the web UI), enabling browser-based interaction with MCP servers that use different transport protocols. + ## Running the Inspector ### Requirements From 2df723804b6f86e0d1f85f76dd2648c058ae5059 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Fri, 30 May 2025 17:13:53 -0400 Subject: [PATCH 038/177] Normalize the reporting of connection setup and connection errors. The logging is verbose and different for every server type. This is an attempt to make the console output cleaner and more readable. * In server/index.js - in createTransport() - stringify query params to put them on one line - remove logging of transport creation (done in callers) - in /mcp POST handler - report POST request if session id is present - otherwise, report new StreamableHttp connection request - report creation of server transport - report creation of client transport - in /stdio GET handler - report new STDIO connection request - report creation of server transport - report creation of client transport - report 401 as authentication error without stack - in stderr data handler - if it includes "MODULE_NOT_FOUND" - report "Command not found" - remove transports - otherwise send to client as usual - in /sse GET handler - report SSE connection request - report 401 as authentication error without stack - report 404 as server that may not support SSE - report error with "ECONNREFUSED" as "Connection refused" without stack - only create, map, and proxy transports if serverTransport was successfully created - in /message POST handler - report received POST message * In mcpProxy.ts - in onServerError() - if error message includes 404 OR error.cause includes ECONNREFUSED, report "Connection refused." --- server/src/index.ts | 104 ++++++++++++++++++++++++----------------- server/src/mcpProxy.ts | 9 +++- 2 files changed, 68 insertions(+), 45 deletions(-) diff --git a/server/src/index.ts b/server/src/index.ts index 1586d0a0..70023611 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -53,7 +53,7 @@ const serverTransports: Map = new Map(); / const createTransport = async (req: express.Request): Promise => { const query = req.query; - console.log("Query parameters:", query); + console.log("Query parameters:", JSON.stringify(query)); const transportType = query.transportType as string; @@ -65,7 +65,7 @@ const createTransport = async (req: express.Request): Promise => { const { cmd, args } = findActualExecutable(command, origArgs); - console.log(`Stdio transport: command=${cmd}, args=${args}`); + console.log(`STDIO transport: command=${cmd}, args=${args}`); const transport = new StdioClientTransport({ command: cmd, @@ -75,8 +75,6 @@ const createTransport = async (req: express.Request): Promise => { }); await transport.start(); - - console.log("Spawned stdio transport"); return transport; } else if (transportType === "sse") { const url = query.url as string; @@ -104,8 +102,6 @@ const createTransport = async (req: express.Request): Promise => { }, }); await transport.start(); - - console.log("Connected to SSE transport"); return transport; } else if (transportType === "streamable-http") { const headers: HeadersInit = { @@ -130,7 +126,6 @@ const createTransport = async (req: express.Request): Promise => { }, ); await transport.start(); - console.log("Connected to Streamable HTTP transport"); return transport; } else { console.error(`Invalid transport type: ${transportType}`); @@ -159,11 +154,10 @@ app.get("/mcp", async (req, res) => { app.post("/mcp", async (req, res) => { const sessionId = req.headers["mcp-session-id"] as string | undefined; - console.log(`Received POST message for sessionId ${sessionId}`); let serverTransport: Transport | undefined; if (!sessionId) { try { - console.log("New streamable-http connection"); + console.log("New StreamableHttp connection request"); try { serverTransport = await createTransport(req); } catch (error) { @@ -179,16 +173,17 @@ app.post("/mcp", async (req, res) => { throw error; } - console.log("Connected MCP client to server transport"); + console.log("Created StreamableHttp server transport"); const webAppTransport = new StreamableHTTPServerTransport({ sessionIdGenerator: randomUUID, onsessioninitialized: (sessionId) => { webAppTransports.set(sessionId, webAppTransport); serverTransports.set(sessionId, serverTransport!); - console.log("Created streamable web app transport " + sessionId); + console.log("New client <-> proxy server sessionId: " + sessionId); }, }); + console.log("Created StreamableHttp client transport"); await webAppTransport.start(); @@ -207,6 +202,7 @@ app.post("/mcp", async (req, res) => { res.status(500).json(error); } } else { + console.log(`Received POST message for sessionId ${sessionId}`); try { const transport = webAppTransports.get( sessionId, @@ -255,15 +251,15 @@ app.delete("/mcp", async (req, res) => { app.get("/stdio", async (req, res) => { try { - console.log("New connection"); + 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; @@ -272,23 +268,37 @@ app.get("/stdio", async (req, res) => { throw error; } - console.log("Connected MCP client to backing server transport"); - const webAppTransport = new SSEServerTransport("/message", res); + console.log("Created client transport"); + webAppTransports.set(webAppTransport.sessionId, webAppTransport); serverTransports.set(webAppTransport.sessionId, serverTransport); - console.log("Created client/server transports"); await webAppTransport.start(); (serverTransport as StdioClientTransport).stderr!.on("data", (chunk) => { - webAppTransport.send({ - jsonrpc: "2.0", - method: "notifications/stderr", - params: { - content: chunk.toString(), - }, - }); + 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({ @@ -296,7 +306,6 @@ app.get("/stdio", async (req, res) => { transportToServer: serverTransport, }); - console.log("Set up MCP proxy"); } catch (error) { console.error("Error in /stdio route:", error); res.status(500).json(error); @@ -306,7 +315,7 @@ app.get("/stdio", async (req, res) => { app.get("/sse", async (req, res) => { try { console.log( - "New SSE connection. NOTE: The sse transport is deprecated and has been replaced by streamable-http", + "New SSE connection request. NOTE: The sse transport is deprecated and has been replaced by StreamableHttp", ); let serverTransport: Transport | undefined; try { @@ -314,32 +323,39 @@ app.get("/sse", async (req, res) => { } 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; + } 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; } - - throw error; } - console.log("Connected MCP client to backing server transport"); + 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"); - 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(); - await webAppTransport.start(); + mcpProxy({ + transportToClient: webAppTransport, + transportToServer: serverTransport, + }); + } - mcpProxy({ - transportToClient: webAppTransport, - transportToServer: serverTransport, - }); - - console.log("Set up MCP proxy"); } catch (error) { console.error("Error in /sse route:", error); res.status(500).json(error); @@ -349,7 +365,7 @@ app.get("/sse", async (req, res) => { app.post("/message", async (req, res) => { try { const sessionId = req.query.sessionId; - console.log(`Received message for sessionId ${sessionId}`); + console.log(`Received POST message for sessionId ${sessionId}`); const transport = webAppTransports.get( sessionId as string, diff --git a/server/src/mcpProxy.ts b/server/src/mcpProxy.ts index 12660504..09ca4012 100644 --- a/server/src/mcpProxy.ts +++ b/server/src/mcpProxy.ts @@ -6,7 +6,14 @@ function onClientError(error: Error) { } function onServerError(error: Error) { - console.error("Error from MCP server:", error); + if ( + (error?.message && error.message.includes("Error POSTing to endpoint (HTTP 404)")) || + (error?.cause && JSON.stringify(error.cause).includes('ECONNREFUSED')) + ) { + console.error("Connection refused. Is the MCP server running?"); + } else { + console.error("Error from MCP server:", error); + } } export default function mcpProxy({ From b732ab408588c9f955adda9a9f78314e95885a25 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Fri, 30 May 2025 17:51:22 -0400 Subject: [PATCH 039/177] prettier --- server/src/index.ts | 8 +++----- server/src/mcpProxy.ts | 9 +++++---- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/server/src/index.ts b/server/src/index.ts index 70023611..8fdce368 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -259,7 +259,7 @@ app.get("/stdio", async (req, res) => { } catch (error) { if (error instanceof SseError && error.code === 401) { console.error( - "Received 401 Unauthorized from MCP server. Authentication failure." + "Received 401 Unauthorized from MCP server. Authentication failure.", ); res.status(401).json(error); return; @@ -305,7 +305,6 @@ app.get("/stdio", async (req, res) => { transportToClient: webAppTransport, transportToServer: serverTransport, }); - } catch (error) { console.error("Error in /stdio route:", error); res.status(500).json(error); @@ -323,7 +322,7 @@ app.get("/sse", async (req, res) => { } catch (error) { if (error instanceof SseError && error.code === 401) { console.error( - "Received 401 Unauthorized from MCP server. Authentication failure." + "Received 401 Unauthorized from MCP server. Authentication failure.", ); res.status(401).json(error); return; @@ -333,7 +332,7 @@ app.get("/sse", async (req, res) => { ); res.status(404).json(error); return; - } else if (JSON.stringify(error).includes("ECONNREFUSED")) { + } else if (JSON.stringify(error).includes("ECONNREFUSED")) { console.error("Connection refused. Is the MCP server running?"); res.status(500).json(error); } else { @@ -355,7 +354,6 @@ app.get("/sse", async (req, res) => { transportToServer: serverTransport, }); } - } catch (error) { console.error("Error in /sse route:", error); res.status(500).json(error); diff --git a/server/src/mcpProxy.ts b/server/src/mcpProxy.ts index 09ca4012..15167305 100644 --- a/server/src/mcpProxy.ts +++ b/server/src/mcpProxy.ts @@ -6,10 +6,11 @@ function onClientError(error: Error) { } function onServerError(error: Error) { - if ( - (error?.message && error.message.includes("Error POSTing to endpoint (HTTP 404)")) || - (error?.cause && JSON.stringify(error.cause).includes('ECONNREFUSED')) - ) { + if ( + (error?.message && + error.message.includes("Error POSTing to endpoint (HTTP 404)")) || + (error?.cause && JSON.stringify(error.cause).includes("ECONNREFUSED")) + ) { console.error("Connection refused. Is the MCP server running?"); } else { console.error("Error from MCP server:", error); From b555e41c0b3c87cbc08cade9a92e587ee4912155 Mon Sep 17 00:00:00 2001 From: olaservo Date: Sun, 1 Jun 2025 09:03:02 -0700 Subject: [PATCH 040/177] Address the schema architecture crisis --- client/src/components/DynamicJsonForm.tsx | 89 ++++++++++++++++++----- client/src/components/ToolsTab.tsx | 8 +- client/src/utils/jsonUtils.ts | 2 +- client/src/utils/schemaUtils.ts | 55 +++++++++----- 4 files changed, 114 insertions(+), 40 deletions(-) diff --git a/client/src/components/DynamicJsonForm.tsx b/client/src/components/DynamicJsonForm.tsx index 6a5993c3..bd8c6cfd 100644 --- a/client/src/components/DynamicJsonForm.tsx +++ b/client/src/components/DynamicJsonForm.tsx @@ -113,6 +113,8 @@ const DynamicJsonForm = ({ currentValue: JsonValue, path: string[] = [], depth: number = 0, + parentSchema?: JsonSchemaType, + propertyName?: string, ) => { if ( depth >= maxDepth && @@ -122,7 +124,7 @@ const DynamicJsonForm = ({ return ( { const val = e.target.value; - // Allow clearing non-required fields by setting undefined - // This preserves the distinction between empty string and unset - if (!val && !propSchema.required) { - handleFieldChange(path, undefined); - } else { - handleFieldChange(path, val); - } + // Always allow setting string values, including empty strings + handleFieldChange(path, val); }} placeholder={propSchema.description} - required={propSchema.required} + required={isRequired} /> ); case "number": @@ -167,9 +167,7 @@ const DynamicJsonForm = ({ value={(currentValue as number)?.toString() ?? ""} onChange={(e) => { const val = e.target.value; - // Allow clearing non-required number fields - // This preserves the distinction between 0 and unset - if (!val && !propSchema.required) { + if (!val && !isRequired) { handleFieldChange(path, undefined); } else { const num = Number(val); @@ -179,7 +177,7 @@ const DynamicJsonForm = ({ } }} placeholder={propSchema.description} - required={propSchema.required} + required={isRequired} /> ); case "integer": @@ -190,9 +188,7 @@ const DynamicJsonForm = ({ value={(currentValue as number)?.toString() ?? ""} onChange={(e) => { const val = e.target.value; - // Allow clearing non-required integer fields - // This preserves the distinction between 0 and unset - if (!val && !propSchema.required) { + if (!val && !isRequired) { handleFieldChange(path, undefined); } else { const num = Number(val); @@ -203,7 +199,7 @@ const DynamicJsonForm = ({ } }} placeholder={propSchema.description} - required={propSchema.required} + required={isRequired} /> ); case "boolean": @@ -213,7 +209,64 @@ const DynamicJsonForm = ({ checked={(currentValue as boolean) ?? false} onChange={(e) => handleFieldChange(path, e.target.checked)} className="w-4 h-4" - required={propSchema.required} + required={isRequired} + /> + ); + case "object": + if (!propSchema.properties) { + return ( + { + try { + const parsed = JSON.parse(newValue); + handleFieldChange(path, parsed); + setJsonError(undefined); + } catch (err) { + setJsonError(err instanceof Error ? err.message : "Invalid JSON"); + } + }} + error={jsonError} + /> + ); + } + + return ( +
+ {Object.entries(propSchema.properties).map(([key, subSchema]) => ( +
+ + {renderFormFields( + subSchema as JsonSchemaType, + (currentValue as Record)?.[key], + [...path, key], + depth + 1, + propSchema, + key, + )} +
+ ))} +
+ ); + case "array": + return ( + { + try { + const parsed = JSON.parse(newValue); + handleFieldChange(path, parsed); + setJsonError(undefined); + } catch (err) { + setJsonError(err instanceof Error ? err.message : "Invalid JSON"); + } + }} + error={jsonError} /> ); default: diff --git a/client/src/components/ToolsTab.tsx b/client/src/components/ToolsTab.tsx index 8a7f6578..93073da3 100644 --- a/client/src/components/ToolsTab.tsx +++ b/client/src/components/ToolsTab.tsx @@ -7,7 +7,7 @@ import { TabsContent } from "@/components/ui/tabs"; import { Textarea } from "@/components/ui/textarea"; import DynamicJsonForm from "./DynamicJsonForm"; import type { JsonValue, JsonSchemaType } from "@/utils/jsonUtils"; -import { generateDefaultValue } from "@/utils/schemaUtils"; +import { generateDefaultValue, isPropertyRequired } from "@/utils/schemaUtils"; import { CompatibilityCallToolResult, ListToolsResult, @@ -48,7 +48,7 @@ const ToolsTab = ({ selectedTool?.inputSchema.properties ?? [], ).map(([key, value]) => [ key, - generateDefaultValue(value as JsonSchemaType), + generateDefaultValue(value as JsonSchemaType, key, selectedTool?.inputSchema as JsonSchemaType), ]); setParams(Object.fromEntries(params)); }, [selectedTool]); @@ -92,13 +92,15 @@ const ToolsTab = ({ {Object.entries(selectedTool.inputSchema.properties ?? []).map( ([key, value]) => { const prop = value as JsonSchemaType; + const inputSchema = selectedTool.inputSchema as JsonSchemaType; + const required = isPropertyRequired(key, inputSchema); return (
{prop.type === "boolean" ? (
diff --git a/client/src/utils/jsonUtils.ts b/client/src/utils/jsonUtils.ts index 28cbf303..83317938 100644 --- a/client/src/utils/jsonUtils.ts +++ b/client/src/utils/jsonUtils.ts @@ -17,7 +17,7 @@ export type JsonSchemaType = { | "object" | "null"; description?: string; - required?: boolean; + required?: string[]; default?: JsonValue; properties?: Record; items?: JsonSchemaType; diff --git a/client/src/utils/schemaUtils.ts b/client/src/utils/schemaUtils.ts index 30210532..fe643b95 100644 --- a/client/src/utils/schemaUtils.ts +++ b/client/src/utils/schemaUtils.ts @@ -81,46 +81,65 @@ export function hasOutputSchema(toolName: string): boolean { /** * Generates a default value based on a JSON schema type * @param schema The JSON schema definition - * @returns A default value matching the schema type, or null for non-required fields + * @param propertyName Optional property name for checking if it's required in parent schema + * @param parentSchema Optional parent schema to check required array + * @returns A default value matching the schema type */ -export function generateDefaultValue(schema: JsonSchemaType): JsonValue { - if ("default" in schema) { +export function generateDefaultValue( + schema: JsonSchemaType, + propertyName?: string, + parentSchema?: JsonSchemaType +): JsonValue { + if ("default" in schema && schema.default !== undefined) { return schema.default; } - if (!schema.required) { - if (schema.type === "array") return []; - if (schema.type === "object") return {}; - return undefined; - } + // Check if this property is required in the parent schema + const isRequired = parentSchema?.required?.includes(propertyName || "") ?? false; switch (schema.type) { case "string": - return ""; + return isRequired ? "" : undefined; case "number": case "integer": - return 0; + return isRequired ? 0 : undefined; case "boolean": - return false; + return isRequired ? false : undefined; case "array": return []; case "object": { if (!schema.properties) return {}; const obj: JsonObject = {}; - Object.entries(schema.properties) - .filter(([, prop]) => prop.required) - .forEach(([key, prop]) => { - const value = generateDefaultValue(prop); - obj[key] = value; - }); + // Only include properties that are required according to the schema's required array + Object.entries(schema.properties).forEach(([key, prop]) => { + const isPropertyRequired = schema.required?.includes(key) ?? false; + if (isPropertyRequired) { + const value = generateDefaultValue(prop, key, schema); + if (value !== undefined) { + obj[key] = value; + } + } + }); return obj; } - default: + case "null": return null; + default: + return undefined; } } +/** + * Helper function to check if a property is required in a schema + * @param propertyName The name of the property to check + * @param schema The parent schema containing the required array + * @returns true if the property is required, false otherwise + */ +export function isPropertyRequired(propertyName: string, schema: JsonSchemaType): boolean { + return schema.required?.includes(propertyName) ?? false; +} + /** * Formats a field key into a human-readable label * @param key The field key to format From daa863ddfcd38c61a2d4dddfea574571d0f26b02 Mon Sep 17 00:00:00 2001 From: Ryan Clark Date: Sun, 1 Jun 2025 13:27:16 -0500 Subject: [PATCH 041/177] feat: add transport option to cli --- cli/src/index.ts | 48 +++++++++++++++++++++++++++++++++++++++++--- cli/src/transport.ts | 20 ++++++++++++++++-- 2 files changed, 63 insertions(+), 5 deletions(-) diff --git a/cli/src/index.ts b/cli/src/index.ts index bda1e8f7..5d5dcf8b 100644 --- a/cli/src/index.ts +++ b/cli/src/index.ts @@ -29,9 +29,13 @@ type Args = { logLevel?: LogLevel; toolName?: string; toolArg?: Record; + transport?: "sse" | "stdio" | "http"; }; -function createTransportOptions(target: string[]): TransportOptions { +function createTransportOptions( + target: string[], + transport?: "sse" | "stdio" | "http", +): TransportOptions { if (target.length === 0) { throw new Error( "Target is required. Specify a URL or a command to execute.", @@ -50,8 +54,30 @@ function createTransportOptions(target: string[]): TransportOptions { throw new Error("Arguments cannot be passed to a URL-based MCP server."); } + let transportType: "sse" | "stdio" | "http"; + if (transport) { + if (!isUrl && transport !== "stdio") { + throw new Error("Only stdio transport can be used with local commands."); + } + if (isUrl && transport === "stdio") { + throw new Error("stdio transport cannot be used with URLs."); + } + transportType = transport; + } else if (isUrl) { + const url = new URL(command); + if (url.pathname.endsWith("/mcp")) { + transportType = "http"; + } else if (url.pathname.endsWith("/sse")) { + transportType = "sse"; + } else { + transportType = "sse"; + } + } else { + transportType = "stdio"; + } + return { - transportType: isUrl ? "sse" : "stdio", + transportType, command: isUrl ? undefined : command, args: isUrl ? undefined : commandArgs, url: isUrl ? command : undefined, @@ -59,7 +85,7 @@ function createTransportOptions(target: string[]): TransportOptions { } async function callMethod(args: Args): Promise { - const transportOptions = createTransportOptions(args.target); + const transportOptions = createTransportOptions(args.target, args.transport); const transport = createTransport(transportOptions); const client = new Client({ name: "inspector-cli", @@ -214,6 +240,22 @@ function parseArgs(): Args { return value as LogLevel; }, + ) + // + // Transport options + // + .option( + "--transport ", + "Transport type (sse, http, or stdio). Auto-detected from URL: /mcp → http, /sse → sse, commands → stdio", + (value: string) => { + const validTransports = ["sse", "http", "stdio"]; + if (!validTransports.includes(value)) { + throw new Error( + `Invalid transport type: ${value}. Valid types are: ${validTransports.join(", ")}`, + ); + } + return value as "sse" | "http" | "stdio"; + }, ); // Parse only the arguments before -- diff --git a/cli/src/transport.ts b/cli/src/transport.ts index e693f246..e0d67b4e 100644 --- a/cli/src/transport.ts +++ b/cli/src/transport.ts @@ -3,11 +3,12 @@ import { getDefaultEnvironment, StdioClientTransport, } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; import { findActualExecutable } from "spawn-rx"; export type TransportOptions = { - transportType: "sse" | "stdio"; + transportType: "sse" | "stdio" | "http"; command?: string; args?: string[]; url?: string; @@ -15,11 +16,22 @@ export type TransportOptions = { function createSSETransport(options: TransportOptions): Transport { const baseUrl = new URL(options.url ?? ""); - const sseUrl = new URL("/sse", baseUrl); + const sseUrl = baseUrl.pathname.endsWith("/sse") + ? baseUrl + : new URL("/sse", baseUrl); return new SSEClientTransport(sseUrl); } +function createHTTPTransport(options: TransportOptions): Transport { + const baseUrl = new URL(options.url ?? ""); + const mcpUrl = baseUrl.pathname.endsWith("/mcp") + ? baseUrl + : new URL("/mcp", baseUrl); + + return new StreamableHTTPClientTransport(mcpUrl); +} + function createStdioTransport(options: TransportOptions): Transport { let args: string[] = []; @@ -67,6 +79,10 @@ export function createTransport(options: TransportOptions): Transport { return createSSETransport(options); } + if (transportType === "http") { + return createHTTPTransport(options); + } + throw new Error(`Unsupported transport type: ${transportType}`); } catch (error) { throw new Error( From 5b674cfe351b76f976bef8bac03f6619167d14a2 Mon Sep 17 00:00:00 2001 From: Ryan Clark Date: Sun, 1 Jun 2025 13:44:19 -0500 Subject: [PATCH 042/177] feat: update README with example for http transport --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9d5017dc..56b4f59b 100644 --- a/README.md +++ b/README.md @@ -252,9 +252,12 @@ npx @modelcontextprotocol/inspector --cli node build/index.js --method resources # List available prompts npx @modelcontextprotocol/inspector --cli node build/index.js --method prompts/list -# Connect to a remote MCP server +# Connect to a remote MCP server (default is SSE transport) npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com +# Connect to a remote MCP server (with Streamable HTTP transport) +npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com --transport http + # Call a tool on a remote server npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com --method tools/call --tool-name remotetool --tool-arg param=value From 990bc0f7fdae85c91300ffd6b086ae55e5b6e52c Mon Sep 17 00:00:00 2001 From: olaservo Date: Sun, 1 Jun 2025 15:41:30 -0700 Subject: [PATCH 043/177] Fix formatting --- client/src/components/DynamicJsonForm.tsx | 16 +++++++++++----- client/src/components/ToolsTab.tsx | 14 +++++++++++--- client/src/utils/schemaUtils.ts | 10 +++++++--- 3 files changed, 29 insertions(+), 11 deletions(-) diff --git a/client/src/components/DynamicJsonForm.tsx b/client/src/components/DynamicJsonForm.tsx index bd8c6cfd..0a73a989 100644 --- a/client/src/components/DynamicJsonForm.tsx +++ b/client/src/components/DynamicJsonForm.tsx @@ -124,7 +124,8 @@ const DynamicJsonForm = ({ return ( ); } - + return (
{Object.entries(propSchema.properties).map(([key, subSchema]) => ( @@ -263,7 +267,9 @@ const DynamicJsonForm = ({ handleFieldChange(path, parsed); setJsonError(undefined); } catch (err) { - setJsonError(err instanceof Error ? err.message : "Invalid JSON"); + setJsonError( + err instanceof Error ? err.message : "Invalid JSON", + ); } }} error={jsonError} diff --git a/client/src/components/ToolsTab.tsx b/client/src/components/ToolsTab.tsx index 93073da3..cf85e4eb 100644 --- a/client/src/components/ToolsTab.tsx +++ b/client/src/components/ToolsTab.tsx @@ -48,7 +48,11 @@ const ToolsTab = ({ selectedTool?.inputSchema.properties ?? [], ).map(([key, value]) => [ key, - generateDefaultValue(value as JsonSchemaType, key, selectedTool?.inputSchema as JsonSchemaType), + generateDefaultValue( + value as JsonSchemaType, + key, + selectedTool?.inputSchema as JsonSchemaType, + ), ]); setParams(Object.fromEntries(params)); }, [selectedTool]); @@ -92,7 +96,8 @@ const ToolsTab = ({ {Object.entries(selectedTool.inputSchema.properties ?? []).map( ([key, value]) => { const prop = value as JsonSchemaType; - const inputSchema = selectedTool.inputSchema as JsonSchemaType; + const inputSchema = + selectedTool.inputSchema as JsonSchemaType; const required = isPropertyRequired(key, inputSchema); return (
@@ -100,7 +105,10 @@ const ToolsTab = ({ htmlFor={key} className="block text-sm font-medium text-gray-700 dark:text-gray-300" > - {key}{required && *} + {key} + {required && ( + * + )} {prop.type === "boolean" ? (
diff --git a/client/src/utils/schemaUtils.ts b/client/src/utils/schemaUtils.ts index fe643b95..c47022e0 100644 --- a/client/src/utils/schemaUtils.ts +++ b/client/src/utils/schemaUtils.ts @@ -88,14 +88,15 @@ export function hasOutputSchema(toolName: string): boolean { export function generateDefaultValue( schema: JsonSchemaType, propertyName?: string, - parentSchema?: JsonSchemaType + parentSchema?: JsonSchemaType, ): JsonValue { if ("default" in schema && schema.default !== undefined) { return schema.default; } // Check if this property is required in the parent schema - const isRequired = parentSchema?.required?.includes(propertyName || "") ?? false; + const isRequired = + parentSchema?.required?.includes(propertyName || "") ?? false; switch (schema.type) { case "string": @@ -136,7 +137,10 @@ export function generateDefaultValue( * @param schema The parent schema containing the required array * @returns true if the property is required, false otherwise */ -export function isPropertyRequired(propertyName: string, schema: JsonSchemaType): boolean { +export function isPropertyRequired( + propertyName: string, + schema: JsonSchemaType, +): boolean { return schema.required?.includes(propertyName) ?? false; } From 06af321530a541d469e7683acbbbc372bcdbd87a Mon Sep 17 00:00:00 2001 From: olaservo Date: Sun, 1 Jun 2025 16:07:45 -0700 Subject: [PATCH 044/177] Fix tests --- .../src/utils/__tests__/schemaUtils.test.ts | 50 ++++++++++--------- 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/client/src/utils/__tests__/schemaUtils.test.ts b/client/src/utils/__tests__/schemaUtils.test.ts index ca6b65ca..ed2c50f9 100644 --- a/client/src/utils/__tests__/schemaUtils.test.ts +++ b/client/src/utils/__tests__/schemaUtils.test.ts @@ -11,60 +11,64 @@ import type { Tool } from "@modelcontextprotocol/sdk/types.js"; describe("generateDefaultValue", () => { test("generates default string", () => { - expect(generateDefaultValue({ type: "string", required: true })).toBe(""); + const parentSchema = { type: "object" as const, required: ["testProp"] }; + expect(generateDefaultValue({ type: "string" }, "testProp", parentSchema)).toBe(""); }); test("generates default number", () => { - expect(generateDefaultValue({ type: "number", required: true })).toBe(0); + const parentSchema = { type: "object" as const, required: ["testProp"] }; + expect(generateDefaultValue({ type: "number" }, "testProp", parentSchema)).toBe(0); }); test("generates default integer", () => { - expect(generateDefaultValue({ type: "integer", required: true })).toBe(0); + const parentSchema = { type: "object" as const, required: ["testProp"] }; + expect(generateDefaultValue({ type: "integer" }, "testProp", parentSchema)).toBe(0); }); test("generates default boolean", () => { - expect(generateDefaultValue({ type: "boolean", required: true })).toBe( + const parentSchema = { type: "object" as const, required: ["testProp"] }; + expect(generateDefaultValue({ type: "boolean" }, "testProp", parentSchema)).toBe( false, ); }); test("generates default array", () => { - expect(generateDefaultValue({ type: "array", required: true })).toEqual([]); + expect(generateDefaultValue({ type: "array" })).toEqual([]); }); test("generates default empty object", () => { - expect(generateDefaultValue({ type: "object", required: true })).toEqual( + expect(generateDefaultValue({ type: "object" })).toEqual( {}, ); }); test("generates default null for unknown types", () => { // @ts-expect-error Testing with invalid type - expect(generateDefaultValue({ type: "unknown", required: true })).toBe( - null, + expect(generateDefaultValue({ type: "unknown" })).toBe( + undefined, ); }); test("generates empty array for non-required array", () => { - expect(generateDefaultValue({ type: "array", required: false })).toEqual( + expect(generateDefaultValue({ type: "array" })).toEqual( [], ); }); test("generates empty object for non-required object", () => { - expect(generateDefaultValue({ type: "object", required: false })).toEqual( + expect(generateDefaultValue({ type: "object" })).toEqual( {}, ); }); - test("generates null for non-required primitive types", () => { - expect(generateDefaultValue({ type: "string", required: false })).toBe( + test("generates undefined for non-required primitive types", () => { + expect(generateDefaultValue({ type: "string" })).toBe( undefined, ); - expect(generateDefaultValue({ type: "number", required: false })).toBe( + expect(generateDefaultValue({ type: "number" })).toBe( undefined, ); - expect(generateDefaultValue({ type: "boolean", required: false })).toBe( + expect(generateDefaultValue({ type: "boolean" })).toBe( undefined, ); }); @@ -72,11 +76,11 @@ describe("generateDefaultValue", () => { test("generates object with properties", () => { const schema: JsonSchemaType = { type: "object", - required: true, + required: ["name", "age", "isActive"], properties: { - name: { type: "string", required: true }, - age: { type: "number", required: true }, - isActive: { type: "boolean", required: true }, + name: { type: "string" }, + age: { type: "number" }, + isActive: { type: "boolean" }, }, }; expect(generateDefaultValue(schema)).toEqual({ @@ -89,18 +93,18 @@ describe("generateDefaultValue", () => { test("handles nested objects", () => { const schema: JsonSchemaType = { type: "object", - required: true, + required: ["user"], properties: { user: { type: "object", - required: true, + required: ["name", "address"], properties: { - name: { type: "string", required: true }, + name: { type: "string" }, address: { type: "object", - required: true, + required: ["city"], properties: { - city: { type: "string", required: true }, + city: { type: "string" }, }, }, }, From e5e2edc4a1c223960980878be56318822ad8772e Mon Sep 17 00:00:00 2001 From: olaservo Date: Sun, 1 Jun 2025 16:11:20 -0700 Subject: [PATCH 045/177] Fix formatting --- .../src/utils/__tests__/schemaUtils.test.ts | 46 ++++++++----------- 1 file changed, 19 insertions(+), 27 deletions(-) diff --git a/client/src/utils/__tests__/schemaUtils.test.ts b/client/src/utils/__tests__/schemaUtils.test.ts index ed2c50f9..133e25ec 100644 --- a/client/src/utils/__tests__/schemaUtils.test.ts +++ b/client/src/utils/__tests__/schemaUtils.test.ts @@ -12,24 +12,30 @@ import type { Tool } from "@modelcontextprotocol/sdk/types.js"; describe("generateDefaultValue", () => { test("generates default string", () => { const parentSchema = { type: "object" as const, required: ["testProp"] }; - expect(generateDefaultValue({ type: "string" }, "testProp", parentSchema)).toBe(""); + expect( + generateDefaultValue({ type: "string" }, "testProp", parentSchema), + ).toBe(""); }); test("generates default number", () => { const parentSchema = { type: "object" as const, required: ["testProp"] }; - expect(generateDefaultValue({ type: "number" }, "testProp", parentSchema)).toBe(0); + expect( + generateDefaultValue({ type: "number" }, "testProp", parentSchema), + ).toBe(0); }); test("generates default integer", () => { const parentSchema = { type: "object" as const, required: ["testProp"] }; - expect(generateDefaultValue({ type: "integer" }, "testProp", parentSchema)).toBe(0); + expect( + generateDefaultValue({ type: "integer" }, "testProp", parentSchema), + ).toBe(0); }); test("generates default boolean", () => { const parentSchema = { type: "object" as const, required: ["testProp"] }; - expect(generateDefaultValue({ type: "boolean" }, "testProp", parentSchema)).toBe( - false, - ); + expect( + generateDefaultValue({ type: "boolean" }, "testProp", parentSchema), + ).toBe(false); }); test("generates default array", () => { @@ -37,40 +43,26 @@ describe("generateDefaultValue", () => { }); test("generates default empty object", () => { - expect(generateDefaultValue({ type: "object" })).toEqual( - {}, - ); + expect(generateDefaultValue({ type: "object" })).toEqual({}); }); test("generates default null for unknown types", () => { // @ts-expect-error Testing with invalid type - expect(generateDefaultValue({ type: "unknown" })).toBe( - undefined, - ); + expect(generateDefaultValue({ type: "unknown" })).toBe(undefined); }); test("generates empty array for non-required array", () => { - expect(generateDefaultValue({ type: "array" })).toEqual( - [], - ); + expect(generateDefaultValue({ type: "array" })).toEqual([]); }); test("generates empty object for non-required object", () => { - expect(generateDefaultValue({ type: "object" })).toEqual( - {}, - ); + expect(generateDefaultValue({ type: "object" })).toEqual({}); }); test("generates undefined for non-required primitive types", () => { - expect(generateDefaultValue({ type: "string" })).toBe( - undefined, - ); - expect(generateDefaultValue({ type: "number" })).toBe( - undefined, - ); - expect(generateDefaultValue({ type: "boolean" })).toBe( - undefined, - ); + expect(generateDefaultValue({ type: "string" })).toBe(undefined); + expect(generateDefaultValue({ type: "number" })).toBe(undefined); + expect(generateDefaultValue({ type: "boolean" })).toBe(undefined); }); test("generates object with properties", () => { From ef6d84933aa686e236341cf03d007749ac5ba85a Mon Sep 17 00:00:00 2001 From: Aaron Powell Date: Mon, 2 Jun 2025 13:49:38 +1000 Subject: [PATCH 046/177] Apply suggestions from code review Co-authored-by: John McBride --- .github/workflows/main.yml | 1 + Dockerfile | 8 +++----- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index b68890f3..45f2c680 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -95,6 +95,7 @@ jobs: with: context: . push: true + platforms: linux/amd64,linux/arm64 tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} diff --git a/Dockerfile b/Dockerfile index 2d318a33..f5c491d4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -14,12 +14,10 @@ RUN npm install --no-package-lock # Build the application RUN npm run build -ENV CLIENT_PORT=6274 -ENV SERVER_PORT=6277 +ARG CLIENT_PORT=6274 +ARG SERVER_PORT=6277 -# Expose the CLIENT_PORT and SERVER_PORT -EXPOSE $CLIENT_PORT -EXPOSE $SERVER_PORT +EXPOSE ${CLIENT_PORT} ${SERVER_PORT} # Use ENTRYPOINT with CMD for arguments ENTRYPOINT ["npm", "start"] From 3475670f1d2e2c08ddb4df070a087d75fb7debbb Mon Sep 17 00:00:00 2001 From: olaservo Date: Sun, 1 Jun 2025 20:53:17 -0700 Subject: [PATCH 047/177] Incorporate nested logic again --- client/src/components/DynamicJsonForm.tsx | 105 ++++++- .../__tests__/DynamicJsonForm.array.test.tsx | 256 ++++++++++++++++++ 2 files changed, 356 insertions(+), 5 deletions(-) create mode 100644 client/src/components/__tests__/DynamicJsonForm.array.test.tsx diff --git a/client/src/components/DynamicJsonForm.tsx b/client/src/components/DynamicJsonForm.tsx index 0a73a989..f799afbb 100644 --- a/client/src/components/DynamicJsonForm.tsx +++ b/client/src/components/DynamicJsonForm.tsx @@ -16,10 +16,39 @@ interface DynamicJsonFormProps { const isSimpleObject = (schema: JsonSchemaType): boolean => { const supportedTypes = ["string", "number", "integer", "boolean", "null"]; if (supportedTypes.includes(schema.type)) return true; - if (schema.type !== "object") return false; - return Object.values(schema.properties ?? {}).every((prop) => - supportedTypes.includes(prop.type), - ); + if (schema.type === "object") { + return Object.values(schema.properties ?? {}).every((prop) => + supportedTypes.includes(prop.type), + ); + } + if (schema.type === "array") { + return !!schema.items && isSimpleObject(schema.items); + } + return false; +}; + +const getArrayItemDefault = (schema: JsonSchemaType): JsonValue => { + if ("default" in schema && schema.default !== undefined) { + return schema.default; + } + + switch (schema.type) { + case "string": + return ""; + case "number": + case "integer": + return 0; + case "boolean": + return false; + case "array": + return []; + case "object": + return {}; + case "null": + return null; + default: + return null; + } }; const DynamicJsonForm = ({ @@ -257,7 +286,72 @@ const DynamicJsonForm = ({ ))}
); - case "array": + case "array": { + const arrayValue = Array.isArray(currentValue) ? currentValue : []; + if (!propSchema.items) return null; + + // If the array items are simple, render as form fields, otherwise use JSON editor + if (isSimpleObject(propSchema.items)) { + return ( +
+ {propSchema.description && ( +

{propSchema.description}

+ )} + + {propSchema.items?.description && ( +

+ Items: {propSchema.items.description} +

+ )} + +
+ {arrayValue.map((item, index) => ( +
+ {renderFormFields( + propSchema.items as JsonSchemaType, + item, + [...path, index.toString()], + depth + 1, + )} + +
+ ))} + +
+
+ ); + } + + // For complex arrays, fall back to JSON editor return ( ); + } default: return null; } diff --git a/client/src/components/__tests__/DynamicJsonForm.array.test.tsx b/client/src/components/__tests__/DynamicJsonForm.array.test.tsx new file mode 100644 index 00000000..00a324bf --- /dev/null +++ b/client/src/components/__tests__/DynamicJsonForm.array.test.tsx @@ -0,0 +1,256 @@ +import { render, screen, fireEvent } from "@testing-library/react"; +import { describe, it, expect, jest } from "@jest/globals"; +import DynamicJsonForm from "../DynamicJsonForm"; +import type { JsonSchemaType } from "@/utils/jsonUtils"; + +describe("DynamicJsonForm Array Fields", () => { + const renderSimpleArrayForm = (props = {}) => { + const defaultProps = { + schema: { + type: "array" as const, + description: "Test array field", + items: { + type: "string" as const, + description: "Array item", + }, + } satisfies JsonSchemaType, + value: [], + onChange: jest.fn(), + }; + return render(); + }; + + const renderComplexArrayForm = (props = {}) => { + const defaultProps = { + schema: { + type: "array" as const, + description: "Test complex array field", + items: { + type: "object" as const, + properties: { + nested: { type: "object" as const }, + }, + }, + } satisfies JsonSchemaType, + value: [], + onChange: jest.fn(), + }; + return render(); + }; + + describe("Simple Array Rendering", () => { + it("should render form fields for simple array items", () => { + renderSimpleArrayForm({ value: ["item1", "item2"] }); + + // Should show array description + expect(screen.getByText("Test array field")).toBeDefined(); + expect(screen.getByText("Items: Array item")).toBeDefined(); + + // Should show input fields for each item + const inputs = screen.getAllByRole("textbox"); + expect(inputs).toHaveLength(2); + expect(inputs[0]).toHaveProperty("value", "item1"); + expect(inputs[1]).toHaveProperty("value", "item2"); + + // Should show remove buttons + const removeButtons = screen.getAllByText("Remove"); + expect(removeButtons).toHaveLength(2); + + // Should show add button + expect(screen.getByText("Add Item")).toBeDefined(); + }); + + it("should add new items when Add Item button is clicked", () => { + const onChange = jest.fn(); + renderSimpleArrayForm({ value: ["item1"], onChange }); + + const addButton = screen.getByText("Add Item"); + fireEvent.click(addButton); + + expect(onChange).toHaveBeenCalledWith(["item1", ""]); + }); + + it("should remove items when Remove button is clicked", () => { + const onChange = jest.fn(); + renderSimpleArrayForm({ value: ["item1", "item2"], onChange }); + + const removeButtons = screen.getAllByText("Remove"); + fireEvent.click(removeButtons[0]); + + expect(onChange).toHaveBeenCalledWith(["item2"]); + }); + + it("should update item values when input changes", () => { + const onChange = jest.fn(); + renderSimpleArrayForm({ value: ["item1"], onChange }); + + const input = screen.getByRole("textbox"); + fireEvent.change(input, { target: { value: "updated item" } }); + + expect(onChange).toHaveBeenCalledWith(["updated item"]); + }); + + it("should handle empty arrays", () => { + renderSimpleArrayForm({ value: [] }); + + // Should show description and add button but no items + expect(screen.getByText("Test array field")).toBeDefined(); + expect(screen.getByText("Add Item")).toBeDefined(); + expect(screen.queryByText("Remove")).toBeNull(); + }); + }); + + describe("Complex Array Fallback", () => { + it("should render JSON editor for complex arrays", () => { + renderComplexArrayForm(); + + // Should render as JSON editor (textarea) + const textarea = screen.getByRole("textbox"); + expect(textarea).toHaveProperty("type", "textarea"); + + // Should not show form-specific array controls + expect(screen.queryByText("Add Item")).toBeNull(); + expect(screen.queryByText("Remove")).toBeNull(); + }); + }); + + describe("Array Type Detection", () => { + it("should detect string arrays as simple", () => { + const schema = { + type: "array" as const, + items: { type: "string" as const }, + }; + renderSimpleArrayForm({ schema, value: ["test"] }); + + // Should render form fields, not JSON editor + expect(screen.getByRole("textbox")).not.toHaveProperty( + "type", + "textarea", + ); + }); + + it("should detect number arrays as simple", () => { + const schema = { + type: "array" as const, + items: { type: "number" as const }, + }; + renderSimpleArrayForm({ schema, value: [1, 2] }); + + // Should render form fields (number inputs) + const inputs = screen.getAllByRole("spinbutton"); + expect(inputs).toHaveLength(2); + }); + + it("should detect boolean arrays as simple", () => { + const schema = { + type: "array" as const, + items: { type: "boolean" as const }, + }; + renderSimpleArrayForm({ schema, value: [true, false] }); + + // Should render form fields (checkboxes) + const checkboxes = screen.getAllByRole("checkbox"); + expect(checkboxes).toHaveLength(2); + }); + + it("should detect simple object arrays as simple", () => { + const schema = { + type: "array" as const, + items: { + type: "object" as const, + properties: { + name: { type: "string" as const }, + age: { type: "number" as const }, + }, + }, + }; + renderSimpleArrayForm({ schema, value: [{ name: "John", age: 30 }] }); + + // Should render form fields for simple objects + expect(screen.getByText("Add Item")).toBeDefined(); + expect(screen.getByText("Remove")).toBeDefined(); + }); + }); + + describe("Array with Different Item Types", () => { + it("should handle integer array items", () => { + const schema = { + type: "array" as const, + items: { type: "integer" as const }, + }; + const onChange = jest.fn(); + renderSimpleArrayForm({ schema, value: [1, 2], onChange }); + + const inputs = screen.getAllByRole("spinbutton"); + expect(inputs).toHaveLength(2); + expect(inputs[0]).toHaveProperty("value", "1"); + expect(inputs[1]).toHaveProperty("value", "2"); + + // Test adding new integer item + const addButton = screen.getByText("Add Item"); + fireEvent.click(addButton); + expect(onChange).toHaveBeenCalledWith([1, 2, 0]); + }); + + it("should handle boolean array items", () => { + const schema = { + type: "array" as const, + items: { type: "boolean" as const }, + }; + const onChange = jest.fn(); + renderSimpleArrayForm({ schema, value: [true, false], onChange }); + + const checkboxes = screen.getAllByRole("checkbox"); + expect(checkboxes).toHaveLength(2); + expect(checkboxes[0]).toHaveProperty("checked", true); + expect(checkboxes[1]).toHaveProperty("checked", false); + + // Test adding new boolean item + const addButton = screen.getByText("Add Item"); + fireEvent.click(addButton); + expect(onChange).toHaveBeenCalledWith([true, false, false]); + }); + }); + + describe("Array Item Descriptions", () => { + it("should show item description when available", () => { + const schema = { + type: "array" as const, + description: "List of names", + items: { + type: "string" as const, + description: "Person name", + }, + }; + renderSimpleArrayForm({ schema }); + + expect(screen.getByText("List of names")).toBeDefined(); + expect(screen.getByText("Items: Person name")).toBeDefined(); + }); + + it("should use item description in add button title", () => { + const schema = { + type: "array" as const, + items: { + type: "string" as const, + description: "Email address", + }, + }; + renderSimpleArrayForm({ schema }); + + const addButton = screen.getByText("Add Item"); + expect(addButton).toHaveProperty("title", "Add new Email address"); + }); + + it("should use default title when no item description", () => { + const schema = { + type: "array" as const, + items: { type: "string" as const }, + }; + renderSimpleArrayForm({ schema }); + + const addButton = screen.getByText("Add Item"); + expect(addButton).toHaveProperty("title", "Add new item"); + }); + }); +}); From 0a1de24fdff629adddc3df4f1fbab0e47b0b6ac1 Mon Sep 17 00:00:00 2001 From: olaservo Date: Sun, 1 Jun 2025 21:05:33 -0700 Subject: [PATCH 048/177] Fix formatting --- client/src/components/DynamicJsonForm.tsx | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/client/src/components/DynamicJsonForm.tsx b/client/src/components/DynamicJsonForm.tsx index f799afbb..081a7d3b 100644 --- a/client/src/components/DynamicJsonForm.tsx +++ b/client/src/components/DynamicJsonForm.tsx @@ -31,7 +31,7 @@ const getArrayItemDefault = (schema: JsonSchemaType): JsonValue => { if ("default" in schema && schema.default !== undefined) { return schema.default; } - + switch (schema.type) { case "string": return ""; @@ -289,13 +289,15 @@ const DynamicJsonForm = ({ case "array": { const arrayValue = Array.isArray(currentValue) ? currentValue : []; if (!propSchema.items) return null; - + // If the array items are simple, render as form fields, otherwise use JSON editor if (isSimpleObject(propSchema.items)) { return (
{propSchema.description && ( -

{propSchema.description}

+

+ {propSchema.description} +

)} {propSchema.items?.description && ( @@ -333,10 +335,7 @@ const DynamicJsonForm = ({ const defaultValue = getArrayItemDefault( propSchema.items as JsonSchemaType, ); - handleFieldChange(path, [ - ...arrayValue, - defaultValue, - ]); + handleFieldChange(path, [...arrayValue, defaultValue]); }} title={ propSchema.items?.description @@ -350,7 +349,7 @@ const DynamicJsonForm = ({
); } - + // For complex arrays, fall back to JSON editor return ( Date: Mon, 2 Jun 2025 16:20:16 +0100 Subject: [PATCH 049/177] fix type errors --- client/src/components/OAuthDebugCallback.tsx | 3 ++- .../src/components/__tests__/AuthDebugger.test.tsx | 12 ++++++++++-- client/src/lib/auth-types.ts | 5 +---- package.json | 1 + 4 files changed, 14 insertions(+), 7 deletions(-) diff --git a/client/src/components/OAuthDebugCallback.tsx b/client/src/components/OAuthDebugCallback.tsx index 17705abb..99774297 100644 --- a/client/src/components/OAuthDebugCallback.tsx +++ b/client/src/components/OAuthDebugCallback.tsx @@ -4,6 +4,7 @@ import { generateOAuthErrorDescription, parseOAuthCallbackParams, } from "@/utils/oauthUtils.ts"; +import { AuthDebuggerState } from "@/lib/auth-types"; interface OAuthCallbackProps { onConnect: ({ @@ -13,7 +14,7 @@ interface OAuthCallbackProps { }: { authorizationCode?: string; errorMsg?: string; - restoredState?: any; + restoredState?: AuthDebuggerState; }) => void; } diff --git a/client/src/components/__tests__/AuthDebugger.test.tsx b/client/src/components/__tests__/AuthDebugger.test.tsx index b2fa4c61..772b3d43 100644 --- a/client/src/components/__tests__/AuthDebugger.test.tsx +++ b/client/src/components/__tests__/AuthDebugger.test.tsx @@ -441,8 +441,16 @@ describe("AuthDebugger", () => { const updateAuthState = jest.fn(); // Mock window.location.href setter - delete (window as any).location; - window.location = { href: "" } as any; + 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({ diff --git a/client/src/lib/auth-types.ts b/client/src/lib/auth-types.ts index daf1bc15..5e8113ef 100644 --- a/client/src/lib/auth-types.ts +++ b/client/src/lib/auth-types.ts @@ -29,10 +29,7 @@ export interface AuthDebuggerState { oauthTokens: OAuthTokens | null; oauthStep: OAuthStep; resourceMetadata: OAuthProtectedResourceMetadata | null; - resourceMetadataError: - | Error - | { status: number; statusText: string; message: string } - | null; + resourceMetadataError: Error | null; authServerUrl: URL | null; oauthMetadata: OAuthMetadata | null; oauthClientInfo: OAuthClientInformationFull | OAuthClientInformation | null; diff --git a/package.json b/package.json index a5e09c6a..6ee5719e 100644 --- a/package.json +++ b/package.json @@ -36,6 +36,7 @@ "test-cli": "cd cli && npm run test", "prettier-fix": "prettier --write .", "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" }, From 98668507c798ce7010e209557ff35be2ebcad92e Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Mon, 2 Jun 2025 16:20:36 +0100 Subject: [PATCH 050/177] version bump --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 6ee5719e..c0f7cf73 100644 --- a/package.json +++ b/package.json @@ -44,7 +44,7 @@ "@modelcontextprotocol/inspector-cli": "^0.13.0", "@modelcontextprotocol/inspector-client": "^0.13.0", "@modelcontextprotocol/inspector-server": "^0.13.0", - "@modelcontextprotocol/sdk": "^1.12.0", + "@modelcontextprotocol/sdk": "^1.12.1", "concurrently": "^9.0.1", "open": "^10.1.0", "shell-quote": "^1.8.2", From fa01fafa59e34285bd5e5580201dc4b3ec13ce18 Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Mon, 2 Jun 2025 16:21:55 +0100 Subject: [PATCH 051/177] version bump + lint --- client/src/components/__tests__/AuthDebugger.test.tsx | 6 +++--- package-lock.json | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/client/src/components/__tests__/AuthDebugger.test.tsx b/client/src/components/__tests__/AuthDebugger.test.tsx index 772b3d43..3727128a 100644 --- a/client/src/components/__tests__/AuthDebugger.test.tsx +++ b/client/src/components/__tests__/AuthDebugger.test.tsx @@ -445,11 +445,11 @@ describe("AuthDebugger", () => { const locationMock = { ...originalLocation, href: "", - origin: "http://localhost:3000" + origin: "http://localhost:3000", }; - Object.defineProperty(window, 'location', { + Object.defineProperty(window, "location", { writable: true, - value: locationMock + value: locationMock, }); // Setup mocks for OAuth flow diff --git a/package-lock.json b/package-lock.json index 6e5d73f0..36588354 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,7 +17,7 @@ "@modelcontextprotocol/inspector-cli": "^0.13.0", "@modelcontextprotocol/inspector-client": "^0.13.0", "@modelcontextprotocol/inspector-server": "^0.13.0", - "@modelcontextprotocol/sdk": "^1.12.0", + "@modelcontextprotocol/sdk": "^1.12.1", "concurrently": "^9.0.1", "open": "^10.1.0", "shell-quote": "^1.8.2", @@ -2005,9 +2005,9 @@ "link": true }, "node_modules/@modelcontextprotocol/sdk": { - "version": "1.12.0", - "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.12.0.tgz", - "integrity": "sha512-m//7RlINx1F3sz3KqwY1WWzVgTcYX52HYk4bJ1hkBXV3zccAEth+jRvG8DBRrdaQuRsPAJOx2MH3zaHNCKL7Zg==", + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.12.1.tgz", + "integrity": "sha512-KG1CZhZfWg+u8pxeM/mByJDScJSrjjxLc8fwQqbsS8xCjBmQfMNEBTotYdNanKekepnfRI85GtgQlctLFpcYPw==", "dependencies": { "ajv": "^6.12.6", "content-type": "^1.0.5", From 9371006838de8224046eb8c0d3656b7eb9355af4 Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Tue, 3 Jun 2025 11:02:34 +0100 Subject: [PATCH 052/177] less noisy errors --- client/src/components/__tests__/AuthDebugger.test.tsx | 7 +++++++ client/src/lib/oauth-state-machine.ts | 2 -- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/client/src/components/__tests__/AuthDebugger.test.tsx b/client/src/components/__tests__/AuthDebugger.test.tsx index 3727128a..2130e68b 100644 --- a/client/src/components/__tests__/AuthDebugger.test.tsx +++ b/client/src/components/__tests__/AuthDebugger.test.tsx @@ -104,6 +104,9 @@ describe("AuthDebugger", () => { jest.clearAllMocks(); sessionStorageMock.getItem.mockReturnValue(null); + // Supress + jest.spyOn(console, "error").mockImplementation(() => {}); + mockDiscoverOAuthMetadata.mockResolvedValue(mockOAuthMetadata); mockRegisterClient.mockResolvedValue(mockOAuthClientInfo); mockDiscoverOAuthProtectedResourceMetadata.mockRejectedValue( @@ -124,6 +127,10 @@ describe("AuthDebugger", () => { mockExchangeAuthorization.mockResolvedValue(mockOAuthTokens); }); + afterEach(() => { + jest.restoreAllMocks(); + }); + const renderAuthDebugger = (props: Partial = {}) => { const mergedProps = { ...defaultProps, diff --git a/client/src/lib/oauth-state-machine.ts b/client/src/lib/oauth-state-machine.ts index d05369c4..101a33cf 100644 --- a/client/src/lib/oauth-state-machine.ts +++ b/client/src/lib/oauth-state-machine.ts @@ -43,8 +43,6 @@ export const oauthTransitions: Record = { authServerUrl = new URL(resourceMetadata.authorization_servers[0]); } } catch (e) { - console.info(`Failed to find protected resource metadata: ${e}`); - console.log(e); if (e instanceof Error) { resourceMetadataError = e; } else { From e2d3989bb219cd34d249cb1d2cc4c5169e85ae30 Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Tue, 3 Jun 2025 11:05:10 +0100 Subject: [PATCH 053/177] use scopes from PRM if available --- client/src/lib/oauth-state-machine.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/client/src/lib/oauth-state-machine.ts b/client/src/lib/oauth-state-machine.ts index 101a33cf..5f10a783 100644 --- a/client/src/lib/oauth-state-machine.ts +++ b/client/src/lib/oauth-state-machine.ts @@ -72,9 +72,13 @@ export const oauthTransitions: Record = { const metadata = context.state.oauthMetadata!; const clientMetadata = context.provider.clientMetadata; + // Prefer scopes from resource metadata if available + const scopesSupported = + context.state.resourceMetadata?.scopes_supported || + metadata.scopes_supported; // Add all supported scopes to client registration - if (metadata.scopes_supported) { - clientMetadata.scope = metadata.scopes_supported.join(" "); + if (scopesSupported) { + clientMetadata.scope = scopesSupported.join(" "); } const fullInformation = await registerClient(context.serverUrl, { From a387c6ad7e5f006a3138aff5235e42d187cbb8e9 Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Tue, 3 Jun 2025 17:29:22 +0100 Subject: [PATCH 054/177] hook warning --- client/src/App.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/App.tsx b/client/src/App.tsx index 00d3bb48..2fbc7494 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -307,7 +307,7 @@ const App = () => { }); } }, - [], + [sseUrl], ); // Load OAuth tokens when sseUrl changes From 2f50a4ba0eecc2774b4ac6544b10149452b96835 Mon Sep 17 00:00:00 2001 From: dr3s Date: Tue, 3 Jun 2025 13:58:33 -0400 Subject: [PATCH 055/177] fix: Resource template query parameters not appended to request URI #450 --- client/src/components/ResourcesTab.tsx | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/client/src/components/ResourcesTab.tsx b/client/src/components/ResourcesTab.tsx index 35742799..1293a0f8 100644 --- a/client/src/components/ResourcesTab.tsx +++ b/client/src/components/ResourcesTab.tsx @@ -16,6 +16,7 @@ import ListPane from "./ListPane"; import { useEffect, useState } from "react"; import { useCompletionState } from "@/lib/hooks/useCompletionState"; import JsonView from "./JsonView"; +import { UriTemplate } from "@modelcontextprotocol/sdk/shared/uriTemplate.js"; const ResourcesTab = ({ resources, @@ -79,10 +80,10 @@ const ResourcesTab = ({ template: string, values: Record, ): string => { - return template.replace( - /{([^}]+)}/g, - (_, key) => values[key] || `{${key}}`, - ); + console.log("Expanding template:", template, "with values:", values); + const result = new UriTemplate(template).expand(values); + console.log("Filled template:", result); + return result; }; const handleTemplateValueChange = async (key: string, value: string) => { @@ -240,7 +241,8 @@ const ResourcesTab = ({ {selectedTemplate.uriTemplate .match(/{([^}]+)}/g) ?.map((param) => { - const key = param.slice(1, -1); + // Remove leading operator characters (?, &, /, #, ;, +, .) from variable name + const key = param.slice(1, -1).replace(/^[?&/#;+.]/, ""); return (
From f1650d06e3d3a835ecdafe65c8e7ce19f129c317 Mon Sep 17 00:00:00 2001 From: dr3s Date: Tue, 3 Jun 2025 13:58:33 -0400 Subject: [PATCH 056/177] use UriTemplate variable names --- client/src/components/ResourcesTab.tsx | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/client/src/components/ResourcesTab.tsx b/client/src/components/ResourcesTab.tsx index 1293a0f8..dd40d1b8 100644 --- a/client/src/components/ResourcesTab.tsx +++ b/client/src/components/ResourcesTab.tsx @@ -238,11 +238,8 @@ const ResourcesTab = ({

{selectedTemplate.description}

- {selectedTemplate.uriTemplate - .match(/{([^}]+)}/g) - ?.map((param) => { - // Remove leading operator characters (?, &, /, #, ;, +, .) from variable name - const key = param.slice(1, -1).replace(/^[?&/#;+.]/, ""); + {new UriTemplate(selectedTemplate.uriTemplate).variableNames + ?.map((key) => { return (
From 07f3e4593b8bb2ffc9cee99fb7813a08ca85f27b Mon Sep 17 00:00:00 2001 From: dr3s Date: Tue, 3 Jun 2025 13:58:33 -0400 Subject: [PATCH 057/177] remove logs --- client/src/components/ResourcesTab.tsx | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/client/src/components/ResourcesTab.tsx b/client/src/components/ResourcesTab.tsx index dd40d1b8..8795e46b 100644 --- a/client/src/components/ResourcesTab.tsx +++ b/client/src/components/ResourcesTab.tsx @@ -80,10 +80,7 @@ const ResourcesTab = ({ template: string, values: Record, ): string => { - console.log("Expanding template:", template, "with values:", values); - const result = new UriTemplate(template).expand(values); - console.log("Filled template:", result); - return result; + return new UriTemplate(template).expand(values); }; const handleTemplateValueChange = async (key: string, value: string) => { From 26f744866aefde5acaec7a2da6314b8c915ec9be Mon Sep 17 00:00:00 2001 From: dr3s Date: Tue, 3 Jun 2025 13:58:33 -0400 Subject: [PATCH 058/177] formatting --- client/src/components/ResourcesTab.tsx | 41 +++++++++++++------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/client/src/components/ResourcesTab.tsx b/client/src/components/ResourcesTab.tsx index 8795e46b..8ec3f91b 100644 --- a/client/src/components/ResourcesTab.tsx +++ b/client/src/components/ResourcesTab.tsx @@ -235,26 +235,27 @@ const ResourcesTab = ({

{selectedTemplate.description}

- {new UriTemplate(selectedTemplate.uriTemplate).variableNames - ?.map((key) => { - return ( -
- - - handleTemplateValueChange(key, value) - } - onInputChange={(value) => - handleTemplateValueChange(key, value) - } - options={completions[key] || []} - /> -
- ); - })} + {new UriTemplate( + selectedTemplate.uriTemplate, + ).variableNames?.map((key) => { + return ( +
+ + + handleTemplateValueChange(key, value) + } + onInputChange={(value) => + handleTemplateValueChange(key, value) + } + options={completions[key] || []} + /> +
+ ); + })} + ), +})); + +describe("ResourcesTab - Template Query Parameters", () => { + const mockListResources = jest.fn(); + const mockClearResources = jest.fn(); + const mockListResourceTemplates = jest.fn(); + const mockClearResourceTemplates = jest.fn(); + const mockReadResource = jest.fn(); + const mockSetSelectedResource = jest.fn(); + const mockHandleCompletion = jest.fn(); + const mockSubscribeToResource = jest.fn(); + const mockUnsubscribeFromResource = jest.fn(); + + const mockResourceTemplate: ResourceTemplate = { + name: "Users API", + uriTemplate: "test://users{?name,limit,offset}", + description: "Fetch users with optional filtering and pagination", + }; + + const mockResource: Resource = { + uri: "test://users?name=john&limit=10&offset=0", + name: "Users Resource", + description: "Expanded users resource", + }; + + const defaultProps = { + resources: [], + resourceTemplates: [mockResourceTemplate], + listResources: mockListResources, + clearResources: mockClearResources, + listResourceTemplates: mockListResourceTemplates, + clearResourceTemplates: mockClearResourceTemplates, + readResource: mockReadResource, + selectedResource: null, + setSelectedResource: mockSetSelectedResource, + handleCompletion: mockHandleCompletion, + completionsSupported: true, + resourceContent: "", + nextCursor: undefined, + nextTemplateCursor: undefined, + error: null, + resourceSubscriptionsSupported: false, + resourceSubscriptions: new Set(), + subscribeToResource: mockSubscribeToResource, + unsubscribeFromResource: mockUnsubscribeFromResource, + }; + + const renderResourcesTab = (props = {}) => + render( + + + , + ); + + beforeEach(() => { + jest.clearAllMocks(); + }); + + it("should parse and display template variables from URI template", () => { + renderResourcesTab(); + + // Click on the resource template to select it + fireEvent.click(screen.getByText("Users API")); + + // Check that input fields are rendered for each template variable + expect(screen.getByTestId("combobox-name")).toBeInTheDocument(); + expect(screen.getByTestId("combobox-limit")).toBeInTheDocument(); + expect(screen.getByTestId("combobox-offset")).toBeInTheDocument(); + }); + + it("should display template description when template is selected", () => { + renderResourcesTab(); + + // Click on the resource template to select it + fireEvent.click(screen.getByText("Users API")); + + expect(screen.getByText("Fetch users with optional filtering and pagination")).toBeInTheDocument(); + }); + + it("should handle template value changes", () => { + renderResourcesTab(); + + // Click on the resource template to select it + fireEvent.click(screen.getByText("Users API")); + + // Find and fill template value inputs + const nameInput = screen.getByTestId("combobox-name"); + const limitInput = screen.getByTestId("combobox-limit"); + const offsetInput = screen.getByTestId("combobox-offset"); + + fireEvent.change(nameInput, { target: { value: "john" } }); + fireEvent.change(limitInput, { target: { value: "10" } }); + fireEvent.change(offsetInput, { target: { value: "0" } }); + + expect(nameInput).toHaveValue("john"); + expect(limitInput).toHaveValue("10"); + expect(offsetInput).toHaveValue("0"); + }); + + it("should expand template and read resource when Read Resource button is clicked", async () => { + renderResourcesTab(); + + // Click on the resource template to select it + fireEvent.click(screen.getByText("Users API")); + + // Fill template values + const nameInput = screen.getByTestId("combobox-name"); + const limitInput = screen.getByTestId("combobox-limit"); + const offsetInput = screen.getByTestId("combobox-offset"); + + fireEvent.change(nameInput, { target: { value: "john" } }); + fireEvent.change(limitInput, { target: { value: "10" } }); + fireEvent.change(offsetInput, { target: { value: "0" } }); + + // Click Read Resource button + const readResourceButton = screen.getByText("Read Resource"); + expect(readResourceButton).not.toBeDisabled(); + + fireEvent.click(readResourceButton); + + // Verify that readResource was called with the expanded URI + expect(mockReadResource).toHaveBeenCalledWith("test://users?name=john&limit=10&offset=0"); + + // Verify that setSelectedResource was called with the expanded resource + expect(mockSetSelectedResource).toHaveBeenCalledWith({ + uri: "test://users?name=john&limit=10&offset=0", + name: "test://users?name=john&limit=10&offset=0" + }); + }); + + it("should disable Read Resource button when no template values are provided", () => { + renderResourcesTab(); + + // Click on the resource template to select it + fireEvent.click(screen.getByText("Users API")); + + // Read Resource button should be disabled when no values are provided + const readResourceButton = screen.getByText("Read Resource"); + expect(readResourceButton).toBeDisabled(); + }); + + it("should handle partial template values correctly", () => { + renderResourcesTab(); + + // Click on the resource template to select it + fireEvent.click(screen.getByText("Users API")); + + // Fill only some template values + const nameInput = screen.getByTestId("combobox-name"); + fireEvent.change(nameInput, { target: { value: "john" } }); + + // Read Resource button should be enabled with partial values + const readResourceButton = screen.getByText("Read Resource"); + expect(readResourceButton).not.toBeDisabled(); + + fireEvent.click(readResourceButton); + + // Should expand with only the provided values + expect(mockReadResource).toHaveBeenCalledWith("test://users?name=john"); + }); + + it("should handle special characters in template values", () => { + renderResourcesTab(); + + // Click on the resource template to select it + fireEvent.click(screen.getByText("Users API")); + + // Fill template values with special characters + const nameInput = screen.getByTestId("combobox-name"); + fireEvent.change(nameInput, { target: { value: "john doe" } }); + + fireEvent.click(screen.getByText("Read Resource")); + + // Should properly encode special characters + expect(mockReadResource).toHaveBeenCalledWith("test://users?name=john%20doe"); + }); + + it("should clear template values when switching between templates", () => { + const anotherTemplate: ResourceTemplate = { + name: "Posts API", + uriTemplate: "test://posts{?author,category}", + description: "Fetch posts by author and category", + }; + + renderResourcesTab({ + resourceTemplates: [mockResourceTemplate, anotherTemplate] + }); + + // Select first template and fill values + fireEvent.click(screen.getByText("Users API")); + const nameInput = screen.getByTestId("combobox-name"); + fireEvent.change(nameInput, { target: { value: "john" } }); + + // Switch to second template + fireEvent.click(screen.getByText("Posts API")); + + // Should show new template fields and clear previous values + expect(screen.getByTestId("combobox-author")).toBeInTheDocument(); + expect(screen.getByTestId("combobox-category")).toBeInTheDocument(); + expect(screen.queryByTestId("combobox-name")).not.toBeInTheDocument(); + }); + + it("should display resource content when a resource is selected", () => { + const resourceContent = '{"users": [{"id": 1, "name": "John"}]}'; + + renderResourcesTab({ + selectedResource: mockResource, + resourceContent: resourceContent + }); + + expect(screen.getByTestId("json-view")).toBeInTheDocument(); + expect(screen.getByText(resourceContent)).toBeInTheDocument(); + }); + + it("should show alert when no resource or template is selected", () => { + renderResourcesTab(); + + expect(screen.getByText("Select a resource or template from the list to view its contents")).toBeInTheDocument(); + }); +}); From c485e57a3995362be56119aa103bf0da021b5fa0 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Tue, 3 Jun 2025 17:46:43 -0400 Subject: [PATCH 060/177] Add reporting of the Proxy <-> Server sessionId. It's only possible to get the session id for this leg of the proxy if it is a StreamableHttp connection. * In server/src/index.ts - slight format tweak of the Client <-> Proxy message so that the two messages will line up when displayed * In server/src/mcpProxy.ts - add reportedServerSession boolean initialized to false - in transportToServer.onmessage, - if reportedServerSession isn't set yet, report the sessionId if present on the transport, and then set reportedServerSession to true --- server/src/index.ts | 2 +- server/src/mcpProxy.ts | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/server/src/index.ts b/server/src/index.ts index 1e43eea2..37327fa2 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -197,7 +197,7 @@ app.post("/mcp", async (req, res) => { onsessioninitialized: (sessionId) => { webAppTransports.set(sessionId, webAppTransport); serverTransports.set(sessionId, serverTransport!); - console.log("New client <-> proxy server sessionId: " + sessionId); + console.log("Client <-> Proxy sessionId: " + sessionId); }, }); console.log("Created StreamableHttp client transport"); diff --git a/server/src/mcpProxy.ts b/server/src/mcpProxy.ts index 15167305..9dee9de4 100644 --- a/server/src/mcpProxy.ts +++ b/server/src/mcpProxy.ts @@ -27,6 +27,8 @@ export default function mcpProxy({ let transportToClientClosed = false; let transportToServerClosed = false; + let reportedServerSession = false; + transportToClient.onmessage = (message) => { transportToServer.send(message).catch((error) => { // Send error response back to client if it was a request (has id) and connection is still open @@ -46,6 +48,15 @@ export default function mcpProxy({ }; transportToServer.onmessage = (message) => { + if (!reportedServerSession) { + if (transportToServer.sessionId) { + // Can only report for StreamableHttp + console.error( + "Proxy <-> Server sessionId: " + transportToServer.sessionId, + ); + } + reportedServerSession = true; + } transportToClient.send(message).catch(onClientError); }; From 769d045c16ea3fbf89cff3baef975dbdc614f2f8 Mon Sep 17 00:00:00 2001 From: Aaron Powell Date: Wed, 4 Jun 2025 12:18:43 +1000 Subject: [PATCH 061/177] Converting to multi-stage dockerfile --- Dockerfile | 46 +++++++++++++++++++++++++++++++++++----------- 1 file changed, 35 insertions(+), 11 deletions(-) diff --git a/Dockerfile b/Dockerfile index f5c491d4..5d7724d0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,24 +1,48 @@ -FROM node:22-slim +# Build stage +FROM node:24-slim AS builder # Set working directory WORKDIR /app -# Copy files -COPY . . +# 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 -# Working around https://github.com/npm/cli/issues/4828 -# RUN npm ci -RUN npm install --no-package-lock +RUN npm ci --ignore-scripts + +# Copy source files +COPY . . # Build the application RUN npm run build -ARG CLIENT_PORT=6274 -ARG SERVER_PORT=6277 +# Production stage +FROM node:24-slim -EXPOSE ${CLIENT_PORT} ${SERVER_PORT} +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 + +# Document which ports the application uses internally +EXPOSE 6274 6277 # Use ENTRYPOINT with CMD for arguments -ENTRYPOINT ["npm", "start"] -CMD [] \ No newline at end of file +ENTRYPOINT ["npm", "start"] \ No newline at end of file From f73894fbf083c044a861b639976fb2b2c2eadbf4 Mon Sep 17 00:00:00 2001 From: Aaron Powell Date: Wed, 4 Jun 2025 12:30:44 +1000 Subject: [PATCH 062/177] Allowing setting of the ports at the environment variable level so the apps are aware of them --- Dockerfile | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 5d7724d0..f36fb8bb 100644 --- a/Dockerfile +++ b/Dockerfile @@ -41,8 +41,12 @@ 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 6274 6277 +EXPOSE ${CLIENT_PORT} ${SERVER_PORT} # Use ENTRYPOINT with CMD for arguments ENTRYPOINT ["npm", "start"] \ No newline at end of file From 93553d591fbfcefca8872009b9603ea849a2658c Mon Sep 17 00:00:00 2001 From: Marc Abramowitz Date: Tue, 3 Jun 2025 22:24:17 -0700 Subject: [PATCH 063/177] Revert "Add tip to README.md" This reverts commit 0e5e94393a3bb7700d0abc8013988dc039cacda7. --- README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/README.md b/README.md index baf9b322..d7c34b97 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,6 @@ The MCP inspector is a developer tool for testing and debugging MCP servers. ![MCP Inspector Screenshot](https://raw.githubusercontent.com/modelcontextprotocol/inspector/main/mcp-inspector.png) -> **Tip:** -> You can resize the left sidebar by dragging its right edge. This allows you to adjust the space for server configuration, environment variables, and other controls to your preference. - ## Running the Inspector ### Requirements From 5da1dc3256980a71e5f3433acd2c90cf52ba8727 Mon Sep 17 00:00:00 2001 From: Marc Abramowitz Date: Tue, 3 Jun 2025 22:54:19 -0700 Subject: [PATCH 064/177] Add tooltip for URL field A quick way to see the full URL if it's cut off Inspired by @cliffhall's [comment](https://github.com/modelcontextprotocol/inspector/pull/459#issuecomment-2932277785) --- client/src/components/Sidebar.tsx | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/client/src/components/Sidebar.tsx b/client/src/components/Sidebar.tsx index eee8eeaa..1b7f78e9 100644 --- a/client/src/components/Sidebar.tsx +++ b/client/src/components/Sidebar.tsx @@ -285,13 +285,20 @@ const Sidebar = ({ - setSseUrl(e.target.value)} - className="font-mono" - /> + + + setSseUrl(e.target.value)} + className="font-mono" + /> + + + {sseUrl || `Enter URL to MCP server`} + +