Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(mcp): dispatch streamable-HTTP replies before the SSE stream ends
yanyh423d53fdabec
diff --git a/apps/desktop/electron/main/plugin-mcp.ts b/apps/desktop/electron/main/plugin-mcp.tsindex 7a482184a..ebf23fbb8 100644--- a/apps/desktop/electron/main/plugin-mcp.ts+++ b/apps/desktop/electron/main/plugin-mcp.ts@@ -324,6 +324,61 @@ async function readBoundedHttpBody(response: Response): Promise<string> {return new TextDecoder().decode(body);}+/**+ * Dispatch `text/event-stream` messages as they arrive instead of waiting for+ * the body to end. A streamable-HTTP server is free to hold the response open+ * long after the JSON-RPC reply has been written, and reading the whole stream+ * first turned that server-side schedule into a client-side timeout.+ */+async function streamSseMessages(+ response: Response,+ onMessage: (message: JsonRpcMessage) => void,+): Promise<void> {+ const contentLength = Number(response.headers.get("content-length"));+ if (Number.isFinite(contentLength) && contentLength > MAX_HTTP_RESPONSE_BYTES) {+ try {+ await response.body?.cancel();+ } catch {+ // The response is already rejected; cancellation is best effort.+ }+ throw mcpError("LIMIT_EXCEEDED", "mcp server response is too large");+ }+ if (!response.body) return;+ const reader = response.body.getReader();+ const decoder = new TextDecoder();+ let buffer = "";+ let bytes = 0;+ const dispatchCompleteEvents = () => {+ for (;;) {+ const boundary = /\r?\n\r?\n/.exec(buffer);+ if (!boundary) return;+ const event = buffer.slice(0, boundary.index);+ buffer = buffer.slice(boundary.index + boundary[0].length);+ for (const entry of parseSseMessages(event)) onMessage(entry);+ }+ };+ try {+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ if (!value) continue;+ bytes += value.byteLength;+ if (bytes > MAX_HTTP_RESPONSE_BYTES) {+ await reader.cancel();+ throw mcpError("LIMIT_EXCEEDED", "mcp server response is too large");+ }+ buffer += decoder.decode(value, { stream: true });+ dispatchCompleteEvents();+ }+ buffer += decoder.decode();+ dispatchCompleteEvents();+ // A body that ends without its closing blank line still owes us that event.+ for (const entry of parseSseMessages(buffer)) onMessage(entry);+ } finally {+ reader.releaseLock();+ }+}+function headersForMcpRequest(headers: Record<string, string>,initialUrl: string,@@ -429,15 +484,19 @@ function createHttpTransport(return;}const contentType = response.headers.get("content-type") ?? "";+ if (contentType.includes("text/event-stream")) {+ // A streamable-HTTP server may hold the SSE stream open long after+ // the JSON-RPC reply is written — keep-alives, or a session it ends+ // on its own schedule (gitmcp.io answers in ~2s and closes ~12s+ // later). Dispatching each event as it lands keeps that wait out of+ // the caller's timeout budget.+ await streamSseMessages(response, handlers.onMessage);+ return;+ }const body = await readBoundedHttpBody(response);if (!body.trim()) return;- const messages = contentType.includes("text/event-stream")- ? parseSseMessages(body)- : (() => {- const parsed = JSON.parse(body) as JsonRpcMessage | JsonRpcMessage[];- return Array.isArray(parsed) ? parsed : [parsed];- })();- for (const entry of messages) handlers.onMessage(entry);+ const parsed = JSON.parse(body) as JsonRpcMessage | JsonRpcMessage[];+ for (const entry of Array.isArray(parsed) ? parsed : [parsed]) handlers.onMessage(entry);return;}} finally {diff --git a/apps/desktop/test/plugin-mcp.test.mjs b/apps/desktop/test/plugin-mcp.test.mjsindex 18c255200..3c64c05c7 100644--- a/apps/desktop/test/plugin-mcp.test.mjs+++ b/apps/desktop/test/plugin-mcp.test.mjs@@ -393,6 +393,57 @@ test("a remote MCP tool can run longer than the connection timeout", async (t) =const result = await client.callTool("slow", {});assert.equal(describeMcpContent(result.content), "finished");});+test("an SSE reply is dispatched before the server closes the stream", async (t) => {+ // A streamable-HTTP server may answer immediately and still hold the body+ // open — gitmcp.io replies in ~2s and ends the stream ~12s later. Waiting for+ // the body to end used to spend the whole connect budget on that gap.+ const encoder = new TextEncoder();+ let closeStream;+ const keepOpen = new Promise((resolve) => {+ closeStream = resolve;+ });+ const fetchImpl = async (_url, options) => {+ const message = JSON.parse(options.body);+ if (message.method === "notifications/initialized") {+ return new Response(null, { status: 202 });+ }+ const result =+ message.method === "initialize"+ ? { protocolVersion: MCP_PROTOCOL_VERSION, capabilities: {} }+ : { tools: [{ name: "streamed" }] };+ const body = new ReadableStream({+ start(controller) {+ controller.enqueue(+ encoder.encode(+ `event: message\ndata: ${JSON.stringify({ jsonrpc: "2.0", id: message.id, result })}\n\n`,+ ),+ );+ void keepOpen.then(() => controller.close());+ },+ });+ return new Response(body, {+ status: 200,+ headers: { "content-type": "text/event-stream" },+ });+ };+ const client = new McpServerClient({+ rootPath: mkdtempSync(join(tmpdir(), "pi-mcp-sse-")),+ server: { id: "streaming", transport: "http", url: "https://streaming.example/mcp" },+ values: {},+ connectTimeoutMs: 500,+ discoveryTimeoutMs: 500,+ fetchImpl,+ });+ t.after(() => {+ closeStream();+ client.close();+ });++ assert.deepEqual(+ (await client.connect()).map((tool) => tool.name),+ ["streamed"],+ );+});test("aborting one HTTP MCP call cancels its request", async (t) => {let callStarted;let cancellationReceived;diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex d81b99fbb..316e0d563 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -15262,6 +15262,27 @@ the latest destination. These assertions measure work counts, not device FPS.- **Status**: Covered by the existing HTTP client integration fixture and afocused component-render validation; no live IDA process required.+### E2E-MCP-HTTP-SSE-held-open — A streamable HTTP reply lands before the server ends the stream (issue #1188)++- **Preconditions**: A local mock Streamable HTTP server writes its JSON-RPC+ reply immediately and keeps the `text/event-stream` body open well past the+ client's handshake budget — the shape `https://gitmcp.io/docs` shows, where+ initialize is answered in about two seconds and the stream only ends about+ twelve seconds later. No provider credentials needed.+- **Steps**: Configure that server with the `http` transport and a handshake+ budget shorter than the stream lifetime; connect, discover the tools, and call+ one. Repeat with a server that keeps the stream open and never answers.+- **Expected**: Handshake, discovery, and the call complete as soon as their+ reply event arrives, so the connection reports `ready` with the discovered+ tools instead of `mcp initialize timed out after <budget>ms`. A server that+ never replies still fails with `TIMEOUT` inside the same budget, and a stream+ left open past its request is aborted rather than kept open.+- **Specs**: 07-plugins/01-plugin-system §12.2; ADR 0038.+- **Acceptance**: HTTP transport integration and the main-process MCP handshake.+- **Milestone**: Maintenance.+- **Status**: Automated by `apps/desktop/test/plugin-mcp.test.mjs` (held-open+ reply case); no live app process required.+### E2E-IMAGE-generation-and-editing- **Preconditions:** Built task candidate containing latest origin/main; isolateddiff --git a/docs/spec/07-plugins/01-plugin-system.md b/docs/spec/07-plugins/01-plugin-system.mdindex a42bc7626..b1a65c63d 100644--- a/docs/spec/07-plugins/01-plugin-system.md+++ b/docs/spec/07-plugins/01-plugin-system.md@@ -524,6 +524,12 @@ Rules the control encodes:responses are not JSON-RPC replies. Any acknowledgement body is discarded,including plain-text `Accepted`; ordinary request replies still follow theJSON/SSE parsing and response-size limits.+- A streamable-HTTP server may write its JSON-RPC reply and keep the SSE stream+ open afterwards — keep-alives, or a session it ends on its own schedule. Each+ `text/event-stream` event is dispatched as it arrives, so a handshake or a+ `tools/list` page completes on its reply instead of on the end of the stream.+ The request budget still bounds the exchange: a server that never replies+ still times out, and a stream left open past its request is aborted.- The MCP row shows “Authorization required” only when runtime status explicitlyreports `authRequired`. Missing credentials, an untested connection, andnon-authentication failures do not imply OAuth is required. A stored OAuthdiff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 092f4e1b3..8d9ec0c46 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -8730,6 +8730,27 @@ the latest destination. These assertions measure work counts, not device FPS.- **Status**: Covered by the existing HTTP client integration fixture and afocused component-render validation; no live IDA process required.+### E2E-MCP-HTTP-SSE-held-open — A streamable HTTP reply lands before the server ends the stream (issue #1188)++- **Preconditions**: A local mock Streamable HTTP server writes its JSON-RPC+ reply immediately and keeps the `text/event-stream` body open well past the+ client's handshake budget — the shape `https://gitmcp.io/docs` shows, where+ initialize is answered in about two seconds and the stream only ends about+ twelve seconds later. No provider credentials needed.+- **Steps**: Configure that server with the `http` transport and a handshake+ budget shorter than the stream lifetime; connect, discover the tools, and call+ one. Repeat with a server that keeps the stream open and never answers.+- **Expected**: Handshake, discovery, and the call complete as soon as their+ reply event arrives, so the connection reports `ready` with the discovered+ tools instead of `mcp initialize timed out after <budget>ms`. A server that+ never replies still fails with `TIMEOUT` inside the same budget, and a stream+ left open past its request is aborted rather than kept open.+- **Specs**: 07-plugins/01-plugin-system §12.2; ADR 0038.+- **Acceptance**: HTTP transport integration and the main-process MCP handshake.+- **Milestone**: Maintenance.+- **Status**: Automated by `apps/desktop/test/plugin-mcp.test.mjs` (held-open+ reply case); no live app process required.+### E2E-PLUGIN-crash-report-names-the-exit-code- **先决条件:** 已加载的插件宿主进程自行死亡——夹具为写一行 stderr 后 `process.exit(7)`——并带一个常驻服务,使监督器路径也被覆盖。diff --git a/docs/zh-CN/spec/07-plugins/01-plugin-system.md b/docs/zh-CN/spec/07-plugins/01-plugin-system.mdindex a98a17d27..953a1bafa 100644--- a/docs/zh-CN/spec/07-plugins/01-plugin-system.md+++ b/docs/zh-CN/spec/07-plugins/01-plugin-system.md@@ -503,6 +503,12 @@ MCP、技能和子代理由设置 > 智能体下的三个独立页面管理,responses are not JSON-RPC replies. Any acknowledgement body is discarded,including plain-text `Accepted`; ordinary request replies still follow theJSON/SSE parsing and response-size limits.+- A streamable-HTTP server may write its JSON-RPC reply and keep the SSE stream+ open afterwards — keep-alives, or a session it ends on its own schedule. Each+ `text/event-stream` event is dispatched as it arrives, so a handshake or a+ `tools/list` page completes on its reply instead of on the end of the stream.+ The request budget still bounds the exchange: a server that never replies+ still times out, and a stream left open past its request is aborted.- The MCP row shows “Authorization required” only when runtime status explicitlyreports `authRequired`. Missing credentials, an untested connection, andnon-authentication failures do not imply OAuth is required. A stored OAuth