| 40 | } |
| 41 | |
| 42 | const readMcpJson = async <A>(response: JsonReadableResponse): Promise<A> => { |
| 43 | const contentType = response.headers.get("content-type") ?? ""; |
| 44 | if (contentType.includes("application/json")) { |
| 45 | return (await response.json()) as A; |
| 46 | } |
| 47 | // Parse the SSE stream properly instead of grabbing the first `data:` line: |
| 48 | // the server may legally interleave other events (e.g. the priming event a |
| 49 | // tools/call stream emits so clients can reconnect) before the JSON-RPC |
| 50 | // message. Only `message`-typed events (the SSE default) carry JSON-RPC. |
| 51 | const text = await response.text(); |
| 52 | let responseMessage: unknown; |
| 53 | for (const block of text.split("\n\n")) { |
| 54 | let eventType = "message"; |
| 55 | let data = ""; |
| 56 | for (const line of block.replace(/\r/g, "").split("\n")) { |
| 57 | if (line.startsWith("event:")) eventType = line.slice("event:".length).trim(); |
| 58 | if (line.startsWith("data:")) data += line.slice("data:".length).trimStart(); |
| 59 | } |
| 60 | if (eventType !== "message" || data.length === 0) continue; |
| 61 | const parsed = decodeUnknownJson(data); |
| 62 | // Skip protocol-legal notifications; the tests want the response. |
| 63 | if ( |
| 64 | typeof parsed === "object" && |
| 65 | parsed !== null && |
| 66 | ("result" in parsed || "error" in parsed) |
| 67 | ) { |
| 68 | responseMessage = parsed; |
| 69 | break; |
| 70 | } |
| 71 | } |
| 72 | expect(responseMessage, "a JSON-RPC response arrives on the SSE stream").toBeTruthy(); |
| 73 | return responseMessage as A; |
| 74 | }; |
| 75 | |
| 76 | describe("cloudflare host e2e (workerd/miniflare)", () => { |
| 77 | let worker: Unstable_DevWorker; |