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): fall back to the legacy HTTP+SSE transport
vastsa03cabe3edf5a
diff --git a/apps/desktop/electron/main/mcp-legacy-sse.ts b/apps/desktop/electron/main/mcp-legacy-sse.tsnew file mode 100644index 000000000..b44db4e72--- /dev/null+++ b/apps/desktop/electron/main/mcp-legacy-sse.ts@@ -0,0 +1,324 @@+import type { JsonRpcMessage, McpTransport, McpTransportHandlers } from "./plugin-mcp.ts";++/**+ * Client side of the MCP 2024-11-05 HTTP+SSE transport.+ *+ * Servers built on that revision expose `GET <url>` as a long-lived event+ * stream whose first `endpoint` event names the URL that accepts client+ * messages; replies arrive on the stream, not in the POST response. The+ * streamable-HTTP client only falls back here when the server rejects its+ * initialize POST the way the spec's backwards-compatibility section+ * describes (issue #2528).+ */++/** Guard against a server streaming one unbounded event at us. */+const MAX_SSE_EVENT_BYTES = 4 * 1024 * 1024;++/** Streamable-HTTP initialize statuses that mean "try the legacy transport". */+const LEGACY_FALLBACK_STATUSES = new Set([400, 404, 405]);++type McpError = Error & { code?: string; status?: number };++function mcpError(code: string, message: string): McpError {+ const error = new Error(message) as McpError;+ error.code = code;+ return error;+}++export function isLegacySseFallbackError(error: unknown): boolean {+ const { code, status } = (error ?? {}) as McpError;+ return code === "HTTP_ERROR" && typeof status === "number" && LEGACY_FALLBACK_STATUSES.has(status);+}++export type LegacySseTransport = McpTransport & {+ /** Open the event stream and wait for the server's message endpoint. */+ connect: (timeoutMs: number, signal?: AbortSignal) => Promise<void>;+ /** Whether the server answered GET with an event stream. */+ streamOpened: () => boolean;+};++type SseEvent = { event: string; data: string };++function parseSseEvent(block: string): SseEvent | null {+ let event = "message";+ const data: string[] = [];+ for (const line of block.split(/\r?\n/)) {+ if (!line || line.startsWith(":")) continue;+ const colon = line.indexOf(":");+ const field = colon < 0 ? line : line.slice(0, colon);+ let value = colon < 0 ? "" : line.slice(colon + 1);+ if (value.startsWith(" ")) value = value.slice(1);+ if (field === "event") event = value;+ else if (field === "data") data.push(value);+ }+ if (data.length === 0) return null;+ return { event, data: data.join("\n") };+}++async function cancelBody(response: Response): Promise<void> {+ try {+ await response.body?.cancel();+ } catch {+ // The body carries nothing the transport needs.+ }+}++export function createLegacySseTransport(+ options: {+ url: string;+ headers: Record<string, string>;+ timeoutMs: number;+ fetchImpl: typeof fetch;+ assertUrlAllowed?: (url: string) => void;+ },+ handlers: McpTransportHandlers,+): LegacySseTransport {+ const streamController = new AbortController();+ const postControllers = new Set<AbortController>();+ let closed = false;+ let opened = false;+ let endpoint: Promise<string> | null = null;++ const shutdown = (reason: string | null) => {+ if (closed) return;+ closed = true;+ streamController.abort();+ for (const controller of postControllers) controller.abort();+ postControllers.clear();+ if (reason !== null) handlers.onClose(reason);+ };++ const readStream = async (+ response: Response,+ onEndpoint: (url: string) => void,+ onFailure: (error: Error) => void,+ ) => {+ if (!response.body) {+ onFailure(mcpError("INVALID_RESPONSE", "mcp sse stream has no body"));+ return;+ }+ const reader = response.body.getReader();+ const decoder = new TextDecoder();+ let buffer = "";+ let endpointSeen = false;+ const dispatch = (block: string) => {+ const event = parseSseEvent(block);+ if (!event) return;+ if (event.event === "endpoint") {+ if (endpointSeen) return;+ endpointSeen = true;+ let next: URL;+ try {+ next = new URL(event.data.trim(), options.url);+ } catch {+ throw mcpError("INVALID_RESPONSE", "mcp sse server sent an invalid endpoint");+ }+ // The message endpoint receives the configured credentials, so it+ // must stay on the origin the user configured.+ if (next.origin !== new URL(options.url).origin) {+ throw mcpError("INVALID_RESPONSE", "mcp sse endpoint is on a different origin");+ }+ options.assertUrlAllowed?.(next.toString());+ onEndpoint(next.toString());+ return;+ }+ if (event.event !== "message") return;+ try {+ handlers.onMessage(JSON.parse(event.data) as JsonRpcMessage);+ } catch {+ // A malformed event is not actionable; its request times out instead.+ }+ };+ try {+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ if (!value) continue;+ buffer += decoder.decode(value, { stream: true });+ for (;;) {+ const boundary = /\r?\n\r?\n/.exec(buffer);+ if (!boundary) break;+ const block = buffer.slice(0, boundary.index);+ buffer = buffer.slice(boundary.index + boundary[0].length);+ dispatch(block);+ }+ if (buffer.length > MAX_SSE_EVENT_BYTES) {+ throw mcpError("LIMIT_EXCEEDED", "mcp sse event is too large");+ }+ }+ onFailure(mcpError("UNAVAILABLE", "mcp sse stream closed"));+ } catch (error) {+ onFailure(closed ? mcpError("UNAVAILABLE", "mcp session closed") : (error as Error));+ } finally {+ try {+ await reader.cancel();+ } catch {+ // The stream is already finished or aborted.+ }+ }+ };++ const openStream = (): Promise<string> =>+ new Promise<string>((resolveEndpoint, rejectEndpoint) => {+ let settled = false;+ const onEndpoint = (url: string) => {+ if (settled) return;+ settled = true;+ resolveEndpoint(url);+ };+ const onFailure = (error: Error) => {+ if (!settled) {+ settled = true;+ rejectEndpoint(error);+ return;+ }+ // The session was live; losing its stream ends it.+ shutdown(error.message);+ };+ void (async () => {+ options.assertUrlAllowed?.(options.url);+ const response = await options.fetchImpl(options.url, {+ method: "GET",+ headers: { ...options.headers, accept: "text/event-stream" },+ redirect: "manual",+ signal: streamController.signal,+ });+ if (response.status >= 300 && response.status <= 399) {+ await cancelBody(response);+ throw mcpError("HTTP_REDIRECT", "mcp sse stream redirects are not supported");+ }+ if (!response.ok) {+ await cancelBody(response);+ const error = mcpError("HTTP_ERROR", `mcp server returned ${response.status}`);+ error.status = response.status;+ throw error;+ }+ if (!(response.headers.get("content-type") ?? "").includes("text/event-stream")) {+ await cancelBody(response);+ throw mcpError("INVALID_RESPONSE", "mcp server did not open an sse stream");+ }+ opened = true;+ await readStream(response, onEndpoint, onFailure);+ })().catch(onFailure);+ });++ const waitForEndpoint = (timeoutMs: number, signal?: AbortSignal): Promise<string> => {+ if (closed) return Promise.reject(mcpError("UNAVAILABLE", "mcp session is closed"));+ endpoint ??= openStream();+ const pending = endpoint;+ return new Promise<string>((resolveWait, rejectWait) => {+ const finish = () => {+ clearTimeout(timer);+ signal?.removeEventListener("abort", abort);+ };+ const abort = () => {+ finish();+ rejectWait(mcpError("TOOL_ABORTED", "mcp request aborted"));+ };+ const timer = setTimeout(() => {+ finish();+ rejectWait(mcpError("TIMEOUT", `mcp sse endpoint not announced after ${timeoutMs}ms`));+ }, timeoutMs);+ if (signal?.aborted) abort();+ else signal?.addEventListener("abort", abort, { once: true });+ pending.then(+ (url) => {+ finish();+ resolveWait(url);+ },+ (error: Error) => {+ finish();+ rejectWait(error);+ },+ );+ });+ };++ return {+ connect: async (timeoutMs, signal) => {+ await waitForEndpoint(timeoutMs, signal);+ },+ streamOpened: () => opened,+ send: async (message, timeoutMs = options.timeoutMs, signal) => {+ const url = await waitForEndpoint(timeoutMs, signal);+ if (closed) throw mcpError("UNAVAILABLE", "mcp session is closed");+ const controller = new AbortController();+ const abort = () => controller.abort();+ if (signal?.aborted) abort();+ else signal?.addEventListener("abort", abort, { once: true });+ postControllers.add(controller);+ const timer = setTimeout(abort, timeoutMs);+ try {+ const response = await options.fetchImpl(url, {+ method: "POST",+ headers: { ...options.headers, "content-type": "application/json" },+ body: JSON.stringify(message),+ redirect: "manual",+ signal: controller.signal,+ });+ // Replies travel on the event stream; the POST is only an acknowledgement.+ await cancelBody(response);+ if (!response.ok) {+ const error = mcpError("HTTP_ERROR", `mcp server returned ${response.status}`);+ error.status = response.status;+ throw error;+ }+ } finally {+ clearTimeout(timer);+ signal?.removeEventListener("abort", abort);+ postControllers.delete(controller);+ }+ },+ close: () => shutdown("mcp session closed"),+ };+}++/**+ * Streamable HTTP first, legacy HTTP+SSE second: the transport is decided by+ * the initialize exchange and fixed for the rest of the session.+ */+export function createHttpTransportWithLegacyFallback(+ options: {+ url: string;+ headers: Record<string, string>;+ timeoutMs: number;+ fetchImpl: typeof fetch;+ assertUrlAllowed?: (url: string) => void;+ },+ handlers: McpTransportHandlers,+ streamable: McpTransport,+): McpTransport {+ let active: McpTransport | null = null;+ return {+ send: async (message, timeoutMs = options.timeoutMs, signal) => {+ if (active) return active.send(message, timeoutMs, signal);+ try {+ await streamable.send(message, timeoutMs, signal);+ active ??= streamable;+ return;+ } catch (error) {+ if (active || message.method !== "initialize" || !isLegacySseFallbackError(error)) throw error;+ let silenced = true;+ const legacy = createLegacySseTransport(options, {+ onMessage: handlers.onMessage,+ onClose: (reason) => {+ if (!silenced) handlers.onClose(reason);+ },+ });+ try {+ await legacy.connect(timeoutMs, signal);+ } catch (legacyError) {+ legacy.close();+ // A server that opened no event stream speaks neither transport;+ // its streamable status is the more useful report. Once the stream+ // is open, the legacy failure is the real one.+ throw legacy.streamOpened() ? legacyError : error;+ }+ silenced = false;+ active = legacy;+ await legacy.send(message, timeoutMs, signal);+ }+ },+ close: () => (active ?? streamable).close(),+ };+}diff --git a/apps/desktop/electron/main/plugin-mcp.ts b/apps/desktop/electron/main/plugin-mcp.tsindex dd60208d4..551e18c55 100644--- a/apps/desktop/electron/main/plugin-mcp.ts+++ b/apps/desktop/electron/main/plugin-mcp.ts@@ -2,6 +2,7 @@ import { spawn as nodeSpawn, type ChildProcess } from "node:child_process";import { isAbsolute, resolve, sep } from "node:path";import type { PluginMcpServerContrib } from "@pi-desktop/plugin-sdk";import { minimalChildEnv } from "./child-process-env.ts";+import { createHttpTransportWithLegacyFallback } from "./mcp-legacy-sse.ts";import {MCP_STDIO_HOST_ENV_KEYS,decodeMcpStderr,@@ -62,7 +63,7 @@ export type McpTransportHandlers = {onClose: (reason: string) => void;};-type McpError = Error & { code?: string };+type McpError = Error & { code?: string; status?: number };function mcpError(code: string, message: string): McpError {const error = new Error(message) as McpError;@@ -469,7 +470,9 @@ function createHttpTransport(} catch {// The status is sufficient for the structured MCP error.}- throw mcpError("HTTP_ERROR", `mcp server returned ${response.status}`);+ const error = mcpError("HTTP_ERROR", `mcp server returned ${response.status}`);+ error.status = response.status;+ throw error;}const nextSession = response.headers.get("mcp-session-id");if (nextSession && new URL(url).origin === initialOrigin) sessionId = nextSession;@@ -700,15 +703,20 @@ export class McpServerClient {handlers,);}- return createHttpTransport(- {- url: String(this.opts.server.url ?? ""),- headers: this.opts.values,- timeoutMs,- fetchImpl: this.opts.fetchImpl,- assertUrlAllowed: this.opts.assertUrlAllowed,- },+ const httpOptions = {+ url: String(this.opts.server.url ?? ""),+ headers: this.opts.values,+ timeoutMs,+ fetchImpl: this.opts.fetchImpl ?? globalThis.fetch,+ assertUrlAllowed: this.opts.assertUrlAllowed,+ };+ // Servers still on the 2024-11-05 HTTP+SSE transport reject the+ // streamable initialize POST (issue #2528); the spec's compatibility path+ // retries over their event stream.+ return createHttpTransportWithLegacyFallback(+ httpOptions,handlers,+ createHttpTransport(httpOptions, handlers),);}diff --git a/apps/desktop/test/mcp-legacy-sse.test.mjs b/apps/desktop/test/mcp-legacy-sse.test.mjsnew file mode 100644index 000000000..1aaa0c173--- /dev/null+++ b/apps/desktop/test/mcp-legacy-sse.test.mjs@@ -0,0 +1,141 @@+import assert from "node:assert/strict";+import test from "node:test";+import { createServer } from "node:http";+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { McpServerClient, describeMcpContent } from "../electron/main/plugin-mcp.ts";++/**+ * An MCP server that only speaks the 2024-11-05 HTTP+SSE transport (issue+ * #2528): `GET <url>` opens the event stream and announces a message endpoint;+ * `POST <url>` is not routed, so a streamable-HTTP client gets 405.+ */+async function startLegacySseServer(t, { postStatus = 405, endpoint = "/messages?session=abc" } = {}) {+ const posts = [];+ const streams = new Set();+ const server = createServer((req, res) => {+ const path = new URL(req.url, "http://localhost").pathname;+ if (path === "/mcp" && req.method === "GET") {+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" });+ res.write(`: connected\n\nevent: endpoint\ndata: ${endpoint}\n\n`);+ streams.add({ req, res });+ req.on("close", () => {+ for (const entry of streams) if (entry.res === res) streams.delete(entry);+ });+ return;+ }+ if (path === "/mcp") {+ res.writeHead(postStatus, { allow: "GET" }).end("Method Not Allowed");+ return;+ }+ if (path === "/messages" && req.method === "POST") {+ const chunks = [];+ req.on("data", (chunk) => chunks.push(chunk));+ req.on("end", () => {+ const message = JSON.parse(Buffer.concat(chunks).toString("utf8"));+ posts.push({ url: req.url, headers: req.headers, message });+ res.writeHead(202).end("Accepted");+ if (message.id === undefined) return;+ let result = {};+ if (message.method === "initialize") {+ result = { protocolVersion: "2024-11-05", capabilities: {} };+ } else if (message.method === "tools/list") {+ result = { tools: [{ name: "echo" }] };+ } else if (message.method === "tools/call") {+ result = { content: [{ type: "text", text: `echo:${req.headers.authorization}` }] };+ }+ const payload = `event: message\ndata: ${JSON.stringify({ jsonrpc: "2.0", id: message.id, result })}\n\n`;+ for (const entry of streams) entry.res.write(payload);+ });+ return;+ }+ res.writeHead(404).end();+ });+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+ t.after(+ () =>+ new Promise((resolve) => {+ for (const entry of streams) entry.res.destroy();+ server.close(resolve);+ }),+ );+ return { url: `http://127.0.0.1:${server.address().port}/mcp`, posts, streams };+}++function client(url, values = {}) {+ return new McpServerClient({+ rootPath: mkdtempSync(join(tmpdir(), "pi-mcp-sse-")),+ server: { id: "legacy", transport: "http", url },+ values,+ connectTimeoutMs: 5_000,+ callTimeoutMs: 5_000,+ });+}++for (const status of [405, 404, 400]) {+ test(`an http server that answers POST with ${status} falls back to the legacy SSE transport`, async (t) => {+ const { url, posts } = await startLegacySseServer(t, { postStatus: status });+ const mcp = client(url, { authorization: "Bearer secret" });+ t.after(() => mcp.close());++ const tools = await mcp.connect();+ assert.deepEqual(tools.map((tool) => tool.name), ["echo"]);+ const result = await mcp.callTool("echo", {});+ assert.equal(describeMcpContent(result.content), "echo:Bearer secret");+ assert.deepEqual(+ posts.map((entry) => entry.message.method),+ ["initialize", "notifications/initialized", "tools/list", "tools/call"],+ );+ assert.ok(posts.every((entry) => entry.url === "/messages?session=abc"));+ });+}++test("closing a legacy SSE client ends its event stream", async (t) => {+ const { url, streams } = await startLegacySseServer(t);+ const mcp = client(url);+ await mcp.connect();+ assert.equal(streams.size, 1);+ mcp.close();+ for (let i = 0; i < 50 && streams.size > 0; i += 1) {+ await new Promise((resolve) => setImmediate(resolve));+ }+ assert.equal(streams.size, 0);+});++test("a legacy SSE endpoint on another origin is refused", async (t) => {+ const { url, posts } = await startLegacySseServer(t, { endpoint: "http://evil.example.test/messages" });+ const mcp = client(url, { authorization: "Bearer secret" });+ t.after(() => mcp.close());+ await assert.rejects(mcp.connect(), (error) => {+ assert.equal(error.code, "INVALID_RESPONSE");+ return true;+ });+ assert.equal(posts.length, 0);+});++test("an authorization failure does not fall back to SSE", async (t) => {+ const { url, posts } = await startLegacySseServer(t, { postStatus: 401 });+ const mcp = client(url);+ t.after(() => mcp.close());+ await assert.rejects(mcp.connect(), (error) => {+ assert.equal(error.code, "HTTP_ERROR");+ assert.match(error.message, /401/);+ return true;+ });+ assert.equal(posts.length, 0);+});++test("a server that rejects both transports keeps the original HTTP error", async (t) => {+ const server = createServer((req, res) => res.writeHead(405).end());+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+ t.after(() => new Promise((resolve) => server.close(resolve)));+ const mcp = client(`http://127.0.0.1:${server.address().port}/mcp`);+ t.after(() => mcp.close());+ await assert.rejects(mcp.connect(), (error) => {+ assert.equal(error.code, "HTTP_ERROR");+ assert.match(error.message, /405/);+ return true;+ });+});diff --git a/docs/spec/06-delivery/e2e/plugins-and-extensions.md b/docs/spec/06-delivery/e2e/plugins-and-extensions.mdindex a7d1985d3..1a5544731 100644--- a/docs/spec/06-delivery/e2e/plugins-and-extensions.md+++ b/docs/spec/06-delivery/e2e/plugins-and-extensions.md@@ -3660,6 +3660,27 @@ plugin-form fixtures in an isolated temporary directory at runtime.- **Status**: Automated by `apps/desktop/test/plugin-mcp.test.mjs` (held-openreply case); no live app process required.+## E2E-MCP-HTTP-legacy-SSE — An HTTP+SSE-only server connects through the compatibility path (issue #2528)++- **Preconditions**: A local mock server speaks only the 2024-11-05 HTTP+SSE+ transport: `GET /mcp` opens an event stream and announces+ `/messages?session=…`; `POST /mcp` answers `405` (repeat with `404` and+ `400`). No provider credentials needed.+- **Steps**: Configure the server with the `http` transport and an+ `authorization` header; connect, discover the tools, and call one. Close the+ client. Repeat with an endpoint on another origin, with `401` from the POST,+ and with a server that rejects both POST and GET.+- **Expected**: Handshake, discovery, and the call succeed over the event+ stream, every message goes to the announced endpoint with the configured+ header, and closing the client ends the stream. A cross-origin endpoint is+ refused before any message is posted, `401` does not fall back, and a server+ speaking neither transport reports the original `HTTP_ERROR` status.+- **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/mcp-legacy-sse.test.mjs`; no live+ app process required.+## E2E-IME-escape: Composition cancellation preserves drafts- **Steps**: Edit a user message; type a draft; dispatch composing Escape and Cmd/Ctrl+Enter. Open global search and dispatch composing Escape from its input. Repeat with legacy keyCode 229, then ordinary Escape and retry shortcuts.diff --git a/docs/spec/07-plugins/01-plugin-system.md b/docs/spec/07-plugins/01-plugin-system.mdindex 27c80dfc8..1a0c8d091 100644--- a/docs/spec/07-plugins/01-plugin-system.md+++ b/docs/spec/07-plugins/01-plugin-system.md@@ -556,6 +556,16 @@ Rules the control encodes:`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 repliesstill times out, and a stream left open past its request is aborted.+- An `http` server that still speaks the 2024-11-05 HTTP+SSE transport rejects+ the streamable initialize POST. When that POST fails with `400`, `404`, or+ `405`, the client follows the MCP backwards-compatibility path: it opens+ `GET <url>` as an event stream, waits for the `endpoint` event, and then+ POSTs every message to that endpoint while replies arrive on the stream. The+ endpoint must share the configured URL's origin because it receives the+ configured headers. Other statuses, including `401`, never fall back. A+ server that opens no event stream keeps the original streamable HTTP error.+ The transport chosen by initialize is fixed for the session; closing the+ client aborts the stream, and a stream that ends closes the session.- 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