Skip to content

Commit 5e75538

Browse files
committed
fix(mcp): bound body-less MCP HTTP text responses at 1 MiB
1 parent 381b44a commit 5e75538

2 files changed

Lines changed: 139 additions & 2 deletions

File tree

‎src/agents/mcp-http-fetch.test.ts‎

Lines changed: 121 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -213,16 +213,20 @@ describe("MCP HTTP fetch helpers", () => {
213213
});
214214

215215
it("returns fetch responses compatible with MCP SDK OAuth error parsing", async () => {
216+
const body = '{"error":"invalid_client_metadata","error_description":"bad redirect"}';
216217
class ForeignResponse {
217218
status = 400;
218219
statusText = "Bad Request";
219-
headers = new Headers({ "content-type": "application/json" });
220+
headers = new Headers({
221+
"content-length": String(Buffer.byteLength(body, "utf8")),
222+
"content-type": "application/json",
223+
});
220224
body = null;
221225
get ok() {
222226
return false;
223227
}
224228
async text() {
225-
return '{"error":"invalid_client_metadata","error_description":"bad redirect"}';
229+
return body;
226230
}
227231
}
228232

@@ -245,4 +249,119 @@ describe("MCP HTTP fetch helpers", () => {
245249
expect(error.message).toContain("bad redirect");
246250
expect(error.message).not.toContain("[object Response]");
247251
});
252+
253+
it("drops body-less text when Content-Length exceeds the 1 MiB cap", async () => {
254+
const text = vi.fn(async () => "x".repeat(1024 * 1024 + 1));
255+
class OversizedResponse {
256+
status = 400;
257+
statusText = "Bad Request";
258+
headers = new Headers({
259+
"content-length": String(1024 * 1024 + 1),
260+
"content-type": "application/json",
261+
});
262+
body = null;
263+
get ok() {
264+
return false;
265+
}
266+
text = text;
267+
}
268+
testGlobal[TEST_UNDICI_RUNTIME_DEPS_KEY] = {
269+
Agent: TestAgent,
270+
EnvHttpProxyAgent: TestEnvHttpProxyAgent,
271+
ProxyAgent: TestProxyAgent,
272+
fetch: async () => new OversizedResponse() as unknown as Response,
273+
};
274+
const fetch = buildMcpHttpFetch({ resourceUrl: "https://mcp.example.com/mcp" });
275+
276+
const response = await fetch("https://mcp.example.com/mcp");
277+
expect(response).toBeInstanceOf(Response);
278+
expect(response.body).toBeNull();
279+
expect(text).not.toHaveBeenCalled();
280+
});
281+
282+
it("drops body-less text when Content-Length is missing", async () => {
283+
const text = vi.fn(async () => '{"error":"too large"}');
284+
class NoLengthResponse {
285+
status = 400;
286+
statusText = "Bad Request";
287+
headers = new Headers({ "content-type": "application/json" });
288+
body = null;
289+
get ok() {
290+
return false;
291+
}
292+
text = text;
293+
}
294+
testGlobal[TEST_UNDICI_RUNTIME_DEPS_KEY] = {
295+
Agent: TestAgent,
296+
EnvHttpProxyAgent: TestEnvHttpProxyAgent,
297+
ProxyAgent: TestProxyAgent,
298+
fetch: async () => new NoLengthResponse() as unknown as Response,
299+
};
300+
const fetch = buildMcpHttpFetch({ resourceUrl: "https://mcp.example.com/mcp" });
301+
302+
const response = await fetch("https://mcp.example.com/mcp");
303+
expect(response).toBeInstanceOf(Response);
304+
expect(response.body).toBeNull();
305+
expect(text).not.toHaveBeenCalled();
306+
});
307+
308+
it.each(["abc", "1e3", "0x40"])(
309+
"drops body-less text when Content-Length is malformed (%s)",
310+
async (contentLength) => {
311+
const text = vi.fn(async () => '{"error":"too large"}');
312+
class MalformedLengthResponse {
313+
status = 400;
314+
statusText = "Bad Request";
315+
headers = new Headers({
316+
"content-length": contentLength,
317+
"content-type": "application/json",
318+
});
319+
body = null;
320+
get ok() {
321+
return false;
322+
}
323+
text = text;
324+
}
325+
testGlobal[TEST_UNDICI_RUNTIME_DEPS_KEY] = {
326+
Agent: TestAgent,
327+
EnvHttpProxyAgent: TestEnvHttpProxyAgent,
328+
ProxyAgent: TestProxyAgent,
329+
fetch: async () => new MalformedLengthResponse() as unknown as Response,
330+
};
331+
const fetch = buildMcpHttpFetch({ resourceUrl: "https://mcp.example.com/mcp" });
332+
333+
const response = await fetch("https://mcp.example.com/mcp");
334+
expect(response).toBeInstanceOf(Response);
335+
expect(response.body).toBeNull();
336+
expect(text).not.toHaveBeenCalled();
337+
},
338+
);
339+
340+
it("accepts body-less responses with valid Content-Length within the 1 MiB cap", async () => {
341+
const body = JSON.stringify({ ok: true });
342+
class WithinLimitResponse {
343+
status = 200;
344+
statusText = "OK";
345+
headers = new Headers({
346+
"content-length": String(Buffer.byteLength(body, "utf8")),
347+
"content-type": "application/json",
348+
});
349+
body = null;
350+
async text() {
351+
return body;
352+
}
353+
}
354+
testGlobal[TEST_UNDICI_RUNTIME_DEPS_KEY] = {
355+
Agent: TestAgent,
356+
EnvHttpProxyAgent: TestEnvHttpProxyAgent,
357+
ProxyAgent: TestProxyAgent,
358+
fetch: async () => new WithinLimitResponse() as unknown as Response,
359+
};
360+
const fetch = buildMcpHttpFetch({ resourceUrl: "https://mcp.example.com/mcp" });
361+
362+
const response = await fetch("https://mcp.example.com/mcp");
363+
expect(response.status).toBe(200);
364+
const text = await response.text();
365+
expect(text).toBe('{"ok":true}');
366+
});
248367
});

