From 04e3d255b1605e08eaedf9a5d3900592c4232c2b Mon Sep 17 00:00:00 2001 From: Glen Maddern Date: Wed, 16 Apr 2025 16:59:36 +1000 Subject: [PATCH 01/33] Added Streamable HTTP support This adds a new CLI argument, --transport, with the following values: http-first (the default), http-only, sse-first, and sse-only. Any of the -first tags attempts to connect to the URL as either an HTTP or SSE server and falls back to the other. --- package.json | 4 +- pnpm-lock.yaml | 158 +++++++++++++++-------------------- src/client.ts | 178 ++++++++++++++++++++-------------------- src/lib/coordination.ts | 34 ++++++++ src/lib/utils.ts | 154 ++++++++++++++++++++++++++++------ src/proxy.ts | 76 ++++++++++++----- 6 files changed, 373 insertions(+), 231 deletions(-) diff --git a/package.json b/package.json index 47cfa99..317eca6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mcp-remote", - "version": "0.0.22", + "version": "0.1.0-2", "description": "Remote proxy for Model Context Protocol, allowing local-only clients to connect to remote servers using oAuth", "keywords": [ "mcp", @@ -28,11 +28,11 @@ "check": "prettier --check . && tsc" }, "dependencies": { - "@modelcontextprotocol/sdk": "^1.9.0", "express": "^4.21.2", "open": "^10.1.0" }, "devDependencies": { + "@modelcontextprotocol/sdk": "^1.10.2", "@types/express": "^5.0.0", "@types/node": "^22.13.10", "@types/react": "^19.0.12", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e550c3e..48d8491 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,9 +8,6 @@ importers: .: dependencies: - '@modelcontextprotocol/sdk': - specifier: ^1.9.0 - version: 1.9.0 express: specifier: ^4.21.2 version: 4.21.2 @@ -18,6 +15,9 @@ importers: specifier: ^10.1.0 version: 10.1.0 devDependencies: + '@modelcontextprotocol/sdk': + specifier: ^1.10.2 + version: 1.10.2 '@types/express': specifier: ^5.0.0 version: 5.0.0 @@ -217,8 +217,8 @@ packages: '@jridgewell/trace-mapping@0.3.25': resolution: {integrity: sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==} - '@modelcontextprotocol/sdk@1.9.0': - resolution: {integrity: sha512-Jq2EUCQpe0iyO5FGpzVYDNFR6oR53AIrwph9yWl7uSc7IWUMsrmpmSaTGra5hQNunXpM+9oit85p924jWuHzUA==} + '@modelcontextprotocol/sdk@1.10.2': + resolution: {integrity: sha512-rb6AMp2DR4SN+kc6L1ta2NCpApyA9WYNx3CrTSZvGxq9wH71bRur+zRqPfg0vQ9mjywR7qZdX2RGHOPq3ss+tA==} engines: {node: '>=18'} '@pkgjs/parseargs@0.11.0': @@ -396,8 +396,8 @@ packages: resolution: {integrity: sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==} engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16} - body-parser@2.1.0: - resolution: {integrity: sha512-/hPxh61E+ll0Ujp24Ilm64cykicul1ypfwjVttduAiEdtnJFvLePSrIPk+HMImtNv5270wOGCb1Tns2rybMkoQ==} + body-parser@2.2.0: + resolution: {integrity: sha512-02qvAaxv8tp7fBa/mw1ga98OGm+eCbqzJOKoRt70sLmfEEi+jyBYVTDGfCL/k06/4EMk/z01gCe7HoCH/f2LTg==} engines: {node: '>=18'} brace-expansion@2.0.1: @@ -490,15 +490,6 @@ packages: supports-color: optional: true - debug@4.3.6: - resolution: {integrity: sha512-O/09Bd4Z1fBrU4VzkhFqVgpPzaGbw6Sm9FEkBT1A/YBXQFGuuSxa1dN2nxgxS34JmKXqYx8CZAwEVoJFImUXIg==} - engines: {node: '>=6.0'} - peerDependencies: - supports-color: '*' - peerDependenciesMeta: - supports-color: - optional: true - debug@4.4.0: resolution: {integrity: sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==} engines: {node: '>=6.0'} @@ -576,12 +567,12 @@ packages: resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} engines: {node: '>= 0.6'} - eventsource-parser@3.0.0: - resolution: {integrity: sha512-T1C0XCUimhxVQzW4zFipdx0SficT651NnkR0ZSH3yQwh+mFMdLfgjABVi4YtMTtaL4s168593DaoaRLMqryavA==} + eventsource-parser@3.0.1: + resolution: {integrity: sha512-VARTJ9CYeuQYb0pZEPbzi740OWFgpHe7AYJ2WFZVnUDUQp5Dk2yJUgF36YsZ81cOyxT0QxmXD2EQpapAouzWVA==} engines: {node: '>=18.0.0'} - eventsource@3.0.5: - resolution: {integrity: sha512-LT/5J605bx5SNyE+ITBDiM3FxffBiq9un7Vx0EwMDM3vg8sWKx/tO2zC+LMqZ+smAM0F2hblaDZUVZF0te2pSw==} + eventsource@3.0.6: + resolution: {integrity: sha512-l19WpE2m9hSuyP06+FbuUUf1G+R0SFLrtQfbRb9PRr+oimOfxQhgGCbVaXg5IvZyyTThJsxh6L/srkMiCeBPDA==} engines: {node: '>=18.0.0'} express-rate-limit@7.5.0: @@ -594,8 +585,8 @@ packages: resolution: {integrity: sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==} engines: {node: '>= 0.10.0'} - express@5.0.1: - resolution: {integrity: sha512-ORF7g6qGnD+YtUG9yx4DFoqCShNMmUKiXuT5oWMHiOvt/4WFbHC6yCwQMTSBMno7AqntNCAzzcnnjowRkTL9eQ==} + express@5.1.0: + resolution: {integrity: sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==} engines: {node: '>= 18'} fdir@6.4.3: @@ -673,10 +664,6 @@ packages: resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==} engines: {node: '>=0.10.0'} - iconv-lite@0.5.2: - resolution: {integrity: sha512-kERHXvpSaB4aU3eANwidg79K8FlrN77m8G9V+0vOR3HYaRifrlwMEpT7ZBJqLSEIHnEgJTHcWK82wwLwwKwtag==} - engines: {node: '>=0.10.0'} - iconv-lite@0.6.3: resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==} engines: {node: '>=0.10.0'} @@ -771,8 +758,8 @@ packages: resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==} engines: {node: '>= 0.6'} - mime-types@3.0.0: - resolution: {integrity: sha512-XqoSHeCGjVClAmoGFG3lVFqQFRIrTVw2OH3axRqAcfaw+gHWIfnASS92AV+Rl/mk0MupgZTRHQOjxY6YVnzK5w==} + mime-types@3.0.1: + resolution: {integrity: sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==} engines: {node: '>= 0.6'} mime@1.6.0: @@ -791,9 +778,6 @@ packages: ms@2.0.0: resolution: {integrity: sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==} - ms@2.1.2: - resolution: {integrity: sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==} - ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} @@ -935,8 +919,8 @@ packages: engines: {node: '>=18.0.0', npm: '>=8.0.0'} hasBin: true - router@2.1.0: - resolution: {integrity: sha512-/m/NSLxeYEgWNtyC+WtNHCF7jbGxOibVWKnn+1Psff4dJGOfoXP+MuC/f2CwSmyiHdOIzYnYFp4W6GxWfekaLA==} + router@2.2.0: + resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==} engines: {node: '>= 18'} run-applescript@7.0.0: @@ -953,16 +937,16 @@ packages: resolution: {integrity: sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==} engines: {node: '>= 0.8.0'} - send@1.1.0: - resolution: {integrity: sha512-v67WcEouB5GxbTWL/4NeToqcZiAWEq90N888fczVArY8A79J0L4FD7vj5hm3eUMua5EpoQ59wa/oovY6TLvRUA==} + send@1.2.0: + resolution: {integrity: sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw==} engines: {node: '>= 18'} serve-static@1.16.2: resolution: {integrity: sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==} engines: {node: '>= 0.8.0'} - serve-static@2.1.0: - resolution: {integrity: sha512-A3We5UfEjG8Z7VkDv6uItWw6HY2bBSBJT1KtVESn6EOoOr2jAxNhxWCLY3jDE2WcuHXByWju74ck3ZgLwL8xmA==} + serve-static@2.2.0: + resolution: {integrity: sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==} engines: {node: '>= 18'} setprototypeof@1.2.0: @@ -1081,8 +1065,8 @@ packages: resolution: {integrity: sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==} engines: {node: '>= 0.6'} - type-is@2.0.0: - resolution: {integrity: sha512-gd0sGezQYCbWSbkZr75mln4YBidWUN60+devscpLF5mtRDUpiaTvKpBNrdaCvel1NdR2k6vclXybU5fBd2i+nw==} + type-is@2.0.1: + resolution: {integrity: sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==} engines: {node: '>= 0.6'} typescript@5.8.2: @@ -1132,8 +1116,8 @@ packages: peerDependencies: zod: ^3.24.1 - zod@3.24.2: - resolution: {integrity: sha512-lY7CDW43ECgW9u1TcT3IoXHflywfVqDYze4waEz812jR/bZ8FHDsl7pFQoSZTz5N+2NqRXs8GBwnAwo3ZNxqhQ==} + zod@3.24.3: + resolution: {integrity: sha512-HhY1oqzWCQWuUqvBFnsyrtZRhyPeR7SUGv+C4+MsisMuVfSPx8HpwWqH8tRahSlt6M3PiFAcoeFhZAqIXTxoSg==} snapshots: @@ -1238,18 +1222,18 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.0 - '@modelcontextprotocol/sdk@1.9.0': + '@modelcontextprotocol/sdk@1.10.2': dependencies: content-type: 1.0.5 cors: 2.8.5 cross-spawn: 7.0.6 - eventsource: 3.0.5 - express: 5.0.1 - express-rate-limit: 7.5.0(express@5.0.1) + eventsource: 3.0.6 + express: 5.1.0 + express-rate-limit: 7.5.0(express@5.1.0) pkce-challenge: 5.0.0 raw-body: 3.0.0 - zod: 3.24.2 - zod-to-json-schema: 3.24.5(zod@3.24.2) + zod: 3.24.3 + zod-to-json-schema: 3.24.5(zod@3.24.3) transitivePeerDependencies: - supports-color @@ -1372,7 +1356,7 @@ snapshots: accepts@2.0.0: dependencies: - mime-types: 3.0.0 + mime-types: 3.0.1 negotiator: 1.0.0 ansi-regex@5.0.1: {} @@ -1408,17 +1392,17 @@ snapshots: transitivePeerDependencies: - supports-color - body-parser@2.1.0: + body-parser@2.2.0: dependencies: bytes: 3.1.2 content-type: 1.0.5 debug: 4.4.0 http-errors: 2.0.0 - iconv-lite: 0.5.2 + iconv-lite: 0.6.3 on-finished: 2.4.1 qs: 6.14.0 raw-body: 3.0.0 - type-is: 2.0.0 + type-is: 2.0.1 transitivePeerDependencies: - supports-color @@ -1496,10 +1480,6 @@ snapshots: dependencies: ms: 2.0.0 - debug@4.3.6: - dependencies: - ms: 2.1.2 - debug@4.4.0: dependencies: ms: 2.1.3 @@ -1575,15 +1555,15 @@ snapshots: etag@1.8.1: {} - eventsource-parser@3.0.0: {} + eventsource-parser@3.0.1: {} - eventsource@3.0.5: + eventsource@3.0.6: dependencies: - eventsource-parser: 3.0.0 + eventsource-parser: 3.0.1 - express-rate-limit@7.5.0(express@5.0.1): + express-rate-limit@7.5.0(express@5.1.0): dependencies: - express: 5.0.1 + express: 5.1.0 express@4.21.2: dependencies: @@ -1621,16 +1601,15 @@ snapshots: transitivePeerDependencies: - supports-color - express@5.0.1: + express@5.1.0: dependencies: accepts: 2.0.0 - body-parser: 2.1.0 + body-parser: 2.2.0 content-disposition: 1.0.0 content-type: 1.0.5 cookie: 0.7.1 cookie-signature: 1.2.2 - debug: 4.3.6 - depd: 2.0.0 + debug: 4.4.0 encodeurl: 2.0.0 escape-html: 1.0.3 etag: 1.8.1 @@ -1638,22 +1617,18 @@ snapshots: fresh: 2.0.0 http-errors: 2.0.0 merge-descriptors: 2.0.0 - methods: 1.1.2 - mime-types: 3.0.0 + mime-types: 3.0.1 on-finished: 2.4.1 once: 1.4.0 parseurl: 1.3.3 proxy-addr: 2.0.7 - qs: 6.13.0 + qs: 6.14.0 range-parser: 1.2.1 - router: 2.1.0 - safe-buffer: 5.2.1 - send: 1.1.0 - serve-static: 2.1.0 - setprototypeof: 1.2.0 + router: 2.2.0 + send: 1.2.0 + serve-static: 2.2.0 statuses: 2.0.1 - type-is: 2.0.0 - utils-merge: 1.0.1 + type-is: 2.0.1 vary: 1.1.2 transitivePeerDependencies: - supports-color @@ -1752,10 +1727,6 @@ snapshots: dependencies: safer-buffer: 2.1.2 - iconv-lite@0.5.2: - dependencies: - safer-buffer: 2.1.2 - iconv-lite@0.6.3: dependencies: safer-buffer: 2.1.2 @@ -1818,7 +1789,7 @@ snapshots: dependencies: mime-db: 1.52.0 - mime-types@3.0.0: + mime-types@3.0.1: dependencies: mime-db: 1.54.0 @@ -1832,8 +1803,6 @@ snapshots: ms@2.0.0: {} - ms@2.1.2: {} - ms@2.1.3: {} mz@2.7.0: @@ -1960,11 +1929,15 @@ snapshots: '@rollup/rollup-win32-x64-msvc': 4.35.0 fsevents: 2.3.3 - router@2.1.0: + router@2.2.0: dependencies: + debug: 4.4.0 + depd: 2.0.0 is-promise: 4.0.0 parseurl: 1.3.3 path-to-regexp: 8.2.0 + transitivePeerDependencies: + - supports-color run-applescript@7.0.0: {} @@ -1990,16 +1963,15 @@ snapshots: transitivePeerDependencies: - supports-color - send@1.1.0: + send@1.2.0: dependencies: debug: 4.4.0 - destroy: 1.2.0 encodeurl: 2.0.0 escape-html: 1.0.3 etag: 1.8.1 - fresh: 0.5.2 + fresh: 2.0.0 http-errors: 2.0.0 - mime-types: 2.1.35 + mime-types: 3.0.1 ms: 2.1.3 on-finished: 2.4.1 range-parser: 1.2.1 @@ -2016,12 +1988,12 @@ snapshots: transitivePeerDependencies: - supports-color - serve-static@2.1.0: + serve-static@2.2.0: dependencies: encodeurl: 2.0.0 escape-html: 1.0.3 parseurl: 1.3.3 - send: 1.1.0 + send: 1.2.0 transitivePeerDependencies: - supports-color @@ -2162,11 +2134,11 @@ snapshots: media-typer: 0.3.0 mime-types: 2.1.35 - type-is@2.0.0: + type-is@2.0.1: dependencies: content-type: 1.0.5 media-typer: 1.1.0 - mime-types: 3.0.0 + mime-types: 3.0.1 typescript@5.8.2: {} @@ -2204,8 +2176,8 @@ snapshots: wrappy@1.0.2: {} - zod-to-json-schema@3.24.5(zod@3.24.2): + zod-to-json-schema@3.24.5(zod@3.24.3): dependencies: - zod: 3.24.2 + zod: 3.24.3 - zod@3.24.2: {} + zod@3.24.3: {} diff --git a/src/client.ts b/src/client.ts index d620884..4e0c14c 100644 --- a/src/client.ts +++ b/src/client.ts @@ -11,25 +11,36 @@ import { EventEmitter } from 'events' import { Client } from '@modelcontextprotocol/sdk/client/index.js' -import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js' import { ListResourcesResultSchema, ListToolsResultSchema } from '@modelcontextprotocol/sdk/types.js' -import { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js' import { NodeOAuthClientProvider } from './lib/node-oauth-client-provider' -import { parseCommandLineArgs, setupSignalHandlers, log, MCP_REMOTE_VERSION, getServerUrlHash } from './lib/utils' -import { coordinateAuth } from './lib/coordination' +import { + parseCommandLineArgs, + setupSignalHandlers, + log, + MCP_REMOTE_VERSION, + getServerUrlHash, + connectToRemoteServer, + TransportStrategy, +} from './lib/utils' +import { createLazyAuthCoordinator } from './lib/coordination' /** * Main function to run the client */ -async function runClient(serverUrl: string, callbackPort: number, headers: Record) { +async function runClient( + serverUrl: string, + callbackPort: number, + headers: Record, + transportStrategy: TransportStrategy = 'http-first', +) { // Set up event emitter for auth flow const events = new EventEmitter() // Get the server URL hash for lockfile operations const serverUrlHash = getServerUrlHash(serverUrl) - // Coordinate authentication with other instances - const { server, waitForAuthCode, skipBrowserAuth } = await coordinateAuth(serverUrlHash, callbackPort, events) + // Create a lazy auth coordinator + const authCoordinator = createLazyAuthCoordinator(serverUrlHash, callbackPort, events) // Create the OAuth client provider const authProvider = new NodeOAuthClientProvider({ @@ -38,14 +49,6 @@ async function runClient(serverUrl: string, callbackPort: number, headers: Recor clientName: 'MCP CLI Client', }) - // If auth was completed by another instance, just log that we'll use the auth from disk - if (skipBrowserAuth) { - log('Authentication was completed by another instance - will use tokens from disk...') - // TODO: remove, the callback is happening before the tokens are exchanged - // so we're slightly too early - await new Promise((res) => setTimeout(res, 1_000)) - } - // Create the client const client = new Client( { @@ -57,10 +60,33 @@ async function runClient(serverUrl: string, callbackPort: number, headers: Recor }, ) - // Create the transport factory - const url = new URL(serverUrl) - function initTransport() { - const transport = new SSEClientTransport(url, { authProvider, requestInit: { headers } }) + // Keep track of the server instance for cleanup + let server: any = null + + // Define an auth initializer function + const authInitializer = async () => { + const authState = await authCoordinator.initializeAuth() + + // Store server in outer scope for cleanup + server = authState.server + + // If auth was completed by another instance, just log that we'll use the auth from disk + if (authState.skipBrowserAuth) { + log('Authentication was completed by another instance - will use tokens from disk...') + // TODO: remove, the callback is happening before the tokens are exchanged + // so we're slightly too early + await new Promise((res) => setTimeout(res, 1_000)) + } + + return { + waitForAuthCode: authState.waitForAuthCode, + skipBrowserAuth: authState.skipBrowserAuth, + } + } + + try { + // Connect to remote server with lazy authentication + const transport = await connectToRemoteServer(client, serverUrl, authProvider, headers, authInitializer, transportStrategy) // Set up message and error handlers transport.onmessage = (message) => { @@ -75,89 +101,59 @@ async function runClient(serverUrl: string, callbackPort: number, headers: Recor log('Connection closed.') process.exit(0) } - return transport - } - const transport = initTransport() - - // Set up cleanup handler - const cleanup = async () => { - log('\nClosing connection...') - await client.close() - server.close() - } - setupSignalHandlers(cleanup) - - // Try to connect - try { - log('Connecting to server...') - await client.connect(transport) - log('Connected successfully!') - } catch (error) { - if (error instanceof UnauthorizedError || (error instanceof Error && error.message.includes('Unauthorized'))) { - log('Authentication required. Waiting for authorization...') - - // Wait for the authorization code from the callback or another instance - const code = await waitForAuthCode() - - try { - log('Completing authorization...') - await transport.finishAuth(code) - - // Reconnect after authorization with a new transport - log('Connecting after authorization...') - await client.connect(initTransport()) - - log('Connected successfully!') - - // Request tools list after auth - log('Requesting tools list...') - const tools = await client.request({ method: 'tools/list' }, ListToolsResultSchema) - log('Tools:', JSON.stringify(tools, null, 2)) - - // Request resources list after auth - log('Requesting resource list...') - const resources = await client.request({ method: 'resources/list' }, ListResourcesResultSchema) - log('Resources:', JSON.stringify(resources, null, 2)) - - log('Listening for messages. Press Ctrl+C to exit.') - } catch (authError) { - log('Authorization error:', authError) + // Set up cleanup handler + const cleanup = async () => { + log('\nClosing connection...') + await client.close() + // If auth was initialized and server was created, close it + if (server) { server.close() - process.exit(1) } - } else { - log('Connection error:', error) - server.close() - process.exit(1) } - } + setupSignalHandlers(cleanup) - try { - // Request tools list - log('Requesting tools list...') - const tools = await client.request({ method: 'tools/list' }, ListToolsResultSchema) - log('Tools:', JSON.stringify(tools, null, 2)) - } catch (e) { - log('Error requesting tools list:', e) - } + log('Connected successfully!') - try { - // Request resources list - log('Requesting resource list...') - const resources = await client.request({ method: 'resources/list' }, ListResourcesResultSchema) - log('Resources:', JSON.stringify(resources, null, 2)) - } catch (e) { - log('Error requesting resources list:', e) - } + try { + // Request tools list + log('Requesting tools list...') + const tools = await client.request({ method: 'tools/list' }, ListToolsResultSchema) + log('Tools:', JSON.stringify(tools, null, 2)) + } catch (e) { + log('Error requesting tools list:', e) + } - log('Listening for messages. Press Ctrl+C to exit.') + try { + // Request resources list + log('Requesting resource list...') + const resources = await client.request({ method: 'resources/list' }, ListResourcesResultSchema) + log('Resources:', JSON.stringify(resources, null, 2)) + } catch (e) { + log('Error requesting resources list:', e) + } + + // log('Listening for messages. Press Ctrl+C to exit.') + log('Exiting OK...') + // Only close the server if it was initialized + if (server) { + server.close() + } + process.exit(0) + } catch (error) { + log('Fatal error:', error) + // Only close the server if it was initialized + if (server) { + server.close() + } + process.exit(1) + } } // Parse command-line arguments and run the client parseCommandLineArgs(process.argv.slice(2), 3333, 'Usage: npx tsx client.ts [callback-port]') - .then(({ serverUrl, callbackPort, headers }) => { - return runClient(serverUrl, callbackPort, headers) + .then(({ serverUrl, callbackPort, headers, transportStrategy }) => { + return runClient(serverUrl, callbackPort, headers, transportStrategy) }) .catch((error) => { console.error('Fatal error:', error) diff --git a/src/lib/coordination.ts b/src/lib/coordination.ts index ad1d2f6..ffe0c5b 100644 --- a/src/lib/coordination.ts +++ b/src/lib/coordination.ts @@ -5,6 +5,10 @@ import express from 'express' import { AddressInfo } from 'net' import { log, setupOAuthCallbackServerWithLongPoll } from './utils' +export type AuthCoordinator = { + initializeAuth: () => Promise<{ server: Server; waitForAuthCode: () => Promise; skipBrowserAuth: boolean }> +} + /** * Checks if a process with the given PID is running * @param pid The process ID to check @@ -88,6 +92,36 @@ export async function waitForAuthentication(port: number): Promise { } } +/** + * Creates a lazy auth coordinator that will only initiate auth when needed + * @param serverUrlHash The hash of the server URL + * @param callbackPort The port to use for the callback server + * @param events The event emitter to use for signaling + * @returns An AuthCoordinator object with an initializeAuth method + */ +export function createLazyAuthCoordinator( + serverUrlHash: string, + callbackPort: number, + events: EventEmitter +): AuthCoordinator { + let authState: { server: Server; waitForAuthCode: () => Promise; skipBrowserAuth: boolean } | null = null + + return { + initializeAuth: async () => { + // If auth has already been initialized, return the existing state + if (authState) { + return authState + } + + log('Initializing auth coordination on-demand') + + // Initialize auth using the existing coordinateAuth logic + authState = await coordinateAuth(serverUrlHash, callbackPort, events) + return authState + } + } +} + /** * Coordinates authentication between multiple instances of the client/proxy * @param serverUrlHash The hash of the server URL diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 40c744d..1b68bef 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -1,6 +1,15 @@ import { OAuthClientProvider, UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js' +import { Client } from '@modelcontextprotocol/sdk/client/index.js' import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js' +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js' import { Transport } from '@modelcontextprotocol/sdk/shared/transport.js' + +// Connection constants +export const REASON_AUTH_NEEDED = 'authentication-needed' +export const REASON_TRANSPORT_FALLBACK = 'falling-back-to-alternate-transport' + +// Transport strategy types +export type TransportStrategy = 'sse-only' | 'http-only' | 'sse-first' | 'http-first' import { OAuthCallbackServerOptions } from './types' import express from 'express' import net from 'net' @@ -65,21 +74,33 @@ export function mcpProxy({ transportToClient, transportToServer }: { transportTo } /** - * Creates and connects to a remote SSE server with OAuth authentication + * Type for the auth initialization function + */ +export type AuthInitializer = () => Promise<{ + waitForAuthCode: () => Promise + skipBrowserAuth: boolean +}> + +/** + * Creates and connects to a remote server with OAuth authentication + * @param client The client to connect with * @param serverUrl The URL of the remote server * @param authProvider The OAuth client provider * @param headers Additional headers to send with the request - * @param waitForAuthCode Function to wait for the auth code - * @param skipBrowserAuth Whether to skip browser auth and use shared auth - * @returns The connected SSE client transport + * @param authInitializer Function to initialize authentication when needed + * @param transportStrategy Strategy for selecting transport type ('sse-only', 'http-only', 'sse-first', 'http-first') + * @param recursionReasons Set of reasons for recursive calls (internal use) + * @returns The connected transport */ export async function connectToRemoteServer( + client: Client | null, serverUrl: string, authProvider: OAuthClientProvider, headers: Record, - waitForAuthCode: () => Promise, - skipBrowserAuth: boolean = false, -): Promise { + authInitializer: AuthInitializer, + transportStrategy: TransportStrategy = 'http-first', + recursionReasons: Set = new Set(), +): Promise { log(`[${pid}] Connecting to remote server: ${serverUrl}`) const url = new URL(serverUrl) @@ -93,25 +114,88 @@ export async function connectToRemoteServer( ...(init?.headers as Record | undefined), ...headers, ...(tokens?.access_token ? { Authorization: `Bearer ${tokens.access_token}` } : {}), - Accept: "text/event-stream", + Accept: 'text/event-stream', } as Record, - }) - ); + }), + ) }, - }; + } - const transport = new SSEClientTransport(url, { - authProvider, - requestInit: { headers }, - eventSourceInit, - }) + log(`Using transport strategy: ${transportStrategy}`) + // Determine if we should attempt to fallback on error + // Choose transport based on user strategy and recursion history + const shouldAttemptFallback = transportStrategy === 'http-first' || transportStrategy === 'sse-first' + + // Create transport instance based on the strategy + const sseTransport = transportStrategy === 'sse-only' || transportStrategy === 'sse-first' + const transport = sseTransport + ? new SSEClientTransport(url, { + authProvider, + requestInit: { headers }, + eventSourceInit, + }) + : new StreamableHTTPClientTransport(url, { + authProvider, + requestInit: { headers }, + }) try { - await transport.start() - log('Connected to remote server') + if (client) { + await client.connect(transport) + } else { + await transport.start() + if (!sseTransport) { + // Extremely hacky, but we didn't actually send a request when calling transport.start() above, so we don't + // know if we're even talking to an HTTP server. But if we forced that now we'd get an error later saying that + // the client is already connected. So let's just create a one-off client to make a single request and figure + // out if we're actually talking to an HTTP server or not. + const testTransport = new StreamableHTTPClientTransport(url, { authProvider, requestInit: { headers } }) + const testClient = new Client({ name: 'mcp-remote-fallback-test', version: '0.0.0' }, { capabilities: {} }) + await testClient.connect(testTransport) + } + } + log(`Connected to remote server using ${transport.constructor.name}`) + return transport } catch (error) { - if (error instanceof UnauthorizedError || (error instanceof Error && error.message.includes('Unauthorized'))) { + // Check if it's a protocol error and we should attempt fallback + if ( + error instanceof Error && + shouldAttemptFallback && + (sseTransport + ? error.message.includes('405') || error.message.includes('Method Not Allowed') + : error.message.includes('404') || error.message.includes('Not Found')) + ) { + log(`Received error: ${error.message}`) + + // If we've already tried falling back once, throw an error + if (recursionReasons.has(REASON_TRANSPORT_FALLBACK)) { + const errorMessage = `Already attempted transport fallback. Giving up.` + log(errorMessage) + throw new Error(errorMessage) + } + + log(`Recursively reconnecting for reason: ${REASON_TRANSPORT_FALLBACK}`) + + // Add to recursion reasons set + recursionReasons.add(REASON_TRANSPORT_FALLBACK) + + // Recursively call connectToRemoteServer with the updated recursion tracking + return connectToRemoteServer( + client, + serverUrl, + authProvider, + headers, + authInitializer, + sseTransport ? 'http-only' : 'sse-only', + recursionReasons, + ) + } else if (error instanceof UnauthorizedError || (error instanceof Error && error.message.includes('Unauthorized'))) { + log('Authentication required. Initializing auth...') + + // Initialize authentication on-demand + const { waitForAuthCode, skipBrowserAuth } = await authInitializer() + if (skipBrowserAuth) { log('Authentication required but skipping browser auth - using shared auth') } else { @@ -125,11 +209,18 @@ export async function connectToRemoteServer( log('Completing authorization...') await transport.finishAuth(code) - // Create a new transport after auth - const newTransport = new SSEClientTransport(url, { authProvider, requestInit: { headers } }) - await newTransport.start() - log('Connected to remote server after authentication') - return newTransport + if (recursionReasons.has(REASON_AUTH_NEEDED)) { + const errorMessage = `Already attempted reconnection for reason: ${REASON_AUTH_NEEDED}. Giving up.` + log(errorMessage) + throw new Error(errorMessage) + } + + // Track this reason for recursion + recursionReasons.add(REASON_AUTH_NEEDED) + log(`Recursively reconnecting for reason: ${REASON_AUTH_NEEDED}`) + + // Recursively call connectToRemoteServer with the updated recursion tracking + return connectToRemoteServer(client, serverUrl, authProvider, headers, authInitializer, transportStrategy, recursionReasons) } catch (authError) { log('Authorization error:', authError) throw authError @@ -301,6 +392,19 @@ export async function parseCommandLineArgs(args: string[], defaultPort: number, const specifiedPort = args[1] ? parseInt(args[1]) : undefined const allowHttp = args.includes('--allow-http') + // Parse transport strategy + let transportStrategy: TransportStrategy = 'http-first' // Default + const transportIndex = args.indexOf('--transport') + if (transportIndex !== -1 && transportIndex < args.length - 1) { + const strategy = args[transportIndex + 1] + if (strategy === 'sse-only' || strategy === 'http-only' || strategy === 'sse-first' || strategy === 'http-first') { + transportStrategy = strategy as TransportStrategy + log(`Using transport strategy: ${transportStrategy}`) + } else { + log(`Warning: Ignoring invalid transport strategy: ${strategy}. Valid values are: sse-only, http-only, sse-first, http-first`) + } + } + if (!serverUrl) { log(usage) process.exit(1) @@ -343,7 +447,7 @@ export async function parseCommandLineArgs(args: string[], defaultPort: number, }) } - return { serverUrl, callbackPort, headers } + return { serverUrl, callbackPort, headers, transportStrategy } } /** diff --git a/src/proxy.ts b/src/proxy.ts index 9fd87d1..7263a95 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -11,22 +11,36 @@ import { EventEmitter } from 'events' import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js' -import { connectToRemoteServer, log, mcpProxy, parseCommandLineArgs, setupSignalHandlers, getServerUrlHash } from './lib/utils' +import { + connectToRemoteServer, + log, + mcpProxy, + parseCommandLineArgs, + setupSignalHandlers, + getServerUrlHash, + MCP_REMOTE_VERSION, + TransportStrategy, +} from './lib/utils' import { NodeOAuthClientProvider } from './lib/node-oauth-client-provider' -import { coordinateAuth } from './lib/coordination' +import { createLazyAuthCoordinator } from './lib/coordination' /** * Main function to run the proxy */ -async function runProxy(serverUrl: string, callbackPort: number, headers: Record) { +async function runProxy( + serverUrl: string, + callbackPort: number, + headers: Record, + transportStrategy: TransportStrategy = 'http-first', +) { // Set up event emitter for auth flow const events = new EventEmitter() // Get the server URL hash for lockfile operations const serverUrlHash = getServerUrlHash(serverUrl) - // Coordinate authentication with other instances - const { server, waitForAuthCode, skipBrowserAuth } = await coordinateAuth(serverUrlHash, callbackPort, events) + // Create a lazy auth coordinator + const authCoordinator = createLazyAuthCoordinator(serverUrlHash, callbackPort, events) // Create the OAuth client provider const authProvider = new NodeOAuthClientProvider({ @@ -35,20 +49,36 @@ async function runProxy(serverUrl: string, callbackPort: number, headers: Record clientName: 'MCP CLI Proxy', }) - // If auth was completed by another instance, just log that we'll use the auth from disk - if (skipBrowserAuth) { - log('Authentication was completed by another instance - will use tokens from disk') - // TODO: remove, the callback is happening before the tokens are exchanged - // so we're slightly too early - await new Promise((res) => setTimeout(res, 1_000)) - } - // Create the STDIO transport for local connections const localTransport = new StdioServerTransport() + // Keep track of the server instance for cleanup + let server: any = null + + // Define an auth initializer function + const authInitializer = async () => { + const authState = await authCoordinator.initializeAuth() + + // Store server in outer scope for cleanup + server = authState.server + + // If auth was completed by another instance, just log that we'll use the auth from disk + if (authState.skipBrowserAuth) { + log('Authentication was completed by another instance - will use tokens from disk') + // TODO: remove, the callback is happening before the tokens are exchanged + // so we're slightly too early + await new Promise((res) => setTimeout(res, 1_000)) + } + + return { + waitForAuthCode: authState.waitForAuthCode, + skipBrowserAuth: authState.skipBrowserAuth, + } + } + try { - // Connect to remote server with authentication - const remoteTransport = await connectToRemoteServer(serverUrl, authProvider, headers, waitForAuthCode, skipBrowserAuth) + // Connect to remote server with lazy authentication + const remoteTransport = await connectToRemoteServer(null, serverUrl, authProvider, headers, authInitializer, transportStrategy) // Set up bidirectional proxy between local and remote transports mcpProxy({ @@ -59,14 +89,17 @@ async function runProxy(serverUrl: string, callbackPort: number, headers: Record // Start the local STDIO server await localTransport.start() log('Local STDIO server running') - log('Proxy established successfully between local STDIO and remote SSE') + log(`Proxy established successfully between local STDIO and remote ${remoteTransport.constructor.name}`) log('Press Ctrl+C to exit') // Setup cleanup handler const cleanup = async () => { await remoteTransport.close() await localTransport.close() - server.close() + // Only close the server if it was initialized + if (server) { + server.close() + } } setupSignalHandlers(cleanup) } catch (error) { @@ -93,15 +126,18 @@ to the CA certificate file. If using claude_desktop_config.json, this might look } `) } - server.close() + // Only close the server if it was initialized + if (server) { + server.close() + } process.exit(1) } } // Parse command-line arguments and run the proxy parseCommandLineArgs(process.argv.slice(2), 3334, 'Usage: npx tsx proxy.ts [callback-port]') - .then(({ serverUrl, callbackPort, headers }) => { - return runProxy(serverUrl, callbackPort, headers) + .then(({ serverUrl, callbackPort, headers, transportStrategy }) => { + return runProxy(serverUrl, callbackPort, headers, transportStrategy) }) .catch((error) => { log('Fatal error:', error) From 5a38b58f63c44825fa6c02c2410e5a4f77f3c484 Mon Sep 17 00:00:00 2001 From: Glen Maddern Date: Wed, 30 Apr 2025 21:57:17 +1000 Subject: [PATCH 02/33] 0.1.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 317eca6..eeb95b5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mcp-remote", - "version": "0.1.0-2", + "version": "0.1.0", "description": "Remote proxy for Model Context Protocol, allowing local-only clients to connect to remote servers using oAuth", "keywords": [ "mcp", From 2b2b12decd409ff627f199cdfaaa6cd3920ba2b9 Mon Sep 17 00:00:00 2001 From: Glen Maddern Date: Fri, 2 May 2025 11:19:22 +1000 Subject: [PATCH 03/33] Treat 404s and 405s as the same regardless of starting with SSE or HTTPs transport Fixes #47 #48 --- src/lib/utils.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 1b68bef..9e3e243 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -162,9 +162,10 @@ export async function connectToRemoteServer( if ( error instanceof Error && shouldAttemptFallback && - (sseTransport - ? error.message.includes('405') || error.message.includes('Method Not Allowed') - : error.message.includes('404') || error.message.includes('Not Found')) + (error.message.includes('405') || + error.message.includes('Method Not Allowed') || + error.message.includes('404') || + error.message.includes('Not Found')) ) { log(`Received error: ${error.message}`) From 15f9c944f6a9c4305a697387d03dbc372c146d6e Mon Sep 17 00:00:00 2001 From: shaun smith <1936278+evalstate@users.noreply.github.com> Date: Thu, 1 May 2025 07:15:09 +0100 Subject: [PATCH 04/33] Update README.md --- README.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/README.md b/README.md index c7f9e73..c36424c 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,23 @@ To bypass authentication, or to emit custom headers on all requests to your remo ] ``` +### Transport Strategies + +MCP Remote supports different transport strategies when connecting to an MCP server. This allows you to control whether it uses Server-Sent Events (SSE) or HTTP transport, and in what order it tries them. + +Specify the transport strategy with the `--transport` flag: + +```bash +npx mcp-remote https://example.remote/server --transport sse-only +``` + +**Available Strategies:** + +- `http-first` (default): Tries HTTP transport first, falls back to SSE if HTTP fails with a 404 error +- `sse-first`: Tries SSE transport first, falls back to HTTP if SSE fails with a 405 error +- `http-only`: Only uses HTTP transport, fails if the server doesn't support it +- `sse-only`: Only uses SSE transport, fails if the server doesn't support it + ### Claude Desktop [Official Docs](https://modelcontextprotocol.io/quickstart/user) From da1330d2aac094753a6a9b1a2fbb0119bccfc96d Mon Sep 17 00:00:00 2001 From: Glen Maddern Date: Fri, 2 May 2025 11:38:28 +1000 Subject: [PATCH 05/33] 0.1.1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index eeb95b5..bb010a7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mcp-remote", - "version": "0.1.0", + "version": "0.1.1", "description": "Remote proxy for Model Context Protocol, allowing local-only clients to connect to remote servers using oAuth", "keywords": [ "mcp", From 026caedd3c28905d3079a414825df0880928cc18 Mon Sep 17 00:00:00 2001 From: Fadojutimi Temitayo Olusegun Date: Mon, 5 May 2025 02:37:41 +0100 Subject: [PATCH 06/33] fix: changed the header argument processing from a forEach loop to a while loop to handle array modifications correctly, preventing index errors. --- src/lib/utils.ts | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 9e3e243..c6238b2 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -130,14 +130,14 @@ export async function connectToRemoteServer( const sseTransport = transportStrategy === 'sse-only' || transportStrategy === 'sse-first' const transport = sseTransport ? new SSEClientTransport(url, { - authProvider, - requestInit: { headers }, - eventSourceInit, - }) + authProvider, + requestInit: { headers }, + eventSourceInit, + }) : new StreamableHTTPClientTransport(url, { - authProvider, - requestInit: { headers }, - }) + authProvider, + requestInit: { headers }, + }) try { if (client) { @@ -376,8 +376,9 @@ export async function findAvailablePort(preferredPort?: number): Promise export async function parseCommandLineArgs(args: string[], defaultPort: number, usage: string) { // Process headers const headers: Record = {} - args.forEach((arg, i) => { - if (arg === '--header' && i < args.length - 1) { + let i = 0; + while (i < args.length) { + if (args[i] === '--header' && i < args.length - 1) { const value = args[i + 1] const match = value.match(/^([A-Za-z0-9_-]+):(.*)$/) if (match) { @@ -386,8 +387,11 @@ export async function parseCommandLineArgs(args: string[], defaultPort: number, log(`Warning: ignoring invalid header argument: ${value}`) } args.splice(i, 2) + // Do not increment i, as the array has shifted + continue } - }) + i++ + } const serverUrl = args[0] const specifiedPort = args[1] ? parseInt(args[1]) : undefined From c4a2d4a2425d85c9bc36b0efbc23e10cacff70f9 Mon Sep 17 00:00:00 2001 From: Glen Maddern Date: Mon, 5 May 2025 12:40:27 +1000 Subject: [PATCH 07/33] 0.1.2 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index bb010a7..341afe2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mcp-remote", - "version": "0.1.1", + "version": "0.1.2", "description": "Remote proxy for Model Context Protocol, allowing local-only clients to connect to remote servers using oAuth", "keywords": [ "mcp", From 67bd63192f41552fe57fe4947d811565fde2c3af Mon Sep 17 00:00:00 2001 From: Glen Maddern Date: Mon, 5 May 2025 15:11:18 +1000 Subject: [PATCH 08/33] Publishing all commits to pkg.pr.new --- .github/workflows/publish.yml | 30 ++++++++++++++++++++++++++++++ package.json | 1 + 2 files changed, 31 insertions(+) create mode 100644 .github/workflows/publish.yml diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..dd32058 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,30 @@ +name: Publish Any Commit +on: + pull_request: + push: + branches: + - "**" + tags: + - "!**" + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - run: corepack enable + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: "pnpm" + + - name: Install dependencies + run: pnpm install + + - name: Build + run: pnpm build + + - run: pnpm dlx pkg-pr-new publish --compact --bin diff --git a/package.json b/package.json index 341afe2..5ee38e5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,7 @@ { "name": "mcp-remote", "version": "0.1.2", + "packageManager": "pnpm@8.15.1", "description": "Remote proxy for Model Context Protocol, allowing local-only clients to connect to remote servers using oAuth", "keywords": [ "mcp", From c9e082d9e28098c0d6b9c5a6c48fbe0ca9473c69 Mon Sep 17 00:00:00 2001 From: Glen Maddern Date: Mon, 5 May 2025 16:49:20 +1000 Subject: [PATCH 09/33] Removing traces of react --- package.json | 6 +----- pnpm-lock.yaml | 24 ------------------------ tsconfig.json | 2 +- 3 files changed, 2 insertions(+), 30 deletions(-) diff --git a/package.json b/package.json index 5ee38e5..2d65086 100644 --- a/package.json +++ b/package.json @@ -36,9 +36,7 @@ "@modelcontextprotocol/sdk": "^1.10.2", "@types/express": "^5.0.0", "@types/node": "^22.13.10", - "@types/react": "^19.0.12", "prettier": "^3.5.3", - "react": "^19.0.0", "tsup": "^8.4.0", "tsx": "^4.19.3", "typescript": "^5.8.2" @@ -54,8 +52,6 @@ "dts": true, "clean": true, "outDir": "dist", - "external": [ - "react" - ] + "external": [] } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 48d8491..a987cf4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -24,15 +24,9 @@ importers: '@types/node': specifier: ^22.13.10 version: 22.13.10 - '@types/react': - specifier: ^19.0.12 - version: 19.0.12 prettier: specifier: ^3.5.3 version: 3.5.3 - react: - specifier: ^19.0.0 - version: 19.0.0 tsup: specifier: ^8.4.0 version: 8.4.0(tsx@4.19.3)(typescript@5.8.2) @@ -350,9 +344,6 @@ packages: '@types/range-parser@1.2.7': resolution: {integrity: sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==} - '@types/react@19.0.12': - resolution: {integrity: sha512-V6Ar115dBDrjbtXSrS+/Oruobc+qVbbUxDFC1RSbRqLt5SYvxxyIDrSC85RWml54g+jfNeEMZhEj7wW07ONQhA==} - '@types/send@0.17.4': resolution: {integrity: sha512-x2EM6TJOybec7c52BX0ZspPodMsQUd5L6PRwOunVyVUhXiBSKf3AezDL8Dgvgt5o0UfKNfuA0eMLr2wLT4AiBA==} @@ -479,9 +470,6 @@ packages: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} - csstype@3.1.3: - resolution: {integrity: sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==} - debug@2.6.9: resolution: {integrity: sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==} peerDependencies: @@ -899,10 +887,6 @@ packages: resolution: {integrity: sha512-RmkhL8CAyCRPXCE28MMH0z2PNWQBNk2Q09ZdxM9IOOXwxwZbN+qbWaatPkdkWIKL2ZVDImrN/pK5HTRz2PcS4g==} engines: {node: '>= 0.8'} - react@19.0.0: - resolution: {integrity: sha512-V8AVnmPIICiWpGfm6GLzCR/W5FXLchHop40W4nXBmdlEceh16rCN8O8LNWm5bh5XUX91fh7KpA+W0TgMKmgTpQ==} - engines: {node: '>=0.10.0'} - readdirp@4.1.2: resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==} engines: {node: '>= 14.18.0'} @@ -1334,10 +1318,6 @@ snapshots: '@types/range-parser@1.2.7': {} - '@types/react@19.0.12': - dependencies: - csstype: 3.1.3 - '@types/send@0.17.4': dependencies: '@types/mime': 1.3.5 @@ -1474,8 +1454,6 @@ snapshots: shebang-command: 2.0.0 which: 2.0.2 - csstype@3.1.3: {} - debug@2.6.9: dependencies: ms: 2.0.0 @@ -1896,8 +1874,6 @@ snapshots: iconv-lite: 0.6.3 unpipe: 1.0.0 - react@19.0.0: {} - readdirp@4.1.2: {} resolve-from@5.0.0: {} diff --git a/tsconfig.json b/tsconfig.json index cd9cfa1..9bfece1 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -7,7 +7,7 @@ "esModuleInterop": true, "noEmit": true, "lib": ["ES2022", "DOM"], - "types": ["node", "react"], + "types": ["node"], "forceConsistentCasingInFileNames": true, "resolveJsonModule": true } From 114ee3c4b6983fe6b425a0ab32b2c01a3cba4301 Mon Sep 17 00:00:00 2001 From: shaun smith <1936278+evalstate@users.noreply.github.com> Date: Mon, 5 May 2025 11:53:53 +0100 Subject: [PATCH 10/33] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c36424c..bc70b15 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ To bypass authentication, or to emit custom headers on all requests to your remo } ``` -**Note:** Cursor has a bug where spaces inside `args` aren't escaped when it invokes `npx`, which ends up mangling these values. You can work around it using: +**Note:** Cursor and Claude Desktop (Windows) have a bug where spaces inside `args` aren't escaped when it invokes `npx`, which ends up mangling these values. You can work around it using: ```jsonc { From b9105958c1f8c40c10361d8542c647d875b204af Mon Sep 17 00:00:00 2001 From: dp-rufus <73200607+dp-rufus@users.noreply.github.com> Date: Fri, 18 Apr 2025 03:30:43 +0100 Subject: [PATCH 11/33] Attempt auto close --- src/lib/utils.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/lib/utils.ts b/src/lib/utils.ts index c6238b2..8843c3f 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -300,7 +300,8 @@ export function setupOAuthCallbackServerWithLongPoll(options: OAuthCallbackServe log('Auth code received, resolving promise') authCompletedResolve(code) - res.send('Authorization successful! You may close this window and return to the CLI.') + res.send('Authorization successful! You may close this window and return to the CLI.' + + '') // Notify main flow that auth code is available options.events.emit('auth-code-received', code) From 5c71b268694635f7687ab35a38144e6ce4e9db6a Mon Sep 17 00:00:00 2001 From: Glen Maddern Date: Mon, 5 May 2025 15:25:49 +1000 Subject: [PATCH 12/33] Added a 2 second delay before closing the browser --- src/lib/utils.ts | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 8843c3f..c88a08b 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -130,14 +130,14 @@ export async function connectToRemoteServer( const sseTransport = transportStrategy === 'sse-only' || transportStrategy === 'sse-first' const transport = sseTransport ? new SSEClientTransport(url, { - authProvider, - requestInit: { headers }, - eventSourceInit, - }) + authProvider, + requestInit: { headers }, + eventSourceInit, + }) : new StreamableHTTPClientTransport(url, { - authProvider, - requestInit: { headers }, - }) + authProvider, + requestInit: { headers }, + }) try { if (client) { @@ -300,8 +300,16 @@ export function setupOAuthCallbackServerWithLongPoll(options: OAuthCallbackServe log('Auth code received, resolving promise') authCompletedResolve(code) - res.send('Authorization successful! You may close this window and return to the CLI.' + - '') + res.send(` + Authorization successful! + You may close this window and return to the CLI. + + `) // Notify main flow that auth code is available options.events.emit('auth-code-received', code) @@ -377,7 +385,7 @@ export async function findAvailablePort(preferredPort?: number): Promise export async function parseCommandLineArgs(args: string[], defaultPort: number, usage: string) { // Process headers const headers: Record = {} - let i = 0; + let i = 0 while (i < args.length) { if (args[i] === '--header' && i < args.length - 1) { const value = args[i + 1] From 45c1739b4c849575458565c8f5feb746c917fc64 Mon Sep 17 00:00:00 2001 From: Glen Maddern Date: Tue, 6 May 2025 11:13:50 +1000 Subject: [PATCH 13/33] Adding (via mcp-remote ) to clientInfo.name on initialize --- .github/workflows/publish.yml | 11 ++++------- package.json | 1 - src/lib/utils.ts | 15 +++++++++++---- 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index dd32058..c58f197 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -15,14 +15,11 @@ jobs: - name: Checkout code uses: actions/checkout@v4 - - run: corepack enable - - uses: actions/setup-node@v4 + - name: Setup pnpm & install + uses: wyvox/action-setup-pnpm@v3 with: - node-version: 20 - cache: "pnpm" - - - name: Install dependencies - run: pnpm install + node-version: 22 + pnpm-version: 10 - name: Build run: pnpm build diff --git a/package.json b/package.json index 2d65086..ba21bf7 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,6 @@ { "name": "mcp-remote", "version": "0.1.2", - "packageManager": "pnpm@8.15.1", "description": "Remote proxy for Model Context Protocol, allowing local-only clients to connect to remote servers using oAuth", "keywords": [ "mcp", diff --git a/src/lib/utils.ts b/src/lib/utils.ts index c88a08b..e86aaac 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -32,14 +32,21 @@ export function mcpProxy({ transportToClient, transportToServer }: { transportTo let transportToClientClosed = false let transportToServerClosed = false - transportToClient.onmessage = (message) => { - // @ts-expect-error TODO + transportToClient.onmessage = (_message) => { + // TODO: fix types + const message = _message as any log('[Local→Remote]', message.method || message.id) + if (message.method === 'initialize') { + const { clientInfo } = message.params + if (clientInfo) clientInfo.name = `${clientInfo.name} (via mcp-remote ${MCP_REMOTE_VERSION})` + log(JSON.stringify(message, null, 2)) + } transportToServer.send(message).catch(onServerError) } - transportToServer.onmessage = (message) => { - // @ts-expect-error TODO: fix this type + transportToServer.onmessage = (_message) => { + // TODO: fix types + const message = _message as any log('[Remote→Local]', message.method || message.id) transportToClient.send(message).catch(onClientError) } From 63e02eef1c11aa4f218ab94906f3ac1e05591198 Mon Sep 17 00:00:00 2001 From: Glen Maddern Date: Tue, 6 May 2025 09:00:58 +1000 Subject: [PATCH 14/33] Use 127.0.0.1 everywhere _except_ as a redirect_uri for the client registration --- src/lib/node-oauth-client-provider.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/node-oauth-client-provider.ts b/src/lib/node-oauth-client-provider.ts index 1e58b7e..806f3af 100644 --- a/src/lib/node-oauth-client-provider.ts +++ b/src/lib/node-oauth-client-provider.ts @@ -37,7 +37,7 @@ export class NodeOAuthClientProvider implements OAuthClientProvider { } get redirectUrl(): string { - return `http://127.0.0.1:${this.options.callbackPort}${this.callbackPath}` + return `http://localhost:${this.options.callbackPort}${this.callbackPath}` } get clientMetadata() { From 46e33334164cb75be0b6490f205a7c87e0ae775c Mon Sep 17 00:00:00 2001 From: Glen Maddern Date: Mon, 12 May 2025 15:27:57 +1000 Subject: [PATCH 15/33] 0.1.3 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index ba21bf7..77a21a4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mcp-remote", - "version": "0.1.2", + "version": "0.1.3", "description": "Remote proxy for Model Context Protocol, allowing local-only clients to connect to remote servers using oAuth", "keywords": [ "mcp", From 767549412f79bd92d85f07a3c9dfe4f8a2f0cf7b Mon Sep 17 00:00:00 2001 From: Tomer Zait Date: Tue, 6 May 2025 19:00:33 +0300 Subject: [PATCH 16/33] fix issue #64 --- src/lib/utils.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/lib/utils.ts b/src/lib/utils.ts index e86aaac..572550c 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -484,6 +484,11 @@ export function setupSignalHandlers(cleanup: () => Promise) { // Keep the process alive process.stdin.resume() + process.stdin.on('end', async () => { + log('\nShutting down...') + await cleanup() + process.exit(0) + }) } /** From bd75a1cdf026bed04e03ce097293124028c329f1 Mon Sep 17 00:00:00 2001 From: Glen Maddern Date: Mon, 12 May 2025 15:37:49 +1000 Subject: [PATCH 17/33] 0.1.4 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 77a21a4..4c7a40d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mcp-remote", - "version": "0.1.3", + "version": "0.1.4", "description": "Remote proxy for Model Context Protocol, allowing local-only clients to connect to remote servers using oAuth", "keywords": [ "mcp", From b209d98074bc680d0bda58ee61075dcbaf4d9026 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Barthelet?= Date: Tue, 13 May 2025 15:25:49 +0200 Subject: [PATCH 18/33] Add port sourcing from existing client information --- src/lib/utils.ts | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 572550c..1f60c5e 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -3,6 +3,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js' import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js' import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js' import { Transport } from '@modelcontextprotocol/sdk/shared/transport.js' +import { OAuthClientInformationFull, OAuthClientInformationFullSchema } from '@modelcontextprotocol/sdk/shared/auth.js' // Connection constants export const REASON_AUTH_NEEDED = 'authentication-needed' @@ -11,6 +12,7 @@ export const REASON_TRANSPORT_FALLBACK = 'falling-back-to-alternate-transport' // Transport strategy types export type TransportStrategy = 'sse-only' | 'http-only' | 'sse-first' | 'http-first' import { OAuthCallbackServerOptions } from './types' +import { readJsonFile } from './mcp-auth-config' import express from 'express' import net from 'net' import crypto from 'crypto' @@ -352,6 +354,21 @@ export function setupOAuthCallbackServer(options: OAuthCallbackServerOptions) { return { server, authCode, waitForAuthCode } } +async function findExistingClientPort(serverUrl: string): Promise { + const serverUrlHash = getServerUrlHash(serverUrl) + const clientInfo = await readJsonFile(serverUrlHash, 'client_info.json', OAuthClientInformationFullSchema) + if (!clientInfo) { + return undefined + } + + const localhostRedirectUri = clientInfo.redirect_uris.map((uri) => new URL(uri)).find(({ hostname }) => hostname === 'localhost') + if (!localhostRedirectUri) { + throw new Error('Cannot find localhost callback URI from existing client information') + } + + return parseInt(localhostRedirectUri.port) +} + /** * Finds an available port on the local machine * @param preferredPort Optional preferred port to try first @@ -440,11 +457,14 @@ export async function parseCommandLineArgs(args: string[], defaultPort: number, process.exit(1) } - // Use the specified port, or find an available one - const callbackPort = specifiedPort || (await findAvailablePort(defaultPort)) + // Use the specified port, or the existing client port or fallback to find an available one + const [existingClientPort, availablePort] = await Promise.all([findExistingClientPort(serverUrl), findAvailablePort(defaultPort)]) + const callbackPort = specifiedPort || existingClientPort || availablePort if (specifiedPort) { log(`Using specified callback port: ${callbackPort}`) + } else if (existingClientPort) { + log(`Using existing client port: ${existingClientPort}`) } else { log(`Using automatically selected callback port: ${callbackPort}`) } From bd6df4222f5bdeaccadad2691c9404b90233ca34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Barthelet?= Date: Tue, 13 May 2025 15:26:18 +0200 Subject: [PATCH 19/33] Fix schema on clientInformation() --- src/lib/node-oauth-client-provider.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/lib/node-oauth-client-provider.ts b/src/lib/node-oauth-client-provider.ts index 806f3af..0826844 100644 --- a/src/lib/node-oauth-client-provider.ts +++ b/src/lib/node-oauth-client-provider.ts @@ -1,9 +1,8 @@ import open from 'open' import { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js' import { - OAuthClientInformation, OAuthClientInformationFull, - OAuthClientInformationSchema, + OAuthClientInformationFullSchema, OAuthTokens, OAuthTokensSchema, } from '@modelcontextprotocol/sdk/shared/auth.js' @@ -57,9 +56,9 @@ export class NodeOAuthClientProvider implements OAuthClientProvider { * Gets the client information if it exists * @returns The client information or undefined */ - async clientInformation(): Promise { + async clientInformation(): Promise { // log('Reading client info') - return readJsonFile(this.serverUrlHash, 'client_info.json', OAuthClientInformationSchema) + return readJsonFile(this.serverUrlHash, 'client_info.json', OAuthClientInformationFullSchema) } /** From e5cdf08bc88616d4b80b04fdd7f553d6169d07fc Mon Sep 17 00:00:00 2001 From: Glen Maddern Date: Wed, 14 May 2025 20:53:40 +1000 Subject: [PATCH 20/33] Updated SDK version --- package.json | 2 +- pnpm-lock.yaml | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index 4c7a40d..1f87b70 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,7 @@ "open": "^10.1.0" }, "devDependencies": { - "@modelcontextprotocol/sdk": "^1.10.2", + "@modelcontextprotocol/sdk": "^1.11.2", "@types/express": "^5.0.0", "@types/node": "^22.13.10", "prettier": "^3.5.3", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a987cf4..d0720bf 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -16,8 +16,8 @@ importers: version: 10.1.0 devDependencies: '@modelcontextprotocol/sdk': - specifier: ^1.10.2 - version: 1.10.2 + specifier: ^1.11.2 + version: 1.11.2 '@types/express': specifier: ^5.0.0 version: 5.0.0 @@ -211,8 +211,8 @@ packages: '@jridgewell/trace-mapping@0.3.25': resolution: {integrity: sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==} - '@modelcontextprotocol/sdk@1.10.2': - resolution: {integrity: sha512-rb6AMp2DR4SN+kc6L1ta2NCpApyA9WYNx3CrTSZvGxq9wH71bRur+zRqPfg0vQ9mjywR7qZdX2RGHOPq3ss+tA==} + '@modelcontextprotocol/sdk@1.11.2': + resolution: {integrity: sha512-H9vwztj5OAqHg9GockCQC06k1natgcxWQSRpQcPJf6i5+MWBzfKkRtxGbjQf0X2ihii0ffLZCRGbYV2f2bjNCQ==} engines: {node: '>=18'} '@pkgjs/parseargs@0.11.0': @@ -1206,7 +1206,7 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.0 - '@modelcontextprotocol/sdk@1.10.2': + '@modelcontextprotocol/sdk@1.11.2': dependencies: content-type: 1.0.5 cors: 2.8.5 From 6f2399bbfb149d80ba41542cbeebf8d05ef45745 Mon Sep 17 00:00:00 2001 From: Glen Maddern Date: Wed, 14 May 2025 21:10:35 +1000 Subject: [PATCH 21/33] remove client info on conflict --- src/lib/utils.ts | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 1f60c5e..f5d4df0 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -12,10 +12,11 @@ export const REASON_TRANSPORT_FALLBACK = 'falling-back-to-alternate-transport' // Transport strategy types export type TransportStrategy = 'sse-only' | 'http-only' | 'sse-first' | 'http-first' import { OAuthCallbackServerOptions } from './types' -import { readJsonFile } from './mcp-auth-config' +import { getConfigFilePath, readJsonFile } from './mcp-auth-config' import express from 'express' import net from 'net' import crypto from 'crypto' +import fs from 'fs/promises' // Package version from package.json export const MCP_REMOTE_VERSION = require('../../package.json').version @@ -459,14 +460,23 @@ export async function parseCommandLineArgs(args: string[], defaultPort: number, // Use the specified port, or the existing client port or fallback to find an available one const [existingClientPort, availablePort] = await Promise.all([findExistingClientPort(serverUrl), findAvailablePort(defaultPort)]) - const callbackPort = specifiedPort || existingClientPort || availablePort + let callbackPort: number if (specifiedPort) { - log(`Using specified callback port: ${callbackPort}`) + if (existingClientPort && specifiedPort !== existingClientPort) { + log( + `Warning! Specified callback port of ${specifiedPort}, which conflicts with existing client registration port ${existingClientPort}. Deleting existing client data to force reregistration.`, + ) + await fs.rm(getConfigFilePath(getServerUrlHash(serverUrl), 'client_info.json')) + } + log(`Using specified callback port: ${specifiedPort}`) + callbackPort = specifiedPort } else if (existingClientPort) { log(`Using existing client port: ${existingClientPort}`) + callbackPort = existingClientPort } else { - log(`Using automatically selected callback port: ${callbackPort}`) + log(`Using automatically selected callback port: ${availablePort}`) + callbackPort = availablePort } if (Object.keys(headers).length > 0) { From b1dfa9fe5b17f5e9642ef73da2ce7259a43e1acc Mon Sep 17 00:00:00 2001 From: Glen Maddern Date: Wed, 14 May 2025 21:21:38 +1000 Subject: [PATCH 22/33] Picking a default port based on the server hash --- src/client.ts | 2 +- src/lib/utils.ts | 31 +++++++++++++++++++------------ src/proxy.ts | 2 +- 3 files changed, 21 insertions(+), 14 deletions(-) diff --git a/src/client.ts b/src/client.ts index 4e0c14c..d87599c 100644 --- a/src/client.ts +++ b/src/client.ts @@ -151,7 +151,7 @@ async function runClient( } // Parse command-line arguments and run the client -parseCommandLineArgs(process.argv.slice(2), 3333, 'Usage: npx tsx client.ts [callback-port]') +parseCommandLineArgs(process.argv.slice(2), 'Usage: npx tsx client.ts [callback-port]') .then(({ serverUrl, callbackPort, headers, transportStrategy }) => { return runClient(serverUrl, callbackPort, headers, transportStrategy) }) diff --git a/src/lib/utils.ts b/src/lib/utils.ts index f5d4df0..a0a60dc 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -4,6 +4,12 @@ import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js' import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js' import { Transport } from '@modelcontextprotocol/sdk/shared/transport.js' import { OAuthClientInformationFull, OAuthClientInformationFullSchema } from '@modelcontextprotocol/sdk/shared/auth.js' +import { OAuthCallbackServerOptions } from './types' +import { getConfigFilePath, readJsonFile } from './mcp-auth-config' +import express from 'express' +import net from 'net' +import crypto from 'crypto' +import fs from 'fs/promises' // Connection constants export const REASON_AUTH_NEEDED = 'authentication-needed' @@ -11,12 +17,6 @@ export const REASON_TRANSPORT_FALLBACK = 'falling-back-to-alternate-transport' // Transport strategy types export type TransportStrategy = 'sse-only' | 'http-only' | 'sse-first' | 'http-first' -import { OAuthCallbackServerOptions } from './types' -import { getConfigFilePath, readJsonFile } from './mcp-auth-config' -import express from 'express' -import net from 'net' -import crypto from 'crypto' -import fs from 'fs/promises' // Package version from package.json export const MCP_REMOTE_VERSION = require('../../package.json').version @@ -355,8 +355,7 @@ export function setupOAuthCallbackServer(options: OAuthCallbackServerOptions) { return { server, authCode, waitForAuthCode } } -async function findExistingClientPort(serverUrl: string): Promise { - const serverUrlHash = getServerUrlHash(serverUrl) +async function findExistingClientPort(serverUrlHash: string): Promise { const clientInfo = await readJsonFile(serverUrlHash, 'client_info.json', OAuthClientInformationFullSchema) if (!clientInfo) { return undefined @@ -370,6 +369,13 @@ async function findExistingClientPort(serverUrl: string): Promise /** * Parses command line arguments for MCP clients and proxies * @param args Command line arguments - * @param defaultPort Default port for the callback server if specified port is unavailable * @param usage Usage message to show on error * @returns A promise that resolves to an object with parsed serverUrl, callbackPort and headers */ -export async function parseCommandLineArgs(args: string[], defaultPort: number, usage: string) { +export async function parseCommandLineArgs(args: string[], usage: string) { // Process headers const headers: Record = {} let i = 0 @@ -457,9 +462,11 @@ export async function parseCommandLineArgs(args: string[], defaultPort: number, log(usage) process.exit(1) } + const serverUrlHash = getServerUrlHash(serverUrl) + const defaultPort = calculateDefaultPort(serverUrlHash) // Use the specified port, or the existing client port or fallback to find an available one - const [existingClientPort, availablePort] = await Promise.all([findExistingClientPort(serverUrl), findAvailablePort(defaultPort)]) + const [existingClientPort, availablePort] = await Promise.all([findExistingClientPort(serverUrlHash), findAvailablePort(defaultPort)]) let callbackPort: number if (specifiedPort) { @@ -467,7 +474,7 @@ export async function parseCommandLineArgs(args: string[], defaultPort: number, log( `Warning! Specified callback port of ${specifiedPort}, which conflicts with existing client registration port ${existingClientPort}. Deleting existing client data to force reregistration.`, ) - await fs.rm(getConfigFilePath(getServerUrlHash(serverUrl), 'client_info.json')) + await fs.rm(getConfigFilePath(serverUrlHash, 'client_info.json')) } log(`Using specified callback port: ${specifiedPort}`) callbackPort = specifiedPort diff --git a/src/proxy.ts b/src/proxy.ts index 7263a95..535bfe2 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -135,7 +135,7 @@ to the CA certificate file. If using claude_desktop_config.json, this might look } // Parse command-line arguments and run the proxy -parseCommandLineArgs(process.argv.slice(2), 3334, 'Usage: npx tsx proxy.ts [callback-port]') +parseCommandLineArgs(process.argv.slice(2), 'Usage: npx tsx proxy.ts [callback-port]') .then(({ serverUrl, callbackPort, headers, transportStrategy }) => { return runProxy(serverUrl, callbackPort, headers, transportStrategy) }) From 5199279ea7b427237d74848b784b0f43cf434a8b Mon Sep 17 00:00:00 2001 From: Glen Maddern Date: Wed, 14 May 2025 21:24:02 +1000 Subject: [PATCH 23/33] 0.1.5 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 1f87b70..b7f3f7f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mcp-remote", - "version": "0.1.4", + "version": "0.1.5", "description": "Remote proxy for Model Context Protocol, allowing local-only clients to connect to remote servers using oAuth", "keywords": [ "mcp", From 7eecc9ca3f388a24c0deb0c526fee3aedc74edb6 Mon Sep 17 00:00:00 2001 From: Will <76718650+the-wc@users.noreply.github.com> Date: Wed, 14 May 2025 11:49:34 -0700 Subject: [PATCH 24/33] Update README.md Move `env` into mcpServer configuration. The examples have it placed outside. If you don't pay attention, you'll end up wondering why you have empty `env` being passed through. --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index bc70b15..bc0a4a7 100644 --- a/README.md +++ b/README.md @@ -46,11 +46,11 @@ To bypass authentication, or to emit custom headers on all requests to your remo "https://remote.mcp.server/sse", "--header", "Authorization: Bearer ${AUTH_TOKEN}" - ] + ], + "env": { + "AUTH_TOKEN": "..." + } }, - "env": { - "AUTH_TOKEN": "..." - } } } ``` @@ -65,11 +65,11 @@ To bypass authentication, or to emit custom headers on all requests to your remo "https://remote.mcp.server/sse", "--header", "Authorization:${AUTH_HEADER}" // note no spaces around ':' - ] + ], + "env": { + "AUTH_HEADER": "Bearer " // spaces OK in env vars + } }, -"env": { - "AUTH_HEADER": "Bearer " // spaces OK in env vars -} ``` ### Flags From 8f83b189665a8e194c9e2bedae2dffe94f97adb3 Mon Sep 17 00:00:00 2001 From: Angel Nunez Mencias Date: Sun, 18 May 2025 17:00:50 +0200 Subject: [PATCH 25/33] adjust ci --- .github/workflows/publish.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index c58f197..0b903a1 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,11 +1,12 @@ name: Publish Any Commit on: + workflow_dispatch: pull_request: push: branches: - "**" tags: - - "!**" + - "v*" jobs: build: From 675dc6a76008de59a2ec97a030dc813ce2be8577 Mon Sep 17 00:00:00 2001 From: Angel Nunez Mencias Date: Sun, 18 May 2025 17:01:58 +0200 Subject: [PATCH 26/33] fix tool path --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 0b903a1..38e9871 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -17,7 +17,7 @@ jobs: uses: actions/checkout@v4 - name: Setup pnpm & install - uses: wyvox/action-setup-pnpm@v3 + uses: https://github.com/wyvox/action-setup-pnpm@v3 with: node-version: 22 pnpm-version: 10 From 4f6de14fbc3f9deaf0a891dda6ed9440bb6bba3e Mon Sep 17 00:00:00 2001 From: Angel Nunez Mencias Date: Sun, 18 May 2025 17:10:14 +0200 Subject: [PATCH 27/33] add packageManager --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index b7f3f7f..32c140e 100644 --- a/package.json +++ b/package.json @@ -31,6 +31,7 @@ "express": "^4.21.2", "open": "^10.1.0" }, + "packageManager": "pnpm@7.1.7", "devDependencies": { "@modelcontextprotocol/sdk": "^1.11.2", "@types/express": "^5.0.0", From 0213c20d3d2eb252a6cd03872568f04f12755670 Mon Sep 17 00:00:00 2001 From: Angel Nunez Mencias Date: Sun, 18 May 2025 17:11:17 +0200 Subject: [PATCH 28/33] update pnpm --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 32c140e..111afce 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,7 @@ "express": "^4.21.2", "open": "^10.1.0" }, - "packageManager": "pnpm@7.1.7", + "packageManager": "pnpm@10", "devDependencies": { "@modelcontextprotocol/sdk": "^1.11.2", "@types/express": "^5.0.0", From 27907a4624bc2786fd5f8020ef675affc5a9e57f Mon Sep 17 00:00:00 2001 From: Angel Nunez Mencias Date: Sun, 18 May 2025 17:12:39 +0200 Subject: [PATCH 29/33] wip --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 111afce..bb4062c 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,7 @@ "express": "^4.21.2", "open": "^10.1.0" }, - "packageManager": "pnpm@10", + "packageManager": "pnpm@10.11.0", "devDependencies": { "@modelcontextprotocol/sdk": "^1.11.2", "@types/express": "^5.0.0", From a7a76d3f1777ebb05dc5bc2ac88d7f07364d1ef0 Mon Sep 17 00:00:00 2001 From: Angel Nunez Mencias Date: Sun, 18 May 2025 17:18:21 +0200 Subject: [PATCH 30/33] wip --- package.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index bb4062c..3820e75 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,10 @@ "express": "^4.21.2", "open": "^10.1.0" }, - "packageManager": "pnpm@10.11.0", + "engines": { + "node": ">=10", + "pnpm": ">=10" + }, "devDependencies": { "@modelcontextprotocol/sdk": "^1.11.2", "@types/express": "^5.0.0", From d8ce2745068160bf86b79e66ed6cb12c0111908a Mon Sep 17 00:00:00 2001 From: Angel Nunez Mencias Date: Sun, 18 May 2025 17:23:07 +0200 Subject: [PATCH 31/33] wip --- .github/workflows/publish.yml | 1 - package.json | 5 +---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 38e9871..6527995 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -20,7 +20,6 @@ jobs: uses: https://github.com/wyvox/action-setup-pnpm@v3 with: node-version: 22 - pnpm-version: 10 - name: Build run: pnpm build diff --git a/package.json b/package.json index 3820e75..bb4062c 100644 --- a/package.json +++ b/package.json @@ -31,10 +31,7 @@ "express": "^4.21.2", "open": "^10.1.0" }, - "engines": { - "node": ">=10", - "pnpm": ">=10" - }, + "packageManager": "pnpm@10.11.0", "devDependencies": { "@modelcontextprotocol/sdk": "^1.11.2", "@types/express": "^5.0.0", From a63b93aa5cad1cfa65ce69e9de9cc420e9789734 Mon Sep 17 00:00:00 2001 From: Angel Nunez Mencias Date: Sun, 18 May 2025 17:32:42 +0200 Subject: [PATCH 32/33] wip --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 6527995..1008364 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -24,4 +24,4 @@ jobs: - name: Build run: pnpm build - - run: pnpm dlx pkg-pr-new publish --compact --bin + - run: pnpm dlx publish --compact --bin From d1cb48f770c4228c8639358ff608544656bbd57c Mon Sep 17 00:00:00 2001 From: Angel Nunez Mencias Date: Sun, 18 May 2025 18:01:29 +0200 Subject: [PATCH 33/33] a --- .github/workflows/publish.yml | 6 ++++++ package.json | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 1008364..005fbc3 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -15,6 +15,12 @@ jobs: steps: - name: Checkout code uses: actions/checkout@v4 + + - name: Add git.kvant.cloud scope + run: npm config set @kvant:registry=https://git.kvant.cloud/api/packages/${{ github.repository_owner }}/npm/ + + - name: Login to git.kvant.cloud npm + run: npm config set -- '//git.kvant.cloud/api/packages/${{ github.repository_owner }}/npm/:_authToken' "${{ secrets.PHOENIX_PACKAGE_WRITER_TOKEN }}" - name: Setup pnpm & install uses: https://github.com/wyvox/action-setup-pnpm@v3 diff --git a/package.json b/package.json index bb4062c..bf4892f 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "name": "mcp-remote", + "name": "@kvant/mcp-remote", "version": "0.1.5", "description": "Remote proxy for Model Context Protocol, allowing local-only clients to connect to remote servers using oAuth", "keywords": [