返回源码地图

packages/mcp/test/streamable-http.test.ts

v1.3.0 · 71023aec1546 · 09:读过取消后不重发与close不refresh测试;未本机执行上游测试

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import type { IncomingMessage, ServerResponse } from "node:http";
2import { afterEach, describe, expect, it, vi } from "vitest";
3import {
4 LATEST_PROTOCOL_VERSION,
5 type McpAuthRequiredError,
6 McpClient,
7 type McpFetch,
8 McpSessionExpiredError,
9 StreamableHttpTransport,
10} from "../src/index.ts";
11import { consumeSseStream, type SseEvent } from "../src/transports/streamable-http.ts";
12import { closeServers, listen, readBody } from "./helpers.ts";
13
14interface RecordedRequest {
15 method: string;
16 headers: IncomingMessage["headers"];
17 message?: Record<string, unknown>;
18}
19
20async function startServer(
21 handler: (request: IncomingMessage, response: ServerResponse, requests: RecordedRequest[]) => Promise<void>,
22): Promise<{ url: string; requests: RecordedRequest[] }> {
23 const requests: RecordedRequest[] = [];
24 const origin = await listen((request, response) => handler(request, response, requests));
25 return { url: `${origin}/mcp`, requests };
26}
27
28async function protocolHandler(
29 request: IncomingMessage,
30 response: ServerResponse,
31 requests: RecordedRequest[],
32 body?: Record<string, unknown>,
33): Promise<void> {
34 if (request.method === "GET") {
35 requests.push({ method: "GET", headers: request.headers });
36 response.statusCode = 405;
37 response.end();
38 return;
39 }
40 if (request.method === "DELETE") {
41 requests.push({ method: "DELETE", headers: request.headers });
42 response.statusCode = 200;
43 response.end();
44 return;
45 }
46 const message = body ?? (JSON.parse(await readBody(request)) as Record<string, unknown>);
47 requests.push({ method: request.method ?? "", headers: request.headers, message });
48 if (!("id" in message)) {
49 response.statusCode = 202;
50 response.end();
51 return;
52 }
53 if (message.method === "initialize") {
54 response.writeHead(200, {
55 "content-type": "application/json",
56 "mcp-session-id": "session-1",
57 });
58 response.end(
59 JSON.stringify({
60 jsonrpc: "2.0",
61 id: message.id,
62 result: {
63 protocolVersion: LATEST_PROTOCOL_VERSION,
64 capabilities: { tools: {} },
65 serverInfo: { name: "http-fixture", version: "1.0.0" },
66 },
67 }),
68 );
69 return;
70 }
71 if (message.method === "tools/list") {
72 response.setHeader("content-type", "application/json");
73 response.end(
74 JSON.stringify({
75 jsonrpc: "2.0",
76 id: message.id,
77 result: { tools: [{ name: "echo", inputSchema: { type: "object" } }] },
78 }),
79 );
80 return;
81 }
82 response.writeHead(200, { "content-type": "text/event-stream" });
83 response.write("id: tool-result\n");
84 response.end(
85 `data: ${JSON.stringify({ jsonrpc: "2.0", id: message.id, result: { content: [{ type: "text", text: "hello" }] } })}\n\n`,
86 );
87}
88
89afterEach(closeServers);
90
91describe("consumeSseStream", () => {
92 it("parses chunked CRLF events, comments, IDs, and multiline data", async () => {
93 const encoder = new TextEncoder();
94 const chunks = [': keepalive\r\nid: 7\r\ndata: {"one":\r\n', "data: 1}\r\n\r\n"];
95 const stream = new ReadableStream<Uint8Array>({
96 start(controller) {
97 for (const chunk of chunks) controller.enqueue(encoder.encode(chunk));
98 controller.close();
99 },
100 });
101 const events: SseEvent[] = [];
102 await consumeSseStream(stream, { onEvent: (event) => events.push(event) });
103 expect(events).toEqual([{ id: "7", data: '{"one":\n1}' }]);
104 });
105
106 it("rejects events whose data lines exceed the limit without a blank line", async () => {
107 const encoder = new TextEncoder();
108 let sent = 0;
109 const stream = new ReadableStream<Uint8Array>({
110 pull(controller) {
111 // Never sends a blank line, so the event is never dispatched.
112 if (sent++ > 1000) controller.close();
113 else controller.enqueue(encoder.encode("data: xxxxxxxxxxxxxxxx\n"));
114 },
115 });
116 await expect(consumeSseStream(stream, { maxEventBytes: 256, onEvent: () => {} })).rejects.toThrow(
117 "MCP SSE event exceeds 256 bytes",
118 );
119 expect(sent).toBeLessThan(100);
120 });
121});
122
123describe("StreamableHttpTransport", () => {
124 it("handles JSON and SSE responses with session and protocol headers", async () => {
125 const { url, requests } = await startServer(protocolHandler);
126 const transport = new StreamableHttpTransport({ url });
127 const client = new McpClient({ name: "http-test", version: "1.0.0" });
128 await client.connect(transport);
129 expect(transport.sessionId).toBe("session-1");
130 expect(await client.listTools()).toEqual([{ name: "echo", inputSchema: { type: "object" } }]);
131 expect(await client.callTool("echo", { text: "hello" })).toEqual({
132 content: [{ type: "text", text: "hello" }],
133 });
134 await client.close();
135
136 const listRequest = requests.find((entry) => entry.message?.method === "tools/list");
137 expect(listRequest?.headers["mcp-session-id"]).toBe("session-1");
138 expect(listRequest?.headers["mcp-protocol-version"]).toBe(LATEST_PROTOCOL_VERSION);
139 expect(requests.some((entry) => entry.method === "GET")).toBe(true);
140 expect(requests.some((entry) => entry.method === "DELETE")).toBe(true);
141 });
142
143 it("classifies authentication failures", async () => {
144 const { url } = await startServer(async (request, response) => {
145 await readBody(request);
146 response.writeHead(401, { "www-authenticate": 'Bearer resource_metadata="https://example.com/meta"' });
147 response.end("login required");
148 });
149 const client = new McpClient({ name: "http-test", version: "1.0.0" });
150 await expect(client.connect(new StreamableHttpTransport({ url }))).rejects.toMatchObject({
151 name: "McpAuthRequiredError",
152 status: 401,
153 body: "login required",
154 wwwAuthenticate: 'Bearer resource_metadata="https://example.com/meta"',
155 } satisfies Partial<McpAuthRequiredError>);
156 });
157
158 it("fails only the request whose SSE stream breaks", async () => {
159 let releaseSlow = () => {};
160 const slowGate = new Promise<void>((resolve) => {
161 releaseSlow = resolve;
162 });
163 const { url } = await startServer(async (request, response, requests) => {
164 if (request.method !== "POST") return protocolHandler(request, response, requests);
165 const message = JSON.parse(await readBody(request)) as Record<string, unknown>;
166 const name = (message.params as { name?: string } | undefined)?.name;
167 if (name === "broken") {
168 response.writeHead(200, { "content-type": "text/event-stream" });
169 response.end("data: not json\n\n");
170 return;
171 }
172 if (name === "slow") await slowGate;
173 await protocolHandler(request, response, requests, message);
174 });
175 const client = new McpClient({ name: "http-test", version: "1.0.0" });
176 const errors: Error[] = [];
177 client.onError((error) => errors.push(error));
178 await client.connect(new StreamableHttpTransport({ url, openGetStream: false }));
179
180 const slow = client.callTool("slow");
181 await expect(client.callTool("broken")).rejects.toThrow("MCP response stream failed");
182 releaseSlow();
183 expect(await slow).toEqual({ content: [{ type: "text", text: "hello" }] });
184 expect(errors).toHaveLength(1);
185 await client.close();
186 });
187
188 it("opens the GET stream after initialization and sends Last-Event-ID only when resuming", async () => {
189 const order: string[] = [];
190 const { url, requests } = await startServer(async (request, response, requests) => {
191 if (request.method === "POST") {
192 const message = JSON.parse(await readBody(request)) as Record<string, unknown>;
193 order.push(String(message.method));
194 return protocolHandler(request, response, requests, message);
195 }
196 order.push(request.method ?? "");
197 return protocolHandler(request, response, requests);
198 });
199 const client = new McpClient({ name: "http-test", version: "1.0.0" });
200 await client.connect(new StreamableHttpTransport({ url }));
201 await client.callTool("echo");
202 await client.listTools();
203 await client.close();
204 expect(order.indexOf("GET")).toBeGreaterThan(order.indexOf("notifications/initialized"));
205 expect(requests.every((entry) => entry.headers["last-event-id"] === undefined)).toBe(true);
206 });
207
208 it("resumes a response stream the server closed before answering", async () => {
209 const resumeHeaders: (string | undefined)[] = [];
210 const { url } = await startServer(async (request, response, requests) => {
211 if (request.method === "GET" && request.headers["last-event-id"]) {
212 resumeHeaders.push(request.headers["last-event-id"] as string);
213 response.writeHead(200, { "content-type": "text/event-stream" });
214 response.end(
215 `id: 2\ndata: ${JSON.stringify({ jsonrpc: "2.0", id: 2, result: { content: [{ type: "text", text: "resumed" }] } })}\n\n`,
216 );
217 return;
218 }
219 if (request.method !== "POST") return protocolHandler(request, response, requests);
220 const message = JSON.parse(await readBody(request)) as Record<string, unknown>;
221 if (message.method !== "tools/call") return protocolHandler(request, response, requests, message);
222 // Priming event (ID, no data) and a retry hint, then the server drops the stream.
223 response.writeHead(200, { "content-type": "text/event-stream" });
224 response.end("id: 1\nretry: 5\ndata:\n\n");
225 });
226 const client = new McpClient({ name: "http-test", version: "1.0.0" });
227 const errors: Error[] = [];
228 client.onError((error) => errors.push(error));
229 await client.connect(new StreamableHttpTransport({ url, openGetStream: false }));
230 expect(await client.callTool("echo")).toEqual({ content: [{ type: "text", text: "resumed" }] });
231 expect(resumeHeaders).toEqual(["1"]);
232 expect(errors).toEqual([]);
233 await client.close();
234 });
235
236 it("fails a request whose response stream ends without an answer", async () => {
237 const { url } = await startServer(async (request, response, requests) => {
238 if (request.method !== "POST") return protocolHandler(request, response, requests);
239 const message = JSON.parse(await readBody(request)) as Record<string, unknown>;
240 if (message.method !== "tools/call") return protocolHandler(request, response, requests, message);
241 response.writeHead(200, { "content-type": "text/event-stream" });
242 response.end(": nothing here\n\n");
243 });
244 const client = new McpClient({ name: "http-test", version: "1.0.0" });
245 await client.connect(new StreamableHttpTransport({ url, openGetStream: false }));
246 await expect(client.callTool("echo", {}, { timeoutMs: 5_000 })).rejects.toThrow(
247 "MCP response stream failed: stream ended without a response",
248 );
249 await client.close();
250 });
251
252 it("reconnects the GET stream after it drops", async () => {
253 let gets = 0;
254 const lastEventIds: (string | undefined)[] = [];
255 const { url } = await startServer(async (request, response, requests) => {
256 if (request.method !== "GET") return protocolHandler(request, response, requests);
257 gets++;
258 lastEventIds.push(request.headers["last-event-id"] as string | undefined);
259 response.writeHead(200, { "content-type": "text/event-stream" });
260 const notification = { jsonrpc: "2.0", method: "notifications/tools/list_changed" };
261 if (gets === 1) {
262 response.end(`id: g1\ndata: ${JSON.stringify(notification)}\n\n`);
263 return;
264 }
265 response.write(`id: g2\ndata: ${JSON.stringify(notification)}\n\n`);
266 });
267 const client = new McpClient({ name: "http-test", version: "1.0.0" });
268 let changes = 0;
269 const secondChange = new Promise<void>((resolve) => {
270 client.onNotification("notifications/tools/list_changed", () => {
271 if (++changes === 2) resolve();
272 });
273 });
274 await client.connect(new StreamableHttpTransport({ url, reconnect: { initialDelayMs: 1 } }));
275 await secondChange;
276 expect(lastEventIds).toEqual([undefined, "g1"]);
277 await client.close();
278 });
279
280 it("rejects a request the server accepts without a response", async () => {
281 const { url } = await startServer(async (request, response, requests) => {
282 if (request.method !== "POST") return protocolHandler(request, response, requests);
283 const message = JSON.parse(await readBody(request)) as Record<string, unknown>;
284 if (message.method !== "tools/call") return protocolHandler(request, response, requests, message);
285 response.statusCode = 202;
286 response.end();
287 });
288 const client = new McpClient({ name: "http-test", version: "1.0.0" });
289 await client.connect(new StreamableHttpTransport({ url, openGetStream: false }));
290 await expect(client.callTool("echo")).rejects.toThrow("without a response");
291 await client.close();
292 });
293
294 it("includes the response body in HTTP errors", async () => {
295 const { url } = await startServer(async (request, response) => {
296 await readBody(request);
297 response.statusCode = 400;
298 response.end("Invalid Accept header");
299 });
300 const client = new McpClient({ name: "http-test", version: "1.0.0" });
301 await expect(client.connect(new StreamableHttpTransport({ url }))).rejects.toThrow(
302 "MCP HTTP request failed with status 400: Invalid Accept header",
303 );
304 });
305
306 it("hands 401 and insufficient-scope 403 responses to the auth provider with the rejected token", async () => {
307 const seen: { status: number; token?: string }[] = [];
308 let token = "old";
309 const { url } = await startServer(async (request, response, requests) => {
310 if (request.method !== "POST") return protocolHandler(request, response, requests);
311 const message = JSON.parse(await readBody(request)) as Record<string, unknown>;
312 if (request.headers.authorization === "Bearer old") {
313 response.writeHead(401, { "www-authenticate": "Bearer" }).end();
314 return;
315 }
316 if (message.method === "tools/call" && request.headers.authorization === "Bearer new") {
317 response.writeHead(403, { "www-authenticate": 'Bearer error="insufficient_scope", scope="admin"' }).end();
318 return;
319 }
320 return protocolHandler(request, response, requests, message);
321 });
322 const client = new McpClient({ name: "http-test", version: "1.0.0" });
323 await client.connect(
324 new StreamableHttpTransport({
325 url,
326 openGetStream: false,
327 authProvider: {
328 token: async () => token,
329 onUnauthorized: async ({ response, token: rejected }) => {
330 seen.push({ status: response.status, token: rejected });
331 if (response.status === 401) token = "new";
332 else token = "admin";
333 },
334 },
335 }),
336 );
337 expect(await client.callTool("echo")).toEqual({ content: [{ type: "text", text: "hello" }] });
338 expect(seen).toEqual([
339 { status: 401, token: "old" },
340 { status: 403, token: "new" },
341 ]);
342 await client.close();
343 });
344
345 // #10598: a request cancelled or timed out while waiting for a shared refresh must not be retried.
346 it("does not retry requests that were cancelled while authorization was recovering", async () => {
347 let token = "old";
348 const executed: unknown[] = [];
349 const { url } = await startServer(async (request, response, requests) => {
350 if (request.method !== "POST") return protocolHandler(request, response, requests);
351 const message = JSON.parse(await readBody(request)) as Record<string, unknown>;
352 if (message.method === "tools/call" && request.headers.authorization === "Bearer old") {
353 response.writeHead(401, { "www-authenticate": "Bearer" }).end();
354 return;
355 }
356 if (message.method === "tools/call") executed.push((message.params as { name: string }).name);
357 return protocolHandler(request, response, requests, message);
358 });
359 let releaseRefresh = () => {};
360 const refreshGate = new Promise<void>((resolve) => {
361 releaseRefresh = resolve;
362 });
363 let refresh: Promise<void> | undefined;
364 let refreshes = 0;
365 let waiting = 0;
366 let allWaiting = () => {};
367 const waitingGate = new Promise<void>((resolve) => {
368 allWaiting = resolve;
369 });
370 const client = new McpClient({ name: "http-test", version: "1.0.0" });
371 await client.connect(
372 new StreamableHttpTransport({
373 url,
374 openGetStream: false,
375 authProvider: {
376 token: async () => token,
377 onUnauthorized: async () => {
378 if (!refresh) {
379 refreshes++;
380 refresh = refreshGate.then(() => {
381 token = "new";
382 });
383 }
384 if (++waiting === 3) allWaiting();
385 await refresh;
386 },
387 },
388 }),
389 );
390 const controller = new AbortController();
391 const aborted = client.callTool("aborted", {}, { signal: controller.signal });
392 const timedOut = client.callTool("timed-out", {}, { timeoutMs: 200 });
393 const kept = client.callTool("kept");
394 await waitingGate;
395 controller.abort();
396 await expect(aborted).rejects.toMatchObject({ name: "AbortError" });
397 await expect(timedOut).rejects.toMatchObject({ name: "McpTimeoutError" });
398 releaseRefresh();
399 expect(await kept).toEqual({ content: [{ type: "text", text: "hello" }] });
400 expect(executed).toEqual(["kept"]);
401 expect(refreshes).toBe(1);
402 await client.close();
403 });
404
405 // #10565: the auth provider may refresh over the network, which closing must not wait for.
406 it("closes the session with the last request's token, without asking the auth provider", async () => {
407 const { url, requests } = await startServer(protocolHandler);
408 let calls = 0;
409 const client = new McpClient({ name: "http-test", version: "1.0.0" });
410 await client.connect(
411 new StreamableHttpTransport({
412 url,
413 openGetStream: false,
414 authProvider: { token: async () => `token-${++calls}` },
415 }),
416 );
417 const before = calls;
418 await client.close();
419 expect(calls).toBe(before);
420 const deletes = requests.filter((entry) => entry.method === "DELETE");
421 expect(deletes.map((entry) => entry.headers.authorization)).toEqual([`Bearer token-${before}`]);
422 expect(deletes[0]?.headers["mcp-session-id"]).toBe("session-1");
423 });
424
425 // #10188: Cloudflare Workers reject the platform fetch when called with a receiver other than globalThis.
426 it("calls fetch without a receiver", async () => {
427 const realFetch = globalThis.fetch;
428 const strictFetch = function (this: unknown, input: string | URL, init?: RequestInit) {
429 if (this !== undefined && this !== globalThis) throw new TypeError("Illegal invocation");
430 return realFetch(input, init);
431 } satisfies McpFetch;
432 const { url } = await startServer(async (request, response, requests) => {
433 if (request.method === "POST" && request.headers.authorization === undefined) {
434 await readBody(request);
435 response.writeHead(401, { "www-authenticate": "Bearer" }).end();
436 return;
437 }
438 return protocolHandler(request, response, requests);
439 });
440 const connect = async (fetch: McpFetch | undefined) => {
441 let token: string | undefined;
442 const client = new McpClient({ name: "http-test", version: "1.0.0" });
443 await client.connect(
444 new StreamableHttpTransport({
445 url,
446 fetch,
447 openGetStream: false,
448 authProvider: {
449 token: async () => token,
450 onUnauthorized: async (context) => {
451 await (await context.fetch(url)).body?.cancel();
452 token = "token";
453 },
454 },
455 }),
456 );
457 expect(await client.listTools()).toEqual([{ name: "echo", inputSchema: { type: "object" } }]);
458 await client.close();
459 };
460
461 await connect(strictFetch);
462 vi.stubGlobal("fetch", strictFetch);
463 try {
464 await connect(undefined);
465 } finally {
466 vi.unstubAllGlobals();
467 }
468 });
469
470 it("classifies an expired established session", async () => {
471 let posts = 0;
472 const { url } = await startServer(async (request, response, requests) => {
473 if (request.method === "POST" && posts++ >= 2) {
474 await readBody(request);
475 response.statusCode = 404;
476 response.end("gone");
477 return;
478 }
479 await protocolHandler(request, response, requests);
480 });
481 const client = new McpClient({ name: "http-test", version: "1.0.0" });
482 await client.connect(new StreamableHttpTransport({ url, openGetStream: false }));
483 await expect(client.listTools()).rejects.toBeInstanceOf(McpSessionExpiredError);
484 await client.close();
485 });
486});