AI-native design editor. Open-source Figma alternative.
feat(mcp): add local transport discovery
Danila Poyarkov2b32a8c7d3d9
diff --git a/AGENTS.md b/AGENTS.mdindex c8d14e099..7371a1be0 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -129,8 +129,9 @@ Release commits are the exception: keep using `Release v0.x.y`.- Registries (`registry*.ts`) assemble tool sets. Add new tools to the appropriate registry so AI chat, MCP, and CLI eval paths can see them.- AI adapter (`packages/core/src/tools/ai-adapter.ts`) converts ToolDefs to Vercel AI tools with valibot schemas. `src/app/ai/tools/index.ts` is a thin app wire that creates `FigmaAPI` from the active editor.- CLI commands in `packages/cli/src/commands/**` are not generated from ToolDefs; they own CLI UX, pagination, and agentfmt formatting. The `eval` command exposes ToolDef operations through `FigmaAPI`.-- MCP server code lives in `packages/mcp/src/server.ts`. MCP-only tools such as `open_file`, `new_document`, `save_file`, and `get_codegen_prompt` are registered there because they need server filesystem access or are not scene-graph tools.-- `open_file` and `new_document` are only registered when `OPENPENCIL_MCP_ROOT` is set. Export tools can write files under that root when given a `path`.+- MCP server code lives under `packages/mcp/src/`. MCP-only tools such as `open_file`, `new_document`, `save_file`, and `get_codegen_prompt` are registered in `tool/registration.ts` because they need server filesystem access or are not scene-graph tools.+- Local MCP transport discovery lives under `packages/mcp/src/transport/`: macOS/Linux prefer an owner-only Unix socket, Windows uses localhost TCP, and `mcp.json` advertises the active transport and token. Keep test discovery paths isolated from the user's runtime file.+- `open_file` and `new_document` are only registered when `OPENPENCIL_MCP_ROOT` is set. Export tools can write files under that root when given a `path`; path checks must resolve symlinks before filesystem access.- Core codegen prompts live as markdown under `packages/core/src/tools/prompts/`; app chat/ACP prompts live under `src/app/ai/**` markdown files.- `FigmaAPI` (`packages/core/src/figma-api/`) is the execution target for tools and CLI eval. It is Figma Plugin API compatible and uses Symbols for hidden internals.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bf30f0241..d1c090823 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +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.### Changeddiff --git a/README.md b/README.mdindex 92f175609..8fcc19daf 100644--- a/README.md+++ b/README.md@@ -206,9 +206,11 @@ For other MCP clients:**HTTP** (scripts, CI):```sh-openpencil-mcp-http # http://localhost:3100/mcp+openpencil-mcp-http # Unix socket on macOS/Linux + http://127.0.0.1:7600/mcp```+Local clients discover the private Unix socket automatically and fall back to localhost TCP. Set `PORT=0` to disable TCP on macOS/Linux.+**File access:** Set `OPENPENCIL_MCP_ROOT` to scope file operations (`open_file`, `new_document`, export `path` param) to a directory. Defaults to the current working directory.### AI agent skilldiff --git a/bun.lock b/bun.lockindex 2404ffe91..fd6f0501e 100644--- a/bun.lock+++ b/bun.lock@@ -120,6 +120,7 @@"dependencies": {"@open-pencil/core": "workspace:*","@open-pencil/dom-css": "workspace:*",+ "@open-pencil/mcp": "workspace:*","@open-pencil/scene-graph": "workspace:*","agentfmt": "^0.1.3","canvaskit-wasm": "^0.40.0",diff --git a/bunfig.toml b/bunfig.tomlnew file mode 100644index 000000000..6746ee7ae--- /dev/null+++ b/bunfig.toml@@ -0,0 +1,7 @@+# Bun configuration.+# Preload discovery-file isolation for every `bun test` run so engine tests+# never clobber the real ~/Library/Application Support/OpenPencil/mcp.json+# (which would break a running OpenPencil desktop app). See+# tests/helpers/mcp-discovery-isolation.ts for the rationale.+[test]+preload = ["./tests/helpers/mcp-discovery-isolation.ts"]diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex 68176cbdb..acd5bda91 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -29,6 +29,7 @@"dependencies": {"@open-pencil/core": "workspace:*","@open-pencil/dom-css": "workspace:*",+ "@open-pencil/mcp": "workspace:*","@open-pencil/scene-graph": "workspace:*","agentfmt": "^0.1.3","canvaskit-wasm": "^0.40.0",diff --git a/packages/cli/src/app-client.ts b/packages/cli/src/app-client.tsindex 95a38f034..53f7e58e6 100644--- a/packages/cli/src/app-client.ts+++ b/packages/cli/src/app-client.ts@@ -1,63 +1,150 @@-import { AUTOMATION_HTTP_PORT } from '@open-pencil/core/constants'+import { request as httpRequest } from 'node:http'+import type { IncomingMessage } from 'node:http'-const HEALTH_URL = `http://127.0.0.1:${AUTOMATION_HTTP_PORT}/health`-const RPC_URL = `http://127.0.0.1:${AUTOMATION_HTTP_PORT}/rpc`+import { readDiscoveryFile } from '@open-pencil/mcp/discovery'+import type { DiscoveryInfo } from '@open-pencil/mcp/discovery'+import { platformHasUnixSockets } from '@open-pencil/mcp/transport'-let cachedToken: string | null = null+/** Maximum time to wait for a single RPC request before giving up. */+const RPC_TIMEOUT_MS = 30_000-export async function getAppToken(): Promise<string> {- if (cachedToken) return cachedToken- const res = await fetch(HEALTH_URL).catch(() => null)- if (!res || !res.ok) {+let cachedInfo: DiscoveryInfo | null = null++async function resolveDiscovery(): Promise<DiscoveryInfo> {+ if (cachedInfo) return cachedInfo++ const info = await readDiscoveryFile()+ if (!info) {throw new Error(- `Could not connect to OpenPencil app on localhost:${AUTOMATION_HTTP_PORT}.\n` ++ 'Could not read MCP discovery file.\n' +'Is the app running? Start it with: bun run tauri dev')}- const data = (await res.json()) as { status: string; token?: string }- if (data.status !== 'ok' || !data.token) {- throw new Error(- 'OpenPencil app is running but no document is open.\n' +- 'Open a document in the app, or provide a .fig file path.'- )- }- cachedToken = data.token- return cachedToken++ cachedInfo = info+ return cachedInfo}-async function doRpc<T>(token: string, command: string, args: unknown): Promise<T> {- const res = await fetch(RPC_URL, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- Authorization: `Bearer ${token}`- },- body: JSON.stringify({ command, args })+function doRequest(+ info: DiscoveryInfo,+ path: string,+ method: string,+ body?: Record<string, unknown>,+ forceTcp = false+): Promise<{ status: number; data: unknown }> {+ return new Promise((resolve, reject) => {+ const bodyJson = body ? JSON.stringify(body) : undefined+ const headers: Record<string, string> = {+ ...(bodyJson ? { 'Content-Type': 'application/json' } : {}),+ ...(info.authToken ? { Authorization: `Bearer ${info.authToken}` } : {})+ }++ // Use the narrowed `useSocket` variable (string | false) to construct+ // request options so TypeScript knows socketPath is a string when truthy.+ const useSocket = !forceTcp && platformHasUnixSockets() && info.socketPath+ const reqOpts = useSocket+ ? { socketPath: useSocket, path, method, headers }+ : { hostname: '127.0.0.1', port: info.httpPort, path, method, headers }++ const req = httpRequest(reqOpts, (res: IncomingMessage) => {+ const chunks: Buffer[] = []+ res.on('data', (chunk: Buffer) => chunks.push(chunk))+ res.on('end', () => {+ clearTimeout(timer)+ const raw = Buffer.concat(chunks).toString('utf-8')+ let data: unknown+ try {+ data = JSON.parse(raw)+ } catch {+ data = raw+ }+ resolve({ status: res.statusCode ?? 500, data })+ })+ res.on('error', (err) => {+ clearTimeout(timer)+ reject(err)+ })+ })++ const timer = setTimeout(() => {+ req.destroy(new Error(`RPC request timed out after ${RPC_TIMEOUT_MS / 1000}s`))+ }, RPC_TIMEOUT_MS)++ req.on('error', (err) => {+ clearTimeout(timer)+ reject(err)+ })+ if (bodyJson) req.write(bodyJson)+ req.end()})+}- if (!res.ok) {- const body = (await res.json().catch(() => ({ error: `HTTP ${res.status}` }))) as {- error?: string- ok?: boolean- }- throw new Error(body.error ?? `RPC failed: HTTP ${res.status}`)+async function doRpc<T>(+ info: DiscoveryInfo,+ command: string,+ args: unknown,+ forceTcp = false+): Promise<T> {+ const { status, data } = await doRequest(info, '/rpc', 'POST', { command, args }, forceTcp)++ if (status === 401) {+ throw new UnauthorizedError(+ 'Unauthorized: the auth token in the MCP discovery file may be stale'+ )+ }+ if (status >= 400) {+ const errData = data as { error?: string }+ throw new Error(errData.error ?? `RPC failed: HTTP ${status}`)}- const body = (await res.json()) as { ok?: boolean; result?: T; error?: string }+ const body = data as { ok?: boolean; result?: T; error?: string }if (body.ok === false) throw new Error(body.error ?? 'RPC failed')return body.result as T}+/** Error class to distinguish auth failures for retry logic. */+class UnauthorizedError extends Error {+ constructor(message: string) {+ super(message)+ this.name = 'UnauthorizedError'+ }+}++function isSocketConnectionError(error: unknown): boolean {+ if (!(error instanceof Error)) return false+ const code = 'code' in error ? String(error.code) : ''+ return (+ code === 'ECONNREFUSED' ||+ code === 'ENOENT' ||+ code === 'FailedToOpenSocket' ||+ error.message.includes('ECONNREFUSED') ||+ error.message.includes('ENOENT')+ )+}++async function rpcWithFallback<T>(info: DiscoveryInfo, command: string, args: unknown): Promise<T> {+ try {+ return await doRpc<T>(info, command, args)+ } catch (error) {+ if (+ !platformHasUnixSockets() ||+ !info.socketPath ||+ info.httpPort <= 0 ||+ !isSocketConnectionError(error)+ ) {+ throw error+ }+ return doRpc<T>(info, command, args, true)+ }+}+export async function rpc<T = unknown>(command: string, args: unknown = {}): Promise<T> {- let token = await getAppToken()try {- return await doRpc<T>(token, command, args)+ return await rpcWithFallback<T>(await resolveDiscovery(), command, args)} catch (error) {- const message = error instanceof Error ? error.message : String(error)- if (!message.includes('Unauthorized')) throw error- cachedToken = null- token = await getAppToken()- return doRpc<T>(token, command, args)+ if (!(error instanceof UnauthorizedError) && !isSocketConnectionError(error)) throw error+ cachedInfo = null+ return rpcWithFallback<T>(await resolveDiscovery(), command, args)}}diff --git a/packages/cli/tsdown.config.ts b/packages/cli/tsdown.config.tsindex 94fbc9440..3eec91132 100644--- a/packages/cli/tsdown.config.ts+++ b/packages/cli/tsdown.config.ts@@ -11,6 +11,7 @@ export default defineConfig({outDir: './dist',treeshake: false,deps: {+ alwaysBundle: ['@open-pencil/mcp', /^@open-pencil\/mcp\//],neverBundle: ['@open-pencil/core', /^@open-pencil\/core\//, 'canvaskit-wasm', /^node:/],onlyBundle: false}diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.tsindex 3283adc03..aa59918b2 100644--- a/packages/core/src/constants.ts+++ b/packages/core/src/constants.ts@@ -336,7 +336,6 @@ export const DEFAULT_AI_PROVIDER: AIProviderID = 'openrouter'export const DEFAULT_AI_MODEL = AI_PROVIDERS[0].defaultModelexport const AUTOMATION_HTTP_PORT = 7600-export const AUTOMATION_WS_PORT = 7601export const GOOGLE_FONTS_API_KEY = 'AIzaSyD1tYDR_dUEiV-Tw1vksEhZbUytgKW5pc8'diff --git a/packages/docs/programmable/mcp-server.md b/packages/docs/programmable/mcp-server.mdindex 7f26eb550..64adb1cd3 100644--- a/packages/docs/programmable/mcp-server.md+++ b/packages/docs/programmable/mcp-server.md@@ -7,7 +7,7 @@ description: Connect Claude Code, Cursor, Windsurf, and other MCP clients to OpeOpenPencil includes an MCP (Model Context Protocol) server that lets AI coding tools — Claude Code, Cursor, Windsurf, etc. — read and modify designs through the running app.-Two transports: **stdio** for MCP clients, **HTTP** for browser extensions and scripts.+Two transports: **stdio** for MCP clients, and **Streamable HTTP** for browser extensions and scripts. On macOS and Linux, local clients prefer a private Unix domain socket; Windows and unavailable sockets fall back to localhost TCP.## Install@@ -17,7 +17,7 @@ npm install -g @open-pencil/mcp## Stdio (Claude Code, Cursor, etc.)-The stdio server connects to the running OpenPencil app via WebSocket (port 7601). Make sure the desktop app is open with a document loaded.+The stdio server discovers the running OpenPencil app automatically. It prefers the app's Unix domain socket on macOS and Linux and falls back to localhost TCP when needed. Make sure the desktop app is open with a document loaded.### Claude Code@@ -101,18 +101,22 @@ openpencil-mcp-httpOr from source: `bun packages/mcp/src/index.ts` / `npx tsx packages/mcp/src/index.ts`-Security defaults (HTTP transport):+Security defaults:-- Binds to `127.0.0.1` by default (`HOST` to override)-- `eval` tool is disabled-- File operations are limited to `OPENPENCIL_MCP_ROOT` (defaults to current working directory)-- CORS is disabled by default; set `OPENPENCIL_MCP_CORS_ORIGIN` to allow one origin-- Optional auth token: `OPENPENCIL_MCP_AUTH_TOKEN` (client sends `Authorization: Bearer <token>` or `x-mcp-token`)+- Unix socket and discovery files are created with owner-only permissions on macOS and Linux.+- TCP binds to `127.0.0.1` and uses port 7600 by default.+- Authentication is enabled by default with a generated token stored in the private discovery file.+- `eval` is disabled.+- File operations are limited to `OPENPENCIL_MCP_ROOT` (defaults to the current working directory) and reject symlink escapes.+- CORS is disabled by default; set `OPENPENCIL_MCP_CORS_ORIGIN` to allow one origin.-Server starts on port 7600 (override with `PORT` env var). Endpoints:+Set `PORT=0` to disable TCP on macOS and Linux. Windows requires TCP. Set `OPENPENCIL_MCP_SOCKET` to override the Unix socket path, or `OPENPENCIL_MCP_DISCOVERY_PATH` to override the discovery file location. To provide a stable token, set `OPENPENCIL_MCP_AUTH_TOKEN`; an explicitly empty value disables authentication and should only be used with a trusted local socket.-- `GET /health` — server status-- `POST /mcp` — MCP Streamable HTTP (SSE). Sessions via `mcp-session-id` header.+Endpoints are available over both active transports:++- `GET /health` — server and app connection status; never returns the auth token.+- `POST /rpc` — authenticated live-app automation.+- `POST /mcp` — MCP Streamable HTTP. Sessions use the `mcp-session-id` header.## Workflowdiff --git a/packages/mcp/package.json b/packages/mcp/package.jsonindex a59546b96..8655a7c07 100644--- a/packages/mcp/package.json+++ b/packages/mcp/package.json@@ -21,6 +21,18 @@"types": "./dist/stdio.d.mts","import": "./dist/stdio.mjs","default": "./dist/stdio.mjs"+ },+ "./transport": {+ "types": "./dist/transport.d.mts",+ "bun": "./src/transport/paths.ts",+ "import": "./dist/transport.mjs",+ "default": "./dist/transport.mjs"+ },+ "./discovery": {+ "types": "./dist/discovery.d.mts",+ "bun": "./src/transport/discovery.ts",+ "import": "./dist/discovery.mjs",+ "default": "./dist/discovery.mjs"}},"bin": {diff --git a/packages/mcp/src/browser-rpc.ts b/packages/mcp/src/browser-rpc.tsindex 3d360194f..aac767c63 100644--- a/packages/mcp/src/browser-rpc.ts+++ b/packages/mcp/src/browser-rpc.ts@@ -2,10 +2,12 @@ import { randomUUID } from 'node:crypto'import type { WebSocket } from 'ws'+import { isAuthorized } from '#mcp/auth'import type { RpcJsonObject } from '#mcp/json'import type { PendingRequest } from '#mcp/rpc-types'const RPC_TIMEOUT = 20_000+const APP_WAIT_TIMEOUT = 10_000const APP_NOT_CONNECTED_MESSAGE ='OpenPencil app is not connected. STOP and tell the user: "The OpenPencil desktop app is not running, no document is open, or the desktop app is connected to a different MCP server. Please start OpenPencil, open a document, and try again." Do NOT attempt to start the app yourself or retry automatically.'@@ -18,7 +20,7 @@ type BrowserRpcBridgeOptions = {type BrowserMessage = {type: stringid?: string- token?: string+ token?: unknownresult?: unknownerror?: stringok?: boolean@@ -29,7 +31,7 @@ function stripEnvelope(msg: BrowserMessage): Record<string, unknown> {return body}-function responsePayload(result: unknown): Record<string, unknown> {+function responsePayload(result: unknown): RpcJsonObject {if (result && typeof result === 'object' && !Array.isArray(result)) {return result as RpcJsonObject}@@ -60,63 +62,125 @@ function createSettler<T>(resolve: (value: T) => void, reject: (error: Error) =>export function createBrowserRpcBridge({ authToken, onConnectionChange }: BrowserRpcBridgeOptions) {const pending = new Map<string, PendingRequest>()const clients = new Set<WebSocket>()+ const connectionWaiters = new Set<PendingRequest>()+ // Track which WebSocket clients have authenticated via a valid+ // register message. Unauthenticated clients can only send register;+ // all other message types (request, response) are rejected.+ const authenticatedClients = new Set<WebSocket>()let browserWs: WebSocket | null = null- let browserToken: string | null = nulllet browserRegistered = false-- function currentRpcToken(): string | null {- return authToken ?? browserToken- }+ let bridgeClosed = falsefunction isConnected(): boolean {return Boolean(browserWs && browserRegistered)}+ function notifyConnectionWaiters() {+ for (const waiter of connectionWaiters) {+ clearTimeout(waiter.timer)+ waiter.resolve(undefined)+ }+ connectionWaiters.clear()+ }++ function rejectConnectionWaiters(reason: string) {+ for (const waiter of connectionWaiters) {+ clearTimeout(waiter.timer)+ waiter.reject(new Error(reason))+ }+ connectionWaiters.clear()+ }++ function waitForConnection(): Promise<void> {+ return new Promise<void>((resolve, reject) => {+ let waiter: PendingRequest | null = null++ const timer = setTimeout(() => {+ if (waiter) connectionWaiters.delete(waiter)+ reject(new Error(APP_NOT_CONNECTED_MESSAGE))+ }, APP_WAIT_TIMEOUT)++ waiter = {+ resolve: () => {+ clearTimeout(timer)+ resolve()+ },+ reject: (error: Error) => {+ clearTimeout(timer)+ reject(error)+ },+ timer+ }+ // Add the waiter BEFORE checking browser state to avoid a lost-wakeup+ // race: if the browser registers between sendRpc's initial check and+ // this point, notifyConnectionWaiters() will have already fired and+ // cleared the set. Without this re-check, the waiter would stall for+ // APP_WAIT_TIMEOUT even though the browser is connected.+ connectionWaiters.add(waiter)+ if (browserWs && browserWs.readyState === browserWs.OPEN && browserRegistered) {+ waiter.resolve(undefined)+ connectionWaiters.delete(waiter)+ }+ })+ }+function rejectAllPending(reason: string) {- for (const [id, req] of pending) {+ for (const [, req] of pending) {clearTimeout(req.timer)req.reject(new Error(reason))- pending.delete(id)}+ pending.clear()}- function sendRegisterToken(ws: WebSocket) {- const token = currentRpcToken()- if (token) sendJson(ws, { type: 'register', token })- }-- function broadcastRegisterToken() {- for (const client of clients) sendRegisterToken(client)+ function sendRegisterPrompt(ws: WebSocket) {+ // Send a prompt inviting the client to register as the browser.+ // IMPORTANT: Do NOT include the auth token here. On TCP, any local+ // process can connect via WebSocket — sending the secret token would+ // leak credentials to unauthenticated clients. The legitimate browser+ // app already knows the token (from the discovery file or Vite env)+ // and sends it proactively in its ws.onopen handler. The token field+ // is set to null to signal that auth is required without revealing+ // the secret. When auth is disabled (authToken === null), null is+ // still correct — it means "no token needed."+ sendJson(ws, { type: 'register', token: null })}- function handleConnection(ws: WebSocket) {- clients.add(ws)- sendRegisterToken(ws)+ function broadcastRegisterPrompt() {+ for (const client of clients) sendRegisterPrompt(client)}function sendRpc(body: Record<string, unknown>): Promise<unknown> {+ if (bridgeClosed) return Promise.reject(new Error('Server shutting down'))return new Promise((resolve, reject) => {- const ws = browserWs- if (!ws || ws.readyState !== ws.OPEN || !browserRegistered) {- reject(new Error(APP_NOT_CONNECTED_MESSAGE))- return- }- const id = randomUUID()- const settle = createSettler(resolve, reject)- const timer = setTimeout(() => {- pending.delete(id)- settle.reject(new Error(`RPC timeout (${Math.round(RPC_TIMEOUT / 1000)}s)`))- }, RPC_TIMEOUT)- pending.set(id, { resolve: settle.resolve, reject: settle.reject, timer })- try {- ws.send(JSON.stringify({ type: 'request', id, ...body }))- } catch (e) {- clearTimeout(timer)- pending.delete(id)- if (!settle.isSettled()) {- settle.reject(e instanceof Error ? e : new Error(String(e)))+ const doSend = () => {+ const ws = browserWs+ if (!ws || ws.readyState !== ws.OPEN || !browserRegistered) {+ reject(new Error(APP_NOT_CONNECTED_MESSAGE))+ return+ }+ const id = randomUUID()+ const settle = createSettler(resolve, reject)+ const timer = setTimeout(() => {+ pending.delete(id)+ settle.reject(new Error(`RPC timeout (${Math.round(RPC_TIMEOUT / 1000)}s)`))+ }, RPC_TIMEOUT)+ pending.set(id, { resolve: settle.resolve, reject: settle.reject, timer })+ try {+ ws.send(JSON.stringify({ ...body, type: 'request', id }))+ } catch (e) {+ clearTimeout(timer)+ pending.delete(id)+ if (!settle.isSettled()) {+ settle.reject(e instanceof Error ? e : new Error(String(e)))+ }}}++ if (browserWs && browserWs.readyState === browserWs.OPEN && browserRegistered) {+ doSend()+ } else {+ void waitForConnection().then(doSend).catch(reject)+ }})}@@ -124,7 +188,7 @@ export function createBrowserRpcBridge({ authToken, onConnectionChange }: Browseif (!msg.id) returntry {const result = await sendRpc(stripEnvelope(msg))- sendJson(ws, { type: 'response', id: msg.id, ok: true, ...responsePayload(result) })+ sendJson(ws, { ...responsePayload(result), type: 'response', id: msg.id, ok: true })} catch (e) {sendJson(ws, {type: 'response',@@ -135,21 +199,30 @@ export function createBrowserRpcBridge({ authToken, onConnectionChange }: Browse}}- function registerBrowser(ws: WebSocket, token: string) {- if (authToken && token !== authToken) {+ function registerBrowser(ws: WebSocket, token: string | null) {+ if (bridgeClosed) return+ if (!isAuthorized(token, authToken)) {ws.close()return}+ // Mark this client as authenticated — it can now send requests.+ authenticatedClients.add(ws)const previousBrowserWs = browserWsbrowserWs = ws- browserToken = tokenbrowserRegistered = true- if (previousBrowserWs && previousBrowserWs !== ws && previousBrowserWs.readyState === ws.OPEN) {- previousBrowserWs.close()+ if (previousBrowserWs && previousBrowserWs !== ws) {+ // Reject in-flight requests to the old browser. Without this, pending+ // requests sit in the pending map until RPC_TIMEOUT (20s), because+ // handleClose for the old socket returns early (browserWs is already+ // set to the new socket, so browserWs !== previousBrowserWs).rejectAllPending('Browser reconnected')+ if (previousBrowserWs.readyState === ws.OPEN) {+ previousBrowserWs.close()+ }}+ notifyConnectionWaiters()onConnectionChange()- broadcastRegisterToken()+ broadcastRegisterPrompt()}function handleBrowserResponse(msg: BrowserMessage, ws: WebSocket) {@@ -158,21 +231,60 @@ export function createBrowserRpcBridge({ authToken, onConnectionChange }: Browseif (!req) returnpending.delete(msg.id)clearTimeout(req.timer)- if (msg.ok === false) req.reject(new Error(msg.error ?? 'RPC failed'))- else req.resolve(stripEnvelope(msg))+ if (msg.ok === false) {+ req.reject(new Error(msg.error ?? 'RPC failed'))+ } else {+ req.resolve(stripEnvelope(msg))+ }}function handleMessage(data: string, ws: WebSocket) {- let msg: BrowserMessage+ if (bridgeClosed) return+ let parsed: unknowntry {- msg = JSON.parse(data) as BrowserMessage+ parsed = JSON.parse(data)} catch (e) {console.warn('Malformed automation message:', e)return}+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ ws.close()+ return+ }+ const msg = parsed as BrowserMessage++ if (msg.type === 'auth') {+ // Authenticate a stdio bridge client without registering it as the+ // browser app. This lets the client send request/response messages+ // without becoming the RPC target. The token is validated the same+ // way as registerBrowser — when auth is disabled (authToken === null),+ // any token is accepted.+ if (msg.token === null || typeof msg.token === 'string') {+ if (!isAuthorized(msg.token, authToken)) {+ ws.close()+ return+ }+ authenticatedClients.add(ws)+ } else if (msg.token !== undefined) {+ ws.close()+ }+ return+ }- if (msg.type === 'register' && msg.token) {- registerBrowser(ws, msg.token)+ if (msg.type === 'register') {+ if (msg.token === null || typeof msg.token === 'string') {+ registerBrowser(ws, msg.token)+ } else if (msg.token !== undefined) {+ ws.close()+ }+ return+ }+ // All non-register messages require authentication. Without this+ // check, an unauthenticated WebSocket client (that hasn't sent a+ // valid register message) could bypass the HTTP auth on /rpc by+ // sending request messages over the WebSocket directly.+ if (!authenticatedClients.has(ws)) {+ ws.close()return}if (msg.type === 'request') {@@ -184,26 +296,48 @@ export function createBrowserRpcBridge({ authToken, onConnectionChange }: Browsefunction handleClose(ws: WebSocket) {clients.delete(ws)+ authenticatedClients.delete(ws)if (browserWs !== ws) returnbrowserWs = null- browserToken = nullbrowserRegistered = falserejectAllPending('Browser disconnected')+ // Intentionally NOT rejecting connectionWaiters here. If a request+ // entered waitForConnection() before the close event (e.g. during a+ // CLOSING→CLOSED transition), the waiter should keep waiting the full+ // APP_WAIT_TIMEOUT for a reconnect. registerBrowser will resolve it+ // via notifyConnectionWaiters if the browser reconnects in time.onConnectionChange()}+ function handleConnection(ws: WebSocket) {+ if (bridgeClosed) return+ clients.add(ws)+ // Transport security restricts WHO can connect: Unix socket with+ // 0o600 permissions (same-user only) or TCP localhost (any local+ // process). The authenticatedClients set gates WHAT connected clients+ // can do: only those that sent a valid register message may forward+ // requests. The register prompt does NOT include the auth token —+ // the browser app sends the token proactively (from the discovery+ // file or Vite env).+ sendRegisterPrompt(ws)+ }+function close() {+ bridgeClosed = truerejectAllPending('Server shutting down')+ rejectConnectionWaiters('Server shutting down')+ browserWs = null+ browserRegistered = falseclients.clear()+ authenticatedClients.clear()}return {close,- currentRpcToken,- handleClose,+ isConnected,+ sendRpc,handleConnection,handleMessage,- isConnected,- sendRpc+ handleClose}}diff --git a/packages/mcp/src/http-options.ts b/packages/mcp/src/http-options.tsindex cf8191d86..9542c8f66 100644--- a/packages/mcp/src/http-options.ts+++ b/packages/mcp/src/http-options.ts@@ -1,5 +1,7 @@export const MCP_CORS_METHODS = ['GET', 'POST', 'DELETE', 'OPTIONS']+// x-mcp-token: OpenPencil extension for MCP clients that cannot set the+// Authorization header (e.g. some IDE plugins). Not part of the MCP spec.export const MCP_CORS_HEADERS = ['Content-Type','Authorization',diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.tsindex 2edc7bf84..75e4efcc7 100644--- a/packages/mcp/src/index.ts+++ b/packages/mcp/src/index.ts@@ -1,31 +1,82 @@#!/usr/bin/env node-import { serve } from '@hono/node-server'--import { startServer } from './server.js'+import { startServer } from '#mcp/server'if (process.argv.includes('--help') || process.argv.includes('-h')) {process.stdout.write(- `openpencil-mcp-http\n\nStart the OpenPencil MCP HTTP and WebSocket server.\n\nOptions:\n --help, -h Show this help message\n`+ `openpencil-mcp-http\n\n` ++ `Start the OpenPencil MCP server.\n\n` ++ `On macOS/Linux, the server listens on a Unix domain socket by default\n` ++ `with optional TCP for browser clients. On Windows, only TCP is available.\n\n` ++ `Options:\n` ++ ` --help, -h Show this help message\n\n` ++ `Environment variables:\n` ++ ` PORT TCP port (default: 7600, set to 0 to disable TCP)\n` ++ ` OPENPENCIL_MCP_SOCKET Override Unix socket path (recorded in the discovery file)\n` ++ ` OPENPENCIL_MCP_DISCOVERY_PATH Override discovery file (mcp.json) location; defaults to the\n` ++ ` platform path. Parent dir created 0o700. Mainly for test isolation.\n` ++ ` OPENPENCIL_MCP_TCP Deprecated — TCP is controlled by PORT (>0 = on, 0 = off)\n` ++ ` OPENPENCIL_MCP_AUTH_TOKEN Bearer token for MCP and RPC auth\n` ++ ` OPENPENCIL_MCP_ROOT Allowed directory for file-scoped tools (default: current working directory)\n` ++ ` OPENPENCIL_MCP_EVAL Set to 1 to enable the eval tool\n` ++ ` OPENPENCIL_MCP_CORS_ORIGIN Allowed CORS origin\n`)process.exit(0)}-const port = Number.parseInt(process.env.PORT ?? '7600', 10)-const wsPort = Number.parseInt(process.env.WS_PORT ?? '7601', 10)-const host = process.env.HOST ?? '127.0.0.1'+const rawPortText = (process.env.PORT ?? '7600').trim()+// Reject non-digit strings (including hex like "0x50" and partially-numeric like+// "7600abc") — Number.parseInt would silently parse these, masking misconfig.+if (!/^\d+$/.test(rawPortText)) {+ process.stderr.write(`Error: PORT must be an integer in 0–65535, got "${process.env.PORT}"\n`)+ process.exit(1)+}+const rawPort = Number.parseInt(rawPortText, 10)+// Validate PORT: must be an integer in 0–65535. 0 means "disable TCP".+if (rawPort < 0 || rawPort > 65535) {+ process.stderr.write(`Error: PORT must be an integer in 0–65535, got "${process.env.PORT}"\n`)+ process.exit(1)+}+const port = rawPort+// OPENPENCIL_MCP_TCP is accepted for backward compat but has no effect —+// the PORT value alone determines whether TCP is enabled (PORT=0 is the kill switch).+const withTcp = port > 0-const { app, httpPort } = startServer({- httpPort: port,- wsPort,+const handle = await startServer({+ httpPort: withTcp ? port : 0,+ withTcp,+ socketPath: process.env.OPENPENCIL_MCP_SOCKET?.trim() || null,enableEval: process.env.OPENPENCIL_MCP_EVAL === '1',mcpRoot: process.env.OPENPENCIL_MCP_ROOT?.trim() || process.cwd(),- authToken: process.env.OPENPENCIL_MCP_AUTH_TOKEN?.trim() || null,+ // Auth token: undefined → auto-generate, empty string → disable auth,+ // non-empty → use trimmed value. Whitespace-only is rejected to prevent a+ // silent fallback to an auto-generated token when the operator intended to+ // set an explicit one.+ authToken: (() => {+ const raw = process.env.OPENPENCIL_MCP_AUTH_TOKEN+ if (raw === undefined) return undefined+ if (raw === '') return null+ const trimmed = raw.trim()+ if (!trimmed) {+ process.stderr.write(+ 'Error: OPENPENCIL_MCP_AUTH_TOKEN is whitespace-only. Set a real token, or use an empty string to disable auth.\n'+ )+ process.exit(1)+ }+ return trimmed+ })(),corsOrigin: process.env.OPENPENCIL_MCP_CORS_ORIGIN?.trim() || null})-serve({ fetch: app.fetch, port: httpPort, hostname: host })-process.stderr.write(`OpenPencil MCP server\n`)-process.stderr.write(` HTTP: http://${host}:${httpPort}\n`)-process.stderr.write(` WS: ws://${host}:${wsPort}\n`)-process.stderr.write(` MCP: http://${host}:${httpPort}/mcp\n`)+if (handle.socketPath) process.stderr.write(` Socket: ${handle.socketPath}\n`)+if (handle.httpPort) process.stderr.write(` HTTP: http://127.0.0.1:${handle.httpPort}\n`)++// Graceful shutdown on signals+const shutdown = async () => {+ process.stderr.write('\nShutting down MCP server...\n')+ await handle.close()+ process.exit(0)+}++process.on('SIGINT', () => void shutdown().catch(() => process.exit(1)))+process.on('SIGTERM', () => void shutdown().catch(() => process.exit(1)))diff --git a/packages/mcp/src/lifecycle.ts b/packages/mcp/src/lifecycle.tsnew file mode 100644index 000000000..32ab538bd--- /dev/null+++ b/packages/mcp/src/lifecycle.ts@@ -0,0 +1,352 @@+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 { dirname } from 'node:path'++import { getRequestListener } from '@hono/node-server'+import type { Hono } from 'hono'+import type { WebSocketServer } from 'ws'++import {+ removeDiscoveryFile,+ removeStaleSocket,+ writeDiscoveryFile+} from '#mcp/transport/discovery'+import {+ getDiscoveryPath,+ getSocketDir,+ getSocketPath,+ platformHasUnixSockets+} from '#mcp/transport/paths'++/** 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) => {+ void listener(req, res)+ })+}++/** Wire the HTTP upgrade handler onto a server. Each server needs its own. */+function wireUpgrade(server: HttpServer, wss: WebSocketServer) {+ server.on('upgrade', (request, socket, head) => {+ wss.handleUpgrade(request, socket, head, (ws) => {+ wss.emit('connection', ws, request)+ })+ })+}++/** Start socket listener; returns the resolved socket path, or null if skipped. */+export async function startSocketListener(+ app: Hono,+ wss: WebSocketServer,+ socketPathOverride: string | null+): Promise<{ server: HttpServer; resolvedPath: string } | null> {+ // Unix domain sockets are not available on Windows — always use TCP there,+ // even when a socketPath override is provided.+ if (!platformHasUnixSockets()) return null++ const resolvedPath = socketPathOverride ?? (await getSocketPath())+ if (socketPathOverride) {+ // Create the parent directory for the caller-provided socket path.+ // For newly-created parent directories, request mode 0o700 to restrict+ // access to the same OS user; existing directories are left unchanged+ // (mkdir with recursive:true does not chmod existing dirs). The socket+ // file itself is later chmodded to 0o600, and the auth token provides+ // the primary defense against unauthorized access.+ await mkdir(dirname(resolvedPath), { recursive: true, mode: 0o700 })+ } else {+ // Ensure the default platform socket directory exists.+ await getSocketDir()+ }+ await removeStaleSocket(resolvedPath)++ // Bun on Linux silently replaces existing Unix socket files on listen().+ // If removeStaleSocket left the file in place (live server detected),+ // throw EADDRINUSE to match Node.js/macOS behavior.+ const socketStillExists = await access(resolvedPath, constants.F_OK)+ .then(() => true)+ .catch(() => false)+ if (socketStillExists) {+ const err = new Error(+ `listen EADDRINUSE: address already in use ${resolvedPath}`+ ) as NodeJS.ErrnoException+ err.code = 'EADDRINUSE'+ throw err+ }++ const server = createAppServer(app)+ wireUpgrade(server, wss)++ const ss = server+ ss.on('error', (err) => console.error('[MCP] Socket server error:', err))+ await new Promise<void>((resolve, reject) => {+ ss.on('error', reject)+ ss.listen(resolvedPath, () => {+ ss.off('error', reject)+ resolve()+ })+ }).catch((err) => {+ ss.removeAllListeners('error')+ server.close(() => {+ void 0+ })+ throw err+ })++ // NOTE: There is a brief TOCTOU window between listen() and chmod() below+ // where the socket file has default permissions (subject to process umask).+ // The auth token mitigates this — unauthenticated requests get 401 — but a+ // same-user process could connect before chmod. This is accepted as a known+ // limitation; calling process.umask(0o077) would close the window but has+ // global side effects.++ try {+ await chmod(resolvedPath, 0o600)+ } catch (e) {+ // Fail closed: if we cannot restrict socket permissions, refuse to+ // serve on this socket. A world-readable socket with auth disabled+ // (OPENPENCIL_MCP_AUTH_TOKEN="") is a security hole.+ await closeServer(server).catch(() => undefined)+ await cleanupSocket(resolvedPath).catch(() => undefined)+ throw new Error(+ `Socket chmod failed — refusing to serve with insecure permissions: ${e instanceof Error ? e.message : String(e)}`+ )+ }++ return { server, resolvedPath }+}++/** Start TCP listener; returns the server and actual port, or null if skipped. */+export async function startTcpListener(+ app: Hono,+ wss: WebSocketServer,+ httpPort: number+): Promise<{ server: HttpServer; port: number } | null> {+ const host = '127.0.0.1'+ const server = createAppServer(app)+ wireUpgrade(server, wss)++ const ts = server+ ts.on('error', (err) => console.error('[MCP] TCP server error:', err))+ const actualPort = await new Promise<number>((resolve, reject) => {+ ts.on('error', reject)+ ts.listen(httpPort, host, () => {+ ts.off('error', reject)+ const addr = ts.address()+ const port = typeof addr === 'object' && addr ? addr.port : httpPort+ resolve(port)+ })+ }).catch((err) => {+ ts.removeAllListeners('error')+ server.close(() => {+ void 0+ })+ throw err+ })++ return { server, port: actualPort }+}++export async function writeDiscovery(+ resolvedSocketPath: string | null,+ actualHttpPort: number,+ authToken: string | null,+ version: string+): Promise<string> {+ const startedAt = new Date().toISOString()+ await writeDiscoveryFile({+ pid: process.pid,+ socketPath: resolvedSocketPath,+ httpPort: actualHttpPort,+ authRequired: authToken !== null,+ authToken,+ version,+ startedAt+ })+ return startedAt+}++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.+ 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.+ const forceClose = setTimeout(() => {+ srv.closeAllConnections()+ srv.close()+ }, 5_000).unref()+ try {+ await new Promise<void>((resolve) => {+ srv.close(() => resolve())+ })+ } finally {+ clearTimeout(forceClose)+ }+}++export async function cleanupSocket(socketPath: string | null): Promise<void> {+ if (!socketPath || !platformHasUnixSockets()) return+ // Only remove the socket if no other server is listening on it.+ // A replacement server that won the restart race may have already+ // bound the same path — unlinking it would kill the replacement.+ try {+ const alive = await new Promise<boolean>((resolve) => {+ let settled = false+ const finish = (value: boolean) => {+ if (settled) return+ settled = true+ client.destroy()+ resolve(value)+ }+ const client = connect(socketPath)+ .on('connect', () => finish(true))+ .on('error', (err: NodeJS.ErrnoException) => {+ // Only ECONNREFUSED and ENOENT mean "nobody is listening".+ // All other errors (EACCES, ECONNRESET, etc.) are treated as+ // "alive" to avoid unlinking a live replacement server's socket.+ const isDead = err.code === 'ECONNREFUSED' || err.code === 'ENOENT'+ finish(!isDead)+ })+ // Fail fast — we only need to know if something is listening.+ // Treat timeout as inconclusive (alive) rather than dead: during+ // system restarts or high load, a timeout doesn't reliably indicate+ // nobody is listening. Being conservative prevents unlinking a live+ // replacement server's socket.+ client.setTimeout(500, () => finish(true))+ })+ if (alive) return // Another server owns this socket — leave it alone.+ } catch {+ // Connection test itself failed (unlikely) — fall through to unlink.+ void 0+ }+ try {+ await unlink(socketPath)+ } catch (e) {+ if (e instanceof Error && 'code' in e && (e as NodeJS.ErrnoException).code !== 'ENOENT') {+ process.stderr.write(` Socket: cleanup warning (${e.message})\n`)+ }+ }+}++export async function cleanupDiscovery(+ ownAuthToken: string | null,+ ownSocketPath: string | null,+ ownHttpPort: number,+ ownStartedAt: string+): Promise<void> {+ // Only remove the discovery file if it was written by this server instance.+ // Without this guard, closing one of two concurrent servers can delete the+ // other's discovery file, breaking auto-discovery for the surviving server.+ // We verify all four identifying fields (authToken, socketPath, httpPort,+ // startedAt) to handle the case where authToken is null (auth disabled) and+ // two servers share the same null token. The startedAt timestamp uniquely+ // identifies the instance since two servers starting at the exact same+ // millisecond is extremely unlikely.+ const discoveryPath = await getDiscoveryPath()+ try {+ const raw = await readFile(discoveryPath, 'utf-8')+ const parsed = JSON.parse(raw)+ if (!parsed || typeof parsed !== 'object') return+ const info = parsed as {+ authToken: string | null+ socketPath?: string | null+ httpPort?: number+ startedAt?: string+ }+ if (info.authToken !== ownAuthToken) return+ if (info.socketPath !== ownSocketPath) return+ if (info.httpPort !== ownHttpPort) return+ if (info.startedAt !== ownStartedAt) return+ } catch {+ return+ }+ await removeDiscoveryFile().catch((e) => {+ process.stderr.write(` Discovery: cleanup warning (${e instanceof Error ? e.message : e})\n`)+ })+}++export interface ListenerState {+ socketResult: { server: HttpServer; resolvedPath: string } | null+ tcpResult: { server: HttpServer; port: number } | null+}++export async function teardownListeners(state: ListenerState): Promise<void> {+ if (state.socketResult) {+ await closeServer(state.socketResult.server)+ await cleanupSocket(state.socketResult.resolvedPath)+ }+ if (state.tcpResult) {+ await closeServer(state.tcpResult.server)+ }+}++/**+ * Close the WebSocket server with a grace period. Prevents new connections,+ * then terminates any lingering clients after 2 seconds to ensure shutdown+ * completes promptly even with unresponsive clients.+ */+export async function closeWssGracefully(wss: WebSocketServer): Promise<void> {+ await new Promise<void>((resolve) => {+ let settled = false+ const done = () => {+ if (settled) return+ settled = true+ resolve()+ }+ const graceTimer = setTimeout(() => {+ // Snapshot clients before iterating — terminate() triggers handleClose+ // which modifies wss.clients mid-iteration via clients.delete(ws).+ const snapshot = [...wss.clients]+ for (const ws of snapshot) {+ try {+ ws.terminate()+ } catch (e) {+ console.warn('[MCP] Failed to terminate WebSocket client:', e)+ }+ }+ }, 2_000).unref()+ wss.close(() => {+ clearTimeout(graceTimer)+ done()+ })+ })+}++export async function tryStartTcp(+ app: Hono,+ wss: WebSocketServer,+ httpPort: number,+ state: ListenerState+): Promise<{ server: HttpServer; port: number } | null> {+ try {+ return await startTcpListener(app, wss, httpPort)+ } catch (err) {+ // If TCP listener fails after the socket listener succeeded, close the+ // socket listener and clean up the socket file to avoid a leak.+ await teardownListeners(state)+ throw err+ }+}++export async function tryWriteDiscovery(+ resolvedSocketPath: string | null,+ actualHttpPort: number,+ authToken: string | null,+ version: string,+ state: ListenerState+): Promise<string> {+ try {+ return await writeDiscovery(resolvedSocketPath, actualHttpPort, authToken, version)+ } catch (err) {+ // If discovery file write fails after both listeners are up, tear down+ // both listeners so we never advertise a running server that clients+ // can't find via the discovery file.+ await teardownListeners(state)+ throw err+ }+}diff --git a/packages/mcp/src/mcp-sessions.ts b/packages/mcp/src/mcp-sessions.tsindex be89de74e..6d5af1421 100644--- a/packages/mcp/src/mcp-sessions.ts+++ b/packages/mcp/src/mcp-sessions.ts@@ -3,7 +3,10 @@ import { randomUUID } from 'node:crypto'import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'-export type MCPTransport = { handleRequest: (request: Request) => Promise<Response> }+export type MCPTransport = {+ handleRequest: (request: Request) => Promise<Response>+ close: () => Promise<void>+}type MCPSession = {transport: MCPTransport@@ -18,12 +21,57 @@ type McpSessionManagerOptions = {const MAX_MCP_SESSIONS = 10const MCP_SESSION_TTL_MS = 15 * 60_000+const SESSION_CLOSE_TIMEOUT_MS = 5_000++function describeError(e: unknown): string {+ return e instanceof Error ? e.message : String(e)+}++/**+ * Wraps a promise with a timeout. Resolves with undefined if the timeout+ * elapses before the promise settles. Used to prevent `transport.close()`+ * from hanging indefinitely — the MCP SDK's close() does not enforce a+ * timeout internally.+ */+function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {+ let timer: ReturnType<typeof setTimeout> | undefined+ return Promise.race([+ promise.finally(() => {+ if (timer) clearTimeout(timer)+ }),+ new Promise<T | undefined>((resolve) => {+ timer = setTimeout(() => resolve(undefined), ms)+ })+ ])+}++async function closeSession(session: MCPSession): Promise<void> {+ try {+ await withTimeout(session.transport.close(), SESSION_CLOSE_TIMEOUT_MS)+ } catch (e) {+ // Best-effort: the transport may already be closed or in a bad state+ process.stderr.write(` MCP session: transport close warning (${describeError(e)})\n`)+ }+ try {+ await withTimeout(session.server.close(), SESSION_CLOSE_TIMEOUT_MS)+ } catch (e) {+ // Best-effort+ process.stderr.write(` MCP session: server close warning (${describeError(e)})\n`)+ }+}export function createMcpSessionManager({serverVersion,registerTools}: McpSessionManagerOptions) {const sessions = new Map<string, MCPSession>()+ const closing = new Set<Promise<void>>()++ function scheduleClose(session: MCPSession): Promise<void> {+ const task = closeSession(session).finally(() => closing.delete(task))+ closing.add(task)+ return task+ }function notifyToolsChanged() {for (const session of sessions.values()) {@@ -40,30 +88,88 @@ export function createMcpSessionManager({for (const [id, session] of sessions) {if (now - session.lastSeen > MCP_SESSION_TTL_MS) {sessions.delete(id)+ void scheduleClose(session)}}}- function createSession(id: string): MCPTransport {- const server = new McpServer({ name: 'open-pencil', version: serverVersion })- registerTools(server)+ const creating = new Map<string, Promise<MCPTransport>>()+ let closed = false- const transport = new WebStandardStreamableHTTPServerTransport({- sessionIdGenerator: () => id,- enableJsonResponse: true- })- void server.connect(transport)- sessions.set(id, { transport, server, lastSeen: Date.now() })- return transport+ async function createSession(id: string): Promise<MCPTransport> {+ if (closed) throw new Error('Session manager is closed')+ const inFlight = creating.get(id)+ if (inFlight) return inFlight++ const promise = (async () => {+ const server = new McpServer({ name: 'open-pencil', version: serverVersion })+ registerTools(server)++ const transport = new WebStandardStreamableHTTPServerTransport({+ sessionIdGenerator: () => id,+ enableJsonResponse: true+ })+ // Await the MCP handshake before storing/returning the transport so+ // handleRequest cannot race the SDK's initialization on a fresh+ // session. Without this, the /mcp route calls resolveTransport() and+ // immediately awaits handleRequest(), which can fail if connect() has+ // not completed yet.+ try {+ await server.connect(transport)+ } catch (e) {+ await transport.close().catch(() => undefined)+ await server.close().catch(() => undefined)+ throw e+ }+ // `closed` is mutated by clear() which can run concurrently — TypeScript's+ // control-flow analysis can't track this cross-closure mutation.+ // oxlint-disable-next-line no-unnecessary-condition+ if (closed) {+ // Manager was closed while we were connecting — clean up immediately.+ await transport.close().catch(() => undefined)+ await server.close().catch(() => undefined)+ throw new Error('Session manager closed during session creation')+ }+ sessions.set(id, { transport, server, lastSeen: Date.now() })+ return transport+ })()++ creating.set(id, promise)+ try {+ return await promise+ } finally {+ creating.delete(id)+ }}- function resolveTransport(sessionId: string | undefined): MCPTransport | { error: 'too_many' } {+ function resolveTransport(+ sessionId: string | undefined+ ): Promise<MCPTransport | { error: 'too_many' | 'closed' }> {+ if (closed) return Promise.resolve({ error: 'closed' })cleanupExpired()const existing = sessionId ? sessions.get(sessionId) : undefined- if (!existing && sessions.size >= MAX_MCP_SESSIONS) {- return { error: 'too_many' }+ if (existing) return Promise.resolve(existing.transport)+ // Reuse an in-flight creation for the same sessionId before enforcing the cap.+ if (sessionId) {+ const inFlight = creating.get(sessionId)+ if (inFlight) {+ // Wrap with the same catch as createSession so clear() during+ // in-flight creation returns { error: 'closed' } instead of throwing.+ return inFlight.catch((e) => {+ if (closed) return { error: 'closed' as const }+ throw e+ })+ }+ }+ if (sessions.size + creating.size + closing.size >= MAX_MCP_SESSIONS) {+ return Promise.resolve({ error: 'too_many' })}- return existing?.transport ?? createSession(sessionId ?? randomUUID())+ return createSession(sessionId ?? randomUUID()).catch((e) => {+ // If the manager was closed during session creation, return the structured+ // error instead of letting the throw escape as a route-level 500.+ if (closed) return { error: 'closed' as const }+ throw e+ })}function touch(sessionId: string | undefined, transport: MCPTransport) {@@ -74,13 +180,45 @@ export function createMcpSessionManager({if (session) session.lastSeen = Date.now()}+ /**+ * Look up an existing session's transport without creating a new session.+ * Used for DELETE requests where creating a session just to delete it+ * would waste a session slot.+ */+ function getExistingTransport(+ sessionId: string | undefined+ ): MCPTransport | { error: 'not_found' | 'closed' } {+ if (closed) return { error: 'closed' }+ if (!sessionId) return { error: 'not_found' }+ const existing = sessions.get(sessionId)+ if (existing) return existing.transport+ return { error: 'not_found' }+ }+function deleteSession(sessionId: string | undefined) {- if (sessionId) sessions.delete(sessionId)+ if (closed) return+ if (!sessionId) return+ const session = sessions.get(sessionId)+ if (!session) return+ sessions.delete(sessionId)+ void scheduleClose(session)}- function clear() {+ async function clear() {+ closed = true+ // Collect sessions before awaiting in-flight creations so new sessions+ // can't be added during shutdown.+ const all = [...sessions.values()]sessions.clear()+ // Wait for in-flight session creations to finish (they will check+ // `closed` and clean up without storing the session).+ const inFlight = [...creating.values()]+ await Promise.allSettled(inFlight)+ creating.clear()+ // Await both previously-scheduled closes (from cleanupExpired/deleteSession)+ // and closes for sessions still alive at clear() time.+ await Promise.allSettled([...closing, ...all.map(scheduleClose)])}- return { clear, deleteSession, notifyToolsChanged, resolveTransport, touch }+ return { clear, deleteSession, getExistingTransport, notifyToolsChanged, resolveTransport, touch }}diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.tsindex 15c637c4b..a5cd47ad9 100644--- a/packages/mcp/src/server.ts+++ b/packages/mcp/src/server.ts@@ -1,3 +1,6 @@+import { randomBytes } from 'node:crypto'+import type { Server as HttpServer } from 'node:http'+import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'import { Hono } from 'hono'import { cors } from 'hono/cors'@@ -5,15 +8,25 @@ import { resolveCommand } from 'package-manager-detector/commands'import { detect, getUserAgent } from 'package-manager-detector/detect'import { WebSocketServer, type WebSocket } from 'ws'+import { bearerToken, isAuthorized, mcpRequestToken } from '#mcp/auth'+import { createBrowserRpcBridge } from '#mcp/browser-rpc'+import { MCP_CORS_HEADERS, MCP_CORS_METHODS, MCP_EXPOSED_HEADERS } from '#mcp/http-options'import type { RpcJsonObject } from '#mcp/json'+import { preprocessRpc } from '#mcp/jsx-preprocess'+import { createMcpSessionManager } from '#mcp/mcp-sessions'+import { registerTools } from '#mcp/tool/registration'import packageJson from '../package.json' with { type: 'json' }-import { bearerToken, isAuthorized, mcpRequestToken } from './auth'-import { createBrowserRpcBridge } from './browser-rpc'-import { MCP_CORS_HEADERS, MCP_CORS_METHODS, MCP_EXPOSED_HEADERS } from './http-options'-import { preprocessRpc } from './jsx-preprocess'-import { createMcpSessionManager } from './mcp-sessions'-import { registerTools } from './tool/registration'+import {+ type ListenerState,+ cleanupDiscovery,+ closeWssGracefully,+ createAppServer,+ startSocketListener,+ teardownListeners,+ tryStartTcp,+ tryWriteDiscovery+} from './lifecycle'export const MCP_VERSION: string = packageJson.version@@ -40,45 +53,170 @@ function mcpInstallCommand(): Promise<string> {return installCommandPromise}-export { fail, ok, type MCPContent, type MCPResult } from './result'+export { fail, ok, type MCPContent, type MCPResult } from '#mcp/result'-export { registerTools, type RegisterToolsOptions, type RpcSender } from './tool/registration'-export { paramToZod } from './tool/schema'+export { registerTools, type RegisterToolsOptions, type RpcSender } from '#mcp/tool/registration'+export { paramToZod } from '#mcp/tool/schema'export interface ServerOptions {+ /** TCP port for the HTTP + WebSocket server. Ignored when `withTcp` is false. When set to 0 with `withTcp: true`, binds to an ephemeral port. Defaults to 7600. */httpPort?: number- wsPort?: number+ /** Path to the Unix domain socket. Auto-resolved if omitted. */+ socketPath?: string | null+ /** Whether to also listen on TCP (in addition to the socket). API default is `false`; the CLI passes `true` by default (derived from PORT, default 7600). */+ withTcp?: booleanenableEval?: booleanmcpRoot?: string | null+ /** Auth token for /mcp and /rpc endpoints. Auto-generated (32-hex) when omitted. Pass null explicitly to disable auth. */authToken?: string | nullcorsOrigin?: string | null}-export function startServer(options: ServerOptions = {}) {- const httpPort = options.httpPort ?? 7600- const wsPort = options.wsPort ?? 7601- const enableEval = options.enableEval ?? false- const mcpRoot = options.mcpRoot ?? null- const authToken = options.authToken ?? null- const corsOrigin = options.corsOrigin ?? null+export interface ServerHandle {+ /** The Hono app (routes) */+ app: Hono+ /** The primary Node.js HTTP server (socket listener if present, otherwise TCP) */+ server: HttpServer+ /** Resolved socket path (null if not listening on socket) */+ socketPath: string | null+ /** TCP port the server is listening on (0 if TCP is disabled) */+ httpPort: number+ /** Shut down the server: close listeners, remove socket and discovery files */+ close: () => Promise<void>+}- const mcpSessions = createMcpSessionManager({- serverVersion: MCP_VERSION,- registerTools: (mcpServer: McpServer) =>- registerTools(mcpServer, { enableEval, mcpRoot, sendRpc: sendToBrowser })+/** Set up Hono routes: /health, /rpc, /mcp */+function createHonoApp(options: {+ authToken: string | null+ corsOrigin: string | null+ browserRpc: ReturnType<typeof createBrowserRpcBridge>+ mcpSessions: ReturnType<typeof createMcpSessionManager>+ sendToBrowser: (msg: RpcJsonObject) => Promise<unknown>+}): Hono {+ const { authToken, corsOrigin, browserRpc, mcpSessions, sendToBrowser } = options++ const app = new Hono()++ if (corsOrigin) {+ app.use(+ '*',+ cors({+ origin: corsOrigin,+ allowMethods: MCP_CORS_METHODS,+ allowHeaders: MCP_CORS_HEADERS,+ exposeHeaders: MCP_EXPOSED_HEADERS+ })+ )+ }++ app.get('/health', async (c) =>+ c.json({+ status: browserRpc.isConnected() ? 'ok' : 'no_app',+ version: MCP_VERSION,+ installCommand: await mcpInstallCommand(),+ authRequired: authToken !== null+ })+ )++ app.use('/rpc', async (c, next) => {+ // When authToken is null (operator explicitly disabled auth), skip token check —+ // the Unix socket or localhost TCP already restricts access to local processes.+ if (authToken !== null) {+ const provided = bearerToken(c.req.header('authorization'))+ if (!isAuthorized(provided, authToken)) {+ return c.json({ error: 'Unauthorized' }, 401)+ }+ }+ return next()})- const browserRpc = createBrowserRpcBridge({- authToken,- onConnectionChange: mcpSessions.notifyToolsChanged++ // Historical note: before the isConnected() guard was removed, a disconnected+ // app returned 503 here. Now errors from sendToBrowser surface as 502. This+ // is a semantic shift from 503 → 502; callers that distinguished 503 may+ // need to handle 502 equivalently.+ app.post('/rpc', async (c) => {+ let body = await c.req.json().catch(() => null)+ if (!body || typeof body !== 'object' || Array.isArray(body)) {+ return c.json({ error: 'Invalid request body' }, 400)+ }+ try {+ body = preprocessRpc(body as RpcJsonObject)+ const result = await sendToBrowser(body as RpcJsonObject)+ return c.json(result)+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e)+ return c.json({ ok: false, error: msg }, 502)+ }})- const sendToBrowser = browserRpc.sendRpc- // --- WebSocket: browser connects here ---+ app.all('/mcp', async (c) => {+ if (authToken !== null) {+ const token = mcpRequestToken(c.req.header('authorization'), c.req.header('x-mcp-token'))+ if (!isAuthorized(token, authToken)) {+ return c.json({ error: 'Unauthorized' }, 401)+ }+ }+ const sessionId = c.req.header('mcp-session-id') ?? undefined+ // Reject anonymous DELETE requests before they allocate a session.+ // Without this guard, a DELETE without a session ID would call+ // resolveTransport(undefined), which creates a fresh session just+ // to no-op on deleteSession(undefined) — burning a session slot.+ if (c.req.method === 'DELETE' && !sessionId) {+ return c.json({ error: 'Missing MCP session id' }, 400)+ }+ // For DELETE, look up the existing session without creating a new one.+ // resolveTransport() would allocate a fresh session for an unknown ID,+ // only to immediately delete it — wasting a session slot.+ if (c.req.method === 'DELETE' && sessionId) {+ const existing = mcpSessions.getExistingTransport(sessionId)+ if ('error' in existing) {+ if (existing.error === 'closed') {+ return c.json({ error: 'MCP server is shutting down' }, 503)+ }+ return c.json({ error: 'MCP session not found' }, 404)+ }+ try {+ return await existing.handleRequest(c.req.raw)+ } finally {+ mcpSessions.deleteSession(sessionId)+ }+ }+ if (sessionId) {+ const existing = mcpSessions.getExistingTransport(sessionId)+ if ('error' in existing) {+ if (existing.error === 'closed') {+ return c.json({ error: 'MCP server is shutting down' }, 503)+ }+ return c.json({ error: 'MCP session not found' }, 404)+ }+ mcpSessions.touch(sessionId, existing)+ return existing.handleRequest(c.req.raw)+ }+ const transport = await mcpSessions.resolveTransport(undefined)+ if ('error' in transport) {+ if (transport.error === 'closed') {+ return c.json({ error: 'MCP server is shutting down' }, 503)+ }+ return c.json(+ { error: 'Too many active MCP sessions' },+ { status: 503, headers: { 'Retry-After': '5' } }+ )+ }+ mcpSessions.touch(undefined, transport)+ return transport.handleRequest(c.req.raw)+ })++ return app+}- const wss = new WebSocketServer({ port: wsPort, host: '127.0.0.1' })+/** Set up shared WebSocket connection handling and heartbeat. Call once. */+function wireConnectionHandling(+ wss: WebSocketServer,+ browserRpc: ReturnType<typeof createBrowserRpcBridge>+) {const alive = new WeakMap<WebSocket, boolean>()- wss.on('connection', (ws) => {+ wss.on('connection', (ws: WebSocket) => {alive.set(ws, true)browserRpc.handleConnection(ws)@@ -122,90 +260,170 @@ export function startServer(options: ServerOptions = {}) {}, HEARTBEAT_INTERVAL_MS)heartbeat.unref()wss.on('close', () => clearInterval(heartbeat))+}- // --- HTTP server ----- const app = new Hono()+function buildServerContext(options: ServerOptions) {+ const httpPort = options.httpPort ?? 7600+ const enableEval = options.enableEval ?? false+ const mcpRoot = options.mcpRoot ?? null+ // Auto-generated so all transports require auth by default. Override via OPENPENCIL_MCP_AUTH_TOKEN or authToken option.+ // Pass authToken: null explicitly to disable auth entirely.+ const authToken =+ options.authToken === undefined ? randomBytes(16).toString('hex') : options.authToken+ const corsOrigin = options.corsOrigin ?? null+ const withTcp = options.withTcp ?? false- if (corsOrigin) {- app.use(- '*',- cors({- origin: corsOrigin,- allowMethods: MCP_CORS_METHODS,- allowHeaders: MCP_CORS_HEADERS,- exposeHeaders: MCP_EXPOSED_HEADERS- })+ // Warn if auth is disabled while TCP is active — any local process can+ // interact with the server without authentication. Socket-only transport+ // (PORT=0) is safer because 0o600 permissions restrict access to the+ // same OS user.+ if (authToken === null && withTcp) {+ process.stderr.write(+ `WARNING: MCP server is running without authentication on TCP port ${httpPort}. ` ++ 'Any local process can interact with the server. ' ++ 'Set OPENPENCIL_MCP_AUTH_TOKEN to enable auth, or use PORT=0 for socket-only transport.\n')}- app.get('/health', async (c) =>- c.json({- status: browserRpc.isConnected() ? 'ok' : 'no_app',- version: MCP_VERSION,- installCommand: await mcpInstallCommand(),- authRequired: authToken !== null,- ...(browserRpc.currentRpcToken() ? { token: browserRpc.currentRpcToken() } : {})- })- )-- app.use('/rpc', async (c, next) => {- const rpcToken = browserRpc.currentRpcToken()- if (!browserRpc.isConnected() || !rpcToken) {- return c.json({ error: 'OpenPencil app is not connected. Is a document open?' }, 503)- }- const provided = bearerToken(c.req.header('authorization'))- if (!isAuthorized(provided, rpcToken)) {- return c.json({ error: 'Unauthorized' }, 401)- }- return next()+ const mcpSessions = createMcpSessionManager({+ serverVersion: MCP_VERSION,+ registerTools: (mcpServer: McpServer) =>+ registerTools(mcpServer, { enableEval, mcpRoot, sendRpc: sendToBrowser })})-- app.post('/rpc', async (c) => {- let body = await c.req.json().catch(() => null)- if (!body || typeof body !== 'object') {- return c.json({ error: 'Invalid request body' }, 400)- }- try {- body = preprocessRpc(body as RpcJsonObject)- const result = await sendToBrowser(body as RpcJsonObject)- return c.json(result)- } catch (e) {- const msg = e instanceof Error ? e.message : String(e)- return c.json({ ok: false, error: msg }, 502)- }+ const browserRpc = createBrowserRpcBridge({+ authToken,+ onConnectionChange: mcpSessions.notifyToolsChanged})+ const sendToBrowser = browserRpc.sendRpc- // --- MCP Streamable HTTP ---+ const app = createHonoApp({ authToken, corsOrigin, browserRpc, mcpSessions, sendToBrowser })+ const wss = new WebSocketServer({ noServer: true })- app.all('/mcp', async (c) => {- if (authToken) {- const token = mcpRequestToken(c.req.header('authorization'), c.req.header('x-mcp-token'))- if (!isAuthorized(token, authToken)) {- return c.json({ error: 'Unauthorized' }, 401)- }- }- const sessionId = c.req.header('mcp-session-id') ?? undefined- const transport = mcpSessions.resolveTransport(sessionId)- if ('error' in transport) {- return c.json(- { error: 'Too many active MCP sessions' },- { status: 503, headers: { 'Retry-After': '5' } }+ return { httpPort, withTcp, mcpSessions, browserRpc, sendToBrowser, app, wss, authToken }+}++/**+ * Unified runtime shutdown: closes browserRpc, clears MCP sessions,+ * terminates WebSocket clients, closes the WSS, and tears down HTTP+ * listeners. Used by both the startup catch block and ServerHandle.close()+ * to ensure no runtime resources (WebSocket, browserRpc, mcpSessions) are+ * left alive.+ */+async function shutdownRuntime(+ browserRpc: ReturnType<typeof createBrowserRpcBridge>,+ mcpSessions: ReturnType<typeof createMcpSessionManager>,+ wss: WebSocketServer,+ state: ListenerState+): Promise<void> {+ const errors: unknown[] = []+ try {+ browserRpc.close()+ } catch (e) {+ errors.push(e)+ }+ try {+ await mcpSessions.clear()+ } catch (e) {+ errors.push(e)+ }+ try {+ await closeWssGracefully(wss)+ } catch (e) {+ errors.push(e)+ }+ try {+ await teardownListeners(state)+ } catch (e) {+ errors.push(e)+ }+ if (errors.length === 1) throw errors[0]+ if (errors.length > 1) throw new AggregateError(errors, 'Multiple shutdown errors')+}++function buildHandle(+ app: Hono,+ wss: WebSocketServer,+ browserRpc: ReturnType<typeof createBrowserRpcBridge>,+ mcpSessions: ReturnType<typeof createMcpSessionManager>,+ state: ListenerState,+ resolvedSocketPath: string | null,+ actualHttpPort: number,+ authToken: string | null,+ startedAt: string+): ServerHandle {+ // Promise-based lock ensures idempotency even under concurrent calls:+ // the first call creates the teardown promise; subsequent calls return+ // the same promise. JavaScript's event loop guarantees no preemption+ // between the guard check and the assignment.+ let closePromise: Promise<void> | null = null++ async function close() {+ if (closePromise) return closePromise+ closePromise = (async () => {+ await shutdownRuntime(browserRpc, mcpSessions, wss, state)+ await cleanupDiscovery(authToken, resolvedSocketPath, actualHttpPort, startedAt)+ })()+ return closePromise+ }++ const primary = state.socketResult?.server ?? state.tcpResult?.server ?? createAppServer(app)+ return {+ app,+ server: primary,+ socketPath: resolvedSocketPath,+ httpPort: actualHttpPort,+ close+ }+}++export async function startServer(options: ServerOptions = {}): Promise<ServerHandle> {+ const ctx = buildServerContext(options)++ // Wire shared connection handling BEFORE starting listeners so that+ // any client connecting during startup is handled immediately.+ wireConnectionHandling(ctx.wss, ctx.browserRpc)++ const state: ListenerState = { socketResult: null, tcpResult: null }+ let startedAt = ''+ try {+ state.socketResult = await startSocketListener(ctx.app, ctx.wss, options.socketPath ?? null)+ state.tcpResult = ctx.withTcp ? await tryStartTcp(ctx.app, ctx.wss, ctx.httpPort, state) : null+ const resolvedSocketPath = state.socketResult?.resolvedPath ?? null+ const actualHttpPort = state.tcpResult?.port ?? 0++ if (!resolvedSocketPath && !actualHttpPort) {+ throw new Error(+ 'MCP server has no active listeners (both socket and TCP are unavailable). ' ++ 'Ensure Unix domain sockets are supported on this platform or enable TCP with withTcp: true.')}- mcpSessions.touch(sessionId, transport)- const response = await transport.handleRequest(c.req.raw)- if (c.req.method === 'DELETE') {- mcpSessions.deleteSession(sessionId)- }- return response- })- function close() {- browserRpc.close()- mcpSessions.clear()- wss.close()+ startedAt = await tryWriteDiscovery(+ resolvedSocketPath,+ actualHttpPort,+ ctx.authToken,+ MCP_VERSION,+ state+ )+ } catch (err) {+ // Tear down any listeners that started before the failure, then close+ // all resources so nothing leaks when startServer rejects.+ await shutdownRuntime(ctx.browserRpc, ctx.mcpSessions, ctx.wss, state).catch(() => undefined)+ throw err}- return { app, wss, httpPort, close }+ const resolvedSocketPath = state.socketResult?.resolvedPath ?? null+ const actualHttpPort = state.tcpResult?.port ?? 0++ return buildHandle(+ ctx.app,+ ctx.wss,+ ctx.browserRpc,+ ctx.mcpSessions,+ state,+ resolvedSocketPath,+ actualHttpPort,+ ctx.authToken,+ startedAt+ )}diff --git a/packages/mcp/src/stdio-bridge.ts b/packages/mcp/src/stdio-bridge.tsindex 3eac1857c..62dad9021 100644--- a/packages/mcp/src/stdio-bridge.ts+++ b/packages/mcp/src/stdio-bridge.ts@@ -1,108 +1,461 @@-import { WebSocket } from 'ws'+import { request } from 'node:http'+import type { ClientRequest, RequestOptions } from 'node:http'-import type { PendingRequest } from '#mcp/rpc-types'+import { readDiscoveryFile } from '#mcp/transport/discovery'+import { getSocketPath, platformHasUnixSockets } from '#mcp/transport/paths'type StdioRpcBridgeOptions = {- wsUrl: string+ /** Override socket path (if known). Auto-discovered if omitted. */+ socketPath?: string | null+ /** Auth token for /rpc Bearer header. */+ authToken?: string | nullreconnectDelayMs?: number- onOpen?: () => void- onMalformedMessage?: () => void+ onReady?: () => void+ onReconnect?: () => void}-const RPC_TIMEOUT = 30_000+// 35s gives a 5s margin over the worst case (10s app wait + 20s RPC timeout = 30s)+const RPC_TIMEOUT = 35_000const DISCONNECTED_MESSAGE ='OpenPencil app is not connected. ' +'STOP and tell the user: "The OpenPencil desktop app is not running or no document is open. ' +'Please start the app and open a document, then try again." ' +'Do NOT attempt to start the app yourself or retry automatically.'-function wsMessageToString(raw: WebSocket.RawData): string {- if (Buffer.isBuffer(raw)) return raw.toString('utf8')- if (Array.isArray(raw)) return Buffer.concat(raw).toString('utf8')- return Buffer.from(raw).toString('utf8')-}+type TransportMode = 'socket' | 'tcp'+/**+ * Creates an RPC bridge that connects to the MCP server via HTTP+ * over a Unix domain socket.+ *+ * This replaces the previous WebSocket-based bridge with a simpler+ * HTTP approach that natively supports Unix domain sockets.+ */export function createStdioRpcBridge({- wsUrl,+ socketPath: socketPathOverride,+ authToken,reconnectDelayMs = 2000,- onOpen,- onMalformedMessage+ onReady,+ onReconnect}: StdioRpcBridgeOptions) {- const pending = new Map<string, PendingRequest>()- let ws: WebSocket | null = null- let registered = false-- function rejectAllPending(reason: string) {- for (const [id, req] of pending) {- clearTimeout(req.timer)- req.reject(new Error(reason))- pending.delete(id)+ let resolvedSocketPath: string | null = socketPathOverride ?? null+ let resolvedHttpPort: number | null = null+ let transportMode: TransportMode | null = null+ let ready = false+ let wasConnected = false+ let reconnectTimer: ReturnType<typeof setTimeout> | undefined+ let connectPromise: Promise<void> | null = null+ let closed = false+ let authFailure = false+ let socketFailed = false++ // Socket path resolution has two tiers:+ // Explicit: socketPathOverride parameter — authoritative pin, never+ // overwritten by discovery during reconnect.+ // Hint: OPENPENCIL_MCP_SOCKET env var — resolved through+ // getSocketPath() and readDiscoveryFile(); NOT treated as+ // explicit, so the bridge can pick up a changed path from the+ // discovery file after a server restart.+ const hasExplicitSocketPath = socketPathOverride !== undefined && socketPathOverride !== null+ // Track whether authToken was explicitly provided by the caller.+ // When false, the token is auto-discovered from the discovery file and+ // can be refreshed transparently on 401 without surfacing the error.+ const hasExplicitAuth = authToken !== undefined+ let resolvedAuthToken: string | null = authToken ?? null++ async function resolveAuthToken(): Promise<string | null> {+ if (hasExplicitAuth) return resolvedAuthToken+ if (resolvedAuthToken) return resolvedAuthToken+ const info = await readDiscoveryFile()+ if (info?.authToken) {+ resolvedAuthToken = info.authToken}+ return resolvedAuthToken}- function connect() {- ws = new WebSocket(wsUrl)+ async function resolveTransport(): Promise<void> {+ // Already resolved+ if (transportMode) return- ws.on('open', () => {- onOpen?.()- })+ // Try reading the discovery file+ const info = await readDiscoveryFile()- ws.on('message', (raw) => {- try {- const msg = JSON.parse(wsMessageToString(raw)) as {- type: string- id?: string- token?: string- result?: unknown- error?: string- ok?: boolean- }- if (msg.type === 'register' && msg.token) {- registered = true- return- }- if (msg.type === 'response' && msg.id) {- const req = pending.get(msg.id)- if (!req) return- pending.delete(msg.id)- clearTimeout(req.timer)- if (msg.ok === false) req.reject(new Error(msg.error ?? 'RPC failed'))- else {- const { type: _, id: __, ...payload } = msg- req.resolve(payload)- }- }- } catch {- onMalformedMessage?.()+ // When the auth token was not explicitly provided, pick it up from the+ // discovery file whenever we re-read transport info. This ensures the+ // bridge picks up a new server-generated token after a restart without+ // waiting for a 401 response.+ if (!hasExplicitAuth && info?.authToken) {+ resolvedAuthToken = info.authToken+ }++ // When no Unix socket is available, prefer TCP via httpPort+ if (!platformHasUnixSockets()) {+ if (info?.httpPort) {+ resolvedHttpPort = info.httpPort+ transportMode = 'tcp'+ return}- })+ throw new Error('No MCP server discovery info found')+ }- ws.on('close', () => {- registered = false- rejectAllPending('WebSocket closed')- setTimeout(connect, reconnectDelayMs)- })+ // Unix: prefer socket path from discovery file, fall back to default.+ // If no socket is available (TCP-only server), use TCP via httpPort.+ // The socketPath option (when provided directly by the caller) takes+ // precedence and is never overwritten by discovery.+ if (hasExplicitSocketPath && resolvedSocketPath) {+ // Caller explicitly provided a socket path — keep it, never overwrite+ } else if (info?.socketPath) {+ resolvedSocketPath = info.socketPath+ } else if (info?.httpPort) {+ // Server is TCP-only (no socket listener) — use TCP+ resolvedHttpPort = info.httpPort+ transportMode = 'tcp'+ return+ } else {+ resolvedSocketPath = await getSocketPath()+ }- ws.on('error', () => {- ws?.close()- })+ // Also capture httpPort as fallback+ if (info?.httpPort) {+ resolvedHttpPort = info.httpPort+ }++ // If the socket previously failed and TCP is available, use TCP+ // instead of retrying the same stale socket indefinitely.+ if (!hasExplicitSocketPath && socketFailed && resolvedHttpPort) {+ transportMode = 'tcp'+ return+ }++ transportMode = 'socket'}- function sendRpc(body: Record<string, unknown>): Promise<unknown> {+ /**+ * Makes an HTTP request to the MCP server via socket or TCP.+ */+ function httpRequest(+ method: string,+ path: string,+ body?: Record<string, unknown>+ ): Promise<{ status: number; data: unknown; req: ClientRequest }> {return new Promise((resolve, reject) => {- if (!ws || ws.readyState !== WebSocket.OPEN || !registered) {+ const bodyJson = body ? JSON.stringify(body) : undefined+ const headers: Record<string, string> = {+ ...(bodyJson ? { 'Content-Type': 'application/json' } : {}),+ ...(resolvedAuthToken ? { Authorization: `Bearer ${resolvedAuthToken}` } : {})+ }++ let reqOpts: RequestOptions | null = null+ if (transportMode === 'socket' && resolvedSocketPath) {+ reqOpts = { socketPath: resolvedSocketPath, path, method, headers }+ } else if (transportMode === 'tcp' && resolvedHttpPort) {+ reqOpts = { hostname: '127.0.0.1', port: resolvedHttpPort, path, method, headers }+ }++ if (!reqOpts) {reject(new Error(DISCONNECTED_MESSAGE))return}- const id = crypto.randomUUID()- const timer = setTimeout(() => {- pending.delete(id)- reject(new Error('RPC timeout (30s)'))- }, RPC_TIMEOUT)- pending.set(id, { resolve, reject, timer })- ws.send(JSON.stringify({ type: 'request', id, ...body }))++ const req = request(reqOpts, (res) => {+ const chunks: Buffer[] = []+ res.on('data', (chunk: Buffer) => chunks.push(chunk))+ res.on('end', () => {+ const raw = Buffer.concat(chunks).toString('utf-8')+ let data: unknown+ try {+ data = JSON.parse(raw)+ } catch {+ data = raw+ }+ resolve({ status: res.statusCode ?? 200, data, req })+ })+ res.on('error', reject)+ })++ req.on('error', reject)+ // Socket-level idle timeout to prevent indefinite hangs on+ // unresponsive connections. Set 5s shorter than the outer RPC_TIMEOUT+ // so this fires deterministically first, producing a clear "server+ // unreachable" signal rather than racing with the outer timer.+ // If the outer sendRpc timer already rejected, the error handler+ // is a no-op (settled guard in attempt()).+ req.setTimeout(RPC_TIMEOUT - 5_000, () => {+ req.destroy(new Error('Socket timeout'))+ })+ if (bodyJson) req.write(bodyJson)+ req.end()})}- return { connect, sendRpc }+ /**+ * Checks if the server is healthy and the browser is connected.+ */+ async function checkHealth(): Promise<{+ reachable: boolean+ appConnected: boolean+ authFailed: boolean+ }> {+ try {+ const { status, data } = await httpRequest('GET', '/health')+ if (status === 401) return { reachable: true, appConnected: false, authFailed: true }+ if (status !== 200) return { reachable: false, appConnected: false, authFailed: false }+ const health = data as { status?: string }+ return {+ reachable: health.status === 'ok' || health.status === 'no_app',+ appConnected: health.status === 'ok',+ authFailed: false+ }+ } catch {+ if (!hasExplicitSocketPath && transportMode === 'socket') socketFailed = true+ return { reachable: false, appConnected: false, authFailed: false }+ }+ }++ /**+ * Attempts to connect to the server. Retries with a fixed delay.+ */+ async function connect(): Promise<void> {+ if (closed) return+ try {+ await resolveTransport()+ if (!resolvedAuthToken) await resolveAuthToken()+ } catch {+ connectPromise = null+ scheduleReconnect()+ return+ }++ // close() may have been called while we were resolving transport.+ // oxlint-disable-next-line no-unnecessary-condition+ if (closed) return++ const { reachable, appConnected, authFailed } = await checkHealth()+ // oxlint-disable-next-line no-unnecessary-condition+ if (closed) return+ if (authFailed) {+ // Auth token is wrong — surface as an auth error rather than a generic+ // disconnect so the caller can prompt for a new token or re-read discovery.+ authFailure = true+ ready = false+ connectPromise = null+ // When using an auto-discovered token, clear it and transportMode so+ // the next reconnect re-reads the discovery file for a fresh token+ // instead of reusing the stale one (which would cause another 401 loop).+ if (!hasExplicitAuth) {+ resolvedAuthToken = null+ transportMode = null+ }+ scheduleReconnect()+ return+ }+ authFailure = false+ if (appConnected) {+ ready = true+ socketFailed = false+ connectPromise = null+ if (wasConnected) {+ onReconnect?.()+ } else {+ wasConnected = true+ onReady?.()+ }+ return+ }++ if (reachable) {+ // Server is up — we can send RPC requests and let the server+ // wait for the desktop app to connect.+ ready = true+ socketFailed = false+ connectPromise = null+ if (!wasConnected) {+ wasConnected = true+ onReady?.()+ }+ return+ }++ transportMode = null+ if (!hasExplicitSocketPath) resolvedSocketPath = null+ resolvedHttpPort = null+ connectPromise = null+ scheduleReconnect()+ }++ function scheduleReconnect() {+ if (closed) return+ clearTimeout(reconnectTimer)+ reconnectTimer = setTimeout(() => {+ connectPromise = connect()+ }, reconnectDelayMs)+ reconnectTimer.unref()+ }++ /**+ * Sends an RPC request to the MCP server.+ *+ * Routes through the /rpc HTTP endpoint, which proxies+ * the call to the connected browser.+ *+ * When using an auto-discovered auth token (hasExplicitAuth === false),+ * a 401 response triggers a transparent retry: the cached token is cleared,+ * the discovery file is re-read for a fresh token, and the request is+ * retried once. Only if the retry also fails is the error surfaced to the+ * caller. This makes server restarts with a new auto-generated token+ * seamless to the AI agent.+ */+ function sendRpc(body: Record<string, unknown>): Promise<unknown> {+ // If not ready, await the in-flight connect() promise first — the+ // bridge may still be resolving transport. Only reject after that+ // completes and we're still not ready.+ const awaitReady = async (): Promise<void> => {+ if (!ready && connectPromise) await connectPromise+ if (authFailure) throw new Error('Unauthorized: check OPENPENCIL_MCP_AUTH_TOKEN')+ if (!ready) throw new Error(DISCONNECTED_MESSAGE)+ }++ return awaitReady().then(+ () =>+ new Promise((resolve, reject) => {+ let settled = false+ const timer = setTimeout(() => {+ if (settled) return+ settled = true+ reject(new Error(`RPC timeout (${Math.round(RPC_TIMEOUT / 1000)}s)`))+ }, RPC_TIMEOUT)++ /**+ * Performs one HTTP request attempt. `allowAuthRetry` controls whether+ * a 401 with an auto-discovered token triggers a re-read and retry.+ * It is set to `false` for the second attempt to prevent infinite loops.+ */+ function attempt(allowAuthRetry: boolean) {+ httpRequest('POST', '/rpc', body)+ .then(({ status, data, req }) => {+ // If the overall RPC timeout fired while the request was in-flight,+ // the server may have already executed the tool. Destroying the+ // request only closes the TCP socket — it does not roll back any+ // server-side mutation. Callers must not assume that a timeout+ // means the operation was not executed.+ if (settled) {+ req.destroy()+ return undefined+ }++ if (status === 401) {+ if (allowAuthRetry && !hasExplicitAuth) {+ // Auto-discovered token may have rotated — re-read the+ // discovery file for a fresh token and retry transparently.+ // IMPORTANT: Do NOT clear the timer here — the retry must+ // still be protected by the overall 35-second timeout.+ resolvedAuthToken = null+ void readDiscoveryFile()+ .then((info) => {+ if (settled) return undefined+ if (info?.authToken) {+ resolvedAuthToken = info.authToken+ // Keep existing transport mode (socket path / port+ // doesn't change on server restart — only the token+ // does). Retry exactly once with the new token.+ attempt(false)+ return undefined+ }+ clearTimeout(timer)+ authFailure = true+ transportMode = null+ if (!hasExplicitSocketPath) resolvedSocketPath = null+ resolvedHttpPort = null+ ready = false+ settled = true+ scheduleReconnect()+ reject(new Error('Unauthorized'))+ return undefined+ })+ .catch(() => {+ if (settled) return+ clearTimeout(timer)+ // Discovery read failed — stale transport state must be+ // discarded so the bridge re-resolves on reconnect.+ transportMode = null+ if (!hasExplicitSocketPath) resolvedSocketPath = null+ resolvedHttpPort = null+ ready = false+ settled = true+ scheduleReconnect()+ reject(new Error(DISCONNECTED_MESSAGE))+ })+ return undefined+ }++ // Explicit token was rejected (config error), or auto-retry+ // already failed — surface the error immediately.+ clearTimeout(timer)+ authFailure = true+ if (!hasExplicitAuth) {+ resolvedAuthToken = null+ }+ transportMode = null+ // Clear auto-discovered transport params so resolveTransport()+ // picks up fresh values from the discovery file on reconnect.+ if (!hasExplicitSocketPath) resolvedSocketPath = null+ resolvedHttpPort = null+ ready = false+ settled = true+ scheduleReconnect()+ reject(new Error('Unauthorized: check OPENPENCIL_MCP_AUTH_TOKEN'))+ return undefined+ }++ clearTimeout(timer)++ if (status >= 400) {+ const errData = data as { error?: string }+ settled = true+ reject(new Error(errData.error ?? `RPC failed with status ${status}`))+ return undefined+ }+ settled = true+ resolve(data)+ return undefined+ })+ .catch(() => {+ if (settled) return+ clearTimeout(timer)+ if (!hasExplicitSocketPath && transportMode === 'socket') {+ socketFailed = true+ }+ transportMode = null+ // Clear auto-discovered transport params so resolveTransport()+ // picks up fresh values from the discovery file on reconnect.+ if (!hasExplicitSocketPath) resolvedSocketPath = null+ resolvedHttpPort = null+ ready = false+ settled = true+ scheduleReconnect()+ reject(new Error(DISCONNECTED_MESSAGE))+ })+ }++ attempt(true)+ })+ )+ }++ /**+ * Stops the reconnect timer and marks the bridge as not ready.+ * Call this to cleanly shut down the bridge and prevent timer leaks.+ */+ function close(): void {+ closed = true+ clearTimeout(reconnectTimer)+ reconnectTimer = undefined+ ready = false+ connectPromise = null+ }++ // Start connection+ connectPromise = connect()++ return { sendRpc, close }}diff --git a/packages/mcp/src/stdio.ts b/packages/mcp/src/stdio.tsindex 186fbaa1f..953561749 100644--- a/packages/mcp/src/stdio.ts+++ b/packages/mcp/src/stdio.ts@@ -2,36 +2,83 @@import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'-import { MCP_VERSION, registerTools } from './server.js'-import { createStdioRpcBridge } from './stdio-bridge.js'+import { MCP_VERSION, registerTools } from '#mcp/server'+import { createStdioRpcBridge } from '#mcp/stdio-bridge'if (process.argv.includes('--help') || process.argv.includes('-h')) {process.stdout.write(- `openpencil-mcp\n\nStart the OpenPencil MCP stdio bridge.\n\nOptions:\n --help, -h Show this help message\n`+ `openpencil-mcp\n\n` ++ `Start the OpenPencil MCP stdio bridge.\n\n` ++ `Connects to the MCP server via Unix domain socket on macOS/Linux ` ++ `(with TCP fallback) or via TCP on Windows.\n` ++ `The MCP server is started by the OpenPencil\n` ++ `desktop app; this bridge only forwards stdio JSON-RPC to it.\n\n` ++ `Options:\n` ++ ` --help, -h Show this help message\n\n` ++ `Environment variables:\n` ++ ` OPENPENCIL_MCP_SOCKET Override socket path (auto-discovered from discovery file when unset)\n` ++ ` OPENPENCIL_MCP_AUTH_TOKEN Bearer token for RPC auth\n` ++ ` OPENPENCIL_MCP_ROOT Allowed directory for file-scoped tools\n` ++ ` (default: cwd when run standalone, home directory when app-spawned)\n` ++ ` OPENPENCIL_MCP_EVAL Set to 1 to enable the eval tool\n`)process.exit(0)}-const wsPort = Number.parseInt(process.env.WS_PORT ?? '7601', 10)-const wsHost = process.env.HOST ?? '127.0.0.1'const enableEval = process.env.OPENPENCIL_MCP_EVAL === '1'const mcpRoot = process.env.OPENPENCIL_MCP_ROOT?.trim() || process.cwd()+// Auth token: undefined → auto-discover from discovery file, empty string →+// disable auth, whitespace-only → reject (same fail-fast as index.ts to catch+// misconfiguration), otherwise → use the trimmed value.+const rawAuthToken = process.env.OPENPENCIL_MCP_AUTH_TOKEN+if (rawAuthToken !== undefined && rawAuthToken !== '' && rawAuthToken.trim() === '') {+ process.stderr.write(+ 'Error: OPENPENCIL_MCP_AUTH_TOKEN is whitespace-only. Set a real token, or use an empty string to disable auth.\n'+ )+ process.exit(1)+}+function resolveAuthToken(raw: string | undefined): string | null | undefined {+ if (raw === undefined) return undefined+ if (raw === '') return null+ return raw.trim()+}+const authToken = resolveAuthToken(rawAuthToken)-const wsUrl = `ws://${wsHost}:${wsPort}`+// OPENPENCIL_MCP_SOCKET is intentionally NOT forwarded as an explicit socketPath.+// The bridge reads the socket path from the discovery file (whose `socketPath`+// field records the override) via auto-discovery. Treating the env var as an+// explicit pin would prevent the bridge from following discovery updates after+// a server restart.const bridge = createStdioRpcBridge({- wsUrl,- onOpen: () => {- process.stderr.write(`Connected to OpenPencil app at ${wsUrl}\n`)+ authToken,+ onReady: () => {+ process.stderr.write(+ 'Connected to OpenPencil MCP server; document availability is checked per tool call\n'+ )},- onMalformedMessage: () => {- process.stderr.write('Malformed WS message\n')+ onReconnect: () => {+ process.stderr.write(+ 'Reconnected to OpenPencil MCP server; document availability is checked per tool call\n'+ )}})-bridge.connect()-const mcpServer = new McpServer({ name: 'open-pencil', version: MCP_VERSION })registerTools(mcpServer, { enableEval, mcpRoot, sendRpc: bridge.sendRpc })const transport = new StdioServerTransport()-void mcpServer.connect(transport)+mcpServer.connect(transport).catch((err) => {+ process.stderr.write(`Fatal: MCP connect failed — ${err instanceof Error ? err.message : err}\n`)+ process.exit(1)+})++process.on('uncaughtException', (err) => {+ process.stderr.write(`Fatal: ${err instanceof Error ? err.message : err}\n`)+ process.exit(1)+})++process.on('unhandledRejection', (reason: unknown) => {+ const message = reason instanceof Error ? reason.message : String(reason)+ process.stderr.write(`Fatal: unhandled rejection — ${message}\n`)+ process.exit(1)+})diff --git a/packages/mcp/src/tool/registration.ts b/packages/mcp/src/tool/registration.tsindex 1e77b53b5..e37cfb083 100644--- a/packages/mcp/src/tool/registration.ts+++ b/packages/mcp/src/tool/registration.ts@@ -8,9 +8,8 @@ import { ALL_TOOLS, CODEGEN_PROMPT } from '@open-pencil/core/tools'import type { RpcJsonObject } from '#mcp/json'import { MAX_RESULT_BYTES, fail, ok, resultTooLargeMessage } from '#mcp/result'--import { resolveSafePath, writeToolOutput } from './output'-import { paramToZod } from './schema'+import { resolveSafePath, writeToolOutput } from '#mcp/tool/output'+import { paramToZod } from '#mcp/tool/schema'export type RpcSender = (body: Record<string, unknown>) => Promise<unknown>diff --git a/packages/mcp/src/transport/discovery.ts b/packages/mcp/src/transport/discovery.tsnew file mode 100644index 000000000..5da372b0c--- /dev/null+++ b/packages/mcp/src/transport/discovery.ts@@ -0,0 +1,249 @@+import { randomBytes } from 'node:crypto'+import { access, constants, lstat, readFile, rename, unlink, writeFile } from 'node:fs/promises'+import { Socket } from 'node:net'++import { getDiscoveryPath, getSocketPath, platformHasUnixSockets } from '#mcp/transport/paths'++/**+ * Metadata written to the discovery file so clients can auto-locate+ * the running MCP server without knowing the socket path or TCP port.+ *+ * WARNING: The discovery file contains a plaintext auth token. Do not sync+ * this file to cloud storage or include it in backups without encryption.+ * Any process running as the same user can read this file.+ */+export interface DiscoveryInfo {+ pid: number+ /** Unix domain socket path, or null on platforms that don't support them (Windows). */+ socketPath: string | null+ httpPort: number+ authRequired: boolean+ authToken: string | null+ version: string+ startedAt: string+}++/**+ * Writes the discovery JSON file at the platform-appropriate location.+ * Overwrites any existing file (from a previous server instance).+ *+ * The write is atomic: a sibling temp file is written first with `0o600`+ * permissions, then renamed over the final path. This avoids leaving+ * a half-written file visible to readers if the process is killed+ * mid-write, and prevents concurrent writers from corrupting the file+ * by interleaving their writes.+ *+ * WARNING: The auth token is written in plaintext. Do not sync the discovery+ * file to cloud storage or include it in backups without encryption.+ */+export async function writeDiscoveryFile(info: DiscoveryInfo): Promise<void> {+ const path = await getDiscoveryPath()+ const json = JSON.stringify(info, null, 2)+ // Add a random component to guarantee uniqueness+ const random = randomBytes(6).toString('hex')+ const tmpPath = `${path}.${process.pid}.${random}.tmp`+ await writeFile(tmpPath, json, { mode: 0o600, encoding: 'utf-8' })+ try {+ await rename(tmpPath, path)+ } catch (err) {+ // Best-effort cleanup of the temp file on rename failure+ await unlink(tmpPath).catch(() => undefined)+ throw err+ }+}++/**+ * Reads the discovery file. Returns null if:+ * - The file does not exist+ * - The file cannot be parsed+ * - The recorded PID is no longer running (stale file)+ *+ * On success, returns the parsed DiscoveryInfo.+ */+export async function readDiscoveryFile(): Promise<DiscoveryInfo | null> {+ const path = await getDiscoveryPath()+ let raw: string+ try {+ raw = await readFile(path, 'utf-8')+ } catch (e) {+ if (!isEnoent(e))+ process.stderr.write(+ ` Discovery: read warning (${e instanceof Error ? e.message : String(e)})\n`+ )+ return null+ }++ let parsed: unknown+ try {+ parsed = JSON.parse(raw)+ } catch {+ return null+ }+ if (!parsed || typeof parsed !== 'object') return null++ const obj = parsed as { [key: string]: unknown }+ const info = validateDiscoveryFields(obj)+ if (!info) return null+ if (!isProcessAlive(info.pid)) return null++ return info+}++function validateDiscoveryFields(obj: { [key: string]: unknown }): DiscoveryInfo | null {+ const { pid, version, httpPort, authRequired, startedAt, socketPath, authToken } = obj+ if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) return null+ if (typeof version !== 'string') return null+ if (typeof httpPort !== 'number' || !Number.isInteger(httpPort)) return null+ if (httpPort < 0 || httpPort > 65535) return null+ if (typeof authRequired !== 'boolean') return null+ if (typeof startedAt !== 'string') return null+ if (typeof socketPath !== 'string' && socketPath !== null) return null+ if (socketPath === '') return null+ if (authToken !== null && typeof authToken !== 'string') return null+ return { pid, version, httpPort, authRequired, startedAt, socketPath, authToken }+}++/**+ * Removes the discovery file. Does not throw if the file does not exist.+ */+export async function removeDiscoveryFile(): Promise<void> {+ const path = await getDiscoveryPath()+ try {+ await unlink(path)+ } catch (e) {+ if (!isEnoent(e)) throw e+ }+}++// TCP health check is more reliable than Unix socket connections in some+// runtimes (Bun on Linux). We read the discovery file directly instead of+// using readDiscoveryFile() to bypass the isProcessAlive PID check — the+// TCP fetch is a stronger liveness probe than process.kill(pid, 0).+async function isSocketLiveViaTcp(socketPath: string): Promise<boolean> {+ let discoveryPath: string+ try {+ discoveryPath = await getDiscoveryPath()+ } catch {+ return false+ }+ const raw = await readFile(discoveryPath, 'utf-8').catch(() => null)+ if (!raw) return false+ let info: DiscoveryInfo | null = null+ try {+ const parsed: unknown = JSON.parse(raw)+ if (parsed && typeof parsed === 'object') {+ info = validateDiscoveryFields(parsed as { [key: string]: unknown })+ }+ } catch {+ return false+ }+ if (!info || info.socketPath !== socketPath) return false++ // If TCP is disabled (httpPort <= 0), fall back to PID-based liveness check+ if (info.httpPort <= 0) {+ return isProcessAlive(info.pid)+ }++ return fetch(`http://127.0.0.1:${info.httpPort}/health`, {+ signal: AbortSignal.timeout(2000)+ })+ .then(() => true)+ .catch((e) => {+ // A timeout means the process is likely alive but slow — don't delete its socket+ if (e instanceof Error && e.name === 'TimeoutError') return true+ return false+ })+}++/**+ * Direct Unix-socket connection probe. A server binds the socket before+ * writeDiscovery(), so isSocketLiveViaTcp() can return false during that+ * window. This probe connects directly to the socket path — a successful+ * connection or timeout means the socket is live; only ECONNREFUSED means+ * no process is listening.+ */+function probeSocketLive(socketPath: string): Promise<boolean> {+ return new Promise((resolve) => {+ let settled = false+ const socket = new Socket()+ const finish = (result: boolean) => {+ if (settled) return+ settled = true+ clearTimeout(timer)+ socket.destroy()+ // oxlint-disable-next-line no-multiple-resolved -- settled flag guarantees single resolution+ resolve(result)+ }+ const timer = setTimeout(() => finish(true), 1000)+ socket.once('connect', () => finish(true))+ socket.once('error', (err) => {+ const code = (err as NodeJS.ErrnoException).code+ finish(code !== 'ECONNREFUSED')+ })+ socket.connect(socketPath)+ })+}++/**+ * Removes a stale Unix domain socket file if it exists and is not live.+ * A socket is considered stale if no process is listening on it.+ */+export async function removeStaleSocket(socketPathOverride?: string): Promise<void> {+ if (!platformHasUnixSockets()) return++ const socketPath = socketPathOverride ?? (await getSocketPath())+ let exists: boolean+ try {+ await access(socketPath, constants.F_OK)+ exists = true+ } catch {+ exists = false+ }++ if (!exists) return++ // Verify the path is actually a socket before unlinking it.+ // A misconfigured OPENPENCIL_MCP_SOCKET could point at a regular file;+ // we must never delete non-socket paths.+ const stat = await lstat(socketPath).catch((e) => {+ if (isEnoent(e)) return null+ throw e+ })+ if (!stat) return+ if (!stat.isSocket()) {+ throw new Error(`Refusing to remove non-socket path: ${socketPath}`)+ }++ if (await probeSocketLive(socketPath)) return+ if (await isSocketLiveViaTcp(socketPath)) return++ // No live server claims this socket — remove the stale file.+ try {+ await unlink(socketPath)+ } catch (e) {+ if (e instanceof Error && 'code' in e && (e as NodeJS.ErrnoException).code !== 'ENOENT') {+ process.stderr.write(`Failed to remove stale socket: ${e.message}\n`)+ }+ }+}++/**+ * Checks if a process with the given PID is still running.+ * Uses process.kill(pid, 0) which doesn't send a signal, just checks existence.+ * Works on both Unix and Windows.+ */+function isProcessAlive(pid: number): boolean {+ try {+ process.kill(pid, 0)+ return true+ } catch (e) {+ if (e instanceof Error && 'code' in e && (e as NodeJS.ErrnoException).code === 'ESRCH') {+ return false+ }+ return true+ }+}++function isEnoent(e: unknown): boolean {+ return e instanceof Error && 'code' in e && (e as NodeJS.ErrnoException).code === 'ENOENT'+}diff --git a/packages/mcp/src/transport/paths.ts b/packages/mcp/src/transport/paths.tsnew file mode 100644index 000000000..91076041e--- /dev/null+++ b/packages/mcp/src/transport/paths.ts@@ -0,0 +1,163 @@+import { chmod, mkdir } from 'node:fs/promises'+import { homedir, platform } from 'node:os'+import { dirname, join } from 'node:path'++/**+ * Platform-specific paths for the MCP server's Unix domain socket+ * and the discovery JSON file.+ *+ * Socket directory layout (overridable via OPENPENCIL_MCP_SOCKET):+ * macOS: ~/Library/Application Support/OpenPencil/+ * Linux: $XDG_RUNTIME_DIR/openpencil/ (fallback: ~/.openpencil/)+ * Windows: %LOCALAPPDATA%\OpenPencil\ (fallback: ~\AppData\Local\OpenPencil\)+ *+ * On Windows, Unix domain sockets are unavailable — the server uses TCP only.+ *+ * Discovery file: at the platform-default path above, UNLESS+ * OPENPENCIL_MCP_DISCOVERY_PATH is set (see getDiscoveryPath()). The socket+ * override (OPENPENCIL_MCP_SOCKET) never moves the discovery file — it is+ * recorded in the discovery file's `socketPath` field so clients read it+ * from the well-known location.+ * Socket file: <socketDir>/mcp.sock (or the override path)+ *+ * IMPORTANT: getSocketDir() returns the directory that contains the socket+ * file. It does NOT always contain the discovery file — when+ * OPENPENCIL_MCP_SOCKET is set, the discovery file stays at getPlatformDir().+ */++const DIR_NAME_UNIX = 'openpencil'+const DIR_NAME_MACOS = 'OpenPencil'+const SOCKET_FILENAME = 'mcp.sock'+const DISCOVERY_FILENAME = 'mcp.json'++const isMacOS = platform() === 'darwin'+const isWindows = platform() === 'win32'++/**+ * Returns the platform-specific default directory for MCP runtime files,+ * ignoring OPENPENCIL_MCP_SOCKET. The discovery file always lives here so+ * clients can find it at a well-known location regardless of socket overrides.+ * Creates the directory (with restrictive permissions) if it does not exist.+ *+ * The 0o700 mode restricts permissions on Unix. On Windows, mkdir ignores+ * the mode and uses default ACLs — directory access is controlled by the+ * filesystem, not the permission bits.+ */+async function getPlatformDir(): Promise<string> {+ let dir: string++ if (isMacOS) {+ dir = join(homedir(), 'Library', 'Application Support', DIR_NAME_MACOS)+ } else if (isWindows) {+ const localAppData = process.env.LOCALAPPDATA?.trim()+ if (localAppData) {+ dir = join(localAppData, DIR_NAME_MACOS)+ } else {+ dir = join(homedir(), 'AppData', 'Local', DIR_NAME_MACOS)+ }+ } else {+ // Linux / other Unix+ const xdgRuntime = process.env.XDG_RUNTIME_DIR?.trim()+ if (xdgRuntime) {+ dir = join(xdgRuntime, DIR_NAME_UNIX)+ } else {+ dir = join(homedir(), `.${DIR_NAME_UNIX}`)+ }+ }++ await mkdir(dir, { recursive: true, mode: 0o700 })+ if (!isWindows) await chmod(dir, 0o700)+ return dir+}++/**+ * Returns the directory for the MCP socket file.+ *+ * When OPENPENCIL_MCP_SOCKET is set, its dirname is used as the socket+ * directory. When unset, the platform default from getPlatformDir() is used.+ * Creates the directory (with restrictive permissions) if it does not exist.+ *+ * NOTE: The discovery file always lives at getPlatformDir(), regardless of+ * OPENPENCIL_MCP_SOCKET. This function should NOT be used to locate it.+ */+export async function getSocketDir(): Promise<string> {+ const socketOverride = process.env.OPENPENCIL_MCP_SOCKET?.trim()++ if (socketOverride) {+ const dir = dirname(socketOverride)+ // Create missing parents with restrictive permissions. Do NOT chmod+ // existing directories — the override path is user-controlled and+ // may be in a shared directory (e.g. /tmp for tests).+ await mkdir(dir, { recursive: true, mode: 0o700 })+ return dir+ }++ return getPlatformDir()+}++/**+ * Returns the full path to the MCP Unix domain socket.+ *+ * On macOS/Linux: <socketDir>/mcp.sock+ *+ * When OPENPENCIL_MCP_SOCKET is set, its value is returned directly+ * (no directory resolution needed).+ */+export async function getSocketPath(): Promise<string> {+ const socketOverride = process.env.OPENPENCIL_MCP_SOCKET?.trim()+ if (socketOverride) {+ // Ensure the override directory exists. getSocketDir() creates the+ // directory for the custom socket path (dirname of the override).+ await getSocketDir()+ return socketOverride+ }++ const dir = await getSocketDir()+ return join(dir, SOCKET_FILENAME)+}++/**+ * Returns the full path to the MCP discovery JSON file.+ *+ * The discovery file lives at the platform-default location so clients can+ * find it without knowing whether OPENPENCIL_MCP_SOCKET is set. It contains+ * the actual socket path (which may be overridden) in its `socketPath` field,+ * so clients read the discovery file to learn where to connect — not the other+ * way around.+ *+ * Set OPENPENCIL_MCP_DISCOVERY_PATH to relocate the discovery file (e.g. to a+ * temp directory for test isolation). The desktop app reads the platform+ * default via its own path computation (src/app/automation/mcp/spawn.ts) and+ * does not honor this override, so it is primarily useful for tests and+ * standalone server invocations. The parent directory is created (0o700) so+ * writeDiscoveryFile's atomic temp-then-rename succeeds.+ */+export async function getDiscoveryPath(): Promise<string> {+ const override = process.env.OPENPENCIL_MCP_DISCOVERY_PATH?.trim()+ if (override) {+ const dir = dirname(override)+ await mkdir(dir, { recursive: true, mode: 0o700 })+ return override+ }+ const dir = await getPlatformDir()+ return join(dir, DISCOVERY_FILENAME)+}++/**+ * Returns true if the current platform supports Unix domain sockets.+ * Unix domain sockets are available on macOS, Linux, and other POSIX+ * platforms but not on native Windows. WSL is detected as Linux.+ */+export function platformHasUnixSockets(): boolean {+ return !isWindows+}++/**+ * Returns the platform name for display purposes.+ */+export function platformName(): 'macos' | 'linux' | 'windows' | 'other' {+ if (isMacOS) return 'macos'+ if (isWindows) return 'windows'+ if (platform() === 'linux') return 'linux'+ return 'other'+}diff --git a/packages/mcp/tsconfig.json b/packages/mcp/tsconfig.jsonindex 554efaa5d..bc4548727 100644--- a/packages/mcp/tsconfig.json+++ b/packages/mcp/tsconfig.json@@ -12,5 +12,5 @@"outDir": "dist","rootDir": "src"},- "include": ["src/index.ts", "src/server.ts", "src/stdio.ts"]+ "include": ["src/index.ts", "src/server.ts", "src/stdio.ts", "src/transport/**/*.ts"]}diff --git a/packages/mcp/tsdown.config.ts b/packages/mcp/tsdown.config.tsindex e6b950653..2a1d17a97 100644--- a/packages/mcp/tsdown.config.ts+++ b/packages/mcp/tsdown.config.ts@@ -4,7 +4,9 @@ export default defineConfig({entry: {index: './src/index.ts',server: './src/server.ts',- stdio: './src/stdio.ts'+ stdio: './src/stdio.ts',+ transport: './src/transport/paths.ts',+ discovery: './src/transport/discovery.ts'},platform: 'node',format: ['esm'],diff --git a/src/app/ai/acp/transport.ts b/src/app/ai/acp/transport.tsindex c109b295e..7865d5992 100644--- a/src/app/ai/acp/transport.ts+++ b/src/app/ai/acp/transport.ts@@ -8,7 +8,7 @@ import type {} from '@agentclientprotocol/sdk'import type { ChatTransport, UIMessage, UIMessageChunk } from 'ai'-import type { ACPAgentDef } from '@open-pencil/core/constants'+import { AUTOMATION_HTTP_PORT, type ACPAgentDef } from '@open-pencil/core/constants'import SYSTEM_PROMPT from '@/app/ai/chat/system-prompt.md?raw'@@ -249,12 +249,23 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {const connection = new ClientSideConnection((_agent: Agent) => clientImpl, stream)const { getAutomationAuthToken } = await import('@/app/automation/mcp/spawn')- const automationAuthToken = await getAutomationAuthToken()+ let automationAuthToken: string | null+ try {+ automationAuthToken = await getAutomationAuthToken()+ } catch (e) {+ await child.kill().catch(() => undefined)+ throw new Error(formatConnectionError(e, this.agentDef))+ }- await connection.initialize({- protocolVersion: PROTOCOL_VERSION,- clientCapabilities: {}- })+ try {+ await connection.initialize({+ protocolVersion: PROTOCOL_VERSION,+ clientCapabilities: {}+ })+ } catch (e) {+ await child.kill().catch(() => undefined)+ throw new Error(formatConnectionError(e, this.agentDef))+ }let sessionResulttry {@@ -264,7 +275,7 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {{type: 'http' as const,name: 'open-pencil',- url: 'http://127.0.0.1:7600/mcp',+ url: `http://127.0.0.1:${AUTOMATION_HTTP_PORT}/mcp`,headers: automationAuthToken? [{ name: 'Authorization', value: `Bearer ${automationAuthToken}` }]: []@@ -272,7 +283,7 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {]})} catch (e) {- await child.kill()+ await child.kill().catch(() => undefined)throw new Error(formatConnectionError(e, this.agentDef))}diff --git a/src/app/automation/bridge/server.ts b/src/app/automation/bridge/server.tsindex db446c3d7..7df94646a 100644--- a/src/app/automation/bridge/server.ts+++ b/src/app/automation/bridge/server.ts@@ -4,7 +4,7 @@* Connects to the bridge via WebSocket, receives RPC requests,* executes them against the live EditorStore, and sends results back.*/-import { AUTOMATION_WS_PORT } from '@open-pencil/core/constants'+import { AUTOMATION_HTTP_PORT } from '@open-pencil/core/constants'import { randomHex } from '@open-pencil/core/random'import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'@@ -25,8 +25,10 @@ export function connectAutomation(getStore: () => EditorStore, authToken: string}function connect() {+ let socket: WebSockettry {- ws = new WebSocket(`ws://127.0.0.1:${AUTOMATION_WS_PORT}`)+ socket = new WebSocket(`ws://127.0.0.1:${AUTOMATION_HTTP_PORT}`)+ ws = socket} catch (e) {console.error('[Automation] WebSocket constructor failed:',@@ -36,12 +38,12 @@ export function connectAutomation(getStore: () => EditorStore, authToken: stringreturn}- ws.onopen = () => {+ socket.onopen = () => {console.debug('[Automation] WebSocket connected to MCP server')- ws?.send(JSON.stringify({ type: 'register', token }))+ socket.send(JSON.stringify({ type: 'register', token }))}- ws.onmessage = async (event) => {+ socket.onmessage = async (event) => {try {const msg = JSON.parse(event.data) as {type: string@@ -52,9 +54,9 @@ export function connectAutomation(getStore: () => EditorStore, authToken: stringif (msg.type !== 'request' || !msg.id) returntry {const result = await handleRequest(msg.id, msg.command, msg.args)- ws?.send(JSON.stringify({ type: 'response', id: msg.id, ...(result as object) }))+ socket.send(JSON.stringify({ type: 'response', id: msg.id, ...(result as object) }))} catch (e) {- ws?.send(+ socket.send(JSON.stringify({type: 'response',id: msg.id,@@ -68,18 +70,16 @@ export function connectAutomation(getStore: () => EditorStore, authToken: string}}- ws.onclose = (event) => {- ws = null- if (intentionalDisconnect) return- const details = `code=${event.code} reason=${event.reason}`- if (event.code === 1000) console.debug('[Automation] WebSocket closed:', details)- else console.error('[Automation] WebSocket closed:', details)+ socket.onclose = (event) => {+ if (ws === socket) ws = null+ if (intentionalDisconnect || event.code === 1000) return+ console.warn('[Automation] WebSocket closed:', `code=${event.code} reason=${event.reason}`)scheduleReconnect()}- ws.onerror = (event) => {- console.error('[Automation] WebSocket error:', event)- ws?.close()+ socket.onerror = (event) => {+ console.warn('[Automation] WebSocket error:', event)+ socket.close()}}diff --git a/src/app/automation/bridge/vite-plugin.ts b/src/app/automation/bridge/vite-plugin.tsindex 3d1ba28de..b9201ca27 100644--- a/src/app/automation/bridge/vite-plugin.ts+++ b/src/app/automation/bridge/vite-plugin.ts@@ -2,50 +2,87 @@ import { spawn } from 'node:child_process'import type { Plugin } from 'vite'+import { AUTOMATION_HTTP_PORT } from '@open-pencil/core/constants'+import { getSocketPath, platformHasUnixSockets } from '@open-pencil/mcp/transport'+// TODO: production — bundle MCP server as Tauri sidecar or spawn via shell pluginexport function automationPlugin(authToken: string | null, corsOrigin: string): Plugin {let child: ReturnType<typeof spawn> | null = null+ let starting: Promise<void> | null = nullreturn {name: 'open-pencil-automation',- configureServer(server) {- if (child) return-- child = spawn('bun', ['run', 'packages/mcp/src/index.ts'], {- stdio: ['ignore', 'inherit', 'pipe'],- env: {- ...process.env,- PORT: '7600',- WS_PORT: '7601',- ...(authToken ? { OPENPENCIL_MCP_AUTH_TOKEN: authToken } : {}),- OPENPENCIL_MCP_CORS_ORIGIN: corsOrigin- }- })-- child.stderr?.on('data', (data: Buffer) => {- const text = data.toString()- if (text.includes('EADDRINUSE')) {- console.error(- '\x1b[31m[MCP] Port 7600 already in use. Is another OpenPencil instance running?\x1b[0m'- )- child?.kill()- child = null- return- }- process.stderr.write(data)- })+ async configureServer() {+ if (child || starting) return- child.on('exit', (code) => {- if (code && code !== 0 && child) {- console.error(`[MCP] Server exited with code ${code}`)- }- child = null- })+ starting = (async () => {+ // Only resolve and forward the socket path on platforms that support+ // Unix domain sockets. On Windows the MCP server falls back to TCP,+ // and forwarding OPENPENCIL_MCP_SOCKET would cause it to attempt a+ // socket listen that cannot succeed.+ const socketPath = platformHasUnixSockets() ? await getSocketPath() : null++ const childEnv = { ...process.env }+ delete childEnv.OPENPENCIL_MCP_SOCKET+ delete childEnv.OPENPENCIL_MCP_AUTH_TOKEN- server.httpServer?.once('close', () => {- child?.kill()- child = null- })+ const spawned = spawn('bun', ['run', 'packages/mcp/src/index.ts'], {+ stdio: ['ignore', 'inherit', 'pipe'],+ env: {+ ...childEnv,+ PORT: String(AUTOMATION_HTTP_PORT),+ OPENPENCIL_MCP_TCP: '1',+ ...(socketPath ? { OPENPENCIL_MCP_SOCKET: socketPath } : {}),+ ...(authToken ? { OPENPENCIL_MCP_AUTH_TOKEN: authToken } : {}),+ OPENPENCIL_MCP_CORS_ORIGIN: corsOrigin,+ OPENPENCIL_MCP_ROOT: process.cwd()+ }+ })+ child = spawned++ spawned.on('error', (err) => {+ console.error(`[MCP] Failed to spawn automation server: ${err.message}`)+ if (child === spawned) child = null+ })++ spawned.stderr.on('data', (data: Buffer) => {+ const text = data.toString()+ if (text.includes('EADDRINUSE')) {+ console.error(+ `\x1b[31m[MCP] MCP bind failed (port ${AUTOMATION_HTTP_PORT}${socketPath ? ` or socket ${socketPath}` : ''}). Is another OpenPencil instance running?\x1b[0m`+ )+ spawned.kill()+ if (child === spawned) child = null+ return+ }+ process.stderr.write(data)+ })++ spawned.on('exit', (code) => {+ if (code && code !== 0) {+ console.error(`[MCP] Server exited with code ${code}`)+ }+ if (child === spawned) child = null+ })+ })()++ try {+ await starting+ } finally {+ starting = null+ }+ },+ async buildEnd() {+ if (starting) {+ try {+ await starting+ } catch {+ void 0+ }+ }+ child?.kill()+ child = null+ starting = null}}}diff --git a/src/app/automation/mcp/spawn.ts b/src/app/automation/mcp/spawn.tsindex 763c79df8..3a6bc2ed0 100644--- a/src/app/automation/mcp/spawn.ts+++ b/src/app/automation/mcp/spawn.ts@@ -2,6 +2,7 @@ import { promiseTimeout } from '@vueuse/core'import { AUTOMATION_HTTP_PORT } from '@open-pencil/core/constants'import { randomHex } from '@open-pencil/core/random'+import type { DiscoveryInfo } from '@open-pencil/mcp/discovery'import { decodeTauriStderr } from '@/app/shell/ui'import { isTauri } from '@/app/tauri/env'@@ -11,7 +12,7 @@ interface AutomationHealth {version?: stringinstallCommand?: stringauthRequired?: boolean- token?: string+ discoveryPath?: string}export interface AutomationServerHandle {@@ -29,6 +30,106 @@ const noop = () => undefinedlet runtimeAutomationAuthToken: string | null = DEV_AUTOMATION_AUTH_TOKEN+/**+ * Reads the auth token from the MCP discovery file via Tauri's FS plugin.+ * The discovery file path is computed locally (not from the /health endpoint)+ * to prevent an unauthenticated /health response from directing file reads+ * to an attacker-controlled path.+ */+async function readDiscoveryToken(discoveryPath: string): Promise<string | null> {+ try {+ const { readTextFile } = await import('@tauri-apps/plugin-fs')+ const raw = await readTextFile(discoveryPath)+ const info = JSON.parse(raw) as DiscoveryInfo+ return info.authToken ?? null+ } catch {+ return null+ }+}++/** Check whether the discovery file exists on disk. */+async function discoveryFileExists(discoveryPath: string): Promise<boolean> {+ try {+ const { exists } = await import('@tauri-apps/plugin-fs')+ return await exists(discoveryPath)+ } catch {+ return false+ }+}++/**+ * Computes the expected MCP discovery file path using the same platform+ * logic as the server's getDiscoveryPath(), but via Tauri APIs since we+ * run in the browser. This avoids trusting the unauthenticated /health+ * endpoint's discoveryPath field.+ */+async function computeExpectedDiscoveryPath(): Promise<string> {+ const { homeDir, join } = await import('@tauri-apps/api/path')+ const home = await homeDir()+ if (!home) throw new Error('homeDir() returned an empty string')++ const isMac = navigator.platform.includes('Mac')+ const isWindows = navigator.platform.includes('Win')+ // Must match the server's getPlatformDir() in packages/mcp/src/transport/paths.ts.+ // On Windows, LOCALAPPDATA usually equals <home>\AppData\Local, so this fallback+ // matches the server's path in the common case. When it doesn't (custom+ // LOCALAPPDATA), resolveDiscoveryPath() falls back to the /health endpoint.+ if (isMac) {+ return join(home, 'Library', 'Application Support', 'OpenPencil', 'mcp.json')+ }+ if (isWindows) {+ return join(home, 'AppData', 'Local', 'OpenPencil', 'mcp.json')+ }+ // Linux: $XDG_RUNTIME_DIR/openpencil/mcp.json or ~/.openpencil/mcp.json.+ // In Tauri we don't have direct env access, so we use the home-directory+ // fallback. The server may use XDG_RUNTIME_DIR if set — when the paths+ // differ, resolveDiscoveryPath() falls back to the /health endpoint.+ return join(home, '.openpencil', 'mcp.json')+}++/**+ * Resolves the discovery path to use for reading the auth token.+ *+ * Prefers the locally-computed path from `computeExpectedDiscoveryPath()` for+ * security. When the server-reported `healthDiscoveryPath` (from the+ * unauthenticated `/health` endpoint) differs, logs a warning and falls back+ * to the server-reported path as a compatibility measure.+ *+ * Security tradeoff: the `/health` endpoint is unauthenticated, so a+ * compromised server could redirect us to a malicious path. This is mitigated+ * by the fact that the server is on localhost and was spawned by us. The+ * fallback exists because local computation can be wrong (e.g., XDG_RUNTIME_DIR+ * mismatches on Linux where the server uses `$XDG_RUNTIME_DIR/openpencil` but+ * the local computation falls back to `~/.openpencil`).+ */+async function resolveDiscoveryPath(healthDiscoveryPath?: string): Promise<string> {+ const expected = await computeExpectedDiscoveryPath()+ if (healthDiscoveryPath && healthDiscoveryPath !== expected) {+ const localExists = await discoveryFileExists(expected)+ if (!localExists) {+ // Validate the server-reported path before accepting it. The /health+ // endpoint is unauthenticated, so we only accept paths within the+ // user's home directory ending in mcp.json.+ const { homeDir } = await import('@tauri-apps/api/path')+ const home = await homeDir()+ const sep = home.includes('\\') ? '\\' : '/'+ const hasTraversal = healthDiscoveryPath.split(/[\\/]/).some((segment) => segment === '..')+ const isSafe =+ healthDiscoveryPath.endsWith('mcp.json') &&+ !hasTraversal &&+ healthDiscoveryPath.startsWith(home + sep)+ if (isSafe) {+ console.warn(+ `[MCP] Server discovery path "${healthDiscoveryPath}" differs from expected "${expected}" ` ++ 'and local path does not exist. Using server-reported path (server is on localhost).'+ )+ return healthDiscoveryPath+ }+ }+ }+ return expected+}+async function readHealth(): Promise<AutomationHealth | null> {try {const res = await fetch(`http://127.0.0.1:${AUTOMATION_HTTP_PORT}/health`, {@@ -42,15 +143,27 @@ async function readHealth(): Promise<AutomationHealth | null> {}}+/**+ * Returns the major.minor portion of a semver string (e.g. "0.5.1" → "0.5").+ * Returns null if the string is not parseable as semver.+ */+function parseMajorMinor(version: string): string | null {+ const match = version.match(/^(\d+)\.(\d+)/)+ return match ? `${match[1]}.${match[2]}` : null+}+function assertCompatibleMcpVersion(health: AutomationHealth): void {- if (health.version === APP_VERSION) return+ const runningMajorMinor = health.version ? parseMajorMinor(health.version) : null+ const oursMajorMinor = parseMajorMinor(APP_VERSION)+ if (!runningMajorMinor || !oursMajorMinor) return // unparseable — don't block+ if (runningMajorMinor === oursMajorMinor) returnconst runningVersion = health.version ? `v${health.version}` : 'an older version'const updateHint = health.installCommand? `Run: ${health.installCommand}, then restart OpenPencil.`: `Update the global @open-pencil/mcp package to v${APP_VERSION} with your package manager, then restart OpenPencil.`throw new Error(- `OpenPencil desktop v${APP_VERSION} requires @open-pencil/mcp v${APP_VERSION}, ` +- `but the running MCP server is ${runningVersion}. ${updateHint}`+ `OpenPencil desktop v${APP_VERSION} requires @open-pencil/mcp v${oursMajorMinor}.x ` ++ `(major.minor compatibility), but the running MCP server is ${runningVersion}. ${updateHint}`)}@@ -66,8 +179,35 @@ async function pollHealth(retries: number, delayMs: number): Promise<AutomationHexport async function getAutomationAuthToken(): Promise<string | null> {if (runtimeAutomationAuthToken) return runtimeAutomationAuthTokenconst health = await readHealth()- if (health) assertCompatibleMcpVersion(health)- runtimeAutomationAuthToken = health?.token ?? null+ if (!health) {+ throw new Error(+ 'MCP server is not reachable. Ensure the desktop app is running and the MCP server has started.'+ )+ }+ assertCompatibleMcpVersion(health)+ const discoveryPath = await resolveDiscoveryPath(health.discoveryPath)+ const token = await readDiscoveryToken(discoveryPath)+ if (health.authRequired && !token) {+ throw new Error(+ 'MCP server requires authentication but the discovery token could not be read. ' ++ 'Ensure the discovery file is accessible and contains an auth token.'+ )+ }+ // When token is null and auth is not required, verify the discovery file+ // actually exists. A missing file means the server hasn't finished starting+ // (discovery file is written after listeners are up). Without this check,+ // we'd return null (meaning "auth disabled") when the server isn't ready+ // yet, causing ACP sessions to proceed without auth.+ if (!token && !health.authRequired) {+ const fileExists = await discoveryFileExists(discoveryPath)+ if (!fileExists) {+ throw new Error(+ `MCP server not yet ready — discovery file not found at ${discoveryPath}. ` ++ 'Wait for the server to finish starting and try again.'+ )+ }+ }+ runtimeAutomationAuthToken = tokenreturn runtimeAutomationAuthToken}@@ -81,7 +221,15 @@ export async function spawnMCPIfNeeded(): Promise<AutomationServerHandle | null>const existing = await readHealth()if (existing) {assertCompatibleMcpVersion(existing)- runtimeAutomationAuthToken = existing.token ?? null+ const discoveryPath = await resolveDiscoveryPath(existing.discoveryPath)+ const token = await readDiscoveryToken(discoveryPath)+ if (existing.authRequired && !token) {+ throw new Error(+ 'MCP server requires authentication but the discovery token could not be read. ' ++ 'Ensure the discovery file is accessible and contains an auth token.'+ )+ }+ runtimeAutomationAuthToken = tokenreturn {disconnect: noop,authToken: runtimeAutomationAuthToken@@ -89,21 +237,33 @@ export async function spawnMCPIfNeeded(): Promise<AutomationServerHandle | null>}const authToken = randomHex(32)- runtimeAutomationAuthToken = authToken+ // Cache only after MCP startup is confirmed healthy.const { Command } = await import('@tauri-apps/plugin-shell')const isWindows = navigator.platform.includes('Win')+ // Set OPENPENCIL_MCP_ROOT to the user's home directory so file-scoped+ // tools (open_file, save_file, export_*) operate on paths inside ~,+ // which is naturally writable and matches user expectations for "my files."+ // The app bundle directory (Tauri executableDir) is read-only and would+ // cause EACCES errors on every file write.+ const mcpRoot = await resolveTauriHomeDir()const command = isWindows? Command.create('cmd', ['/c', 'openpencil-mcp-http'], {env: {+ PORT: String(AUTOMATION_HTTP_PORT),OPENPENCIL_MCP_AUTH_TOKEN: authToken,- OPENPENCIL_MCP_CORS_ORIGIN: window.location.origin+ OPENPENCIL_MCP_CORS_ORIGIN: window.location.origin,+ OPENPENCIL_MCP_TCP: '1',+ OPENPENCIL_MCP_ROOT: mcpRoot}}): Command.create('openpencil-mcp-http', [], {env: {+ PORT: String(AUTOMATION_HTTP_PORT),OPENPENCIL_MCP_AUTH_TOKEN: authToken,- OPENPENCIL_MCP_CORS_ORIGIN: window.location.origin+ OPENPENCIL_MCP_CORS_ORIGIN: window.location.origin,+ OPENPENCIL_MCP_TCP: '1',+ OPENPENCIL_MCP_ROOT: mcpRoot}})@@ -111,26 +271,75 @@ export async function spawnMCPIfNeeded(): Promise<AutomationServerHandle | null>console.error('[MCP]', decodeTauriStderr(raw))})+ let spawnedToken: string | null = nullcommand.on('close', (data: { code: number | null }) => {console.error(`[MCP] Server exited (code ${data.code ?? 'null'})`)+ if (spawnedToken && runtimeAutomationAuthToken === spawnedToken) {+ runtimeAutomationAuthToken = null+ }})const child = await command.spawn()const health = await pollHealth(5, 1000)if (health) {- assertCompatibleMcpVersion(health)- runtimeAutomationAuthToken = health.token ?? authToken- return {- disconnect: () => {- void child.kill()- },- authToken: runtimeAutomationAuthToken+ try {+ assertCompatibleMcpVersion(health)+ const discoveryPath = await resolveDiscoveryPath(health.discoveryPath)+ const discovered = await readDiscoveryToken(discoveryPath)+ const token = discovered ?? authToken+ spawnedToken = token+ runtimeAutomationAuthToken = token+ return {+ disconnect: () => {+ void child.kill().catch((e) => {+ console.error('[MCP] Failed to kill server:', e)+ })+ if (runtimeAutomationAuthToken === token) {+ runtimeAutomationAuthToken = null+ }+ },+ authToken: token+ }+ } catch (err) {+ await child.kill().catch(() => undefined)+ runtimeAutomationAuthToken = null+ throw err}}- await child.kill()+ try {+ await child.kill().catch(() => undefined)+ } finally {+ runtimeAutomationAuthToken = null+ }throw new Error(`Failed to start MCP server. Install @open-pencil/mcp@${APP_VERSION} globally with your package manager, then restart OpenPencil.`)}++/**+ * Returns the user's home directory. Used as the default OPENPENCIL_MCP_ROOT+ * so file-scoped tools operate on paths inside ~, which is writable and+ * matches user expectations. Throws if the Tauri path plugin is unavailable+ * — this function is only invoked under !import.meta.env.DEV && isTauri(),+ * so the Tauri path plugin should always succeed. A silent fallback to '/'+ * would defeat path scoping in resolveSafePath, and process.cwd() is+ * unpredictable and may also be too broad.+ */+async function resolveTauriHomeDir(): Promise<string> {+ try {+ const { homeDir } = await import('@tauri-apps/api/path')+ const dir = await homeDir()+ if (!dir) {+ throw new Error('homeDir() returned an empty string')+ }+ return dir+ } catch (e) {+ throw new Error(+ 'Failed to resolve home directory for MCP root. ' ++ 'The MCP server requires a home directory to scope file operations. ' ++ (e instanceof Error ? e.message : String(e))+ )+ }+}diff --git a/tests/engine/cli/app-client.test.ts b/tests/engine/cli/app-client.test.tsnew file mode 100644index 000000000..b705b6c43--- /dev/null+++ b/tests/engine/cli/app-client.test.ts@@ -0,0 +1,54 @@+import { afterEach, describe, expect, test } from 'bun:test'+import { createServer, type Server } from 'node:http'+import type { AddressInfo } from 'node:net'+import { join } from 'node:path'++import { removeDiscoveryFile, writeDiscoveryFile } from '@open-pencil/mcp/discovery'++import { rpc } from '#cli/app-client'++let server: Server | null = null++afterEach(async () => {+ await new Promise<void>((resolve) => {+ if (!server) {+ resolve()+ return+ }+ server.close(() => resolve())+ })+ server = null+ await removeDiscoveryFile()+})++describe('CLI app transport discovery', () => {+ test('falls back to discovered TCP when the Unix socket is unavailable', async () => {+ const token = 'cli-test-token'+ server = createServer((request, response) => {+ if (request.url !== '/rpc' || request.headers.authorization !== `Bearer ${token}`) {+ response.writeHead(401, { 'Content-Type': 'application/json' })+ response.end(JSON.stringify({ error: 'Unauthorized' }))+ return+ }+ response.writeHead(200, { 'Content-Type': 'application/json' })+ response.end(JSON.stringify({ ok: true, result: { source: 'tcp' } }))+ })+ await new Promise<void>((resolve) => {+ server?.listen(0, '127.0.0.1', resolve)+ })+ const address = server.address() as AddressInfo++ await writeDiscoveryFile({+ pid: process.pid,+ socketPath: join('/tmp', `missing-openpencil-${process.pid}.sock`),+ httpPort: address.port,+ authRequired: true,+ authToken: token,+ version: '0.0.0-test',+ startedAt: new Date().toISOString()+ })++ const result = await rpc('list_documents')+ expect(result).toEqual({ source: 'tcp' })+ })+})diff --git a/tests/engine/mcp/browser-rpc.test.ts b/tests/engine/mcp/browser-rpc.test.tsnew file mode 100644index 000000000..d052bf3bb--- /dev/null+++ b/tests/engine/mcp/browser-rpc.test.ts@@ -0,0 +1,440 @@+import { describe, expect, test, afterEach } from 'bun:test'+import { randomUUID } from 'node:crypto'+import { createServer, type Server } from 'node:http'++import { WebSocket, WebSocketServer } from 'ws'++import { createBrowserRpcBridge } from '#mcp/browser-rpc'++const AUTH_TOKEN = 'test-bridge-token'+const RPC_BODY = { command: 'get_current_page' }++/**+ * Create a temporary WebSocket server.+ */+function createWsServer(): Promise<{+ httpServer: Server+ wss: WebSocketServer+ url: string+}> {+ return new Promise((resolve, reject) => {+ const httpServer = createServer()+ const wss = new WebSocketServer({ noServer: true })++ httpServer.on('upgrade', (request, socket, head) => {+ wss.handleUpgrade(request, socket, head, (ws) => {+ wss.emit('connection', ws, request)+ })+ })++ httpServer.listen(0, '127.0.0.1', () => {+ const addr = httpServer.address()+ const port = typeof addr === 'object' && addr ? addr.port : 0+ resolve({ httpServer, wss, url: `ws://127.0.0.1:${port}` })+ })+ httpServer.on('error', reject)+ })+}++/**+ * Connect a WebSocket client.+ */+function connectClient(url: string): Promise<WebSocket> {+ return new Promise((resolve, reject) => {+ const ws = new WebSocket(url)+ ws.on('open', () => resolve(ws))+ ws.on('error', reject)+ })+}++/**+ * Set up a connected pair: one client-side WS and one server-side WS.+ *+ * IMPORTANT: The 'connection' handler is registered BEFORE the client+ * connects, because wss emits 'connection' during the upgrade handshake+ * (before the client receives its 'open' event). Any code that awaits+ * connectClient() first and then registers the connection handler will+ * miss the event.+ */+async function setupWsPair(): Promise<{+ serverWs: WebSocket+ clientWs: WebSocket+ wss: WebSocketServer+ httpServer: Server+}> {+ const srv = await createWsServer()++ const serverWsPromise = new Promise<WebSocket>((resolve) => {+ srv.wss.on('connection', resolve)+ })++ const clientWs = await connectClient(srv.url)+ const serverWs = await serverWsPromise++ return { serverWs, clientWs, wss: srv.wss, httpServer: srv.httpServer }+}++/**+ * Register a server-side WebSocket as the browser on the bridge.+ * Mirrors the wiring in server.ts -> wireConnectionHandling.+ *+ * Bridge handleConnection sends { type: 'register', token } through the+ * server-side WS to the browser. We receive it on the client side and+ * echo it back through the same WS pair.+ */+async function registerBrowser(+ serverWs: WebSocket,+ clientWs: WebSocket,+ bridge: ReturnType<typeof createBrowserRpcBridge>+): Promise<void> {+ // Wire message + close handlers the same way server.ts does+ serverWs.on('message', (raw: Buffer) => {+ const data = Buffer.from(raw as Buffer).toString('utf-8')+ bridge.handleMessage(data, serverWs)+ })+ serverWs.on('close', () => bridge.handleClose(serverWs))++ // Bridge sends register prompt to the client (token is null for security)+ bridge.handleConnection(serverWs)++ // Client receives the register prompt+ const raw: Buffer = await new Promise<Buffer>((resolve) => {+ clientWs.once('message', resolve)+ })+ const msg = JSON.parse(raw.toString())+ expect(msg.type).toBe('register')++ // The browser app sends the register message with the known token.+ // It gets the token from the discovery file or Vite env, not from the prompt.+ clientWs.send(JSON.stringify({ type: 'register', token: AUTH_TOKEN }))++ // Wait for the bridge to process the register message by observing+ // the onConnectionChange callback (isConnected becomes true).+ // Use a one-shot polling approach to avoid the no-multiple-resolved+ // lint rule that flags setInterval-based resolve patterns.+ for (let i = 0; i < 200; i++) {+ if (bridge.isConnected()) break+ await new Promise<void>((r) => {+ setTimeout(r, 5)+ })+ }+ expect(bridge.isConnected()).toBe(true)+}++describe('BrowserRpcBridge reconnection', () => {+ const servers: { httpServer: Server; wss: WebSocketServer }[] = []++ afterEach(() => {+ for (const s of servers) {+ s.wss.close()+ s.httpServer.close()+ }+ servers.length = 0+ })++ function track(srv: { httpServer: Server; wss: WebSocketServer }) {+ servers.push(srv)+ }++ test('pending requests from old browser are rejected on reconnect (Fix 1)', async () => {+ const pairA = await setupWsPair()+ track(pairA)+ const pairB = await setupWsPair()+ track(pairB)++ const bridge = createBrowserRpcBridge({+ authToken: AUTH_TOKEN,+ onConnectionChange: () => undefined+ })++ // Register the old browser+ await registerBrowser(pairA.serverWs, pairA.clientWs, bridge)++ // Send an RPC — goes to old browser (no response, sits in pending map).+ // Attach .catch() immediately to prevent unhandled rejection when+ // rejectAllPending fires during registerBrowser below.+ const rpcPromise = bridge.sendRpc(RPC_BODY)++ // A new browser reconnects on a different WS connection.+ // This triggers rejectAllPending() inside registerBrowser.+ const start = Date.now()+ await registerBrowser(pairB.serverWs, pairB.clientWs, bridge)++ // Assert the rejection directly instead of sleeping for handler propagation.+ await expect(rpcPromise).rejects.toThrow('Browser reconnected')+ const elapsed = Date.now() - start+ expect(elapsed).toBeLessThan(5_000)+ })++ test('connection waiters survive handleClose and are NOT rejected (Fix 2)', async () => {+ const pair = await setupWsPair()+ track(pair)++ const bridge = createBrowserRpcBridge({+ authToken: AUTH_TOKEN,+ onConnectionChange: () => undefined+ })++ // Register the browser+ await registerBrowser(pair.serverWs, pair.clientWs, bridge)++ // Close the client side — this should trigger serverWs 'close'+ // which calls bridge.handleClose(). Fix 2 ensures that connection+ // waiters are NOT rejected here.+ pair.clientWs.close()+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 200)+ })++ // sendRpc enters waitForConnection() because browserWs is null.+ // The waiter should survive handleClose and stay pending.+ const rpcPromise = bridge.sendRpc(RPC_BODY)+ // Consume the eventual rejection (after APP_WAIT_TIMEOUT) to prevent+ // an unhandled rejection after the test ends — handleClose intentionally+ // does NOT reject connectionWaiters, so the promise will reject on timeout.+ void rpcPromise.catch(() => undefined)++ try {+ // Race the waiter against a short timeout — if handleClose wrongly+ // rejects waiters, rpcPromise would settle quickly.+ const raceOutcome = await Promise.race([+ rpcPromise.then(+ (v) => ({ settled: true, value: v }) as const,+ (e) => ({ settled: true, error: (e as Error).message }) as const+ ),+ new Promise<{ settled: false }>((resolve) => {+ setTimeout(() => resolve({ settled: false }), 500)+ })+ ])++ expect(raceOutcome.settled).toBe(false)+ } finally {+ bridge.close()+ }+ })++ test('connection waiters resolved when browser reconnects after close', async () => {+ const pairA = await setupWsPair()+ track(pairA)++ const bridge = createBrowserRpcBridge({+ authToken: AUTH_TOKEN,+ onConnectionChange: () => undefined+ })++ // Register initial browser+ await registerBrowser(pairA.serverWs, pairA.clientWs, bridge)++ // Close client — triggers serverWs 'close', bridge.handleClose,+ // browserWs set to null, browserRegistered = false+ pairA.clientWs.close()+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 200)+ })++ // sendRpc enters waitForConnection+ const rpcPromise = bridge.sendRpc(RPC_BODY)+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 50)+ })++ // A new browser connects+ const pairB = await setupWsPair()+ track(pairB)++ const serverWsB = pairB.serverWs+ const clientWsB = pairB.clientWs++ // Wire server-side message/close handlers+ serverWsB.on('message', (raw: Buffer) => {+ const data = Buffer.from(raw as Buffer).toString('utf-8')+ bridge.handleMessage(data, serverWsB)+ })+ serverWsB.on('close', () => bridge.handleClose(serverWsB))++ // Set up client-side handler to respond to incoming RPC requests.+ // Must match the protocol: handleClientRequest sends+ // { type: 'response', id, ok: true, ...responsePayload(result) }+ // where responsePayload spreads result fields directly (not under a+ // "result" key). handleBrowserResponse then strips type/id via+ // stripEnvelope, so sendRpc resolves with { ok: true, ...result }.+ clientWsB.on('message', (raw: Buffer) => {+ const msg = JSON.parse(raw.toString())+ if (msg.type === 'request') {+ clientWsB.send(JSON.stringify({ type: 'response', id: msg.id, ok: true, connected: true }))+ }+ })++ // Bridge sends register prompt through serverWsB to clientWsB+ bridge.handleConnection(serverWsB)++ // Client receives the register prompt and sends the known token+ const regRaw: Buffer = await new Promise<Buffer>((resolve) => {+ clientWsB.once('message', resolve)+ })+ const reg = JSON.parse(regRaw.toString())+ expect(reg.type).toBe('register')+ clientWsB.send(JSON.stringify({ type: 'register', token: AUTH_TOKEN }))++ // The echo triggers registerBrowser() which resolves the waiter,+ // re-sends the pending RPC, and resolves rpcPromise.+ const result = await rpcPromise+ expect(result).toEqual({ ok: true, connected: true })+ }, 5_000)++ test('sendRpc rejects after timeout when browser never connects', async () => {+ const bridge = createBrowserRpcBridge({+ authToken: AUTH_TOKEN,+ onConnectionChange: () => undefined+ })++ // No browser registered — sendRpc rejects with APP_NOT_CONNECTED.+ await expect(bridge.sendRpc(RPC_BODY)).rejects.toThrow('OpenPencil app is not connected')+ }, 12_000)++ test('response from non-browser WebSocket is ignored (ws guard)', async () => {+ // Set up two independent WS pairs: one for the browser, one for a+ // non-browser client (e.g. a stdio bridge).+ const browserPair = await setupWsPair()+ track(browserPair)+ const clientPair = await setupWsPair()+ track(clientPair)++ const bridge = createBrowserRpcBridge({+ authToken: AUTH_TOKEN,+ onConnectionChange: () => undefined+ })++ // Register the browser+ await registerBrowser(browserPair.serverWs, browserPair.clientWs, bridge)++ // Also wire the non-browser client into the bridge so it can send+ // messages via handleMessage (simulating a stdio bridge WS).+ // Authenticate it first so handleMessage doesn't reject at the auth gate.+ clientPair.serverWs.on('message', (raw: Buffer) => {+ const data = Buffer.from(raw as Buffer).toString('utf-8')+ bridge.handleMessage(data, clientPair.serverWs)+ })+ bridge.handleConnection(clientPair.serverWs)+ await new Promise<void>((resolve) => {+ clientPair.clientWs.send(JSON.stringify({ type: 'auth', token: AUTH_TOKEN }))+ // Wait briefly for the auth message to be processed+ clientPair.clientWs.once('message', () => resolve())+ })++ // Capture the request ID from the browser side. Set up the listener+ // BEFORE sending the RPC to avoid a race where the request message+ // arrives before the handler is attached.+ const capturedIdPromise = new Promise<string>((resolve) => {+ browserPair.clientWs.on('message', function handler(raw: Buffer) {+ const msg = JSON.parse(raw.toString())+ if (msg.type === 'request') {+ browserPair.clientWs.off('message', handler)+ resolve(msg.id)+ }+ })+ })++ // Send an RPC — it goes to the real browser.+ const rpcPromise = bridge.sendRpc(RPC_BODY)++ const capturedId = await capturedIdPromise++ // Have the non-browser client inject a fake response with a random UUID.+ // The ws guard (browserWs !== ws) fires because the message arrives from+ // a non-browser WebSocket — it returns before pending.get(msg.id) is+ // reached. The matching-UUID case is tested in the next test.+ const fakeId = randomUUID()+ clientPair.clientWs.send(+ JSON.stringify({ type: 'response', id: fakeId, ok: true, result: 'fake' })+ )++ // Give the fake message time to be processed+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 50)+ })++ // Now send the legitimate browser response+ browserPair.clientWs.send(+ JSON.stringify({ type: 'response', id: capturedId, ok: true, real: true })+ )++ // The RPC should resolve with the real browser's response, not the+ // fake one. The ws guard ensures responses from non-browser sockets+ // are silently dropped.+ const result = await rpcPromise+ expect(result).toEqual({ ok: true, real: true })+ })++ test('response with matching UUID from non-browser WebSocket is rejected by ws guard', async () => {+ // This test specifically exercises the browserWs !== ws guard with+ // a matching request UUID, which is the more dangerous attack vector.+ const browserPair = await setupWsPair()+ track(browserPair)+ const attackerPair = await setupWsPair()+ track(attackerPair)++ const bridge = createBrowserRpcBridge({+ authToken: AUTH_TOKEN,+ onConnectionChange: () => undefined+ })++ // Register the browser+ await registerBrowser(browserPair.serverWs, browserPair.clientWs, bridge)++ // Wire the attacker's WS into the bridge so it can send messages.+ // Authenticate it first so handleMessage doesn't reject at the auth gate,+ // ensuring the ws-guard logic is actually tested.+ attackerPair.serverWs.on('message', (raw: Buffer) => {+ const data = Buffer.from(raw as Buffer).toString('utf-8')+ bridge.handleMessage(data, attackerPair.serverWs)+ })+ bridge.handleConnection(attackerPair.serverWs)+ await new Promise<void>((resolve) => {+ attackerPair.clientWs.send(JSON.stringify({ type: 'auth', token: AUTH_TOKEN }))+ attackerPair.clientWs.once('message', () => resolve())+ })++ // Set up the message listener BEFORE sending the RPC to avoid a race+ // where the request arrives before the handler is attached.+ const capturedIdPromise = new Promise<string>((resolve) => {+ browserPair.clientWs.on('message', function handler(raw: Buffer) {+ const msg = JSON.parse(raw.toString())+ if (msg.type === 'request') {+ browserPair.clientWs.off('message', handler)+ resolve(msg.id)+ }+ })+ })++ // Send an RPC — it goes to the real browser.+ const rpcPromise = bridge.sendRpc(RPC_BODY)++ const capturedId = await capturedIdPromise+ expect(capturedId).toBeTruthy()+ const requestId = capturedId++ // The attacker sends a fake response with the REAL request UUID+ // from a different WebSocket. The browserWs !== ws guard must+ // prevent this from resolving the pending request.+ attackerPair.clientWs.send(+ JSON.stringify({ type: 'response', id: requestId, ok: true, injected: true })+ )++ // Give the fake message time to be processed+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 50)+ })++ // Now the real browser responds+ browserPair.clientWs.send(+ JSON.stringify({ type: 'response', id: requestId, ok: true, legitimate: true })+ )++ // The RPC must resolve with the real browser's response, proving+ // the attacker's injection was ignored by the ws guard.+ const result = (await rpcPromise) as { legitimate?: boolean; injected?: boolean }+ expect(result.legitimate).toBe(true)+ expect(result.injected).toBeUndefined()+ })+})diff --git a/tests/engine/mcp/discovery-isolation.test.ts b/tests/engine/mcp/discovery-isolation.test.tsnew file mode 100644index 000000000..90c2e8f28--- /dev/null+++ b/tests/engine/mcp/discovery-isolation.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from 'bun:test'++import { isAliveFromKillError, isProcessAlive } from '#tests/helpers/mcp-discovery-isolation'++describe('mcp-discovery-isolation > isProcessAlive', () => {+ it('returns true for the current (live) process', () => {+ // The stale-dir sweep must never treat the running process as dead.+ expect(isProcessAlive(process.pid)).toBe(true)+ })++ it('treats EPERM (process exists but is unsignalable) as alive', () => {+ // The destructive sweep must NOT delete a dir whose process may exist.+ // This is the defect flagged in scratch/review-01.md.+ const err = new Error('Operation not permitted') as NodeJS.ErrnoException+ err.code = 'EPERM'+ expect(isAliveFromKillError(err)).toBe(true)+ })++ it('treats ESRCH (no such process) as dead', () => {+ const err = new Error('No such process') as NodeJS.ErrnoException+ err.code = 'ESRCH'+ expect(isAliveFromKillError(err)).toBe(false)+ })++ it('treats an error without a code as alive', () => {+ expect(isAliveFromKillError(new Error('unknown'))).toBe(true)+ })++ it('treats a non-Error throw as alive', () => {+ expect(isAliveFromKillError('not an error')).toBe(true)+ })+})diff --git a/tests/engine/mcp/helpers.ts b/tests/engine/mcp/helpers.tsnew file mode 100644index 000000000..fab22158b--- /dev/null+++ b/tests/engine/mcp/helpers.ts@@ -0,0 +1,306 @@+import { type RequestOptions, request as httpRequest } from 'node:http'++import { WebSocket } from 'ws'++import {+ type SceneGraph,+ ALL_TOOLS,+ FigmaAPI,+ computeAllLayouts,+ executeRpcCommand+} from '@open-pencil/core'++export interface HealthResponse {+ status: string+ version: string+ authRequired: boolean+ discoveryPath?: string+}++export interface MockBrowserRequest {+ command: string+ args?: unknown+}++export interface MockBrowser {+ ws: WebSocket+ graph: SceneGraph+ requests: MockBrowserRequest[]+ close: () => void+}++/** Read the next WebSocket JSON message with a timeout. */+export function readWsJson<T>(ws: WebSocket, timeoutMs = 1000): Promise<T> {+ return new Promise((resolve, reject) => {+ const cleanup = () => {+ clearTimeout(timer)+ ws.off('message', onMessage)+ ws.off('error', onError)+ }+ const onMessage = (raw: WebSocket.RawData) => {+ cleanup()+ try {+ resolve(JSON.parse(raw.toString()) as T)+ } catch (error) {+ reject(error)+ }+ }+ const onError = (error: Error) => {+ cleanup()+ reject(error)+ }+ const timer = setTimeout(() => {+ cleanup()+ reject(new Error('Timed out waiting for WebSocket message'))+ }, timeoutMs)+ ws.on('message', onMessage)+ ws.on('error', onError)+ })+}++/** Open a WebSocket connection, optionally authenticating as a stdio bridge client. */+export function openWs(url: string, authToken?: string | null): Promise<WebSocket> {+ const ws = new WebSocket(url)+ return new Promise((resolve, reject) => {+ ws.once('open', () => {+ if (authToken) {+ // Authenticate as a stdio bridge client (not the browser app).+ // The "auth" message type validates the token and adds the client+ // to authenticatedClients without replacing the registered browser.+ ws.send(JSON.stringify({ type: 'auth', token: authToken }))+ }+ resolve(ws)+ })+ ws.once('error', reject)+ })+}++/** Read the next WebSocket JSON message, skipping any 'register' broadcasts. */+export async function readNextResponse<T>(ws: WebSocket, timeoutMs = 5000): Promise<T> {+ const start = Date.now()+ for (let i = 0; ; i++) {+ const remaining = timeoutMs - (Date.now() - start)+ if (remaining <= 0) throw new Error(`Timed out after reading ${i} register messages`)+ const msg = await readWsJson<T & { type: string }>(ws, remaining)+ if (msg.type !== 'register') return msg+ }+}++/** Low-level HTTP request via Node's http module, with timeout. */+export function nodeHttpRequest(+ opts: RequestOptions,+ bodyJson?: string,+ timeoutMs = 5_000+): Promise<{ status: number; data: unknown }> {+ return new Promise((resolve, reject) => {+ const req = httpRequest(opts, (res) => {+ const chunks: Buffer[] = []+ res.on('data', (chunk: Buffer) => chunks.push(chunk))+ res.on('end', () => {+ clearTimeout(timeout)+ const raw = Buffer.concat(chunks).toString('utf-8')+ let data: unknown+ try {+ data = JSON.parse(raw)+ } catch {+ data = raw+ }+ resolve({ status: res.statusCode ?? 200, data })+ })+ res.on('error', (err) => {+ clearTimeout(timeout)+ reject(err)+ })+ })+ const timeout = setTimeout(() => {+ req.destroy(new Error(`nodeHttpRequest timed out after ${timeoutMs / 1000}s`))+ }, timeoutMs)+ req.on('error', (err) => {+ clearTimeout(timeout)+ reject(err)+ })+ // Connection-level timeout: destroys the socket if the server stalls+ // during connection or mid-request. The response-level timeout above+ // handles slow responses; this handles hung connections (e.g., socket+ // exists but no one is listening).+ req.setTimeout(timeoutMs, () => {+ req.destroy(new Error(`nodeHttpRequest connection timed out after ${timeoutMs / 1000}s`))+ })+ if (bodyJson) req.write(bodyJson)+ req.end()+ })+}++/** Make an HTTP request via TCP to a specific port. */+export function tcpRequest(+ port: number,+ method: string,+ path: string,+ body?: Record<string, unknown>,+ headers?: Record<string, string>+): Promise<{ status: number; data: unknown }> {+ if (!port) throw new Error('tcpRequest: port not initialized — beforeAll must run first')+ const bodyJson = body ? JSON.stringify(body) : undefined+ return nodeHttpRequest(+ {+ hostname: '127.0.0.1',+ port,+ path,+ method,+ headers: { ...(bodyJson ? { 'Content-Type': 'application/json' } : {}), ...headers }+ },+ bodyJson+ )+}++/** Make an HTTP request via Unix domain socket. */+export function socketRequest(+ socketPath: string,+ method: string,+ path: string,+ headers?: Record<string, string>+): Promise<{ status: number; data: unknown }> {+ return nodeHttpRequest({ socketPath, path, method, headers: headers ?? {} })+}++/** Generate a random hex string of the given byte length using crypto.getRandomValues(). */+function randomHex(bytes: number): string {+ const buf = new Uint8Array(bytes)+ globalThis.crypto.getRandomValues(buf)+ return Array.from(buf)+ .map((b) => b.toString(16).padStart(2, '0'))+ .join('')+}++async function handleMockCommand(+ graph: SceneGraph,+ command: string,+ rawArgs: unknown+): Promise<unknown> {+ const args = rawArgs as { name?: string; args?: Record<string, unknown> } | undefined++ if (command === 'tool' && args?.name) {+ const def = ALL_TOOLS.find((t) => t.name === args.name)+ if (!def) throw new Error(`Unknown tool: ${args.name}`)+ const api = new FigmaAPI(graph)+ const pages = graph.getPages()+ if (pages.length === 0) throw new Error('No pages in graph')+ api.currentPage = api.wrapNode(pages[0].id)+ const result = await def.execute(api, args.args ?? {})+ if (def.mutates) computeAllLayouts(graph)+ return result+ }++ if (command === 'list_documents') {+ const pages = graph.getPages()+ const currentPage = pages[0]+ return {+ documents: [+ {+ id: 'doc-1',+ name: 'Mock document',+ active: true,+ current_page_id: currentPage?.id ?? '',+ current_page_name: currentPage?.name ?? '',+ pages: pages.map((page) => ({ id: page.id, name: page.name }))+ }+ ]+ }+ }++ if (command === 'save_file' || command === 'new_document' || command === 'open_file') {+ return {}+ }++ return executeRpcCommand(graph, command, args ?? {})+}++export function connectMockBrowser(+ port: number,+ graph: SceneGraph,+ authToken?: string+): Promise<MockBrowser> {+ return new Promise((resolve, reject) => {+ const ws = new WebSocket(`ws://127.0.0.1:${port}`)+ const requests: MockBrowserRequest[] = []+ const token = authToken ?? 'test-token-' + randomHex(8)++ let settled = false++ ws.on('open', () => {+ ws.send(JSON.stringify({ type: 'register', token }))++ ws.on('message', async (raw) => {+ let parsed: unknown+ try {+ parsed = JSON.parse(raw.toString())+ } catch {+ return // Ignore malformed payloads+ }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return+ const msg = parsed as { type: string; id: string; command: string; args?: unknown }+ if (msg.type !== 'request') return++ try {+ requests.push({ command: msg.command, args: msg.args })+ const result = await handleMockCommand(graph, msg.command, msg.args)+ ws.send(JSON.stringify({ type: 'response', id: msg.id, ok: true, result }))+ } catch (e) {+ ws.send(+ JSON.stringify({+ type: 'response',+ id: msg.id,+ ok: false,+ error: e instanceof Error ? e.message : String(e)+ })+ )+ }+ })++ if (!settled) {+ settled = true+ // Wait for the server to confirm browser registration before resolving.+ // Without this, follow-up test traffic can start before the server marks+ // the browser as connected, causing race conditions.+ void waitForBrowserRegistration(port).then(+ () => {+ resolve({ ws, graph, requests, close: () => ws.close() })+ return undefined+ },+ (err) => {+ ws.close()+ reject(err)+ }+ )+ }+ })++ ws.on('error', (err) => {+ if (!settled) {+ settled = true+ reject(err)+ }+ })+ })+}++export async function waitForBrowserRegistration(port: number, timeoutMs = 5000): Promise<void> {+ const start = Date.now()+ let lastStatus = 'unknown'+ while (Date.now() - start < timeoutMs) {+ try {+ const resp = await fetch(`http://127.0.0.1:${port}/health`)+ const health = (await resp.json()) as HealthResponse+ lastStatus = health.status+ if (health.status === 'ok') return+ } catch {+ void 0+ }+ await new Promise<void>((r) => {+ setTimeout(r, 100)+ })+ }+ throw new Error(+ `Browser registration not confirmed within ${timeoutMs}ms (last status: ${lastStatus})`+ )+}diff --git a/tests/engine/mcp/lifecycle-failure.test.ts b/tests/engine/mcp/lifecycle-failure.test.tsnew file mode 100644index 000000000..a71631b4b--- /dev/null+++ b/tests/engine/mcp/lifecycle-failure.test.ts@@ -0,0 +1,241 @@+import { describe, expect, test, beforeAll, afterAll } from 'bun:test'+import { mkdir, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { startServer, type ServerHandle } from '#mcp/server'++import { socketRequest, type HealthResponse } from './helpers'++const isUnix = process.platform !== 'win32'+const SOCKET_DIR = join(tmpdir(), `openpencil-test-lifecycle-${process.pid}`)+const TEST_AUTH_TOKEN = 'test-auth-token'+let testCounter = 0++function testSocketPath(): string | null {+ if (!isUnix) return null+ return join(SOCKET_DIR, `mcp-test-${process.pid}-${++testCounter}.sock`)+}++// ---------------------------------------------------------------------------+// Listen failure cleanup tests (Reviews 02, 03)+// ---------------------------------------------------------------------------++describe('MCP lifecycle failure cleanup', () => {+ beforeAll(async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ })++ afterAll(async () => {+ if (isUnix) await rm(SOCKET_DIR, { recursive: true, force: true })+ })++ test('TCP listen failure rejects and does not leak the server', async () => {+ // Start the first server on an ephemeral port+ const handle1 = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: TEST_AUTH_TOKEN,+ enableEval: false,+ mcpRoot: null+ })+ const occupiedPort = handle1.httpPort+ expect(occupiedPort).toBeGreaterThan(0)++ try {+ // Try to start a second server on the same TCP port — must fail+ await expect(+ startServer({+ httpPort: occupiedPort,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: 'different-token',+ enableEval: false,+ mcpRoot: null+ })+ ).rejects.toThrow()++ // The first server must still be healthy — the failed second start+ // must not have corrupted the first server's listener.+ const health = await fetch(`http://127.0.0.1:${occupiedPort}/health`)+ expect(health.status).toBe(200)+ const data = (await health.json()) as HealthResponse+ expect(data.status).toBe('no_app')+ } finally {+ await handle1.close()+ }+ })++ if (isUnix) {+ test('Unix socket listen failure rejects and does not leak the server', async () => {+ const socketPath = testSocketPath()+ expect(socketPath).toBeTruthy()+ if (!socketPath) return++ // Start the first server on the socket path+ const handle1 = await startServer({+ httpPort: 0,+ withTcp: false,+ socketPath,+ authToken: TEST_AUTH_TOKEN,+ enableEval: false,+ mcpRoot: null+ })+ expect(handle1.socketPath).toBe(socketPath)++ try {+ // Try to start a second server on the same socket path — must fail.+ // removeStaleSocket detects the first server is alive and leaves+ // the socket file in place, so listen() fails with EADDRINUSE.+ await expect(+ startServer({+ httpPort: 0,+ withTcp: false,+ socketPath,+ authToken: 'different-token',+ enableEval: false,+ mcpRoot: null+ })+ ).rejects.toThrow()++ // The first server must still be healthy — verify via Unix socket+ // since withTcp:false means no HTTP port is available.+ const health = await socketRequest(socketPath, 'GET', '/health')+ expect(health.status).toBe(200)+ } finally {+ await handle1.close()+ }+ })+ }+})++// ---------------------------------------------------------------------------+// DELETE session cleanup tests (Review 03)+// ---------------------------------------------------------------------------++describe('MCP DELETE session cleanup', () => {+ let handle: ServerHandle | undefined+ let httpPort: number++ beforeAll(async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: TEST_AUTH_TOKEN,+ enableEval: false,+ mcpRoot: null+ })+ httpPort = handle.httpPort+ if (!httpPort) {+ await handle.close()+ throw new Error('TCP listener not started')+ }+ })++ afterAll(async () => {+ await handle?.close()+ })++ test('DELETE removes the session so subsequent DELETE returns 404', async () => {+ // Initialize a session via POST /mcp. Use fetch (not tcpRequest) because+ // we need the mcp-session-id response header, which tcpRequest doesn't expose.+ const initFetch = await fetch(`http://127.0.0.1:${httpPort}/mcp`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ Authorization: `Bearer ${TEST_AUTH_TOKEN}`+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: {+ protocolVersion: '2025-06-18',+ capabilities: {},+ clientInfo: { name: 'delete-test', version: '0.0.0' }+ }+ })+ })+ expect(initFetch.status).toBe(200)+ const sessionId = initFetch.headers.get('mcp-session-id')+ expect(sessionId).toBeTruthy()+ if (!sessionId) return++ // Send DELETE to terminate the session+ const deleteResp = await fetch(`http://127.0.0.1:${httpPort}/mcp`, {+ method: 'DELETE',+ headers: {+ Authorization: `Bearer ${TEST_AUTH_TOKEN}`,+ 'mcp-session-id': sessionId+ }+ })+ expect(deleteResp.status).toBe(200)++ // Send another DELETE with the same session ID — must return 404+ // because the session was deleted by the finally block+ const deleteResp2 = await fetch(`http://127.0.0.1:${httpPort}/mcp`, {+ method: 'DELETE',+ headers: {+ Authorization: `Bearer ${TEST_AUTH_TOKEN}`,+ 'mcp-session-id': sessionId+ }+ })+ expect(deleteResp2.status).toBe(404)+ })++ test('DELETE with invalid protocol version still cleans up the session', async () => {+ // Initialize a session+ const initFetch = await fetch(`http://127.0.0.1:${httpPort}/mcp`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ Authorization: `Bearer ${TEST_AUTH_TOKEN}`+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: {+ protocolVersion: '2025-06-18',+ capabilities: {},+ clientInfo: { name: 'delete-test-3', version: '0.0.0' }+ }+ })+ })+ expect(initFetch.status).toBe(200)+ const sessionId = initFetch.headers.get('mcp-session-id')+ expect(sessionId).toBeTruthy()+ if (!sessionId) return++ // Send DELETE with an invalid protocol version header.+ // The SDK's handleDeleteRequest calls validateProtocolVersion which+ // returns a 400 error response (does not throw). The try/finally+ // block must still delete the session.+ const deleteResp = await fetch(`http://127.0.0.1:${httpPort}/mcp`, {+ method: 'DELETE',+ headers: {+ Authorization: `Bearer ${TEST_AUTH_TOKEN}`,+ 'mcp-session-id': sessionId,+ 'mcp-protocol-version': 'invalid-version-999'+ }+ })+ // The SDK returns 400 for invalid protocol version+ expect(deleteResp.status).toBe(400)++ // The session must still be deleted despite the error response.+ // Send another DELETE — must return 404.+ const deleteResp2 = await fetch(`http://127.0.0.1:${httpPort}/mcp`, {+ method: 'DELETE',+ headers: {+ Authorization: `Bearer ${TEST_AUTH_TOKEN}`,+ 'mcp-session-id': sessionId+ }+ })+ expect(deleteResp2.status).toBe(404)+ })+})diff --git a/tests/engine/mcp/server-auth.test.ts b/tests/engine/mcp/server-auth.test.tsnew file mode 100644index 000000000..95e93fb0b--- /dev/null+++ b/tests/engine/mcp/server-auth.test.ts@@ -0,0 +1,444 @@+import { describe, expect, test } from 'bun:test'+import { mkdir } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'++import { Client } from '@modelcontextprotocol/sdk/client/index.js'+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'++import { SceneGraph } from '@open-pencil/scene-graph'++import { startServer, paramToZod } from '#mcp/server'+import type { DiscoveryInfo } from '#mcp/transport/discovery'++import { connectMockBrowser, waitForBrowserRegistration, type HealthResponse } from './helpers'++const isUnix = process.platform !== 'win32'+const SOCKET_DIR = join(tmpdir(), `openpencil-test-server-${process.pid}`)+const TEST_AUTH_TOKEN = 'test-auth-token'+const NO_AUTH_TOKEN = null as string | null+let testCounter = 0++// ---------------------------------------------------------------------------+// Shared helpers+// ---------------------------------------------------------------------------++function testSocketPath(): string | null {+ if (!isUnix) return null+ return join(SOCKET_DIR, `mcp-test-${process.pid}-${++testCounter}.sock`)+}++// ---------------------------------------------------------------------------+// Auto-generated auth token+// ---------------------------------------------------------------------------++describe('MCP server auto-generated auth token', () => {+ test('requires auth when authToken is omitted (auto-generated)', async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ enableEval: false,+ mcpRoot: null+ })++ const httpPort = handle.httpPort+ if (!httpPort) {+ await handle.close()+ throw new Error('withTcp: true did not produce an HTTP port')+ }++ try {+ // Request without auth should be rejected+ const response = await fetch(`http://127.0.0.1:${httpPort}/mcp`, {+ method: 'POST',+ headers: {+ accept: 'application/json, text/event-stream',+ 'content-type': 'application/json'+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: {+ protocolVersion: '2025-06-18',+ capabilities: {},+ clientInfo: { name: 'no-auth-test', version: '0.0.0' }+ }+ })+ })+ expect(response.status).toBe(401)++ // /health should show authRequired: true+ const healthResp = await fetch(`http://127.0.0.1:${httpPort}/health`)+ const health = (await healthResp.json()) as HealthResponse+ expect(health.authRequired).toBe(true)+ } finally {+ await handle.close()+ }+ })+})++// ---------------------------------------------------------------------------+// /rpc auth skip when authToken is null+// ---------------------------------------------------------------------------++describe('MCP server /rpc auth skip', () => {+ test('/rpc skips auth when authToken is explicitly null', async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: NO_AUTH_TOKEN,+ enableEval: false,+ mcpRoot: null+ })++ const httpPort = handle.httpPort+ if (!httpPort) {+ await handle.close()+ throw new Error('withTcp: true did not produce an HTTP port')+ }++ try {+ // /health should show authRequired: false+ const healthResp = await fetch(`http://127.0.0.1:${httpPort}/health`)+ const health = (await healthResp.json()) as HealthResponse+ expect(health.authRequired).toBe(false)++ // Connect a browser+ const graph = new SceneGraph()+ const browser = await connectMockBrowser(httpPort, graph)+ await waitForBrowserRegistration(httpPort)++ try {+ // /rpc should succeed without auth when browser IS connected+ const rpcResp = await fetch(`http://127.0.0.1:${httpPort}/rpc`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ command: 'tool', args: { name: 'get_current_page' } })+ })+ expect(rpcResp.status).toBe(200)++ // /mcp should still work (no auth required)+ const mcpResp = await fetch(`http://127.0.0.1:${httpPort}/mcp`, {+ method: 'POST',+ headers: {+ accept: 'application/json, text/event-stream',+ 'content-type': 'application/json'+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: {+ protocolVersion: '2025-06-18',+ capabilities: {},+ clientInfo: { name: 'no-auth-rpc-test', version: '0.0.0' }+ }+ })+ })+ expect(mcpResp.status).toBe(200)+ } finally {+ browser.close()+ }+ } finally {+ await handle.close()+ }+ })+})++// ---------------------------------------------------------------------------+// paramToZod coercion+// ---------------------------------------------------------------------------++describe('paramToZod coercion', () => {+ test('number param accepts numeric strings', () => {+ const schema = paramToZod({ type: 'number', description: 'x', required: true })+ expect(schema.parse('42')).toBe(42)+ expect(schema.parse(42)).toBe(42)+ expect(schema.parse('3.14')).toBeCloseTo(3.14)+ })++ test('number param rejects non-numeric strings', () => {+ const schema = paramToZod({ type: 'number', description: 'x', required: true })+ expect(() => schema.parse('abc')).toThrow()+ })++ test('number param respects min/max after coercion', () => {+ const schema = paramToZod({+ type: 'number',+ description: 'x',+ required: true,+ min: 0,+ max: 100+ })+ expect(schema.parse('50')).toBe(50)+ expect(() => schema.parse('200')).toThrow()+ expect(() => schema.parse('-1')).toThrow()+ })+})++// ---------------------------------------------------------------------------+// GAP-04: wrong auth token rejected+// ---------------------------------------------------------------------------++describe('MCP auth boundary', () => {+ test('server rejects requests with an incorrect auth token', async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: 'correct-token',+ enableEval: false,+ mcpRoot: null+ })+ const httpPort = handle.httpPort+ if (!httpPort) {+ await handle.close()+ throw new Error('withTcp: true did not produce an HTTP port')+ }++ try {+ const r = await fetch(`http://127.0.0.1:${httpPort}/mcp`, {+ method: 'POST',+ headers: {+ Authorization: 'Bearer wrong-token',+ 'content-type': 'application/json'+ },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'mcp.ping', params: {} })+ })+ expect(r.status).toBe(401)+ } finally {+ await handle.close()+ }+ })++ test('server rejects requests with no Authorization header when auth is enabled', async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: 'correct-token',+ enableEval: false,+ mcpRoot: null+ })+ const httpPort = handle.httpPort+ if (!httpPort) {+ await handle.close()+ throw new Error('withTcp: true did not produce an HTTP port')+ }++ try {+ const r = await fetch(`http://127.0.0.1:${httpPort}/mcp`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'mcp.ping', params: {} })+ })+ expect(r.status).toBe(401)+ } finally {+ await handle.close()+ }+ })++ test('server accepts requests with authToken: null (auth disabled)', async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: null,+ enableEval: false,+ mcpRoot: null+ })+ const httpPort = handle.httpPort+ if (!httpPort) {+ await handle.close()+ throw new Error('withTcp: true did not produce an HTTP port')+ }++ try {+ const healthResp = (await (+ await fetch(`http://127.0.0.1:${httpPort}/health`)+ ).json()) as HealthResponse+ expect(healthResp.authRequired).toBe(false)++ const mcpResp = await fetch(`http://127.0.0.1:${httpPort}/mcp`, {+ method: 'POST',+ headers: {+ accept: 'application/json, text/event-stream',+ 'content-type': 'application/json'+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: {+ protocolVersion: '2025-06-18',+ capabilities: {},+ clientInfo: { name: 'auth-disabled-test', version: '0.0.0' }+ }+ })+ })+ expect(mcpResp.status).toBe(200)+ } finally {+ await handle.close()+ }+ })+})++// ---------------------------------------------------------------------------+// GAP-05: MCP session limits — MAX_MCP_SESSIONS=10+// ---------------------------------------------------------------------------++describe('MCP session limits', () => {+ test('server returns 503 when MAX_MCP_SESSIONS is exceeded', async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: TEST_AUTH_TOKEN,+ enableEval: false,+ mcpRoot: null+ })+ const httpPort = handle.httpPort+ if (!httpPort) {+ await handle.close()+ throw new Error('withTcp: true did not produce an HTTP port')+ }++ const sessions: Client[] = []+ const openSession = async () => {+ const c = new Client({ name: 'limit-client', version: '0.0.0' })+ const t = new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${httpPort}/mcp`), {+ requestInit: { headers: { Authorization: `Bearer ${TEST_AUTH_TOKEN}` } }+ })+ await c.connect(t)+ sessions.push(c)+ return c+ }++ try {+ // Open MAX_MCP_SESSIONS (10) sessions successfully+ for (let i = 0; i < 10; i++) await openSession()++ // The 11th must be rejected with 503. The MCP SDK wraps non-2xx+ // responses in StreamableHTTPError, so we assert on the error text+ // rather than on a successful return.+ const overflow = new Client({ name: 'overflow', version: '0.0.0' })+ const overflowTransport = new StreamableHTTPClientTransport(+ new URL(`http://127.0.0.1:${httpPort}/mcp`),+ { requestInit: { headers: { Authorization: `Bearer ${TEST_AUTH_TOKEN}` } } }+ )+ let caught: unknown = null+ try {+ await overflow.connect(overflowTransport)+ await overflow.listTools()+ } catch (e) {+ caught = e+ }+ expect(caught).toBeInstanceOf(Error)+ expect((caught as Error).message).toContain('Too many active MCP sessions')+ await overflow.close().catch(() => undefined)+ } finally {+ for (const s of sessions) await s.close().catch(() => undefined)+ await handle.close()+ }+ }, 30000)+})++// ---------------------------------------------------------------------------+// GAP-03: PID recycling in discovery — stale PID should not be treated as live+// ---------------------------------------------------------------------------++describe('Discovery PID liveness', () => {+ test('readDiscoveryFile does not treat a recycled PID as live', async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const { getDiscoveryPath } = await import('#mcp/transport/paths')++ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: TEST_AUTH_TOKEN,+ enableEval: false,+ mcpRoot: null+ })+ try {+ const discoveryPath = await getDiscoveryPath()+ const raw = (await Bun.file(discoveryPath).json()) as Pick<DiscoveryInfo, 'pid'>+ expect(raw.pid).toBe(process.pid)+ } finally {+ await handle.close()+ }++ // After close, the discovery file should be gone — even if the PID+ // is reused by a future process, the absence of the file is the+ // primary signal that the server is no longer reachable.+ const discoveryPath = await getDiscoveryPath()+ expect(await Bun.file(discoveryPath).exists()).toBe(false)+ })++ test('readDiscoveryFile returns null for a discovery file with a dead PID', async () => {+ const { getDiscoveryPath } = await import('#mcp/transport/paths')+ const { readDiscoveryFile } = await import('#mcp/transport/discovery')+ const discoveryPath = await getDiscoveryPath()++ // Snapshot any existing discovery file so we can restore it after the test.+ let originalContents: string | null = null+ try {+ originalContents = await Bun.file(discoveryPath).text()+ } catch {+ void 0 // File doesn't exist — nothing to save+ }++ // Spawn a child process, kill it, and use its PID — guaranteed dead.+ // This avoids relying on a hardcoded magic number (like 4_194_304) that+ // could theoretically be alive on systems with a high pid_max.+ // Uses an inline Bun script instead of the `sleep` binary so the+ // fixture is self-contained and portable (no external dependency).+ const child = Bun.spawn({+ cmd: [process.execPath, '-e', 'setTimeout(()=>{},999999)'],+ detached: true+ })+ const deadPid = child.pid+ child.kill()+ await child.exited+ const discoveryDir = dirname(discoveryPath)+ await mkdir(discoveryDir, { recursive: true })+ await Bun.write(+ discoveryPath,+ JSON.stringify({+ pid: deadPid,+ socketPath: '/tmp/nonexistent-mcp.sock',+ httpPort: 9999,+ authRequired: true,+ authToken: 'dead-pid-test-token',+ version: '0.1.0-test',+ startedAt: new Date().toISOString()+ })+ )++ try {+ const result = await readDiscoveryFile()+ expect(result).toBeNull()+ } finally {+ // Restore the original discovery file (or remove our seeded one)+ if (originalContents !== null) {+ await Bun.write(discoveryPath, originalContents)+ } else {+ try {+ const { unlink } = await import('node:fs/promises')+ await unlink(discoveryPath)+ } catch {+ void 0+ }+ }+ }+ })+})diff --git a/tests/engine/mcp/server-transport.test.ts b/tests/engine/mcp/server-transport.test.tsnew file mode 100644index 000000000..dd121ec03--- /dev/null+++ b/tests/engine/mcp/server-transport.test.ts@@ -0,0 +1,487 @@+import { describe, expect, it, test, beforeAll, afterAll } from 'bun:test'+import { stat, mkdir, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import type { WebSocket } from 'ws'++import { SceneGraph } from '@open-pencil/scene-graph'++import { startServer, type ServerHandle } from '#mcp/server'++import {+ connectMockBrowser,+ openWs,+ readNextResponse,+ readWsJson,+ socketRequest,+ tcpRequest,+ waitForBrowserRegistration,+ type HealthResponse,+ type MockBrowser+} from './helpers'++const isUnix = process.platform !== 'win32'+const SOCKET_DIR = join(tmpdir(), `openpencil-test-server-${process.pid}`)+const SOCKET_PATH = isUnix ? join(SOCKET_DIR, 'mcp.sock') : null+const TEST_AUTH_TOKEN = 'test-auth-token'+let testCounter = 0+let sharedPort = 0++function testSocketPath(): string | null {+ if (!isUnix) return null+ return join(SOCKET_DIR, `mcp-test-${process.pid}-${++testCounter}.sock`)+}++// ---------------------------------------------------------------------------+// Unified transport tests (socket + TCP)+// ---------------------------------------------------------------------------++describe('MCP server unified transport', () => {+ let handle: ServerHandle | null = null++ beforeAll(async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ try {+ handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: SOCKET_PATH,+ authToken: 'test-token-123',+ enableEval: false,+ mcpRoot: null+ })+ sharedPort = handle.httpPort+ } catch (e) {+ await handle?.close().catch(() => undefined)+ throw e+ }+ })++ afterAll(async () => {+ await handle?.close()+ if (isUnix) await rm(SOCKET_DIR, { recursive: true, force: true })+ })++ describe('TCP HTTP endpoint', () => {+ it('responds to /health', async () => {+ const result = await tcpRequest(sharedPort, 'GET', '/health')+ expect(result.status).toBe(200)+ const health = result.data as HealthResponse+ expect(health.version).toBeTruthy()+ expect(health.status).toBe('no_app')+ expect(health.authRequired).toBe(true)+ })++ it('rejects /rpc without auth', async () => {+ const result = await tcpRequest(sharedPort, 'POST', '/rpc', { command: 'tool' })+ expect(result.status).toBe(401)+ })++ it('rejects /mcp without auth', async () => {+ const result = await tcpRequest(sharedPort, 'POST', '/mcp')+ expect(result.status).toBe(401)+ })++ it('accepts /mcp with auth token', async () => {+ const result = await tcpRequest(+ sharedPort,+ 'POST',+ '/mcp',+ {+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: {+ protocolVersion: '2025-06-18',+ capabilities: {},+ clientInfo: { name: 'smoke-test', version: '0.0.0' }+ }+ },+ {+ accept: 'application/json, text/event-stream',+ Authorization: 'Bearer test-token-123'+ }+ )+ expect(result.status).toBe(200)+ })+ })++ if (isUnix) {+ describe('Unix domain socket endpoint', () => {+ it('responds to /health via socket', async () => {+ if (!handle) throw new Error('Server handle not initialized')+ const socketPath = handle.socketPath+ expect(socketPath).toBeTruthy()+ if (!socketPath) throw new Error('socketPath is null')+ const result = await socketRequest(socketPath, 'GET', '/health')+ expect(result.status).toBe(200)+ const health = result.data as HealthResponse+ expect(health.version).toBeTruthy()+ })++ it('socket file has restrictive permissions', async () => {+ if (!handle) throw new Error('Server handle not initialized')+ const socketPath = handle.socketPath+ expect(socketPath).toBeTruthy()+ if (!socketPath) throw new Error('socketPath is null')+ const info = await stat(socketPath)+ const mode = info.mode & 0o777+ expect(mode).toBe(0o600)+ })+ })+ }++ describe('Discovery', () => {+ it('writes a discovery file matching the running server', async () => {+ const { getDiscoveryPath } = await import('#mcp/transport/paths')+ const discoveryPath = await getDiscoveryPath()+ const file = Bun.file(discoveryPath)+ expect(await file.exists()).toBe(true)+ const info = (await file.json()) as {+ pid: number+ httpPort: number+ socketPath: string | null+ version: string+ authToken: string | null+ }+ expect(info.pid).toBe(process.pid)+ expect(info.httpPort).toBe(handle?.httpPort ?? 0)+ expect(info.socketPath).toBe(handle?.socketPath ?? null)+ expect(info.version).toBeTruthy()+ expect(info.authToken).toBe('test-token-123')+ })+ })+})++// ---------------------------------------------------------------------------+// Streamable HTTP transport+// ---------------------------------------------------------------------------++describe('MCP Streamable HTTP transport', () => {+ test('returns JSON responses for request/response calls', async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: TEST_AUTH_TOKEN,+ enableEval: false,+ mcpRoot: null+ })++ const httpPort = handle.httpPort+ if (!httpPort) {+ await handle.close()+ throw new Error('withTcp: true did not produce an HTTP port')+ }++ try {+ const response = await fetch(`http://127.0.0.1:${httpPort}/mcp`, {+ method: 'POST',+ headers: {+ accept: 'application/json, text/event-stream',+ 'content-type': 'application/json',+ Authorization: `Bearer ${TEST_AUTH_TOKEN}`+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: {+ protocolVersion: '2025-06-18',+ capabilities: {},+ clientInfo: { name: 'raw-test', version: '0.0.0' }+ }+ })+ })++ expect(response.status).toBe(200)+ expect(response.headers.get('content-type')).toContain('application/json')+ expect(response.headers.get('content-type')).not.toContain('text/event-stream')+ } finally {+ await handle.close()+ }+ })+})++// ---------------------------------------------------------------------------+// WebSocket stdio bridge routing+// ---------------------------------------------------------------------------++describe('MCP WebSocket stdio bridge routing', () => {+ test('forwards stdio client requests to the registered desktop app', async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const authToken = 'bridge-test-token'+ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken,+ enableEval: false,+ mcpRoot: null+ })++ let browser: MockBrowser | undefined+ let clientWs: WebSocket | undefined+ try {+ const httpPort = handle.httpPort+ if (!httpPort) throw new Error('withTcp: true did not produce an HTTP port')++ const graph = new SceneGraph()+ browser = await connectMockBrowser(httpPort, graph, authToken)+ await waitForBrowserRegistration(httpPort)+ clientWs = await openWs(`ws://127.0.0.1:${httpPort}`, authToken)++ const register = await readWsJson<{ type: string; token?: string | null }>(clientWs)+ expect(register.type).toBe('register')+ expect(register.token).toBeNull()++ clientWs.send(+ JSON.stringify({+ type: 'request',+ id: 'stdio-1',+ command: 'tool',+ args: { name: 'get_current_page', args: {} }+ })+ )+ const response = await readNextResponse<{+ type: string+ id: string+ ok?: boolean+ result?: { name: string }+ }>(clientWs)++ expect(response.type).toBe('response')+ expect(response.id).toBe('stdio-1')+ expect(response.ok).toBe(true)+ expect(response.result?.name).toBe('Page 1')+ expect(browser.requests.at(-1)?.command).toBe('tool')+ } finally {+ clientWs?.close()+ browser?.close()+ await handle.close()+ }+ })++ test('returns a disconnected response after waiting when no app is registered', async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: 'bridge-test-token',+ enableEval: false,+ mcpRoot: null+ })++ let clientWs: WebSocket | undefined+ try {+ const httpPort = handle.httpPort+ if (!httpPort) throw new Error('withTcp: true did not produce an HTTP port')++ clientWs = await openWs(`ws://127.0.0.1:${httpPort}`, 'bridge-test-token')++ const register = await readWsJson<{ type: string; token?: string | null }>(clientWs)+ expect(register.type).toBe('register')++ clientWs.send(+ JSON.stringify({+ type: 'request',+ id: 'stdio-no-app',+ command: 'tool',+ args: { name: 'get_current_page', args: {} }+ })+ )+ const response = await readNextResponse<{+ type: string+ id: string+ ok?: boolean+ error?: string+ }>(clientWs, 15_000)++ expect(response.type).toBe('response')+ expect(response.id).toBe('stdio-no-app')+ expect(response.ok).toBe(false)+ expect(response.error).toContain('OpenPencil app is not connected')+ } finally {+ clientWs?.close()+ await handle.close()+ }+ }, 20_000)++ test('notifies already-connected stdio clients when the desktop app registers later', async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const authToken = 'bridge-test-token'+ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken,+ enableEval: false,+ mcpRoot: null+ })++ let clientWs: WebSocket | undefined+ let browser: MockBrowser | undefined+ try {+ const httpPort = handle.httpPort+ if (!httpPort) throw new Error('withTcp: true did not produce an HTTP port')++ clientWs = await openWs(`ws://127.0.0.1:${httpPort}`, authToken)+ const graph = new SceneGraph()++ const initialRegister = await readWsJson<{ type: string; token?: string | null }>(clientWs)+ expect(initialRegister.type).toBe('register')+ expect(initialRegister.token).toBeNull()++ const broadcastPromise = readWsJson<{ type: string; token?: string | null }>(clientWs, 3_000)+ browser = await connectMockBrowser(httpPort, graph, authToken)+ const broadcastRegister = await broadcastPromise+ expect(broadcastRegister.type).toBe('register')+ expect(broadcastRegister.token).toBeNull()+ } finally {+ clientWs?.close()+ browser?.close()+ await handle.close()+ }+ })++ test('pending request succeeds when browser connects during the wait', async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const authToken = 'bridge-test-token'+ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken,+ enableEval: false,+ mcpRoot: null+ })++ let clientWs: WebSocket | undefined+ let browser: MockBrowser | undefined+ try {+ const httpPort = handle.httpPort+ if (!httpPort) throw new Error('withTcp: true did not produce an HTTP port')++ clientWs = await openWs(`ws://127.0.0.1:${httpPort}`, authToken)+ const ws = clientWs++ const initReg = await readWsJson<{ type: string; token?: string | null }>(ws)+ expect(initReg.type).toBe('register')++ const requestPromise = (async () => {+ ws.send(+ JSON.stringify({+ type: 'request',+ id: 'wait-test-1',+ command: 'tool',+ args: { name: 'get_current_page', args: {} }+ })+ )+ return readNextResponse<{+ type: string+ id: string+ ok?: boolean+ result?: { name: string }+ }>(ws, 15_000)+ })()++ await new Promise<void>((r) => {+ setTimeout(r, 500)+ })+ const graph = new SceneGraph()+ browser = await connectMockBrowser(httpPort, graph, authToken)++ const response = await requestPromise+ expect(response.type).toBe('response')+ expect(response.id).toBe('wait-test-1')+ expect(response.ok).toBe(true)+ expect(response.result?.name).toBe('Page 1')+ } finally {+ clientWs?.close()+ browser?.close()+ await handle.close()+ }+ }, 20_000)++ test('routes new requests to the latest registered desktop app after reconnect', async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const authToken = 'bridge-test-token'+ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken,+ enableEval: false,+ mcpRoot: null+ })++ let clientWs: WebSocket | undefined+ let secondBrowser: MockBrowser | undefined+ try {+ const httpPort = handle.httpPort+ if (!httpPort) throw new Error('withTcp: true did not produce an HTTP port')++ const waitForHealth = async (+ predicate: (status: string) => boolean,+ timeoutMs = 2000+ ): Promise<{ status: string }> => {+ const sleep = (ms: number) =>+ new Promise<void>((resolve) => {+ setTimeout(resolve, ms)+ })+ const start = Date.now()+ let last: { status: string } = { status: 'unknown' }+ while (Date.now() - start < timeoutMs) {+ const r = await fetch(`http://127.0.0.1:${httpPort}/health`)+ last = (await r.json()) as { status: string }+ if (predicate(last.status)) return last+ await sleep(25)+ }+ throw new Error(+ `Health predicate never matched within ${timeoutMs}ms (last status: ${last.status})`+ )+ }++ const firstGraph = new SceneGraph()+ const firstBrowser = await connectMockBrowser(httpPort, firstGraph, authToken)+ await waitForHealth((s) => s === 'ok')+ firstBrowser.close()++ await waitForHealth((s) => s === 'no_app')++ const secondGraph = new SceneGraph()+ secondBrowser = await connectMockBrowser(httpPort, secondGraph, authToken)+ const browser2 = secondBrowser+ await waitForHealth((s) => s === 'ok')++ clientWs = await openWs(`ws://127.0.0.1:${httpPort}`, authToken)+ const ws = clientWs++ const initReg = await readWsJson<{ type: string; token?: string | null }>(ws)+ expect(initReg.type).toBe('register')+ expect(initReg.token).toBeNull()++ ws.send(+ JSON.stringify({+ type: 'request',+ id: 'stdio-after-reconnect',+ command: 'tool',+ args: { name: 'get_current_page', args: {} }+ })+ )+ const response = await readNextResponse<{ type: string; id: string; ok?: boolean }>(ws)++ expect(response.type).toBe('response')+ expect(response.id).toBe('stdio-after-reconnect')+ expect(response.ok).toBe(true)+ expect(browser2.requests.at(-1)?.command).toBe('tool')+ } finally {+ clientWs?.close()+ secondBrowser?.close()+ await handle.close()+ }+ }, 10000)+})diff --git a/tests/engine/mcp/server.test.ts b/tests/engine/mcp/server.test.tsindex 82c73de96..b79bce59d 100644--- a/tests/engine/mcp/server.test.ts+++ b/tests/engine/mcp/server.test.ts@@ -1,161 +1,102 @@import { describe, expect, test, beforeEach, afterEach } from 'bun:test'-import { mkdir, realpath } from 'node:fs/promises'-import type { AddressInfo } from 'node:net'+import { mkdir, stat } from 'node:fs/promises'import { tmpdir } from 'node:os'-import path from 'node:path'+import { join } from 'node:path'-import { serve } from '@hono/node-server'import { Client } from '@modelcontextprotocol/sdk/client/index.js'import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'-import WebSocket from 'ws'-import {- ALL_TOOLS,- FigmaAPI,- SceneGraph,- computeAllLayouts,- executeRpcCommand-} from '@open-pencil/core'--import { startServer, paramToZod } from '#mcp/server'--interface MockBrowserRequest {- command: string- args?: unknown-}--interface MockBrowser {- ws: WebSocket- graph: SceneGraph- requests: MockBrowserRequest[]- close: () => void-}--const TEST_MCP_ROOT = path.join(tmpdir(), 'open-pencil-mcp-root')--function connectMockBrowser(port: number, graph: SceneGraph): Promise<MockBrowser> {- return new Promise((resolve, reject) => {- const ws = new WebSocket(`ws://127.0.0.1:${port}`)- const requests: MockBrowserRequest[] = []- const token = 'test-token-' + Date.now()-- ws.on('open', () => {- ws.send(JSON.stringify({ type: 'register', token }))-- ws.on('message', async (raw) => {- const msg = JSON.parse(raw.toString()) as {- type: string- id: string- command: string- args?: unknown- }- if (msg.type !== 'request') return-- try {- const command = msg.command- requests.push({ command, args: msg.args })- const args = msg.args as { name?: string; args?: Record<string, unknown> } | undefined-- let result: unknown- if (command === 'tool' && args?.name) {- const def = ALL_TOOLS.find((t) => t.name === args.name)- if (!def) throw new Error(`Unknown tool: ${args.name}`)- const api = new FigmaAPI(graph)- api.currentPage = api.wrapNode(graph.getPages()[0].id)- result = await def.execute(api, args.args ?? {})- if (def.mutates) computeAllLayouts(graph)- } else if (- command === 'save_file' ||- command === 'new_document' ||- command === 'open_file'- ) {- result = {}- } else {- result = executeRpcCommand(graph, command, args ?? {})- }-- ws.send(JSON.stringify({ type: 'response', id: msg.id, ok: true, result }))- } catch (e) {- ws.send(- JSON.stringify({- type: 'response',- id: msg.id,- ok: false,- error: e instanceof Error ? e.message : String(e)- })- )- }- })-- resolve({ ws, graph, requests, close: () => ws.close() })- })-- ws.on('error', reject)- })-}+import { SceneGraph } from '@open-pencil/scene-graph'-function readWsJson<T>(ws: WebSocket): Promise<T> {- return new Promise((resolve, reject) => {- const timer = setTimeout(- () => reject(new Error('Timed out waiting for WebSocket message')),- 1000- )- ws.once('message', (raw) => {- clearTimeout(timer)- try {- resolve(JSON.parse(raw.toString()) as T)- } catch (error) {- reject(error)- }- })- ws.once('error', (error) => {- clearTimeout(timer)- reject(error)- })- })-}+import { startServer } from '#mcp/server'-function openWs(url: string): Promise<WebSocket> {- const ws = new WebSocket(url)- return new Promise((resolve, reject) => {- ws.once('open', () => resolve(ws))- ws.once('error', reject)- })+import {+ connectMockBrowser,+ waitForBrowserRegistration,+ type HealthResponse,+ type MockBrowser+} from './helpers'++const isUnix = process.platform !== 'win32'+const SOCKET_DIR = join(tmpdir(), `openpencil-test-server-${process.pid}`)+const TEST_MCP_ROOT = join(tmpdir(), 'open-pencil-mcp-root')+const TEST_AUTH_TOKEN = 'test-auth-token'+let testCounter = 0++// ---------------------------------------------------------------------------+// Test client: starts server with ephemeral TCP port, connects mock browser + MCP client+// ---------------------------------------------------------------------------++function testSocketPath(): string | null {+ if (!isUnix) return null+ return join(SOCKET_DIR, `mcp-test-${process.pid}-${++testCounter}.sock`)}-function waitForWsListening(wss: InstanceType<typeof WebSocket.Server>): Promise<number> {- return new Promise((resolve) => {- if (wss.address()) {- resolve((wss.address() as AddressInfo).port)- return- }- wss.on('listening', () => resolve((wss.address() as AddressInfo).port))+async function createTestClient() {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const authToken = 'test-client-token'+ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken,+ enableEval: false,+ mcpRoot: null})-}-async function createTestClient() {- const { app, wss, close: closeServer } = startServer({ httpPort: 0, wsPort: 0 })- const httpServer = serve({ fetch: app.fetch, port: 0, hostname: '127.0.0.1' })- const actualHttpPort = (httpServer.address() as AddressInfo).port- const actualWsPort = await waitForWsListening(wss)+ const httpPort = handle.httpPort+ if (!httpPort) {+ await handle.close()+ throw new Error('TCP listener not started')+ }const graph = new SceneGraph()- const browser = await connectMockBrowser(actualWsPort, graph)+ let browser: MockBrowser | undefined+ let client: Client | undefined- const client = new Client({ name: 'test-client', version: '0.0.0' })- const transport = new StreamableHTTPClientTransport(- new URL(`http://127.0.0.1:${actualHttpPort}/mcp`)- )- await client.connect(transport)+ try {+ browser = await connectMockBrowser(httpPort, graph, authToken)+ await waitForBrowserRegistration(httpPort)++ client = new Client({ name: 'test-client', version: '0.0.0' })+ const transport = new StreamableHTTPClientTransport(+ new URL(`http://127.0.0.1:${httpPort}/mcp`),+ {+ requestInit: { headers: { Authorization: `Bearer ${authToken}` } }+ }+ )+ await client.connect(transport)+ } catch (e) {+ await client?.close().catch(() => undefined)+ browser?.close()+ await handle.close()+ throw e+ }+ const safeClient = client+ const safeBrowser = browserreturn {- client,+ client: safeClient,graph,+ handle,close: async () => {- await client.close()- browser.close()- closeServer()- httpServer.close()+ const errors: unknown[] = []+ try {+ await safeClient?.close()+ } catch (e) {+ errors.push(e)+ }+ try {+ safeBrowser?.close()+ } catch (e) {+ errors.push(e)+ }+ try {+ await handle.close()+ } catch (e) {+ errors.push(e)+ }+ if (errors.length > 0) throw errors[0]}}}@@ -165,20 +106,30 @@ function parseResult(result: { content: { type: string; text?: string }[] }): unreturn textContent?.text ? JSON.parse(textContent.text) : null}+// ---------------------------------------------------------------------------+// MCP tool + session tests+// ---------------------------------------------------------------------------+describe('MCP server', () => {let client: Clientlet graph: SceneGraph- let cleanup: () => Promise<void>+ let cleanup: (() => Promise<void>) | null = nullbeforeEach(async () => {- const ctx = await createTestClient()- client = ctx.client- graph = ctx.graph- cleanup = ctx.close+ try {+ const ctx = await createTestClient()+ client = ctx.client+ graph = ctx.graph+ cleanup = ctx.close+ } catch (e) {+ if (cleanup) await cleanup().catch(() => undefined)+ throw e+ }})afterEach(async () => {- await cleanup()+ if (cleanup) await cleanup()+ cleanup = null})test('lists all registered tools', async () => {@@ -280,308 +231,330 @@ describe('MCP server', () => {})})-describe('MCP Streamable HTTP transport', () => {- test('returns JSON responses for request/response calls', async () => {- const { app, close: closeServer } = startServer({ httpPort: 0, wsPort: 0 })- const httpServer = serve({ fetch: app.fetch, port: 0, hostname: '127.0.0.1' })- const actualHttpPort = (httpServer.address() as AddressInfo).port+// ---------------------------------------------------------------------------+// mcpRoot tests+// ---------------------------------------------------------------------------- try {- const response = await fetch(`http://127.0.0.1:${actualHttpPort}/mcp`, {- method: 'POST',- headers: {- accept: 'application/json, text/event-stream',- 'content-type': 'application/json'- },- body: JSON.stringify({- jsonrpc: '2.0',- id: 1,- method: 'initialize',- params: {- protocolVersion: '2025-06-18',- capabilities: {},- clientInfo: { name: 'raw-test', version: '0.0.0' }- }- })- })-- expect(response.status).toBe(200)- expect(response.headers.get('content-type')).toContain('application/json')- expect(response.headers.get('content-type')).not.toContain('text/event-stream')- } finally {- closeServer()- httpServer.close()- }- })-})+describe('MCP server with mcpRoot', () => {+ async function withMcpRootServer(+ mcpRoot: string | null,+ fn: (client: Client, browser: MockBrowser, graph: SceneGraph) => Promise<void>+ ) {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ if (mcpRoot) await mkdir(mcpRoot, { recursive: true })+ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: TEST_AUTH_TOKEN,+ enableEval: false,+ mcpRoot+ })-describe('MCP WebSocket stdio bridge routing', () => {- test('forwards stdio client requests to the registered desktop app', async () => {- const { wss, close: closeServer } = startServer({ httpPort: 0, wsPort: 0 })- const wsPort = await waitForWsListening(wss)- const graph = new SceneGraph()- const browser = await connectMockBrowser(wsPort, graph)- const clientWs = await openWs(`ws://127.0.0.1:${wsPort}`)+ let browser: MockBrowser | null = null+ let client: Client | null = nulltry {- const register = await readWsJson<{ type: string; token?: string }>(clientWs)- expect(register.type).toBe('register')- expect(register.token).toBeTruthy()-- clientWs.send(- JSON.stringify({- type: 'request',- id: 'stdio-1',- command: 'tool',- args: { name: 'get_current_page', args: {} }- })+ const httpPort = handle.httpPort+ if (!httpPort) throw new Error('withTcp: true did not produce an HTTP port')++ const graph = new SceneGraph()+ browser = await connectMockBrowser(httpPort, graph, TEST_AUTH_TOKEN)+ await waitForBrowserRegistration(httpPort)++ client = new Client({ name: 'test-root', version: '0.0.0' })+ const transport = new StreamableHTTPClientTransport(+ new URL(`http://127.0.0.1:${httpPort}/mcp`),+ { requestInit: { headers: { Authorization: `Bearer ${TEST_AUTH_TOKEN}` } } })- const response = await readWsJson<{- type: string- id: string- ok?: boolean- result?: { name: string }- }>(clientWs)-- expect(response.type).toBe('response')- expect(response.id).toBe('stdio-1')- expect(response.ok).toBe(true)- expect(response.result?.name).toBe('Page 1')- expect(browser.requests.at(-1)?.command).toBe('tool')+ await client.connect(transport)++ await fn(client, browser, graph)} finally {- clientWs.close()- browser.close()- closeServer()+ await client?.close().catch(() => undefined)+ browser?.close()+ await handle.close()}+ }++ test('registers open_file and new_document tools when mcpRoot is set', async () => {+ await withMcpRootServer(TEST_MCP_ROOT, async (client) => {+ const { tools } = await client.listTools()+ const names = tools.map((t) => t.name)+ expect(names).toContain('open_file')+ expect(names).toContain('new_document')+ })})- test('returns a disconnected response instead of timing out when no app is registered', async () => {- const { wss, close: closeServer } = startServer({ httpPort: 0, wsPort: 0 })- const wsPort = await waitForWsListening(wss)- const clientWs = await openWs(`ws://127.0.0.1:${wsPort}`)+ test('save_file accepts an explicit path inside mcpRoot', async () => {+ await withMcpRootServer(TEST_MCP_ROOT, async (client, browser) => {+ await mkdir(join(TEST_MCP_ROOT, 'unicode'), { recursive: true })+ const savePath = join(TEST_MCP_ROOT, 'unicode', 'пример.fig')+ const result = await client.callTool({+ name: 'save_file',+ arguments: { path: savePath }+ })- try {- clientWs.send(- JSON.stringify({- type: 'request',- id: 'stdio-no-app',- command: 'tool',- args: { name: 'get_current_page', args: {} }- })- )- const response = await readWsJson<{ type: string; id: string; ok?: boolean; error?: string }>(- clientWs- )+ expect(result.isError).not.toBe(true)+ const request = browser.requests.find((item) => item.command === 'save_file')+ // The server sends the canonical (realpath-resolved) path to the browser+ // to prevent TOCTOU races. On macOS, /var -> /private/var.+ const { realpath } = await import('node:fs/promises')+ const { dirname, basename } = await import('node:path')+ const canonicalPath = join(await realpath(dirname(savePath)), basename(savePath))+ expect(request?.args).toEqual({ path: canonicalPath })+ })+ })- expect(response.type).toBe('response')- expect(response.id).toBe('stdio-no-app')- expect(response.ok).toBe(false)- expect(response.error).toContain('OpenPencil app is not connected')- } finally {- clientWs.close()- closeServer()- }+ test('save_file rejects paths outside mcpRoot', async () => {+ await withMcpRootServer(TEST_MCP_ROOT, async (client, browser) => {+ const result = await client.callTool({+ name: 'save_file',+ arguments: { path: join(join(TEST_MCP_ROOT, '..'), 'outside.fig') }+ })++ expect(result.isError).toBe(true)+ expect(browser.requests.some((item) => item.command === 'save_file')).toBe(false)+ })})- test('notifies already-connected stdio clients when the desktop app registers later', async () => {- const { wss, close: closeServer } = startServer({ httpPort: 0, wsPort: 0 })- const wsPort = await waitForWsListening(wss)- const clientWs = await openWs(`ws://127.0.0.1:${wsPort}`)- const graph = new SceneGraph()- let browser: MockBrowser | null = null+ test('does not register open_file when mcpRoot is null', async () => {+ await withMcpRootServer(null, async (client) => {+ const { tools } = await client.listTools()+ const names = tools.map((t) => t.name)+ expect(names).not.toContain('open_file')+ expect(names).not.toContain('new_document')+ })+ })+})+// ---------------------------------------------------------------------------+// GAP-01: server.close() resource cleanup+// ---------------------------------------------------------------------------++describe('MCP server lifecycle', () => {+ test('close() removes the discovery file from disk', async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const { getDiscoveryPath } = await import('#mcp/transport/paths')+ const discoveryPath = await getDiscoveryPath()++ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: TEST_AUTH_TOKEN,+ enableEval: false,+ mcpRoot: null+ })try {- browser = await connectMockBrowser(wsPort, graph)- const register = await readWsJson<{ type: string; token?: string }>(clientWs)- expect(register.type).toBe('register')- expect(register.token).toBeTruthy()+ expect(await Bun.file(discoveryPath).exists()).toBe(true)} finally {- clientWs.close()- browser?.close()- closeServer()+ await handle.close()}+ expect(await Bun.file(discoveryPath).exists()).toBe(false)})- test('routes new requests to the latest registered desktop app after reconnect', async () => {- const { wss, close: closeServer } = startServer({ httpPort: 0, wsPort: 0 })- const wsPort = await waitForWsListening(wss)- const firstBrowser = await connectMockBrowser(wsPort, new SceneGraph())- const secondBrowser = await connectMockBrowser(wsPort, new SceneGraph())- const clientWs = await openWs(`ws://127.0.0.1:${wsPort}`)-+ test('close() removes the unix socket file from disk', async () => {+ if (!isUnix) return+ await mkdir(SOCKET_DIR, { recursive: true })+ const socketPath = testSocketPath()+ expect(socketPath).toBeTruthy()++ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath,+ authToken: TEST_AUTH_TOKEN,+ enableEval: false,+ mcpRoot: null+ })try {- await readWsJson<{ type: string; token?: string }>(clientWs)- clientWs.send(- JSON.stringify({- type: 'request',- id: 'stdio-after-reconnect',- command: 'tool',- args: { name: 'get_current_page', args: {} }- })- )- const response = await readWsJson<{ type: string; id: string; ok?: boolean }>(clientWs)-- expect(response.type).toBe('response')- expect(response.id).toBe('stdio-after-reconnect')- expect(response.ok).toBe(true)- expect(firstBrowser.requests).toHaveLength(0)- expect(secondBrowser.requests.at(-1)?.command).toBe('tool')+ const info = await stat(socketPath)+ expect(info.isSocket()).toBe(true)} finally {- clientWs.close()- firstBrowser.close()- secondBrowser.close()- closeServer()+ await handle.close()}+ await expect(stat(socketPath)).rejects.toThrow()})-})--describe('MCP server with mcpRoot', () => {- test('registers open_file and new_document tools when mcpRoot is set', async () => {- const {- app,- wss,- close: closeServer- } = startServer({ httpPort: 0, wsPort: 0, mcpRoot: TEST_MCP_ROOT })- const httpServer = serve({ fetch: app.fetch, port: 0, hostname: '127.0.0.1' })- const actualWsPort = await waitForWsListening(wss)-- const graph = new SceneGraph()- const browser = await connectMockBrowser(actualWsPort, graph)-- const client = new Client({ name: 'test-root', version: '0.0.0' })- const transport = new StreamableHTTPClientTransport(- new URL(`http://127.0.0.1:${(httpServer.address() as AddressInfo).port}/mcp`)- )- await client.connect(transport)-- const { tools } = await client.listTools()- const names = tools.map((t) => t.name)- expect(names).toContain('open_file')- expect(names).toContain('new_document')-- await client.close()- browser.close()- closeServer()- httpServer.close()- })-- test('save_file accepts an explicit path inside mcpRoot', async () => {- const {- app,- wss,- close: closeServer- } = startServer({ httpPort: 0, wsPort: 0, mcpRoot: TEST_MCP_ROOT })- const httpServer = serve({ fetch: app.fetch, port: 0, hostname: '127.0.0.1' })- const actualWsPort = await waitForWsListening(wss)-- const graph = new SceneGraph()- const browser = await connectMockBrowser(actualWsPort, graph)-- const client = new Client({ name: 'test-root-save', version: '0.0.0' })- const transport = new StreamableHTTPClientTransport(- new URL(`http://127.0.0.1:${(httpServer.address() as AddressInfo).port}/mcp`)- )- await client.connect(transport)- const savePath = path.join(TEST_MCP_ROOT, 'unicode', 'пример.fig')- await mkdir(path.dirname(savePath), { recursive: true })- const result = await client.callTool({- name: 'save_file',- arguments: { path: savePath }+ test('close() removes socket file when no replacement server is listening', async () => {+ if (!isUnix) return+ await mkdir(SOCKET_DIR, { recursive: true })+ const socketPath = testSocketPath()++ const handle1 = await startServer({+ httpPort: 0,+ withTcp: false,+ socketPath,+ authToken: TEST_AUTH_TOKEN,+ enableEval: false,+ mcpRoot: null})-- expect(result.isError).not.toBe(true)- const request = browser.requests.find((item) => item.command === 'save_file')- const canonicalPath = path.join(await realpath(path.dirname(savePath)), path.basename(savePath))- expect(request?.args).toEqual({ path: canonicalPath })-- await client.close()- browser.close()- closeServer()- httpServer.close()+ try {+ expect(handle1.socketPath).toBe(socketPath)+ } finally {+ await handle1.close()+ }+ await expect(stat(socketPath)).rejects.toThrow()})- test('save_file rejects paths outside mcpRoot', async () => {- const {- app,- wss,- close: closeServer- } = startServer({ httpPort: 0, wsPort: 0, mcpRoot: TEST_MCP_ROOT })- const httpServer = serve({ fetch: app.fetch, port: 0, hostname: '127.0.0.1' })- const actualWsPort = await waitForWsListening(wss)-- const graph = new SceneGraph()- const browser = await connectMockBrowser(actualWsPort, graph)-- const client = new Client({ name: 'test-root-save-outside', version: '0.0.0' })- const transport = new StreamableHTTPClientTransport(- new URL(`http://127.0.0.1:${(httpServer.address() as AddressInfo).port}/mcp`)- )- await client.connect(transport)-- const result = await client.callTool({- name: 'save_file',- arguments: { path: path.join(path.dirname(TEST_MCP_ROOT), 'outside.fig') }+ test('close() is idempotent and does not throw on second call', async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: TEST_AUTH_TOKEN,+ enableEval: false,+ mcpRoot: null})-- expect(result.isError).toBe(true)- expect(browser.requests.some((item) => item.command === 'save_file')).toBe(false)-- await client.close()- browser.close()- closeServer()- httpServer.close()+ await handle.close()+ await expect(handle.close()).resolves.toBeUndefined()})- test('does not register open_file when mcpRoot is null', async () => {- const { app, wss, close: closeServer } = startServer({ httpPort: 0, wsPort: 0 })- const httpServer = serve({ fetch: app.fetch, port: 0, hostname: '127.0.0.1' })- const actualWsPort = await waitForWsListening(wss)-- const graph = new SceneGraph()- const browser = await connectMockBrowser(actualWsPort, graph)-- const client = new Client({ name: 'test-no-root', version: '0.0.0' })- const transport = new StreamableHTTPClientTransport(- new URL(`http://127.0.0.1:${(httpServer.address() as AddressInfo).port}/mcp`)- )- await client.connect(transport)+ test('close() rejects subsequent RPC requests', async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: TEST_AUTH_TOKEN,+ enableEval: false,+ mcpRoot: null+ })+ const httpPort = handle.httpPort+ if (!httpPort) {+ await handle.close()+ throw new Error('withTcp: true did not produce an HTTP port')+ }- const { tools } = await client.listTools()- const names = tools.map((t) => t.name)- expect(names).not.toContain('open_file')- expect(names).not.toContain('new_document')+ try {+ const healthyResp = await fetch(`http://127.0.0.1:${httpPort}/health`)+ expect(healthyResp.status).toBe(200)+ } finally {+ await handle.close()+ }- await client.close()- browser.close()- closeServer()- httpServer.close()+ await expect(fetch(`http://127.0.0.1:${httpPort}/health`)).rejects.toThrow()})})-describe('paramToZod coercion', () => {- test('number param accepts numeric strings', () => {- const schema = paramToZod({ type: 'number', description: 'x', required: true })- expect(schema.parse('42')).toBe(42)- expect(schema.parse(42)).toBe(42)- expect(schema.parse('3.14')).toBeCloseTo(3.14)- })+// ---------------------------------------------------------------------------+// GAP-02: concurrent startServer calls produce non-overlapping servers+// ---------------------------------------------------------------------------++describe('MCP server concurrent startServer', () => {+ test('two simultaneous startServer calls each get their own discovery file and both stay up', async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const { getDiscoveryPath } = await import('#mcp/transport/paths')++ // Use unique socket paths so the two servers don't fight over the+ // socket file. The test still covers discovery atomicity by writing+ // to the same shared discovery path.+ const results = await Promise.allSettled([+ startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: 'token-a',+ enableEval: false,+ mcpRoot: null+ }),+ startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: 'token-b',+ enableEval: false,+ mcpRoot: null+ })+ ])- test('number param rejects non-numeric strings', () => {- const schema = paramToZod({ type: 'number', description: 'x', required: true })- expect(() => schema.parse('abc')).toThrow()- })+ const a = results[0].status === 'fulfilled' ? results[0].value : null+ const b = results[1].status === 'fulfilled' ? results[1].value : null- test('number param respects min/max after coercion', () => {- const schema = paramToZod({- type: 'number',- description: 'x',- required: true,- min: 0,- max: 100+ if (!a || !b) {+ if (a) await a.close()+ if (b) await b.close()+ throw new Error('Multi-server startup failed')+ }++ try {+ // Both servers are listening on their own ephemeral ports.+ expect(a.httpPort).toBeGreaterThan(0)+ expect(b.httpPort).toBeGreaterThan(0)+ expect(a.httpPort).not.toBe(b.httpPort)++ // Each responds on /health with the expected auth state.+ const aHealth = (await (+ await fetch(`http://127.0.0.1:${a.httpPort}/health`)+ ).json()) as HealthResponse+ const bHealth = (await (+ await fetch(`http://127.0.0.1:${b.httpPort}/health`)+ ).json()) as HealthResponse+ expect(aHealth.status).toBe('no_app')+ expect(bHealth.status).toBe('no_app')++ // Discovery file exists and was last written by one of the two servers+ // (atomic rename guarantees it's a complete file, not interleaved).+ const discoveryPath = await getDiscoveryPath()+ const file = Bun.file(discoveryPath)+ expect(await file.exists()).toBe(true)+ const info = (await file.json()) as { pid: number; authToken: string }+ expect(info.pid).toBe(process.pid)+ expect(['token-a', 'token-b']).toContain(info.authToken)+ } finally {+ await a.close()+ await b.close()+ }+ }, 15000)++ test("closing one server does not delete another server's discovery file", async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const { getDiscoveryPath } = await import('#mcp/transport/paths')++ const a = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: 'token-a',+ enableEval: false,+ mcpRoot: null})- expect(schema.parse('50')).toBe(50)- expect(() => schema.parse('200')).toThrow()- expect(() => schema.parse('-1')).toThrow()- })+ let b: ServerHandle | undefined+ try {+ b = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: 'token-b',+ enableEval: false,+ mcpRoot: null+ })+ } catch (err) {+ await a.close()+ throw err+ }++ try {+ // Close server a — its discovery cleanup should NOT remove the file+ // because server b still owns it (different auth token).+ await a.close()++ // Server b should still be healthy and reachable.+ const bHealth = (await (+ await fetch(`http://127.0.0.1:${b.httpPort}/health`)+ ).json()) as HealthResponse+ expect(bHealth.status).toBe('no_app')++ // Discovery file should still exist (owned by server b now).+ const discoveryPath = await getDiscoveryPath()+ const file = Bun.file(discoveryPath)+ expect(await file.exists()).toBe(true)+ const info = (await file.json()) as { authToken: string }+ expect(info.authToken).toBe('token-b')+ } finally {+ await b.close()+ }+ }, 15000)})diff --git a/tests/engine/mcp/stdio-auth.test.ts b/tests/engine/mcp/stdio-auth.test.tsnew file mode 100644index 000000000..754183d49--- /dev/null+++ b/tests/engine/mcp/stdio-auth.test.ts@@ -0,0 +1,290 @@+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test'+import { existsSync } from 'node:fs'+import { mkdir, rm, writeFile, unlink } from 'node:fs/promises'+import { createServer, type Server } from 'node:http'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { createStdioRpcBridge } from '#mcp/stdio-bridge'++const TEST_DIR = join(tmpdir(), `openpencil-test-stdio-auth-${process.pid}`)+const TEST_SOCKET = join(TEST_DIR, 'mcp-test.sock')+const TEST_DISCOVERY_PATH = join(TEST_DIR, 'test-mcp.json')+const AUTH_TOKEN = 'test-auto-token'++/**+ * Writes a mock discovery file at the test-isolated discovery path so the+ * bridge's readDiscoveryFile() finds it without touching the developer's+ * real mcp.json.+ */+async function writeMockDiscovery(+ socketPath: string,+ authToken: string | null,+ httpPort: number = 0+): Promise<void> {+ await writeFile(+ TEST_DISCOVERY_PATH,+ JSON.stringify({+ pid: process.pid,+ socketPath,+ httpPort,+ authRequired: authToken !== null,+ authToken,+ version: '0.1.0-test',+ startedAt: new Date().toISOString()+ }),+ 'utf-8'+ )+}++/**+ * Creates and starts a minimal HTTP server on a Unix socket that+ * mimics the MCP server's health and RPC endpoints.+ */+function createMockMcpServer(+ socketPath: string,+ options: {+ /** Auth token required for /rpc. null = no auth needed. */+ authToken?: string | null+ /** When true, the first /rpc request returns 401 regardless of auth. */+ firstRpcFailsWith401?: boolean+ } = {}+): Promise<Server> {+ const { authToken = null, firstRpcFailsWith401 = false } = options+ let rpcCount = 0++ return new Promise((resolve, reject) => {+ const server = createServer((req, res) => {+ // Health check — always succeeds+ if (req.url === '/health' && req.method === 'GET') {+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ status: 'ok' }))+ return+ }++ // RPC endpoint+ if (req.url === '/rpc' && req.method === 'POST') {+ rpcCount++++ // Simulate first-call 401 for retry testing+ if (firstRpcFailsWith401 && rpcCount === 1) {+ res.writeHead(401)+ res.end(JSON.stringify({ error: 'Unauthorized' }))+ return+ }++ // Check auth+ const auth = req.headers.authorization+ if (authToken && auth !== `Bearer ${authToken}`) {+ res.writeHead(401)+ res.end(JSON.stringify({ error: 'bad auth' }))+ return+ }++ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ result: `ok-${rpcCount}` }))+ return+ }++ res.writeHead(404)+ res.end(JSON.stringify({ error: 'not found' }))+ })++ server.once('error', reject)+ server.listen(socketPath, () => {+ server.off('error', reject)+ resolve(server)+ })+ })+}++/**+ * Creates a stdio bridge and returns a Promise that resolves with the+ * bridge once its onReady callback fires (meaning health check passed+ * and ready=true). Rejects with a timeout if the bridge never becomes+ * ready.+ */+async function createBridgeAndWaitForReady(+ options: Parameters<typeof createStdioRpcBridge>[0]+): Promise<ReturnType<typeof createStdioRpcBridge>> {+ const { onReady: _ignored, ...rest } = options+ const TIMEOUT_MS = 5_000++ return new Promise((resolve, reject) => {+ let bridge: ReturnType<typeof createStdioRpcBridge> | null = null++ const timer = setTimeout(() => {+ bridge?.close()+ reject(new Error('Bridge never became ready'))+ }, TIMEOUT_MS)++ bridge = createStdioRpcBridge({+ ...rest,+ onReady: () => {+ clearTimeout(timer)+ resolve(bridge as ReturnType<typeof createStdioRpcBridge>)+ }+ })+ })+}++const isUnix = process.platform !== 'win32'++describe.skipIf(!isUnix)('Fix 4 - Auth token auto-discovery and transparent retry', () => {+ let httpServer: Server | null = null+ let bridges: Array<ReturnType<typeof createStdioRpcBridge>> = []+ const origSocketEnv = process.env.OPENPENCIL_MCP_SOCKET+ const origDiscoveryEnv = process.env.OPENPENCIL_MCP_DISCOVERY_PATH++ beforeAll(() => {+ process.env.OPENPENCIL_MCP_DISCOVERY_PATH = TEST_DISCOVERY_PATH+ })++ afterAll(() => {+ if (origDiscoveryEnv === undefined) {+ delete process.env.OPENPENCIL_MCP_DISCOVERY_PATH+ } else {+ process.env.OPENPENCIL_MCP_DISCOVERY_PATH = origDiscoveryEnv+ }+ })++ afterEach(async () => {+ for (const bridge of bridges) {+ try {+ bridge.close()+ } catch {+ void 0+ }+ }+ bridges = []+ if (httpServer) {+ await new Promise<void>((resolve) => {+ httpServer?.close(() => resolve())+ })+ httpServer = null+ }+ if (origSocketEnv === undefined) {+ delete process.env.OPENPENCIL_MCP_SOCKET+ } else {+ process.env.OPENPENCIL_MCP_SOCKET = origSocketEnv+ }+ try {+ if (existsSync(TEST_SOCKET)) await unlink(TEST_SOCKET)+ } catch {+ void 0+ }+ try {+ if (existsSync(TEST_DISCOVERY_PATH)) await unlink(TEST_DISCOVERY_PATH)+ } catch {+ void 0+ }+ await rm(TEST_DIR, { recursive: true, force: true })+ })++ test('auto-discovers auth token from discovery file', async () => {+ await mkdir(TEST_DIR, { recursive: true })++ // Set up infrastructure BEFORE creating the bridge, so its async+ // connect() succeeds on the first attempt.+ await writeMockDiscovery(TEST_SOCKET, AUTH_TOKEN)+ process.env.OPENPENCIL_MCP_SOCKET = TEST_SOCKET+ httpServer = await createMockMcpServer(TEST_SOCKET, { authToken: AUTH_TOKEN })++ // Bridge without explicit authToken — should auto-discover+ const bridge = await createBridgeAndWaitForReady({+ socketPath: TEST_SOCKET+ })+ bridges.push(bridge)++ const result = await bridge.sendRpc({ command: 'test' })+ expect(result).toEqual({ result: 'ok-1' })+ }, 10_000)++ test('401 with auto-discovered token retries transparently', async () => {+ await mkdir(TEST_DIR, { recursive: true })+ await writeMockDiscovery(TEST_SOCKET, AUTH_TOKEN)+ process.env.OPENPENCIL_MCP_SOCKET = TEST_SOCKET+ httpServer = await createMockMcpServer(TEST_SOCKET, {+ authToken: AUTH_TOKEN,+ firstRpcFailsWith401: true+ })++ const bridge = await createBridgeAndWaitForReady({+ socketPath: TEST_SOCKET+ // No authToken — auto-discovered+ })+ bridges.push(bridge)++ // The bridge is ready. sendRpc hits the server:+ // Attempt 1 → 401 → bridge re-reads discovery, retries+ // Attempt 2 → 200 with ok-2 (second call to /rpc)+ const result = await bridge.sendRpc({ command: 'test' })+ expect(result).toEqual({ result: 'ok-2' })+ }, 10_000)++ test('401 with explicit auth token surfaces error immediately (no retry)', async () => {+ await mkdir(TEST_DIR, { recursive: true })+ await writeMockDiscovery(TEST_SOCKET, AUTH_TOKEN)+ process.env.OPENPENCIL_MCP_SOCKET = TEST_SOCKET+ httpServer = await createMockMcpServer(TEST_SOCKET, { authToken: AUTH_TOKEN })++ // Bridge has EXPLICIT wrong token — 401 must surface immediately+ const bridge = await createBridgeAndWaitForReady({+ socketPath: TEST_SOCKET,+ authToken: 'wrong-token',+ reconnectDelayMs: 500+ })+ bridges.push(bridge)++ await expect(bridge.sendRpc({ command: 'test' })).rejects.toThrow(+ 'Unauthorized: check OPENPENCIL_MCP_AUTH_TOKEN'+ )+ }, 10_000)++ test('explicit auth token is NOT overridden by discovery file', async () => {+ await mkdir(TEST_DIR, { recursive: true })+ await writeMockDiscovery(TEST_SOCKET, 'discovery-token-unused')+ process.env.OPENPENCIL_MCP_SOCKET = TEST_SOCKET+ httpServer = await createMockMcpServer(TEST_SOCKET, { authToken: 'explicit-token' })++ const bridge = await createBridgeAndWaitForReady({+ socketPath: TEST_SOCKET,+ authToken: 'explicit-token',+ reconnectDelayMs: 500+ })+ bridges.push(bridge)++ const result = await bridge.sendRpc({ command: 'test' })+ expect(result).toEqual({ result: 'ok-1' })+ }, 10_000)++ test('/rpc rejects unauthenticated requests when authToken is set', async () => {+ await mkdir(TEST_DIR, { recursive: true })+ await writeMockDiscovery(TEST_SOCKET, AUTH_TOKEN)+ process.env.OPENPENCIL_MCP_SOCKET = TEST_SOCKET+ httpServer = await createMockMcpServer(TEST_SOCKET, { authToken: AUTH_TOKEN })++ // Bridge with no explicit token — it auto-discovers from the discovery+ // file and should succeed because the discovery file has the correct token.+ // This verifies the /rpc 401 → retry → 200 flow indirectly.+ const bridge = await createBridgeAndWaitForReady({+ socketPath: TEST_SOCKET+ })+ bridges.push(bridge)++ const result = await bridge.sendRpc({ command: 'test' })+ expect(result).toEqual({ result: 'ok-1' })++ // Explicitly verify that a wrong-token bridge gets 401+ const badBridge = await createBridgeAndWaitForReady({+ socketPath: TEST_SOCKET,+ authToken: 'invalid-token',+ reconnectDelayMs: 500+ })+ bridges.push(badBridge)++ await expect(badBridge.sendRpc({ command: 'test' })).rejects.toThrow(+ 'Unauthorized: check OPENPENCIL_MCP_AUTH_TOKEN'+ )+ }, 10_000)+})diff --git a/tests/engine/mcp/stdio-bridge-reconnect.test.ts b/tests/engine/mcp/stdio-bridge-reconnect.test.tsnew file mode 100644index 000000000..896da7725--- /dev/null+++ b/tests/engine/mcp/stdio-bridge-reconnect.test.ts@@ -0,0 +1,466 @@+import { afterEach, describe, expect, test } from 'bun:test'+import { existsSync } from 'node:fs'+import { mkdir, rm, unlink, writeFile } from 'node:fs/promises'+import { createServer, type Server } from 'node:http'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { createStdioRpcBridge } from '#mcp/stdio-bridge'+import { getDiscoveryPath } from '#mcp/transport/paths'++const isUnix = process.platform !== 'win32'+const TEST_DIR = join(tmpdir(), `op-mcp-reconnect-${process.pid}`)+const SOCKET_PATH = join(TEST_DIR, 'mcp-test.sock')+const SOCKET_PATH_2 = join(TEST_DIR, 'mcp-test-v2.sock')+const AUTH_TOKEN = 'test-reconnect-token'++/**+ * Writes a mock discovery file at the platform discovery path so the+ * bridge's readDiscoveryFile() finds it.+ */+async function writeMockDiscovery(+ socketPath: string,+ authToken: string | null,+ httpPort: number = 0+): Promise<void> {+ const discoveryPath = await getDiscoveryPath()+ await writeFile(+ discoveryPath,+ JSON.stringify({+ pid: process.pid,+ socketPath,+ httpPort,+ authRequired: authToken !== null,+ authToken,+ version: '0.1.0-test',+ startedAt: new Date().toISOString()+ }),+ 'utf-8'+ )+}++/**+ * Minimal HTTP server on a Unix socket that mimics the MCP /health+ * and /rpc endpoints.+ */+function createMockMcpServer(+ socketPath: string,+ options: { authToken?: string | null; label?: string } = {}+): Promise<Server> {+ const { authToken = null, label = 'default' } = options++ return new Promise((resolve, reject) => {+ const server = createServer((req, res) => {+ if (req.url === '/health' && req.method === 'GET') {+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ status: 'ok' }))+ return+ }++ if (req.url === '/rpc' && req.method === 'POST') {+ const auth = req.headers.authorization+ if (authToken && auth !== `Bearer ${authToken}`) {+ res.writeHead(401)+ res.end(JSON.stringify({ error: 'Unauthorized' }))+ return+ }+ res.writeHead(200, { 'Content-Type': 'application/json' })+ // Include the label so callers can verify which server responded+ res.end(JSON.stringify({ result: `ok-${label}` }))+ return+ }++ res.writeHead(404)+ res.end(JSON.stringify({ error: 'not found' }))+ })++ server.once('error', reject)+ server.listen(socketPath, () => {+ server.off('error', reject)+ resolve(server)+ })+ })+}++/**+ * Creates a stdio bridge and returns a Promise that resolves once onReady+ * fires (meaning the initial health check passed).+ */+async function createBridgeAndWaitForReady(+ options: Parameters<typeof createStdioRpcBridge>[0]+): Promise<ReturnType<typeof createStdioRpcBridge>> {+ const TIMEOUT_MS = 5_000++ return new Promise((resolve, reject) => {+ let bridge: ReturnType<typeof createStdioRpcBridge> | null = null++ const timer = setTimeout(() => {+ bridge?.close()+ reject(new Error('Bridge never became ready'))+ }, TIMEOUT_MS)++ bridge = createStdioRpcBridge({+ ...options,+ onReady: () => {+ clearTimeout(timer)+ resolve(bridge as ReturnType<typeof createStdioRpcBridge>)+ }+ })+ })+}++/**+ * Closes a server gracefully, removing the socket file if it exists.+ */+async function closeMockServer(server: Server | null, socketPath?: string): Promise<void> {+ if (!server) return+ await new Promise<void>((resolve) => {+ server.close(() => resolve())+ })+ if (socketPath && existsSync(socketPath)) {+ try {+ await unlink(socketPath)+ } catch {+ void 0 // best-effort+ }+ }+}++async function createMockTcpMcpServer(+ authToken: string+): Promise<{ server: Server; port: number }> {+ const server = createServer((request, response) => {+ if (request.url === '/health') {+ response.writeHead(200, { 'Content-Type': 'application/json' })+ response.end(JSON.stringify({ status: 'ok' }))+ return+ }+ if (request.url === '/rpc' && request.headers.authorization === `Bearer ${authToken}`) {+ response.writeHead(200, { 'Content-Type': 'application/json' })+ response.end(JSON.stringify({ result: 'ok-tcp' }))+ return+ }+ response.writeHead(401)+ response.end(JSON.stringify({ error: 'Unauthorized' }))+ })+ await new Promise<void>((resolve) => {+ server.listen(0, '127.0.0.1', resolve)+ })+ const address = server.address()+ if (!address || typeof address === 'string') {+ await closeMockServer(server)+ throw new Error('Mock TCP server did not expose a port')+ }+ return { server, port: address.port }+}++// ---------------------------------------------------------------------------+// Tests for stdio-bridge transport state management on reconnect+// ---------------------------------------------------------------------------++describe('stdio-bridge transport reconnection', () => {+ const origSocketEnv = process.env.OPENPENCIL_MCP_SOCKET++ afterEach(async () => {+ if (origSocketEnv === undefined) {+ delete process.env.OPENPENCIL_MCP_SOCKET+ } else {+ process.env.OPENPENCIL_MCP_SOCKET = origSocketEnv+ }+ try {+ const discoveryPath = await getDiscoveryPath()+ if (existsSync(discoveryPath)) await unlink(discoveryPath)+ } catch {+ void 0 // best-effort cleanup+ }+ await rm(TEST_DIR, { recursive: true, force: true })+ })++ test.skipIf(!isUnix)('falls back to TCP when the discovered socket is unavailable', async () => {+ let tcpServer: Server | null = null+ let bridge: ReturnType<typeof createStdioRpcBridge> | null = null+ try {+ const tcp = await createMockTcpMcpServer(AUTH_TOKEN)+ tcpServer = tcp.server+ await writeMockDiscovery(SOCKET_PATH, AUTH_TOKEN, tcp.port)+ bridge = await createBridgeAndWaitForReady({ reconnectDelayMs: 20 })+ await expect(bridge.sendRpc({ command: 'test' })).resolves.toEqual({+ result: 'ok-tcp'+ })+ } finally {+ bridge?.close()+ await closeMockServer(tcpServer)+ }+ })++ test.skipIf(!isUnix)(+ 'bridge reconnects after server restart on the same socket path',+ async () => {+ let server1: Server | null = null+ let server2: Server | null = null+ let bridge: ReturnType<typeof createStdioRpcBridge> | null = null++ try {+ await mkdir(TEST_DIR, { recursive: true })+ await writeMockDiscovery(SOCKET_PATH, AUTH_TOKEN)+ process.env.OPENPENCIL_MCP_SOCKET = SOCKET_PATH++ // Start server+ server1 = await createMockMcpServer(SOCKET_PATH, {+ authToken: AUTH_TOKEN,+ label: 'first'+ })++ // Create bridge with explicit socket path+ bridge = await createBridgeAndWaitForReady({+ socketPath: SOCKET_PATH,+ authToken: AUTH_TOKEN,+ reconnectDelayMs: 300+ })++ // Verify initial connection+ const result1 = await bridge.sendRpc({ command: 'test' })+ expect(result1).toEqual({ result: 'ok-first' })++ // Kill server+ await closeMockServer(server1, SOCKET_PATH)+ server1 = null++ // RPC should fail (connection refused)+ await expect(bridge.sendRpc({ command: 'test' })).rejects.toThrow()++ // Restart server on the same socket+ server2 = await createMockMcpServer(SOCKET_PATH, {+ authToken: AUTH_TOKEN,+ label: 'second'+ })++ // Wait for the bridge to reconnect by polling sendRpc+ let reconnected = false+ for (let i = 0; i < 20; i++) {+ try {+ const result = await bridge.sendRpc({ command: 'test' })+ expect(result).toEqual({ result: 'ok-second' })+ reconnected = true+ break+ } catch {+ await new Promise<void>((r) => {+ setTimeout(r, 300)+ })+ }+ }+ expect(reconnected).toBe(true)+ } finally {+ bridge?.close()+ bridge = null+ await closeMockServer(server1, SOCKET_PATH)+ await closeMockServer(server2, SOCKET_PATH)+ }+ },+ 15_000+ )++ test.skipIf(!isUnix)(+ 'auto-discovered socket path is refreshed after transport reset',+ async () => {+ let server1: Server | null = null+ let server2: Server | null = null+ let bridge: ReturnType<typeof createStdioRpcBridge> | null = null++ try {+ await mkdir(TEST_DIR, { recursive: true })+ await writeMockDiscovery(SOCKET_PATH, AUTH_TOKEN)+ // Set OPENPENCIL_MCP_SOCKET so the bridge's readDiscoveryFile() finds+ // the mock discovery file in our test directory.+ process.env.OPENPENCIL_MCP_SOCKET = SOCKET_PATH++ // Start server+ server1 = await createMockMcpServer(SOCKET_PATH, {+ authToken: AUTH_TOKEN,+ label: 'first'+ })++ // Create bridge WITHOUT explicit socketPath — forces auto-discovery+ // from the discovery file. hasExplicitSocketPath will be false.+ bridge = await createBridgeAndWaitForReady({+ // No socketPath — auto-discover from discovery file+ authToken: AUTH_TOKEN,+ reconnectDelayMs: 300+ })++ // Verify initial connection+ const result1 = await bridge.sendRpc({ command: 'test' })+ expect(result1).toEqual({ result: 'ok-first' })++ // Kill server+ await closeMockServer(server1, SOCKET_PATH)+ server1 = null++ // RPC should fail (transport error resets transportMode to null)+ await expect(bridge.sendRpc({ command: 'test' })).rejects.toThrow()++ // Restart server on the same socket path+ server2 = await createMockMcpServer(SOCKET_PATH, {+ authToken: AUTH_TOKEN,+ label: 'second'+ })++ // After transport reset, the bridge should clear the auto-discovered+ // resolvedSocketPath, re-read the discovery file, and reconnect.+ let reconnected = false+ for (let i = 0; i < 20; i++) {+ try {+ const result = await bridge.sendRpc({ command: 'test' })+ expect(result).toEqual({ result: 'ok-second' })+ reconnected = true+ break+ } catch {+ await new Promise<void>((r) => {+ setTimeout(r, 300)+ })+ }+ }+ expect(reconnected).toBe(true)+ } finally {+ bridge?.close()+ bridge = null+ await closeMockServer(server1, SOCKET_PATH)+ await closeMockServer(server2, SOCKET_PATH)+ }+ },+ 15_000+ )++ test.skipIf(!isUnix)(+ 'explicit socket path override is never overwritten by discovery',+ async () => {+ let server1: Server | null = null+ let server2: Server | null = null+ let bridge: ReturnType<typeof createStdioRpcBridge> | null = null++ try {+ await mkdir(TEST_DIR, { recursive: true })+ await writeMockDiscovery(SOCKET_PATH, AUTH_TOKEN)+ process.env.OPENPENCIL_MCP_SOCKET = SOCKET_PATH++ server1 = await createMockMcpServer(SOCKET_PATH, {+ authToken: AUTH_TOKEN,+ label: 'explicit1'+ })++ // Bridge WITH explicit socketPath — must never be overwritten by discovery+ bridge = await createBridgeAndWaitForReady({+ socketPath: SOCKET_PATH,+ authToken: AUTH_TOKEN,+ reconnectDelayMs: 300+ })++ const result1 = await bridge.sendRpc({ command: 'test' })+ expect(result1).toEqual({ result: 'ok-explicit1' })++ // Kill and restart on same socket+ await closeMockServer(server1, SOCKET_PATH)+ server1 = null+ server2 = await createMockMcpServer(SOCKET_PATH, {+ authToken: AUTH_TOKEN,+ label: 'explicit2'+ })++ // Reconnect — explicit path must be preserved+ let reconnected = false+ for (let i = 0; i < 20; i++) {+ try {+ const result = await bridge.sendRpc({ command: 'test' })+ expect(result).toEqual({ result: 'ok-explicit2' })+ reconnected = true+ break+ } catch {+ await new Promise<void>((r) => {+ setTimeout(r, 300)+ })+ }+ }+ expect(reconnected).toBe(true)+ } finally {+ bridge?.close()+ bridge = null+ await closeMockServer(server1, SOCKET_PATH)+ await closeMockServer(server2, SOCKET_PATH)+ }+ },+ 15_000+ )++ test.skipIf(!isUnix)(+ 'auto-discovered socket path picks up a CHANGED path from discovery after transport reset',+ async () => {+ let server1: Server | null = null+ let server2: Server | null = null+ let bridge: ReturnType<typeof createStdioRpcBridge> | null = null++ try {+ await mkdir(TEST_DIR, { recursive: true })+ await writeMockDiscovery(SOCKET_PATH, AUTH_TOKEN)+ process.env.OPENPENCIL_MCP_SOCKET = SOCKET_PATH++ // Start server on SOCKET_PATH+ server1 = await createMockMcpServer(SOCKET_PATH, {+ authToken: AUTH_TOKEN,+ label: 'old-socket'+ })++ // Create bridge WITHOUT explicit socketPath — auto-discovers+ bridge = await createBridgeAndWaitForReady({+ // No socketPath — auto-discover from discovery file+ authToken: AUTH_TOKEN,+ reconnectDelayMs: 300+ })++ // Verify initial connection to old socket+ const result1 = await bridge.sendRpc({ command: 'test' })+ expect(result1).toEqual({ result: 'ok-old-socket' })++ // Kill server on old socket+ await closeMockServer(server1, SOCKET_PATH)+ server1 = null++ // RPC should fail (triggers transportMode reset + clears resolvedSocketPath)+ await expect(bridge.sendRpc({ command: 'test' })).rejects.toThrow()++ // Simulate server restart on a NEW socket path:+ // 1. Update the discovery file to point to the new socket+ // 2. Start a new server on the new socket+ await writeMockDiscovery(SOCKET_PATH_2, AUTH_TOKEN)+ server2 = await createMockMcpServer(SOCKET_PATH_2, {+ authToken: AUTH_TOKEN,+ label: 'new-socket'+ })++ // The bridge must reconnect to the NEW socket path by re-reading+ // the updated discovery file. Without the fix (clearing+ // resolvedSocketPath on transport reset), the bridge would keep+ // trying the old SOCKET_PATH forever.+ let reconnected = false+ for (let i = 0; i < 20; i++) {+ try {+ const result = await bridge.sendRpc({ command: 'test' })+ expect(result).toEqual({ result: 'ok-new-socket' })+ reconnected = true+ break+ } catch {+ await new Promise<void>((r) => {+ setTimeout(r, 300)+ })+ }+ }+ expect(reconnected).toBe(true)+ } finally {+ bridge?.close()+ bridge = null+ await closeMockServer(server1, SOCKET_PATH)+ await closeMockServer(server2, SOCKET_PATH_2)+ }+ },+ 15_000+ )+})diff --git a/tests/engine/mcp/stdio.test.ts b/tests/engine/mcp/stdio.test.tsindex ed9b7fd6d..17d2da3db 100644--- a/tests/engine/mcp/stdio.test.ts+++ b/tests/engine/mcp/stdio.test.ts@@ -1,134 +1,108 @@import { afterEach, beforeEach, describe, expect, test } from 'bun:test'-import type { AddressInfo } from 'node:net'+import { mkdir, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'import type { Client } from '@modelcontextprotocol/sdk/client/index.js'import type { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'-import { WebSocketServer, type WebSocket } from 'ws'-import {- ALL_TOOLS,- FigmaAPI,- SceneGraph,- computeAllLayouts,- executeRpcCommand-} from '@open-pencil/core'+import { SceneGraph } from '@open-pencil/scene-graph'-import { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'--function createMockApp() {- const graph = new SceneGraph()- const wss = new WebSocketServer({ port: 0, host: '127.0.0.1' })- let clientWs: WebSocket | null = null- const requests: Array<{- command: string- args?: { name?: string; document_id?: string; page_id?: string; args?: Record<string, unknown> }- }> = []-- wss.on('connection', (ws) => {- clientWs = ws- ws.send(JSON.stringify({ type: 'register', token: 'mock-token' }))-- ws.on('message', async (raw) => {- const msg = JSON.parse(String(raw)) as {- type: string- id: string- command: string- args?: { name?: string; args?: Record<string, unknown> }- }- if (msg.type !== 'request') return- requests.push({ command: msg.command, args: msg.args })-- try {- let result: unknown- if (msg.command === 'tool' && msg.args?.name) {- const toolName = msg.args.name- const def = ALL_TOOLS.find((t) => t.name === toolName)- if (!def) throw new Error(`Unknown tool: ${toolName}`)- const api = new FigmaAPI(graph)- api.currentPage = api.wrapNode(graph.getPages()[0].id)- result = await def.execute(api, msg.args.args ?? {})- if (def.mutates) computeAllLayouts(graph)- } else if (msg.command === 'save_file') {- result = { ok: true }- } else if (msg.command === 'list_documents') {- result = {- documents: [- {- id: 'doc-1',- name: 'Mock document',- active: true,- current_page_id: graph.getPages()[0].id,- current_page_name: graph.getPages()[0].name,- pages: graph.getPages().map((page) => ({ id: page.id, name: page.name }))- }- ]- }- } else {- result = executeRpcCommand(graph, msg.command, msg.args ?? {})- }+import { startServer, type ServerHandle } from '#mcp/server'- ws.send(JSON.stringify({ type: 'response', id: msg.id, ok: true, result }))- } catch (e) {- ws.send(- JSON.stringify({- type: 'response',- id: msg.id,- ok: false,- error: e instanceof Error ? e.message : String(e)- })- )- }- })- })+import { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'- const port = new Promise<number>((resolve) => {- wss.on('listening', () => resolve((wss.address() as AddressInfo).port))- })+import { connectMockBrowser, waitForBrowserRegistration, type MockBrowser } from './helpers'- return {- graph,- requests,- wss,- port,- close: () => {- clientWs?.close()- wss.close()- }- }-}+const AUTH_TOKEN = 'test-stdio-token'+const NO_DOCUMENT_AUTH_TOKEN = 'test-stdio-no-document-token'+const isUnix = process.platform !== 'win32'+const SOCKET_DIR = join(tmpdir(), `openpencil-test-stdio-${process.pid}`)+const SOCKET_PATH = isUnix ? join(SOCKET_DIR, 'mcp.sock') : null-async function createStdioClient(wsPort: number) {+async function createStdioClient(socketPath: string, authToken: string | null) {const { Client } = await import('@modelcontextprotocol/sdk/client/index.js')const { StdioClientTransport } = await import('@modelcontextprotocol/sdk/client/stdio.js')+ const env: Record<string, string> = {}+ for (const [key, value] of Object.entries(process.env)) {+ if (!key.startsWith('OPENPENCIL_MCP_') && value !== undefined) {+ env[key] = value+ }+ }+ if (process.env.OPENPENCIL_MCP_DISCOVERY_PATH) {+ env.OPENPENCIL_MCP_DISCOVERY_PATH = process.env.OPENPENCIL_MCP_DISCOVERY_PATH+ }+ env.PATH = process.env.PATH ?? ''+ // Only set OPENPENCIL_MCP_SOCKET when a socket path exists.+ // An empty string on Windows would break the stdio bridge's transport+ // discovery (it would try to connect to an empty socket path).+ if (socketPath) {+ env.OPENPENCIL_MCP_SOCKET = socketPath+ }+ if (authToken) {+ env.OPENPENCIL_MCP_AUTH_TOKEN = authToken+ }const transport = new StdioClientTransport({command: 'bun',args: ['packages/mcp/src/stdio.ts'],- env: {- ...process.env,- WS_PORT: String(wsPort),- PATH: process.env.PATH ?? ''- },+ env,stderr: 'pipe'})const client = new Client({ name: 'test-stdio-client', version: '0.0.0' })- await new Promise<void>((resolve) => {+ let stderrBuffer = ''++ // The bridge must reach the MCP server before tool calls can be sent.+ // Wait for the stderr readiness marker — this confirms server reachability+ // and ready=true, but document/browser availability is still checked per+ // tool call.+ // Also reject on timeout or stream end so the test fails fast if the+ // bridge never connects.+ const BRIDGE_TIMEOUT = 10_000+ const bridgeConnected = new Promise<void>((resolve, reject) => {+ const timer = setTimeout(() => {+ reject(new Error('Bridge did not connect within timeout'))+ }, BRIDGE_TIMEOUT)+const stderr = transport.stderrif (stderr && 'on' in stderr) {- ;(stderr as NodeJS.ReadableStream).on('data', (chunk: Buffer) => {- if (chunk.toString().includes('Connected to OpenPencil app')) {+ const stream = stderr as NodeJS.ReadableStream+ stream.on('data', (chunk: Buffer) => {+ // Buffer stderr so the readiness marker is not missed if it+ // straddles a chunk boundary.+ stderrBuffer += chunk.toString()+ if (stderrBuffer.includes('Connected to OpenPencil')) {+ clearTimeout(timer)resolve()}})+ stream.on('end', () => {+ clearTimeout(timer)+ reject(new Error('Bridge stderr stream ended before connection'))+ })+ stream.on('error', (err: Error) => {+ clearTimeout(timer)+ reject(new Error(`Bridge stderr error: ${err.message}`))+ })+ } else {+ clearTimeout(timer)+ reject(new Error('No stderr stream available'))}- void client.connect(transport).then(() => {- setTimeout(resolve, 1000)- return undefined- })})- return { client, transport }+ // Start the MCP session and wait for the bridge to be ready in parallel.+ // client.connect() handles the JSON-RPC initialize/handshake;+ // bridgeConnected confirms the bridge can actually reach the server.+ try {+ await Promise.all([client.connect(transport), bridgeConnected])+ } catch (err) {+ await client.close().catch(() => undefined)+ await transport.close().catch(() => undefined)+ throw err+ }++ return { client, transport, stderrText: () => stderrBuffer }}function textContent(content: unknown): string {@@ -140,25 +114,84 @@ function textContent(content: unknown): string {}describe('MCP stdio transport', () => {- let app: ReturnType<typeof createMockApp>- let client: Client- let transport: StdioClientTransport+ let handle: ServerHandle | undefined+ let graph: SceneGraph | undefined+ let browser: MockBrowser | undefined+ let client: Client | undefined+ let transport: StdioClientTransport | undefined+ let stderrText: (() => string) | undefinedbeforeEach(async () => {- app = createMockApp()- const wsPort = await app.port- const ctx = await createStdioClient(wsPort)- client = ctx.client- transport = ctx.transport- })+ // Fail-safe: clean up any leftover state from a failed previous test+ if (client) await client.close().catch(() => undefined)+ if (browser) browser.close()+ if (transport) await transport.close().catch(() => undefined)+ if (handle) await handle.close().catch(() => undefined)++ graph = new SceneGraph()++ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })++ // Bun does not run afterEach() when beforeEach() throws, so we must clean+ // up any partially-initialized resources ourselves before rethrowing.+ try {+ handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: SOCKET_PATH,+ authToken: AUTH_TOKEN,+ enableEval: false,+ mcpRoot: null+ })++ if (!handle.httpPort) {+ throw new Error('TCP listener not started — httpPort is undefined')+ }++ browser = await connectMockBrowser(handle.httpPort, graph, AUTH_TOKEN)+ await waitForBrowserRegistration(handle.httpPort)++ const socketPath = handle.socketPath ?? ''+ if (isUnix && !socketPath) {+ throw new Error('Unix socket listener not started — socketPath is undefined')+ }+ const ctx = await createStdioClient(socketPath, AUTH_TOKEN)+ client = ctx.client+ transport = ctx.transport+ stderrText = ctx.stderrText+ } catch (err) {+ if (client) await client.close().catch(() => undefined)+ if (browser) browser.close()+ if (transport) await transport.close().catch(() => undefined)+ if (handle) await handle.close().catch(() => undefined)+ throw err+ }+ }, 15000)afterEach(async () => {- await client.close()- app.close()+ if (client) await client.close().catch(() => undefined)+ if (browser) browser.close()+ if (transport) await transport.close().catch(() => undefined)+ if (handle) await handle.close().catch(() => undefined)+ if (isUnix) await rm(SOCKET_DIR, { recursive: true, force: true })+ handle = undefined+ browser = undefined+ client = undefined+ transport = undefined+ stderrText = undefined})+ function requireClient(): Client {+ if (!client) throw new Error('client not initialized')+ return client+ }+ function requireGraph(): SceneGraph {+ if (!graph) throw new Error('graph not initialized')+ return graph+ }+test('lists tools over stdio', async () => {- const { tools } = await client.listTools()+ const { tools } = await requireClient().listTools()const names = tools.map((t) => t.name)expect(names).toContain('create_shape')expect(names).toContain('get_page_tree')@@ -172,10 +205,10 @@ describe('MCP stdio transport', () => {expect(JSON.stringify(createShape.inputSchema)).toContain('document_id')expect(JSON.stringify(createShape.inputSchema)).toContain('page_id')expect(tools.length).toBeGreaterThan(30)- })+ }, 10000)test('create_shape via stdio creates a node', async () => {- const result = await client.callTool({+ const result = await requireClient().callTool({name: 'create_shape',arguments: { type: 'FRAME', x: 10, y: 20, width: 200, height: 100, name: 'StdioFrame' }})@@ -188,8 +221,8 @@ describe('MCP stdio transport', () => {expect(data.type).toBe('FRAME')expect(data.name).toBe('StdioFrame')- expect(getNodeOrThrow(app.graph, data.id).width).toBe(200)- })+ expect(getNodeOrThrow(requireGraph(), data.id).width).toBe(200)+ }, 10000)test('tool target fields are sent in the app RPC envelope', async () => {const result = await client.callTool({@@ -207,13 +240,24 @@ describe('MCP stdio transport', () => {})expect(result.isError).not.toBe(true)const request = expectDefined(- app.requests.find((item) => item.command === 'tool' && item.args?.name === 'create_shape'),+ browser?.requests.find((item) => {+ const args = item.args as { name?: string } | undefined+ return item.command === 'tool' && args?.name === 'create_shape'+ }),'tool request')- expect(request.args?.document_id).toBe('doc-1')- expect(request.args?.page_id).toBe('page-1')- expect(request.args?.args?.document_id).toBeUndefined()- expect(request.args?.args?.page_id).toBeUndefined()+ const requestArgs = request.args as+ | {+ name?: string+ document_id?: string+ page_id?: string+ args?: Record<string, unknown>+ }+ | undefined+ expect(requestArgs?.document_id).toBe('doc-1')+ expect(requestArgs?.page_id).toBe('page-1')+ expect(requestArgs?.args?.document_id).toBeUndefined()+ expect(requestArgs?.args?.page_id).toBeUndefined()})test('list_documents via stdio returns open documents', async () => {@@ -223,53 +267,81 @@ describe('MCP stdio transport', () => {documents: Array<{ id: string; current_page_id: string }>}expect(data.documents[0].id).toBe('doc-1')- expect(data.documents[0].current_page_id).toBe(app.graph.getPages()[0].id)+ expect(data.documents[0].current_page_id).toBe(browser?.graph.getPages()[0].id)})test('save_file via stdio succeeds', async () => {- const result = await client.callTool({ name: 'save_file', arguments: {} })+ const result = await requireClient().callTool({ name: 'save_file', arguments: {} })expect(result.isError).not.toBe(true)const data = JSON.parse(textContent(result.content)) as { saved: boolean }expect(data.saved).toBe(true)- })+ }, 10000)test('get_codegen_prompt via stdio returns prompt', async () => {- const result = await client.callTool({ name: 'get_codegen_prompt', arguments: {} })+ const result = await requireClient().callTool({ name: 'get_codegen_prompt', arguments: {} })expect(result.isError).not.toBe(true)const data = JSON.parse(textContent(result.content)) as { prompt: string }expect(data.prompt.length).toBeGreaterThan(100)- })+ }, 10000)- test('delete_node via stdio removes a node', async () => {- const create = await client.callTool({+ test('sequential tool calls work (create then delete)', async () => {+ const create = await requireClient().callTool({name: 'create_shape',arguments: { type: 'RECTANGLE', x: 0, y: 0, width: 50, height: 50 }})+ expect(create.isError).not.toBe(true)const { id } = JSON.parse(textContent(create.content)) as { id: string }- expect(app.graph.getNode(id)).toBeDefined()+ expect(getNodeOrThrow(requireGraph(), id)).toBeDefined()- await client.callTool({ name: 'delete_node', arguments: { id } })-- expect(app.graph.getNode(id)).toBeUndefined()- })+ await requireClient().callTool({ name: 'delete_node', arguments: { id } })+ expect(requireGraph().getNode(id)).toBeUndefined()+ }, 10000)test('stderr does not contain JSON-RPC', async () => {- const stderrChunks: string[] = []- const stderr = transport.stderr- if (stderr && 'on' in stderr) {- ;(stderr as NodeJS.ReadableStream).on('data', (chunk: Buffer) => {- stderrChunks.push(chunk.toString())- })- }-- await client.callTool({+ await requireClient().callTool({name: 'create_shape',arguments: { type: 'FRAME', x: 0, y: 0, width: 100, height: 100 }})- const allStderr = stderrChunks.join('')+ const allStderr = stderrText?.() ?? ''expect(allStderr).not.toContain('"jsonrpc"')expect(allStderr).not.toContain('"method"')- })+ }, 10000)+})++describe('MCP stdio readiness without an open document', () => {+ test('readiness marker means server reachable, while document tools report no document', async () => {+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })+ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: isUnix ? join(SOCKET_DIR, 'mcp-no-document.sock') : null,+ authToken: NO_DOCUMENT_AUTH_TOKEN,+ enableEval: false,+ mcpRoot: null+ })++ let client: Client | undefined+ let transport: StdioClientTransport | undefined+ try {+ const socketPath = handle.socketPath ?? ''+ const ctx = await createStdioClient(socketPath, NO_DOCUMENT_AUTH_TOKEN)+ client = ctx.client+ transport = ctx.transport++ expect(ctx.stderrText()).toContain('document availability is checked per tool call')++ const result = await client.callTool({ name: 'get_current_page', arguments: {} })+ expect(result.isError).toBe(true)+ const message = textContent(result.content)+ expect(message).toContain('OpenPencil app is not connected')+ expect(message).toContain('no document is open')+ } finally {+ await client?.close().catch(() => undefined)+ await transport?.close().catch(() => undefined)+ await handle.close().catch(() => undefined)+ if (isUnix) await rm(SOCKET_DIR, { recursive: true, force: true })+ }+ }, 30000)})diff --git a/tests/engine/mcp/transport.test.ts b/tests/engine/mcp/transport.test.tsnew file mode 100644index 000000000..ea1804eff--- /dev/null+++ b/tests/engine/mcp/transport.test.ts@@ -0,0 +1,205 @@+import { describe, expect, it } from 'bun:test'+import { randomUUID } from 'node:crypto'+import { stat } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import {+ getSocketDir,+ getSocketPath,+ getDiscoveryPath,+ platformHasUnixSockets,+ platformName+} from '#mcp/transport/paths'++describe('transport/paths', () => {+ describe('getSocketDir', () => {+ it('returns a valid directory path', async () => {+ const dir = await getSocketDir()+ expect(dir).toBeTruthy()+ expect(typeof dir).toBe('string')+ })++ it('respects OPENPENCIL_MCP_SOCKET env override', async () => {+ const originalSocket = process.env.OPENPENCIL_MCP_SOCKET+ process.env.OPENPENCIL_MCP_SOCKET = join(tmpdir(), 'test-openpencil-socket', 'mcp.sock')+ try {+ const dir = await getSocketDir()+ expect(dir).toBe(join(tmpdir(), 'test-openpencil-socket'))+ } finally {+ if (originalSocket == null) {+ delete process.env.OPENPENCIL_MCP_SOCKET+ } else {+ process.env.OPENPENCIL_MCP_SOCKET = originalSocket+ }+ }+ })++ it('uses platform-appropriate default path', async () => {+ const originalSocket = process.env.OPENPENCIL_MCP_SOCKET+ delete process.env.OPENPENCIL_MCP_SOCKET+ try {+ const dir = await getSocketDir()+ if (process.platform === 'darwin') {+ expect(dir).toContain('Library/Application Support/OpenPencil')+ } else if (process.platform === 'win32') {+ const localAppData = process.env.LOCALAPPDATA+ if (localAppData) {+ expect(dir.toLowerCase()).toContain(localAppData.toLowerCase())+ }+ expect(dir.toLowerCase()).toContain('openpencil')+ } else {+ // Linux / other Unix+ const xdg = process.env.XDG_RUNTIME_DIR+ if (xdg) {+ expect(dir).toContain(xdg)+ } else {+ expect(dir).toContain('.openpencil')+ }+ }+ } finally {+ if (originalSocket == null) {+ delete process.env.OPENPENCIL_MCP_SOCKET+ } else {+ process.env.OPENPENCIL_MCP_SOCKET = originalSocket+ }+ }+ })++ it('creates the directory if it does not exist', async () => {+ const testDir = join(tmpdir(), `openpencil-test-${Date.now()}`)+ const originalSocket = process.env.OPENPENCIL_MCP_SOCKET+ process.env.OPENPENCIL_MCP_SOCKET = `${testDir}/mcp.sock`+ try {+ const dir = await getSocketDir()+ expect(dir).toBe(testDir)+ const info = await stat(dir).catch(() => null)+ expect(info).not.toBeNull()+ expect(info?.isDirectory()).toBe(true)+ } finally {+ if (originalSocket == null) {+ delete process.env.OPENPENCIL_MCP_SOCKET+ } else {+ process.env.OPENPENCIL_MCP_SOCKET = originalSocket+ }+ const { rm } = await import('node:fs/promises')+ await rm(testDir, { recursive: true, force: true }).catch(() => null)+ }+ })+ })++ describe('getSocketPath', () => {+ it('returns a path ending in mcp.sock', async () => {+ const originalSocket = process.env.OPENPENCIL_MCP_SOCKET+ delete process.env.OPENPENCIL_MCP_SOCKET+ try {+ const path = await getSocketPath()+ expect(path).toMatch(/mcp\.sock$/)+ } finally {+ if (originalSocket == null) {+ delete process.env.OPENPENCIL_MCP_SOCKET+ } else {+ process.env.OPENPENCIL_MCP_SOCKET = originalSocket+ }+ }+ })++ it('respects OPENPENCIL_MCP_SOCKET override', async () => {+ const originalSocket = process.env.OPENPENCIL_MCP_SOCKET+ const overrideDir = join(tmpdir(), 'openpencil-test-override')+ process.env.OPENPENCIL_MCP_SOCKET = join(overrideDir, 'mcp.sock')+ try {+ const path = await getSocketPath()+ expect(path).toBe(join(overrideDir, 'mcp.sock'))+ } finally {+ if (originalSocket == null) {+ delete process.env.OPENPENCIL_MCP_SOCKET+ } else {+ process.env.OPENPENCIL_MCP_SOCKET = originalSocket+ }+ const { rm } = await import('node:fs/promises')+ await rm(overrideDir, { recursive: true, force: true }).catch(() => null)+ }+ })+ })++ describe('getDiscoveryPath', () => {+ // The test preload (tests/helpers/mcp-discovery-isolation.ts) sets+ // OPENPENCIL_MCP_DISCOVERY_PATH to a per-process temp path. Each case+ // below saves/clears/restores both env vars so platform-default behavior+ // can be asserted independently of the preload.+ it('returns a path ending in mcp.json', async () => {+ const originalSocket = process.env.OPENPENCIL_MCP_SOCKET+ const originalDiscovery = process.env.OPENPENCIL_MCP_DISCOVERY_PATH+ delete process.env.OPENPENCIL_MCP_SOCKET+ delete process.env.OPENPENCIL_MCP_DISCOVERY_PATH+ try {+ const path = await getDiscoveryPath()+ expect(path).toMatch(/mcp\.json$/)+ } finally {+ if (originalSocket == null) delete process.env.OPENPENCIL_MCP_SOCKET+ else process.env.OPENPENCIL_MCP_SOCKET = originalSocket+ if (originalDiscovery == null) delete process.env.OPENPENCIL_MCP_DISCOVERY_PATH+ else process.env.OPENPENCIL_MCP_DISCOVERY_PATH = originalDiscovery+ }+ })++ it('ignores OPENPENCIL_MCP_SOCKET override (stays on platform path)', async () => {+ const originalSocket = process.env.OPENPENCIL_MCP_SOCKET+ const originalDiscovery = process.env.OPENPENCIL_MCP_DISCOVERY_PATH+ const overrideDir = join(tmpdir(), 'openpencil-test-discovery-override')+ process.env.OPENPENCIL_MCP_SOCKET = join(overrideDir, 'mcp.sock')+ delete process.env.OPENPENCIL_MCP_DISCOVERY_PATH+ try {+ const path = await getDiscoveryPath()+ // The discovery file must NOT be co-located with the override socket —+ // it always stays on the well-known platform path so clients can find+ // it without knowing the socket override.+ expect(path).not.toBe(join(overrideDir, 'mcp.json'))+ expect(path).toMatch(/mcp\.json$/)+ } finally {+ if (originalSocket == null) delete process.env.OPENPENCIL_MCP_SOCKET+ else process.env.OPENPENCIL_MCP_SOCKET = originalSocket+ if (originalDiscovery == null) delete process.env.OPENPENCIL_MCP_DISCOVERY_PATH+ else process.env.OPENPENCIL_MCP_DISCOVERY_PATH = originalDiscovery+ }+ })++ it('respects OPENPENCIL_MCP_DISCOVERY_PATH override', async () => {+ const originalSocket = process.env.OPENPENCIL_MCP_SOCKET+ const originalDiscovery = process.env.OPENPENCIL_MCP_DISCOVERY_PATH+ const overrideDir = join(tmpdir(), `openpencil-test-discovery-path-${randomUUID()}`)+ const overridePath = join(overrideDir, 'mcp.json')+ process.env.OPENPENCIL_MCP_DISCOVERY_PATH = overridePath+ try {+ const path = await getDiscoveryPath()+ expect(path).toBe(overridePath)+ // The parent directory is created (0o700) so writeDiscoveryFile can+ // write its temp file in the same directory before the atomic rename.+ const info = await stat(overrideDir).catch(() => null)+ expect(info).not.toBeNull()+ expect(info?.isDirectory()).toBe(true)+ } finally {+ if (originalSocket == null) delete process.env.OPENPENCIL_MCP_SOCKET+ else process.env.OPENPENCIL_MCP_SOCKET = originalSocket+ if (originalDiscovery == null) delete process.env.OPENPENCIL_MCP_DISCOVERY_PATH+ else process.env.OPENPENCIL_MCP_DISCOVERY_PATH = originalDiscovery+ const { rm } = await import('node:fs/promises')+ await rm(overrideDir, { recursive: true, force: true }).catch(() => null)+ }+ })+ })++ describe('platformHasUnixSockets', () => {+ it('returns true on POSIX platforms, false on Windows', () => {+ expect(platformHasUnixSockets()).toBe(process.platform !== 'win32')+ })+ })++ describe('platformName', () => {+ it('returns a valid platform name', () => {+ const name = platformName()+ expect(['macos', 'linux', 'windows', 'other']).toContain(name)+ })+ })+})diff --git a/tests/engine/tauri/mcp-spawn.test.ts b/tests/engine/tauri/mcp-spawn.test.tsindex 8a84e0509..18f783d3c 100644--- a/tests/engine/tauri/mcp-spawn.test.ts+++ b/tests/engine/tauri/mcp-spawn.test.ts@@ -4,6 +4,17 @@ import { spawnMCPIfNeeded } from '@/app/automation/mcp/spawn'import { clearTauriMocks, installTauriMockWindow, mockTauriIPC } from '#tests/helpers/tauri/mocks'+const DISCOVERY_PATH = '/mock/home/.openpencil/mcp.json'+const DISCOVERY_JSON = JSON.stringify({+ pid: 1234,+ socketPath: '/mock/home/.openpencil/mcp.sock',+ httpPort: 7600,+ authRequired: true,+ authToken: 'discovery-token',+ version: '0.0.0-test',+ startedAt: new Date().toISOString()+})+afterEach(async () => {await clearTauriMocks()vi.restoreAllMocks()@@ -26,10 +37,13 @@ describe('Tauri MCP spawning', () => {healthChecks += 1if (healthChecks === 1) return new Response('', { status: 404 })return new Response(- JSON.stringify({ status: 'ok', version: '0.0.0-test', token: 'server-token' }),- {- status: 200- }+ JSON.stringify({+ status: 'ok',+ version: '0.0.0-test',+ authRequired: true,+ discoveryPath: DISCOVERY_PATH+ }),+ { status: 200 })})@@ -41,6 +55,16 @@ describe('Tauri MCP spawning', () => {onEvent = (args as { onEvent: { onmessage: (event: unknown) => void } }).onEvent.onmessagereturn 77}+ if (cmd === 'plugin:fs|read_text_file') {+ // Only return discovery data when reading the expected discovery path+ const pathArg = (args as { path?: string })?.path+ if (pathArg === DISCOVERY_PATH) return new TextEncoder().encode(DISCOVERY_JSON)+ return null+ }+ // Handle homeDir() IPC call from resolveTauriHomeDir+ if (cmd === 'plugin:path|resolve_directory') {+ return '/mock/home'+ }return null})@@ -49,18 +73,15 @@ describe('Tauri MCP spawning', () => {handle?.disconnect()await Promise.resolve()- expect(handle?.authToken).toBe('server-token')- expect(calls[0]?.cmd).toBe('plugin:shell|spawn')- expect(calls[0]?.args).toMatchObject({- program: 'openpencil-mcp-http',- args: [],- options: {- env: {- OPENPENCIL_MCP_AUTH_TOKEN: expect.any(String),- OPENPENCIL_MCP_CORS_ORIGIN: 'tauri://localhost'- }- }- })+ expect(handle?.authToken).toBe('discovery-token')+ expect(calls.some((c) => c.cmd === 'plugin:shell|spawn')).toBe(true)+ expect(+ calls.some(+ (c) =>+ c.cmd === 'plugin:fs|read_text_file' &&+ (c.args as { path?: string })?.path === DISCOVERY_PATH+ )+ ).toBe(true)expect(calls.at(-1)).toEqual({ cmd: 'plugin:shell|kill', args: { cmd: 'killChild', pid: 77 } })})})diff --git a/tests/helpers/mcp-discovery-isolation.ts b/tests/helpers/mcp-discovery-isolation.tsnew file mode 100644index 000000000..1718f454f--- /dev/null+++ b/tests/helpers/mcp-discovery-isolation.ts@@ -0,0 +1,104 @@+import { randomUUID } from 'node:crypto'+import { readdirSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++/**+ * Test preload: isolate the MCP discovery file so `bun test` runs never+ * clobber the real `~/Library/Application Support/OpenPencil/mcp.json`.+ *+ * Deleting that file while the OpenPencil desktop app is running breaks every+ * MCP client: the discovery file is the only place the server's auth token is+ * published, so stdio bridges fall back to a null token and every /rpc call+ * returns 401 (surfacing as a spurious "auth issue"). The engine tests in+ * tests/engine/mcp/** call startServer()/handle.close() which writes and then+ * removes the discovery file — without isolation they did so at the real+ * platform path.+ *+ * Honored via OPENPENCIL_MCP_DISCOVERY_PATH in getDiscoveryPath()+ * (packages/mcp/src/transport/paths.ts). Per-process temp path so parallel+ * bun workers don't collide. A crypto.randomUUID() suffix guarantees that+ * PID reuse after a crash cannot reuse a stale discovery dir from a prior+ * process that happened to recycle the same PID. An operator-provided value+ * is respected.+ */+const tmpDiscoveryDir = join(tmpdir(), `openpencil-mcp-test-${process.pid}-${randomUUID()}`)+let ownsDiscoveryPath = false+if (!process.env.OPENPENCIL_MCP_DISCOVERY_PATH) {+ process.env.OPENPENCIL_MCP_DISCOVERY_PATH = join(tmpDiscoveryDir, 'mcp.json')+ ownsDiscoveryPath = true+}++/**+ * Decides liveness from a `process.kill(pid, 0)` error.+ *+ * POSIX `kill(pid, 0)` throws:+ * - ESRCH: no such process => dead+ * - EPERM: process exists but we lack => ALIVE (we just can't signal it)+ * permission to signal it+ *+ * For a DESTRUCTIVE cleanup sweep, EPERM must be treated as "alive": the+ * process exists, so its temp dir must never be deleted. (Root never sees+ * EPERM — it bypasses permission checks, so `kill` succeeds for any live PID+ * regardless of owner. EPERM only arises for a non-root user probing another+ * user's live PID, e.g. on a shared, non-sticky temp directory.) Unknown+ * error shapes are also treated as "alive" — conservative: don't clean up+ * resources if we're not sure the process is dead. Only ESRCH (no such+ * process) is treated as "not alive".+ *+ * Exported (and kept pure) so the EPERM branch is unit-testable without+ * monkey-patching `process.kill`.+ */+export function isAliveFromKillError(e: unknown): boolean {+ if (e instanceof Error && 'code' in e) {+ return (e as NodeJS.ErrnoException).code !== 'ESRCH'+ }+ return true+}++/**+ * Returns true if the given PID is (or may be) alive, via a zero-signal probe+ * (`process.kill(pid, 0)`). See `isAliveFromKillError` for the EPERM rationale.+ */+export function isProcessAlive(pid: number): boolean {+ try {+ process.kill(pid, 0)+ return true+ } catch (e) {+ return isAliveFromKillError(e)+ }+}++/**+ * Best-effort cleanup of stale temp dirs from previous (crashed/killed) test+ * runs. bun's test runner does not emit 'exit'/'beforeExit' reliably, so we+ * cannot rely on a process-exit handler. Instead, sweep $TMPDIR at startup for+ * our own `openpencil-mcp-test-<pid>` dirs (with or without a UUID suffix)+ * whose owner PID is no longer alive. Live PIDs (concurrent runs) are skipped;+ * the current run's dir does not exist yet at this point so it is never touched.+ */+if (ownsDiscoveryPath) {+ // Matches both the old format (openpencil-mcp-test-<pid>) and the new+ // UUID-suffixed format (openpencil-mcp-test-<pid>-<uuid>) so leftovers+ // from either naming convention are swept. The PID is always capture group 1.+ const stalePattern = /^openpencil-mcp-test-(\d+)(?:-[a-f0-9-]+)?$/+ let entries: string[] = []+ try {+ entries = readdirSync(tmpdir())+ } catch {+ void 0+ }+ for (const name of entries) {+ const match = stalePattern.exec(name)+ if (!match) continue+ const pid = Number.parseInt(match[1], 10)+ // Skip live processes (could be a concurrent test run). The current+ // process is alive, so its (not-yet-created) dir is skipped here too.+ if (isProcessAlive(pid)) continue+ try {+ rmSync(join(tmpdir(), name), { recursive: true, force: true })+ } catch {+ void 0+ }+ }+}