Skip to content

Commit ba10d05

Browse files
committed
fix(mcp): stop subscriptions/listen streams holding functions open
Vercel logs show 2026-07-28 clients (claude-code 2.1.30x) opening a subscriptions/listen stream that runs until the 300s maxDuration kill, then reconnecting: 40-64% of /api/mcp invocations ended that way. mcp-use advertises listChanged: true unconditionally, the TypeScript client auto-opens listen when it sees that flag, and the SDK keeps the SSE stream alive with keep-alives. The in-process event bus cannot reach other instances and the catalog is static, so those streams never delivered a notification. Follow the Python SDK's opt-out (modelcontextprotocol/python-sdk#3626) in the route's POST wrapper: - server/discover reports listChanged and subscribe as false, so the client skips auto-opening a listen stream. - A subscriptions/listen that still arrives is answered at once with JSON-RPC -32601 over HTTP 404, which the client reports and moves past. Every other request passes through unchanged. Tracked upstream in modelcontextprotocol/typescript-sdk#2873. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01M83Ub5YoyGHcFYWpB8nscP
1 parent 76e7059 commit ba10d05

4 files changed

Lines changed: 316 additions & 3 deletions

File tree

‎src/app/api/mcp/[[...path]]/embedded.test.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,3 +257,66 @@ describe("embedded /api/mcp views", () => {
257257
// ~15 RPCs + asset GETs; generous budget for full-suite contention.
258258
}, 120_000);
259259
});
260+
261+
// Wire contract with the real mcp-use server behind the route wrapper (see
262+
// src/mcp/subscriptions.ts): a 2026-07-28 client reads the change flags from
263+
// server/discover to decide whether to open a listen stream, and a listen
264+
// that still arrives must not hold the function open.
265+
describe("embedded /api/mcp subscriptions opt-out", () => {
266+
const modern = (method: string, id: string, params: object = {}) =>
267+
new Request("http://localhost/api/mcp", {
268+
method: "POST",
269+
headers: {
270+
"content-type": "application/json",
271+
accept: "application/json, text/event-stream",
272+
"mcp-method": method,
273+
"mcp-protocol-version": "2026-07-28",
274+
},
275+
body: JSON.stringify({
276+
jsonrpc: "2.0",
277+
id,
278+
method,
279+
params: {
280+
_meta: {
281+
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
282+
"io.modelcontextprotocol/clientInfo": { name: "t", version: "1" },
283+
"io.modelcontextprotocol/clientCapabilities": {},
284+
},
285+
...params,
286+
},
287+
}),
288+
});
289+
290+
it("server/discover advertises no change notifications", async () => {
291+
vi.stubEnv("MCP_DEV_BYPASS", "true");
292+
const route = await import("./route");
293+
const res = await route.POST(modern("server/discover", "d1"));
294+
expect(res.status).toBe(200);
295+
const payload = parseRpcBody(await res.text()) as {
296+
result?: { capabilities?: Record<string, Record<string, boolean>> };
297+
};
298+
const caps = payload.result?.capabilities;
299+
expect(caps?.tools?.listChanged).toBe(false);
300+
expect(caps?.prompts?.listChanged).toBe(false);
301+
expect(caps?.resources?.listChanged).toBe(false);
302+
expect(caps?.resources?.subscribe).toBe(false);
303+
vi.unstubAllEnvs();
304+
});
305+
306+
it("subscriptions/listen is declined at once instead of streaming", async () => {
307+
vi.stubEnv("MCP_DEV_BYPASS", "true");
308+
const route = await import("./route");
309+
const res = await route.POST(
310+
modern("subscriptions/listen", "listen:0", {
311+
notifications: { toolsListChanged: true },
312+
}),
313+
);
314+
expect(res.status).toBe(404);
315+
expect(res.headers.get("content-type")).not.toContain("text/event-stream");
316+
expect(await res.json()).toMatchObject({
317+
id: "listen:0",
318+
error: { code: -32601 },
319+
});
320+
vi.unstubAllEnvs();
321+
});
322+
});

‎src/app/api/mcp/[[...path]]/route.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { createNextHandler } from "mcp-use/next";
22

33
import { buildRouteServer } from "@/mcp/route-server";
4+
import { declineSubscriptions } from "@/mcp/subscriptions";
45

56
export const runtime = "nodejs";
67
// 12-round tool chains need the Vercel Pro ceiling (same pin as
@@ -12,6 +13,19 @@ export const maxDuration = 300;
1213
// passes through untouched. The unbound-method disable is a false positive:
1314
// createNextHandler returns closures over `handle`, not prototype methods
1415
// needing `this` (see node_modules/mcp-use/dist/next/index.js).
15-
// eslint-disable-next-line @typescript-eslint/unbound-method -- handlers are this-independent closures, not methods
16-
export const { GET, POST, DELETE, OPTIONS } =
17-
createNextHandler(buildRouteServer());
16+
/* eslint-disable @typescript-eslint/unbound-method -- handlers are this-independent closures, not methods */
17+
const {
18+
GET,
19+
POST: mcpPost,
20+
DELETE,
21+
OPTIONS,
22+
} = createNextHandler(buildRouteServer());
23+
/* eslint-enable @typescript-eslint/unbound-method */
24+
25+
// POST declines `subscriptions/listen` and hides the change-notification
26+
// flags from `server/discover`: a listen stream otherwise holds the function
27+
// until the maxDuration kill (see src/mcp/subscriptions.ts). The wrapper
28+
// forwards every other argument, so the handler contract is unchanged.
29+
const POST = declineSubscriptions(mcpPost);
30+
31+
export { GET, POST, DELETE, OPTIONS };

