Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix: bound persistent MCP SSE messages instead of connection lifetime

Afloat31b398fa6078
diff --git a/server/mcp-http.test.ts b/server/mcp-http.test.ts
index e489bd8835..07ec46c004 100644
--- a/server/mcp-http.test.ts
+++ b/server/mcp-http.test.ts
@@ -11,6 +11,16 @@ afterEach(async () => {
});
describe("a server's own requests to the client", () => {
+ it("does not charge earlier SSE replies against a later request's byte limit", async () => {
+ fake = await startFakeHttpMcp({ transport: "sse", tools: [{ name: "still_available" }] });
+ client = new RemoteMcpClient({ type: "sse", url: fake.url, headers: {} }, { maxBytes: 512 });
+ await client.initialize("fixture", AbortSignal.timeout(5_000));
+ for (let i = 0; i < 20; i++) {
+ await expect(client.request("tools/list", {}, AbortSignal.timeout(1_000))).resolves.toEqual({ tools: [{ name: "still_available" }] });
+ }
+ expect(fake.toolsLists).toBe(20);
+ });
+
it("keeps the shared SSE stream alive after the opening request's signal expires", async () => {
fake = await startFakeHttpMcp({ transport: "sse", tools: [{ name: "still_available" }] });
let streamSignal: AbortSignal | null | undefined;
diff --git a/server/mcp-http.ts b/server/mcp-http.ts
index 93862dd36c..90dd0bb122 100644
--- a/server/mcp-http.ts
+++ b/server/mcp-http.ts
@@ -121,8 +121,12 @@ async function readSse(
signal: AbortSignal,
onEvent: (event: SseEvent) => "stop" | undefined,
maxBytes = MAX_REMOTE_MCP_BYTES,
- /** One POST's reply: a stateless server may hang up right after its last event, leaving off the closing blank line. */
- lastEventAtEnd = false,
+ options: {
+ /** One POST's reply may end without a closing blank line. */
+ lastEventAtEnd?: boolean;
+ /** Bound each normalized UTF-8 event, including its blank line, on a shared connection. */
+ perEventLimit?: boolean;
+ } = {},
): Promise<void> {
const reader = response.body?.getReader();
if (!reader) throw new McpHttpError("protocol", "empty event stream");
@@ -136,27 +140,37 @@ async function readSse(
for (;;) {
const { value, done } = await reader.read();
if (done) {
- const last = lastEventAtEnd ? parseSseBlock(buffer + decoder.decode()) : null;
+ const last = options.lastEventAtEnd ? parseSseBlock(buffer + decoder.decode()) : null;
if (last) onEvent(last);
return;
}
- bytes += value.byteLength;
- if (bytes > maxBytes) throw new McpHttpError("protocol", "event stream too large");
+ if (!options.perEventLimit) {
+ bytes += value.byteLength;
+ if (bytes > maxBytes) throw new McpHttpError("protocol", "event stream too large");
+ }
const chunk = decoder.decode(value, { stream: true });
if (chunk) {
const start = afterCr && chunk.startsWith("\n") ? 1 : 0;
afterCr = chunk.endsWith("\r");
- buffer += chunk.slice(start).replace(/\r\n?/g, "\n");
+ const normalized = chunk.slice(start).replace(/\r\n?/g, "\n");
+ buffer += normalized;
+ if (options.perEventLimit) bytes += Buffer.byteLength(normalized);
}
let separator: number;
while ((separator = buffer.indexOf("\n\n")) !== -1) {
const block = buffer.slice(0, separator);
buffer = buffer.slice(separator + 2);
+ if (options.perEventLimit) {
+ const eventBytes = Buffer.byteLength(block) + 2;
+ if (eventBytes > maxBytes) throw new McpHttpError("protocol", "event stream too large");
+ bytes -= eventBytes;
+ }
const event = parseSseBlock(block);
if (event && onEvent(event) === "stop") {
return;
}
}
+ if (options.perEventLimit && bytes > maxBytes) throw new McpHttpError("protocol", "event stream too large");
}
} finally {
signal.removeEventListener("abort", onAbort);
@@ -324,7 +338,7 @@ export class RemoteMcpClient {
if (!message) return undefined;
found = message;
return "stop";
- }, this.maxBytes, true);
+ }, this.maxBytes, { lastEventAtEnd: true });
if (signal.aborted) throw new McpHttpError("network", "aborted");
if (!found) throw new McpHttpError("protocol", "event stream ended without the response");
return unwrap(found);
@@ -387,7 +401,7 @@ export class RemoteMcpClient {
}
}
return undefined;
- }, this.maxBytes);
+ }, this.maxBytes, { perEventLimit: true });
fail(new McpHttpError("network", "event stream ended"));
})
.catch((error: unknown) => {
diff --git a/server/mcp-sse-budget.test.ts b/server/mcp-sse-budget.test.ts
new file mode 100644
index 0000000000..28518be1f6
--- /dev/null
+++ b/server/mcp-sse-budget.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from "vitest";
+
+import { RemoteMcpClient } from "./mcp-http.ts";
+
+const encode = (text: string) => new TextEncoder().encode(text);
+const event = (value: unknown) => `data: ${JSON.stringify(value)}\n\n`;
+const reply = (id: number) => event({ jsonrpc: "2.0", id, result: { tools: [] } });
+
+function legacy(chunks: (id: number) => string[], maxBytes: number, onNotification?: () => void) {
+ let stream!: ReadableStreamDefaultController<Uint8Array>;
+ let cancelled = false;
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) { stream = controller; stream.enqueue(encode("event: endpoint\ndata: /messages\n\n")); },
+ cancel() { cancelled = true; },
+ });
+ const client = new RemoteMcpClient({ type: "sse", url: "https://fixture.example/sse", headers: {} }, {
+ maxBytes, onNotification,
+ fetch: async (_url, init) => {
+ if (init?.method === "GET") return new Response(body, { headers: { "content-type": "text/event-stream" } });
+ const frame = JSON.parse(String(init?.body)) as { id?: number };
+ if (frame.id !== undefined) for (const chunk of chunks(frame.id)) stream.enqueue(encode(chunk));
+ return new Response(null, { status: 202 });
+ },
+ });
+ return { client, body, get cancelled() { return cancelled; } };
+}
+
+describe("a persistent MCP SSE connection's byte budget", () => {
+ it.each(["\n", "\r\n", "\r"])("allows many small events in one chunk with %j line endings", async (newline) => {
+ let notifications = 0;
+ const batch = Array.from({ length: 20 }, (_, i) => event({ jsonrpc: "2.0", method: "notifications/progress", params: { progress: i } })).join("");
+ const fixture = legacy((id) => [(batch + reply(id)).replaceAll("\n", newline)], 128, () => { notifications++; });
+ try {
+ await expect(fixture.client.request("tools/list", {}, AbortSignal.timeout(1_000))).resolves.toEqual({ tools: [] });
+ expect(notifications).toBe(20);
+ } finally { await fixture.client.close(); }
+ });
+
+ it.each([
+ { name: "complete oversized event", chunks: () => [":".repeat(129) + "\n\n"] },
+ { name: "split unterminated event", chunks: () => [":".repeat(70), ":".repeat(70)] },
+ { name: "UTF-8 bytes exceeding the character count", chunks: (id: number) => [event({ jsonrpc: "2.0", id, result: "界".repeat(40) })] },
+ ])("still rejects and releases a $name", async ({ chunks }) => {
+ const fixture = legacy(chunks, 128);
+ try {
+ await expect(fixture.client.request("tools/list", {}, AbortSignal.timeout(1_000))).rejects.toThrow("event stream too large");
+ expect(fixture.cancelled).toBe(true);
+ expect(fixture.body.locked).toBe(false);
+ } finally { await fixture.client.close(); }
+ });
+
+ it("accepts an event exactly at its byte limit and rejects one byte more", async () => {
+ for (const extra of [0, 1]) {
+ const fixture = legacy((id) => [reply(id)], encode(reply(1)).byteLength - extra);
+ try {
+ const pending = fixture.client.request("tools/list", {}, AbortSignal.timeout(1_000));
+ if (extra) await expect(pending).rejects.toThrow("event stream too large");
+ else await expect(pending).resolves.toEqual({ tools: [] });
+ } finally { await fixture.client.close(); }
+ }
+ });
+
+ it("keeps the aggregate byte limit for one streamable HTTP response", async () => {
+ const notification = event({ jsonrpc: "2.0", method: "notifications/progress", params: { progress: 1 } });
+ const client = new RemoteMcpClient({ type: "http", url: "https://fixture.example/mcp", headers: {} }, {
+ maxBytes: 128,
+ fetch: async () => new Response(notification.repeat(20) + reply(1), { headers: { "content-type": "text/event-stream" } }),
+ });
+ try {
+ await expect(client.request("tools/list", {}, AbortSignal.timeout(1_000))).rejects.toThrow("event stream too large");
+ } finally { await client.close(); }
+ });
+});