‎src/agents/mcp-http-fetch.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ const fetchWithUndiciGuard = async (
2525
): Promise<Response> => await fetchWithUndici(input instanceof Request ? input.url : input, init);
2626

2727
const MCP_HTTP_MAX_REDIRECTS = 20;
28+
/** Safety cap for MCP HTTP response body reads (1 MiB). */
29+
const MCP_HTTP_MAX_RESPONSE_BYTES = 1 * 1024 * 1024;
2830
const managedMcpResponseCleanupRegistry = new FinalizationRegistry<{
2931
finalize: () => Promise<void>;
3032
}>((held) => {
@@ -66,7 +68,23 @@ async function ensureGlobalFetchResponse(response: Response): Promise<Response>
6668
return new Response(null, init);
6769
}
6870
if (typeof response.text === "function") {
71+
const contentLength = response.headers.get("content-length");
72+
// Reject without reading when the declared size is missing, malformed,
73+
// or exceeds the cap. A missing Content-Length on a body-less response
74+
// means we cannot verify the size before calling text(), so we skip the
75+
// read to avoid unbounded allocation on untrusted input.
76+
if (contentLength == null || !/^\d+$/.test(contentLength)) {
77+
return new Response(null, init);
78+
}
79+
const length = Number(contentLength);
80+
if (!Number.isFinite(length) || length > MCP_HTTP_MAX_RESPONSE_BYTES) {
81+
return new Response(null, init);
82+
}
6983
const text = await response.text();
84+
// Guard against declared Content-Length that understates the actual body.
85+
if (Buffer.byteLength(text, "utf8") > MCP_HTTP_MAX_RESPONSE_BYTES) {
86+
return new Response(null, init);
87+
}
7088
return new Response(text, init);
7189
}
7290
return new Response(null, init);

0 commit comments

Comments
 (0)