AI-native design editor. Open-source Figma alternative.
feat(mcp): add open_file, new_document tools and disk export via path param
Danila Poyarkovb502b43c4d22
diff --git a/desktop/capabilities/default.json b/desktop/capabilities/default.jsonindex 1527af7d6..ca5dc7218 100644--- a/desktop/capabilities/default.json+++ b/desktop/capabilities/default.json@@ -17,7 +17,14 @@"identifier": "fs:allow-write-file","allow": [{ "path": "**" }]},- "fs:allow-watch",+ {+ "identifier": "fs:allow-mkdir",+ "allow": [{ "path": "**" }]+ },+ {+ "identifier": "fs:allow-watch",+ "allow": [{ "path": "**" }]+ },"fs:allow-unwatch",{"identifier": "shell:allow-spawn",diff --git a/packages/core/src/tools/read.ts b/packages/core/src/tools/read.tsindex bc561d28c..6b05081ea 100644--- a/packages/core/src/tools/read.ts+++ b/packages/core/src/tools/read.ts@@ -288,7 +288,11 @@ export const getJsx = defineTool({description:'Get JSX representation of a node and its children. Compact round-trip format — same syntax as the render tool.',params: {- id: { type: 'string', description: 'Node ID', required: true }+ id: { type: 'string', description: 'Node ID', required: true },+ path: {+ type: 'string',+ description: 'Write JSX to this path instead of returning it (requires OPENPENCIL_MCP_ROOT)'+ }},execute: (figma, { id }) => {const node = figma.getNodeById(id)diff --git a/packages/core/src/tools/vector.ts b/packages/core/src/tools/vector.tsindex 6c03fa1dc..506e47687 100644--- a/packages/core/src/tools/vector.ts+++ b/packages/core/src/tools/vector.ts@@ -263,6 +263,10 @@ export const exportSvg = defineTool({ids: {type: 'string[]',description: 'Node IDs to export. Omit to export all top-level nodes on the current page.'+ },+ path: {+ type: 'string',+ description: 'Write SVG to this path instead of returning it (requires OPENPENCIL_MCP_ROOT)'}},execute: async (figma, args) => {@@ -297,6 +301,11 @@ export const exportImage = defineTool({default: 1,min: 0.1,max: 4+ },+ path: {+ type: 'string',+ description:+ 'Write image to this path instead of returning base64 (requires OPENPENCIL_MCP_ROOT)'}},execute: async (figma, args) => {diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.tsindex 32b3530a0..ebdc08da7 100644--- a/packages/mcp/src/index.ts+++ b/packages/mcp/src/index.ts@@ -11,6 +11,7 @@ const { app, httpPort } = startServer({httpPort: port,wsPort,enableEval: process.env.OPENPENCIL_MCP_EVAL === '1',+ mcpRoot: process.env.OPENPENCIL_MCP_ROOT?.trim() || process.cwd(),authToken: process.env.OPENPENCIL_MCP_AUTH_TOKEN?.trim() || null,corsOrigin: process.env.OPENPENCIL_MCP_CORS_ORIGIN?.trim() || null})diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.tsindex b98921d57..05183ab27 100644--- a/packages/mcp/src/server.ts+++ b/packages/mcp/src/server.ts@@ -1,5 +1,7 @@import { randomUUID } from 'node:crypto'+import { writeFile, mkdir } from 'node:fs/promises'import { createRequire } from 'node:module'+import { resolve, dirname, sep as osSep } from 'node:path'import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'@@ -47,13 +49,47 @@ export type RpcSender = (body: Record<string, unknown>) => Promise<unknown>export interface RegisterToolsOptions {enableEval: boolean+ mcpRoot?: string | nullsendRpc: RpcSender}+function resolveSafePath(filePath: string, root: string): string {+ const resolved = resolve(filePath)+ const sep = root.endsWith('/') || root.endsWith('\\') ? '' : osSep+ if (!resolved.startsWith(root + sep) && resolved !== root) {+ throw new Error(`Path is outside the allowed root: ${root}`)+ }+ return resolved+}+export function registerTools(mcpServer: McpServer, options: RegisterToolsOptions) {const { enableEval, sendRpc } = options+ const resolvedRoot = options.mcpRoot ? resolve(options.mcpRoot) : nullconst register = mcpServer.registerTool.bind(mcpServer) as (...a: unknown[]) => void+ async function writeToolOutput(+ toolName: string,+ r: Record<string, unknown>,+ filePath: string,+ root: string+ ): Promise<MCPResult | null> {+ const resolved = resolveSafePath(filePath, root)+ await mkdir(dirname(resolved), { recursive: true })+ if (toolName === 'export_svg' && typeof r.svg === 'string') {+ await writeFile(resolved, r.svg, 'utf8')+ return ok({ written: resolved, byteLength: Buffer.byteLength(r.svg, 'utf8') })+ }+ if (toolName === 'export_image' && typeof r.base64 === 'string') {+ await writeFile(resolved, Buffer.from(r.base64, 'base64'))+ return ok({ written: resolved, byteLength: r.byteLength ?? null })+ }+ if (toolName === 'get_jsx' && typeof r.jsx === 'string') {+ await writeFile(resolved, r.jsx, 'utf8')+ return ok({ written: resolved, byteLength: Buffer.byteLength(r.jsx, 'utf8') })+ }+ return null+ }+for (const def of ALL_TOOLS) {if (!enableEval && def.name === 'eval') continueconst shape: Record<string, z.ZodType> = {}@@ -69,6 +105,11 @@ export function registerTools(mcpServer: McpServer, options: RegisterToolsOptionconst res = result as { ok?: boolean; result?: unknown; error?: string }if (res.ok === false) return fail(new Error(res.error))const r = res.result as Record<string, unknown> | undefined+ const filePath = typeof args.path === 'string' ? args.path : null+ if (r && filePath && resolvedRoot) {+ const written = await writeToolOutput(def.name, r, filePath, resolvedRoot)+ if (written) return written+ }if (r && 'base64' in r && 'mimeType' in r) {return {content: [@@ -107,6 +148,50 @@ export function registerTools(mcpServer: McpServer, options: RegisterToolsOption})+ if (resolvedRoot) {+ register(+ 'open_file',+ {+ description: `Open a .fig or .pen file from disk into a new tab. Path must be inside ${resolvedRoot}.`,+ inputSchema: z.object({+ path: z.string().describe('Absolute path to the design file')+ })+ },+ async (args: { path: string }) => {+ try {+ const safe = resolveSafePath(args.path, resolvedRoot)+ const result = await sendRpc({ command: 'open_file', args: { path: safe } })+ const res = result as { ok?: boolean; error?: string }+ if (res.ok === false) return fail(new Error(res.error))+ return ok({ opened: true })+ } catch (e) {+ return fail(e)+ }+ }+ )++ register(+ 'new_document',+ {+ description: `Create a new empty document. Optionally set a save path inside ${resolvedRoot}.`,+ inputSchema: z.object({+ path: z.string().describe('Optional absolute path for the new file').optional()+ })+ },+ async (args: { path?: string }) => {+ try {+ const safePath = args.path ? resolveSafePath(args.path, resolvedRoot) : undefined+ const result = await sendRpc({ command: 'new_document', args: { path: safePath } })+ const res = result as { ok?: boolean; error?: string }+ if (res.ok === false) return fail(new Error(res.error))+ return ok({ created: true })+ } catch (e) {+ return fail(e)+ }+ }+ )+ }+register('get_codegen_prompt',{@@ -143,6 +228,7 @@ export interface ServerOptions {httpPort?: numberwsPort?: numberenableEval?: boolean+ mcpRoot?: string | nullauthToken?: string | nullcorsOrigin?: string | null}@@ -151,6 +237,7 @@ export function startServer(options: ServerOptions = {}) {const httpPort = options.httpPort ?? 7600const wsPort = options.wsPort ?? 7601const enableEval = options.enableEval ?? false+ const mcpRoot = options.mcpRoot ?? nullconst authToken = options.authToken ?? nullconst corsOrigin = options.corsOrigin ?? null@@ -360,7 +447,7 @@ export function startServer(options: ServerOptions = {}) {function createMCPSession(id: string): MCPTransport {const mcpServer = new McpServer({ name: 'open-pencil', version: MCP_VERSION })- registerTools(mcpServer, { enableEval, sendRpc: sendToBrowser })+ registerTools(mcpServer, { enableEval, mcpRoot, sendRpc: sendToBrowser })const transport = new WebStandardStreamableHTTPServerTransport({sessionIdGenerator: () => iddiff --git a/packages/mcp/src/stdio.ts b/packages/mcp/src/stdio.tsindex 563a9bcc8..929261ed4 100644--- a/packages/mcp/src/stdio.ts+++ b/packages/mcp/src/stdio.ts@@ -8,6 +8,7 @@ import { MCP_VERSION, registerTools } from './server.js'const wsPort = parseInt(process.env.WS_PORT ?? '7601', 10)const wsHost = process.env.HOST ?? '127.0.0.1'const enableEval = process.env.OPENPENCIL_MCP_EVAL === '1'+const mcpRoot = process.env.OPENPENCIL_MCP_ROOT?.trim() || process.cwd()const wsUrl = `ws://${wsHost}:${wsPort}`let ws: WebSocket | null = null@@ -77,7 +78,14 @@ function connect() {function sendRpc(body: Record<string, unknown>): Promise<unknown> {return new Promise((resolve, reject) => {if (!ws || ws.readyState !== WebSocket.OPEN || !registered) {- reject(new Error('OpenPencil app is not connected. Start the app and open a document.'))+ reject(+ new Error(+ 'OpenPencil app is not connected. ' ++ 'STOP and tell the user: "The OpenPencil desktop app is not running or no document is open. ' ++ 'Please start the app and open a document, then try again." ' ++ 'Do NOT attempt to start the app yourself or retry automatically.'+ )+ )return}const id = crypto.randomUUID()@@ -93,7 +101,7 @@ function sendRpc(body: Record<string, unknown>): Promise<unknown> {connect()const mcpServer = new McpServer({ name: 'open-pencil', version: MCP_VERSION })-registerTools(mcpServer, { enableEval, sendRpc })+registerTools(mcpServer, { enableEval, mcpRoot, sendRpc })const transport = new StdioServerTransport()void mcpServer.connect(transport)diff --git a/src/automation/server.ts b/src/automation/server.tsindex 4eb788ca7..51434346a 100644--- a/src/automation/server.ts+++ b/src/automation/server.ts@@ -1,4 +1,6 @@import { makeFigmaFromStore } from '@/automation/figma-factory'+import { openFileFromPath } from '@/composables/use-menu'+import { createTab, openFileInNewTab } from '@/stores/tabs'/*** Browser-side automation handler.*@@ -8,6 +10,7 @@ import { makeFigmaFromStore } from '@/automation/figma-factory'import {ALL_TOOLS,AUTOMATION_WS_PORT,+ IS_TAURI,executeRpcCommand,renderTreeNode,computeAllLayouts,@@ -126,6 +129,37 @@ export function connectAutomation(getStore: () => EditorStore, authToken: stringreturn { ok: true }}+ async function handleNewDocument(_store: EditorStore, args: unknown): Promise<unknown> {+ const path = (args as { path?: string }).path+ const tab = createTab()+ if (path) {+ tab.store.setPlannedFilePath(path)+ if (IS_TAURI) {+ const { mkdir } = await import('@tauri-apps/plugin-fs')+ const dir = path.replace(/[\\/][^\\/]+$/, '')+ await mkdir(dir, { recursive: true })+ }+ await tab.store.saveFigFile()+ tab.store.startWatchingCurrentFile()+ }+ return { ok: true }+ }++ async function handleOpenFile(_store: EditorStore, args: unknown): Promise<unknown> {+ const path = (args as { path?: string }).path+ if (!path) throw new Error('Missing "path" in args')+ if (IS_TAURI) {+ await openFileFromPath(path)+ } else {+ const response = await fetch(path)+ if (!response.ok) throw new Error(`Failed to fetch file: ${response.statusText}`)+ const name = path.split(/[\\/]/).pop() ?? 'file.fig'+ const file = new File([await response.blob()], name)+ await openFileInNewTab(file, undefined, path)+ }+ return { ok: true }+ }+async function handleSelection(store: EditorStore): Promise<unknown> {const ids = [...store.state.selectedIds]const nodes = ids@@ -151,7 +185,9 @@ export function connectAutomation(getStore: () => EditorStore, authToken: stringexport_jsx: handleExportJsx,selection: handleSelection,- save_file: handleSaveFile+ save_file: handleSaveFile,+ new_document: handleNewDocument,+ open_file: handleOpenFile}async function handleRequest(_id: string, command: string, args: unknown): Promise<unknown> {diff --git a/src/composables/use-menu.ts b/src/composables/use-menu.tsindex 1210f14e6..17b0c749f 100644--- a/src/composables/use-menu.ts+++ b/src/composables/use-menu.ts@@ -23,18 +23,23 @@ if (IS_BROWSER) {}}+export async function openFileFromPath(path: string) {+ if (!IS_TAURI) return+ const { readFile } = await import('@tauri-apps/plugin-fs')+ const bytes = await readFile(path)+ const file = new File([bytes], path.split('/').pop() ?? 'file.fig')+ await openFileInNewTab(file, undefined, path)+}+export async function openFileDialog() {if (IS_TAURI) {const { open } = await import('@tauri-apps/plugin-dialog')- const { readFile } = await import('@tauri-apps/plugin-fs')const path = await open({filters: [{ name: 'Design file', extensions: ['fig', 'pen'] }],multiple: false})if (!path) return- const bytes = await readFile(path)- const file = new File([bytes], path.split('/').pop() ?? 'file.fig')- await openFileInNewTab(file, undefined, path)+ await openFileFromPath(path)return}diff --git a/src/stores/editor.ts b/src/stores/editor.tsindex 2aaf392c0..6bc907cbc 100644--- a/src/stores/editor.ts+++ b/src/stores/editor.ts@@ -869,6 +869,18 @@ export function createEditorStore(initialGraph?: SceneGraph) {}}+ function setPlannedFilePath(path: string) {+ stopWatchingFile()+ fileHandle = null+ filePath = path+ downloadName = path.split(/[\\/]/).pop() ?? 'Untitled.fig'+ state.documentName = downloadName.replace(/\.fig$/i, '')+ }++ function startWatchingCurrentFile() {+ void startWatchingFile()+ }+function dispose() {stopWatchingFile();(debouncedAutosave as typeof debouncedAutosave & { cancel?: () => void }).cancel?.()@@ -1256,6 +1268,8 @@ export function createEditorStore(initialGraph?: SceneGraph) {saveFigFile,saveFigFileAs,setDocumentSource,+ setPlannedFilePath,+ startWatchingCurrentFile,dispose,renderExportImage,listSelectionExportFormats,