AI-native design editor. Open-source Figma alternative.
fix(automation): wait for a slow MCP server and stop it with the app (#1257)
Niraj Sanganib5afdefc6f68
diff --git a/changes/1257/fixed.md b/changes/1257/fixed.mdnew file mode 100644index 000000000..667ea86b9--- /dev/null+++ b/changes/1257/fixed.md@@ -0,0 +1 @@+- The desktop app waits up to 20 seconds for a slow-starting MCP server instead of giving up after five, and stopping the server from the app, or quitting the app, now ends the server process too, so a leftover server no longer keeps answering after the app lets go of it (#1167).diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.tsindex 91699fd96..de01752c9 100644--- a/packages/mcp/src/index.ts+++ b/packages/mcp/src/index.ts@@ -40,7 +40,10 @@ if (process.argv.includes('--help') || process.argv.includes('-h')) {` file after no app is attached for this many ms. The\n` +` grace period starts at startup and after disconnects.\n` +` Unset/0 disables it (default) — do not set this for\n` +- ` manual/CLI use, since nothing may ever register.\n`+ ` manual/CLI use, since nothing may ever register.\n` ++ ` OPENPENCIL_MCP_EXIT_ON_STDIN_CLOSE Set to 1 to shut down when stdin closes, so a\n` ++ ` parent that starts the server through a shell wrapper\n` ++ ` can stop it by closing the pipe. Unset for manual/CLI use.\n`)process.exit(0)}@@ -132,3 +135,18 @@ const shutdown = async () => {process.on('SIGINT', () => void shutdown().catch(() => process.exit(1)))process.on('SIGTERM', () => void shutdown().catch(() => process.exit(1)))++// A parent that started this server through a shell wrapper cannot always kill it directly+// (on Windows, ending `cmd /c` leaves the process it started running), but its end of the+// stdin pipe closes with it.+if (process.env.OPENPENCIL_MCP_EXIT_ON_STDIN_CLOSE === '1') {+ let stdinClosed = false+ const onStdinClosed = () => {+ if (stdinClosed) return+ stdinClosed = true+ void shutdown().catch(() => process.exit(1))+ }+ process.stdin.on('end', onStdinClosed)+ process.stdin.on('close', onStdinClosed)+ process.stdin.resume()+}diff --git a/packages/mcp/tests/transport/stdin-close.test.ts b/packages/mcp/tests/transport/stdin-close.test.tsnew file mode 100644index 000000000..53cb74e29--- /dev/null+++ b/packages/mcp/tests/transport/stdin-close.test.ts@@ -0,0 +1,71 @@+import { afterEach, describe, expect, test } from 'bun:test'+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++const ENTRY = Bun.resolveSync('#mcp/index', import.meta.dir)+const READY = 'OpenPencil MCP server'++const cleanups: Array<() => void> = []++afterEach(() => {+ for (const cleanup of cleanups.splice(0)) cleanup()+})++/** A port nothing listens on, since Windows has no Unix socket for the server to use. */+function freePort(): number {+ const probe = Bun.serve({ port: 0, fetch: () => new Response('') })+ const { port } = probe+ void probe.stop(true)+ if (port === undefined) throw new Error('No free port was assigned')+ return port+}++/** Starts the server and waits until it reports that it is listening. */+async function startServer(env: Record<string, string>) {+ const directory = mkdtempSync(join(tmpdir(), 'op-mcp-stdin-'))+ const child = Bun.spawn(['bun', ENTRY], {+ stdin: 'pipe',+ stdout: 'ignore',+ stderr: 'pipe',+ env: {+ ...process.env,+ PORT: String(freePort()),+ OPENPENCIL_MCP_SOCKET: join(directory, 'mcp.sock'),+ OPENPENCIL_MCP_AUTH_TOKEN: '',+ ...env+ }+ })+ cleanups.push(() => {+ child.kill()+ rmSync(directory, { recursive: true, force: true })+ })+ const reader = child.stderr.getReader()+ const decoder = new TextDecoder()+ let output = ''+ while (!output.includes(READY)) {+ const { done, value } = await reader.read()+ if (done) throw new Error(`The server exited before it was ready: ${output}`)+ output += decoder.decode(value)+ }+ reader.releaseLock()+ return child+}++describe('closing the standard input of the HTTP server', () => {+ test('shuts it down when the parent asked for that', async () => {+ const child = await startServer({ OPENPENCIL_MCP_EXIT_ON_STDIN_CLOSE: '1' })+ await child.stdin.end()++ expect(await child.exited).toBe(0)+ })++ test('leaves a server started by hand running', async () => {+ // Set off explicitly, so a value the test run inherits does not turn it on.+ const child = await startServer({ OPENPENCIL_MCP_EXIT_ON_STDIN_CLOSE: '0' })+ await child.stdin.end()+ const outcome = await Promise.race([child.exited, Bun.sleep(500).then(() => 'running')])++ expect(outcome).toBe('running')+ })+})diff --git a/src/app/automation/mcp/spawn.ts b/src/app/automation/mcp/spawn.tsindex fccc9de7c..774e3dcbc 100644--- a/src/app/automation/mcp/spawn.ts+++ b/src/app/automation/mcp/spawn.ts@@ -74,6 +74,10 @@ interface MCPLookup {// prevents a server that outlives a crashed/reloaded app from squatting the// port forever while still allowing brief renderer reloads (issue #488).const MCP_APP_ATTACH_TIMEOUT_MS = 30_000+// A server started from a cold npm shim can take longer than a few seconds to answer (14.8 s on+// a Windows VM, issue #1167). The app waits this long for it, leaving the rest of the attach+// grace above for the app to connect once it does.+const MCP_STARTUP_HEALTH_DEADLINE_MS = MCP_APP_ATTACH_TIMEOUT_MS - 10_000/** Delays used while a spawned server comes up; tests shorten them. */export interface MCPStartupTiming {@@ -81,6 +85,8 @@ export interface MCPStartupTiming {earlyExitMs: number/** Delay before each of the health polls after spawning. */healthPollMs: number+ /** How long to keep polling while the child runs before giving up on it. */+ healthDeadlineMs?: number}const DEFAULT_STARTUP_TIMING: MCPStartupTiming = { earlyExitMs: 250, healthPollMs: 1000 }@@ -363,6 +369,36 @@ async function pollHealth(return null}+/**+ * Polls a server the app just started for as long as it runs, up to a deadline, so a slow start+ * is not mistaken for a failed one. Resolves to null when the deadline passes or the child exits.+ */+async function waitForHealth(+ deadlineMs: number,+ delayMs: number,+ authToken: string | null,+ childClosed: Promise<unknown>+): Promise<AutomationHealth | null> {+ const exited = childClosed.then(() => 'exited' as const)+ const giveUpAt = Date.now() + deadlineMs+ const deadline = promiseTimeout(deadlineMs).then(() => 'deadline' as const)+ for (;;) {+ const remainingMs = giveUpAt - Date.now()+ if (remainingMs <= 0) return null+ const woke = await Promise.race([+ promiseTimeout(Math.min(delayMs, remainingMs)).then(() => 'waited' as const),+ deadline,+ exited+ ])+ if (woke !== 'waited') return null+ // A probe still running at the deadline does not count.+ const health = await Promise.race([readAutomationHealth(authToken), deadline, exited])+ // An answer from a server whose process already ended does not count.+ if (health === 'deadline' || health === 'exited') return null+ if (health) return health+ }+}+export async function getAutomationAuthToken(): Promise<string | null> {if (runtimeAutomationAuthToken) return runtimeAutomationAuthTokenconst health = await readAutomationHealth()@@ -451,6 +487,23 @@ async function configureDevMCP(): Promise<AutomationServerHandle> {return { disconnect: noop, authToken, managed: true }}+function exitedStartupError(+ message: string,+ event: { code: number | null; signal: number | null },+ stderr: string+): MCPStartupError {+ const details = stderr.trim()+ return new MCPStartupError(+ `${message} (code ${event.code ?? 'null'}, signal ${event.signal ?? 'null'})${details ? `: ${details}` : '.'}`,+ mcpFailure(+ 'exited',+ compact([`code=${event.code ?? 'null'}`, `signal=${event.signal ?? 'null'}`, details]).join(+ ' '+ )+ )+ )+}+async function startMCPIfNeeded(timing: MCPStartupTiming): Promise<AutomationServerHandle | null> {runtimeAutomationStartupError = nullruntimeAutomationStartupFailure = null@@ -483,6 +536,9 @@ async function startMCPIfNeeded(timing: MCPStartupTiming): Promise<AutomationSerOPENPENCIL_MCP_TCP: '1',OPENPENCIL_MCP_ROOT: mcpRoot,OPENPENCIL_MCP_APP_TIMEOUT_MS: String(MCP_APP_ATTACH_TIMEOUT_MS),+ // Killing the shell wrapper on Windows leaves the server it started running; the app's end+ // of the pipe closes with it, and the server exits on that.+ OPENPENCIL_MCP_EXIT_ON_STDIN_CLOSE: '1',OPENPENCIL_MCP_DISABLED_TOOLS: serializeDisabledTools(disabledMCPTools.value),OPENPENCIL_MCP_SCOPE: mcpScope()}@@ -518,22 +574,16 @@ async function startMCPIfNeeded(timing: MCPStartupTiming): Promise<AutomationSerpromiseTimeout(timing.earlyExitMs).then(() => null)])if (earlyExit) {- const details = startupStderr.trim()return rememberStartupError(- new MCPStartupError(- `MCP server exited before startup completed (code ${earlyExit.code ?? 'null'}, signal ${earlyExit.signal ?? 'null'})${details ? `: ${details}` : '.'}`,- mcpFailure(- 'exited',- compact([- `code=${earlyExit.code ?? 'null'}`,- `signal=${earlyExit.signal ?? 'null'}`,- details- ]).join(' ')- )- )+ exitedStartupError('MCP server exited before startup completed', earlyExit, startupStderr))}- const health = await pollHealth(5, timing.healthPollMs, authToken)+ const health = await waitForHealth(+ timing.healthDeadlineMs ?? MCP_STARTUP_HEALTH_DEADLINE_MS,+ timing.healthPollMs,+ authToken,+ childClosed+ )if (health) {try {@@ -564,11 +614,18 @@ async function startMCPIfNeeded(timing: MCPStartupTiming): Promise<AutomationSer}}+ // A child that exited while the app waited for it is a crash, not a slow start.+ const exitedWhileWaiting = await Promise.race([childClosed, Promise.resolve(null)])try {await child.kill().catch(() => undefined)} finally {runtimeAutomationAuthToken = null}+ if (exitedWhileWaiting) {+ return rememberStartupError(+ exitedStartupError('MCP server exited before it answered', exitedWhileWaiting, startupStderr)+ )+ }return rememberStartupError(new MCPStartupError(`MCP server did not become healthy within the startup timeout${startupStderr.trim() ? `: ${startupStderr.trim()}` : '.'}`,diff --git a/tests/engine/tauri/mcp-spawn.test.ts b/tests/engine/tauri/mcp-spawn.test.tsindex 66c99851e..3eb3c96c2 100644--- a/tests/engine/tauri/mcp-spawn.test.ts+++ b/tests/engine/tauri/mcp-spawn.test.ts@@ -232,7 +232,8 @@ describe('Tauri MCP spawning', () => {OPENPENCIL_MCP_CORS_ORIGIN: 'tauri://localhost',OPENPENCIL_MCP_TCP: '1',OPENPENCIL_MCP_ROOT: '/mock/home',- OPENPENCIL_MCP_APP_TIMEOUT_MS: '30000'+ OPENPENCIL_MCP_APP_TIMEOUT_MS: '30000',+ OPENPENCIL_MCP_EXIT_ON_STDIN_CLOSE: '1'}}})@@ -274,4 +275,86 @@ describe('Tauri MCP spawning', () => {).toBe(true)expect(calls.at(-1)).toEqual({ cmd: 'plugin:shell|kill', args: { cmd: 'killChild', pid: 77 } })})++ test('keeps waiting for a server that is slow to answer while its child runs', async () => {+ installTauriMockWindow()+ Object.assign(globalThis.window, { location: { origin: 'tauri://localhost' } })+ Object.defineProperty(globalThis, 'navigator', {+ configurable: true,+ value: { platform: 'Win32', userAgent: 'Windows' }+ })++ let healthChecks = 0+ vi.spyOn(globalThis, 'fetch').mockImplementation(+ fetchStub(async () => {+ healthChecks += 1+ // Slower than the five fixed tries the app used to allow.+ if (healthChecks <= 9) return new Response('', { status: 404 })+ return new Response(+ JSON.stringify({+ status: 'ok',+ version: '0.0.0-test',+ authRequired: true,+ discoveryPath: DISCOVERY_PATH+ }),+ { status: 200 }+ )+ })+ )+ await mockTauriIPC((cmd, args) => {+ if (cmd === 'mcp_lookup')+ return { available: true, path: '/mock/bin/openpencil-mcp-http', searched: ['/mock/bin'] }+ if (cmd === 'plugin:shell|spawn') return 77+ const pathArg = (args as { path?: string })?.path+ if (cmd === 'plugin:fs|exists') return pathArg === DISCOVERY_PATH+ if (cmd === 'plugin:fs|read_text_file')+ return pathArg === DISCOVERY_PATH ? new TextEncoder().encode(DISCOVERY_JSON) : null+ if (cmd === 'plugin:path|resolve_directory') return '/mock/home'+ return null+ })++ const handle = await spawnMCPIfNeeded({+ earlyExitMs: 5,+ healthPollMs: 5,+ healthDeadlineMs: 5000+ })+ expect(handle?.managed).toBe(true)+ expect(healthChecks).toBeGreaterThan(9)+ })++ test('reports a child that exits while the app waits as exited, not as a timeout', async () => {+ installTauriMockWindow()+ Object.assign(globalThis.window, { location: { origin: 'tauri://localhost' } })+ Object.defineProperty(globalThis, 'navigator', {+ configurable: true,+ value: { platform: 'MacIntel', userAgent: 'Macintosh' }+ })++ vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('', { status: 404 }))+ await mockTauriIPC((cmd, args) => {+ if (cmd === 'mcp_lookup')+ return { available: true, path: '/mock/bin/openpencil-mcp-http', searched: ['/mock/bin'] }+ if (cmd === 'plugin:path|resolve_directory') return '/mock/home'+ if (cmd === 'plugin:fs|exists') return false+ if (cmd === 'plugin:shell|spawn') {+ const onEvent = (args as { onEvent: { onmessage: (event: unknown) => void } }).onEvent+ .onmessage+ // Past the early-exit window, before the deadline.+ setTimeout(() => onEvent({ event: 'Terminated', payload: { code: 3, signal: null } }), 40)+ return 88+ }+ return null+ })++ const handle = await spawnMCPIfNeeded({+ earlyExitMs: 5,+ healthPollMs: 5,+ healthDeadlineMs: 5000+ })+ expect(handle).toBeNull()+ expect(getAutomationStartupFailure()).toMatchObject({+ code: 'exited',+ detail: expect.stringContaining('code=3')+ })+ })})