Skip to content

Commit feb251d

Browse files
cliffhallclaude
andcommitted
fix(everything): SSE reports a port already in use instead of "Server is running"
Express 5 passes a listen error to the same callback it calls on success, and sse.ts had no error listener, so on EADDRINUSE it printed its success line while bound to nothing. Both HTTP transports now bind through listenOrExit (transports/listen.ts), which prints the listening line only for a real bind and otherwise names the port and exits 1. That also removes the false listening line Streamable HTTP printed ahead of its error. Closes #4923 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 5093574 commit feb251d

8 files changed

Lines changed: 164 additions & 25 deletions

File tree

‎.changeset/sse-port-in-use.md‎

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+
The HTTP+SSE transport no longer prints "Server is running" and stays up when its port is already in use: it reports the port and exits non-zero, as Streamable HTTP does. Streamable HTTP no longer prints its listening line before that error.

‎scripts/smoke-servers.mjs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,8 @@
4040
* 3001, so the smoke does not collide with a server the developer has running.
4141
* That port is not reserved between the probe and the server's own `listen`,
4242
* so a launch whose server reports the port taken is relaunched on a fresh
43-
* one. Streamable HTTP reports it; HTTP+SSE does not yet (#4923: it prints
44-
* "Server is running" either way), so there a lost port is a failed smoke.
43+
* one. Both HTTP transports report it (`listenOrExit` in `everything`'s
44+
* `transports/listen.ts`).
4545
*
4646
* One server failing does not stop the rest: the run reports every target's
4747
* verdict and exits non-zero if any failed, so one run shows the whole picture.
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
// `listenOrExit` is what stops an HTTP transport from reporting a port it does
2+
// not hold (#4923: SSE printed "Server is running" on a port another process
3+
// had, and stayed up listening on nothing). These tests bind real sockets,
4+
// because the defect lived in how Express hands a real listen error to the
5+
// success callback; a mocked `listen` would not have reproduced it.
6+
// `process.exit` is replaced so the failure path can be observed without ending
7+
// the test run, and `console.error` is silenced because that path prints.
8+
9+
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
10+
import { createServer, type Server } from "node:http";
11+
import { once } from "node:events";
12+
import express from "express";
13+
import { listenOrExit } from "../transports/listen.js";
14+
15+
const LISTENING = "listening line";
16+
17+
describe("listenOrExit", () => {
18+
let servers: Server[];
19+
let errorSpy: ReturnType<typeof vi.spyOn>;
20+
let exited: Promise<number | undefined>;
21+
22+
beforeEach(() => {
23+
servers = [];
24+
errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
25+
exited = new Promise((resolve) => {
26+
vi.spyOn(process, "exit").mockImplementation((code) => {
27+
resolve(typeof code === "number" ? code : undefined);
28+
return undefined as never;
29+
});
30+
});
31+
});
32+
33+
afterEach(async () => {
34+
vi.restoreAllMocks();
35+
await Promise.all(
36+
servers
37+
.filter((server) => server.listening)
38+
.map(
39+
(server) =>
40+
new Promise<void>((resolve) => server.close(() => resolve())),
41+
),
42+
);
43+
});
44+
45+
/** A server holding a port, and the port it holds. */
46+
async function holdPort(): Promise<number> {
47+
const holder = createServer();
48+
servers.push(holder);
49+
// No host, as the transports bind: a holder on 127.0.0.1 alone would not
50+
// conflict with their wildcard bind on every platform.
51+
holder.listen(0);
52+
await once(holder, "listening");
53+
const address = holder.address();
54+
if (address === null || typeof address === "string") {
55+
throw new Error("expected a TCP address");
56+
}
57+
return address.port;
58+
}
59+
60+
it("prints the listening line once the port is bound, and does not exit", async () => {
61+
const server = listenOrExit(express(), 0, LISTENING);
62+
servers.push(server);
63+
await once(server, "listening");
64+
65+
expect(server.listening).toBe(true);
66+
expect(errorSpy).toHaveBeenCalledWith(LISTENING);
67+
expect(process.exit).not.toHaveBeenCalled();
68+
});
69+
70+
it("reports a port already in use and exits 1 without claiming to listen", async () => {
71+
const port = await holdPort();
72+
const server = listenOrExit(express(), port, LISTENING);
73+
servers.push(server);
74+
75+
expect(await exited).toBe(1);
76+
expect(server.listening).toBe(false);
77+
expect(errorSpy).toHaveBeenCalledWith(
78+
`Failed to start: Port ${port} is already in use. Set PORT to a free port or stop the conflicting process.`,
79+
);
80+
expect(errorSpy).not.toHaveBeenCalledWith(LISTENING);
81+
});
82+
83+
it("reports any other server error and exits 1", async () => {
84+
const server = listenOrExit(express(), 0, LISTENING);
85+
servers.push(server);
86+
await once(server, "listening");
87+
88+
const failure = Object.assign(new Error("permission denied"), {
89+
code: "EACCES",
90+
});
91+
server.emit("error", failure);
92+
93+
expect(await exited).toBe(1);
94+
expect(errorSpy).toHaveBeenCalledWith(
95+
"HTTP server encountered an error while starting:",
96+
failure,
97+
);
98+
});
99+
});

