Skip to content

Commit 64d488d

Browse files
cliffhallclaude
andcommitted
fix(everything): harden HTTP transport request handling
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 69b53e9 commit 64d488d

6 files changed

Lines changed: 268 additions & 16 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@modelcontextprotocol/server-everything": patch
3+
---
4+
5+
Harden request handling in the HTTP transports.

‎src/everything/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,8 @@ npm run start:streamableHttp
108108

109109
The endpoint is `http://localhost:3001/mcp` (`PORT` overrides the port). It serves 2026-07-28 clients statelessly and 2025-era clients with sessions, from the same URL.
110110

111+
Both HTTP transports (Streamable HTTP and HTTP+SSE) accept browser requests only from a localhost origin: an `Origin` header whose host is `localhost`, `127.0.0.1` or `[::1]`, on any port, such as the MCP Inspector's. A request carrying any other `Origin` is refused with `403 Forbidden`. Clients that send no `Origin` header, which is every non-browser client, are unaffected.
112+
111113
## Running from source with [HTTP+SSE Transport](https://modelcontextprotocol.io/specification/2024-11-05/basic/transports#http-with-sse) (deprecated as of [2025-03-26](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports))
112114

113115
```shell

‎src/everything/__tests__/sse.test.ts‎

Lines changed: 89 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@
44
* raw HTTP for the requests a well-behaved client never sends. The launcher's
55
* `startSseServer()` is checked with `listenOrExit` stubbed, so no fixed port
66
* is ever bound.
7+
*
8+
* A browser request is served only from a localhost origin: the tests pin
9+
* that a foreign `Origin` is refused with a 403 and no CORS grant at every
10+
* route, preflights included, and that a localhost one is served.
711
*/
812
import type { Server } from "node:http";
913
import { once } from "node:events";
@@ -172,20 +176,102 @@ describe("SSE transport", () => {
172176
);
173177
});
174178

175-
it("answers a CORS preflight for any origin", async () => {
179+
it("answers a CORS preflight from a localhost origin, echoing that origin", async () => {
176180
const response = await fetch(`${base}/message`, {
177181
method: "OPTIONS",
178182
headers: {
179-
origin: "http://elsewhere.example",
183+
origin: "http://localhost:6274",
180184
"access-control-request-method": "POST",
181185
},
182186
});
183187
expect(response.status).toBe(204);
184-
expect(response.headers.get("access-control-allow-origin")).toBe("*");
188+
expect(response.headers.get("access-control-allow-origin")).toBe(
189+
"http://localhost:6274",
190+
);
185191
expect(response.headers.get("access-control-allow-methods")).toBe(
186192
"GET,POST",
187193
);
188194
});
195+
196+
it("serves a client whose requests carry a localhost Origin", async () => {
197+
const client = new Client({ name: "sse-test", version: "0.0.0" });
198+
// Every request the transport makes, the stream's GET included, carries
199+
// the Origin a browser page served from localhost would send.
200+
const withOrigin = (url: string | URL, init?: RequestInit) => {
201+
const headers = new Headers(init?.headers);
202+
headers.set("origin", "http://127.0.0.1:6274");
203+
return fetch(url, { ...init, headers });
204+
};
205+
await client.connect(
206+
new SSEClientTransport(new URL(`${base}/sse`), { fetch: withOrigin }),
207+
);
208+
const result = await client.callTool({
209+
name: "echo",
210+
arguments: { message: "from localhost" },
211+
});
212+
expect(result.content).toEqual([
213+
{ type: "text", text: "Echo: from localhost" },
214+
]);
215+
await client.close();
216+
});
217+
218+
describe("a request from a foreign origin", () => {
219+
const FOREIGN = "http://elsewhere.example";
220+
221+
it("is refused at preflight, with no CORS grant", async () => {
222+
const response = await fetch(`${base}/message`, {
223+
method: "OPTIONS",
224+
headers: {
225+
origin: FOREIGN,
226+
"access-control-request-method": "POST",
227+
},
228+
});
229+
expect(response.status).toBe(403);
230+
expect(response.headers.get("access-control-allow-origin")).toBeNull();
231+
});
232+
233+
it("cannot open an SSE stream", async () => {
234+
const response = await fetch(`${base}/sse`, {
235+
headers: { origin: FOREIGN },
236+
signal: AbortSignal.timeout(2000),
237+
});
238+
expect(response.status).toBe(403);
239+
expect(response.headers.get("access-control-allow-origin")).toBeNull();
240+
expect(error).not.toHaveBeenCalledWith(
241+
"Client Connected: ",
242+
expect.anything(),
243+
);
244+
});
245+
246+
it("cannot call a tool on an open session", async () => {
247+
const { client, sessionId } = await connectSse();
248+
const messages = () =>
249+
error.mock.calls.filter(
250+
(c: unknown[]) => c[0] === "Client Message from",
251+
).length;
252+
const before = messages();
253+
const response = await fetch(`${base}/message?sessionId=${sessionId}`, {
254+
method: "POST",
255+
headers: { "content-type": "application/json", origin: FOREIGN },
256+
body: JSON.stringify({
257+
jsonrpc: "2.0",
258+
id: 2,
259+
method: "tools/call",
260+
params: { name: "get-env", arguments: {} },
261+
}),
262+
signal: AbortSignal.timeout(2000),
263+
});
264+
expect(response.status).toBe(403);
265+
expect(await response.json()).toMatchObject({
266+
jsonrpc: "2.0",
267+
error: { code: -32000 },
268+
id: null,
269+
});
270+
// The refused message never reached the session's transport.
271+
expect(messages()).toBe(before);
272+
await client.close();
273+
});
274+
});
189275
});
190276

191277
describe("startSseServer", () => {

‎src/everything/__tests__/streamable-http.test.ts‎

Lines changed: 137 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@
1414
* negotiates that era, including the `Mcp-Param-Region` header the client
1515
* mirrors from `get-header-params`'s `x-mcp-header` argument and the change
1616
* notifications published on the handler's subscription bus.
17+
*
18+
* A browser request is served only from a localhost origin: the tests pin
19+
* that a foreign `Origin` is refused with a 403 and no CORS grant at every
20+
* route, preflights included, and that a localhost one is served.
1721
*/
1822
import type { Server } from "node:http";
1923
import { once } from "node:events";
@@ -404,20 +408,150 @@ describe("Streamable HTTP transport", () => {
404408
);
405409
});
406410

407-
it("answers a CORS preflight for any origin and exposes the MCP headers", async () => {
411+
it("answers a CORS preflight from a localhost origin, echoing that origin, and exposes the MCP headers", async () => {
408412
const response = await fetch(mcp, {
409413
method: "OPTIONS",
410414
headers: {
411-
origin: "http://elsewhere.example",
415+
origin: "http://localhost:6274",
412416
"access-control-request-method": "DELETE",
413417
},
414418
});
415419
expect(response.status).toBe(204);
416-
expect(response.headers.get("access-control-allow-origin")).toBe("*");
420+
expect(response.headers.get("access-control-allow-origin")).toBe(
421+
"http://localhost:6274",
422+
);
417423
expect(response.headers.get("access-control-allow-methods")).toBe(
418424
"GET,POST,DELETE",
419425
);
420426
});
427+
428+
it.each(["legacy", "modern"] as const)(
429+
"serves a %s-era client whose requests carry a localhost Origin",
430+
async (era) => {
431+
// Every request the transport makes carries the Origin a browser page
432+
// served from localhost would send.
433+
const withOrigin = (url: string | URL, init?: RequestInit) => {
434+
const headers = new Headers(init?.headers);
435+
headers.set("origin", "http://[::1]:6274");
436+
return fetch(url, { ...init, headers });
437+
};
438+
const client = new Client(
439+
{ name: "http-origin-test", version: "0.0.0" },
440+
era === "modern"
441+
? { versionNegotiation: { mode: { pin: "2026-07-28" } } }
442+
: {},
443+
);
444+
await client.connect(
445+
new StreamableHTTPClientTransport(new URL(mcp), { fetch: withOrigin }),
446+
);
447+
expect(client.getProtocolEra()).toBe(era);
448+
const result = await client.callTool({
449+
name: "echo",
450+
arguments: { message: "from localhost" },
451+
});
452+
expect(result.content).toEqual([
453+
{ type: "text", text: "Echo: from localhost" },
454+
]);
455+
await client.close();
456+
},
457+
);
458+
459+
describe("a request from a foreign origin", () => {
460+
const FOREIGN = "http://elsewhere.example";
461+
const CALL_GET_ENV = {
462+
jsonrpc: "2.0",
463+
id: 2,
464+
method: "tools/call",
465+
params: { name: "get-env", arguments: {} },
466+
};
467+
468+
/** POST `message` with a foreign Origin, and expect it refused. */
469+
async function expectRefused(message: object, headers = {}) {
470+
const response = await fetch(mcp, {
471+
method: "POST",
472+
headers: { ...JSON_HEADERS, ...headers, origin: FOREIGN },
473+
body: JSON.stringify(message),
474+
});
475+
expect(response.status).toBe(403);
476+
expect(response.headers.get("access-control-allow-origin")).toBeNull();
477+
expect(await response.json()).toMatchObject({
478+
jsonrpc: "2.0",
479+
error: { code: -32000 },
480+
id: null,
481+
});
482+
}
483+
484+
it("is refused at preflight, with no CORS grant", async () => {
485+
const response = await fetch(mcp, {
486+
method: "OPTIONS",
487+
headers: {
488+
origin: FOREIGN,
489+
"access-control-request-method": "POST",
490+
},
491+
});
492+
expect(response.status).toBe(403);
493+
expect(response.headers.get("access-control-allow-origin")).toBeNull();
494+
});
495+
496+
it("cannot start a 2025-era session", async () => {
497+
await expectRefused({
498+
jsonrpc: "2.0",
499+
id: 1,
500+
method: "initialize",
501+
params: {
502+
protocolVersion: "2025-11-25",
503+
capabilities: {},
504+
clientInfo: { name: "raw", version: "0" },
505+
},
506+
});
507+
expect(log).not.toHaveBeenCalledWith(
508+
expect.stringMatching(/^Session initialized/),
509+
);
510+
});
511+
512+
it("cannot call a tool on an open 2025-era session", async () => {
513+
const { sessionId } = await rawInitialize();
514+
await expectRefused(CALL_GET_ENV, {
515+
"mcp-session-id": sessionId,
516+
"mcp-protocol-version": "2025-11-25",
517+
});
518+
});
519+
520+
it("cannot call a tool as a 2026-07-28 client", async () => {
521+
const foreign = (url: string | URL, init?: RequestInit) => {
522+
const headers = new Headers(init?.headers);
523+
headers.set("origin", FOREIGN);
524+
return fetch(url, { ...init, headers });
525+
};
526+
const client = new Client(
527+
{ name: "http-foreign-test", version: "0.0.0" },
528+
{ versionNegotiation: { mode: { pin: "2026-07-28" } } },
529+
);
530+
const attempt = async () => {
531+
await client.connect(
532+
new StreamableHTTPClientTransport(new URL(mcp), { fetch: foreign }),
533+
);
534+
return client.callTool({ name: "get-env", arguments: {} });
535+
};
536+
await expect(attempt()).rejects.toThrow(/403|Invalid Origin/);
537+
await client.close();
538+
});
539+
540+
it.each(["GET", "DELETE"])("cannot %s a session", async (method) => {
541+
const { sessionId } = await rawInitialize();
542+
const response = await fetch(mcp, {
543+
method,
544+
headers: {
545+
accept: "text/event-stream",
546+
"mcp-session-id": sessionId,
547+
"mcp-protocol-version": "2025-11-25",
548+
origin: FOREIGN,
549+
},
550+
signal: AbortSignal.timeout(2000),
551+
});
552+
expect(response.status).toBe(403);
553+
});
554+
});
421555
});
422556

423557
describe("shutdown", () => {

‎src/everything/transports/sse.ts‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,13 @@
1313
// app has its own session map. `startSseServer()` is what the launcher runs.
1414

1515
import { SSEServerTransport } from "@modelcontextprotocol/server-legacy/sse";
16-
import express, { type Express, type Response } from "express";
16+
import { localhostOriginValidation } from "@modelcontextprotocol/node";
17+
import express, {
18+
type Express,
19+
type NextFunction,
20+
type Request,
21+
type Response,
22+
} from "express";
1723
import type { Server } from "node:http";
1824
import { createServer } from "../server/index.js";
1925
import cors from "cors";
@@ -32,15 +38,24 @@ function sendError(res: Response, status: number, message: string): void {
3238
}
3339

3440
/**
35-
* Build the SSE transport's Express app: CORS, `GET /sse` and `POST /message`,
36-
* and the map from session id to transport that they share.
41+
* Build the SSE transport's Express app: Origin validation, CORS, `GET /sse`
42+
* and `POST /message`, and the map from session id to transport that they
43+
* share.
3744
*/
3845
export function createApp(): Express {
39-
// Express app with permissive CORS for testing with Inspector direct connect mode
4046
const app = express();
47+
// A browser page may reach this server only from a localhost origin. The
48+
// SDK's guard answers any other Origin with a 403 before a route or the
49+
// CORS middleware sees it, preflights included; a request with no Origin
50+
// (a non-browser client) passes. CORS then grants the origin that passed,
51+
// so the Inspector's direct connect mode keeps working from localhost.
52+
const allowOrigin = localhostOriginValidation();
53+
app.use((req: Request, res: Response, next: NextFunction) => {
54+
if (allowOrigin(req, res)) next();
55+
});
4156
app.use(
4257
cors({
43-
origin: "*", // use "*" with caution in production
58+
origin: true,
4459
methods: "GET,POST",
4560
preflightContinue: false,
4661
optionsSuccessStatus: 204,

‎src/everything/transports/streamableHttp.ts‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import {
3232
isLegacyRequest,
3333
} from "@modelcontextprotocol/server";
3434
import {
35+
localhostOriginValidation,
3536
NodeStreamableHTTPServerTransport,
3637
toNodeHandler,
3738
toWebRequest,
@@ -132,16 +133,25 @@ export type StreamableHttpApp = {
132133
};
133134

134135
/**
135-
* Build the Streamable HTTP transport's Express app: CORS, the `/mcp` POST,
136-
* GET and DELETE routes, the map from session id to transport that they
137-
* share, the 2026-07-28 handler, and the shutdown handler that closes them.
136+
* Build the Streamable HTTP transport's Express app: Origin validation, CORS,
137+
* the `/mcp` POST, GET and DELETE routes, the map from session id to
138+
* transport that they share, the 2026-07-28 handler, and the shutdown handler
139+
* that closes them.
138140
*/
139141
export function createApp(): StreamableHttpApp {
140-
// Express app with permissive CORS for testing with Inspector direct connect mode
141142
const app = express();
143+
// A browser page may reach this server only from a localhost origin. The
144+
// SDK's guard answers any other Origin with a 403 before a route or the
145+
// CORS middleware sees it, preflights included; a request with no Origin
146+
// (a non-browser client) passes. CORS then grants the origin that passed,
147+
// so the Inspector's direct connect mode keeps working from localhost.
148+
const allowOrigin = localhostOriginValidation();
149+
app.use((req: Request, res: Response, next: NextFunction) => {
150+
if (allowOrigin(req, res)) next();
151+
});
142152
app.use(
143153
cors({
144-
origin: "*", // use "*" with caution in production
154+
origin: true,
145155
methods: "GET,POST,DELETE",
146156
preflightContinue: false,
147157
optionsSuccessStatus: 204,

0 commit comments

Comments
 (0)