‎src/mcp/subscriptions.test.ts‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
3+
import { declineSubscriptions } from "./subscriptions";
4+
5+
const rpc = (method: string, id: unknown = 1, headers?: HeadersInit) =>
6+
new Request("http://localhost/api/mcp", {
7+
method: "POST",
8+
headers: { "content-type": "application/json", ...headers },
9+
body: JSON.stringify({ jsonrpc: "2.0", id, method, params: {} }),
10+
});
11+
12+
const capabilities = {
13+
logging: {},
14+
tools: { listChanged: true },
15+
prompts: { listChanged: true },
16+
resources: { listChanged: true, subscribe: true },
17+
};
18+
19+
const discoverResult = (id: unknown) => ({
20+
jsonrpc: "2.0",
21+
id,
22+
result: { supportedVersions: ["2026-07-28"], capabilities },
23+
});
24+
25+
const offCapabilities = {
26+
logging: {},
27+
tools: { listChanged: false },
28+
prompts: { listChanged: false },
29+
resources: { listChanged: false, subscribe: false },
30+
};
31+
32+
describe("declineSubscriptions", () => {
33+
it("answers subscriptions/listen with -32601 over 404 without opening a stream", async () => {
34+
const post = vi.fn();
35+
const res = await declineSubscriptions(post)(
36+
rpc("subscriptions/listen", "listen:0"),
37+
);
38+
expect(post).not.toHaveBeenCalled();
39+
expect(res.status).toBe(404);
40+
expect(res.headers.get("content-type")).toContain("application/json");
41+
expect(await res.json()).toEqual({
42+
jsonrpc: "2.0",
43+
id: "listen:0",
44+
error: {
45+
code: -32601,
46+
message: "Method not found: subscriptions/listen",
47+
},
48+
});
49+
});
50+
51+
it("recognises listen from the Mcp-Method header", async () => {
52+
const post = vi.fn();
53+
const res = await declineSubscriptions(post)(
54+
new Request("http://localhost/api/mcp", {
55+
method: "POST",
56+
headers: { "mcp-method": "subscriptions/listen" },
57+
body: "not json",
58+
}),
59+
);
60+
expect(post).not.toHaveBeenCalled();
61+
expect(res.status).toBe(404);
62+
});
63+
64+
it("turns the change-notification flags off in a JSON discover result", async () => {
65+
const post = vi.fn(async () => Response.json(discoverResult(7)));
66+
const res = await declineSubscriptions(post)(rpc("server/discover", 7));
67+
expect(res.status).toBe(200);
68+
const body = (await res.json()) as {
69+
result: { capabilities: unknown; supportedVersions: string[] };
70+
};
71+
expect(body.result.capabilities).toEqual(offCapabilities);
72+
expect(body.result.supportedVersions).toEqual(["2026-07-28"]);
73+
});
74+
75+
it("turns the flags off in an SSE discover result", async () => {
76+
const post = vi.fn(
77+
async () =>
78+
new Response(
79+
`event: message\ndata: ${JSON.stringify(discoverResult(8))}\n\n`,
80+
{ headers: { "content-type": "text/event-stream" } },
81+
),
82+
);
83+
const res = await declineSubscriptions(post)(rpc("server/discover", 8));
84+
const text = await res.text();
85+
expect(text.startsWith("event: message\ndata: ")).toBe(true);
86+
const frame = text.split("\n").find((line) => line.startsWith("data:"));
87+
const body = JSON.parse(frame!.slice("data:".length)) as {
88+
result: { capabilities: unknown };
89+
};
90+
expect(body.result.capabilities).toEqual(offCapabilities);
91+
});
92+
93+
it("passes every other method through untouched, with its arguments", async () => {
94+
const response = new Response("ok");
95+
const post = vi.fn(async (_request: Request, _context: { n: number }) =>
96+
Promise.resolve(response),
97+
);
98+
const request = rpc("tools/call");
99+
const context = { n: 1 };
100+
const res = await declineSubscriptions(post)(request, context);
101+
expect(res).toBe(response);
102+
expect(post).toHaveBeenCalledWith(request, context);
103+
// The wrapper reads a clone, so the handler can still read the body.
104+
expect(await request.json()).toMatchObject({ method: "tools/call" });
105+
});
106+
107+
it("leaves a failed discover response as it is", async () => {
108+
const response = new Response("nope", { status: 401 });
109+
const post = vi.fn(async () => response);
110+
const res = await declineSubscriptions(post)(rpc("server/discover"));
111+
expect(res).toBe(response);
112+
});
113+
});

