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