Skip to content
Back to search

mcp-proxy

A TypeScript streamable HTTP and SSE proxy for MCP servers that use stdio transport.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/punkpeye--mcp-proxy/badge.svg)](/listings/punkpeye--mcp-proxy)

HTML

<a href="/listings/punkpeye--mcp-proxy"><img src="/api/listings/punkpeye--mcp-proxy/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

npm install mcp-proxy

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 622 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # MCP Proxy
  2. A TypeScript streamable HTTP and SSE proxy for [MCP](https://modelcontextprotocol.io/) servers that use `stdio` transport.
  3. > [!NOTE]
  4. > CORS is enabled by default with configurable options. See [CORS Configuration](#cors-configuration) for details.
  5. > [!NOTE]
  6. > For the inverse — giving a stdio-only client access to a remote MCP server, including the interactive OAuth flow — see [mcp-remote](https://github.com/punkpeye/mcp-remote).
  7. > [!NOTE]
  8. > MCP Proxy is what [FastMCP](https://github.com/punkpeye/fastmcp) uses to enable streamable HTTP and SSE.
  9. ## Protocol revisions
  10. MCP Proxy serves protocol revision `2026-07-28` and the 2025-era revisions
  11. (`2024-10-07` through `2025-11-25`) from the same endpoint. Every POST to the
  12. streamable HTTP endpoint is classified by its own content — the 2026-07-28
  13. revision puts a `_meta` envelope on every request, and requests without one are
  14. served by the 2025-era session machinery — so old and new clients share one URL
  15. and neither has to know the other exists.
  16. | | 2025-era clients | 2026-07-28 clients |
  17. | --------------------- | ---------------- | ----------------------------- |
  18. | `/mcp` (streamable) | yes, sessionful | yes, per-request |
  19. | `/sse` (HTTP+SSE) | yes | n/a — no SSE transport exists |
  20. | stdio (`startStdioServer`) | yes | not yet — see below |
  21. | Change notifications | unsolicited | `subscriptions/listen` stream |
  22. Progress notifications and cancellation cross the proxy in both eras: a
  23. forwarded call carries the caller's abort signal, and relayed progress is
  24. re-tagged with the token the caller sent.
  25. Use `--no-modern` to serve only 2025-era clients; a 2026-07-28 client is then
  26. answered by the 2025-era machinery, which does not recognise its request. The
  27. modern leg lives on the streamable HTTP endpoint, so it is also absent when that
  28. endpoint is disabled (`--server sse`, or `streamEndpoint: null`).
  29. The upstream connection — the server MCP Proxy spawns — negotiates its own
  30. revision independently, so any combination works. It uses the 2025 `initialize`
  31. handshake by default; pass `--upstreamProtocol auto` to probe with
  32. `server/discover` first (needed to front a 2026-07-28 server) or
  33. `--upstreamProtocol modern` to require it.
  34. ```bash
  35. # front a 2026-07-28 stdio server, serving both eras downstream
  36. npx mcp-proxy --upstreamProtocol auto -- my-modern-mcp-server
  37. ```
  38. ### What does not cross the proxy
  39. These are consequences of one design decision — the proxy multiplexes every
  40. downstream connection onto a **single** upstream connection — and are called out
  41. rather than half-solved.
  42. - **Anything that asks the client for input** (elicitation, sampling, roots).
  43. A 2025-era server pushes its request out of band, carrying nothing that says
  44. which caller it belongs to, so relaying it means guessing whose screen to put
  45. the prompt on. A 2026-07-28 upstream is not ambiguous that way — the request
  46. comes back as the `input_required` result of the call the proxy forwarded —
  47. so that direction is a question of scope, not correlation. Not implemented
  48. yet.
  49. - **Log messages, on both sides of a 2026-07-28 connection.** That revision
  50. carries logs per request: the client asks in a request's `_meta`, the server
  51. answers on that request's stream. The proxy can do neither half — downstream
  52. it has no per-request log callback and its notification handlers are passed
  53. nothing to attribute a log to; upstream it cannot ask for logs at all, so a
  54. 2026-07-28 server's per-request logging never fires. 2025-era clients still
  55. get the deprecated unsolicited path: everything from a 2025-era upstream, and
  56. from a 2026-07-28 upstream only what it sends outside the per-request
  57. channel, which a conformant one will not use.
  58. - **`logging/setLevel` upstream.** Answered and honored per downstream
  59. connection — messages below the level a connection asked for are not
  60. forwarded to it — but never passed on: the shared upstream carries one level,
  61. so forwarding would let one client silence another's logs, and the method
  62. does not exist on a 2026-07-28 upstream at all.
  63. - **Client identity.** The upstream sees `mcp-proxy` as its client, not the
  64. downstream caller — so does any telemetry keyed on it.
  65. - **2026-07-28 over stdio.** `startStdioServer` serves 2025-era clients only;
  66. the HTTP side serves both.
  67. - **MCP Events push, and per-caller principals.** See
  68. [MCP Events](#mcp-events-experimental).
  69. > [!NOTE]
  70. > The `/sse` endpoint uses the frozen `@modelcontextprotocol/server-legacy`
  71. > copy of the HTTP+SSE transport, which the v2 SDK removed. That transport is
  72. > deprecated as of `2026-07-28` with a twelve-month window; migrate clients to
  73. > the streamable HTTP endpoint.
  74. ## MCP Events (experimental)
  75. MCP Proxy forwards the webhook and poll half of the Events extension
  76. ([SEP-3415](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/3415),
  77. a draft, last checked against `b08e4f9`). This is experimental forwarding, not
  78. SEP-3415 compliance: anything the table does not list is not forwarded.
  79. | Method | Through the proxy |
  80. | ----------------------------------- | ----------------------------------------------------- |
  81. | `events/list` | forwarded, pagination included |
  82. | `events/poll` | forwarded; cursors come back unchanged |
  83. | `events/subscribe` | forwarded, to subscribe and to refresh |
  84. | `events/unsubscribe` | forwarded |
  85. | `events/stream` (push) | not forwarded: `-32026 Unsupported` |
  86. | `notifications/events/list_changed` | not delivered: `listChanged` is advertised as `false` |
  87. - **Only when the upstream offers it.** These methods are answered only if the
  88. upstream advertises `capabilities.extensions["io.modelcontextprotocol/events"]`
  89. (an empty `{}` counts). Otherwise every `events/*` request is `-32601 Method
  90. not found`, as before.
  91. - **Passed through, not parsed.** Params and results cross as they are: `null`
  92. stays distinct from absent (`cursor`, `ttlMs`), and unknown fields and
  93. `_meta` survive. Errors keep their code, message and `data` for every code
  94. SEP-3415 uses. `resultType` belongs to the protocol revision, so each
  95. connection drops and re-stamps it, and a 2026-07-28 connection adds a
  96. `serverInfo` entry to a result's `_meta` when it has none. Cancellation,
  97. progress and `--requestTimeout` apply as to any forwarded call.
  98. - **Webhooks go straight to the caller.** The upstream POSTs to `delivery.url`
  99. itself. The proxy never receives a webhook, creates or checks a secret,
  100. stores a subscription or refreshes one, and a downstream connection closing
  101. unsubscribes nothing. A subscription lasts as long as the upstream keeps it:
  102. until its TTL lapses, someone calls `events/unsubscribe`, or the upstream
  103. ends it.
  104. - **No push.** The proxy answers `events/stream` itself with `-32026
  105. Unsupported` and `data: { "feature": "deliveryMode", "value": "push" }`:
  106. SEP-3415's signal that a delivery mode is not available, so a client can
  107. fall back to poll or webhook. (`-32601` would read as "no Events support at
  108. all".) The catalog is not rewritten, so event types still list `"push"`, and
  109. those that offer only push cannot be consumed through the proxy. Like every
  110. SEP-3415 code, `-32026` is provisional until the SEP is accepted.
  111. - **Upstream revision.** SEP-3415 is defined for `2026-07-28`, so a conformant
  112. server advertises the extension on `server/discover` only. Run the proxy
  113. with `--upstreamProtocol auto` (or `modern`). Under the default `legacy`
  114. handshake the proxy sees the extension only if the server also puts it in
  115. its `initialize` result, as some do. Downstream, both eras get the methods.
  116. - **`Mcp-Name`.** SEP-3415 requires it, set to `params.name`, on `events/poll`,
  117. `events/subscribe` and `events/unsubscribe` over streamable HTTP. The SDK
  118. client sets it; the proxy does not check it.
  119. - **Only `extensions` is relayed.** The pre-SEP top-level `capabilities.events`
  120. that some clients still read is dropped when the SDK parses the upstream's
  121. capabilities.
  122. - **Your own `Server`.** The CLI and `startStdioServer` advertise
  123. `listChanged: false`. If you build the downstream `Server` yourself (for
  124. `proxyServer`, or through `initStdioServer`), do the same.
  125. > [!WARNING]
  126. > **Every caller is the same principal upstream.** SEP-3415 keys a webhook
  127. > subscription on `(principal, delivery.url, name, arguments)`, where the
  128. > principal is whoever the upstream authenticated. The proxy has one upstream
  129. > connection (for the CLI, one process), so every downstream caller is that
  130. > process's own identity: its credentials, its environment.
  131. >
  132. > - Two callers that send the same `delivery.url`, `name` and `arguments`
  133. > share one subscription, and either can refresh it, rotate its secret or
  134. > delete it.
  135. > - The upstream caches a callback URL's verification per principal, so a URL
  136. > one caller has verified is open to every other caller without a new
  137. > challenge.
  138. > - stdio carries no MCP authentication, and SEP-3415 has a server refuse
  139. > `events/subscribe` and `events/unsubscribe` without a principal
  140. > (`Forbidden`). Through the CLI they work only if the server treats its own
  141. > process identity as the principal.
  142. > - Webhooks are POSTed from wherever the upstream runs — for the CLI, the
  143. > proxy's host. Anyone who can reach the proxy chooses those URLs, so make
  144. > sure the server does the URL checks SEP-3415 requires before exposing the
  145. > proxy.
  146. >
  147. > `--apiKey` and `authenticate` decide who reaches the proxy, not who the
  148. > upstream thinks is calling, and the proxy passes on no per-caller identity.
  149. > Isolating principals takes a separate upstream connection (process) per
  150. > principal, or a trusted delegation mechanism designed for it.
  151. ## Installation
  152. ```bash
  153. npm install mcp-proxy
  154. ```
  155. ## Quickstart
  156. ### Command-line
  157. ```bash
  158. # no mcp-proxy options
  159. npx mcp-proxy npx -y @anthropic/mcp-server-filesystem /path
  160. # with mcp-proxy options
  161. npx mcp-proxy --port 8080 --shell -- tsx server.js
  162. ```
  163. The second spawns `tsx server.js` over `stdio` and serves it on port 8080 at `/mcp` (streamable HTTP) and `/sse` (SSE).
  164. > [!NOTE]
  165. > **About the `--` separator:**
  166. > - The `--` separator is **optional** when you don't need to pass options to mcp-proxy
  167. > - Use `--` when you need to pass options to mcp-proxy (like `--port`, `--shell`, etc.) to clearly separate them from the command
  168. > - Without `--`, the first positional argument is treated as the command, and all subsequent arguments are passed to that command
  169. > - The `--` separator is also useful when the command itself has flags that might conflict with mcp-proxy options
  170. options:
  171. - `--server`: Set to `sse` or `stream` to only enable the respective transport (default: both)
  172. - `--endpoint`: If `server` is set to `sse` or `stream`, this option sets the endpoint path (default: `/sse` or `/mcp`)
  173. - `--sseEndpoint`: Set the SSE endpoint path (default: `/sse`). Overrides `--endpoint` if `server` is set to `sse`.
  174. - `--streamEndpoint`: Set the streamable HTTP endpoint path (default: `/mcp`). Overrides `--endpoint` if `server` is set to `stream`.
  175. - `--stateless`: Create a fresh server instance per request instead of maintaining sessions. Applies to the 2025-era leg; 2026-07-28 is per-request by construction.
  176. - `--modern`: Serve protocol revision 2026-07-28 on the streamable HTTP endpoint alongside the 2025-era revisions (default: `true`). Use `--no-modern` to serve only 2025-era clients. See [Protocol revisions](#protocol-revisions).
  177. - `--upstreamProtocol`: Which protocol revision to speak to the spawned server — `legacy` (default), `auto`, or `modern`. See [Protocol revisions](#protocol-revisions).
  178. - `--port`: Specify the port to listen on (default: 8080)
  179. - `--connectionTimeout`: Timeout in milliseconds for the initial connection to the MCP server (default: 60000)
  180. - `--requestTimeout`: Timeout in milliseconds for requests to the MCP server (default: 300000)
  181. - `--keepAliveTimeout`: HTTP keep-alive timeout in milliseconds for stateful stream sessions (default: 300000)
  182. - `--sessionIdleTimeout`: How long in milliseconds a stateful stream session survives with no stream attached and no requests before it is closed (default: 1800000, 30 minutes). Set to `0` to keep every session until its client sends `DELETE`. See [Abandoned sessions](#abandoned-sessions).
  183. - `--eventStore`: Enable the resumability event store, letting clients replay missed messages after a reconnect (default: `true`). `--no-eventStore` disables it. See [Resumability and memory use](#resumability-and-memory-use).
  184. - `--eventStoreMaxEvents`: Maximum number of buffered events the resumability event store retains per session before it evicts the oldest (default: 1000). Ignored when `--no-eventStore` is set.
  185. - `--maxBodySize`: Maximum request body size in bytes accepted by the streamable HTTP endpoint and the SSE endpoint's `POST /messages`; larger requests are answered with `413 Payload Too Large` (default: 10485760, 10 MiB). Set to `0` to disable the limit. See [Request body size](#request-body-size).
  186. - `--debug`: Enable debug logging
  187. - `--shell`: Spawn the server via the user's shell
  188. - `--apiKey`: API key for authenticating requests (uses X-API-Key header)
  189. - `--sslCa`: Filename to override the trusted CA certificates
  190. - `--sslCert`: Cert chains filename in PEM format
  191. - `--sslKey`: Private keys filename in PEM format
  192. - `--corsAddAllowedHeader`: Add a header name to `Access-Control-Allow-Headers` (defaults preserved). Repeat to add multiple. Useful when running with `--apiKey` so browser preflights for `X-API-Key` succeed.
  193. ### Troubleshooting Python stdio servers
  194. If a Python stdio server times out with `Expected server to respond to ping`, run Python unbuffered — buffered stdout can delay JSON-RPC messages long enough for the proxy to treat the server as unresponsive:
  195. ```bash
  196. npx mcp-proxy -- python -u -m your_package.mcp_server
  197. # or: PYTHONUNBUFFERED=1 npx mcp-proxy -- python -m your_package.mcp_server
  198. ```
  199. stdio servers should also reserve stdout for protocol messages — send diagnostics to stderr, and use `--debug` for proxy-side logs.
  200. ### Stateless Mode
  201. By default each client connection holds a server instance for the life of its session. `--stateless` creates a fresh instance per request instead, so requests are fully independent — which suits serverless platforms, load-balanced deployments, and anywhere you'd rather not hold connection state.
  202. ```bash
  203. npx mcp-proxy --port 8080 --stateless -- tsx server.js
  204. # stream-only transport
  205. npx mcp-proxy --port 8080 --stateless --server stream -- tsx server.js
  206. ```
  207. > [!NOTE]
  208. > Stateless mode only affects HTTP streamable transport (`/mcp` endpoint). SSE transport behavior remains unchanged.
  209. ### API Key Authentication
  210. Optional and off by default. When enabled, clients must send a valid key in the `X-API-Key` header.
  211. ```bash
  212. npx mcp-proxy --port 8080 --apiKey "your-secret-key" -- tsx server.js
  213. # or via the environment
  214. export MCP_PROXY_API_KEY="your-secret-key"
  215. npx mcp-proxy --port 8080 -- tsx server.js
  216. ```
  217. Clients pass it as a transport header:
  218. ```typescript
  219. const transport = new StreamableHTTPClientTransport(
  220. new URL("http://localhost:8080/mcp"),
  221. { headers: { "X-API-Key": "your-secret-key" } },
  222. );
  223. ```
  224. `/ping` and `OPTIONS` preflights are exempt. Keys travel in a header, so serve over HTTPS in production.
  225. ### CORS Configuration
  226. #### Default Behavior
  227. CORS is enabled by default with:
  228. - **Origin**: `*` (allow all origins)
  229. - **Methods**: `GET, POST, DELETE, OPTIONS`
  230. - **Headers**: `Content-Type, Authorization, Accept, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-Id, Mcp-Method, Mcp-Name`
  231. - **Credentials**: `true`
  232. - **Exposed Headers**: `Mcp-Session-Id`
  233. `Access-Control-Allow-Credentials` is omitted whenever the allowed origin comes
  234. out as `*`, because the Fetch Standard makes a browser
  235. [reject the whole CORS response](https://fetch.spec.whatwg.org/#http-access-control-allow-credentials)
  236. when it sees both. Credentialed browser requests (`credentials: "include"`,
  237. `withCredentials`) therefore need an explicit `origin` — a list or a function,
  238. not a wildcard.
  239. `Mcp-Method` and `Mcp-Name` are required on 2026-07-28 streamable HTTP POSTs, so
  240. browser clients on that revision need them allowed. That revision's
  241. `Mcp-Param-*` headers are a prefix, which `Access-Control-Allow-Headers` cannot
  242. express — if your tools declare `x-mcp-header` parameters, add those header
  243. names explicitly with `--corsAddAllowedHeader` or `allowedHeaders`.
  244. #### Configuration
  245. `cors: true` (or omitted) uses the defaults, `cors: false` disables it, and a
  246. `CorsOptions` object overrides individual fields:
  247. ```typescript
  248. import { startHTTPServer, CorsOptions } from "mcp-proxy";
  249. const cors: CorsOptions = {
  250. // A list, or a function for dynamic validation
  251. origin: ["https://app.example.com"],
  252. methods: ["GET", "POST", "DELETE", "OPTIONS"],
  253. // "*" allows any header — the usual fix for browser preflight failures.
  254. // Listing headers instead REPLACES the defaults, so restate the protocol's
  255. // own: dropping Mcp-Method/Mcp-Name breaks browser clients on 2026-07-28.
  256. allowedHeaders: "*",
  257. exposedHeaders: ["Mcp-Session-Id"],
  258. credentials: true,
  259. maxAge: 86400,
  260. };
  261. await startHTTPServer({ cors, createServer, port: 3000 });
  262. ```
  263. Upgrading from 5.5.6 or earlier, where headers were wildcarded automatically?
  264. Set `allowedHeaders: "*"` to restore that behavior.
  265. #### CLI: adding allowed headers
  266. `--corsAddAllowedHeader` appends to the default `Access-Control-Allow-Headers`
  267. list, keeping the defaults. Repeat it to add more. The common use is unblocking
  268. the browser preflight for a custom auth header under `--apiKey`:
  269. ```bash
  270. npx mcp-proxy --port 8080 --apiKey secret \
  271. --corsAddAllowedHeader X-API-Key \
  272. -- npx -y @modelcontextprotocol/server-filesystem /srv
  273. ```
  274. For origin allowlists, wildcard headers, or disabling CORS, use the
  275. programmatic `cors` option above.
  276. ### Node.js SDK
  277. #### `proxyServer`
  278. Sets up a proxy between a server and a client.
  279. ```ts
  280. const transport = new StdioClientTransport();
  281. const client = new Client();
  282. await client.connect(transport);
  283. const serverCapabilities = client.getServerCapabilities();
  284. const server = new Server(client.getServerVersion(), {
  285. capabilities: serverCapabilities,
  286. });
  287. await proxyServer({
  288. client,
  289. server,
  290. serverCapabilities,
  291. });
  292. ```
  293. In this example, the server will proxy all requests to the client and vice
  294. versa. Handlers are registered from `serverCapabilities`, so a method the
  295. upstream never advertised is answered "method not found" locally instead of
  296. making a round trip to find out.
  297. Options:
  298. - `client`: The connected upstream client
  299. - `server`: The downstream server to wire up
  300. - `serverCapabilities`: What the upstream advertised; decides which handlers are registered
  301. - `requestTimeout`: Timeout in milliseconds applied to every forwarded request (optional)
  302. > [!NOTE]
  303. > One `proxyServer` call serves one downstream connection, but they share a
  304. > single upstream client, so an upstream notification is received once and
  305. > offered to **every** connected client. Two are narrowed before they are
  306. > forwarded: `notifications/resources/updated` reaches only the connections
  307. > that subscribed to that URI, and `notifications/message` only those whose
  308. > `logging/setLevel` admits it — a connection that never set one still gets
  309. > everything. The `list_changed` notifications are not
  310. > narrowed — they describe the one upstream, which every connection is looking
  311. > at. If you derive per-request identity in `createServer` to serve several
  312. > tenants from one proxy, that is the line to check against your model.
  313. #### `startHTTPServer`
  314. Starts a proxy that listens on a `port`, and sends messages to the attached server via `StreamableHTTPServerTransport` and `SSEServerTransport`.
  315. ```ts
  316. import { Server } from "@modelcontextprotocol/server";
  317. import { startHTTPServer } from "mcp-proxy";
  318. const { close, notify } = await startHTTPServer({
  319. createServer: async () => {
  320. return new Server();
  321. },
  322. port: 8080,
  323. stateless: false, // Optional: enable stateless mode for streamable HTTP transport
  324. });
  325. close();
  326. ```
  327. Options:
  328. - `createServer`: Function that creates a new server instance for each connection
  329. - `eventStore`: Event store for the streamable HTTP transport's resumability support (optional). Pass `false` to disable resumability entirely; omit to get a fresh, bounded `InMemoryEventStore` per session (see `eventStoreMaxEvents`); pass an `EventStore` instance to bring your own (e.g. persistent/cross-process), shared across all sessions. See [Resumability and memory use](#resumability-and-memory-use).
  330. - `eventStoreMaxEvents`: Caps how many events the auto-created per-session `InMemoryEventStore` retains before evicting the oldest (default: 1000). Only applies when `eventStore` is not explicitly provided.
  331. - `port`: Port number to listen on
  332. - `host`: Host to bind to (default: "::")
  333. - `keepAliveTimeout`: HTTP keep-alive timeout in milliseconds for stateful stream sessions (default: 300000)
  334. - `sessionIdleTimeout`: How long in milliseconds a stateful stream session survives with no stream attached and no requests before it is closed (default: 1800000, 30 minutes). Pass `0` to keep every session until its client sends `DELETE`. See [Abandoned sessions](#abandoned-sessions).
  335. - `maxBodySize`: Caps how many bytes of a request body the streamable HTTP endpoint and the SSE endpoint's `POST /messages` buffer; larger requests are answered with `413 Payload Too Large` (default: 10485760, 10 MiB). Pass `false` to disable the cap. See [Request body size](#request-body-size).
  336. - `sseEndpoint`: SSE endpoint path (default: "/sse", set to null to disable)
  337. - `streamEndpoint`: Streamable HTTP endpoint path (default: "/mcp", set to null to disable)
  338. - `stateless`: Enable stateless mode for HTTP streamable transport (default: false). Applies to the 2025-era leg; protocol revision 2026-07-28 is per-request by construction.
  339. - `modern`: Serve protocol revision 2026-07-28 alongside the 2025-era revisions on `streamEndpoint` (default: true). See [Protocol revisions](#protocol-revisions).
  340. - `apiKey`: API key for authenticating requests (optional)
  341. - `cors`: CORS configuration (default: enabled with permissive settings, see CORS Configuration section)
  342. - `onConnect`: Callback when a server instance is created (optional). Fires once per session on the 2025-era legs and **once per request** on the 2026-07-28 leg, which builds a fresh instance per request.
  343. - `onClose`: Callback when a server instance is torn down (optional). Same per-era unit as `onConnect`; keep it cheap and idempotent. A rejection is logged and does not stop the rest of teardown.
  344. - `onUnhandledRequest`: Callback for unhandled HTTP requests (optional)
  345. - `beforeDispatch`: Lets the server answer a request with its own HTTP response before `mcp-proxy` hands it to the transport (optional). See [Answering before dispatch](#answering-before-dispatch).
  346. Returns `{ close, notify }`. See [Change notifications](#change-notifications)
  347. for what `notify` is for.
  348. ##### Change notifications
  349. A 2025-era client receives `list_changed` and `resources/updated` unsolicited on
  350. its own connection, and `proxyServer` forwards them there for you.
  351. Protocol revision 2026-07-28 has no such connection: it delivers those events
  352. only on a `subscriptions/listen` stream the client opened, and the per-request
  353. server instances that serve it own no stream. Those events are published to the
  354. handler's bus instead, which is what `startHTTPServer` returns as `notify`. Wire
  355. your upstream change events to it:
  356. ```ts
  357. import { getUpstreamBridge, startHTTPServer } from "mcp-proxy";
  358. const { notify } = await startHTTPServer({ createServer, port: 8080 });
  359. getUpstreamBridge({ client }).subscribe({
  360. promptsListChanged: () => notify.promptsChanged(),
  361. resourcesListChanged: () => notify.resourcesChanged(),
  362. resourceUpdated: ({ uri }) => notify.resourceUpdated(uri),
  363. toolsListChanged: () => notify.toolsChanged(),
  364. });
  365. ```
  366. `notify` is a no-op when `modern: false`, so this wiring is safe to leave in
  367. place unconditionally. The `mcp-proxy` CLI does exactly this.
  368. `getUpstreamBridge(client)` registers the upstream notification handlers once
  369. per client and fans them out, so several downstream connections can share one
  370. upstream server. `subscribe(sink)` returns a lease with
  371. `addResourceSubscription` / `removeResourceSubscription` / `owns` / `release`.
  372. Resource subscriptions are owned per lease, so one connection unsubscribing
  373. never cancels a URI another still wants, and `release()` drops whatever a
  374. disconnecting connection held.
  375. A 2026-07-28 client asks for resource updates through the `resourceSubscriptions`
  376. field of its `subscriptions/listen` filter rather than `resources/subscribe`.
  377. Pass `onListenSubscriptions` to act on those URIs; `acquireListenSubscriptions`
  378. is the implementation the CLI uses, and acquires them all-or-nothing so a filter
  379. the upstream only partly accepts does not strand the rest:
  380. ```ts
  381. import { acquireListenSubscriptions } from "mcp-proxy";
  382. await startHTTPServer({
  383. createServer,
  384. onListenSubscriptions: (uris) => acquireListenSubscriptions({ client, uris }),
  385. port: 8080,
  386. });
  387. ```
  388. ##### Resumability and memory use
  389. The streamable HTTP transport can retain server→client messages so a client
  390. reconnecting with a `Last-Event-ID` resumes where it left off. Each session gets
  391. its own `InMemoryEventStore` capped at 1000 events (oldest evicted first, via
  392. `--eventStoreMaxEvents` / `eventStoreMaxEvents`), so a long-lived session's
  393. memory stays bounded rather than growing for the life of the process.
  394. Don't need resume-after-reconnect? `--no-eventStore` (CLI) or
  395. `eventStore: false` (library) drops the bookkeeping entirely. For a larger
  396. replay window or shared storage across processes (e.g. Redis), pass your own
  397. `EventStore` — you're then responsible for bounding its size.
  398. ##### Abandoned sessions
  399. A 2025-era session outlives the connection that created it — that is what makes
  400. replay-on-reconnect work — and is meant to be ended by a `DELETE`. In practice
  401. most clients never send one: they close a laptop, get killed, or lose a network,
  402. and are simply never heard from again. Each session left behind holds a server
  403. instance, a transport, and an event store that goes on buffering notifications
  404. it can no longer deliver.
  405. `mcp-proxy` closes a session once nothing is attached to it and nothing has
  406. happened for 30 minutes (`--sessionIdleTimeout` / `sessionIdleTimeout`). A
  407. session with a stream attached is never closed however quiet it is, so a client
  408. parked on the notification stream is unaffected; the countdown starts when the
  409. stream drops, not at the last request. Closing runs the same path a `DELETE`
  410. does, so `onClose` fires exactly as it always has.
  411. What this costs is resumability past the timeout: a client returning later with
  412. a `Last-Event-ID` gets a new session instead of its replay. With the default
  413. in-memory store capped at 1000 events, there is usually little left to replay by
  414. then anyway. Set the timeout to `0` to keep every session until its client sends
  415. `DELETE`.
  416. Sessions on the `/sse` endpoint end with their connection and are unaffected, as
  417. are `--stateless` mode and protocol revision 2026-07-28, neither of which
  418. retains anything between requests.
  419. ##### Request body size
  420. The streamable HTTP endpoint and the SSE endpoint's `POST /messages` buffer each
  421. request body before parsing it, so a slow-chunking client could otherwise grow
  422. the process's memory for as long as it kept sending. `mcp-proxy` caps that
  423. buffer at 10 MiB (`--maxBodySize` / `maxBodySize`). An oversized
  424. `Content-Length` is rejected before any body is read; a chunked body is cut off
  425. as soon as it exceeds the cap. Either way the answer is `413 Payload Too Large`
  426. with a JSON-RPC error body naming the limit, then the connection closes.
  427. The default is deliberately generous — base64 images, documents and long pasted
  428. text routinely push a single tool call past a megabyte. Raise it if your clients
  429. legitimately send more, or set `0` (CLI) / `false` (library) to disable it,
  430. which restores unbounded buffering and is only safe behind a gateway that
  431. already limits body size.
  432. ##### Answering before dispatch
  433. Once a message reaches the transport, the SDK owns the HTTP response: a tool
  434. runs after that, and whatever it throws comes back as a JSON-RPC error on a
  435. `200`. So a tool cannot send MCP's `403 insufficient_scope` challenge, which
  436. tells the client to re-authorize with more scopes.
  437. `beforeDispatch` runs first. It is offered every message POSTed to the
  438. streamable HTTP endpoint or the SSE endpoint's `POST /messages` once
  439. `authenticate` has passed, along with that request's `authResult` and the
  440. `server` that would handle it. A batch is offered one message at a time. Return
  441. a `Response` to answer the request with it - none of its messages is then
  442. dispatched - or nothing to let the message through. For the scope
  443. challenge, throw an `InsufficientScopeError` and `mcp-proxy` builds it:
  444. ```ts
  445. await startHTTPServer({
  446. authenticate,
  447. beforeDispatch: ({ authResult, message }) => {
  448. const missing = missingScopes(authResult, message); // your own check
  449. if (missing.length > 0) {
  450. throw {
  451. data: { error: "insufficient_scope", requiredScopes: missing },
  452. name: "InsufficientScopeError",
  453. };
  454. }
  455. },
  456. createServer,
  457. oauth: { protectedResource: { resource: "https://example.com/mcp" } },
  458. port: 8080,
  459. });
  460. ```
  461. The client gets a `403` with `WWW-Authenticate: Bearer error="insufficient_scope",
  462. scope="…", resource_metadata="…"`. `resource_metadata` comes from
  463. `oauth.protectedResource.resource` and is left out without it; `oauth.realm`
  464. adds `realm`. A thrown `Response` is sent as is; anything else thrown is
  465. answered with a `500`.
  466. #### `startStdioServer`
  467. Starts a proxy that listens on a `stdio`, and sends messages to the attached `sse` or `streamable` server.
  468. ```ts
  469. import { ServerType, startStdioServer } from "mcp-proxy";
  470. await startStdioServer({
  471. serverType: ServerType.SSE,
  472. url: "http://127.0.0.1:8080/sse",
  473. });
  474. ```
  475. Options:
  476. - `serverType`: `ServerType.SSE` or `ServerType.HTTPStream`
  477. - `url`: URL of the upstream MCP server
  478. - `transportOptions`: Options passed to the client transport (optional)
  479. - `upstreamProtocol`: Which protocol revision to speak upstream — `"legacy"` (default, the 2025 `initialize` handshake), `"auto"` (probe with `server/discover`, fall back to the handshake), or `"modern"` (require 2026-07-28). See [Protocol revisions](#protocol-revisions). Note that the stdio connection this serves is 2025-era regardless.
  480. - `initStdioServer` / `initStreamClient`: Bring your own `Server` / `Client` instance (optional)
  481. Closing the returned server also closes the upstream client created by
  482. `startStdioServer`. A client supplied by `initStreamClient` remains caller-owned
  483. during ordinary shutdown.
  484. #### `tapTransport`
  485. Taps into a transport and logs events.
  486. ```ts
  487. import { tapTransport } from "mcp-proxy";
  488. const transport = tapTransport(new StdioClientTransport(), (event) => {
  489. console.log(event);
  490. });
  491. ```
  492. ## Development
  493. ### Running MCP Proxy with a local server
  494. ```bash
  495. tsx src/bin/mcp-proxy.ts --debug -- tsx src/fixtures/simple-stdio-server.ts
  496. ```

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.