Skip to content

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

feat(mcp): add export_image_file tool and fix headless PNG rendering (#108)

mcdmagsc847eab75c65
diff --git a/packages/core/src/render/renderer.ts b/packages/core/src/render/renderer.ts
index a94e9c32c..df157ad79 100644
--- a/packages/core/src/render/renderer.ts
+++ b/packages/core/src/render/renderer.ts
@@ -2,6 +2,7 @@ import { parseColor, colorToFill } from '../color'
import { TRANSPARENT } from '../constants'
import { fetchIcons } from '../iconify'
import { createIconFromPaths } from '../icon-render'
+import { computeAllLayouts } from '../layout'
import { isTreeNode } from './tree'
import type { SceneGraph, SceneNode, NodeType, LayoutMode, GridTrack, Stroke } from '../scene-graph'
@@ -92,6 +93,8 @@ export async function renderTree(
if (options.x !== undefined) graph.updateNode(result.id, { x: options.x })
if (options.y !== undefined) graph.updateNode(result.id, { y: options.y })
+ computeAllLayouts(graph)
+
return {
id: result.id,
name: result.name,
diff --git a/packages/core/src/tools/index.ts b/packages/core/src/tools/index.ts
index ba6987743..33436bb79 100644
--- a/packages/core/src/tools/index.ts
+++ b/packages/core/src/tools/index.ts
@@ -1,4 +1,5 @@
export { ALL_TOOLS, CORE_TOOLS, EXTENDED_TOOLS } from './registry'
+export { exportImage } from './vector'
export { defineTool, nodeToResult, nodeSummary } from './schema'
export type { ToolDef, ParamDef, ParamType } from './schema'
export { toolsToAI, buildDebugLog } from './ai-adapter'
diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts
index 20a5f63c3..94b1b4229 100644
--- a/packages/mcp/src/server.ts
+++ b/packages/mcp/src/server.ts
@@ -13,6 +13,7 @@ import {
SceneGraph,
headlessRenderNodes
} from '@open-pencil/core'
+import { exportImage } from '@open-pencil/core/tools'
import type { ToolDef, ParamDef, ParamType, ExportFormat } from '@open-pencil/core'
@@ -170,6 +171,36 @@ export function createServer(version: string, options: CreateServerOptions = {})
}
)
+ register(
+ 'export_image_file',
+ {
+ description: 'Export nodes as a PNG/JPG/WEBP image file saved to disk. Returns the file path and size.',
+ inputSchema: z.object({
+ path: z.string().describe('Absolute path to save the image file (e.g. /tmp/design.png)'),
+ ids: z.array(z.string()).min(1).optional().describe('Node IDs to export. Omit to export all top-level nodes on the current page.'),
+ format: z.enum(['PNG', 'JPG', 'WEBP']).optional().describe('Image format (default: PNG)'),
+ scale: z.number().min(0.1).max(4).optional().describe('Export scale multiplier (default: 2)')
+ })
+ },
+ async ({ path: filePath, ids, format, scale }: { path: string; ids?: string[]; format?: string; scale?: number }) => {
+ try {
+ const outPath = resolveAndCheckPath(filePath)
+ const result = await exportImage.execute(makeFigma(), {
+ ids,
+ format: format ?? 'PNG',
+ scale: scale ?? 2
+ })
+ if (result && 'error' in result) throw new Error(result.error as string)
+ const { base64 } = result as { base64: string }
+ const data = Buffer.from(base64, 'base64')
+ await writeFile(outPath, data)
+ return ok({ saved: outPath, bytes: data.length, format: (format ?? 'PNG').toUpperCase(), scale: scale ?? 2 })
+ } catch (e) {
+ return fail(e)
+ }
+ }
+ )
+
for (const tool of ALL_TOOLS) {
if (!enableEval && tool.name === 'eval') continue
registerTool(tool)
diff --git a/tests/engine/mcp-server.test.ts b/tests/engine/mcp-server.test.ts
index 4963af3a9..1910a0c2d 100644
--- a/tests/engine/mcp-server.test.ts
+++ b/tests/engine/mcp-server.test.ts
@@ -290,6 +290,117 @@ describe('MCP server', () => {
}
})
+ test('export_image_file produces a valid PNG after new_document + render', async () => {
+ const tmpPath = join(import.meta.dir, '..', `_mcp_test_export_${Date.now()}.png`)
+ try {
+ await client.callTool({ name: 'new_document', arguments: {} })
+ await client.callTool({
+ name: 'render',
+ arguments: { jsx: '<Frame w={200} h={100} bg="#FF0000"><Text size={14}>Hello</Text></Frame>' }
+ })
+ const result = await client.callTool({
+ name: 'export_image_file',
+ arguments: { path: tmpPath, format: 'PNG', scale: 1 }
+ })
+ expect(result.isError).not.toBe(true)
+ const data = parseResult(result) as { saved: string; bytes: number; format: string }
+ expect(data.saved).toBe(tmpPath)
+ expect(data.bytes).toBeGreaterThan(100)
+ expect(data.format).toBe('PNG')
+ } finally {
+ await unlink(tmpPath).catch(() => {})
+ }
+ })
+
+ test('export_image_file without ids exports all page children', async () => {
+ const tmpPath = join(import.meta.dir, '..', `_mcp_test_export_all_${Date.now()}.png`)
+ try {
+ await client.callTool({ name: 'new_document', arguments: {} })
+ await client.callTool({
+ name: 'create_shape',
+ arguments: { type: 'FRAME', x: 0, y: 0, width: 100, height: 100 }
+ })
+ const result = await client.callTool({
+ name: 'export_image_file',
+ arguments: { path: tmpPath }
+ })
+ expect(result.isError).not.toBe(true)
+ const data = parseResult(result) as { bytes: number }
+ expect(data.bytes).toBeGreaterThan(0)
+ } finally {
+ await unlink(tmpPath).catch(() => {})
+ }
+ })
+
+ test('export_image_file without a loaded document returns an error', async () => {
+ const result = await client.callTool({
+ name: 'export_image_file',
+ arguments: { path: '/tmp/_no_doc.png' }
+ })
+ expect(result.isError).toBe(true)
+ })
+
+ test('export_image_file with out-of-root path returns an error', async () => {
+ const rootDir = await mkdtemp(join(tmpdir(), 'openpencil-mcp-export-root-'))
+ const custom = await createLinkedClient({ fileRoot: rootDir })
+ try {
+ await custom.client.callTool({ name: 'new_document', arguments: {} })
+ await custom.client.callTool({
+ name: 'create_shape',
+ arguments: { type: 'RECTANGLE', x: 0, y: 0, width: 50, height: 50 }
+ })
+ const result = await custom.client.callTool({
+ name: 'export_image_file',
+ arguments: { path: '/tmp/_outside_root.png' }
+ })
+ expect(result.isError).toBe(true)
+ const data = parseResult(result) as { error: string }
+ expect(data.error).toContain('outside allowed root')
+ } finally {
+ await custom.close()
+ await rm(rootDir, { recursive: true, force: true })
+ }
+ })
+
+ test('export_image_file JPG and WEBP formats produce non-empty output', async () => {
+ const jpgPath = join(import.meta.dir, '..', `_mcp_test_${Date.now()}.jpg`)
+ const webpPath = join(import.meta.dir, '..', `_mcp_test_${Date.now()}.webp`)
+ try {
+ await client.callTool({ name: 'new_document', arguments: {} })
+ await client.callTool({
+ name: 'create_shape',
+ arguments: { type: 'RECTANGLE', x: 0, y: 0, width: 80, height: 80 }
+ })
+
+ const jpgResult = await client.callTool({
+ name: 'export_image_file',
+ arguments: { path: jpgPath, format: 'JPG', scale: 1 }
+ })
+ expect(jpgResult.isError).not.toBe(true)
+ const jpgData = parseResult(jpgResult) as { bytes: number; format: string }
+ expect(jpgData.bytes).toBeGreaterThan(0)
+ expect(jpgData.format).toBe('JPG')
+
+ const webpResult = await client.callTool({
+ name: 'export_image_file',
+ arguments: { path: webpPath, format: 'WEBP', scale: 1 }
+ })
+ expect(webpResult.isError).not.toBe(true)
+ const webpData = parseResult(webpResult) as { bytes: number; format: string }
+ expect(webpData.bytes).toBeGreaterThan(0)
+ expect(webpData.format).toBe('WEBP')
+ } finally {
+ await unlink(jpgPath).catch(() => {})
+ await unlink(webpPath).catch(() => {})
+ }
+ })
+
+ test('export_image_file is listed in tools', async () => {
+ const { tools } = await client.listTools()
+ const names = tools.map((t) => t.name)
+ expect(names).toContain('export_image_file')
+ })
+
test('createServer option fileRoot restricts open_file and save_file paths', async () => {
const rootDir = await mkdtemp(join(tmpdir(), 'openpencil-mcp-root-'))
const insidePath = join(rootDir, 'inside.fig')