Skip to content

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

fix(mcp): let the app render JSX sent through the stdio server (#1027)

Danila Poyarkova8b3997ba9f2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index af96eaa5f..6c03909e3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@
### Breaking changes
+- The app renders `render` JSX itself and no longer accepts the pre-rendered tree that earlier versions of `openpencil-mcp` send, so an older `openpencil-mcp` fails to render into this app version; update it with the app.
- `VectorizedPath` from `@open-pencil/core/vector` replaces `clipNetworks` with `clips`, each the clip path's `id` and one network per clip shape, and adds `elements`, the groups and shape a path was drawn from. `SVGImportData` from `@open-pencil/core/io` adds the root `name` and whether the SVG is `sized`.
- `SceneNode` from `@open-pencil/scene-graph` has `isExposedInstance`, whether an instance inside a component shows its properties on instances of that component, so code that builds `SceneNode` objects itself must include it. In the plugin API, `isExposedInstance` and `exposedInstances` follow that flag and Figma's rules instead of treating an instance whose swap is bound to a property as exposed: only an instance in a component's own layers whose component has properties can be exposed, and its copies in instances report it but cannot change it.
- `usePosition` from `@open-pencil/vue` reports and edits `x`, `y`, and `rotation` as Figma's properties panel does: the turned layer's box on the canvas, measured from its frame or page, and its counterclockwise angle. `getDefaultCanvasBgColor` and `CANVAS_BG_COLOR_DARK` are removed from `@open-pencil/core/constants`; new pages use `PAGE_DEFAULT_BACKGROUNDS`, keyed by interface theme.
@@ -142,6 +143,7 @@
### Fixed
+- Keep design variable bindings and honor `replace_id` and `insert_index` when `render` runs through the stdio MCP server (`openpencil-mcp`) against the desktop or web app, as it already did through the HTTP endpoint (#830).
- Draw layers masked by a group, such as Figma's clip path groups, instead of hiding them; a group used as a mask masks with what its layers draw.
- Import SVG files that start with an XML declaration or doctype, such as Illustrator and Inkscape exports, instead of reporting no supported elements.
- Keep `fill-opacity` and `stroke-opacity` when importing SVG instead of drawing those paints opaque.
diff --git a/bun.lock b/bun.lock
index d033020f5..4c71daefd 100644
--- a/bun.lock
+++ b/bun.lock
@@ -402,7 +402,6 @@
"@hono/node-server": "^1.19.17",
"@modelcontextprotocol/server": "^2.0.0",
"@open-pencil/core": "workspace:*",
- "@open-pencil/design-jsx": "workspace:*",
"@open-pencil/scene-graph": "workspace:*",
"@valibot/to-json-schema": "^1.8.0",
"es-toolkit": "^1.52.0",
diff --git a/packages/mcp/package.json b/packages/mcp/package.json
index 3e4a0577e..0adbcd970 100644
--- a/packages/mcp/package.json
+++ b/packages/mcp/package.json
@@ -66,7 +66,6 @@
"@hono/node-server": "^1.19.17",
"@modelcontextprotocol/server": "^2.0.0",
"@open-pencil/core": "workspace:*",
- "@open-pencil/design-jsx": "workspace:*",
"@open-pencil/scene-graph": "workspace:*",
"@valibot/to-json-schema": "^1.8.0",
"es-toolkit": "^1.52.0",
diff --git a/packages/mcp/src/jsx-preprocess.ts b/packages/mcp/src/jsx-preprocess.ts
deleted file mode 100644
index 82cd81629..000000000
--- a/packages/mcp/src/jsx-preprocess.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { buildComponent, createElement, resolveToTree } from '@open-pencil/design-jsx'
-
-export function preprocessRPC(body: Record<string, unknown>): Record<string, unknown> {
- if (body.command !== 'tool') return body
- const args = body.args as { name?: string; args?: Record<string, unknown> } | undefined
- if (args?.name !== 'render' || !args.args?.jsx) return body
- try {
- const Component = buildComponent(args.args.jsx as string)
- const element = createElement(Component, null)
- const tree = resolveToTree(element)
- return {
- ...body,
- args: { ...args, args: { ...args.args, jsx: undefined, tree } }
- }
- } catch (e) {
- console.warn('JSX preprocessing failed, passing raw:', e instanceof Error ? e.message : e)
- return body
- }
-}
diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts
index 53e0f9cf6..56ebee88b 100644
--- a/packages/mcp/src/server.ts
+++ b/packages/mcp/src/server.ts
@@ -14,7 +14,6 @@ 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/server/sessions'
import { createToolDescriptors } from '#mcp/tool/manifest'
import type { ToolDescriptor, ToolPolicy } from '#mcp/tool/metadata'
@@ -181,12 +180,11 @@ function createHonoApp(options: {
// 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)
+ const 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) {
diff --git a/src/app/automation/bridge/tool-handlers.ts b/src/app/automation/bridge/tool-handlers.ts
index f8766071e..fdbcd3fed 100644
--- a/src/app/automation/bridge/tool-handlers.ts
+++ b/src/app/automation/bridge/tool-handlers.ts
@@ -1,4 +1,3 @@
-import { renderTree } from '@open-pencil/core/design-jsx'
import type { FigmaAPI } from '@open-pencil/core/figma-api'
import {
ALL_TOOLS,
@@ -29,34 +28,6 @@ import { useLibraryService } from '@/app/libraries'
type FigmaFactory = (store: AutomationTarget['store'], pageId?: string) => FigmaAPI
export function createAutomationToolHandler(makeFigma: FigmaFactory) {
- async function handleToolRender(
- target: AutomationTarget,
- toolArgs: Record<string, unknown>
- ): Promise<{ id: string; name: string; type: string; children: string[] }> {
- const store = target.store
- const tree = toolArgs.tree as Parameters<typeof renderTree>[1]
- const parentId = (toolArgs.parent_id as string | undefined) ?? target.pageId
- // A parent on another page puts the new layers there, so that page's history records them.
- const undoPageId = pageIdOf(store.graph, parentId) ?? target.pageId
- const result = await executeWithPageUndo(store, undoPageId, automationUndoLabel('render'), () =>
- store.runMutationWithLayout(
- () =>
- renderTree(store.graph, tree, {
- parentId,
- x: toolArgs.x as number | undefined,
- y: toolArgs.y as number | undefined
- }),
- target.pageId,
- async (node) => {
- await ensureGraphFonts(store.graph, [node.id], store.renderer)
- }
- )
- )
- store.requestRender()
- store.flashNodes([result.id])
- return { id: result.id, name: result.name, type: result.type, children: result.childIds }
- }
-
return async function handleTool(target: AutomationTarget, args: unknown): Promise<unknown> {
const toolName = (args as { name?: string }).name
const requestedArgs = (args as { args?: Record<string, unknown> }).args ?? {}
@@ -86,10 +57,6 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {
toolName: string,
toolArgs: Record<string, unknown>
): Promise<{ result: unknown; edited: boolean }> {
- if (toolName === 'render' && toolArgs.tree) {
- return { result: await handleToolRender(target, toolArgs), edited: true }
- }
-
const def = ALL_TOOLS.find((t) => t.name === toolName && isToolExposed(t, 'mcp'))
if (!def) throw new Error(`Unknown tool: ${toolName}`)
const store = target.store
@@ -103,13 +70,13 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {
label: AUTOMATION_UNDO_LABEL
})
} else if (def.mutates) {
- const pageId = figma.currentPageId
+ const pageId = writtenPageId(store.graph, toolArgs) ?? figma.currentPageId
const mutate = () =>
store.runMutationWithLayout(
() => def.execute(figma, toolArgs),
- figma.currentPageId,
+ pageId,
async () => {
- const pageNode = store.graph.getNode(figma.currentPageId)
+ const pageNode = store.graph.getNode(pageId)
if (pageNode) await ensureGraphFonts(store.graph, pageNode.childIds, store.renderer)
}
)
@@ -129,6 +96,19 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {
}
}
+/**
+ * A parent or a replaced layer on another page puts the new layers there, so that page lays out,
+ * loads their fonts, and records the change in its history.
+ */
+function writtenPageId(
+ graph: AutomationTarget['store']['graph'],
+ args: Record<string, unknown>
+): string | null {
+ // As render places it: a replaced layer's parent wins over parent_id.
+ const nodeId = args.replace_id ?? args.parent_id
+ return typeof nodeId === 'string' ? pageIdOf(graph, nodeId) : null
+}
+
function pageIdOf(graph: AutomationTarget['store']['graph'], nodeId: string): string | null {
let node = graph.getNode(nodeId)
while (node && node.type !== 'CANVAS')
diff --git a/tests/app/automation/bridge/handlers.test.ts b/tests/app/automation/bridge/handlers.test.ts
index d23f48ee4..86e9b92c3 100644
--- a/tests/app/automation/bridge/handlers.test.ts
+++ b/tests/app/automation/bridge/handlers.test.ts
@@ -183,7 +183,7 @@ describe('undo and redo', () => {
name: 'render',
args: {
parent_id: frame.id,
- tree: { type: 'frame', props: { name: 'Rendered', w: 40, h: 40 }, children: [] }
+ jsx: '<Frame name="Rendered" w={40} h={40} />'
}
})
const id = String(rendered.result.id)
@@ -194,6 +194,30 @@ describe('undo and redo', () => {
expect(graph.getNode(frame.id)?.childIds).toEqual([])
})
+ test('undo reverts a render that replaces a layer on another page', async () => {
+ const tab = createTab()
+ const graph = tab.store.graph
+ const otherPage = graph.addPage('Other')
+ const frame = graph.createNode('FRAME', otherPage.id, { width: 200, height: 200 })
+ const placeholder = graph.createNode('RECTANGLE', frame.id, { width: 40, height: 40 })
+ // replace_id decides where the layer goes, so its page records the change.
+ const rendered = await request('tool', {
+ document_id: tab.id,
+ name: 'render',
+ args: {
+ jsx: '<Frame name="Rendered" w={40} h={40} />',
+ replace_id: placeholder.id,
+ parent_id: tab.store.state.currentPageId
+ }
+ })
+ const id = String(rendered.result.id)
+ expect(graph.getNode(id)?.parentId).toBe(frame.id)
+
+ await request('undo', { document_id: tab.id })
+ expect(graph.getNode(id)).toBeUndefined()
+ expect(graph.getNode(frame.id)?.childIds).toEqual([placeholder.id])
+ })
+
test('a read-only eval leaves the history unchanged', async () => {
const tab = createTab()
await request('eval', { document_id: tab.id, code: 'return figma.currentPage.name' })
@@ -201,6 +225,69 @@ describe('undo and redo', () => {
})
})
+// The stdio MCP server sends render JSX as written; these are what #830 lost on that path.
+describe('render JSX', () => {
+ function render(tabId: string, args: Record<string, unknown>) {
+ return request('tool', { document_id: tabId, name: 'render', args })
+ }
+
+ test('binds a design variable', async () => {
+ const tab = createTab()
+ const graph = tab.store.graph
+ graph.addCollection({
+ id: 'brand',
+ name: 'Brand',
+ modes: [{ modeId: 'default', name: 'Default' }],
+ defaultModeId: 'default',
+ variableIds: []
+ })
+ graph.addVariable({
+ id: 'var-primary',
+ name: 'Brand/primary',
+ type: 'COLOR',
+ collectionId: 'brand',
+ valuesByMode: { default: { r: 1, g: 0, b: 0, a: 1 } },
+ description: '',
+ hiddenFromPublishing: false
+ })
+ const rendered = await render(tab.id, {
+ jsx: "<Frame w={100} h={100} fill={designVar('Brand/primary')} />"
+ })
+ const node = graph.getNode(String(rendered.result.id))
+ expect(node?.boundVariables['fills/0/color']).toBe('var-primary')
+ })
+
+ test('replaces a placeholder in its place', async () => {
+ const tab = createTab()
+ const graph = tab.store.graph
+ const placeholder = tab.store.createShape('RECTANGLE', 60, 30, 40, 40)
+ const rendered = await render(tab.id, {
+ jsx: '<Frame name="Card" w={40} h={40} />',
+ replace_id: placeholder
+ })
+ const node = graph.getNode(String(rendered.result.id))
+ expect(graph.getNode(placeholder)).toBeUndefined()
+ expect([node?.x, node?.y]).toEqual([60, 30])
+ })
+
+ test('inserts at the requested index', async () => {
+ const tab = createTab()
+ const graph = tab.store.graph
+ const frame = graph.createNode('FRAME', tab.store.state.currentPageId, {
+ width: 200,
+ height: 200
+ })
+ graph.createNode('RECTANGLE', frame.id, { name: 'First' })
+ graph.createNode('RECTANGLE', frame.id, { name: 'Second' })
+ const rendered = await render(tab.id, {
+ jsx: '<Frame name="Inserted" w={20} h={20} />',
+ parent_id: frame.id,
+ insert_index: 1
+ })
+ expect(graph.getNode(frame.id)?.childIds[1]).toBe(String(rendered.result.id))
+ })
+})
+
describe('close_file and save_file never prompt', () => {
function dirtyTab() {
const tab = createTab()
diff --git a/tests/engine/mcp/server/index.test.ts b/tests/engine/mcp/server/index.test.ts
index bb9faf7d6..93b3de04d 100644
--- a/tests/engine/mcp/server/index.test.ts
+++ b/tests/engine/mcp/server/index.test.ts
@@ -406,6 +406,35 @@ describe('MCP server sharing only the selection', () => {
})
})
+describe('raw RPC', () => {
+ test('forwards render JSX to the app as written, with its placement', async () => {
+ const ctx = await createTestClient()
+ try {
+ const { browser, handle } = ctx
+ const args = {
+ jsx: "<Frame w={100} h={100} fill={designVar('Brand/primary')} />",
+ replace_id: '0:1',
+ insert_index: 0
+ }
+ await fetch(`http://127.0.0.1:${handle.httpPort}/rpc`, {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${TEST_CLIENT_AUTH_TOKEN}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({ command: 'tool', args: { name: 'render', args } })
+ })
+ // The app renders it, so variable references survive; a tree sent as JSON would lose them.
+ const call = expectDefined(browser, 'browser').requests.find(
+ (request) => request.command === 'tool'
+ )
+ expect(call?.args).toEqual({ name: 'render', args })
+ } finally {
+ await ctx.close()
+ }
+ })
+})
+
describe('MCP server with mcpRoot', () => {
async function withMCPRootServer(
mcpRoot: string | null,