|
| 1 | +// @effect-diagnostics nodeBuiltinImport:off globalDate:off globalTimers:off |
| 2 | +import * as NodeChildProcess from "node:child_process"; |
| 3 | +import * as NodeFSP from "node:fs/promises"; |
| 4 | +import * as NodeHttp from "node:http"; |
| 5 | +import * as NodeOS from "node:os"; |
| 6 | +import * as NodePath from "node:path"; |
| 7 | + |
| 8 | +import { describe, expect, it } from "vite-plus/test"; |
| 9 | + |
| 10 | +import { |
| 11 | + MCP_STDIO_BRIDGE_FILE_NAME, |
| 12 | + MCP_STDIO_BRIDGE_SOURCE, |
| 13 | + mcpStdioBridgeEntry, |
| 14 | +} from "./McpStdioBridge.ts"; |
| 15 | + |
| 16 | +interface SeenRequest { |
| 17 | + readonly method: string; |
| 18 | + readonly sessionId: string | undefined; |
| 19 | + readonly protocolVersion: string | undefined; |
| 20 | + readonly authorization: string | undefined; |
| 21 | +} |
| 22 | + |
| 23 | +describe("McpStdioBridge", () => { |
| 24 | + it("builds a stdio MCP entry that launches the bridge under the current runtime", () => { |
| 25 | + const entry = mcpStdioBridgeEntry({ |
| 26 | + bridgePath: "/tmp/state/mcp-stdio-bridge.mjs", |
| 27 | + endpoint: "http://127.0.0.1:9/mcp", |
| 28 | + authorizationHeader: "Bearer test", |
| 29 | + }); |
| 30 | + expect(entry).toEqual({ |
| 31 | + name: "t3-code", |
| 32 | + command: process.execPath, |
| 33 | + args: ["/tmp/state/mcp-stdio-bridge.mjs"], |
| 34 | + env: [ |
| 35 | + { name: "T3_MCP_ENDPOINT", value: "http://127.0.0.1:9/mcp" }, |
| 36 | + { name: "T3_MCP_AUTHORIZATION", value: "Bearer test" }, |
| 37 | + ], |
| 38 | + }); |
| 39 | + }); |
| 40 | + |
| 41 | + it("relays stdio JSON-RPC to the streamable-HTTP endpoint and preserves session headers", async () => { |
| 42 | + const dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-mcp-bridge-")); |
| 43 | + const bridgePath = NodePath.join(dir, MCP_STDIO_BRIDGE_FILE_NAME); |
| 44 | + await NodeFSP.writeFile(bridgePath, MCP_STDIO_BRIDGE_SOURCE); |
| 45 | + |
| 46 | + const seen: SeenRequest[] = []; |
| 47 | + const server = NodeHttp.createServer((req, res) => { |
| 48 | + let body = ""; |
| 49 | + req.on("data", (chunk) => { |
| 50 | + body += chunk; |
| 51 | + }); |
| 52 | + req.on("end", () => { |
| 53 | + const parsed = JSON.parse(body) as { id?: number; method?: string }; |
| 54 | + seen.push({ |
| 55 | + method: parsed.method ?? "", |
| 56 | + sessionId: req.headers["mcp-session-id"] as string | undefined, |
| 57 | + protocolVersion: req.headers["mcp-protocol-version"] as string | undefined, |
| 58 | + authorization: req.headers.authorization, |
| 59 | + }); |
| 60 | + switch (parsed.method) { |
| 61 | + case "initialize": |
| 62 | + res.writeHead(200, { |
| 63 | + "content-type": "application/json", |
| 64 | + "mcp-session-id": "stub-session-1", |
| 65 | + "mcp-protocol-version": "2025-06-18", |
| 66 | + }); |
| 67 | + res.end( |
| 68 | + JSON.stringify({ |
| 69 | + jsonrpc: "2.0", |
| 70 | + id: parsed.id, |
| 71 | + result: { protocolVersion: "2025-06-18" }, |
| 72 | + }), |
| 73 | + ); |
| 74 | + return; |
| 75 | + case "tools/list": |
| 76 | + res.writeHead(200, { "content-type": "application/json" }); |
| 77 | + res.end( |
| 78 | + JSON.stringify({ |
| 79 | + jsonrpc: "2.0", |
| 80 | + id: parsed.id, |
| 81 | + result: { tools: [{ name: "link_pull_request" }] }, |
| 82 | + }), |
| 83 | + ); |
| 84 | + return; |
| 85 | + case "tools/call": |
| 86 | + res.writeHead(200, { "content-type": "text/event-stream" }); |
| 87 | + res.end( |
| 88 | + `data: ${JSON.stringify({ jsonrpc: "2.0", id: parsed.id, result: { ok: true } })}\n\n`, |
| 89 | + ); |
| 90 | + return; |
| 91 | + case "boom/fail": |
| 92 | + res.writeHead(500, { "content-type": "text/plain" }); |
| 93 | + res.end("upstream exploded"); |
| 94 | + return; |
| 95 | + default: |
| 96 | + res.writeHead(202); |
| 97 | + res.end(); |
| 98 | + } |
| 99 | + }); |
| 100 | + }); |
| 101 | + await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve)); |
| 102 | + const address = server.address(); |
| 103 | + if (!address || typeof address === "string") throw new Error("stub server missing address"); |
| 104 | + const endpoint = `http://127.0.0.1:${address.port}/mcp`; |
| 105 | + |
| 106 | + const child = NodeChildProcess.spawn(process.execPath, [bridgePath], { |
| 107 | + env: { T3_MCP_ENDPOINT: endpoint, T3_MCP_AUTHORIZATION: "Bearer test-token" }, |
| 108 | + stdio: ["pipe", "pipe", "pipe"], |
| 109 | + }); |
| 110 | + const stdout: Array<Record<string, unknown>> = []; |
| 111 | + let stdoutBuffer = ""; |
| 112 | + child.stdout.setEncoding("utf8"); |
| 113 | + child.stdout.on("data", (chunk) => { |
| 114 | + stdoutBuffer += chunk; |
| 115 | + let index = stdoutBuffer.indexOf("\n"); |
| 116 | + while (index >= 0) { |
| 117 | + const line = stdoutBuffer.slice(0, index).trim(); |
| 118 | + stdoutBuffer = stdoutBuffer.slice(index + 1); |
| 119 | + if (line) stdout.push(JSON.parse(line) as Record<string, unknown>); |
| 120 | + index = stdoutBuffer.indexOf("\n"); |
| 121 | + } |
| 122 | + }); |
| 123 | + const send = (message: unknown) => child.stdin.write(`${JSON.stringify(message)}\n`); |
| 124 | + const waitForResponses = async (count: number) => { |
| 125 | + const deadline = Date.now() + 10_000; |
| 126 | + while (stdout.length < count && Date.now() < deadline) { |
| 127 | + await new Promise((resolve) => setTimeout(resolve, 25)); |
| 128 | + } |
| 129 | + expect(stdout.length).toBeGreaterThanOrEqual(count); |
| 130 | + }; |
| 131 | + |
| 132 | + try { |
| 133 | + // Deliberately pipeline: the notification and requests are written before |
| 134 | + // the initialize response arrives; the bridge must hold them until it |
| 135 | + // has the session id. |
| 136 | + send({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} }); |
| 137 | + send({ jsonrpc: "2.0", method: "notifications/initialized" }); |
| 138 | + send({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} }); |
| 139 | + send({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "x" } }); |
| 140 | + send({ jsonrpc: "2.0", id: 4, method: "boom/fail", params: {} }); |
| 141 | + await waitForResponses(4); |
| 142 | + |
| 143 | + const byId = new Map( |
| 144 | + stdout.filter((message) => "id" in message).map((message) => [message.id, message]), |
| 145 | + ); |
| 146 | + expect(byId.get(1)).toMatchObject({ result: { protocolVersion: "2025-06-18" } }); |
| 147 | + expect(byId.get(2)).toMatchObject({ result: { tools: [{ name: "link_pull_request" }] } }); |
| 148 | + // SSE event payloads are decoded back into plain JSON-RPC messages. |
| 149 | + expect(byId.get(3)).toMatchObject({ result: { ok: true } }); |
| 150 | + // A non-JSON error body becomes a JSON-RPC error carrying the request id. |
| 151 | + expect(byId.get(4)).toMatchObject({ error: { code: -32603 } }); |
| 152 | + |
| 153 | + const initialize = seen.find((request) => request.method === "initialize"); |
| 154 | + expect(initialize?.authorization).toBe("Bearer test-token"); |
| 155 | + |
| 156 | + for (const method of ["notifications/initialized", "tools/list", "tools/call", "boom/fail"]) { |
| 157 | + const request = seen.find((entry) => entry.method === method); |
| 158 | + expect(request?.sessionId).toBe("stub-session-1"); |
| 159 | + expect(request?.protocolVersion).toBe("2025-06-18"); |
| 160 | + expect(request?.authorization).toBe("Bearer test-token"); |
| 161 | + } |
| 162 | + // The notification gets no JSON-RPC response on stdout. |
| 163 | + expect(stdout.every((message) => message.method !== "notifications/initialized")).toBe(true); |
| 164 | + } finally { |
| 165 | + child.kill(); |
| 166 | + server.close(); |
| 167 | + await NodeFSP.rm(dir, { recursive: true, force: true }); |
| 168 | + } |
| 169 | + }); |
| 170 | +}); |
0 commit comments