Skip to content

AI-native design editor. Open-source Figma alternative.

fix(mcp): complete local transport integration

Danila Poyarkov33fa9ee32033
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d1c090823..384414824 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,7 +15,7 @@
- Target a specific open document and page from live CLI and MCP automation, including sessions with multiple documents.
- Test OpenAI-compatible provider connections from AI settings with clearer setup errors.
- Build custom property panels with new Vue SDK number fields, bindable values, property sections, segmented controls, property lists, color models, fill controls, and gradient primitives.
-- Connect local MCP clients through automatically discovered private Unix sockets on macOS and Linux, with localhost TCP fallback.
+- Connect local MCP clients through automatically discovered private Unix sockets on macOS and Linux, with localhost TCP fallback. (#338)
### Changed
@@ -27,7 +27,7 @@
### Fixed
-- Keep MCP file access inside its configured root even when paths contain symlinks, and harden local authentication token checks.
+- Keep MCP file access inside its configured root even when paths contain symlinks, and harden local authentication token checks. (#338)
- Keep desktop text visible across the scene and overlay canvases, refresh it after local fonts load, and preserve rendering when a requested italic face is unavailable (#395).
- Honor node-scoped variable modes in `.fig` files so light and dark component examples keep their intended colors.
- Preserve nested instance text, visibility, paint, geometry, and clipping across repeated children and component swaps in `.fig` files.
diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts
index bac648467..a778a45a3 100644
--- a/packages/mcp/src/server.ts
+++ b/packages/mcp/src/server.ts
@@ -360,8 +360,22 @@ function buildHandle(
async function close() {
if (closePromise) return closePromise
closePromise = (async () => {
- await shutdownRuntime(browserRpc, mcpSessions, wss, state)
- await cleanupDiscovery(authToken, resolvedSocketPath, actualHttpPort, startedAt)
+ const errors: unknown[] = []
+ try {
+ // Stop advertising this process before the slower WebSocket grace
+ // period. This also makes signal-driven shutdown resilient when a
+ // parent process exits before all clients finish closing.
+ await cleanupDiscovery(authToken, resolvedSocketPath, actualHttpPort, startedAt)
+ } catch (error) {
+ errors.push(error)
+ }
+ try {
+ await shutdownRuntime(browserRpc, mcpSessions, wss, state)
+ } catch (error) {
+ errors.push(error)
+ }
+ if (errors.length === 1) throw errors[0]
+ if (errors.length > 1) throw new AggregateError(errors, 'Multiple shutdown errors')
})()
return closePromise
}
diff --git a/packages/mcp/src/server/lifecycle.ts b/packages/mcp/src/server/lifecycle.ts
index 32ab538bd..9a0759958 100644
--- a/packages/mcp/src/server/lifecycle.ts
+++ b/packages/mcp/src/server/lifecycle.ts
@@ -1,7 +1,7 @@
import { access, chmod, constants, mkdir, readFile, unlink } from 'node:fs/promises'
import { createServer } from 'node:http'
import type { Server as HttpServer } from 'node:http'
-import { connect } from 'node:net'
+import { connect, type Socket } from 'node:net'
import { dirname } from 'node:path'
import { getRequestListener } from '@hono/node-server'
@@ -20,12 +20,25 @@ import {
platformHasUnixSockets
} from '#mcp/transport/paths'
+const trackedConnections = Symbol('open-pencil-mcp-connections')
+
+type TrackedHttpServer = HttpServer & {
+ [trackedConnections]?: Set<Socket>
+}
+
/** Create an HTTP server bound to the Hono app. Each server can listen on one address. */
export function createAppServer(app: Hono): HttpServer {
const listener = getRequestListener(app.fetch)
- return createServer((req, res) => {
+ const server: TrackedHttpServer = createServer((req, res) => {
void listener(req, res)
})
+ const connections = new Set<Socket>()
+ server[trackedConnections] = connections
+ server.on('connection', (socket) => {
+ connections.add(socket)
+ socket.once('close', () => connections.delete(socket))
+ })
+ return server
}
/** Wire the HTTP upgrade handler onto a server. Each server needs its own. */
@@ -170,13 +183,18 @@ export async function writeDiscovery(
export async function closeServer(srv: HttpServer | null): Promise<void> {
if (!srv) return
- // Close all idle keep-alive connections first to prevent server.close()
- // from hanging indefinitely on persistent HTTP connections.
+ // The WebSocket grace period has already elapsed by the time listener
+ // teardown begins. Close HTTP connections and explicitly destroy upgraded
+ // sockets, which Node's closeAllConnections() intentionally does not cover.
srv.closeIdleConnections()
- // If any stubborn connections remain after 5 seconds, force-close them
- // so the server shutdown can complete. Without this, a misbehaving HTTP
- // client with an active request can block shutdown indefinitely.
+ srv.closeAllConnections()
+ const connections = (srv as TrackedHttpServer)[trackedConnections]
+ for (const socket of connections ?? []) socket.destroy()
+
+ // Keep a final bound in case a platform-specific connection escapes the
+ // tracked set or arrives during shutdown.
const forceClose = setTimeout(() => {
+ for (const socket of connections ?? []) socket.destroy()
srv.closeAllConnections()
srv.close()
}, 5_000).unref()
@@ -298,6 +316,16 @@ export async function closeWssGracefully(wss: WebSocketServer): Promise<void> {
settled = true
resolve()
}
+ // WebSocketServer.close() stops accepting connections but waits for
+ // existing clients; it does not initiate their closing handshakes.
+ // Ask clients to close first, then terminate only the stragglers.
+ for (const ws of wss.clients) {
+ try {
+ ws.close(1001, 'Server shutting down')
+ } catch (e) {
+ console.warn('[MCP] Failed to close WebSocket client:', e)
+ }
+ }
const graceTimer = setTimeout(() => {
// Snapshot clients before iterating — terminate() triggers handleClose
// which modifies wss.clients mid-iteration via clients.delete(ws).
@@ -309,6 +337,7 @@ export async function closeWssGracefully(wss: WebSocketServer): Promise<void> {
console.warn('[MCP] Failed to terminate WebSocket client:', e)
}
}
+ done()
}, 2_000).unref()
wss.close(() => {
clearTimeout(graceTimer)
diff --git a/tests/engine/mcp/server/cleanup.test.ts b/tests/engine/mcp/server/cleanup.test.ts
index 9d5a9e2df..b1961c045 100644
--- a/tests/engine/mcp/server/cleanup.test.ts
+++ b/tests/engine/mcp/server/cleanup.test.ts
@@ -1,9 +1,13 @@
-import { describe, expect, test, beforeAll, afterAll } from 'bun:test'
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
+import { existsSync } from 'node:fs'
import { mkdir, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
+import { WebSocket } from 'ws'
+
import { startServer, type ServerHandle } from '#mcp/server'
+import { getDiscoveryPath } from '#mcp/transport/paths'
import { socketRequest, type HealthResponse } from '#tests/helpers/mcp/server'
@@ -110,9 +114,38 @@ describe('MCP lifecycle failure cleanup', () => {
}
})
-// ---------------------------------------------------------------------------
-// DELETE session cleanup tests (Review 03)
-// ---------------------------------------------------------------------------
+describe('MCP graceful shutdown', () => {
+ test('removes discovery while closing connected WebSocket clients', async () => {
+ const handle = await startServer({
+ httpPort: 0,
+ withTcp: true,
+ socketPath: testSocketPath(),
+ authToken: TEST_AUTH_TOKEN,
+ enableEval: false,
+ mcpRoot: null
+ })
+ const discoveryPath = await getDiscoveryPath()
+ expect(existsSync(discoveryPath)).toBe(true)
+
+ const client = new WebSocket(`ws://127.0.0.1:${handle.httpPort}`)
+ await new Promise<void>((resolve, reject) => {
+ client.once('open', resolve)
+ client.once('error', reject)
+ })
+
+ const closing = handle.close()
+ const deadline = Date.now() + 1_000
+ while (existsSync(discoveryPath) && Date.now() < deadline) {
+ await new Promise<void>((resolve) => {
+ setTimeout(resolve, 10)
+ })
+ }
+
+ expect(existsSync(discoveryPath)).toBe(false)
+ await closing
+ expect(client.readyState).toBe(WebSocket.CLOSED)
+ })
+})
describe('MCP DELETE session cleanup', () => {
let handle: ServerHandle | undefined
diff --git a/vite/aliases.ts b/vite/aliases.ts
index 8506a7eaa..47e4af779 100644
--- a/vite/aliases.ts
+++ b/vite/aliases.ts
@@ -37,6 +37,14 @@ export function createOpenPencilAliases(rootDir: string) {
{ find: '@open-pencil/kiwi', replacement: resolve(rootDir, 'packages/kiwi/src') },
{ find: /^@open-pencil\/fig$/, replacement: resolve(rootDir, 'packages/fig/src/index.ts') },
{ find: '@open-pencil/fig', replacement: resolve(rootDir, 'packages/fig/src') },
+ {
+ find: /^@open-pencil\/mcp\/discovery$/,
+ replacement: resolve(rootDir, 'packages/mcp/src/transport/discovery.ts')
+ },
+ {
+ find: /^@open-pencil\/mcp\/transport$/,
+ replacement: resolve(rootDir, 'packages/mcp/src/transport/paths.ts')
+ },
{ find: /^@open-pencil\/vue$/, replacement: resolve(rootDir, 'packages/vue/src/index.ts') },
{ find: '@open-pencil/vue', replacement: resolve(rootDir, 'packages/vue/src') },
{ find: /^@open-pencil\/core$/, replacement: resolve(rootDir, 'packages/core/src/index.ts') },