Skip to content

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

fix(mcp): apply Settings preferences in development

Victor Wads67b534609da2
diff --git a/src/app/automation/bridge/vite-plugin.ts b/src/app/automation/bridge/vite-plugin.ts
index b9201ca27..e95c1e861 100644
--- a/src/app/automation/bridge/vite-plugin.ts
+++ b/src/app/automation/bridge/vite-plugin.ts
@@ -1,88 +1,162 @@
import { spawn } from 'node:child_process'
+import type { IncomingMessage } from 'node:http'
import type { Plugin } from 'vite'
import { AUTOMATION_HTTP_PORT } from '@open-pencil/core/constants'
import { getSocketPath, platformHasUnixSockets } from '@open-pencil/mcp/transport'
+import {
+ DEV_MCP_RESTART_PATH,
+ isDevMCPConfiguration,
+ type DevMCPConfiguration
+} from '../mcp/dev-control'
+
+interface AutomationEnvironmentOptions {
+ authToken: string | null
+ baseEnv: NodeJS.ProcessEnv
+ configuration: DevMCPConfiguration
+ corsOrigin: string
+ socketPath: string | null
+}
+
+export function createAutomationEnvironment(
+ options: AutomationEnvironmentOptions
+): NodeJS.ProcessEnv {
+ const { authToken, baseEnv, configuration, corsOrigin, socketPath } = options
+ const childEnv = { ...baseEnv }
+ delete childEnv.OPENPENCIL_MCP_SOCKET
+ delete childEnv.OPENPENCIL_MCP_AUTH_TOKEN
+ return {
+ ...childEnv,
+ PORT: String(AUTOMATION_HTTP_PORT),
+ OPENPENCIL_MCP_TCP: '1',
+ ...(socketPath ? { OPENPENCIL_MCP_SOCKET: socketPath } : {}),
+ OPENPENCIL_MCP_AUTH_TOKEN: configuration.authenticationEnabled ? (authToken ?? '') : '',
+ OPENPENCIL_MCP_CORS_ORIGIN: corsOrigin,
+ OPENPENCIL_MCP_ROOT: configuration.rootDirectory.trim() || process.cwd(),
+ OPENPENCIL_MCP_DISABLED_TOOLS: configuration.disabledTools
+ }
+}
+
+async function readConfiguration(request: IncomingMessage): Promise<unknown> {
+ let body = ''
+ for await (const chunk of request) {
+ body += String(chunk)
+ if (body.length > 70_000) throw new Error('Request body is too large')
+ }
+ return JSON.parse(body)
+}
+
// TODO: production — bundle MCP server as Tauri sidecar or spawn via shell plugin
export function automationPlugin(authToken: string | null, corsOrigin: string): Plugin {
let child: ReturnType<typeof spawn> | null = null
- let starting: Promise<void> | null = null
+ let lifecycle = Promise.resolve()
+ let configuration: DevMCPConfiguration = {
+ authenticationEnabled: true,
+ rootDirectory: '',
+ disabledTools: ''
+ }
- return {
- name: 'open-pencil-automation',
- async configureServer() {
- if (child || starting) return
+ function enqueue(operation: () => Promise<void>): Promise<void> {
+ const next = lifecycle.then(operation, operation)
+ lifecycle = next.catch(() => undefined)
+ return next
+ }
- 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
+ async function stopChild(): Promise<void> {
+ const running = child
+ if (!running) return
+ child = null
+ const exited = new Promise<void>((resolve) => {
+ running.once('exit', () => resolve())
+ })
+ running.kill()
+ const timeout = new Promise<void>((resolve) => {
+ setTimeout(resolve, 2_000)
+ })
+ await Promise.race([exited, timeout])
+ if (running.exitCode === null) running.kill('SIGKILL')
+ }
- const childEnv = { ...process.env }
- delete childEnv.OPENPENCIL_MCP_SOCKET
- delete childEnv.OPENPENCIL_MCP_AUTH_TOKEN
+ async function startChild(): Promise<void> {
+ const socketPath = platformHasUnixSockets() ? await getSocketPath() : null
+ const spawned = spawn('bun', ['run', 'packages/mcp/src/index.ts'], {
+ stdio: ['ignore', 'inherit', 'pipe'],
+ env: createAutomationEnvironment({
+ authToken,
+ baseEnv: process.env,
+ configuration,
+ corsOrigin,
+ socketPath
+ })
+ })
+ child = spawned
- 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.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.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
+ })
+ }
- spawned.on('exit', (code) => {
- if (code && code !== 0) {
- console.error(`[MCP] Server exited with code ${code}`)
- }
- if (child === spawned) child = null
- })
- })()
+ async function restartChild(nextConfiguration: DevMCPConfiguration): Promise<void> {
+ configuration = nextConfiguration
+ await stopChild()
+ await startChild()
+ }
- try {
- await starting
- } finally {
- starting = null
- }
+ return {
+ name: 'open-pencil-automation',
+ async configureServer(server) {
+ server.middlewares.use(DEV_MCP_RESTART_PATH, (request, response, next) => {
+ if (request.method !== 'POST') {
+ next()
+ return
+ }
+ if (!authToken || request.headers.authorization !== `Bearer ${authToken}`) {
+ response.statusCode = 401
+ response.end('Unauthorized')
+ return
+ }
+ void (async () => {
+ try {
+ const nextConfiguration = await readConfiguration(request)
+ if (!isDevMCPConfiguration(nextConfiguration)) {
+ response.statusCode = 400
+ response.end('Invalid MCP configuration')
+ return
+ }
+ await enqueue(() => restartChild(nextConfiguration))
+ response.statusCode = 204
+ response.end()
+ } catch (error) {
+ response.statusCode = 500
+ response.end(error instanceof Error ? error.message : String(error))
+ }
+ })()
+ })
+ await enqueue(startChild)
},
async buildEnd() {
- if (starting) {
- try {
- await starting
- } catch {
- void 0
- }
- }
- child?.kill()
- child = null
- starting = null
+ await enqueue(stopChild)
}
}
}
diff --git a/src/app/automation/mcp/dev-control.ts b/src/app/automation/mcp/dev-control.ts
new file mode 100644
index 000000000..cea40e1ef
--- /dev/null
+++ b/src/app/automation/mcp/dev-control.ts
@@ -0,0 +1,21 @@
+export const DEV_MCP_RESTART_PATH = '/__openpencil/mcp/restart'
+
+export interface DevMCPConfiguration {
+ authenticationEnabled: boolean
+ rootDirectory: string
+ disabledTools: string
+}
+
+export function isDevMCPConfiguration(value: unknown): value is DevMCPConfiguration {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false
+ const authenticationEnabled = Reflect.get(value, 'authenticationEnabled')
+ const rootDirectory = Reflect.get(value, 'rootDirectory')
+ const disabledTools = Reflect.get(value, 'disabledTools')
+ return (
+ typeof authenticationEnabled === 'boolean' &&
+ typeof rootDirectory === 'string' &&
+ rootDirectory.length <= 4_096 &&
+ typeof disabledTools === 'string' &&
+ disabledTools.length <= 65_536
+ )
+}
diff --git a/src/app/automation/mcp/spawn.ts b/src/app/automation/mcp/spawn.ts
index 0ee1b11d1..f84879ad0 100644
--- a/src/app/automation/mcp/spawn.ts
+++ b/src/app/automation/mcp/spawn.ts
@@ -9,6 +9,7 @@ import { decodeTauriStderr } from '@/app/shell/ui'
import { resolvePlatformCommand } from '@/app/tauri/command'
import { isTauri } from '@/app/tauri/env'
+import { DEV_MCP_RESTART_PATH, type DevMCPConfiguration } from './dev-control'
import { disabledMCPToolsCSV, mcpAuthenticationEnabled, mcpRootDirectory } from './preferences'
export interface AutomationHealth {
@@ -259,13 +260,35 @@ async function readExistingServerHandle(): Promise<AutomationServerHandle | null
return { disconnect: noop, authToken: token, managed: false }
}
+async function configureDevMCP(): Promise<AutomationServerHandle> {
+ if (!DEV_AUTOMATION_AUTH_TOKEN) throw new Error('MCP development control token is unavailable')
+ const configuration: DevMCPConfiguration = {
+ authenticationEnabled: mcpAuthenticationEnabled.value,
+ rootDirectory: mcpRootDirectory.value,
+ disabledTools: disabledMCPToolsCSV()
+ }
+ const response = await fetch(DEV_MCP_RESTART_PATH, {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${DEV_AUTOMATION_AUTH_TOKEN}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(configuration)
+ })
+ if (!response.ok) {
+ throw new Error(`Failed to configure development MCP server (${response.status})`)
+ }
+ const health = await pollHealth(10, 250)
+ if (!health) throw new Error('Development MCP server did not become healthy')
+ const authToken = configuration.authenticationEnabled ? DEV_AUTOMATION_AUTH_TOKEN : null
+ runtimeAutomationAuthToken = authToken
+ return { disconnect: noop, authToken, managed: true }
+}
+
async function startMCPIfNeeded(): Promise<AutomationServerHandle | null> {
runtimeAutomationStartupError = null
- if (import.meta.env.DEV || !isTauri()) {
- return DEV_AUTOMATION_AUTH_TOKEN
- ? { disconnect: noop, authToken: DEV_AUTOMATION_AUTH_TOKEN, managed: false }
- : null
- }
+ if (import.meta.env.DEV) return configureDevMCP()
+ if (!isTauri()) return null
const existing = await readExistingServerHandle()
if (existing) {
diff --git a/tests/engine/app/automation/mcp-vite-plugin.test.ts b/tests/engine/app/automation/mcp-vite-plugin.test.ts
new file mode 100644
index 000000000..18cf9aa20
--- /dev/null
+++ b/tests/engine/app/automation/mcp-vite-plugin.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createAutomationEnvironment } from '@/app/automation/bridge/vite-plugin'
+
+describe('MCP Vite development server', () => {
+ test('passes an explicit empty auth token when authentication is disabled', () => {
+ const env = createAutomationEnvironment({
+ authToken: 'development-token',
+ baseEnv: { OPENPENCIL_MCP_AUTH_TOKEN: 'inherited-token' },
+ configuration: {
+ authenticationEnabled: false,
+ rootDirectory: '/designs',
+ disabledTools: 'eval,delete_node'
+ },
+ corsOrigin: 'http://localhost:1420',
+ socketPath: '/tmp/open-pencil.sock'
+ })
+
+ expect(env.OPENPENCIL_MCP_AUTH_TOKEN).toBe('')
+ expect(env.OPENPENCIL_MCP_ROOT).toBe('/designs')
+ expect(env.OPENPENCIL_MCP_DISABLED_TOOLS).toBe('eval,delete_node')
+ })
+})