AI-native design editor. Open-source Figma alternative.
fix(mcp): harden tool responses
Danila Poyarkov31a1e1710544
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f7c8d4bca..49c28652d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,7 @@### Fixes+- Harden MCP calls with bounded page-tree responses, oversized-result errors, JSON HTTP responses, and stale WebSocket cleanup.- Improve Figma boolean imports by preserving XOR operations as editable exclude nodes and falling back to imported fill geometry when boolean path reconstruction cannot produce a path.- Preserve rotated Figma transform origins for imported vector nodes.- Render complex text fills through vector glyph outlines so imported Figma text can use the normal fill pipeline for gradients, images, patterns, and other non-solid paints.diff --git a/packages/core/src/tools/read/nodes.ts b/packages/core/src/tools/read/nodes.tsindex ad305ef8f..5fee785c6 100644--- a/packages/core/src/tools/read/nodes.ts+++ b/packages/core/src/tools/read/nodes.ts@@ -10,7 +10,23 @@ interface TreeEntry {children?: TreeEntry[]}-function nodeToTreeEntry(node: FigmaNodeProxy): TreeEntry {+function nodeToTreeEntry(+ node: FigmaNodeProxy,+ level: number,+ maxDepth?: number,+ typeFilter?: Set<string>+): TreeEntry | null {+ const children: TreeEntry[] = []+ if ((maxDepth === undefined || level < maxDepth) && node.children.length > 0) {+ for (const child of node.children) {+ const entry = nodeToTreeEntry(child, level + 1, maxDepth, typeFilter)+ if (entry) children.push(entry)+ }+ }++ const matches = !typeFilter || typeFilter.has(node.type)+ if (!matches && children.length === 0) return null+const entry: TreeEntry = {id: node.id,type: node.type,@@ -18,23 +34,45 @@ function nodeToTreeEntry(node: FigmaNodeProxy): TreeEntry {w: node.width,h: node.height}- if (node.children.length > 0) {- entry.children = node.children.map(nodeToTreeEntry)- }+ if (children.length > 0) entry.children = childrenreturn entry}export const getPageTree = defineTool({name: 'get_page_tree',description:- 'Get the node tree of the current page. Returns lightweight hierarchy: id, type, name, size. Use get_node for full properties of a specific node.',- params: {},- execute: (figma) => {+ 'Get the node tree of the current page. Returns lightweight hierarchy: id, type, name, size. Use depth, root_id, or node_types to keep large pages small. Use get_node for full properties of a specific node.',+ params: {+ depth: {+ type: 'number',+ description: 'Max nesting depth to return (1 = returned root nodes only). Default: unlimited',+ min: 1+ },+ root_id: {+ type: 'string',+ description: 'Return only this node subtree instead of the whole current page'+ },+ node_types: {+ type: 'string[]',+ description: 'Keep only these node types and their ancestors, for example FRAME or TEXT'+ }+ },+ execute: (figma, { depth, root_id, node_types }) => {+ const typeFilter = node_types && node_types.length > 0 ? new Set(node_types) : undefined++ if (root_id !== undefined) {+ const root = figma.getNodeById(root_id)+ if (!root) return { error: `Node "${root_id}" not found` }+ return { root: root.id, tree: nodeToTreeEntry(root, 1, depth, typeFilter) }+ }+const page = figma.currentPage- return {- page: page.name,- children: page.children.map(nodeToTreeEntry)+ const children: TreeEntry[] = []+ for (const child of page.children) {+ const entry = nodeToTreeEntry(child, 1, depth, typeFilter)+ if (entry) children.push(entry)}+ return { page: page.name, children }}})diff --git a/packages/mcp/src/browser-rpc.ts b/packages/mcp/src/browser-rpc.tsindex 5ea21f19b..3d360194f 100644--- a/packages/mcp/src/browser-rpc.ts+++ b/packages/mcp/src/browser-rpc.ts@@ -5,7 +5,7 @@ import type { WebSocket } from 'ws'import type { RpcJsonObject } from '#mcp/json'import type { PendingRequest } from '#mcp/rpc-types'-const RPC_TIMEOUT = 30_000+const RPC_TIMEOUT = 20_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.'@@ -40,6 +40,23 @@ function sendJson(ws: WebSocket, body: Record<string, unknown>) {if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(body))}+function createSettler<T>(resolve: (value: T) => void, reject: (error: Error) => void) {+ let settled = false+ return {+ resolve: (value: T) => {+ if (settled) return+ settled = true+ resolve(value)+ },+ reject: (error: Error) => {+ if (settled) return+ settled = true+ reject(error)+ },+ isSettled: () => settled+ }+}+export function createBrowserRpcBridge({ authToken, onConnectionChange }: BrowserRpcBridgeOptions) {const pending = new Map<string, PendingRequest>()const clients = new Set<WebSocket>()@@ -79,17 +96,27 @@ export function createBrowserRpcBridge({ authToken, onConnectionChange }: Browsefunction sendRpc(body: Record<string, unknown>): Promise<unknown> {return new Promise((resolve, reject) => {- if (!browserWs || browserWs.readyState !== browserWs.OPEN || !browserRegistered) {+ 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)- reject(new Error('RPC timeout (30s)'))+ settle.reject(new Error(`RPC timeout (${Math.round(RPC_TIMEOUT / 1000)}s)`))}, RPC_TIMEOUT)- pending.set(id, { resolve, reject, timer })- browserWs.send(JSON.stringify({ type: 'request', id, ...body }))+ 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)))+ }+ }})}diff --git a/packages/mcp/src/mcp-sessions.ts b/packages/mcp/src/mcp-sessions.tsindex f2ffb8b06..be89de74e 100644--- a/packages/mcp/src/mcp-sessions.ts+++ b/packages/mcp/src/mcp-sessions.ts@@ -49,7 +49,8 @@ export function createMcpSessionManager({registerTools(server)const transport = new WebStandardStreamableHTTPServerTransport({- sessionIdGenerator: () => id+ sessionIdGenerator: () => id,+ enableJsonResponse: true})void server.connect(transport)sessions.set(id, { transport, server, lastSeen: Date.now() })diff --git a/packages/mcp/src/result.ts b/packages/mcp/src/result.tsindex f811cd8e6..fd245f823 100644--- a/packages/mcp/src/result.ts+++ b/packages/mcp/src/result.ts@@ -1,11 +1,34 @@+import { Buffer } from 'node:buffer'+export type MCPContent =| { type: 'text'; text: string }| { type: 'image'; data: string; mimeType: string }export type MCPResult = { content: MCPContent[]; isError?: boolean }-export function ok(data: unknown): MCPResult {- return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] }+export const MAX_RESULT_BYTES = 900_000++export function resultTooLargeMessage(kind: string, bytes: number, hint: string): string {+ return `${kind} is too large (${Math.round(bytes / 1024)}KB, limit ${Math.round(+ MAX_RESULT_BYTES / 1024+ )}KB). ${hint}`+}++export function ok(data: unknown, toolName?: string): MCPResult {+ const text = JSON.stringify(data, null, 2)+ const bytes = Buffer.byteLength(text, 'utf8')+ if (bytes > MAX_RESULT_BYTES) {+ return fail(+ new Error(+ resultTooLargeMessage(+ toolName ? `Result from "${toolName}"` : 'Result',+ bytes,+ 'Narrow the request with depth/root_id/node_types, get_node, or find_nodes.'+ )+ )+ )+ }+ return { content: [{ type: 'text', text }] }}export function fail(e: unknown): MCPResult {diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.tsindex e5c400863..15c637c4b 100644--- a/packages/mcp/src/server.ts+++ b/packages/mcp/src/server.ts@@ -3,7 +3,7 @@ import { Hono } from 'hono'import { cors } from 'hono/cors'import { resolveCommand } from 'package-manager-detector/commands'import { detect, getUserAgent } from 'package-manager-detector/detect'-import { WebSocketServer } from 'ws'+import { WebSocketServer, type WebSocket } from 'ws'import type { RpcJsonObject } from '#mcp/json'@@ -17,6 +17,8 @@ import { registerTools } from './tool/registration'export const MCP_VERSION: string = packageJson.version+const HEARTBEAT_INTERVAL_MS = 5_000+let installCommandPromise: Promise<string> | null = nullasync function resolveMcpInstallCommand(): Promise<string> {@@ -74,11 +76,15 @@ export function startServer(options: ServerOptions = {}) {// --- WebSocket: browser connects here ---const wss = new WebSocketServer({ port: wsPort, host: '127.0.0.1' })+ const alive = new WeakMap<WebSocket, boolean>()wss.on('connection', (ws) => {+ alive.set(ws, true)browserRpc.handleConnection(ws)+ ws.on('pong', () => alive.set(ws, true))ws.on('message', (raw) => {+ alive.set(ws, true)const data = typeof raw === 'string' ? raw : Buffer.from(raw as Buffer).toString('utf-8')browserRpc.handleMessage(data, ws)})@@ -86,8 +92,37 @@ export function startServer(options: ServerOptions = {}) {ws.on('close', () => {browserRpc.handleClose(ws)})++ ws.on('error', () => {+ try {+ ws.terminate()+ } catch {+ alive.delete(ws)+ }+ })})+ const heartbeat = setInterval(() => {+ for (const ws of wss.clients) {+ if (alive.get(ws) === false) {+ try {+ ws.terminate()+ } catch {+ continue+ }+ continue+ }+ alive.set(ws, false)+ try {+ ws.ping()+ } catch {+ continue+ }+ }+ }, HEARTBEAT_INTERVAL_MS)+ heartbeat.unref()+ wss.on('close', () => clearInterval(heartbeat))+// --- HTTP server ---const app = new Hono()diff --git a/packages/mcp/src/tool/registration.ts b/packages/mcp/src/tool/registration.tsindex 582b44ca9..0702b2363 100644--- a/packages/mcp/src/tool/registration.ts+++ b/packages/mcp/src/tool/registration.ts@@ -1,3 +1,4 @@+import { Buffer } from 'node:buffer'import { resolve } from 'node:path'import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'@@ -6,7 +7,7 @@ import { z } from 'zod'import { ALL_TOOLS, CODEGEN_PROMPT } from '@open-pencil/core/tools'import type { RpcJsonObject } from '#mcp/json'-import { fail, ok } from '#mcp/result'+import { MAX_RESULT_BYTES, fail, ok, resultTooLargeMessage } from '#mcp/result'import { resolveSafePath, writeToolOutput } from './output'import { paramToZod } from './schema'@@ -45,17 +46,30 @@ export function registerTools(mcpServer: McpServer, options: RegisterToolsOptionif (written) return written}if (r && 'base64' in r && 'mimeType' in r) {+ const base64 = String(r.base64)+ const bytes = Buffer.byteLength(base64, 'utf8')+ if (bytes > MAX_RESULT_BYTES) {+ return fail(+ new Error(+ resultTooLargeMessage(+ `Image from "${def.name}"`,+ bytes,+ 'Export a smaller region or lower the scale/resolution.'+ )+ )+ )+ }return {content: [{type: 'image' as const,- data: r.base64 as string,+ data: base64,mimeType: r.mimeType as string}]}}- return ok(r)+ return ok(r, def.name)} catch (e) {return fail(e)}diff --git a/tests/engine/mcp/result.test.ts b/tests/engine/mcp/result.test.tsnew file mode 100644index 000000000..3b2093ac5--- /dev/null+++ b/tests/engine/mcp/result.test.ts@@ -0,0 +1,16 @@+import { describe, expect, test } from 'bun:test'++import { MAX_RESULT_BYTES, ok } from '#mcp/result'++describe('MCP result formatting', () => {+ test('returns structured errors for oversized text results', () => {+ const result = ok({ payload: 'x'.repeat(MAX_RESULT_BYTES) }, 'large_tool')++ expect(result.isError).toBe(true)+ expect(result.content[0].type).toBe('text')+ if (result.content[0].type !== 'text') throw new Error('Expected text result')+ const error = JSON.parse(result.content[0].text) as { error: string }+ expect(error.error).toContain('large_tool')+ expect(error.error).toContain('too large')+ })+})diff --git a/tests/engine/mcp/server.test.ts b/tests/engine/mcp/server.test.tsindex 287895f3b..814464109 100644--- a/tests/engine/mcp/server.test.ts+++ b/tests/engine/mcp/server.test.ts@@ -279,6 +279,41 @@ 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++ 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 WebSocket stdio bridge routing', () => {test('forwards stdio client requests to the registered desktop app', async () => {const { wss, close: closeServer } = startServer({ httpPort: 0, wsPort: 0 })diff --git a/tests/engine/mcp/tools.test.ts b/tests/engine/mcp/tools.test.tsindex 7fb088509..91e5a9a2b 100644--- a/tests/engine/mcp/tools.test.ts+++ b/tests/engine/mcp/tools.test.ts@@ -11,6 +11,8 @@ interface PageTreeResult {interface PageTreeNode {id: string+ type: string+ name: stringchildren?: PageTreeNode[]}@@ -55,6 +57,59 @@ describe('MCP tool execution', () => {expect(result.children).toBeArray()})+ test('get_page_tree supports depth, root_id, and node_types filters', () => {+ const { api } = setup()+ const parent = findTool('create_shape').execute(api, {+ type: 'FRAME',+ x: 0,+ y: 0,+ width: 400,+ height: 400,+ name: 'Parent'+ }) as { id: string }+ const text = findTool('create_shape').execute(api, {+ type: 'TEXT',+ x: 0,+ y: 0,+ width: 100,+ height: 20,+ parent_id: parent.id,+ name: 'Nested text'+ }) as { id: string }+ findTool('create_shape').execute(api, {+ type: 'RECTANGLE',+ x: 0,+ y: 0,+ width: 50,+ height: 50,+ name: 'Other rect'+ })++ const depthTree = findTool('get_page_tree').execute(api, { depth: 1 }) as PageTreeResult+ const depthParent = expectDefined(+ depthTree.children.find((node) => node.id === parent.id),+ 'depth-limited parent'+ )+ expect(depthParent.children).toBeUndefined()++ const subtree = findTool('get_page_tree').execute(api, { root_id: parent.id }) as {+ root: string+ tree: PageTreeNode+ }+ expect(subtree.root).toBe(parent.id)+ expect(subtree.tree.children?.[0]?.id).toBe(text.id)++ const filtered = findTool('get_page_tree').execute(api, {+ node_types: ['TEXT']+ }) as PageTreeResult+ expect(filtered.children.some((node) => node.type === 'RECTANGLE')).toBe(false)+ const filteredParent = expectDefined(+ filtered.children.find((node) => node.id === parent.id),+ 'filtered parent'+ )+ expect(filteredParent.children?.[0]?.type).toBe('TEXT')+ })+test('create_shape creates a frame', () => {const { api } = setup()const result = findTool('create_shape').execute(api, {diff --git a/vite/automation.ts b/vite/automation.tsindex 8c129b474..abc5ef9cf 100644--- a/vite/automation.ts+++ b/vite/automation.ts@@ -1,8 +1,9 @@import { randomUUID } from 'node:crypto'+import process from 'node:process'import { automationPlugin } from '../src/app/automation/bridge/vite-plugin'-const devAutomationAuthToken = randomUUID()+const devAutomationAuthToken = process.env.OPENPENCIL_DEV_TOKEN ?? randomUUID()export function localAutomationToken(command: string): string | null {return command === 'serve' ? devAutomationAuthToken : null