AI-native design editor. Open-source Figma alternative.
fix(mcp): fix stdio handshake and eval return values
Danila Poyarkov9e013e60e779
diff --git a/packages/core/src/tools/analyze.ts b/packages/core/src/tools/analyze.tsindex 9ac6fc864..70f95defc 100644--- a/packages/core/src/tools/analyze.ts+++ b/packages/core/src/tools/analyze.ts@@ -2,5 +2,6 @@ export { analyzeClusters, calcClusterConfidence } from './analyze/clusters'export { analyzeColors } from './analyze/colors'export { diffCreate, diffShow } from './analyze/diff'export { evalCode } from './analyze/eval'+export { wrapEvalCode } from './analyze/eval-wrap'export { analyzeSpacing } from './analyze/spacing'export { analyzeTypography } from './analyze/typography'diff --git a/packages/core/src/tools/analyze/eval-wrap.ts b/packages/core/src/tools/analyze/eval-wrap.tsnew file mode 100644index 000000000..a511481bc--- /dev/null+++ b/packages/core/src/tools/analyze/eval-wrap.ts@@ -0,0 +1,26 @@+const STATEMENT_START =+ /^(const |let |var |if |else |for |while |do |switch |try |catch |throw |return |async function |function |class |\{|\}|\/\/|\/\*)/++/**+ * Wrap eval code so the last bare expression is returned (REPL-style).+ *+ * - Already starts with `return` -> used verbatim+ * - Last non-empty line looks like a statement -> wrap everything in async IIFE+ * - Otherwise -> promote the last expression line to `return (expr)`+ */+export function wrapEvalCode(code: string): string {+ const trimmed = code.trim()+ if (trimmed.startsWith('return')) return trimmed++ const lines = trimmed.split('\n')+ let lastIdx = lines.length - 1+ while (lastIdx > 0 && !lines[lastIdx].trim()) lastIdx--+ const lastLine = lines[lastIdx].trim()++ if (lastLine && !STATEMENT_START.test(lastLine) && !lastLine.endsWith('}')) {+ const body = lines.slice(0, lastIdx).join('\n')+ return body ? `${body}\nreturn (${lastLine})` : `return (${lastLine})`+ }++ return `return (async () => { ${trimmed} })()`+}diff --git a/packages/core/src/tools/analyze/eval.ts b/packages/core/src/tools/analyze/eval.tsindex 4aafdc9b5..a94afd910 100644--- a/packages/core/src/tools/analyze/eval.ts+++ b/packages/core/src/tools/analyze/eval.ts@@ -1,5 +1,7 @@import { defineTool } from '#core/tools/schema'+import { wrapEvalCode } from './eval-wrap'+export const evalCode = defineTool({name: 'eval',description:@@ -14,8 +16,7 @@ export const evalCode = defineTool({) => (...args: unknown[]) => Promise<unknown>const AsyncFunction = Object.getPrototypeOf(async () => undefined).constructor as AsyncFunctionConstructor- const wrapped = code.trim().startsWith('return') ? code : `return (async () => { ${code} })()`- const fn = new AsyncFunction('figma', wrapped)+ const fn = new AsyncFunction('figma', wrapEvalCode(code))const result = await fn(figma)if (result && typeof result === 'object') {const toJSON = Reflect.get(result, 'toJSON')diff --git a/packages/core/src/tools/index.ts b/packages/core/src/tools/index.tsindex 88cada854..9d5d7808b 100644--- a/packages/core/src/tools/index.ts+++ b/packages/core/src/tools/index.ts@@ -5,6 +5,6 @@ export { defineTool, nodeToResult, nodeSummary, requireNode, NodeNotFoundError }export type { ToolDef, ParamDef, ParamType } from './schema'export { toolsToAI, buildDebugLog } from './ai-adapter'export type { ToolLogEntry, ToolDebugLog, AIAdapterOptions, StepBudget } from './ai-adapter'-export { calcClusterConfidence } from './analyze'+export { calcClusterConfidence, wrapEvalCode } from './analyze'export { setPexelsApiKey, setUnsplashAccessKey } from './stock-photo'export { importSvg } from './create'diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.tsindex 7fd3eb3a3..9339f5c13 100644--- a/packages/mcp/src/server.ts+++ b/packages/mcp/src/server.ts@@ -53,6 +53,9 @@ export function startServer(options: ServerOptions = {}) {const wss = new WebSocketServer({ port: wsPort, host: '127.0.0.1' })wss.on('connection', (ws) => {+ const token = browserRpc.currentRpcToken()+ if (token) ws.send(JSON.stringify({ type: 'register', token }))+ws.on('message', (raw) => {browserRpc.handleMessage(typeof raw === 'string' ? raw : Buffer.from(raw as Buffer).toString('utf-8'),diff --git a/src/app/automation/bridge/eval-handler.ts b/src/app/automation/bridge/eval-handler.tsindex 119f7fa34..9162abd17 100644--- a/src/app/automation/bridge/eval-handler.ts+++ b/src/app/automation/bridge/eval-handler.ts@@ -1,4 +1,5 @@import type { FigmaAPI } from '@open-pencil/core/figma-api'+import { wrapEvalCode } from '@open-pencil/core/tools'import type { EditorStore } from '@/app/editor/active-store'@@ -12,10 +13,7 @@ export function createAutomationEvalHandler(makeFigma: FigmaFactory) {const AsyncFunction = Object.getPrototypeOf(async function () {/* noop */}).constructor- const wrappedCode = code.trim().startsWith('return')- ? code- : `return (async () => { ${code} })()`- const fn = new AsyncFunction('figma', wrappedCode)+ const fn = new AsyncFunction('figma', wrapEvalCode(code))const result = await fn(figma)store.requestRender()return { ok: true, result: result ?? null }diff --git a/tests/engine/tools/eval-wrap.test.ts b/tests/engine/tools/eval-wrap.test.tsnew file mode 100644index 000000000..c5f273f02--- /dev/null+++ b/tests/engine/tools/eval-wrap.test.ts@@ -0,0 +1,66 @@+import { describe, expect, test } from 'bun:test'++import { wrapEvalCode } from '@open-pencil/core/tools'++type AsyncFn = (...args: unknown[]) => Promise<unknown>+const AsyncFunction = Object.getPrototypeOf(async () => undefined).constructor as new (+ ...args: string[]+) => AsyncFn++async function run(code: string): Promise<unknown> {+ return new AsyncFunction(wrapEvalCode(code))()+}++describe('wrapEvalCode', () => {+ test('bare number is returned', async () => {+ expect(await run('42')).toBe(42)+ })++ test('bare string is returned', async () => {+ expect(await run('"hello"')).toBe('hello')+ })++ test('arithmetic expression is returned', async () => {+ expect(await run('1 + 2')).toBe(3)+ })++ test('multi-line: last expression is returned', async () => {+ expect(await run('const x = 10\nx * 2')).toBe(20)+ })++ test('code starting with return is used verbatim', async () => {+ expect(await run('return 99')).toBe(99)+ })++ test('variable declaration alone returns undefined', async () => {+ expect(await run('const x = 5')).toBeUndefined()+ })++ test('await expression is returned', async () => {+ expect(await run('await Promise.resolve(7)')).toBe(7)+ })++ test('object literal is returned', async () => {+ expect(await run('({ a: 1 })')).toEqual({ a: 1 })+ })++ test('array literal is returned', async () => {+ expect(await run('[1, 2, 3]')).toEqual([1, 2, 3])+ })++ test('function call result is returned', async () => {+ expect(await run('JSON.stringify({ x: 1 })')).toBe('{"x":1}')+ })++ test('closing brace wraps in IIFE', () => {+ expect(wrapEvalCode('function f() {}')).toContain('async ()')+ })++ test('if statement wraps in IIFE', () => {+ expect(wrapEvalCode('if (true) { 1 }')).toContain('async ()')+ })++ test('for loop wraps in IIFE', () => {+ expect(wrapEvalCode('for (let i = 0; i < 1; i++) {}')).toContain('async ()')+ })+})