AI-native design editor. Open-source Figma alternative.
feat(automation): expose reviewed tools through WebMCP
Danila Poyarkovfdf04c35e5a4
diff --git a/AGENTS.md b/AGENTS.mdindex cfd73d917..daae32fd9 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -112,6 +112,7 @@ Use Conventional Commits (`feat`, `fix`, `refactor`, `perf`, `docs`, `test`, `bu- `ai-adapter.ts` converts ToolDefs for Vercel AI; `src/app/ai/tools/index.ts` binds them to the active editor's `FigmaAPI`.- CLI commands own CLI UX independently; `eval` exposes operations through `FigmaAPI`.- MCP-only filesystem/server tools live in `packages/mcp/src/tool/registration.ts`; listener/session lifecycle lives under `server/`, stdio under `stdio/`, and transport discovery under `transport/`. File access must resolve symlinks inside the effective MCP root; CLI defaults are cwd on macOS/Linux and home on Windows.+- Browser-native WebMCP registration lives under `src/app/automation/webmcp/`, uses explicit inspection and atomic-edit allowlists, and is feature-detected through `document.modelContext`. Shared synchronous property/variable transactions live under `src/app/automation/execution/` and are used by AI, MCP, and WebMCP; never add an async or structural tool to that allowlist. Font loading runs after commit. Keep browser lifecycle out of Core and the MCP server package.- Keep MCP transport tests under `tests/engine/mcp/{server,stdio,transport}` and shared fixtures under `tests/helpers/mcp`; isolate tests from user runtime discovery.- Shared scene-authoring guidance and tested examples live under `packages/core/src/design-jsx/reference/`; `reference.ts` combines them with renderer metadata. Core codegen prompts under `packages/core/src/tools/prompts/` and the app chat/ACP prompt compose that public reference rather than copying it. Run `bun run generate:authoring-reference` after changes; committed skill/docs copies are checked by `check:authoring-reference` (also part of `check:docs`). Do not edit generated reference files directly.- The installable agent skill is maintained in `skills/open-pencil/`. Changes to agent-facing APIs, CLI/MCP behavior, or design authoring must update affected skill examples, prompts, and public documentation in the same change. Keep examples valid in their actual execution environment; do not advertise library exports as scripting globals unless exposed there. Prefer runtime discovery and canonical references over duplicated API/tool inventories.@@ -125,7 +126,7 @@ Use Conventional Commits (`feat`, `fix`, `refactor`, `perf`, `docs`, `test`, `bu## Code conventions-- Use Valibot for first-party runtime validation. Keep Zod at upstream SDK integration boundaries that require it, such as MCP tool registration; do not maintain parallel first-party schemas in both libraries.+- Use Valibot for first-party runtime validation. MCP v2 registration uses Standard Schema with Valibot JSON Schema conversion; AI and WebMCP adapters share the Core tool input contract. Keep Zod only where upstream dependencies require it; do not maintain parallel first-party schemas in both libraries.- Put code and tests in the established owning domain; inspect nearby structure before adding files.- `bun run check:arch` enforces boundaries: use public workspace exports, keep Core framework-neutral, keep app services out of views/shared UI, and keep property-panel internals scoped to that panel.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b70f44f42..76ef8e9f8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,10 +4,12 @@### Breaking changes+- Use MCP SDK v2 server/client types for programmatic MCP integrations. Replace the removed `paramToZod()` export with the shared Valibot tool input contract from `@open-pencil/core/tools`.- Update custom Vue SDK binding providers to implement `getBindingId()` and handle `unresolved`. Replace `setValue()` with `prepareEdit()`, returning a stable edit key, captured value, setter, and restoration callback.### Added+- Expose design inspection and undoable layer-property and variable edits to browser agents through experimental WebMCP in supporting browsers.- Bind Design JSX spacing, sizing, corners, and typography directly to numeric document variables.- Define component properties and assign instance values in Design JSX using stable property IDs.- Save AI conversations and attachment previews locally, switch between chats, rename or delete them, and browse saved transcripts across documents. Choose whether reasoning stays collapsed, expands while thinking, or stays expanded, with animated disclosure controls that respect reduced motion.diff --git a/packages/docs/programmable/mcp-server.md b/packages/docs/programmable/mcp-server.mdindex 93ca43894..e1be970fa 100644--- a/packages/docs/programmable/mcp-server.md+++ b/packages/docs/programmable/mcp-server.md@@ -9,6 +9,16 @@ OpenPencil includes an MCP (Model Context Protocol) server that lets AI coding tTwo transports: **stdio** for MCP clients, and **Streamable HTTP** for browser extensions and scripts. On macOS and Linux, local clients prefer a private Unix domain socket; Windows and unavailable sockets fall back to localhost TCP.+## Browser-native WebMCP (experimental)++In browsers exposing `document.modelContext`, OpenPencil registers a reviewed set of tools directly in the workspace. Browser agents can inspect nodes, JSX, variables, components, and design patterns, and edit existing layer properties and variable values without installing or connecting an MCP server.++Tools target the document and page active when the call starts. Switching tabs does not redirect an in-flight call. Closing the workspace unregisters the tools. Tool inputs are validated and large inspection results require a narrower query. Oversized editing results are omitted with a committed-edit notice rather than reporting a successful edit as failed.++Edits to geometry, paints, layout, text, and variable bindings/values commit synchronously as individual undoable operations. Failed edits roll back, and undo targets the original document/page even after a page switch. Cancellation prevents an edit from starting; cancellation after commit does not reverse it. Font loading finishes separately without holding a mutation transaction open. Atomic editing currently requires a document with at most 10,000 nodes and variables combined; this shared limit also applies when the same editing tools run through app AI/MCP.++This surface does **not** expose structural creation/deletion, arbitrary JavaScript/JSX execution, image loading, filesystem operations, or credentials. Those tools retain their existing AI/MCP paths. WebMCP is an evolving browser proposal, not universally available; unsupported browsers continue to use OpenPencil normally. The stdio and HTTP integrations below remain independent.+## Install```shdiff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.mdindex bdd287f1d..342060ad1 100644--- a/skills/open-pencil/SKILL.md+++ b/skills/open-pencil/SKILL.md@@ -205,9 +205,15 @@ The CLI defaults the filesystem root to the home directory on Windows and the cu5. **Navigate** — after creating or editing visible canvas content, call `select_nodes` and `viewport_zoom_to_fit { id }` (or `node_bounds` + `viewport_set`) so the user can see the result in the running editor.6. **Save/export** — `save_file`, `export_image`, `export_svg`, `export_pdf`, or CLI `export`.+### Browser-native WebMCP (experimental)++Supporting browsers expose inspection and undoable existing-layer/property and variable edits directly from the OpenPencil workspace through `document.modelContext`, without an MCP server connection. Discover this browser surface separately: it excludes structural creation/deletion, arbitrary JS/JSX execution, external assets, filesystem operations, and credentials.++Calls capture the active document/page. Cancellation prevents an edit from starting but does not reverse an already committed edit; use editor undo instead. Atomic edits require at most 10,000 nodes and variables combined, including when these same tools run through app AI/MCP. See the [WebMCP guide](https://openpencil.dev/programmable/mcp-server#browser-native-webmcp-experimental) for scope and browser requirements.+## Tool discovery-Discover available tools and their arguments from the connected server; availability varies by version and server mode. Do not rely on a fixed tool count or a copied inventory.+Discover available tools and their arguments from the connected server or browser; availability varies by version and mode. Do not rely on a fixed tool count or a copied inventory.> Tool availability can depend on server mode. `open_file`, `save_file`, and disk-writing export paths are scoped to the effective filesystem root; set it explicitly with `OPENPENCIL_MCP_ROOT`.diff --git a/src/app/automation/webmcp/registration.ts b/src/app/automation/webmcp/registration.tsnew file mode 100644index 000000000..43d287868--- /dev/null+++ b/src/app/automation/webmcp/registration.ts@@ -0,0 +1,96 @@+// eslint-disable-next-line open-pencil/no-mixed-case-acronym-identifiers -- Upstream export spelling.+import { toJsonSchema as toJSONSchema } from '@valibot/to-json-schema'+import * as v from 'valibot'+import type { WebMCP } from 'webmcp-types'++import { ALL_TOOLS, toolInputEntries, type ToolDef } from '@open-pencil/core/tools'++import { ATOMIC_TOOL_NAMES } from '@/app/automation/execution/atomic'++/** Reviewed inspection surface: no code execution, network or file access. */+const READ_TOOLS = new Set([+ 'get_page_tree',+ 'get_node',+ 'find_nodes',+ 'get_jsx',+ 'list_pages',+ 'get_current_page',+ 'list_variables',+ 'get_variable',+ 'find_variables',+ 'list_collections',+ 'get_components',+ 'analyze_colors',+ 'analyze_typography',+ 'analyze_spacing',+ 'design_to_tokens',+ 'design_to_component_map'+])++const MAX_RESULT_BYTES = 256 * 1024++export interface WebMCPExecutionTarget {+ execute: (def: ToolDef, args: Record<string, unknown>, signal: AbortSignal) => Promise<unknown>+}++export interface WebMCPRegistration {+ ready: Promise<void>+ dispose: () => void+}++/** Capture the document before invoking any asynchronous work. */+export function registerWebMCPTools(+ context: Pick<WebMCP.ModelContext, 'registerTool'> | undefined,+ getTarget: () => WebMCPExecutionTarget+): WebMCPRegistration {+ const lifetime = new AbortController()+ const dispose = () => lifetime.abort()+ const ready = (async () => {+ if (!context) return+ try {+ for (const def of ALL_TOOLS) {+ if (!READ_TOOLS.has(def.name) && !ATOMIC_TOOL_NAMES.has(def.name)) continue+ lifetime.signal.throwIfAborted()+ const schema = v.object(toolInputEntries(v, def.params))+ await context.registerTool(+ {+ name: def.name,+ description: `${def.description} Targets the active OpenPencil document.`,+ inputSchema: toJSONSchema(schema),+ annotations: { readOnlyHint: !def.mutates, untrustedContentHint: true },+ execute: async (input, options?: WebMCP.ToolExecuteCallbackOptions) => {+ // Early document.modelContext implementations omit execution options.+ const signal = options?.signal ?? new AbortController().signal+ lifetime.signal.throwIfAborted()+ signal.throwIfAborted()+ const args = v.parse(schema, input)+ const target = getTarget()+ const result = await target.execute(def, args, signal)+ // A synchronous mutation has committed; a later abort cannot roll it back.+ if (!def.mutates) signal.throwIfAborted()+ const text = JSON.stringify(result ?? null)+ if (new TextEncoder().encode(text).byteLength > MAX_RESULT_BYTES) {+ if (def.mutates) {+ return JSON.stringify({+ ok: true,+ resultOmitted: true,+ message:+ 'Edit committed. Result exceeds the size limit; inspect a smaller selection.'+ })+ }+ throw new Error('Result too large. Narrow the query or reduce its depth/limit.')+ }+ return text+ }+ },+ { signal: lifetime.signal }+ )+ }+ } catch (error) {+ const disposed = lifetime.signal.aborted+ dispose()+ if (!disposed) throw error+ }+ })()+ return { ready, dispose }+}diff --git a/src/app/automation/webmcp/runtime.ts b/src/app/automation/webmcp/runtime.tsnew file mode 100644index 000000000..4a2416d9e--- /dev/null+++ b/src/app/automation/webmcp/runtime.ts@@ -0,0 +1,46 @@+import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'+import { resolveAutomationTarget } from '@/app/automation/bridge/target'+import { createAutomationToolHandler } from '@/app/automation/bridge/tool-handlers'+import { executeAtomicEditorTool } from '@/app/automation/execution/editor'+import type { EditorStore } from '@/app/editor/active-store'+import { getTabById } from '@/app/tabs'++import { registerWebMCPTools } from './registration'++/** Browser-native tools reuse the same editor targeting and handlers as remote MCP. */+export function startWebMCP(getStore: () => EditorStore): () => void {+ const handleTool = createAutomationToolHandler(makeFigmaFromStore)+ const registration = registerWebMCPTools(+ typeof document === 'undefined' ? undefined : document.modelContext,+ () => {+ const target = resolveAutomationTarget(getStore(), undefined)+ if (getTabById(target.documentId)?.kind !== 'document') {+ throw new Error('Open a document before using WebMCP tools')+ }+ return {+ execute: async (def, args, signal) => {+ signal.throwIfAborted()+ if (def.mutates) {+ return {+ ok: true,+ result: await executeAtomicEditorTool(+ target.store,+ makeFigmaFromStore(target.store, target.pageId),+ def,+ args,+ {+ signal,+ label: 'WebMCP',+ isLive: () => getTabById(target.documentId)?.store === target.store+ }+ )+ }+ }+ return handleTool(target, { name: def.name, args })+ }+ }+ }+ )+ void registration.ready.catch((error: unknown) => console.warn('[WebMCP]', error))+ return registration.dispose+}diff --git a/src/views/WorkspaceView.vue b/src/views/WorkspaceView.vueindex ddcf703eb..e665c5e83 100644--- a/src/views/WorkspaceView.vue+++ b/src/views/WorkspaceView.vue@@ -5,6 +5,7 @@ import { onMounted, onUnmounted, provide, ref } from 'vue'import { useRoute } from 'vue-router'import { startMCPRuntime, stopMCPRuntime } from '@/app/automation/mcp/runtime'+import { startWebMCP } from '@/app/automation/webmcp/runtime'import { exposeCollaborationActions } from '@/app/browser-bridge'import { COLLAB_KEY, useCollab } from '@/app/collab/use'import { createDemoShapes } from '@/app/demo/document'@@ -80,7 +81,10 @@ async function bindAssociatedFileOpen(): Promise<void> {await openPendingAssociatedFiles()}+let stopWebMCP: (() => void) | undefined+onMounted(async () => {+ stopWebMCP = startWebMCP(getActiveStore)await startMCPRuntime(getActiveStore)try {@@ -91,6 +95,7 @@ onMounted(async () => {})onUnmounted(() => {+ stopWebMCP?.()void stopMCPRuntime()fileAssociationCleanup.value?.()})diff --git a/tests/e2e/app/webmcp.spec.ts b/tests/e2e/app/webmcp.spec.tsnew file mode 100644index 000000000..05cbd6b33--- /dev/null+++ b/tests/e2e/app/webmcp.spec.ts@@ -0,0 +1,92 @@+import { test, expect } from '@playwright/test'+import * as v from 'valibot'++const pageResult = v.object({+ ok: v.literal(true),+ result: v.object({ id: v.string(), name: v.string() })+})++test.use({+ launchOptions: { args: ['--enable-blink-features=WebMCP', '--enable-unsafe-swiftshader'] }+})++test('native WebMCP discovery, editing, validation and undo', async ({ page, browserName }) => {+ test.skip(browserName !== 'chromium', 'Native WebMCP requires a supporting Chromium build')+ await page.goto('/?test')+ await expect(page.getByRole('button', { name: 'Add page', exact: true })).toBeVisible()+ test.skip(+ !(await page.evaluate(() => Boolean(document.modelContext))),+ 'Browser lacks document.modelContext'+ )++ const cdp = await page.context().newCDPSession(page)+ const frames = new Map<string, string>()+ const responses = new Map<string, { status: string; output: unknown }>()+ cdp.on('WebMCP.toolsAdded', ({ tools }) => {+ for (const tool of tools) frames.set(tool.name, tool.frameId)+ })+ cdp.on('WebMCP.toolResponded', (response) => {+ responses.set(response.invocationId, { status: response.status, output: response.output })+ })++ async function invoke(name: string, input: Record<string, string> = {}) {+ await expect.poll(() => frames.has(name)).toBe(true)+ const frameId = frames.get(name)+ if (!frameId) throw new Error(`Missing native WebMCP tool ${name}`)+ const { invocationId } = await cdp.send('WebMCP.invokeTool', { frameId, toolName: name, input })+ await expect.poll(() => responses.has(invocationId)).toBe(true)+ const response = responses.get(invocationId)+ if (!response) throw new Error('Missing tool response')+ return {+ status: response.status,+ output:+ typeof response.output === 'string'+ ? (JSON.parse(response.output) as unknown)+ : response.output+ }+ }++ try {+ await cdp.send('WebMCP.enable')+ await expect.poll(() => frames.has('update_node')).toBe(true)+ expect(frames.has('eval')).toBe(false)+ expect(frames.has('save_file')).toBe(false)+ const current = await invoke('get_current_page')+ expect(current.status).toBe('Completed')+ const original = v.parse(pageResult, current.output).result+ expect(+ (await invoke('update_node', { id: original.id, name: 'Browser agent page' })).status+ ).toBe('Completed')+ await expect(+ page.getByRole('button', { name: 'Browser agent page', exact: true })+ ).toBeVisible()+ const modifier = process.platform === 'darwin' ? 'Meta' : 'Control'+ await page.keyboard.press(`${modifier}+z`)+ expect(v.parse(pageResult, (await invoke('get_current_page')).output).result.name).toBe(+ original.name+ )+ await page.keyboard.press(`${modifier}+Shift+z`)+ expect(v.parse(pageResult, (await invoke('get_current_page')).output).result.name).toBe(+ 'Browser agent page'+ )+ expect((await invoke('update_node', { name: 'Missing id' })).status).toBe('Error')+ expect(v.parse(pageResult, (await invoke('get_current_page')).output).result.name).toBe(+ 'Browser agent page'+ )+ await page.getByRole('button', { name: 'Add page', exact: true }).click()+ const secondPage = v.parse(pageResult, (await invoke('get_current_page')).output).result+ expect(secondPage.id).not.toBe(original.id)+ expect((await invoke('update_node', { id: original.id, name: 'Other page edit' })).status).toBe(+ 'Completed'+ )+ await page.keyboard.press(`${modifier}+z`)+ expect(v.parse(pageResult, (await invoke('get_current_page')).output).result.id).toBe(+ secondPage.id+ )+ expect(+ v.parse(pageResult, (await invoke('get_node', { id: original.id })).output).result.name+ ).toBe('Browser agent page')+ } finally {+ await cdp.detach()+ }+})diff --git a/tests/engine/mcp/webmcp.test.ts b/tests/engine/mcp/webmcp.test.tsnew file mode 100644index 000000000..e388e9eaf--- /dev/null+++ b/tests/engine/mcp/webmcp.test.ts@@ -0,0 +1,151 @@+import { describe, expect, test } from 'bun:test'++import type { WebMCP } from 'webmcp-types'++import { registerWebMCPTools } from '@/app/automation/webmcp/registration'++function host() {+ const tools = new Map<string, WebMCP.ModelContextTool>()+ return {+ tools,+ async registerTool(+ tool: WebMCP.ModelContextTool,+ options?: WebMCP.ModelContextRegisterToolOptions+ ) {+ tools.set(tool.name, tool)+ options?.signal?.addEventListener('abort', () => tools.delete(tool.name), { once: true })+ }+ }+}++function requiredTool(tools: Map<string, WebMCP.ModelContextTool>, name: string) {+ const tool = tools.get(name)+ if (!tool) throw new Error(`Missing tool ${name}`)+ return tool+}++const options = () => ({ signal: new AbortController().signal })++describe('WebMCP registration', () => {+ test('unsupported browsers do nothing', async () => {+ const registration = registerWebMCPTools(undefined, () => {+ throw new Error('Must not resolve an editor')+ })+ await registration.ready+ registration.dispose()+ })++ test('registers only reviewed tools and unregisters on disposal', async () => {+ const context = host()+ const registration = registerWebMCPTools(context, () => ({ execute: async () => ({}) }))+ await registration.ready+ expect(context.tools.has('get_node')).toBe(true)+ for (const name of [+ 'eval',+ 'render',+ 'save_file',+ 'delete_node',+ 'create_variable',+ 'set_image_fill'+ ]) {+ expect(context.tools.has(name)).toBe(false)+ }+ expect(context.tools.get('get_node')?.annotations?.readOnlyHint).toBe(true)+ expect(context.tools.get('set_fill')?.annotations?.readOnlyHint).toBe(false)+ for (const tool of context.tools.values()) {+ expect(tool.annotations?.untrustedContentHint).toBe(true)+ expect(tool.inputSchema).toMatchObject({ type: 'object' })+ }+ registration.dispose()+ expect(context.tools.size).toBe(0)+ })++ test('validates before execution and captures the target for each call', async () => {+ const context = host()+ let active = 'first'+ let calls = 0+ const registration = registerWebMCPTools(context, () => {+ const captured = active+ return {+ execute: async () => {+ calls+++ await Promise.resolve()+ return { document: captured }+ }+ }+ })+ await registration.ready+ try {+ const tool = requiredTool(context.tools, 'get_node')+ await expect(tool.execute({}, options())).rejects.toThrow()+ expect(calls).toBe(0)+ const pending = tool.execute({ id: 'node' }, options())+ active = 'second'+ expect(await pending).toBe('{"document":"first"}')+ expect(await tool.execute({ id: 'node' }, options())).toBe('{"document":"second"}')+ } finally {+ registration.dispose()+ }+ })++ test('rejects cancelled calls and excessive results', async () => {+ const context = host()+ const registration = registerWebMCPTools(context, () => ({+ execute: async () => 'x'.repeat(300_000)+ }))+ await registration.ready+ try {+ const tool = requiredTool(context.tools, 'get_node')+ const cancelled = new AbortController()+ cancelled.abort()+ await expect(tool.execute({ id: 'node' }, { signal: cancelled.signal })).rejects.toThrow()+ await expect(tool.execute({ id: 'node' }, options())).rejects.toThrow('Result too large')+ } finally {+ registration.dispose()+ }+ })++ test('reports committed edits even when their result exceeds the size limit', async () => {+ const context = host()+ let content = ''+ const registration = registerWebMCPTools(context, () => ({+ execute: async (_def, args) => {+ content = String(args.text)+ return { id: args.id, text: content }+ }+ }))+ await registration.ready+ try {+ const text = 'x'.repeat(300_000)+ const result = await requiredTool(context.tools, 'set_text').execute(+ { id: 'node', text },+ options()+ )+ expect(content).toBe(text)+ expect(result).toBe(+ JSON.stringify({+ ok: true,+ resultOmitted: true,+ message: 'Edit committed. Result exceeds the size limit; inspect a smaller selection.'+ })+ )+ } finally {+ registration.dispose()+ }+ })++ test('cleans partial registration after browser rejection', async () => {+ const context = host()+ const registration = registerWebMCPTools(+ {+ async registerTool(tool, options) {+ if (context.tools.size === 2) throw new Error('Registration denied')+ await context.registerTool(tool, options)+ }+ },+ () => ({ execute: async () => ({}) })+ )+ await expect(registration.ready).rejects.toThrow('Registration denied')+ expect(context.tools.size).toBe(0)+ })+})