‎src/everything/docs/startup.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@
4343
- **DELETE** (termination)
4444
- Uses an event store for resumability and stores transports by `sessionId`.
4545
- Calls `cleanup(sessionId)` on **DELETE**.
46+
- **SSE** and **Streamable HTTP** bind their port (`PORT`, default `3001`) through `listenOrExit()` in `transports/listen.ts`.
47+
- The listening line is printed only once the port is bound.
48+
- A bind failure, such as a port already in use, is reported on stderr and the process exits non-zero.
4649

4750
## 3. The Server Factory
4851

‎src/everything/docs/structure.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ src/everything
5858
│ ├── trigger-sampling-request-async.ts
5959
│ └── trigger-url-elicitation.ts
6060
└── transports
61+
├── listen.ts
6162
├── sse.ts
6263
├── stdio.ts
6364
└── streamableHttp.ts
@@ -188,6 +189,9 @@ src/everything
188189

189190
### `transports/`
190191

192+
- `listen.ts`
193+
- `listenOrExit(app, port, listeningMessage)`: binds an Express app to its port for both HTTP transports.
194+
- Prints the listening message only once the port is bound; on a bind failure (such as a port already in use) prints why and exits non-zero.
191195
- `stdio.ts`
192196
- Starts a `StdioServerTransport`, created the server via `createServer()`, and connects it.
193197
- Handles `SIGINT` to close cleanly and calls `cleanup()` to remove any live intervals.
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Binds an HTTP transport's Express app to its port, and is the one place that
2+
// decides whether that worked (#4923).
3+
//
4+
// Express 5 passes a listen error to the same callback it calls on success, so
5+
// a callback that ignores its argument prints "running" for a server bound to
6+
// nothing, and with no `error` listener the process then stays up on no port.
7+
// Both HTTP transports start through here so neither can report a port it
8+
// does not hold: the listening line is printed only for a real bind, and a
9+
// failed one names the port and exits non-zero, which is what lets a launcher
10+
// (the boot smoke, `npm`) see the failure and retry or report it.
11+
12+
import type { Server } from "node:http";
13+
import type { Express } from "express";
14+
15+
/**
16+
* Start `app` on `port`. Prints `listeningMessage` once the port is bound; on a
17+
* bind failure prints why and exits the process with status 1.
18+
*/
19+
export function listenOrExit(
20+
app: Express,
21+
port: string | number,
22+
listeningMessage: string,
23+
): Server {
24+
const server = app.listen(port, (error?: Error) => {
25+
// A failed bind arrives here too; the `error` listener below reports it.
26+
if (error) return;
27+
console.error(listeningMessage);
28+
});
29+
30+
server.on("error", (err: unknown) => {
31+
const code =
32+
typeof err === "object" && err !== null && "code" in err
33+
? (err as { code?: unknown }).code
34+
: undefined;
35+
if (code === "EADDRINUSE") {
36+
console.error(
37+
`Failed to start: Port ${port} is already in use. Set PORT to a free port or stop the conflicting process.`,
38+
);
39+
} else {
40+
console.error("HTTP server encountered an error while starting:", err);
41+
}
42+
// Ensure a non-zero exit so npm reports the failure instead of silently exiting
43+
process.exit(1);
44+
});
45+
46+
return server;
47+
}

‎src/everything/transports/sse.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
22
import express from "express";
33
import { createServer } from "../server/index.js";
44
import cors from "cors";
5+
import { listenOrExit } from "./listen.js";
56

67
console.error("Starting SSE server...");
78

@@ -72,6 +73,4 @@ app.post("/message", async (req, res) => {
7273

7374
// Start the express server
7475
const PORT = process.env.PORT || 3001;
75-
app.listen(PORT, () => {
76-
console.error(`Server is running on port ${PORT}`);
77-
});
76+
listenOrExit(app, PORT, `Server is running on port ${PORT}`);

‎src/everything/transports/streamableHttp.ts‎

Lines changed: 2 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import express, { Request, Response } from "express";
66
import { createServer } from "../server/index.js";
77
import { randomUUID } from "node:crypto";
88
import cors from "cors";
9+
import { listenOrExit } from "./listen.js";
910

1011
// Simple in-memory event store for SSE resumability
1112
class InMemoryEventStore implements EventStore {
@@ -199,26 +200,7 @@ app.delete("/mcp", async (req: Request, res: Response) => {
199200

200201
// Start the server
201202
const PORT = process.env.PORT || 3001;
202-
const server = app.listen(PORT, () => {
203-
console.error(`MCP Streamable HTTP Server listening on port ${PORT}`);
204-
});
205-
206-
// Handle server errors
207-
server.on("error", (err: unknown) => {
208-
const code =
209-
typeof err === "object" && err !== null && "code" in err
210-
? (err as { code?: unknown }).code
211-
: undefined;
212-
if (code === "EADDRINUSE") {
213-
console.error(
214-
`Failed to start: Port ${PORT} is already in use. Set PORT to a free port or stop the conflicting process.`,
215-
);
216-
} else {
217-
console.error("HTTP server encountered an error while starting:", err);
218-
}
219-
// Ensure a non-zero exit so npm reports the failure instead of silently exiting
220-
process.exit(1);
221-
});
203+
listenOrExit(app, PORT, `MCP Streamable HTTP Server listening on port ${PORT}`);
222204

223205
// Handle server shutdown
224206
process.on("SIGINT", async () => {

0 commit comments

Comments
 (0)