AI-native design editor. Open-source Figma alternative.
fix: keep MCP path data off disk, and open and save file paths from the browser app (#1340)
Danila Poyarkov8aeaf697cf24
diff --git a/changes/1340/fixed.md b/changes/1340/fixed.mdnew file mode 100644index 000000000..9a6e5dbda--- /dev/null+++ b/changes/1340/fixed.md@@ -0,0 +1,3 @@+- MCP tools whose `path` is their own data, such as `create_vector` and `path_set`, no longer fail on long paths or create folders, and `export_pdf` writes the file its `path` names.+- MCP `open_file`, `save_file`, and `new_document` work with paths in the browser app: files are read from and copies saved to the MCP root through the server.+- A document opened from a link whose name has spaces or non-Latin letters keeps its name instead of showing it percent-encoded.diff --git a/packages/docs/programmable/mcp-server.md b/packages/docs/programmable/mcp-server.mdindex 484aff2da..043d77d87 100644--- a/packages/docs/programmable/mcp-server.md+++ b/packages/docs/programmable/mcp-server.md@@ -136,6 +136,7 @@ Security defaults:- Authentication is enabled by default with a generated token stored in the private discovery file.- `eval` is disabled.- File operations are limited to `OPENPENCIL_MCP_ROOT` (defaults to the current working directory) and reject symlink escapes.+- The browser app reaches those files through the server: `open_file` reads one, and `save_file` or `new_document` with a path writes a copy, so a document opened in the browser keeps saving where it did before.- Only the desktop app's own origin (`tauri://localhost` and its `http(s)://tauri.localhost` variants) is allowed by default, so a server you start yourself works from the app without extra configuration. Set `OPENPENCIL_MCP_CORS_ORIGIN` to a comma-separated list to allow other origins, such as a worktree dev server.Set `PORT=0` to disable TCP on macOS and Linux. Windows requires TCP. Set `OPENPENCIL_MCP_SOCKET` to override the Unix socket path, or `OPENPENCIL_MCP_DISCOVERY_PATH` to override the discovery file location. To provide a stable token, set `OPENPENCIL_MCP_AUTH_TOKEN`; an explicitly empty value disables authentication and should only be used with a trusted local socket.diff --git a/packages/mcp/src/http-options.ts b/packages/mcp/src/http-options.tsindex 9542c8f66..1ead89986 100644--- a/packages/mcp/src/http-options.ts+++ b/packages/mcp/src/http-options.ts@@ -1,4 +1,4 @@-export const MCP_CORS_METHODS = ['GET', 'POST', 'DELETE', 'OPTIONS']+export const MCP_CORS_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']// x-mcp-token: OpenPencil extension for MCP clients that cannot set the// Authorization header (e.g. some IDE plugins). Not part of the MCP spec.diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.tsindex 4253c334a..06ed63892 100644--- a/packages/mcp/src/server.ts+++ b/packages/mcp/src/server.ts@@ -1,8 +1,9 @@import { randomBytes } from 'node:crypto'import type { Server as HttpServer } from 'node:http'+import { resolve } from 'node:path'import type { McpServer } from '@modelcontextprotocol/server'-import { Hono } from 'hono'+import { Hono, type Context, type Next } from 'hono'import { cors } from 'hono/cors'import { resolveCommand } from 'package-manager-detector/commands'import { detect, getUserAgent } from 'package-manager-detector/detect'@@ -14,6 +15,7 @@ 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 { registerFileRoutes } from '#mcp/server/files'import { createMCPSessionManager } from '#mcp/server/sessions'import { createToolDescriptors } from '#mcp/tool/manifest'import type { ToolDescriptor, ToolPolicy } from '#mcp/tool/metadata'@@ -133,16 +135,19 @@ export interface ServerHandle {close: () => Promise<void>}-/** Set up Hono routes: /health, /rpc, /mcp */+/** Set up Hono routes: /health, /rpc, /files, /mcp */function createHonoApp(options: {authToken: string | nullcorsOrigin: string | readonly string[] | null+ /** The root `/files` reads and writes inside, or null to leave the route out. */+ fileRoot: string | nullbrowserRPC: ReturnType<typeof createBrowserRPCBridge>mcpSessions: ReturnType<typeof createMCPSessionManager>sendToBrowser: (msg: RPCJSONObject) => Promise<unknown>toolDescriptors: ToolDescriptor[]}): Hono {- const { authToken, corsOrigin, browserRPC, mcpSessions, sendToBrowser, toolDescriptors } = options+ const { authToken, corsOrigin, fileRoot, browserRPC, mcpSessions, sendToBrowser } = options+ const { toolDescriptors } = optionsconst app = new Hono()@@ -170,7 +175,7 @@ function createHonoApp(options: {})})- app.use('/rpc', async (c, next) => {+ const requireToken = async (c: Context, next: Next) => {// When authToken is null (operator explicitly disabled auth), skip token check —// the Unix socket or localhost TCP already restricts access to local processes.if (authToken !== null) {@@ -180,7 +185,14 @@ function createHonoApp(options: {}}return next()- })+ }++ app.use('/rpc', requireToken)++ if (fileRoot !== null) {+ app.use('/files/*', requireToken)+ registerFileRoutes(app, fileRoot)+ }// Historical note: before the isConnected() guard was removed, a disconnected// app returned 503 here. Now errors from sendToBrowser surface as 502. This@@ -364,6 +376,8 @@ function buildServerContext(options: ServerOptions) {const app = createHonoApp({authToken,corsOrigin,+ // A client limited to the selection reaches no files, as the file tools are left out then.+ fileRoot: mcpRoot !== null && toolPolicy.scope !== 'selection' ? resolve(mcpRoot) : null,browserRPC,mcpSessions,sendToBrowser,diff --git a/packages/mcp/src/server/files.ts b/packages/mcp/src/server/files.tsnew file mode 100644index 000000000..7cc1f9d17--- /dev/null+++ b/packages/mcp/src/server/files.ts@@ -0,0 +1,49 @@+import type { Context, Hono } from 'hono'+import { bodyLimit } from 'hono/body-limit'++import { MAX_FILE_TRANSFER_BYTES, readInsideRoot, writeInsideRoot } from '#mcp/tool/output'++/**+ * The path after `/files/`, one encoded segment per folder, so the URL ends in the file's name.+ * Empty segments keep a POSIX root (`/files//Users/…`) and a Windows share (`/files///server/…`).+ * Decoded from the raw URL, since the router's path is already partly decoded.+ */+function filePath(c: Context): string {+ const pathname = new URL(c.req.url).pathname+ return pathname.slice('/files/'.length).split('/').map(decodeURIComponent).join('/')+}++function failure(c: Context, e: unknown) {+ return c.json({ error: e instanceof Error ? e.message : String(e) }, 400)+}++/**+ * A browser app cannot reach the paths the file tools name, so it reads and writes them through+ * `/files/`, inside the same root the tools resolve them in. The caller guards the route with the+ * server's token.+ */+export function registerFileRoutes(app: Hono, root: string): void {+ app.get('/files/*', async (c) => {+ try {+ const bytes = await readInsideRoot(filePath(c), root)+ return c.body(bytes, 200, { 'content-type': 'application/octet-stream' })+ } catch (e) {+ return failure(c, e)+ }+ })+ app.put(+ '/files/*',+ bodyLimit({+ maxSize: MAX_FILE_TRANSFER_BYTES,+ onError: (c) => c.json({ error: 'File is too large' }, 413)+ }),+ async (c) => {+ try {+ const bytes = new Uint8Array(await c.req.arrayBuffer())+ return c.json(await writeInsideRoot(filePath(c), root, bytes))+ } catch (e) {+ return failure(c, e)+ }+ }+ )+}diff --git a/packages/mcp/src/tool/output.ts b/packages/mcp/src/tool/output.tsindex 2a3ed3a89..046cb6c4a 100644--- a/packages/mcp/src/tool/output.ts+++ b/packages/mcp/src/tool/output.ts@@ -1,4 +1,13 @@-import { lstat, mkdir, readlink, realpath, writeFile } from 'node:fs/promises'+import { constants } from 'node:fs'+import {+ lstat,+ mkdir,+ open,+ readlink,+ realpath,+ writeFile,+ type FileHandle+} from 'node:fs/promises'import { dirname, basename, isAbsolute, join, parse, resolve, sep as osSep } from 'node:path'import { compact } from 'es-toolkit/array'@@ -216,12 +225,35 @@ export async function resolveSafePath(filePath: string, root: string): Promise<Sreturn resolveSafePathInternal(filePath, root, 0)}-export async function writeToolOutput(- toolName: string,- result: Record<string, unknown>,+/**+ * The tools whose `path` names a file to write their result to, and the bytes each writes. Other+ * tools' `path` is their own data, such as `create_vector`'s SVG path, and never touches disk.+ */+const FILE_OUTPUTS: Record<+ string,+ (result: Record<string, unknown>) => string | Uint8Array | null+> = {+ export_svg: (result) => (typeof result.svg === 'string' ? result.svg : null),+ get_jsx: (result) => (typeof result.jsx === 'string' ? result.jsx : null),+ export_image: (result) =>+ typeof result.base64 === 'string' ? toUint8Array(result.base64) : null,+ export_pdf: (result) => (typeof result.base64 === 'string' ? toUint8Array(result.base64) : null)+}++/** Whether a tool's `path` argument names a file it writes, rather than data of its own. */+export function writesFileOutput(toolName: string): boolean {+ return toolName in FILE_OUTPUTS+}++/** The largest document `/files` passes either way, as the app caps documents it fetches. */+export const MAX_FILE_TRANSFER_BYTES = 64 * 1024 * 1024++/** Write `content` to a path inside `root`, creating its folders, and return where it landed. */+export async function writeInsideRoot(filePath: string,- root: string-): Promise<MCPResult | null> {+ root: string,+ content: string | Uint8Array+): Promise<{ written: string; byteLength: number }> {const { resolved, realPath } = await resolveSafePath(filePath, root)// Use the canonical realPath for filesystem operations to prevent TOCTOU:// an attacker could swap a directory component with a symlink between@@ -234,21 +266,71 @@ export async function writeToolOutput(// with a symlink between resolveSafePath and the write would be detected// here — realpath follows the ancestor symlink and resolves outside root.await resolveSafePath(parentDir, root)- if (toolName === 'export_svg' && typeof result.svg === 'string') {- await writeFile(realPath, result.svg, 'utf8')- await resolveSafePath(realPath, root)- return ok({ written: resolved, byteLength: Buffer.byteLength(result.svg, 'utf8') })+ await writeFile(realPath, content)+ await resolveSafePath(realPath, root)+ const byteLength =+ typeof content === 'string' ? Buffer.byteLength(content, 'utf8') : content.byteLength+ return { written: resolved, byteLength }+}++const READ_CHUNK_BYTES = 1024 * 1024++/**+ * Read an open file to its end in chunks, refusing it as soon as it passes the cap, so a file+ * that grows while it is read is never buffered whole.+ */+async function readBounded(handle: FileHandle, name: string): Promise<Uint8Array<ArrayBuffer>> {+ const chunks: Uint8Array[] = []+ let total = 0+ for (;;) {+ const chunk = new Uint8Array(READ_CHUNK_BYTES)+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, total)+ if (bytesRead === 0) break+ total += bytesRead+ if (total > MAX_FILE_TRANSFER_BYTES) {+ throw new Error(`"${name}" is larger than ${MAX_FILE_TRANSFER_BYTES} bytes`)+ }+ chunks.push(chunk.subarray(0, bytesRead))}- if (toolName === 'export_image' && typeof result.base64 === 'string') {- const bytes = toUint8Array(result.base64)- await writeFile(realPath, bytes)- await resolveSafePath(realPath, root)- return ok({ written: resolved, byteLength: bytes.length })+ const bytes = new Uint8Array(total)+ let offset = 0+ for (const chunk of chunks) {+ bytes.set(chunk, offset)+ offset += chunk.length}- if (toolName === 'get_jsx' && typeof result.jsx === 'string') {- await writeFile(realPath, result.jsx, 'utf8')+ return bytes+}++/** Read a file inside `root`, refusing one larger than `MAX_FILE_TRANSFER_BYTES`. */+export async function readInsideRoot(+ filePath: string,+ root: string+): Promise<Uint8Array<ArrayBuffer>> {+ const { realPath } = await resolveSafePath(filePath, root)+ // One descriptor for the checks and the read, so the file cannot be swapped between them; a+ // symlink in its place is refused, and a folder swapped above it is caught by the re-check.+ // Windows has no O_NOFOLLOW (it is undefined there), so only the re-check guards it.+ const handle = await open(realPath, constants.O_RDONLY | constants.O_NOFOLLOW)+ try {+ const stats = await handle.stat()+ if (!stats.isFile()) throw new Error(`"${basename(realPath)}" is not a file`)+ if (stats.size > MAX_FILE_TRANSFER_BYTES) {+ throw new Error(`"${basename(realPath)}" is larger than ${MAX_FILE_TRANSFER_BYTES} bytes`)+ }await resolveSafePath(realPath, root)- return ok({ written: resolved, byteLength: Buffer.byteLength(result.jsx, 'utf8') })+ return await readBounded(handle, basename(realPath))+ } finally {+ await handle.close()}- return null+}++export async function writeToolOutput(+ toolName: string,+ result: Record<string, unknown>,+ filePath: string,+ root: string+): Promise<MCPResult | null> {+ const content = FILE_OUTPUTS[toolName]?.(result)+ if (content == null) return null+ return ok(await writeInsideRoot(filePath, root, content))}diff --git a/packages/mcp/src/tool/registration.ts b/packages/mcp/src/tool/registration.tsindex 0148a9828..e6a603d3a 100644--- a/packages/mcp/src/tool/registration.ts+++ b/packages/mcp/src/tool/registration.ts@@ -17,7 +17,7 @@ import type { RPCJSONObject } from '#mcp/json'import { MAX_RESULT_BYTES, fail, ok, resultTooLargeMessage } from '#mcp/result'import { createToolDescriptors, getMCPToolDefinitions } from '#mcp/tool/manifest'import type { ToolDescriptor, ToolEffect, ToolPolicy } from '#mcp/tool/metadata'-import { resolveSafePath, writeToolOutput } from '#mcp/tool/output'+import { resolveSafePath, writeToolOutput, writesFileOutput } from '#mcp/tool/output'import { isToolEnabled } from '#mcp/tool/policy'import { SELECTION_SCOPE_FILE_OUTPUT_ERROR } from '#mcp/tool/scope'@@ -144,7 +144,9 @@ export function registerTools(mcpServer: McpServer, options: RegisterToolsOptionasync (args: Record<string, unknown>) => {try {const { target, args: toolArgs } = splitAutomationTarget(args)- if (policy.scope === 'selection' && toolArgs.path !== undefined) {+ const filePath =+ writesFileOutput(def.name) && typeof toolArgs.path === 'string' ? toolArgs.path : null+ if (policy.scope === 'selection' && filePath !== null) {return fail(new Error(SELECTION_SCOPE_FILE_OUTPUT_ERROR))}const result = await sendRPC({@@ -161,12 +163,17 @@ 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 RPCJSONObject | undefined- const filePath = typeof toolArgs.path === 'string' ? toolArgs.path : nullif (r && filePath && resolvedRoot) {const written = await writeToolOutput(def.name, r, filePath, resolvedRoot)if (written) return written}- if (r && 'base64' in r && 'mimeType' in r) {+ // Only an image goes back as one; a PDF stays base64 in the JSON result, as described.+ if (+ r &&+ 'base64' in r &&+ typeof r.mimeType === 'string' &&+ r.mimeType.startsWith('image/')+ ) {const base64 = String(r.base64)const bytes = Buffer.byteLength(base64, 'utf8')if (bytes > MAX_RESULT_BYTES) {@@ -185,7 +192,7 @@ export function registerTools(mcpServer: McpServer, options: RegisterToolsOption{type: 'image' as const,data: base64,- mimeType: r.mimeType as string+ mimeType: r.mimeType}]}diff --git a/packages/mcp/tests/tool/registration.test.ts b/packages/mcp/tests/tool/registration.test.tsnew file mode 100644index 000000000..ac3bedb2a--- /dev/null+++ b/packages/mcp/tests/tool/registration.test.ts@@ -0,0 +1,115 @@+import { afterEach, describe, expect, test } from 'bun:test'+import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { fromUint8Array } from 'js-base64'++import { createMCPSessionManager } from '#mcp/server/sessions'+import { registerTools } from '#mcp/tool/registration'++const cleanups: (() => Promise<void>)[] = []+afterEach(async () => {+ await Promise.all(cleanups.splice(0).map((cleanup) => cleanup()))+})++function request(body: unknown, sessionId?: string) {+ return new Request('http://localhost/mcp', {+ method: 'POST',+ headers: {+ accept: 'application/json, text/event-stream',+ 'content-type': 'application/json',+ ...(sessionId ? { 'mcp-session-id': sessionId } : {})+ },+ body: JSON.stringify(body)+ })+}++interface ToolResult {+ isError?: boolean+ content: { type: string; text?: string }[]+}++/** An MCP server over a fresh root whose app answers each tool with `results[name]`. */+async function server(results: Record<string, unknown>) {+ const root = await mkdtemp(join(tmpdir(), 'op-mcp-root-'))+ const manager = createMCPSessionManager({+ serverVersion: '0.0.0',+ registerTools: (mcpServer, agentSession, onToolSettled) =>+ registerTools(mcpServer, {+ policy: { allowEval: false, disabledTools: [], scope: 'document' },+ agentSession,+ onToolSettled,+ mcpRoot: root,+ sendRPC: async (body) => {+ const { args } = body as { args: { name: string } }+ return { ok: true, result: results[args.name] }+ }+ })+ })+ cleanups.push(async () => {+ await manager.clear()+ await rm(root, { recursive: true, force: true })+ })+ const connection = await manager.resolveTransport(undefined)+ if ('error' in connection) throw new Error(connection.error)+ const init = await connection.handleRequest(+ request({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: {+ protocolVersion: '2025-06-18',+ capabilities: {},+ clientInfo: { name: 'test', version: '1' }+ }+ })+ )+ const sessionId = init.headers.get('mcp-session-id') ?? undefined+ let id = 1+ const call = async (name: string, args: Record<string, unknown>): Promise<ToolResult> => {+ const response = await connection.handleRequest(+ request(+ { jsonrpc: '2.0', id: ++id, method: 'tools/call', params: { name, arguments: args } },+ sessionId+ )+ )+ const text = await response.text()+ const json = text.startsWith('{') ? text : (text.split('data: ')[1] ?? '')+ const message: unknown = JSON.parse(json)+ return (message as { result: ToolResult }).result+ }+ return { root, call }+}++const zigzag = `M0 0${Array.from({ length: 64 }, (_, i) => ` L${(i + 1) * 3} ${(i % 2) * 20}`).join('')}`+const node = { id: '0:1', name: 'Vector', type: 'VECTOR' }++describe('MCP tool file output', () => {+ test("a tool's own path data is never taken for a file", async () => {+ const { root, call } = await server({ create_vector: node, path_set: node })+ const created = await call('create_vector', { x: 0, y: 0, path: zigzag })+ expect(created.isError).toBeFalsy()+ expect(created.content[0].text).toContain('"VECTOR"')+ const network = JSON.stringify({+ vertices: Array.from({ length: 40 }, (_, i) => ({ x: i, y: i % 2 })),+ segments: Array.from({ length: 39 }, (_, i) => ({ start: i, end: i + 1 }))+ })+ expect((await call('path_set', { id: '0:1', path: network })).isError).toBeFalsy()+ expect(await readdir(root)).toEqual([])+ })++ test('export_pdf writes its file, and without a path returns base64 text', async () => {+ const pdf = new TextEncoder().encode('%PDF-1.3 test')+ const result = { mimeType: 'application/pdf', base64: fromUint8Array(pdf), byteLength: 13 }+ const { root, call } = await server({ export_pdf: result })++ const written = await call('export_pdf', { path: 'out/doc.pdf' })+ expect(written.isError).toBeFalsy()+ expect(new Uint8Array(await readFile(join(root, 'out/doc.pdf')))).toEqual(pdf)++ const inline = await call('export_pdf', {})+ expect(inline.content[0].type).toBe('text')+ expect(inline.content[0].text).toContain(result.base64)+ })+})diff --git a/src/app/automation/bridge/file-handlers.ts b/src/app/automation/bridge/file-handlers.tsindex eba2951a3..c84b49429 100644--- a/src/app/automation/bridge/file-handlers.ts+++ b/src/app/automation/bridge/file-handlers.ts@@ -13,6 +13,12 @@ import { openFileFromPath } from '@/app/shell/menu/use'import { closeTab, createTab, getActiveStore, getTabById } from '@/app/tabs'import { isTauri } from '@/app/tauri/env'+/** Where a browser app reads and writes the paths the file tools name: the MCP server's `/files/`. */+export interface AutomationFiles {+ url: (path: string) => URL+ headers: Record<string, string>+}+const saveArgsSchema = v.object({ path: v.optional(v.string()) })const closeArgsSchema = v.object({@@ -20,24 +26,6 @@ const closeArgsSchema = v.object({unsaved: v.optional(v.picklist(['error', 'save', 'discard']), 'error')})-// Automation never opens the Save dialog: nobody may be there to answer it.-async function saveWithoutPrompt(store: AutomationTarget['store'], path?: string): Promise<void> {- const name = store.state.documentName- if (!path && !store.hasWritableSource()) {- throw new Error(`"${name}" has not been saved to a file yet; pass a path to save it`)- }- if (path) await ensureTauriParentDirectory(path)- // A failed save to a new path leaves the document with the source it had.- const saved = path ? await store.saveFigFileToPath(path) : await store.saveFigFile()- if (!saved) throw new Error(`Could not save "${name}"`)-}--export async function handleSaveFile(target: AutomationTarget, args: unknown): Promise<unknown> {- const { path } = parseToolArgs('save_file', saveArgsSchema, args)- await saveWithoutPrompt(target.store, path)- return { ok: true, result: { saved: true } }-}-export async function ensureTauriParentDirectory(path: string): Promise<void> {if (!isTauri()) returnconst [{ dirname }, { mkdir }] = await Promise.all([@@ -49,50 +37,96 @@ export async function ensureTauriParentDirectory(path: string): Promise<void> {await mkdir(dir, { recursive: true })}-export async function handleCloseFile(target: AutomationTarget, args: unknown): Promise<unknown> {- const { path, unsaved } = parseToolArgs('close_file', closeArgsSchema, args)- const store = target.store- if (store.hasUnsavedChanges()) {- if (unsaved === 'error') {- throw new Error(- `"${store.state.documentName}" has unsaved changes. ` +- 'Save or discard them: CLI --save or --discard, MCP unsaved "save" or "discard"'- )+/**+ * The file commands. `files` is the MCP server a browser app reads and writes paths through;+ * without one, as in-process on the landing page, a browser path is a URL beside the page.+ */+export function createFileHandlers(files?: AutomationFiles) {+ /**+ * A browser cannot write the path, so the MCP server writes a copy there, and the document+ * counts as saved as after a download.+ */+ async function writeThroughServer(+ server: AutomationFiles,+ path: string,+ data: Uint8Array+ ): Promise<void> {+ const response = await fetch(server.url(path), {+ method: 'PUT',+ headers: { ...server.headers, 'content-type': 'application/octet-stream' },+ body: new Uint8Array(data)+ })+ if (!response.ok) throw new Error(`Could not write ${path}: ${await response.text()}`)+ }++ // Automation never opens the Save dialog: nobody may be there to answer it.+ async function saveWithoutPrompt(store: AutomationTarget['store'], path?: string): Promise<void> {+ const name = store.state.documentName+ if (!path && !store.hasWritableSource()) {+ throw new Error(`"${name}" has not been saved to a file yet; pass a path to save it`)+ }+ if (path && files && !isTauri()) {+ await store.saveFigFileCopy((data) => writeThroughServer(files, path, data))+ return}- if (unsaved === 'save') await saveWithoutPrompt(store, path)+ if (path) await ensureTauriParentDirectory(path)+ // A failed save to a new path leaves the document with the source it had.+ const saved = path ? await store.saveFigFileToPath(path) : await store.saveFigFile()+ if (!saved) throw new Error(`Could not save "${name}"`)+ }++ async function handleSaveFile(target: AutomationTarget, args: unknown): Promise<unknown> {+ const { path } = parseToolArgs('save_file', saveArgsSchema, args)+ await saveWithoutPrompt(target.store, path)+ return { ok: true, result: { saved: true } }}- await closeTab(target.documentId, unsaved === 'discard' ? 'discard' : 'save')- return { ok: true, result: { closed: getTabById(target.documentId) === undefined } }-}-export async function handleNewDocument(- _target: AutomationTarget,- args: unknown-): Promise<unknown> {- const { path } = parseToolArgs('new_document', saveArgsSchema, args)- const tab = createTab()- if (path) {- try {- await saveWithoutPrompt(tab.store, path)- } catch (error) {- await closeTab(tab.id, 'discard')- throw error+ async function handleCloseFile(target: AutomationTarget, args: unknown): Promise<unknown> {+ const { path, unsaved } = parseToolArgs('close_file', closeArgsSchema, args)+ const store = target.store+ if (store.hasUnsavedChanges()) {+ if (unsaved === 'error') {+ throw new Error(+ `"${store.state.documentName}" has unsaved changes. ` ++ 'Save or discard them: CLI --save or --discard, MCP unsaved "save" or "discard"'+ )+ }+ if (unsaved === 'save') await saveWithoutPrompt(store, path)}+ await closeTab(target.documentId, unsaved === 'discard' ? 'discard' : 'save')+ return { ok: true, result: { closed: getTabById(target.documentId) === undefined } }}- const target = resolveAutomationTarget(tab.store, { document_id: tab.id })- return responseWithTarget({ ok: true, result: { created: true } }, target)-}-export async function handleOpenFile(_target: AutomationTarget, args: unknown): Promise<unknown> {- const path = (args as { path?: string }).path- if (!path) throw new Error('Missing "path" in args')- if (isTauri()) {- await openFileFromPath(path)- } else {- // Same fetch, cap and format check as every other browser open: an automation client- // is not more trusted than a link.- await openBrowserFileFromURL(resolveBrowserFileURL(path))+ async function handleNewDocument(_target: AutomationTarget, args: unknown): Promise<unknown> {+ const { path } = parseToolArgs('new_document', saveArgsSchema, args)+ const tab = createTab()+ if (path) {+ try {+ await saveWithoutPrompt(tab.store, path)+ } catch (error) {+ await closeTab(tab.id, 'discard')+ throw error+ }+ }+ const target = resolveAutomationTarget(tab.store, { document_id: tab.id })+ return responseWithTarget({ ok: true, result: { created: true } }, target)}- const target = resolveAutomationTarget(getActiveStore(), undefined)- return responseWithTarget({ ok: true, result: { opened: true } }, target)++ async function handleOpenFile(_target: AutomationTarget, args: unknown): Promise<unknown> {+ const path = (args as { path?: string }).path+ if (!path) throw new Error('Missing "path" in args')+ if (isTauri()) {+ await openFileFromPath(path)+ } else if (files) {+ // The browser cannot read the path, so it fetches it from the MCP server, with the same+ // cap and format check as every other browser open.+ await openBrowserFileFromURL(files.url(path), { headers: files.headers })+ } else {+ await openBrowserFileFromURL(resolveBrowserFileURL(path))+ }+ const target = resolveAutomationTarget(getActiveStore(), undefined)+ return responseWithTarget({ ok: true, result: { opened: true } }, target)+ }++ return { handleSaveFile, handleCloseFile, handleNewDocument, handleOpenFile }}diff --git a/src/app/automation/bridge/handlers.ts b/src/app/automation/bridge/handlers.tsindex f987efebe..51f9a3cd0 100644--- a/src/app/automation/bridge/handlers.ts+++ b/src/app/automation/bridge/handlers.ts@@ -11,12 +11,7 @@ import {} from '@/app/automation/bridge/app-handlers'import { createAutomationEvalHandler } from '@/app/automation/bridge/eval-handler'import { handleExport, handleExportJSX } from '@/app/automation/bridge/export-handlers'-import {- handleCloseFile,- handleNewDocument,- handleOpenFile,- handleSaveFile-} from '@/app/automation/bridge/file-handlers'+import { createFileHandlers, type AutomationFiles } from '@/app/automation/bridge/file-handlers'import { handleRPCFallback } from '@/app/automation/bridge/rpc-handler'import { handleSelection } from '@/app/automation/bridge/selection-handler'import {@@ -35,9 +30,11 @@ type FigmaFactory = (store: EditorStore, pageId?: string) => FigmaAPItype CommandHandler = (target: AutomationTarget, args: unknown) => Promise<unknown>-export function createAutomationCommandHandlers(makeFigma: FigmaFactory) {+export function createAutomationCommandHandlers(makeFigma: FigmaFactory, files?: AutomationFiles) {const handleEval = createAutomationEvalHandler(makeFigma)const handleTool = createAutomationToolHandler(makeFigma)+ const { handleSaveFile, handleCloseFile, handleNewDocument, handleOpenFile } =+ createFileHandlers(files)const commandHandlers: Partial<Record<string, CommandHandler>> = {eval: handleEval,diff --git a/src/app/automation/bridge/server.ts b/src/app/automation/bridge/server.tsindex 831c22b7f..1e8f14374 100644--- a/src/app/automation/bridge/server.ts+++ b/src/app/automation/bridge/server.ts@@ -10,6 +10,7 @@ import { randomHex } from '@open-pencil/scene-graph/random'import { endAgentSession, readAgentSession } from '@/app/automation/agents'import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'+import type { AutomationFiles } from '@/app/automation/bridge/file-handlers'import { createAutomationCommandHandlers } from '@/app/automation/bridge/handlers'import { isUnknownRecord } from '@/app/automation/bridge/target'import type { EditorStore } from '@/app/editor/active-store'@@ -33,6 +34,19 @@ const AutomationRequestJSON = v.pipe(*/const sessionSockets = new Map<string, Set<WebSocket>>()+/**+ * The MCP server's `/files/`, beside the socket the app connects to, where a browser app reads and+ * writes the paths the file tools name. Each folder is one URL segment, so the URL ends in the+ * file's own name; a leading separator stays as an empty segment, as in a Windows share's `\\`.+ */+export function automationFiles(automationURL: string, token: string): AutomationFiles {+ const base = new URL(automationURL.replace(/^ws/, 'http'))+ return {+ url: (path) => new URL(`/files/${path.split(/[\\/]/).map(encodeURIComponent).join('/')}`, base),+ headers: { authorization: `Bearer ${token}` }+ }+}+export function connectAutomation(getStore: () => EditorStore,authToken: string | null = null,@@ -43,8 +57,10 @@ export function connectAutomation(let reconnectTimer: ReturnType<typeof setTimeout> | undefinedlet intentionalDisconnect = false- const { handleRequest: handleAutomationRequest } =- createAutomationCommandHandlers(makeFigmaFromStore)+ const { handleRequest: handleAutomationRequest } = createAutomationCommandHandlers(+ makeFigmaFromStore,+ automationFiles(automationURL, token)+ )async function handleRequest(_id: string, command: string, args: unknown): Promise<unknown> {return handleAutomationRequest(getStore(), command, args)diff --git a/src/app/document/io/create.ts b/src/app/document/io/create.tsindex bed895dce..18fb1e16e 100644--- a/src/app/document/io/create.ts+++ b/src/app/document/io/create.ts@@ -85,6 +85,7 @@ export function createDocumentIOActions(setStorageDocumentSource: sourceActions.setStorageDocumentSource,setPlannedFilePath: sourceActions.setPlannedFilePath,saveFigFileToPath: sourceActions.saveFigFileToPath,+ saveFigFileCopy: sourceActions.saveFigFileCopy,saveFigFileToStorage: sourceActions.saveFigFileToStorage,startWatchingCurrentFile: sourceActions.startWatchingCurrentFile,disposeDocumentIO: sourceActions.disposeDocumentIO,diff --git a/src/app/document/io/source/actions.ts b/src/app/document/io/source/actions.tsindex 19fe6fb78..4281e3925 100644--- a/src/app/document/io/source/actions.ts+++ b/src/app/document/io/source/actions.ts@@ -217,6 +217,17 @@ export function createDocumentSourceActions({return saved}+ /**+ * Hand the document to `write`, such as an MCP server saving it to a path a browser cannot+ * reach, and count it saved as a download is. Where the document saves next does not change.+ */+ async function saveFigFileCopy(write: (data: Uint8Array) => Promise<void>): Promise<boolean> {+ const version = changes.capture()+ await write(await buildFigFile())+ await recovery.markProtectedVersion(version)+ return true+ }+/** Upload the document to storage as a new stored document and keep editing it there. */async function saveFigFileToStorage(location: StorageLocation): Promise<boolean> {const saved = await saveToNewTarget(() => {@@ -249,6 +260,8 @@ export function createDocumentSourceActions({setStorageDocumentSource,setPlannedFilePath,saveFigFileToPath,+ saveFigFileCopy: (write: (data: Uint8Array) => Promise<void>) =>+ saveAndTrack(() => saveFigFileCopy(write)),saveFigFileToStorage,startWatchingCurrentFile,disposeDocumentIO,diff --git a/src/app/editor/session/modules.ts b/src/app/editor/session/modules.tsindex 2c2a7084b..131e55adb 100644--- a/src/app/editor/session/modules.ts+++ b/src/app/editor/session/modules.ts@@ -100,6 +100,7 @@ export function createEditorStoreModules(setStorageDocumentSource: documentIO.setStorageDocumentSource,setPlannedFilePath: documentIO.setPlannedFilePath,saveFigFileToPath: documentIO.saveFigFileToPath,+ saveFigFileCopy: documentIO.saveFigFileCopy,saveFigFileToStorage: documentIO.saveFigFileToStorage,startWatchingCurrentFile: documentIO.startWatchingCurrentFile,designCheck,diff --git a/src/app/shell/menu/files.ts b/src/app/shell/menu/files.tsindex ace3757d5..8073bb050 100644--- a/src/app/shell/menu/files.ts+++ b/src/app/shell/menu/files.ts@@ -1,5 +1,6 @@import { useFileDialog } from '@vueuse/core'import { uniq } from 'es-toolkit/array'+import { decode } from 'ufo'import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'@@ -57,6 +58,14 @@ if (IS_BROWSER && 'window' in globalThis) {})}+/**+ * The file name a URL ends in, decoded, so `my%20design.fig` opens as "my design"; a malformed+ * escape stays as written.+ */+function fileNameFromURL(url: URL): string {+ return decode(url.pathname.split('/').pop() ?? '') || 'file.fig'+}+/** Fetches a document over HTTP and opens it in a new tab. Browser builds only. */export async function openBrowserFileFromURL(url: URL, init?: RequestInit): Promise<void> {// The cap needs a controller of its own, so a caller's signal is combined with it@@ -74,7 +83,7 @@ export async function openBrowserFileFromURL(url: URL, init?: RequestInit): Promif (bytes.byteLength === 0) {throw new Error('Failed to fetch file: the response carried no body')}- const name = url.pathname.split('/').pop() ?? 'file.fig'+ const name = fileNameFromURL(url)assertSupportedDesignFile(name)const file = new File([bytes], name, { type: 'application/octet-stream' })await openFileInNewTab(file, undefined, url.href)diff --git a/tests/app/automation/bridge/handlers.test.ts b/tests/app/automation/bridge/handlers.test.tsindex 643425db4..cb601c24a 100644--- a/tests/app/automation/bridge/handlers.test.ts+++ b/tests/app/automation/bridge/handlers.test.ts@@ -7,12 +7,14 @@ import * as layoutModule from '@open-pencil/core/layout'import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'import { createAutomationCommandHandlers } from '@/app/automation/bridge/handlers'+import { automationFiles } from '@/app/automation/bridge/server'import { recentDocuments } from '@/app/recent-files'import { recentFilesLimit } from '@/app/recent-files/preferences'import { appPreferences } from '@/app/settings/preferences/store'import { createTab, getActiveStore, getActiveTabId, getTabById, getTabsSnapshot } from '@/app/tabs'import { asDouble } from '#tests/helpers/doubles'+import { testPath } from '#tests/helpers/paths'function setupGlobals() {globalThis.window = asDouble<Window & typeof globalThis>({@@ -370,6 +372,56 @@ describe('close_file and save_file never prompt', () => {})})+describe('file paths in a browser go through the MCP server', () => {+ const { handleRequest: handleThroughServer } = createAutomationCommandHandlers(+ makeFigmaFromStore,+ automationFiles('ws://mcp.test', 'token')+ )+ const requestThroughServer = (command: string, args: Record<string, unknown>) =>+ handleThroughServer(getActiveStore(), command, args)++ function dirtyTab() {+ const tab = createTab()+ tab.store.createShape('RECTANGLE', 0, 0, 10, 10)+ return tab+ }++ test('saving to a path hands the server a copy, saved as a download is', async () => {+ const tab = dirtyTab()+ const fetch = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('{}'))+ await requestThroughServer('save_file', { document_id: tab.id, path: '/root/copy.fig' })++ const [url, init] = fetch.mock.calls[0]+ expect(String(url)).toBe('http://mcp.test/files//root/copy.fig')+ expect(init?.method).toBe('PUT')+ expect(new Headers(init?.headers).get('authorization')).toBe('Bearer token')+ expect(tab.store.hasUnsavedChanges()).toBe(false)+ // Where the document saves next does not change.+ expect(tab.store.hasWritableSource()).toBe(false)+ })++ test('a copy the server refuses leaves the changes unsaved', async () => {+ const tab = dirtyTab()+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('outside', { status: 400 }))+ await expect(+ requestThroughServer('save_file', { document_id: tab.id, path: '/elsewhere/copy.fig' })+ ).rejects.toThrow('Could not write /elsewhere/copy.fig: outside')+ expect(tab.store.hasUnsavedChanges()).toBe(true)+ })++ test('opening a path fetches it from the server with the token', async () => {+ const bytes = new Uint8Array(await Bun.file(testPath('fixtures', 'slots.fig')).arrayBuffer())+ const fetch = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(bytes))+ await settle(requestThroughServer('open_file', { path: '/root/my #1 slots.fig' }))++ const [url, init] = fetch.mock.calls[0]+ // A reserved character stays in the path rather than starting a fragment.+ expect(String(url)).toBe('http://mcp.test/files//root/my%20%231%20slots.fig')+ expect(new Headers(init?.headers).get('authorization')).toBe('Bearer token')+ expect(getActiveStore().state.documentName).toBe('my #1 slots')+ })+})+describe('list_recent_files', () => {let previousPreferences: typeof appPreferences.valuediff --git a/tests/engine/mcp/server/index.test.ts b/tests/engine/mcp/server/index.test.tsindex a85fc2c15..2e27f98f4 100644--- a/tests/engine/mcp/server/index.test.ts+++ b/tests/engine/mcp/server/index.test.ts@@ -1,7 +1,7 @@/* eslint-disable max-lines -- MCP server scenarios share lifecycle and transport fixtures */import { describe, expect, test, beforeEach, afterEach } from 'bun:test'-import { mkdir, stat } from 'node:fs/promises'+import { mkdir, readFile, stat } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'@@ -445,7 +445,7 @@ describe('raw RPC', () => {describe('MCP server with mcpRoot', () => {async function withMCPRootServer(mcpRoot: string | null,- fn: (client: Client, browser: MockBrowser, graph: SceneGraph) => Promise<void>+ fn: (client: Client, browser: MockBrowser, graph: SceneGraph, httpPort: number) => Promise<void>) {if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })if (mcpRoot) await mkdir(mcpRoot, { recursive: true })@@ -476,7 +476,7 @@ describe('MCP server with mcpRoot', () => {)await client.connect(transport)- await fn(client, browser, graph)+ await fn(client, browser, graph, httpPort)} finally {await client?.close().catch(() => undefined)browser?.close()@@ -484,6 +484,50 @@ describe('MCP server with mcpRoot', () => {}}+ test('a browser app reads and writes files inside mcpRoot through /files', async () => {+ await withMCPRootServer(TEST_MCP_ROOT, async (_client, _browser, _graph, httpPort) => {+ const path = join(TEST_MCP_ROOT, 'browser', 'saved.fig')+ const url = (filePath: string) =>+ `http://127.0.0.1:${httpPort}/files/${filePath.split(/[\\/]/).map(encodeURIComponent).join('/')}`+ const auth = { authorization: `Bearer ${TEST_AUTH_TOKEN}` }+ const bytes = new Uint8Array([80, 75, 3, 4, 1, 2, 3])++ const put = await fetch(url(path), { method: 'PUT', headers: auth, body: bytes })+ expect(put.status).toBe(200)+ expect(new Uint8Array(await readFile(path))).toEqual(bytes)+ const get = await fetch(url(path), { headers: auth })+ expect(new Uint8Array(await get.arrayBuffer())).toEqual(bytes)++ // Larger than one read chunk, so the file is read back across several.+ const large = Uint8Array.from({ length: 2.5 * 1024 * 1024 }, (_, i) => i % 251)+ await fetch(url(path), { method: 'PUT', headers: auth, body: large })+ const back = await fetch(url(path), { headers: auth })+ expect(new Uint8Array(await back.arrayBuffer())).toEqual(large)++ // A name the URL must carry exactly: a space, a fragment mark, a literal escape, Cyrillic.+ const awkward = join(TEST_MCP_ROOT, 'browser', 'my #1 %20 файл.fig')+ expect(+ (await fetch(url(awkward), { method: 'PUT', headers: auth, body: bytes })).status+ ).toBe(200)+ expect(new Uint8Array(await readFile(awkward))).toEqual(bytes)++ expect((await fetch(url(path))).status).toBe(401)+ const outside = join(TEST_MCP_ROOT, '..', 'outside.fig')+ expect(+ (await fetch(url(outside), { method: 'PUT', headers: auth, body: bytes })).status+ ).toBe(400)+ })+ })++ test('has no /files without mcpRoot', async () => {+ await withMCPRootServer(null, async (_client, _browser, _graph, httpPort) => {+ const response = await fetch(`http://127.0.0.1:${httpPort}/files/tmp/a.fig`, {+ headers: { authorization: `Bearer ${TEST_AUTH_TOKEN}` }+ })+ expect(response.status).toBe(404)+ })+ })+test('registers open_file and new_document tools when mcpRoot is set', async () => {await withMCPRootServer(TEST_MCP_ROOT, async (client) => {const { tools } = await client.listTools()