‎src/mcp/subscriptions.ts‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
/**
2+
* Opt the embedded /api/mcp route out of `subscriptions/listen` (protocol
3+
* revision 2026-07-28), the way the Python SDK's `subscriptions=False` does
4+
* (modelcontextprotocol/python-sdk#3626):
5+
*
6+
* - `server/discover` reports `listChanged: false` (and `subscribe: false`),
7+
* so the TypeScript client's `listChanged` option skips auto-opening a
8+
* listen stream.
9+
* - A `subscriptions/listen` that still arrives is answered at once with
10+
* JSON-RPC -32601 over HTTP 404 instead of opening a stream.
11+
*
12+
* Why: mcp-use hard-codes `listChanged: true`, and the SDK serves listen as
13+
* an SSE stream with 15s keep-alives that only ends when the client leaves.
14+
* On Vercel each stream held a function until the 300s maxDuration kill
15+
* (40-64% of /api/mcp invocations), and the client then reconnected. The
16+
* in-process event bus cannot reach other instances, and the catalog is
17+
* static, so no change notification was ever delivered on those streams.
18+
* See modelcontextprotocol/typescript-sdk#2873.
19+
*/
20+
21+
const LISTEN_METHOD = "subscriptions/listen";
22+
const DISCOVER_METHOD = "server/discover";
23+
const METHOD_NOT_FOUND = -32601;
24+
25+
type JsonRpcRequest = { id?: unknown; method?: unknown };
26+
27+
/** Reads the JSON-RPC method: the `Mcp-Method` header first, else the body. */
28+
async function readRequest(request: Request): Promise<JsonRpcRequest | null> {
29+
const headerMethod = request.headers.get("mcp-method");
30+
try {
31+
const body = (await request.clone().json()) as unknown;
32+
if (body && typeof body === "object" && !Array.isArray(body)) {
33+
const message = body as JsonRpcRequest;
34+
return { id: message.id, method: headerMethod ?? message.method };
35+
}
36+
} catch {
37+
// Not a JSON body: fall through to the header alone.
38+
}
39+
return headerMethod ? { id: null, method: headerMethod } : null;
40+
}
41+
42+
type Capabilities = {
43+
tools?: { listChanged?: boolean };
44+
prompts?: { listChanged?: boolean };
45+
resources?: { listChanged?: boolean; subscribe?: boolean };
46+
};
47+
48+
/** Flips the change-notification flags off in one JSON-RPC message. */
49+
function withoutChangeNotifications(message: unknown): unknown {
50+
const capabilities = (
51+
message as { result?: { capabilities?: Capabilities } } | null
52+
)?.result?.capabilities;
53+
if (!capabilities) return message;
54+
if (capabilities.tools) capabilities.tools.listChanged = false;
55+
if (capabilities.prompts) capabilities.prompts.listChanged = false;
56+
if (capabilities.resources) {
57+
capabilities.resources.listChanged = false;
58+
capabilities.resources.subscribe = false;
59+
}
60+
return message;
61+
}
62+
63+
/** Rewrites a discover response, as plain JSON or as SSE `data:` frames. */
64+
async function rewriteDiscover(response: Response): Promise<Response> {
65+
const text = await response.text();
66+
const isSse = (response.headers.get("content-type") ?? "").includes(
67+
"text/event-stream",
68+
);
69+
const rewrite = (raw: string) =>
70+
JSON.stringify(withoutChangeNotifications(JSON.parse(raw)));
71+
72+
let body = text;
73+
try {
74+
body = isSse
75+
? text
76+
.split("\n")
77+
.map((line) =>
78+
line.startsWith("data:")
79+
? `data: ${rewrite(line.slice("data:".length).trim())}`
80+
: line,
81+
)
82+
.join("\n")
83+
: rewrite(text);
84+
} catch {
85+
// Unparseable (e.g. an error page): pass the original body through.
86+
}
87+
88+
const headers = new Headers(response.headers);
89+
headers.delete("content-length");
90+
return new Response(body, {
91+
status: response.status,
92+
statusText: response.statusText,
93+
headers,
94+
});
95+
}
96+
97+
/** Wraps the route's POST handler with the subscriptions opt-out. */
98+
export function declineSubscriptions<Rest extends unknown[]>(
99+
post: (request: Request, ...rest: Rest) => Promise<Response>,
100+
) {
101+
return async (request: Request, ...rest: Rest): Promise<Response> => {
102+
const message = await readRequest(request);
103+
104+
if (message?.method === LISTEN_METHOD) {
105+
return Response.json(
106+
{
107+
jsonrpc: "2.0",
108+
id: message.id ?? null,
109+
error: {
110+
code: METHOD_NOT_FOUND,
111+
message: `Method not found: ${LISTEN_METHOD}`,
112+
},
113+
},
114+
{ status: 404 },
115+
);
116+
}
117+
118+
const response = await post(request, ...rest);
119+
return message?.method === DISCOVER_METHOD && response.ok
120+
? rewriteDiscover(response)
121+
: response;
122+
};
123+
}

0 commit comments

Comments
 (0)