From 01a7342f4b66fa9177730fc796dcf30f9f885858 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mehmet=20Ya=C4=9F=C4=B1z=20Maktav?= <115627863+myagizmaktav@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:59:38 +0300 Subject: [PATCH] :bug: Add opt-in MCP JSON replies and deliver pending outcomes on shutdown (#12492) * :bug: Add opt-in MCP JSON replies and deliver pending outcomes on shutdown Stateless legacy POST requests can opt in to a single correlated JSON reply with PENPOT_MCP_JSON_RESPONSE=true; SSE remains the default. Shutdown now rejects pending plugin tasks before closing HTTP connections and gives in-flight requests a bounded grace period to send their replies, so a tool call interrupted by shutdown reports an unknown outcome instead of a dropped stream (both JSON and SSE). Tool execution failures now set isError on the MCP result. Refs #12497 AI-assisted-by: claude-opus-5-5 * :paperclip: Give the 100-round JSON reply test room on loaded CI machines AI-assisted-by: claude-opus-5-5 --- mcp/README.md | 1 + mcp/packages/server/src/JsonResponse.test.ts | 265 +++++++++++++++++++ mcp/packages/server/src/PenpotMcpServer.ts | 94 ++++++- mcp/packages/server/src/PluginBridge.ts | 6 +- mcp/packages/server/src/Tool.ts | 4 +- 5 files changed, 358 insertions(+), 12 deletions(-) create mode 100644 mcp/packages/server/src/JsonResponse.test.ts diff --git a/mcp/README.md b/mcp/README.md index 095fe64214..26a88028a2 100644 --- a/mcp/README.md +++ b/mcp/README.md @@ -291,6 +291,7 @@ The Penpot MCP server can be configured using environment variables. |--------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------| | `PENPOT_MCP_SERVER_HOST` | Address on which the MCP server listens (binds to) | `localhost` | | `PENPOT_MCP_SERVER_PORT` | Port for the MCP server | `4401` | +| `PENPOT_MCP_JSON_RESPONSE` | Reply to stateless legacy (`2025-*` protocol) requests with a single `application/json` body instead of an SSE stream. The reply carries the request id, so a proxy or client that loses SSE frames still receives a correlated result, including the error of a tool call interrupted by shutdown. Set to `true` to enable; when unset or `false`, the SDK's default (SSE) behaviour is kept. | `false` | | `PENPOT_MCP_WEBSOCKET_PORT` | Port for the WebSocket server (plugin connection) | `4402` | | `PENPOT_MCP_REPL_PORT` | Port for the REPL server (development/debugging) | `4403` | | `PENPOT_MCP_REPL_HOST` | Address on which the REPL server listens (binds to) | `localhost` | diff --git a/mcp/packages/server/src/JsonResponse.test.ts b/mcp/packages/server/src/JsonResponse.test.ts new file mode 100644 index 0000000000..5b59e69f16 --- /dev/null +++ b/mcp/packages/server/src/JsonResponse.test.ts @@ -0,0 +1,265 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { once } from "node:events"; +import { WebSocket } from "ws"; +import { PenpotMcpServer } from "./PenpotMcpServer"; + +const MODERN_PROTOCOL = "2026-07-28"; + +let nextPort = 16_700; + +/** + * Starts a multi-user server on fresh loopback ports with the given `PENPOT_MCP_JSON_RESPONSE` value + * (`undefined` removes the variable) and returns it together with a function restoring the environment. + */ +async function startServer( + jsonResponse: string | undefined +): Promise<{ server: PenpotMcpServer; restoreEnv: () => void }> { + const previousEnv = { ...process.env }; + Object.assign(process.env, { + PENPOT_MCP_SERVER_HOST: "127.0.0.1", + PENPOT_MCP_SERVER_PORT: String(nextPort++), + PENPOT_MCP_WEBSOCKET_PORT: String(nextPort++), + PENPOT_MCP_DEVENV: "false", + PENPOT_MCP_REPL_ENABLE: "false", + }); + if (jsonResponse === undefined) { + delete process.env.PENPOT_MCP_JSON_RESPONSE; + } else { + process.env.PENPOT_MCP_JSON_RESPONSE = jsonResponse; + } + delete process.env.PENPOT_MCP_REDIS_URI; + delete process.env.PENPOT_MCP_AUTH_URI; + const server = new PenpotMcpServer(true); + await server.start(); + return { server, restoreEnv: () => (process.env = previousEnv) }; +} + +/** + * Returns the protocol-specific headers and `_meta` parameters of a `tools/call` request. + */ +function protocolFields(protocol: string): { headers: Record; params: Record } { + if (protocol !== MODERN_PROTOCOL) { + return { headers: {}, params: {} }; + } + return { + headers: { "Mcp-Method": "tools/call", "Mcp-Name": "execute_code" }, + params: { + _meta: { + "io.modelcontextprotocol/protocolVersion": protocol, + "io.modelcontextprotocol/clientInfo": { name: "regression", version: "1" }, + "io.modelcontextprotocol/clientCapabilities": {}, + }, + }, + }; +} + +/** + * Connects a synthetic plugin for the given owner which echoes each task's code and holds tasks with code `__hold__`. + */ +async function connectPlugin(server: PenpotMcpServer, owner: string, onHeld: () => void): Promise { + const plugin = new WebSocket(`ws://127.0.0.1:${server.webSocketPort}/?userToken=${owner}`); + const initialized = new Promise((resolve) => { + plugin.on("message", (raw) => { + const task = JSON.parse(raw.toString()); + if (task.type === "initialized") { + resolve(); + return; + } + if (task.params.code === "__hold__") { + onHeld(); + return; + } + plugin.send(JSON.stringify({ id: task.id, success: true, data: { owner, code: task.params.code } })); + }); + }); + await once(plugin, "open"); + plugin.send( + JSON.stringify({ + type: "initialize", + session: { sessionId: owner, fileId: owner, fileName: owner }, + }) + ); + await initialized; + return plugin; +} + +/** + * Asserts that the plugin bridge no longer tracks any task. + */ +function assertNoTrackedTasks(server: PenpotMcpServer): void { + const bridge = server.pluginBridge as any; + assert.equal(bridge.pendingTasks.size, 0); + assert.equal(bridge.taskTimeouts.size, 0); + assert.equal(bridge.taskConnections.size, 0); +} + +for (const protocol of ["2025-03-26", MODERN_PROTOCOL]) { + test(`opt-in JSON preserves ${protocol} payloads, owners and pending shutdown`, { timeout: 60000 }, async () => { + const { server, restoreEnv } = await startServer("true"); + const plugins: WebSocket[] = []; + let stopped = false; + let onHeld = () => {}; + try { + for (const owner of ["alice", "bob"]) { + plugins.push(await connectPlugin(server, owner, () => onHeld())); + } + const fields = protocolFields(protocol); + const post = (id: number, owner?: string, code = `return ${id};`) => + fetch(`http://127.0.0.1:${server.port}/mcp${owner ? `?userToken=${owner}` : ""}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json, text/event-stream", + "MCP-Protocol-Version": protocol, + ...fields.headers, + }, + body: JSON.stringify({ + jsonrpc: "2.0", + id, + method: "tools/call", + params: { name: "execute_code", arguments: { code }, ...fields.params }, + }), + signal: AbortSignal.timeout(5000), + }); + for (let id = 1; id <= 100; id++) { + await Promise.all( + ["alice", "bob"].map(async (owner) => { + const response = await post(id, owner); + assert.equal(response.status, 200); + assert.match(response.headers.get("content-type")!, /^application\/json/); + assert.equal(response.headers.get("mcp-session-id"), null); + const reply: any = await response.json(); + assert.equal(reply.id, id); + assert.notEqual(reply.result.isError, true); + assert.deepEqual(JSON.parse(reply.result.content[0].text), { owner, code: `return ${id};` }); + }) + ); + } + const denied: any = await (await post(301)).json(); + assert.equal(denied.id, 301); + assert.match(denied.result.content[0].text, /^Tool execution failed:/); + assert.match(JSON.stringify(denied), /authentication|userToken/); + + const held = new Promise((resolve) => { + onHeld = resolve; + }); + // a dropped connection rejects this fetch and thereby fails the test + const pending = post(400, "alice", "__hold__"); + await held; + // leave the plugin connected: stop must release its socket and task itself + await Promise.race([ + server.stop(), + new Promise((_, reject) => + setTimeout(() => reject(new Error("pending JSON shutdown hung")), 5000).unref() + ), + ]); + stopped = true; + const response = await pending; + assert.equal(response.status, 200); + const reply: any = await response.json(); + assert.equal(reply.id, 400); + assert.equal(reply.result.isError, true, "shutdown cannot report success"); + assert.match(reply.result.content[0].text, /shutting down; task outcome may be unknown/); + assertNoTrackedTasks(server); + } finally { + if (!stopped) { + await server.stop(); + } + for (const plugin of plugins) { + plugin.terminate(); + } + restoreEnv(); + } + }); +} + +for (const flag of [undefined, "false"]) { + test(`JSON flag ${flag ?? "absent"} preserves upstream legacy SSE`, async () => { + const { server, restoreEnv } = await startServer(flag); + try { + const response = await fetch(`http://127.0.0.1:${server.port}/mcp`, { + method: "POST", + headers: { "Content-Type": "application/json", Accept: "application/json, text/event-stream" }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-03-26", + capabilities: {}, + clientInfo: { name: "default", version: "1" }, + }, + }), + signal: AbortSignal.timeout(5000), + }); + assert.equal(response.status, 200); + assert.match(response.headers.get("content-type")!, /^text\/event-stream/); + assert.match(await response.text(), /"id":1/); + } finally { + await server.stop(); + restoreEnv(); + } + }); +} + +for (const flag of [undefined, "true"]) { + test(`JSON flag ${flag ?? "absent"} rejects legacy GET and DELETE`, async () => { + const { server, restoreEnv } = await startServer(flag); + try { + for (const method of ["GET", "DELETE"]) { + const response = await fetch(`http://127.0.0.1:${server.port}/mcp`, { + method, + headers: { Accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2025-03-26" }, + signal: AbortSignal.timeout(5000), + }); + assert.equal(response.status, 405, `${method} status`); + await response.body?.cancel(); + } + } finally { + await server.stop(); + restoreEnv(); + } + }); +} + +test("default SSE shutdown delivers the unknown outcome of a pending tool call", { timeout: 15000 }, async () => { + const { server, restoreEnv } = await startServer(undefined); + let plugin: WebSocket | undefined; + let stopped = false; + try { + let onHeld = () => {}; + const held = new Promise((resolve) => { + onHeld = resolve; + }); + plugin = await connectPlugin(server, "alice", () => onHeld()); + const pending = fetch(`http://127.0.0.1:${server.port}/mcp?userToken=alice`, { + method: "POST", + headers: { "Content-Type": "application/json", Accept: "application/json, text/event-stream" }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 7, + method: "tools/call", + params: { name: "execute_code", arguments: { code: "__hold__" } }, + }), + signal: AbortSignal.timeout(5000), + }); + await held; + const stopping = server.stop(); + const response = await pending; + assert.match(response.headers.get("content-type")!, /^text\/event-stream/); + const text = await response.text(); + await stopping; + stopped = true; + assert.match(text, /"id":7/); + assert.match(text, /"isError":true/); + assert.match(text, /shutting down; task outcome may be unknown/); + assertNoTrackedTasks(server); + } finally { + if (!stopped) { + await server.stop(); + } + plugin?.terminate(); + restoreEnv(); + } +}); diff --git a/mcp/packages/server/src/PenpotMcpServer.ts b/mcp/packages/server/src/PenpotMcpServer.ts index d9a1668f89..cb10553c9a 100644 --- a/mcp/packages/server/src/PenpotMcpServer.ts +++ b/mcp/packages/server/src/PenpotMcpServer.ts @@ -1,6 +1,6 @@ -import { createMcpHandler, McpServer, type McpHttpHandler } from "@modelcontextprotocol/server"; -import { toNodeHandler } from "@modelcontextprotocol/node"; -import type { Server as HttpServer } from "node:http"; +import { createMcpHandler, isLegacyRequest, McpServer, type McpHttpHandler } from "@modelcontextprotocol/server"; +import { NodeStreamableHTTPServerTransport, toNodeHandler, toWebRequest } from "@modelcontextprotocol/node"; +import type { IncomingMessage, Server as HttpServer, ServerResponse } from "node:http"; import type { Express } from "express"; import { z } from "zod"; import { AsyncLocalStorage } from "async_hooks"; @@ -27,6 +27,11 @@ import { ApiDocs } from "./ApiDocs"; import { McpAuthentication } from "./McpAuthentication"; import { RequestGuard } from "./RequestGuard"; +/** + * Time that in-flight requests get to deliver their replies during shutdown. + */ +const SHUTDOWN_REPLY_GRACE_MS = 2_000; + /** * Session context for request-scoped data. */ @@ -121,6 +126,19 @@ export class PenpotMcpServer { * Check of the `Host` and `Origin` headers of HTTP and plugin WebSocket requests. */ public readonly requestGuard: RequestGuard; + + /** + * Whether stateless legacy requests receive a single JSON reply instead of an SSE stream + * (`PENPOT_MCP_JSON_RESPONSE=true`). + */ + private readonly jsonResponse = process.env.PENPOT_MCP_JSON_RESPONSE === "true"; + private readonly jsonLegacyTransports = new Set(); + + /** + * HTTP requests currently being handled, so that shutdown can let them deliver their replies. + */ + private readonly inFlightRequests = new Set>(); + public readonly pluginBridge: PluginBridge; private readonly replServer: ReplServer | null; private apiDocs: ApiDocs; @@ -185,7 +203,9 @@ export class PenpotMcpServer { this.connectionInstructions = this.configLoader.getBaseInstructions(); this.tools = this.initTools(); - this.mcpHandler = createMcpHandler(() => this.createMcpServer()); + this.mcpHandler = createMcpHandler(() => this.createMcpServer(), { + responseMode: this.jsonResponse ? "json" : "auto", + }); // Enable multi-instance task routing when running in multi-user mode with a // configured Redis URI. Without it, the server operates in single-instance mode, @@ -321,6 +341,28 @@ export class PenpotMcpServer { return server; } + /** + * Handles a stateless legacy request with a dedicated transport that replies with a single JSON body. + */ + private async handleJsonLegacyRequest( + req: IncomingMessage & { body?: unknown }, + res: ServerResponse + ): Promise { + const transport = new NodeStreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + enableJsonResponse: true, + }); + const server = this.createMcpServer(); + this.jsonLegacyTransports.add(transport); + try { + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + } finally { + this.jsonLegacyTransports.delete(transport); + await server.close(); + } + } + private setupHttpEndpoints(): void { const handleMcpRequest = toNodeHandler(this.mcpHandler); this.app.all("/mcp", async (req, res) => { @@ -331,9 +373,25 @@ export class PenpotMcpServer { this.logger.info( `Received MCP request: method=${req.body?.method ?? ""}; userTokenFp=${PenpotMcpServer.tokenFingerprint(authResult.userToken)}` ); - await this.sessionContext.run({ userToken: authResult.userToken }, () => - handleMcpRequest(req, res, req.body) - ); + const request = this.sessionContext.run({ userToken: authResult.userToken }, async () => { + // keep upstream's stateless legacy protocol, opting in only to JSON replies for POST; + // other methods fall through so the default handler rejects them + if ( + this.jsonResponse && + req.method === "POST" && + (await isLegacyRequest(await toWebRequest(req, req.body), req.body)) + ) { + await this.handleJsonLegacyRequest(req, res); + return; + } + await handleMcpRequest(req, res, req.body); + }); + this.inFlightRequests.add(request); + try { + await request; + } finally { + this.inFlightRequests.delete(request); + } }); } @@ -393,13 +451,33 @@ export class PenpotMcpServer { this.httpServer!.close((error) => (error ? reject(error) : resolve())); }) : Promise.resolve(); + // reject pending plugin tasks first, so that their requests can still report the unknown outcome + await this.pluginBridge.close(); + await this.awaitInFlightRequests(SHUTDOWN_REPLY_GRACE_MS); + // open SSE streams and requests exceeding the grace period would otherwise keep the server alive + this.httpServer?.closeAllConnections(); + await Promise.all([...this.jsonLegacyTransports].map((transport) => transport.close())); await this.mcpHandler.close(); await httpClosed; - await this.pluginBridge.close(); await this.redisBridge?.close(); if (this.replServer) { await this.replServer.stop(); } this.logger.info("Penpot MCP Server stopped"); } + + /** + * Waits until all in-flight HTTP requests have been handled or the given time has elapsed. + */ + private async awaitInFlightRequests(timeoutMs: number): Promise { + if (this.inFlightRequests.size === 0) { + return; + } + let timer: NodeJS.Timeout | undefined; + const timeout = new Promise((resolve) => { + timer = setTimeout(resolve, timeoutMs); + }); + await Promise.race([Promise.allSettled([...this.inFlightRequests]), timeout]); + clearTimeout(timer); + } } diff --git a/mcp/packages/server/src/PluginBridge.ts b/mcp/packages/server/src/PluginBridge.ts index 50fe62fa78..23df1483fe 100644 --- a/mcp/packages/server/src/PluginBridge.ts +++ b/mcp/packages/server/src/PluginBridge.ts @@ -547,13 +547,13 @@ export class PluginBridge implements TaskDispatchHost { * Also releases task tracking and dispatch subscriptions. */ public async close(): Promise { + for (const taskId of this.pendingTasks.keys()) { + this.rejectPendingTask(taskId, new Error("Plugin bridge is shutting down; task outcome may be unknown")); + } for (const socket of this.wsServer.clients) { this.removeConnection(socket); socket.terminate(); } - for (const taskId of this.pendingTasks.keys()) { - this.rejectPendingTask(taskId, new Error("MCP server is shutting down.")); - } await this.dispatcher.close(); return new Promise((resolve) => { this.wsServer.close(() => { diff --git a/mcp/packages/server/src/Tool.ts b/mcp/packages/server/src/Tool.ts index f6cee26a50..4a56acbeef 100644 --- a/mcp/packages/server/src/Tool.ts +++ b/mcp/packages/server/src/Tool.ts @@ -76,7 +76,9 @@ export abstract class Tool { return result; } catch (error) { this.logger.error("Tool execution #%d failed: %s; error: %s", executionId, this.getToolName(), error); - return new TextResponse(`Tool execution failed: ${String(error)}`); + const response = new TextResponse(`Tool execution failed: ${String(error)}`); + response.isError = true; + return response; } }