AI-native design editor. Open-source Figma alternative.
refactor(tools)!: centralize schemas and execution contracts
Danila Poyarkov4a9bad5cec27
diff --git a/AGENTS.md b/AGENTS.mdindex daae32fd9..b449c448b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -108,11 +108,11 @@ Use Conventional Commits (`feat`, `fix`, `refactor`, `perf`, `docs`, `test`, `bu## Tools (AI / MCP / CLI)-- Core operations are `ToolDef`s under `packages/core/src/tools/**`; `schema.ts` defines their contract and registries expose them. Add work to the nearest existing domain and the appropriate registry.+- Core operations are `ToolDef`s under `packages/core/src/tools/**`; `schema.ts` defines their contract and registries expose them. Each definition owns its native Valibot `input`, execution/mutation metadata, and explicit browser exposure. Infer arguments from the schema; derive effects and default capabilities from execution metadata instead of maintaining parameter DSLs or tool-name lists. Add work to the nearest existing domain and the appropriate registry.- `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.+- Browser-native WebMCP registration lives under `src/app/automation/webmcp/`, consumes per-tool exposure metadata, and is feature-detected through `document.modelContext`. Core owns synchronous property/variable transactions in `editor/history/atomic-tool.ts`; Scene Graph owns checkpoint recovery, including hierarchy and indexes. AI, MCP, and WebMCP share this execution path; async and structural tools cannot declare atomic property execution. App completion under `src/app/automation/execution/` loads fonts 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.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 76ef8e9f8..fdca38421 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,7 +4,7 @@### 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`.+- Use MCP SDK v2 server/client types for programmatic MCP integrations. Define custom tools with native Valibot `input` schemas and execution metadata instead of `params`, `ParamDef`, or `paramToZod()`; tool arguments and effects derive from this shared contract.- 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.### Addeddiff --git a/bun.lock b/bun.lockindex db4bbb42f..13f430519 100644--- a/bun.lock+++ b/bun.lock@@ -180,6 +180,7 @@"@open-pencil/pen": "workspace:*","@open-pencil/scene-graph": "workspace:*","@tauri-apps/api": "^2.11.1",+ "@valibot/to-json-schema": "^1.8.0","@xmldom/xmldom": "^0.9.11","acorn": "^8.18.0","canvaskit-wasm": "^0.41.1",diff --git a/packages/core/package.json b/packages/core/package.jsonindex 2fba31403..0f2005c32 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -180,6 +180,7 @@"@open-pencil/pen": "workspace:*","@open-pencil/scene-graph": "workspace:*","@tauri-apps/api": "^2.11.1",+ "@valibot/to-json-schema": "^1.8.0","@xmldom/xmldom": "^0.9.11","acorn": "^8.18.0","canvaskit-wasm": "^0.41.1",diff --git a/src/app/automation/execution/atomic.ts b/packages/core/src/editor/history/atomic-tool.tssimilarity index 78%rename from src/app/automation/execution/atomic.tsrename to packages/core/src/editor/history/atomic-tool.tsindex 7888b052a..a03b42fb8 100644--- a/src/app/automation/execution/atomic.ts+++ b/packages/core/src/editor/history/atomic-tool.ts@@ -1,45 +1,20 @@import { isEqual } from 'es-toolkit'-import type { FigmaAPI } from '@open-pencil/core/figma-api'-import type { ToolDef } from '@open-pencil/core/tools'-import type { SceneGraph, SceneNode, Variable } from '@open-pencil/scene-graph'+import {+ captureGraphCheckpoint,+ type SceneGraph,+ type SceneNode,+ type Variable+} from '@open-pencil/scene-graph'-import type { EditorStore } from '@/app/editor/active-store'--/** Audited synchronous operations: update existing nodes/values, never hierarchy or assets. */-export const ATOMIC_TOOL_NAMES: ReadonlySet<string> = new Set([- 'update_node',- 'set_rotation',- 'set_opacity',- 'set_radius',- 'set_minmax',- 'set_fill',- 'set_stroke',- 'set_effects',- 'set_visible',- 'set_blend',- 'set_locked',- 'set_stroke_align',- 'set_layout',- 'set_constraints',- 'set_layout_child',- 'set_text',- 'set_font',- 'set_font_range',- 'set_text_resize',- 'set_text_properties',- 'set_variable',- 'bind_variable',- 'unbind_variable'-])+import type { Editor } from '#core/editor/create'+import type { FigmaAPI } from '#core/figma-api'+import { isAtomicTool, type ToolDef } from '#core/tools/schema'// Capture property changes across pages. Component synchronization remains editor-owned.const MAX_TRANSACTION_NODES = 10_000-type MutationEditor = Pick<- EditorStore,- 'graph' | 'runLayoutForNode' | 'requestRender' | 'pushUndoEntry'->+type MutationEditor = Pick<Editor, 'graph' | 'runLayoutForNode' | 'requestRender' | 'pushUndoEntry'>type Changes<T> = { id: string; before: Partial<T>; after: Partial<T> }function changes<T extends object>(before: Map<string, T>, after: Map<string, T>): Changes<T>[] {@@ -73,7 +48,7 @@ export function executeAtomicTool(args: Record<string, unknown>,options: { signal?: AbortSignal; isLive?: () => boolean; label?: string } = {}): unknown {- if (!ATOMIC_TOOL_NAMES.has(def.name)) throw new Error(`Not an atomic tool: ${def.name}`)+ if (!isAtomicTool(def)) throw new Error(`Not an atomic tool: ${def.name}`)options.signal?.throwIfAborted()if (editor.graph !== figma.graph || options.isLive?.() === false) {throw new Error('The target document is no longer open')@@ -82,8 +57,8 @@ export function executeAtomicTool(if (graph.nodes.size + graph.variables.size > MAX_TRANSACTION_NODES) {throw new Error('Document too large for atomic agent editing (maximum 10000 nodes)')}- const nodes = structuredClone(graph.nodes)- const variables = structuredClone(graph.variables)+ const checkpoint = captureGraphCheckpoint(graph)+ const { nodes, variables } = checkpointconst pageId = figma.currentPageIdconst replay = (@@ -116,6 +91,7 @@ export function executeAtomicTool(if (result && typeof result === 'object' && 'error' in result) {throw new Error(String(result.error))}+ checkpoint.assertPropertiesOnly()const variableChanges = changes(variables, graph.variables)layout(graph,@@ -139,7 +115,8 @@ export function executeAtomicTool(}return result} catch (error) {- replay(changes(nodes, graph.nodes), changes(variables, graph.variables), 'before')+ checkpoint.restore()+ editor.requestRender()throw error}}diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.tsindex 13d241399..30c09801a 100644--- a/packages/core/src/editor/index.ts+++ b/packages/core/src/editor/index.ts@@ -13,6 +13,7 @@ export {pickEditorViewState} from './state/view'export { createDefaultEditorState, createEditor } from './create'+export { executeAtomicTool } from './history/atomic-tool'export type { ClipboardPayload, ClipboardSnapshot } from './clipboard/copy'export type { Editor } from './create'export { reapplyInstanceComponentProperties } from './components/properties'diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 1ffa9ec8d..e6b058571 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -85,8 +85,8 @@ export {} from './tools'export type {ToolDef,- ParamDef,- ParamType,+ ToolExecution,+ ToolCapability,ToolLogEntry,ToolDebugLog,AIAdapterOptions,diff --git a/packages/core/src/tools/ai-adapter.ts b/packages/core/src/tools/ai-adapter.tsindex f8b01f6c0..6d38d7fc1 100644--- a/packages/core/src/tools/ai-adapter.ts+++ b/packages/core/src/tools/ai-adapter.ts@@ -1,20 +1,18 @@/*** Adapter: tool definitions → Vercel AI SDK `tool()` objects.*- * Converts ParamDef types to valibot schemas and wraps execute- * functions with FigmaAPI instantiation.+ * Consumes native tool input schemas and wraps execution with FigmaAPI instantiation.*/-import type { valibotSchema as createValibotSchema } from '@ai-sdk/valibot'+// eslint-disable-next-line open-pencil/no-mixed-case-acronym-identifiers -- Upstream export spelling.+import { toStandardJsonSchema as toStandardJSONSchema } from '@valibot/to-json-schema'import type { ToolSet, tool as createTool } from 'ai'-import type * as valibot from 'valibot'import type { JSONObject } from '@open-pencil/scene-graph/primitives'import type { FigmaAPI } from '#core/figma-api'import type { ToolDef } from './schema'-import { toolInputEntries } from './validation'export interface ToolLogEntry {tool: string@@ -144,18 +142,16 @@ export function toolsToAI(tools: ToolDef[],options: AIAdapterOptions,deps: {- v: typeof valibot- valibotSchema: typeof createValibotSchematool: typeof createTool}): ToolSet {- const { v, valibotSchema, tool } = deps+ const { tool } = depsconst result: ToolSet = {}for (const def of tools) {const toolOpts: Record<string, unknown> = {description: def.description,- inputSchema: valibotSchema(v.object(toolInputEntries(v, def.params))),+ inputSchema: toStandardJSONSchema(def.input),execute: async (args: Record<string, unknown>) => {const startTime = Date.now()const figma = options.getFigma()diff --git a/packages/core/src/tools/analyze/clusters.ts b/packages/core/src/tools/analyze/clusters.tsindex 0ed784de3..e9e6133d8 100644--- a/packages/core/src/tools/analyze/clusters.ts+++ b/packages/core/src/tools/analyze/clusters.ts@@ -1,6 +1,8 @@import { orderBy, sortBy } from 'es-toolkit/array'import { meanBy } from 'es-toolkit/math'+import * as v from 'valibot'+import { toolNumber } from '#core/tools/input'import { defineTool } from '#core/tools/schema'interface SizedItem {@@ -28,11 +30,18 @@ export const analyzeClusters = defineTool({name: 'analyze_clusters',description:'Find repeated design patterns (potential components). Groups nodes by structural signature — type, size, and child structure.',- params: {- min_count: { type: 'number', description: 'Min instances to form a cluster (default: 2)' },- min_size: { type: 'number', description: 'Min node size in px (default: 30)' },- limit: { type: 'number', description: 'Max clusters to return (default: 20)' }- },+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({+ min_count: v.optional(+ toolNumber(v.pipe(v.number(), v.description('Min instances to form a cluster (default: 2)')))+ ),+ min_size: v.optional(+ toolNumber(v.pipe(v.number(), v.description('Min node size in px (default: 30)')))+ ),+ limit: v.optional(+ toolNumber(v.pipe(v.number(), v.description('Max clusters to return (default: 20)')))+ )+ }),execute: (figma, args) => {const minCount = args.min_count ?? 2const minSize = args.min_size ?? 30diff --git a/packages/core/src/tools/analyze/colors.ts b/packages/core/src/tools/analyze/colors.tsindex e00acc81e..94f57d827 100644--- a/packages/core/src/tools/analyze/colors.ts+++ b/packages/core/src/tools/analyze/colors.ts@@ -1,12 +1,16 @@import { orderBy } from 'es-toolkit/array'import { sumBy } from 'es-toolkit/math'+import * as v from 'valibot'import type { Color } from '@open-pencil/scene-graph/primitives'import { colorDistance, colorToHex } from '#core/color'import type { ColorUsageEntry } from '#core/color/analysis'+import { toolNumber } from '#core/tools/input'import { defineTool } from '#core/tools/schema'+import { analysisLimitInput } from './input'+type ColorEntry = ColorUsageEntryfunction trackColor(colorMap: Map<string, ColorEntry>, color: Color, variableName: string | null) {@@ -26,19 +30,21 @@ export const analyzeColors = defineTool({name: 'analyze_colors',description:'Analyze color palette usage across the current page. Shows frequency, variable bindings, and optionally clusters similar colors.',- params: {- limit: { type: 'number', description: 'Max colors to return (default: 30)' },- show_similar: {- type: 'boolean',- description: 'Include similar-color clusters for potential merging'- },- threshold: {- type: 'number',- description: 'Distance threshold for clustering (0-50, default: 15)'- }- },+ execution: { kind: 'sync', mutation: 'none' },+ exposure: { webmcp: true },+ input: v.object({+ limit: analysisLimitInput,+ show_similar: v.optional(+ v.pipe(v.boolean(), v.description('Include similar-color clusters for potential merging'))+ ),+ threshold: v.optional(+ toolNumber(+ v.pipe(v.number(), v.description('Distance threshold for clustering (0-50, default: 15)'))+ )+ )+ }),execute: (figma, args) => {- const limit = args.limit ?? 30+ const limit = args.limitconst threshold = args.threshold ?? 15const page = figma.currentPageconst colorMap = new Map<string, ColorEntry>()diff --git a/packages/core/src/tools/analyze/diff.ts b/packages/core/src/tools/analyze/diff.tsindex f4a318fb5..ad3f38da5 100644--- a/packages/core/src/tools/analyze/diff.ts+++ b/packages/core/src/tools/analyze/diff.ts@@ -1,10 +1,12 @@import { safeDestr } from 'destr'import { createTwoFilesPatch } from 'diff'+import * as v from 'valibot'import type { SceneNode } from '@open-pencil/scene-graph'import { colorToHex, parseColor } from '#core/color'import type { FigmaAPI } from '#core/figma-api'+import { toolNumber, nodeIdInput } from '#core/tools/input'import { defineTool } from '#core/tools/schema'function serializePaintProps(raw: SceneNode, lines: string[]): void {@@ -123,11 +125,12 @@ export const diffCreate = defineTool({name: 'diff_create',description:'Create a structural diff between two node trees. Compares properties (fills, strokes, effects, text, size, position) in unified diff format.',- params: {- from: { type: 'string', description: 'Source node ID', required: true },- to: { type: 'string', description: 'Target node ID', required: true },- depth: { type: 'number', description: 'Max tree depth (default: 10)' }- },+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({+ from: v.pipe(v.string(), v.description('Source node ID')),+ to: v.pipe(v.string(), v.description('Target node ID')),+ depth: v.optional(toolNumber(v.pipe(v.number(), v.description('Max tree depth (default: 10)'))))+ }),execute: (figma, args) => {const maxDepth = args.depth ?? 10const fromNode = figma.graph.getNode(args.from)@@ -177,15 +180,16 @@ export const diffShow = defineTool({name: 'diff_show',description:'Preview what would change if properties were applied to a node. Shows a unified diff of current vs proposed state.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- props: {- type: 'string',- description:- 'JSON object of new properties, e.g. \'{"opacity": 1, "fill": "#FF0000", "width": 200}\'',- required: true- }- },+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({+ id: nodeIdInput,+ props: v.pipe(+ v.string(),+ v.description(+ 'JSON object of new properties, e.g. \'{"opacity": 1, "fill": "#FF0000", "width": 200}\''+ )+ )+ }),execute: (figma, args) => {const raw = figma.graph.getNode(args.id)if (!raw) return { error: `Node "${args.id}" not found` }diff --git a/packages/core/src/tools/analyze/eval/index.ts b/packages/core/src/tools/analyze/eval/index.tsindex cb0fca20c..04ac32ce5 100644--- a/packages/core/src/tools/analyze/eval/index.ts+++ b/packages/core/src/tools/analyze/eval/index.ts@@ -1,3 +1,5 @@+import * as v from 'valibot'+import { defineTool } from '#core/tools/schema'import { wrapEvalCode } from './wrap'@@ -6,10 +8,13 @@ export const evalCode = defineTool({name: 'eval',description:'Execute JavaScript with full Figma Plugin API access. Use for operations not covered by other tools. The `figma` global is available.',- params: {- code: { type: 'string', description: 'JavaScript code to execute', required: true }- },- mutates: true,+ execution: { kind: 'async', mutation: 'document' },+ capabilities: ['document:read', 'document:write', 'code:execute'],+ availability: 'eval',+ input: v.object({+ code: v.pipe(v.string(), v.description('JavaScript code to execute'))+ }),+execute: async (figma, { code }) => {type AsyncFunctionConstructor = new (...args: string[]diff --git a/packages/core/src/tools/analyze/input.ts b/packages/core/src/tools/analyze/input.tsnew file mode 100644index 000000000..18c09519c--- /dev/null+++ b/packages/core/src/tools/analyze/input.ts@@ -0,0 +1,8 @@+import * as v from 'valibot'++import { toolNumber } from '#core/tools/input'++export const analysisLimitInput = v.optional(+ toolNumber(v.pipe(v.number(), v.description('Maximum results to return (default: 30)'))),+ 30+)diff --git a/packages/core/src/tools/analyze/overlaps/index.ts b/packages/core/src/tools/analyze/overlaps/index.tsindex 7e2780adc..0cebb151d 100644--- a/packages/core/src/tools/analyze/overlaps/index.ts+++ b/packages/core/src/tools/analyze/overlaps/index.ts@@ -1,8 +1,10 @@import { orderBy } from 'es-toolkit/array'+import * as v from 'valibot'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import type { FigmaAPI } from '#core/figma-api'+import { toolNumber } from '#core/tools/input'import { defineTool } from '#core/tools/schema'import {@@ -332,64 +334,75 @@ export const analyzeOverlaps = defineTool({name: 'analyze_overlaps',description:'Detect visual overlaps and layout overflows across the current page. Useful for finding content that covers footers, text that bleeds outside frames, and accidental sibling overlaps.',- params: {- scope: {- type: 'string',- description:- 'Which pairs to inspect: all, same-parent, cross-parent, top-level, inside-parent (default: all)',- enum: ['all', 'same-parent', 'cross-parent', 'top-level', 'inside-parent'],- default: 'all'- },- category: {- type: 'string',- description:- 'Comma-separated categories: sibling-overlap, parent-overflow, overlay (default: all)'- },- severity: {- type: 'string',- description: 'Minimum severity to include: critical, major, minor, info (default: info)',- enum: ['critical', 'major', 'minor', 'info'],- default: 'info'- },- min_area: {- type: 'number',- description: 'Minimum overlap area in square pixels (default: 0)'- },- min_ratio: {- type: 'number',- description: 'Minimum overlap ratio relative to the smaller node, 0.0–1.0 (default: 0)'- },- include_hidden: {- type: 'boolean',- description: 'Include hidden nodes in the analysis'- },- include_locked: {- type: 'boolean',- description: 'Include locked nodes in the analysis'- },- include_absolute: {- type: 'boolean',- description: 'Include absolutely-positioned nodes in the analysis'- },- page: {- type: 'string',- description: 'Limit analysis to nodes on the named page'- },- page_id: {- type: 'string',- description:- 'Limit analysis to nodes on the page with this stable ID (takes precedence over page)'- },- type: {- type: 'string',- description: 'Comma-separated node types to analyze, e.g. FRAME,TEXT'- },- limit: {- type: 'number',- description: 'Maximum overlap findings to return (default: 100)',- default: 100- }- },+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({+ scope: v.optional(+ v.pipe(+ v.picklist(['all', 'same-parent', 'cross-parent', 'top-level', 'inside-parent']),+ v.description(+ 'Which pairs to inspect: all, same-parent, cross-parent, top-level, inside-parent (default: all)'+ )+ ),+ 'all'+ ),+ category: v.optional(+ v.pipe(+ v.string(),+ v.description(+ 'Comma-separated categories: sibling-overlap, parent-overflow, overlay (default: all)'+ )+ )+ ),+ severity: v.optional(+ v.pipe(+ v.picklist(['critical', 'major', 'minor', 'info']),+ v.description('Minimum severity to include: critical, major, minor, info (default: info)')+ ),+ 'info'+ ),+ min_area: v.optional(+ toolNumber(+ v.pipe(v.number(), v.description('Minimum overlap area in square pixels (default: 0)'))+ )+ ),+ min_ratio: v.optional(+ toolNumber(+ v.pipe(+ v.number(),+ v.description('Minimum overlap ratio relative to the smaller node, 0.0–1.0 (default: 0)')+ )+ )+ ),+ include_hidden: v.optional(+ v.pipe(v.boolean(), v.description('Include hidden nodes in the analysis'))+ ),+ include_locked: v.optional(+ v.pipe(v.boolean(), v.description('Include locked nodes in the analysis'))+ ),+ include_absolute: v.optional(+ v.pipe(v.boolean(), v.description('Include absolutely-positioned nodes in the analysis'))+ ),+ page: v.optional(+ v.pipe(v.string(), v.description('Limit analysis to nodes on the named page'))+ ),+ page_id: v.optional(+ v.pipe(+ v.string(),+ v.description(+ 'Limit analysis to nodes on the page with this stable ID (takes precedence over page)'+ )+ )+ ),+ type: v.optional(+ v.pipe(v.string(), v.description('Comma-separated node types to analyze, e.g. FRAME,TEXT'))+ ),+ limit: v.optional(+ toolNumber(+ v.pipe(v.number(), v.description('Maximum overlap findings to return (default: 100)'))+ ),+ 100+ )+ }),execute: (figma: FigmaAPI, args) => {const page_id = args.page_id ?? (args.page ? undefined : figma.currentPageId)return computeOverlaps(figma.graph, { ...(args as AnalyzeOverlapsArgs), page_id })diff --git a/packages/core/src/tools/analyze/spacing.ts b/packages/core/src/tools/analyze/spacing.tsindex 332c65d56..94c69c6af 100644--- a/packages/core/src/tools/analyze/spacing.ts+++ b/packages/core/src/tools/analyze/spacing.ts@@ -1,14 +1,20 @@import { orderBy } from 'es-toolkit/array'+import * as v from 'valibot'+import { toolNumber } from '#core/tools/input'import { defineTool } from '#core/tools/schema'export const analyzeSpacing = defineTool({name: 'analyze_spacing',description:'Analyze spacing values (gap, padding) across the current page. Checks grid compliance.',- params: {- grid: { type: 'number', description: 'Base grid size to check against (default: 8)' }- },+ execution: { kind: 'sync', mutation: 'none' },+ exposure: { webmcp: true },+ input: v.object({+ grid: v.optional(+ toolNumber(v.pipe(v.number(), v.description('Base grid size to check against (default: 8)')))+ )+ }),execute: (figma, args) => {const gridSize = args.grid ?? 8const page = figma.currentPagediff --git a/packages/core/src/tools/analyze/typography.ts b/packages/core/src/tools/analyze/typography.tsindex 33604fbe0..9d4800d9d 100644--- a/packages/core/src/tools/analyze/typography.ts+++ b/packages/core/src/tools/analyze/typography.ts@@ -1,21 +1,24 @@import { orderBy, sortBy } from 'es-toolkit/array'+import * as v from 'valibot'import { defineTool } from '#core/tools/schema'+import { analysisLimitInput } from './input'+export const analyzeTypography = defineTool({name: 'analyze_typography',description:'Analyze typography usage across the current page. Shows font families, sizes, weights, and their frequencies.',- params: {- limit: { type: 'number', description: 'Max styles to return (default: 30)' },- group_by: {- type: 'string',- description: 'Group results by a property',- enum: ['family', 'size', 'weight']- }- },+ execution: { kind: 'sync', mutation: 'none' },+ exposure: { webmcp: true },+ input: v.object({+ limit: analysisLimitInput,+ group_by: v.optional(+ v.pipe(v.picklist(['family', 'size', 'weight']), v.description('Group results by a property'))+ )+ }),execute: (figma, args) => {- const limit = args.limit ?? 30+ const limit = args.limitconst page = figma.currentPageconst styleMap = new Map<string,diff --git a/packages/core/src/tools/calc.ts b/packages/core/src/tools/calc.tsindex 469892125..3181d36a6 100644--- a/packages/core/src/tools/calc.ts+++ b/packages/core/src/tools/calc.ts@@ -1,4 +1,5 @@import ExprEval from 'expr-eval'+import * as v from 'valibot'import { defineTool } from './schema'@@ -25,13 +26,10 @@ export const calc = defineTool({'Pass one expression or a JSON array of expressions — all evaluated in one call. ' +'Supports: + - * / % ** ( ) min max floor ceil round abs sqrt pow. ' +'Examples: "844 - 56 - 96 - 82", \'["1440 * 8 / 12", "(952 - 16) / 2", "floor(390 * 0.6)"]\'',- params: {- expr: {- type: 'string',- description: 'Single expression or JSON array of expressions',- required: true- }- },+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({+ expr: v.pipe(v.string(), v.description('Single expression or JSON array of expressions'))+ }),execute: (_figma, { expr }) => {let exprs: string[]try {diff --git a/packages/core/src/tools/codegen/component-map.ts b/packages/core/src/tools/codegen/component-map.tsindex 2ec934578..82d54d20c 100644--- a/packages/core/src/tools/codegen/component-map.ts+++ b/packages/core/src/tools/codegen/component-map.ts@@ -1,3 +1,5 @@+import * as v from 'valibot'+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import type { FigmaAPI } from '#core/figma-api'@@ -112,12 +114,13 @@ export const designToComponentMap = defineTool({name: 'design_to_component_map',description:'Analyze the document and return a structured component decomposition: components (with variants, props, instance counts), screens, and a dependency overview.',- params: {- page: {- type: 'string',- description: 'Page name to analyze (default: current page)'- }- },+ execution: { kind: 'sync', mutation: 'none' },+ exposure: { webmcp: true },+ input: v.object({+ page: v.optional(+ v.pipe(v.string(), v.description('Page name to analyze (default: current page)'))+ )+ }),execute: (figma, args) => {if (args.page) {const target = figma.root.children.find((page) => page.name === args.page)diff --git a/packages/core/src/tools/codegen/tokens.ts b/packages/core/src/tools/codegen/tokens.tsindex 0ff7641d6..3fdc54c54 100644--- a/packages/core/src/tools/codegen/tokens.ts+++ b/packages/core/src/tools/codegen/tokens.ts@@ -1,3 +1,5 @@+import * as v from 'valibot'+import type { Variable, VariableCollection, VariableValue } from '@open-pencil/scene-graph'import type { Color } from '@open-pencil/scene-graph/primitives'@@ -164,25 +166,25 @@ export const designToTokens = defineTool({name: 'design_to_tokens',description:'Extract design tokens from Figma variables as CSS custom properties, Tailwind theme config, or JSON. Resolves aliases, handles multiple modes (light/dark).',- params: {- format: {- type: 'string',- description: 'Output format',- enum: ['css', 'tailwind', 'json'],- default: 'css'- },- collection: {- type: 'string',- description: 'Filter by collection name (substring, case-insensitive)'- },- type: {- type: 'string',- description: 'Filter by variable type',- enum: ['COLOR', 'FLOAT', 'STRING', 'BOOLEAN']- }- },+ execution: { kind: 'sync', mutation: 'none' },+ exposure: { webmcp: true },+ input: v.object({+ format: v.optional(+ v.pipe(v.picklist(['css', 'tailwind', 'json']), v.description('Output format')),+ 'css'+ ),+ collection: v.optional(+ v.pipe(v.string(), v.description('Filter by collection name (substring, case-insensitive)'))+ ),+ type: v.optional(+ v.pipe(+ v.picklist(['COLOR', 'FLOAT', 'STRING', 'BOOLEAN']),+ v.description('Filter by variable type')+ )+ )+ }),execute: (figma, args) => {- const format = args.format ?? 'css'+ const format = args.formatlet variables = figma.getLocalVariables()const collections = figma.getLocalVariableCollections()diff --git a/packages/core/src/tools/create/basic.ts b/packages/core/src/tools/create/basic.tsindex fd756616b..f2035f054 100644--- a/packages/core/src/tools/create/basic.ts+++ b/packages/core/src/tools/create/basic.ts@@ -1,25 +1,26 @@+import * as v from 'valibot'+import type { FigmaNodeProxy } from '#core/figma-api'+import { toolNumber, positionInputs } from '#core/tools/input'import { defineTool, nodeSummary } from '#core/tools/schema'export const createShape = defineTool({name: 'create_shape',- mutates: true,+description:'Create a shape on the canvas. Use FRAME for containers/cards, RECTANGLE for solid blocks, ELLIPSE for circles, TEXT for labels, LINE for rules and dividers, STAR for starbursts and badges, POLYGON for triangles and regular polygons, and SECTION for page sections. Use create_vector with an SVG path for arbitrary shapes.',- params: {- type: {- type: 'string',- description: 'Node type',- required: true,- enum: ['FRAME', 'RECTANGLE', 'ELLIPSE', 'TEXT', 'LINE', 'STAR', 'POLYGON', 'SECTION']- },- x: { type: 'number', description: 'X position', required: true },- y: { type: 'number', description: 'Y position', required: true },- width: { type: 'number', description: 'Width in pixels', required: true, min: 1 },- height: { type: 'number', description: 'Height in pixels', required: true, min: 1 },- name: { type: 'string', description: 'Node name shown in layers panel' },- parent_id: { type: 'string', description: 'Parent node ID to nest inside' }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ type: v.pipe(+ v.picklist(['FRAME', 'RECTANGLE', 'ELLIPSE', 'TEXT', 'LINE', 'STAR', 'POLYGON', 'SECTION']),+ v.description('Node type')+ ),+ ...positionInputs,+ width: toolNumber(v.pipe(v.number(), v.minValue(1), v.description('Width in pixels'))),+ height: toolNumber(v.pipe(v.number(), v.minValue(1), v.description('Height in pixels'))),+ name: v.optional(v.pipe(v.string(), v.description('Node name shown in layers panel'))),+ parent_id: v.optional(v.pipe(v.string(), v.description('Parent node ID to nest inside')))+ }),execute: (figma, args) => {const parentId = args.parent_idconst parent = parentId ? figma.getNodeById(parentId) : null@@ -45,11 +46,12 @@ export const createShape = defineTool({export const createPage = defineTool({name: 'create_page',- mutates: true,+description: 'Create a new page.',- params: {- name: { type: 'string', description: 'Page name', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ name: v.pipe(v.string(), v.description('Page name'))+ }),execute: (figma, { name }) => {const page = figma.createPage()page.name = name@@ -59,16 +61,16 @@ export const createPage = defineTool({export const createSlice = defineTool({name: 'create_slice',- mutates: true,+description: 'Create a slice (export region) on the canvas.',- params: {- x: { type: 'number', description: 'X position', required: true },- y: { type: 'number', description: 'Y position', required: true },- width: { type: 'number', description: 'Width', required: true, min: 1 },- height: { type: 'number', description: 'Height', required: true, min: 1 },- name: { type: 'string', description: 'Slice name' },- parent_id: { type: 'string', description: 'Parent node ID' }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ ...positionInputs,+ width: toolNumber(v.pipe(v.number(), v.minValue(1), v.description('Width'))),+ height: toolNumber(v.pipe(v.number(), v.minValue(1), v.description('Height'))),+ name: v.optional(v.pipe(v.string(), v.description('Slice name'))),+ parent_id: v.optional(v.pipe(v.string(), v.description('Parent node ID')))+ }),execute: (figma, args) => {const node = figma.createFrame()node.x = args.xdiff --git a/packages/core/src/tools/create/components.ts b/packages/core/src/tools/create/components.tsindex b6585a42a..32a0f3400 100644--- a/packages/core/src/tools/create/components.ts+++ b/packages/core/src/tools/create/components.ts@@ -1,13 +1,17 @@+import * as v from 'valibot'+import type { FigmaComponentNode, FigmaNodeProxy } from '#core/figma-api'+import { toolNumber } from '#core/tools/input'import { defineTool, nodeSummary, requireNodes } from '#core/tools/schema'export const createComponent = defineTool({name: 'create_component',- mutates: true,+description: 'Convert a frame/group into a component.',- params: {- id: { type: 'string', description: 'Node ID to convert', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ id: v.pipe(v.string(), v.description('Node ID to convert'))+ }),execute: (figma, { id }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }@@ -18,13 +22,14 @@ export const createComponent = defineTool({export const createInstance = defineTool({name: 'create_instance',- mutates: true,+description: 'Create an instance of a component.',- params: {- component_id: { type: 'string', description: 'Component node ID', required: true },- x: { type: 'number', description: 'X position' },- y: { type: 'number', description: 'Y position' }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ component_id: v.pipe(v.string(), v.description('Component node ID')),+ x: v.optional(toolNumber(v.pipe(v.number(), v.description('X position')))),+ y: v.optional(toolNumber(v.pipe(v.number(), v.description('Y position'))))+ }),execute: (figma, args) => {const component = figma.getNodeById(args.component_id)if (!component) return { error: `Component "${args.component_id}" not found` }@@ -37,13 +42,14 @@ export const createInstance = defineTool({export const combineAsVariants = defineTool({name: 'combine_as_variants',- mutates: true,+description:'Combine components sharing a parent into a component set (variant set). Components named ' +'"Category/Value" (e.g. "Button/Primary") derive variant properties from the name segments.',- params: {- ids: { type: 'string[]', description: 'Component node IDs to combine', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ ids: v.pipe(v.array(v.string()), v.minLength(1), v.description('Component node IDs to combine'))+ }),execute: (figma, { ids }) => {const nodes = requireNodes(figma, ids)if (!nodes) return { error: 'One or more node IDs were not found' }@@ -66,17 +72,18 @@ export const combineAsVariants = defineTool({export const exposeInstanceSwap = defineTool({name: 'expose_instance_swap',- mutates: true,+description: 'Expose nested instances as an instance-swap slot on their component.',- params: {- instance_ids: { type: 'string[]', description: 'Instance node IDs', required: true },- candidate_ids: {- type: 'string[]',- description: 'Candidate component node IDs',- required: true- },- property_name: { type: 'string', description: 'Property name' }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ instance_ids: v.pipe(v.array(v.string()), v.minLength(1), v.description('Instance node IDs')),+ candidate_ids: v.pipe(+ v.array(v.string()),+ v.minLength(1),+ v.description('Candidate component node IDs')+ ),+ property_name: v.optional(v.pipe(v.string(), v.description('Property name')))+ }),execute: (figma, { instance_ids, candidate_ids, property_name }) => {const slots = instance_ids.map((id) => figma.getNodeById(id))diff --git a/packages/core/src/tools/create/icons.ts b/packages/core/src/tools/create/icons.tsindex 8f3c577d8..b2482d637 100644--- a/packages/core/src/tools/create/icons.ts+++ b/packages/core/src/tools/create/icons.ts@@ -1,20 +1,27 @@+import * as v from 'valibot'+import { parseColor } from '#core/color'import { fetchIcons, searchIconsBatch } from '#core/icons'import { createIconFromPaths } from '#core/icons/render'+import { toolNumber } from '#core/tools/input'import { defineTool } from '#core/tools/schema'export const fetchIconsTool = defineTool({name: 'fetch_icons',description:'Pre-fetch icons from Iconify into cache. Batches by prefix (one HTTP request per set). Call this once with all needed icons, then use insert_icon to place them instantly. Popular sets: lucide (outline), mdi (filled), heroicons, tabler, solar, mingcute, ri (remix).',- params: {- names: {- type: 'string[]',- description: 'Icon names as prefix:name (e.g. ["lucide:heart", "lucide:home", "mdi:star"])',- required: true- },- size: { type: 'number', description: 'Icon size in pixels (default: 24)' }- },+ execution: { kind: 'async', mutation: 'none' },+ capabilities: ['network:access'],+ input: v.object({+ names: v.pipe(+ v.array(v.string()),+ v.minLength(1),+ v.description('Icon names as prefix:name (e.g. ["lucide:heart", "lucide:home", "mdi:star"])')+ ),+ size: v.optional(+ toolNumber(v.pipe(v.number(), v.description('Icon size in pixels (default: 24)')))+ )+ }),execute: async (_figma, args) => {const size = args.size ?? 24try {@@ -32,26 +39,32 @@ export const fetchIconsTool = defineTool({export const insertIcon = defineTool({name: 'insert_icon',- mutates: true,+description:'Insert one or more vector icons onto the canvas. Pass a single name or multiple names to batch-insert into the same parent. If already cached by fetch_icons — instant, no network request.',- params: {- names: {- type: 'string[]',- description:- 'Icon names as prefix:name (e.g. ["lucide:heart"] or ["lucide:heart","lucide:home","lucide:star"])'- },- name: {- type: 'string',- description: 'Single icon name (shorthand for names with one icon)'- },- size: { type: 'number', description: 'Icon size in pixels (default: 24)' },- color: {- type: 'color',- description: 'Icon color hex (replaces currentColor). Default: #000000'- },- parent_id: { type: 'string', description: 'Parent node ID for all icons' }- },+ execution: { kind: 'async', mutation: 'document' },+ capabilities: ['document:write', 'network:access'],+ input: v.object({+ names: v.optional(+ v.pipe(+ v.array(v.string()),+ v.minLength(1),+ v.description(+ 'Icon names as prefix:name (e.g. ["lucide:heart"] or ["lucide:heart","lucide:home","lucide:star"])'+ )+ )+ ),+ name: v.optional(+ v.pipe(v.string(), v.description('Single icon name (shorthand for names with one icon)'))+ ),+ size: v.optional(+ toolNumber(v.pipe(v.number(), v.description('Icon size in pixels (default: 24)')))+ ),+ color: v.optional(+ v.pipe(v.string(), v.description('Icon color hex (replaces currentColor). Default: #000000'))+ ),+ parent_id: v.optional(v.pipe(v.string(), v.description('Parent node ID for all icons')))+ }),execute: async (figma, args) => {const names = args.names ?? (args.name ? [args.name] : [])if (names.length === 0) return { error: 'Provide "names" (array) or "name" (string)' }@@ -95,15 +108,21 @@ export const searchIconsTool = defineTool({name: 'search_icons',description:'Search Iconify for icons by keyword. Accepts multiple queries — all searched in parallel. Returns results keyed by query.',- params: {- queries: {- type: 'string[]',- description: 'Search keywords (e.g. ["heart", "arrow", "settings"])',- required: true- },- limit: { type: 'number', description: 'Max results per query (default: 5)' },- prefix: { type: 'string', description: 'Filter by icon set prefix (e.g. "lucide", "mdi")' }- },+ execution: { kind: 'async', mutation: 'none' },+ capabilities: ['network:access'],+ input: v.object({+ queries: v.pipe(+ v.array(v.string()),+ v.minLength(1),+ v.description('Search keywords (e.g. ["heart", "arrow", "settings"])')+ ),+ limit: v.optional(+ toolNumber(v.pipe(v.number(), v.description('Max results per query (default: 5)')))+ ),+ prefix: v.optional(+ v.pipe(v.string(), v.description('Filter by icon set prefix (e.g. "lucide", "mdi")'))+ )+ }),execute: async (_figma, args) => {try {const results = await searchIconsBatch(args.queries, {diff --git a/packages/core/src/tools/create/render.ts b/packages/core/src/tools/create/render.tsindex b983f29ef..863769d0b 100644--- a/packages/core/src/tools/create/render.ts+++ b/packages/core/src/tools/create/render.ts@@ -1,24 +1,36 @@+import * as v from 'valibot'++import { toolNumber } from '#core/tools/input'import { defineTool } from '#core/tools/schema'export const render = defineTool({name: 'render',- mutates: true,+description:'Render JSX to design nodes. Supports inline SVG paths, including open stroked paths: <svg viewBox="0 0 24 24" size={24}><path d="M2 12 L22 12" stroke="#000" fill="none" /></svg>. Use replace_id to replace a placeholder while preserving its position.',- params: {- replace_id: {- type: 'string',- description: 'Node ID to replace — new node takes its position in parent, old node is deleted'- },- parent_id: { type: 'string', description: 'Parent node ID to render into' },- insert_index: {- type: 'number',- description: 'Position among siblings (0 = first child). Omit to append at end.'- },- x: { type: 'number', description: 'X position of the root node' },- y: { type: 'number', description: 'Y position of the root node' },- jsx: { type: 'string', description: 'JSX string to render', required: true }- },+ execution: { kind: 'async', mutation: 'document' },+ input: v.object({+ replace_id: v.optional(+ v.pipe(+ v.string(),+ v.description(+ 'Node ID to replace — new node takes its position in parent, old node is deleted'+ )+ )+ ),+ parent_id: v.optional(v.pipe(v.string(), v.description('Parent node ID to render into'))),+ insert_index: v.optional(+ toolNumber(+ v.pipe(+ v.number(),+ v.description('Position among siblings (0 = first child). Omit to append at end.')+ )+ )+ ),+ x: v.optional(toolNumber(v.pipe(v.number(), v.description('X position of the root node')))),+ y: v.optional(toolNumber(v.pipe(v.number(), v.description('Y position of the root node')))),+ jsx: v.pipe(v.string(), v.description('JSX string to render'))+ }),execute: async (figma, args) => {const { renderJSX } = await import('#core/design-jsx/render.js')diff --git a/packages/core/src/tools/create/svg.ts b/packages/core/src/tools/create/svg.tsindex 186024563..eed5725b2 100644--- a/packages/core/src/tools/create/svg.ts+++ b/packages/core/src/tools/create/svg.ts@@ -1,26 +1,33 @@+import * as v from 'valibot'+import { createSVGNodes } from '#core/io/formats/svg'+import { toolNumber } from '#core/tools/input'import { defineTool } from '#core/tools/schema'export const importSVG = defineTool({name: 'import_svg',- mutates: true,+description:'Import raw SVG markup onto the canvas as editable vector nodes. Supports common SVG shapes, inherited presentation attributes, transforms, gradients, and internal <use> references.',- params: {- svg: {- type: 'string',- description: 'SVG markup string (e.g. \'<svg viewBox="0 0 24 24"><path d="M..."/></svg>\')',- required: true- },- name: { type: 'string', description: 'Name for the created frame (default: "SVG")' },- color: {- type: 'color',- description: 'Default color for currentColor fills/strokes (default: #000000)'- },- parent_id: { type: 'string', description: 'Parent node ID' },- x: { type: 'number', description: 'X position' },- y: { type: 'number', description: 'Y position' }- },+ execution: { kind: 'async', mutation: 'document' },+ input: v.object({+ svg: v.pipe(+ v.string(),+ v.description('SVG markup string (e.g. \'<svg viewBox="0 0 24 24"><path d="M..."/></svg>\')')+ ),+ name: v.optional(+ v.pipe(v.string(), v.description('Name for the created frame (default: "SVG")'))+ ),+ color: v.optional(+ v.pipe(+ v.string(),+ v.description('Default color for currentColor fills/strokes (default: #000000)')+ )+ ),+ parent_id: v.optional(v.pipe(v.string(), v.description('Parent node ID'))),+ x: v.optional(toolNumber(v.pipe(v.number(), v.description('X position')))),+ y: v.optional(toolNumber(v.pipe(v.number(), v.description('Y position'))))+ }),execute: async (figma, args) => {if (!args.svg || typeof args.svg !== 'string') return { error: 'svg parameter is required' }diff --git a/packages/core/src/tools/create/vector.ts b/packages/core/src/tools/create/vector.tsindex b5614d5ea..33c123f31 100644--- a/packages/core/src/tools/create/vector.ts+++ b/packages/core/src/tools/create/vector.ts@@ -1,4 +1,5 @@import { safeDestr } from 'destr'+import * as v from 'valibot'import {normalizeVectorNetwork,@@ -9,6 +10,7 @@ import type { VectorNetwork } from '@open-pencil/scene-graph'import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'import { parseColor } from '#core/color'+import { toolNumber, positionInputs } from '#core/tools/input'import { defineTool, nodeSummary } from '#core/tools/schema'import { computeAccurateBounds } from '#core/vector/curve-math'@@ -54,22 +56,25 @@ function parseVectorPath(path: string): VectorPathResult {export const createVector = defineTool({name: 'create_vector',- mutates: true,+description: 'Create a vector node from SVG path data or a VectorNetwork.',- params: {- x: { type: 'number', description: 'X position', required: true },- y: { type: 'number', description: 'Y position', required: true },- name: { type: 'string', description: 'Node name' },- path: {- type: 'string',- description:- 'SVG path data (preferred, e.g. "M0 0 L100 0 L50 80 Z") or VectorNetwork JSON, e.g. {"vertices":[{"x":0,"y":0},{"x":10,"y":0}],"segments":[{"start":0,"end":1}],"regions":[]}'- },- fill: { type: 'color', description: 'Fill color (hex)' },- stroke: { type: 'color', description: 'Stroke color (hex)' },- stroke_weight: { type: 'number', description: 'Stroke weight' },- parent_id: { type: 'string', description: 'Parent node ID' }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ ...positionInputs,+ name: v.optional(v.pipe(v.string(), v.description('Node name'))),+ path: v.optional(+ v.pipe(+ v.string(),+ v.description(+ 'SVG path data (preferred, e.g. "M0 0 L100 0 L50 80 Z") or VectorNetwork JSON, e.g. {"vertices":[{"x":0,"y":0},{"x":10,"y":0}],"segments":[{"start":0,"end":1}],"regions":[]}'+ )+ )+ ),+ fill: v.optional(v.pipe(v.string(), v.description('Fill color (hex)'))),+ stroke: v.optional(v.pipe(v.string(), v.description('Stroke color (hex)'))),+ stroke_weight: v.optional(toolNumber(v.pipe(v.number(), v.description('Stroke weight')))),+ parent_id: v.optional(v.pipe(v.string(), v.description('Parent node ID')))+ }),execute: (figma, args) => {let parsedPath: ParsedVectorPath | null = nullif (args.path !== undefined) {diff --git a/packages/core/src/tools/describe/index.ts b/packages/core/src/tools/describe/index.tsindex aae7985f8..2475e9b73 100644--- a/packages/core/src/tools/describe/index.ts+++ b/packages/core/src/tools/describe/index.ts@@ -1,3 +1,6 @@+import * as v from 'valibot'++import { toolNumber } from '#core/tools/input'import { defineTool } from '#core/tools/schema'import { autoDepth, describeOneNode } from './tree'@@ -6,12 +9,23 @@ export const describe = defineTool({name: 'describe',description:'Semantic description of one or more nodes. Pass `id` for a single node, or `ids` for multiple nodes in one call. Omit depth for auto — adapts to subtree size (small block → deeper, large page → shallower).',- params: {- id: { type: 'string', description: 'Node ID (single node)' },- ids: { type: 'string[]', description: 'Node IDs (multiple nodes in one call)' },- depth: { type: 'number', description: 'Override depth (auto if omitted, max: 5)' },- grid: { type: 'number', description: 'Grid size for alignment checks (default: 8)' }- },+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({+ id: v.optional(v.pipe(v.string(), v.description('Node ID (single node)'))),+ ids: v.optional(+ v.pipe(+ v.array(v.string()),+ v.minLength(1),+ v.description('Node IDs (multiple nodes in one call)')+ )+ ),+ depth: v.optional(+ toolNumber(v.pipe(v.number(), v.description('Override depth (auto if omitted, max: 5)')))+ ),+ grid: v.optional(+ toolNumber(v.pipe(v.number(), v.description('Grid size for alignment checks (default: 8)')))+ )+ }),execute: (figma, args) => {const gridSize = args.grid ?? 8diff --git a/packages/core/src/tools/index.ts b/packages/core/src/tools/index.tsindex d3748ca7f..783ef827e 100644--- a/packages/core/src/tools/index.ts+++ b/packages/core/src/tools/index.ts@@ -16,8 +16,9 @@ export {NodeNotFoundError,toolChangesDocument} from './schema'-export type { ToolDef, ParamDef, ParamType } from './schema'-export { toolInputEntries } from './validation'+export type { ToolDef, ToolExecution, ToolCapability } from './schema'+export { isAtomicTool } from './schema'+export { toolNumber } from './input'export { toolsToAI, buildDebugLog } from './ai-adapter'export type { ToolLogEntry, ToolDebugLog, AIAdapterOptions, StepBudget } from './ai-adapter'export { calcClusterConfidence, wrapEvalCode } from './analyze'diff --git a/packages/core/src/tools/input.ts b/packages/core/src/tools/input.tsnew file mode 100644index 000000000..629d15bd7--- /dev/null+++ b/packages/core/src/tools/input.ts@@ -0,0 +1,23 @@+import * as v from 'valibot'++export const nodeIdInput = v.pipe(v.string(), v.description('Node ID'))+export const nodeInput = v.object({ id: nodeIdInput })+export const positionInputs = {+ x: toolNumber(v.pipe(v.number(), v.description('X position'))),+ y: toolNumber(v.pipe(v.number(), v.description('Y position')))+}++/** Reuse a native number schema for both numeric and numeric-string agent inputs. */+export function toolNumber(schema: v.GenericSchema<number, number> = v.number()) {+ // JSON Schema numbers are finite. Express that with representable bounds as well as at runtime.+ const finite = v.pipe(schema, v.minValue(-Number.MAX_VALUE), v.maxValue(Number.MAX_VALUE))+ return v.union([+ finite,+ v.pipe(+ v.string(),+ v.description(v.getDescription(schema) ?? 'Numeric value'),+ v.transform(Number),+ finite+ )+ ])+}diff --git a/packages/core/src/tools/modify/effects.ts b/packages/core/src/tools/modify/effects.tsindex 090ad0028..e6d2319c2 100644--- a/packages/core/src/tools/modify/effects.ts+++ b/packages/core/src/tools/modify/effects.ts@@ -1,28 +1,34 @@+import * as v from 'valibot'+import type { Effect } from '@open-pencil/scene-graph'import { parseColor } from '#core/color'import { DEFAULT_SHADOW_COLOR, TRANSPARENT } from '#core/constants'+import { toolNumber, nodeIdInput } from '#core/tools/input'import { defineTool, nodeNotFound } from '#core/tools/schema'export const setEffects = defineTool({name: 'set_effects',- mutates: true,+description:'Set effects on a node (drop shadow, inner shadow, blur). Pass an array or a single effect.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- type: {- type: 'string',- description: 'Effect type',- required: true,- enum: ['DROP_SHADOW', 'INNER_SHADOW', 'FOREGROUND_BLUR', 'BACKGROUND_BLUR']- },- color: { type: 'color', description: 'Shadow color (hex). Ignored for blur.' },- offset_x: { type: 'number', description: 'Shadow X offset', default: 0 },- offset_y: { type: 'number', description: 'Shadow Y offset', default: 4 },- radius: { type: 'number', description: 'Blur radius', default: 4, min: 0 },- spread: { type: 'number', description: 'Shadow spread', default: 0 }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: nodeIdInput,+ type: v.pipe(+ v.picklist(['DROP_SHADOW', 'INNER_SHADOW', 'FOREGROUND_BLUR', 'BACKGROUND_BLUR']),+ v.description('Effect type')+ ),+ color: v.optional(v.pipe(v.string(), v.description('Shadow color (hex). Ignored for blur.'))),+ offset_x: v.optional(toolNumber(v.pipe(v.number(), v.description('Shadow X offset'))), 0),+ offset_y: v.optional(toolNumber(v.pipe(v.number(), v.description('Shadow Y offset'))), 4),+ radius: v.optional(+ toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Blur radius'))),+ 4+ ),+ spread: v.optional(toolNumber(v.pipe(v.number(), v.description('Shadow spread'))), 0)+ }),execute: (figma, args) => {const node = figma.getNodeById(args.id)if (!node) return nodeNotFound(args.id)@@ -34,10 +40,10 @@ export const setEffects = defineTool({const effect: Effect = {type: args.type as Effect['type'],visible: true,- radius: args.radius ?? 4,+ radius: args.radius,color,- offset: { x: isBlur ? 0 : (args.offset_x ?? 0), y: isBlur ? 0 : (args.offset_y ?? 4) },- spread: isBlur ? 0 : (args.spread ?? 0)+ offset: { x: isBlur ? 0 : args.offset_x, y: isBlur ? 0 : args.offset_y },+ spread: isBlur ? 0 : args.spread}node.effects = [...node.effects, effect]diff --git a/packages/core/src/tools/modify/geometry.ts b/packages/core/src/tools/modify/geometry.tsindex f559b106f..51ab2c83e 100644--- a/packages/core/src/tools/modify/geometry.ts+++ b/packages/core/src/tools/modify/geometry.ts@@ -1,13 +1,18 @@+import * as v from 'valibot'++import { toolNumber, nodeIdInput } from '#core/tools/input'import { defineTool, nodeNotFound } from '#core/tools/schema'export const setRotation = defineTool({name: 'set_rotation',- mutates: true,+description: 'Set rotation angle of a node in degrees.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- angle: { type: 'number', description: 'Rotation angle in degrees', required: true }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: nodeIdInput,+ angle: toolNumber(v.pipe(v.number(), v.description('Rotation angle in degrees')))+ }),execute: (figma, { id, angle }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }@@ -18,12 +23,16 @@ export const setRotation = defineTool({export const setOpacity = defineTool({name: 'set_opacity',- mutates: true,+description: 'Set opacity of a node (0-1).',- params: {- id: { type: 'string', description: 'Node ID', required: true },- value: { type: 'number', description: 'Opacity (0-1)', required: true, min: 0, max: 1 }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: nodeIdInput,+ value: toolNumber(+ v.pipe(v.number(), v.minValue(0), v.maxValue(1), v.description('Opacity (0-1)'))+ )+ }),execute: (figma, { id, value }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }@@ -34,16 +43,28 @@ export const setOpacity = defineTool({export const setRadius = defineTool({name: 'set_radius',- mutates: true,+description: 'Set corner radius. Use individual corners for independent values.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- radius: { type: 'number', description: 'Corner radius for all corners', min: 0 },- top_left: { type: 'number', description: 'Top-left radius', min: 0 },- top_right: { type: 'number', description: 'Top-right radius', min: 0 },- bottom_right: { type: 'number', description: 'Bottom-right radius', min: 0 },- bottom_left: { type: 'number', description: 'Bottom-left radius', min: 0 }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: nodeIdInput,+ radius: v.optional(+ toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Corner radius for all corners')))+ ),+ top_left: v.optional(+ toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Top-left radius')))+ ),+ top_right: v.optional(+ toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Top-right radius')))+ ),+ bottom_right: v.optional(+ toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Bottom-right radius')))+ ),+ bottom_left: v.optional(+ toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Bottom-left radius')))+ )+ }),execute: (figma, args) => {const node = figma.getNodeById(args.id)if (!node) return nodeNotFound(args.id)@@ -70,15 +91,25 @@ export const setRadius = defineTool({export const setMinMax = defineTool({name: 'set_minmax',- mutates: true,+description: 'Set min/max width and height constraints on a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- min_width: { type: 'number', description: 'Minimum width', min: 0 },- max_width: { type: 'number', description: 'Maximum width', min: 0 },- min_height: { type: 'number', description: 'Minimum height', min: 0 },- max_height: { type: 'number', description: 'Maximum height', min: 0 }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: nodeIdInput,+ min_width: v.optional(+ toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Minimum width')))+ ),+ max_width: v.optional(+ toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Maximum width')))+ ),+ min_height: v.optional(+ toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Minimum height')))+ ),+ max_height: v.optional(+ toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Maximum height')))+ )+ }),execute: (figma, args) => {const node = figma.getNodeById(args.id)if (!node) return nodeNotFound(args.id)diff --git a/packages/core/src/tools/modify/layout.ts b/packages/core/src/tools/modify/layout.tsindex cd73ea7bb..8e05ff8ed 100644--- a/packages/core/src/tools/modify/layout.ts+++ b/packages/core/src/tools/modify/layout.ts@@ -1,46 +1,67 @@+import * as v from 'valibot'+import type { SceneNode } from '@open-pencil/scene-graph'+import { toolNumber, nodeIdInput } from '#core/tools/input'import { defineTool, nodeNotFound } from '#core/tools/schema'export const setLayout = defineTool({name: 'set_layout',- mutates: true,+description: 'Set auto-layout (flexbox) on a frame. Direction, alignment, spacing, padding.',- params: {- id: { type: 'string', description: 'Frame node ID', required: true },- direction: {- type: 'string',- description: 'Layout direction (keeps current if omitted)',- enum: ['HORIZONTAL', 'VERTICAL']- },- spacing: {- type: 'number',- description: 'Gap between items (only changes if provided)',- min: 0- },- padding: {- type: 'number',- description: 'Equal padding on all sides (only changes if provided)',- min: 0- },- padding_horizontal: { type: 'number', description: 'Horizontal padding', min: 0 },- padding_vertical: { type: 'number', description: 'Vertical padding', min: 0 },- align: {- type: 'string',- description: 'Primary axis alignment (only changes if provided)',- enum: ['MIN', 'CENTER', 'MAX', 'SPACE_BETWEEN']- },- counter_align: {- type: 'string',- description: 'Cross axis alignment (only changes if provided)',- enum: ['MIN', 'CENTER', 'MAX', 'STRETCH']- },- flow_direction: {- type: 'string',- description: 'Child flow direction for auto-layout. AUTO inherits from parent.',- enum: ['AUTO', 'LTR', 'RTL']- }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: v.pipe(v.string(), v.description('Frame node ID')),+ direction: v.optional(+ v.pipe(+ v.picklist(['HORIZONTAL', 'VERTICAL']),+ v.description('Layout direction (keeps current if omitted)')+ )+ ),+ spacing: v.optional(+ toolNumber(+ v.pipe(+ v.number(),+ v.minValue(0),+ v.description('Gap between items (only changes if provided)')+ )+ )+ ),+ padding: v.optional(+ toolNumber(+ v.pipe(+ v.number(),+ v.minValue(0),+ v.description('Equal padding on all sides (only changes if provided)')+ )+ )+ ),+ padding_horizontal: v.optional(+ toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Horizontal padding')))+ ),+ padding_vertical: v.optional(+ toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Vertical padding')))+ ),+ align: v.optional(+ v.pipe(+ v.picklist(['MIN', 'CENTER', 'MAX', 'SPACE_BETWEEN']),+ v.description('Primary axis alignment (only changes if provided)')+ )+ ),+ counter_align: v.optional(+ v.pipe(+ v.picklist(['MIN', 'CENTER', 'MAX', 'STRETCH']),+ v.description('Cross axis alignment (only changes if provided)')+ )+ ),+ flow_direction: v.optional(+ v.pipe(+ v.picklist(['AUTO', 'LTR', 'RTL']),+ v.description('Child flow direction for auto-layout. AUTO inherits from parent.')+ )+ )+ }),execute: (figma, args) => {const node = figma.getNodeById(args.id)if (!node) return nodeNotFound(args.id)@@ -53,7 +74,7 @@ export const setLayout = defineTool({}const wasNone = raw?.layoutMode === 'NONE'- if (args.direction) node.layoutMode = args.direction as 'HORIZONTAL' | 'VERTICAL'+ if (args.direction) node.layoutMode = args.directionif (wasNone) {node.primaryAxisSizingMode = 'AUTO'node.counterAxisSizingMode = 'AUTO'@@ -85,21 +106,25 @@ export const setLayout = defineTool({export const setConstraints = defineTool({name: 'set_constraints',- mutates: true,+description: 'Set resize constraints for a node within its parent.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- horizontal: {- type: 'string',- description: 'Horizontal constraint',- enum: ['MIN', 'CENTER', 'MAX', 'STRETCH', 'SCALE']- },- vertical: {- type: 'string',- description: 'Vertical constraint',- enum: ['MIN', 'CENTER', 'MAX', 'STRETCH', 'SCALE']- }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: nodeIdInput,+ horizontal: v.optional(+ v.pipe(+ v.picklist(['MIN', 'CENTER', 'MAX', 'STRETCH', 'SCALE']),+ v.description('Horizontal constraint')+ )+ ),+ vertical: v.optional(+ v.pipe(+ v.picklist(['MIN', 'CENTER', 'MAX', 'STRETCH', 'SCALE']),+ v.description('Vertical constraint')+ )+ )+ }),execute: (figma, args) => {const node = figma.getNodeById(args.id)if (!node) return nodeNotFound(args.id)@@ -115,33 +140,37 @@ export const setConstraints = defineTool({export const setLayoutChild = defineTool({name: 'set_layout_child',- mutates: true,+description:'Configure auto-layout child: sizing (FIXED/HUG/FILL), grow, alignment, absolute positioning.',- params: {- id: { type: 'string', description: 'Child node ID', required: true },- sizing_horizontal: {- type: 'string',- description: 'Horizontal sizing mode',- enum: ['FIXED', 'HUG', 'FILL']- },- sizing_vertical: {- type: 'string',- description: 'Vertical sizing mode',- enum: ['FIXED', 'HUG', 'FILL']- },- grow: { type: 'number', description: 'Flex grow factor (0 = fixed, 1 = grow)', min: 0 },- align_self: {- type: 'string',- description: 'Self alignment override (cross-axis)',- enum: ['INHERIT', 'MIN', 'CENTER', 'MAX', 'STRETCH', 'BASELINE']- },- positioning: {- type: 'string',- description: 'ABSOLUTE to take node out of auto-layout flow',- enum: ['AUTO', 'ABSOLUTE']- }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: v.pipe(v.string(), v.description('Child node ID')),+ sizing_horizontal: v.optional(+ v.pipe(v.picklist(['FIXED', 'HUG', 'FILL']), v.description('Horizontal sizing mode'))+ ),+ sizing_vertical: v.optional(+ v.pipe(v.picklist(['FIXED', 'HUG', 'FILL']), v.description('Vertical sizing mode'))+ ),+ grow: v.optional(+ toolNumber(+ v.pipe(v.number(), v.minValue(0), v.description('Flex grow factor (0 = fixed, 1 = grow)'))+ )+ ),+ align_self: v.optional(+ v.pipe(+ v.picklist(['INHERIT', 'MIN', 'CENTER', 'MAX', 'STRETCH', 'BASELINE']),+ v.description('Self alignment override (cross-axis)')+ )+ ),+ positioning: v.optional(+ v.pipe(+ v.picklist(['AUTO', 'ABSOLUTE']),+ v.description('ABSOLUTE to take node out of auto-layout flow')+ )+ )+ }),execute: (figma, args) => {const node = figma.getNodeById(args.id)if (!node) return nodeNotFound(args.id)diff --git a/packages/core/src/tools/modify/paint.ts b/packages/core/src/tools/modify/paint.tsindex 67be68e90..8f37e73f6 100644--- a/packages/core/src/tools/modify/paint.ts+++ b/packages/core/src/tools/modify/paint.ts@@ -1,29 +1,33 @@+import * as v from 'valibot'+import type { Matrix } from '@open-pencil/scene-graph/primitives'import { decodeBase64 } from '#core/bytes'import { parseColor } from '#core/color'import { BLACK } from '#core/constants'+import { toolNumber, nodeIdInput } from '#core/tools/input'import { defineTool } from '#core/tools/schema'export const setFill = defineTool({name: 'set_fill',- mutates: true,+description:'Set fill on a node. Solid: color="#ff0000". Linear gradient: gradient="top-bottom" or "left-right" with color (start) and color_end (end).',- params: {- id: { type: 'string', description: 'Node ID', required: true },- color: {- type: 'color',- description: 'Color (hex). For gradient: start color.',- required: true- },- color_end: { type: 'color', description: 'End color for gradient (if omitted, solid fill)' },- gradient: {- type: 'string',- description: 'Gradient direction',- enum: ['top-bottom', 'bottom-top', 'left-right', 'right-left']- }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: nodeIdInput,+ color: v.pipe(v.string(), v.description('Color (hex). For gradient: start color.')),+ color_end: v.optional(+ v.pipe(v.string(), v.description('End color for gradient (if omitted, solid fill)'))+ ),+ gradient: v.optional(+ v.pipe(+ v.picklist(['top-bottom', 'bottom-top', 'left-right', 'right-left']),+ v.description('Gradient direction')+ )+ )+ }),execute: (figma, { id, color, color_end, gradient }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }@@ -61,19 +65,22 @@ export const setFill = defineTool({export const setStroke = defineTool({name: 'set_stroke',- mutates: true,+description: 'Set the stroke (border) of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- color: { type: 'color', description: 'Stroke color (hex)', required: true },- weight: { type: 'number', description: 'Stroke weight', default: 1, min: 0.1 },- align: {- type: 'string',- description: 'Stroke alignment',- default: 'INSIDE',- enum: ['INSIDE', 'CENTER', 'OUTSIDE']- }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: nodeIdInput,+ color: v.pipe(v.string(), v.description('Stroke color (hex)')),+ weight: v.optional(+ toolNumber(v.pipe(v.number(), v.minValue(0.1), v.description('Stroke weight'))),+ 1+ ),+ align: v.optional(+ v.pipe(v.picklist(['INSIDE', 'CENTER', 'OUTSIDE']), v.description('Stroke alignment')),+ 'INSIDE'+ )+ }),execute: (figma, { id, color, weight, align }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }@@ -82,40 +89,38 @@ export const setStroke = defineTool({node.strokes = [{color: c,- weight: weight ?? 1,+ weight: weight,opacity: 1,visible: true,- align: (align ?? 'INSIDE') as 'INSIDE' | 'CENTER' | 'OUTSIDE'+ align}]- return { id, color: c, weight: weight ?? 1 }+ return { id, color: c, weight: weight }}})export const setImageFill = defineTool({name: 'set_image_fill',- mutates: true,+description: 'Set an image fill on a node from base64-encoded image data.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- image_data: {- type: 'string',- description: 'Base64-encoded image bytes (PNG, JPEG, or WEBP)',- required: true- },- scale_mode: {- type: 'string',- description: 'Image scale mode',- default: 'FILL',- enum: ['FILL', 'FIT', 'CROP', 'TILE']- }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ id: nodeIdInput,+ image_data: v.pipe(+ v.string(),+ v.description('Base64-encoded image bytes (PNG, JPEG, or WEBP)')+ ),+ scale_mode: v.optional(+ v.pipe(v.picklist(['FILL', 'FIT', 'CROP', 'TILE']), v.description('Image scale mode')),+ 'FILL'+ )+ }),execute: (figma, { id, image_data, scale_mode }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }const bytes = decodeBase64(image_data)const image = figma.createImage(bytes)- const mode = (scale_mode ?? 'FILL') as 'FILL' | 'FIT' | 'CROP' | 'TILE'+ const mode = scale_modenode.fills = [{type: 'IMAGE',diff --git a/packages/core/src/tools/modify/state.ts b/packages/core/src/tools/modify/state.tsindex e7722022b..105f35041 100644--- a/packages/core/src/tools/modify/state.ts+++ b/packages/core/src/tools/modify/state.ts@@ -1,13 +1,18 @@+import * as v from 'valibot'++import { nodeIdInput } from '#core/tools/input'import { defineTool } from '#core/tools/schema'export const setVisible = defineTool({name: 'set_visible',- mutates: true,+description: 'Set visibility of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- value: { type: 'boolean', description: 'Visible (true/false)', required: true }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: nodeIdInput,+ value: v.pipe(v.boolean(), v.description('Visible (true/false)'))+ }),execute: (figma, { id, value }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }@@ -18,15 +23,14 @@ export const setVisible = defineTool({export const setBlend = defineTool({name: 'set_blend',- mutates: true,+description: 'Set blend mode of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- mode: {- type: 'string',- description: 'Blend mode',- required: true,- enum: [+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: nodeIdInput,+ mode: v.pipe(+ v.picklist(['NORMAL','DARKEN','MULTIPLY',@@ -43,9 +47,10 @@ export const setBlend = defineTool({'SATURATION','COLOR','LUMINOSITY'- ]- }- },+ ]),+ v.description('Blend mode')+ )+ }),execute: (figma, { id, mode }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }@@ -56,12 +61,14 @@ export const setBlend = defineTool({export const setLocked = defineTool({name: 'set_locked',- mutates: true,+description: 'Set locked state of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- value: { type: 'boolean', description: 'Locked (true/false)', required: true }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: nodeIdInput,+ value: v.pipe(v.boolean(), v.description('Locked (true/false)'))+ }),execute: (figma, { id, value }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }@@ -72,17 +79,14 @@ export const setLocked = defineTool({export const setStrokeAlign = defineTool({name: 'set_stroke_align',- mutates: true,+description: 'Set stroke alignment of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- align: {- type: 'string',- description: 'Stroke alignment',- required: true,- enum: ['INSIDE', 'CENTER', 'OUTSIDE']- }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: nodeIdInput,+ align: v.pipe(v.picklist(['INSIDE', 'CENTER', 'OUTSIDE']), v.description('Stroke alignment'))+ }),execute: (figma, { id, align }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }diff --git a/packages/core/src/tools/modify/text.ts b/packages/core/src/tools/modify/text.tsindex e933312ce..4963a509b 100644--- a/packages/core/src/tools/modify/text.ts+++ b/packages/core/src/tools/modify/text.ts@@ -1,18 +1,23 @@+import * as v from 'valibot'+import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph'import { parseColor } from '#core/color'import { styleToWeight } from '#core/text/fonts'import { applyStyleToRange } from '#core/text/style-runs'+import { toolNumber, nodeIdInput } from '#core/tools/input'import { defineTool, nodeNotFound } from '#core/tools/schema'export const setText = defineTool({name: 'set_text',- mutates: true,+description: 'Set text content of a text node.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- text: { type: 'string', description: 'Text content', required: true }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: nodeIdInput,+ text: v.pipe(v.string(), v.description('Text content'))+ }),execute: (figma, { id, text }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }@@ -23,14 +28,18 @@ export const setText = defineTool({export const setFont = defineTool({name: 'set_font',- mutates: true,+description: 'Set font properties of a text node.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- family: { type: 'string', description: 'Font family name' },- size: { type: 'number', description: 'Font size', min: 1 },- style: { type: 'string', description: 'Font style (e.g. "Bold", "Regular", "Bold Italic")' }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: nodeIdInput,+ family: v.optional(v.pipe(v.string(), v.description('Font family name'))),+ size: v.optional(toolNumber(v.pipe(v.number(), v.minValue(1), v.description('Font size')))),+ style: v.optional(+ v.pipe(v.string(), v.description('Font style (e.g. "Bold", "Regular", "Bold Italic")'))+ )+ }),execute: (figma, args) => {const node = figma.getNodeById(args.id)if (!node) return nodeNotFound(args.id)@@ -48,17 +57,19 @@ export const setFont = defineTool({export const setFontRange = defineTool({name: 'set_font_range',- mutates: true,+description: 'Set font properties for a text range.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- start: { type: 'number', description: 'Start character index', required: true, min: 0 },- end: { type: 'number', description: 'End character index', required: true, min: 0 },- family: { type: 'string', description: 'Font family name' },- size: { type: 'number', description: 'Font size', min: 1 },- style: { type: 'string', description: 'Font style' },- color: { type: 'color', description: 'Text color (hex)' }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: nodeIdInput,+ start: toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Start character index'))),+ end: toolNumber(v.pipe(v.number(), v.minValue(0), v.description('End character index'))),+ family: v.optional(v.pipe(v.string(), v.description('Font family name'))),+ size: v.optional(toolNumber(v.pipe(v.number(), v.minValue(1), v.description('Font size')))),+ style: v.optional(v.pipe(v.string(), v.description('Font style'))),+ color: v.optional(v.pipe(v.string(), v.description('Text color (hex)')))+ }),execute: (figma, args) => {const node = figma.getNodeById(args.id)if (!node) return nodeNotFound(args.id)@@ -83,17 +94,17 @@ export const setFontRange = defineTool({export const setTextResize = defineTool({name: 'set_text_resize',- mutates: true,+description: 'Set text auto-resize mode.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- mode: {- type: 'string',- description: 'Resize mode',- required: true,- enum: ['NONE', 'WIDTH_AND_HEIGHT', 'HEIGHT', 'TRUNCATE']- }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: nodeIdInput,+ mode: v.pipe(+ v.picklist(['NONE', 'WIDTH_AND_HEIGHT', 'HEIGHT', 'TRUNCATE']),+ v.description('Resize mode')+ )+ }),execute: (figma, { id, mode }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }@@ -104,37 +115,35 @@ export const setTextResize = defineTool({export const setTextProperties = defineTool({name: 'set_text_properties',- mutates: true,+description:'Set text layout properties: alignment, auto-resize, text case, decoration, truncation.',- params: {- id: { type: 'string', description: 'Text node ID', required: true },- align_horizontal: {- type: 'string',- description: 'Horizontal text alignment',- enum: ['LEFT', 'CENTER', 'RIGHT', 'JUSTIFIED']- },- align_vertical: {- type: 'string',- description: 'Vertical text alignment',- enum: ['TOP', 'CENTER', 'BOTTOM']- },- auto_resize: {- type: 'string',- description: 'Text auto-resize mode',- enum: ['NONE', 'WIDTH_AND_HEIGHT', 'HEIGHT', 'TRUNCATE']- },- direction: {- type: 'string',- description: 'Text direction',- enum: ['AUTO', 'LTR', 'RTL']- },- text_decoration: {- type: 'string',- description: 'Text decoration',- enum: ['NONE', 'UNDERLINE', 'STRIKETHROUGH']- }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: v.pipe(v.string(), v.description('Text node ID')),+ align_horizontal: v.optional(+ v.pipe(+ v.picklist(['LEFT', 'CENTER', 'RIGHT', 'JUSTIFIED']),+ v.description('Horizontal text alignment')+ )+ ),+ align_vertical: v.optional(+ v.pipe(v.picklist(['TOP', 'CENTER', 'BOTTOM']), v.description('Vertical text alignment'))+ ),+ auto_resize: v.optional(+ v.pipe(+ v.picklist(['NONE', 'WIDTH_AND_HEIGHT', 'HEIGHT', 'TRUNCATE']),+ v.description('Text auto-resize mode')+ )+ ),+ direction: v.optional(+ v.pipe(v.picklist(['AUTO', 'LTR', 'RTL']), v.description('Text direction'))+ ),+ text_decoration: v.optional(+ v.pipe(v.picklist(['NONE', 'UNDERLINE', 'STRIKETHROUGH']), v.description('Text decoration'))+ )+ }),execute: (figma, args) => {const node = figma.getNodeById(args.id)if (!node) return nodeNotFound(args.id)diff --git a/packages/core/src/tools/modify/update.ts b/packages/core/src/tools/modify/update.tsindex c4b0c028d..7e3c8206b 100644--- a/packages/core/src/tools/modify/update.ts+++ b/packages/core/src/tools/modify/update.ts@@ -1,37 +1,47 @@+import * as v from 'valibot'+import type { SceneNode } from '@open-pencil/scene-graph'import { assertNodeEditable } from '#core/editor/capabilities'+import { toolNumber, nodeIdInput } from '#core/tools/input'import { defineTool, nodeNotFound } from '#core/tools/schema'export const updateNode = defineTool({name: 'update_node',- mutates: true,+description:'Update properties of an existing node: position, size, opacity, corner radius, visibility, text, font.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- x: { type: 'number', description: 'X position' },- y: { type: 'number', description: 'Y position' },- width: { type: 'number', description: 'Width', min: 1 },- height: { type: 'number', description: 'Height', min: 1 },- opacity: { type: 'number', description: 'Opacity (0-1)', min: 0, max: 1 },- corner_radius: { type: 'number', description: 'Corner radius', min: 0 },- visible: { type: 'boolean', description: 'Visibility' },- text: { type: 'string', description: 'Text content (TEXT nodes)' },- text_direction: {- type: 'string',- description: 'Text direction for TEXT nodes',- enum: ['AUTO', 'LTR', 'RTL']- },- flow_direction: {- type: 'string',- description: 'Auto-layout flow direction for FRAME nodes',- enum: ['AUTO', 'LTR', 'RTL']- },- font_size: { type: 'number', description: 'Font size', min: 1 },- font_weight: { type: 'number', description: 'Font weight (100-900)' },- name: { type: 'string', description: 'Layer name' }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: nodeIdInput,+ x: v.optional(toolNumber(v.pipe(v.number(), v.description('X position')))),+ y: v.optional(toolNumber(v.pipe(v.number(), v.description('Y position')))),+ width: v.optional(toolNumber(v.pipe(v.number(), v.minValue(1), v.description('Width')))),+ height: v.optional(toolNumber(v.pipe(v.number(), v.minValue(1), v.description('Height')))),+ opacity: v.optional(+ toolNumber(v.pipe(v.number(), v.minValue(0), v.maxValue(1), v.description('Opacity (0-1)')))+ ),+ corner_radius: v.optional(+ toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Corner radius')))+ ),+ visible: v.optional(v.pipe(v.boolean(), v.description('Visibility'))),+ text: v.optional(v.pipe(v.string(), v.description('Text content (TEXT nodes)'))),+ text_direction: v.optional(+ v.pipe(v.picklist(['AUTO', 'LTR', 'RTL']), v.description('Text direction for TEXT nodes'))+ ),+ flow_direction: v.optional(+ v.pipe(+ v.picklist(['AUTO', 'LTR', 'RTL']),+ v.description('Auto-layout flow direction for FRAME nodes')+ )+ ),+ font_size: v.optional(+ toolNumber(v.pipe(v.number(), v.minValue(1), v.description('Font size')))+ ),+ font_weight: v.optional(toolNumber(v.pipe(v.number(), v.description('Font weight (100-900)')))),+ name: v.optional(v.pipe(v.string(), v.description('Layer name')))+ }),execute: (figma, args) => {const node = figma.getNodeById(args.id)if (!node) return nodeNotFound(args.id)diff --git a/packages/core/src/tools/read/components.ts b/packages/core/src/tools/read/components.tsindex 59e5e0254..11d700fcb 100644--- a/packages/core/src/tools/read/components.ts+++ b/packages/core/src/tools/read/components.ts@@ -1,4 +1,7 @@+import * as v from 'valibot'+import { getComponentCatalog } from '#core/tools/component-catalog'+import { toolNumber } from '#core/tools/input'import { defineTool } from '#core/tools/schema'interface DocumentComponentResult {@@ -26,20 +29,24 @@ export const getComponents = defineTool({name: 'get_components',description:'List reusable components from the document and enabled component libraries, optionally filtered by name.',- params: {- name: { type: 'string', description: 'Filter by name (case-insensitive substring)' },- source: {- type: 'string',- description: 'Component source',- enum: ['all', 'document', 'libraries'],- default: 'all'- },- library_id: { type: 'string', description: 'Filter library components by library ID' },- limit: { type: 'number', description: 'Max results (default: 50)' }- },+ execution: { kind: 'async', mutation: 'none' },+ exposure: { webmcp: true },+ input: v.object({+ name: v.optional(+ v.pipe(v.string(), v.description('Filter by name (case-insensitive substring)'))+ ),+ source: v.optional(+ v.pipe(v.picklist(['all', 'document', 'libraries']), v.description('Component source')),+ 'all'+ ),+ library_id: v.optional(+ v.pipe(v.string(), v.description('Filter library components by library ID'))+ ),+ limit: v.optional(toolNumber(v.pipe(v.number(), v.description('Max results (default: 50)'))))+ }),execute: async (figma, args) => {const limit = args.limit ?? 50- const source = args.source ?? 'all'+ const source = args.sourceconst nameFilter = args.name?.toLowerCase()const documentComponents: DocumentComponentResult[] = []diff --git a/packages/core/src/tools/read/fonts.ts b/packages/core/src/tools/read/fonts.tsindex 5b466b21e..279aca8bc 100644--- a/packages/core/src/tools/read/fonts.ts+++ b/packages/core/src/tools/read/fonts.ts@@ -1,4 +1,5 @@import { uniq } from 'es-toolkit/array'+import * as v from 'valibot'import { defineTool } from '#core/tools/schema'@@ -7,16 +8,18 @@ export const getFontStatus = defineTool({description:'Report whether fonts used on the current page are faithfully available. Returns requested ' +'faces, their loaded source, active substitutions, and affected nodes.',- params: {},+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({}),execute: (figma) => figma.getFontStatus()})export const listFonts = defineTool({name: 'list_fonts',description: 'List fonts used in the current page.',- params: {- family: { type: 'string', description: 'Filter by family name (substring)' }- },+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({+ family: v.optional(v.pipe(v.string(), v.description('Filter by family name (substring)')))+ }),execute: (figma, args) => {const fonts = new Map<string, Set<number>>()const page = figma.currentPage@@ -49,9 +52,12 @@ export const listAvailableFonts = defineTool({'List font families the host can render (system fonts on desktop plus any bundled fonts). ' +'Use this to discover what fonts are available to set on a text node — distinct from list_fonts ' +'which only reports families currently used in the page.',- params: {- family: { type: 'string', description: 'Filter by family name (substring, case-insensitive)' }- },+ execution: { kind: 'async', mutation: 'none' },+ input: v.object({+ family: v.optional(+ v.pipe(v.string(), v.description('Filter by family name (substring, case-insensitive)'))+ )+ }),execute: async (figma, args) => {const fonts = await figma.listAvailableFontsAsync()let families = uniq(fonts.map((font) => font.fontName.family))diff --git a/packages/core/src/tools/read/jsx.ts b/packages/core/src/tools/read/jsx.tsindex 5be756d8a..7db226058 100644--- a/packages/core/src/tools/read/jsx.ts+++ b/packages/core/src/tools/read/jsx.ts@@ -1,6 +1,8 @@import { createTwoFilesPatch } from 'diff'+import * as v from 'valibot'import { sceneNodeToJSX } from '#core/io/formats/jsx'+import { nodeIdInput } from '#core/tools/input'import { defineTool } from '#core/tools/schema'const MAX_JSX_LENGTH = 12_000@@ -9,13 +11,19 @@ export const getJSX = defineTool({name: 'get_jsx',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 },- path: {- type: 'string',- description: 'Write JSX to this path instead of returning it (requires OPENPENCIL_MCP_ROOT)'- }- },+ execution: { kind: 'sync', mutation: 'none' },+ exposure: { webmcp: true },+ input: v.object({+ id: nodeIdInput,+ path: v.optional(+ v.pipe(+ v.string(),+ v.description(+ 'Write JSX to this path instead of returning it (requires OPENPENCIL_MCP_ROOT)'+ )+ )+ )+ }),execute: (figma, { id }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }@@ -37,10 +45,11 @@ export const diffJSX = defineTool({name: 'diff_jsx',description:'Structural diff between two nodes in JSX format. Shows added/removed children, changed props.',- params: {- from: { type: 'string', description: 'Source node ID', required: true },- to: { type: 'string', description: 'Target node ID', required: true }- },+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({+ from: v.pipe(v.string(), v.description('Source node ID')),+ to: v.pipe(v.string(), v.description('Target node ID'))+ }),execute: (figma, { from, to }) => {const fromNode = figma.getNodeById(from)if (!fromNode) return { error: `Node "${from}" not found` }diff --git a/packages/core/src/tools/read/libraries.ts b/packages/core/src/tools/read/libraries.tsindex 346622fdb..34b2926cf 100644--- a/packages/core/src/tools/read/libraries.ts+++ b/packages/core/src/tools/read/libraries.ts@@ -1,10 +1,14 @@+import * as v from 'valibot'+import { getComponentCatalog } from '#core/tools/component-catalog'+import { toolNumber } from '#core/tools/input'import { defineTool } from '#core/tools/schema'export const listLibraries = defineTool({name: 'list_libraries',description: 'List available published component libraries.',- params: {},+ execution: { kind: 'async', mutation: 'none' },+ input: v.object({}),execute: async (figma) => {const catalog = getComponentCatalog(figma.graph)const libraries = catalog ? await catalog.listLibraries() : []@@ -16,19 +20,19 @@ export const insertLibraryComponent = defineTool({name: 'insert_library_component',description:'Insert a reusable component from an enabled library by stable library and asset identity.',- mutates: true,- params: {- library_id: { type: 'string', description: 'Library ID', required: true },- revision_id: { type: 'string', description: 'Pinned revision ID' },- asset_key: { type: 'string', description: 'Stable asset key', required: true },- parent_id: { type: 'string', description: 'Optional parent node ID' },- x: { type: 'number', description: 'X position' },- y: { type: 'number', description: 'Y position' },- variant_values: {- type: 'string',- description: 'Optional JSON object of variant property values'- }- },++ execution: { kind: 'async', mutation: 'document' },+ input: v.object({+ library_id: v.pipe(v.string(), v.description('Library ID')),+ revision_id: v.optional(v.pipe(v.string(), v.description('Pinned revision ID'))),+ asset_key: v.pipe(v.string(), v.description('Stable asset key')),+ parent_id: v.optional(v.pipe(v.string(), v.description('Optional parent node ID'))),+ x: v.optional(toolNumber(v.pipe(v.number(), v.description('X position')))),+ y: v.optional(toolNumber(v.pipe(v.number(), v.description('Y position')))),+ variant_values: v.optional(+ v.pipe(v.string(), v.description('Optional JSON object of variant property values'))+ )+ }),execute: async (figma, args) => {const catalog = getComponentCatalog(figma.graph)if (!catalog) throw new Error('No component library catalog is configured')diff --git a/packages/core/src/tools/read/nodes.ts b/packages/core/src/tools/read/nodes.tsindex 5fee785c6..c5048737e 100644--- a/packages/core/src/tools/read/nodes.ts+++ b/packages/core/src/tools/read/nodes.ts@@ -1,4 +1,7 @@+import * as v from 'valibot'+import type { FigmaNodeProxy } from '#core/figma-api'+import { toolNumber, nodeIdInput } from '#core/tools/input'import { defineTool, nodeSummary, nodeToResult } from '#core/tools/schema'interface TreeEntry {@@ -42,21 +45,34 @@ export const getPageTree = defineTool({name: 'get_page_tree',description:'Get the node tree of the current page. Returns lightweight hierarchy: id, type, name, size. Use depth, root_id, or node_types to keep large pages small. Use get_node for full properties of a specific node.',- params: {- depth: {- type: 'number',- description: 'Max nesting depth to return (1 = returned root nodes only). Default: unlimited',- min: 1- },- root_id: {- type: 'string',- description: 'Return only this node subtree instead of the whole current page'- },- node_types: {- type: 'string[]',- description: 'Keep only these node types and their ancestors, for example FRAME or TEXT'- }- },+ execution: { kind: 'sync', mutation: 'none' },+ exposure: { webmcp: true },+ input: v.object({+ depth: v.optional(+ toolNumber(+ v.pipe(+ v.number(),+ v.minValue(1),+ v.description(+ 'Max nesting depth to return (1 = returned root nodes only). Default: unlimited'+ )+ )+ )+ ),+ root_id: v.optional(+ v.pipe(+ v.string(),+ v.description('Return only this node subtree instead of the whole current page')+ )+ ),+ node_types: v.optional(+ v.pipe(+ v.array(v.string()),+ v.minLength(1),+ v.description('Keep only these node types and their ancestors, for example FRAME or TEXT')+ )+ )+ }),execute: (figma, { depth, root_id, node_types }) => {const typeFilter = node_types && node_types.length > 0 ? new Set(node_types) : undefined@@ -80,13 +96,19 @@ export const getNode = defineTool({name: 'get_node',description:'Get detailed properties of a node by ID. Use depth to limit child recursion (0 = node only, 1 = direct children, etc). Default: unlimited.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- depth: {- type: 'number',- description: 'Max depth of children to include (0 = no children). Default: unlimited'- }- },+ execution: { kind: 'sync', mutation: 'none' },+ exposure: { webmcp: true },+ input: v.object({+ id: nodeIdInput,+ depth: v.optional(+ toolNumber(+ v.pipe(+ v.number(),+ v.description('Max depth of children to include (0 = no children). Default: unlimited')+ )+ )+ )+ }),execute: (figma, { id, depth }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }@@ -97,27 +119,32 @@ export const getNode = defineTool({export const findNodes = defineTool({name: 'find_nodes',description: 'Find nodes by name pattern and/or type.',- params: {- name: { type: 'string', description: 'Name substring to match (case-insensitive)' },- type: {- type: 'string',- description: 'Node type filter',- enum: [- 'FRAME',- 'RECTANGLE',- 'ELLIPSE',- 'TEXT',- 'LINE',- 'STAR',- 'POLYGON',- 'SECTION',- 'GROUP',- 'COMPONENT',- 'INSTANCE',- 'VECTOR'- ]- }- },+ execution: { kind: 'sync', mutation: 'none' },+ exposure: { webmcp: true },+ input: v.object({+ name: v.optional(+ v.pipe(v.string(), v.description('Name substring to match (case-insensitive)'))+ ),+ type: v.optional(+ v.pipe(+ v.picklist([+ 'FRAME',+ 'RECTANGLE',+ 'ELLIPSE',+ 'TEXT',+ 'LINE',+ 'STAR',+ 'POLYGON',+ 'SECTION',+ 'GROUP',+ 'COMPONENT',+ 'INSTANCE',+ 'VECTOR'+ ]),+ v.description('Node type filter')+ )+ )+ }),execute: (figma, args) => {const page = figma.currentPageconst matches = page.findAll((node) => {diff --git a/packages/core/src/tools/read/pages.ts b/packages/core/src/tools/read/pages.tsindex 83b72af0a..41a5df5a8 100644--- a/packages/core/src/tools/read/pages.ts+++ b/packages/core/src/tools/read/pages.ts@@ -1,3 +1,5 @@+import * as v from 'valibot'+import { computeBounds } from '@open-pencil/scene-graph/geometry'import { defineTool } from '#core/tools/schema'@@ -5,7 +7,9 @@ import { defineTool } from '#core/tools/schema'export const listPages = defineTool({name: 'list_pages',description: 'List all pages in the document.',- params: {},+ execution: { kind: 'sync', mutation: 'none' },+ exposure: { webmcp: true },+ input: v.object({}),execute: (figma) => {const pages = figma.root.childrenreturn {@@ -17,12 +21,12 @@ export const listPages = defineTool({export const switchPage = defineTool({name: 'switch_page',- mutates: true,- changesDocument: false,+description: 'Switch to a different page by name or ID.',- params: {- page: { type: 'string', description: 'Page name or ID', required: true }- },+ execution: { kind: 'sync', mutation: 'view' },+ input: v.object({+ page: v.pipe(v.string(), v.description('Page name or ID'))+ }),execute: (figma, { page }) => {const target =figma.root.children.find((candidate) => candidate.name === page) ?? figma.getNodeById(page)@@ -35,7 +39,9 @@ export const switchPage = defineTool({export const getCurrentPage = defineTool({name: 'get_current_page',description: 'Get the current page name and ID.',- params: {},+ execution: { kind: 'sync', mutation: 'none' },+ exposure: { webmcp: true },+ input: v.object({}),execute: (figma) => {return { id: figma.currentPage.id, name: figma.currentPage.name }}@@ -44,7 +50,8 @@ export const getCurrentPage = defineTool({export const pageBounds = defineTool({name: 'page_bounds',description: 'Get bounding box of all objects on the current page.',- params: {},+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({}),execute: (figma) => {return computeBounds(figma.currentPage.children.map((child) => child.absoluteBoundingBox))}diff --git a/packages/core/src/tools/read/query.ts b/packages/core/src/tools/read/query.tsindex d01ffbe90..df8aa349d 100644--- a/packages/core/src/tools/read/query.ts+++ b/packages/core/src/tools/read/query.ts@@ -1,3 +1,6 @@+import * as v from 'valibot'++import { toolNumber } from '#core/tools/input'import { defineTool } from '#core/tools/schema'import { queryByXPath } from '#core/xpath'@@ -6,18 +9,19 @@ export const queryNodes = defineTool({description: `Query nodes using XPath selectors. Node types are element names (FRAME, TEXT, RECTANGLE, ELLIPSE, etc.). Attributes: name, width, height, x, y, visible, opacity, cornerRadius, fontSize, fontFamily, fontWeight, layoutMode, itemSpacing, paddingTop/Right/Bottom/Left, strokeWeight, rotation, locked, blendMode, text, lineHeight, letterSpacing.Examples:- //FRAME — all frames- //FRAME[@width < 300] — frames narrower than 300px- //COMPONENT[starts-with(@name, 'Button')] — components starting with "Button"- //SECTION/FRAME — direct frame children of sections- //SECTION//TEXT — all text nodes inside sections- //*[@cornerRadius > 0] — any node with corner radius- //TEXT[contains(@text, 'Hello')] — text nodes containing "Hello"`,- params: {- selector: { type: 'string', description: 'XPath selector', required: true },- page: { type: 'string', description: 'Page name (default: current page)' },- limit: { type: 'number', description: 'Max results (default: 1000)' }- },+//FRAME — all frames+//FRAME[@width < 300] — frames narrower than 300px+//COMPONENT[starts-with(@name, 'Button')] — components starting with "Button"+//SECTION/FRAME — direct frame children of sections+//SECTION//TEXT — all text nodes inside sections+//*[@cornerRadius > 0] — any node with corner radius+//TEXT[contains(@text, 'Hello')] — text nodes containing "Hello"`,+ execution: { kind: 'async', mutation: 'none' },+ input: v.object({+ selector: v.pipe(v.string(), v.description('XPath selector')),+ page: v.optional(v.pipe(v.string(), v.description('Page name (default: current page)'))),+ limit: v.optional(toolNumber(v.pipe(v.number(), v.description('Max results (default: 1000)'))))+ }),execute: async (figma, args) => {try {const nodes = await queryByXPath(figma.graph, args.selector, {diff --git a/packages/core/src/tools/read/selection.ts b/packages/core/src/tools/read/selection.tsindex ae43fd993..09d9374c1 100644--- a/packages/core/src/tools/read/selection.ts+++ b/packages/core/src/tools/read/selection.ts@@ -1,10 +1,13 @@+import * as v from 'valibot'+import type { FigmaNodeProxy } from '#core/figma-api'import { defineTool, nodeToResult } from '#core/tools/schema'export const getSelection = defineTool({name: 'get_selection',description: 'Get details about currently selected nodes.',- params: {},+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({}),execute: (figma) => {const selection = figma.currentPage.selectionreturn { selection: selection.map(nodeToResult) }@@ -13,12 +16,12 @@ export const getSelection = defineTool({export const selectNodes = defineTool({name: 'select_nodes',- mutates: true,- changesDocument: false,+description: 'Select one or more nodes by ID.',- params: {- ids: { type: 'string[]', description: 'Node IDs to select', required: true }- },+ execution: { kind: 'sync', mutation: 'view' },+ input: v.object({+ ids: v.pipe(v.array(v.string()), v.minLength(1), v.description('Node IDs to select'))+ }),execute: (figma, { ids }) => {figma.currentPage.selection = ids.map((id) => figma.getNodeById(id))diff --git a/packages/core/src/tools/schema.ts b/packages/core/src/tools/schema.tsindex 98e7ea757..a4bb2c24f 100644--- a/packages/core/src/tools/schema.ts+++ b/packages/core/src/tools/schema.ts@@ -1,69 +1,75 @@/*** Tool definition schema.*- * Each tool is defined once with typed params and an execute function- * that operates on FigmaAPI. Adapters for AI chat (valibot), CLI (citty),- * and MCP (JSON Schema) are generated from these definitions.+ * Native Valibot inputs and execution capabilities are owned by each tool.+ * Adapters consume these contracts rather than maintaining transport-specific schemas.*/+import * as v from 'valibot'+import type { SceneNode } from '@open-pencil/scene-graph'import type { FigmaAPI, FigmaNodeProxy } from '#core/figma-api'-export type ParamType = 'string' | 'number' | 'boolean' | 'color' | 'string[]'+export type ToolCapability =+ | 'document:read'+ | 'document:write'+ | 'filesystem:read'+ | 'filesystem:write'+ | 'network:access'+ | 'code:execute'-export interface ParamDef {- type: ParamType- description: string- required?: boolean- default?: unknown- enum?: string[]- min?: number- max?: number-}+export type ToolExecution =+ | { kind: 'sync'; mutation: 'none' | 'view' | 'properties' | 'document' }+ | { kind: 'async'; mutation: 'none' | 'view' | 'document' }-export interface ToolDef {+interface ToolMetadata {name: stringdescription: string- /** Whether execution changes persisted document content. Defaults to `mutates`. */- changesDocument?: boolean- mutates?: boolean- params: Record<string, ParamDef>+ execution: ToolExecution+ /** Explicit browser opt-in, independent of execution or read-only status. */+ exposure: { webmcp: boolean }+ capabilities: readonly ToolCapability[]+ availability: 'default' | 'eval'+}++export interface ToolDef extends ToolMetadata {+ input: v.ObjectSchema<v.ObjectEntries, undefined>+ /** Derived from execution metadata, never declared independently by a tool. */+ readonly mutates: booleanexecute: (figma: FigmaAPI, args: Record<string, unknown>) => unknown}-type ResolvedType<T extends ParamType> = T extends 'string'- ? string- : T extends 'number'- ? number- : T extends 'boolean'- ? boolean- : T extends 'color'- ? string- : T extends 'string[]'- ? string[]- : never--type ResolvedParams<P extends Record<string, ParamDef>> = {- [K in keyof P as P[K]['required'] extends true ? K : never]: ResolvedType<P[K]['type']>-} & {- [K in keyof P as P[K]['required'] extends true ? never : K]?: ResolvedType<P[K]['type']>+type ToolDefinitionMetadata = Omit<ToolMetadata, 'exposure' | 'capabilities' | 'availability'> &+ Partial<Pick<ToolMetadata, 'exposure' | 'capabilities' | 'availability'>>++export function defineTool<P extends v.ObjectEntries, R>(+ def: ToolDefinitionMetadata & {+ input: v.ObjectSchema<P, undefined>+ execution: ToolExecution & (R extends PromiseLike<unknown> ? { kind: 'async' } : unknown)+ execute: (figma: FigmaAPI, args: v.InferOutput<v.ObjectSchema<P, undefined>>) => R+ }+): ToolDef {+ return {+ ...def,+ exposure: def.exposure ?? { webmcp: false },+ capabilities: def.capabilities ?? [+ toolChangesDocument(def) ? 'document:write' : 'document:read'+ ],+ availability: def.availability ?? 'default',+ get mutates() {+ return def.execution.mutation !== 'none'+ },+ execute: (figma, args) => def.execute(figma, v.parse(def.input, args))+ }}-export function defineTool<P extends Record<string, ParamDef>>(def: {- name: string- description: string- /** Whether execution changes persisted document content. Defaults to `mutates`. */- changesDocument?: boolean- mutates?: boolean- params: P- execute: (figma: FigmaAPI, args: ResolvedParams<P>) => unknown-}): ToolDef {- return def as ToolDef+export function toolChangesDocument(def: Pick<ToolDef, 'execution'>): boolean {+ return def.execution.mutation === 'properties' || def.execution.mutation === 'document'}-export function toolChangesDocument(def: ToolDef): boolean {- return def.changesDocument ?? def.mutates === true+export function isAtomicTool(def: ToolDef): boolean {+ return def.execution.kind === 'sync' && def.execution.mutation === 'properties'}export class NodeNotFoundError extends Error {diff --git a/packages/core/src/tools/stock-photo.ts b/packages/core/src/tools/stock-photo.tsindex 922d19644..050a081c3 100644--- a/packages/core/src/tools/stock-photo.ts+++ b/packages/core/src/tools/stock-photo.ts@@ -1,3 +1,5 @@+import * as v from 'valibot'+import { defineTool } from './schema'import { applyPhoto } from './stock-photo/apply'import { getActiveProvider } from './stock-photo/providers'@@ -17,19 +19,21 @@ export {export const stockPhoto = defineTool({name: 'stock_photo',- mutates: true,+description:'Search stock photos and apply to leaf image placeholders or closed area geometry. ' +'Pass a JSON array; each item is {id, query, index?, orientation?}. ' +'Containers with content, text, lines, and structural nodes are rejected.',- params: {- requests: {- type: 'string',- description:- 'JSON array: [{"id":"0:5","query":"mountain sunset"},{"id":"0:8","query":"business team","orientation":"square"}]',- required: true- }- },+ execution: { kind: 'async', mutation: 'document' },+ capabilities: ['document:write', 'network:access'],+ input: v.object({+ requests: v.pipe(+ v.string(),+ v.description(+ 'JSON array: [{"id":"0:5","query":"mountain sunset"},{"id":"0:8","query":"business team","orientation":"square"}]'+ )+ )+ }),execute: async (figma, { requests }) => {const provider = getActiveProvider()if (!provider) {diff --git a/packages/core/src/tools/structure/arrange.ts b/packages/core/src/tools/structure/arrange.tsindex 0405c45ad..1178eae27 100644--- a/packages/core/src/tools/structure/arrange.ts+++ b/packages/core/src/tools/structure/arrange.ts@@ -1,25 +1,37 @@+import * as v from 'valibot'+import type { FigmaNodeProxy } from '#core/figma-api'+import { toolNumber } from '#core/tools/input'import { defineTool } from '#core/tools/schema'export const arrangeNodes = defineTool({name: 'arrange',- mutates: true,+description:'Arrange top-level nodes on the canvas in a grid, row, or column layout. Useful after batch creation to tidy up overlapping frames.',- params: {- ids: { type: 'string[]', description: 'Node IDs to arrange (default: all top-level children)' },- mode: {- type: 'string',- description: 'Layout mode',- enum: ['grid', 'row', 'column'],- default: 'grid'- },- gap: { type: 'number', description: 'Spacing between nodes (default: 40)' },- cols: { type: 'number', description: 'Column count for grid mode (default: auto)' }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ ids: v.optional(+ v.pipe(+ v.array(v.string()),+ v.minLength(1),+ v.description('Node IDs to arrange (default: all top-level children)')+ )+ ),+ mode: v.optional(+ v.pipe(v.picklist(['grid', 'row', 'column']), v.description('Layout mode')),+ 'grid'+ ),+ gap: v.optional(+ toolNumber(v.pipe(v.number(), v.description('Spacing between nodes (default: 40)')))+ ),+ cols: v.optional(+ toolNumber(v.pipe(v.number(), v.description('Column count for grid mode (default: auto)')))+ )+ }),execute: (figma, args) => {const gap = args.gap ?? 40- const mode = args.mode ?? 'grid'+ const mode = args.modeconst page = figma.currentPagelet nodes: FigmaNodeProxy[]diff --git a/packages/core/src/tools/structure/basic.ts b/packages/core/src/tools/structure/basic.tsindex c2a40bd84..d864db681 100644--- a/packages/core/src/tools/structure/basic.ts+++ b/packages/core/src/tools/structure/basic.ts@@ -1,12 +1,16 @@+import * as v from 'valibot'++import { toolNumber, nodeIdInput, nodeInput } from '#core/tools/input'import { defineTool, nodeNotFound, nodeSummary } from '#core/tools/schema'export const deleteNode = defineTool({name: 'delete_node',- mutates: true,+description: 'Delete a node by ID.',- params: {- id: { type: 'string', description: 'Node ID to delete', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ id: v.pipe(v.string(), v.description('Node ID to delete'))+ }),execute: (figma, { id }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }@@ -17,11 +21,12 @@ export const deleteNode = defineTool({export const cloneNode = defineTool({name: 'clone_node',- mutates: true,+description: 'Clone (duplicate) a node.',- params: {- id: { type: 'string', description: 'Node ID to clone', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ id: v.pipe(v.string(), v.description('Node ID to clone'))+ }),execute: (figma, { id }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }@@ -32,12 +37,13 @@ export const cloneNode = defineTool({export const renameNode = defineTool({name: 'rename_node',- mutates: true,+description: 'Rename a node in the layers panel.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- name: { type: 'string', description: 'New name', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ id: nodeIdInput,+ name: v.pipe(v.string(), v.description('New name'))+ }),execute: (figma, { id, name }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }@@ -49,9 +55,8 @@ export const renameNode = defineTool({export const nodeBounds = defineTool({name: 'node_bounds',description: 'Get absolute bounding box of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true }- },+ execution: { kind: 'sync', mutation: 'none' },+ input: nodeInput,execute: (figma, { id }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }@@ -61,13 +66,14 @@ export const nodeBounds = defineTool({export const nodeMove = defineTool({name: 'node_move',- mutates: true,+description: 'Move a node to new coordinates.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- x: { type: 'number', description: 'X position', required: true },- y: { type: 'number', description: 'Y position', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ id: nodeIdInput,+ x: toolNumber(v.pipe(v.number(), v.description('X position'))),+ y: toolNumber(v.pipe(v.number(), v.description('Y position')))+ }),execute: (figma, { id, x, y }) => {const node = figma.getNodeById(id)if (!node) return nodeNotFound(id)@@ -79,13 +85,14 @@ export const nodeMove = defineTool({export const nodeResize = defineTool({name: 'node_resize',- mutates: true,+description: 'Resize a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- width: { type: 'number', description: 'Width', required: true, min: 1 },- height: { type: 'number', description: 'Height', required: true, min: 1 }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ id: nodeIdInput,+ width: toolNumber(v.pipe(v.number(), v.minValue(1), v.description('Width'))),+ height: toolNumber(v.pipe(v.number(), v.minValue(1), v.description('Height')))+ }),execute: (figma, { id, width, height }) => {const node = figma.getNodeById(id)if (!node) return nodeNotFound(id)diff --git a/packages/core/src/tools/structure/batch.ts b/packages/core/src/tools/structure/batch.tsindex ee0069e4a..6f0e81980 100644--- a/packages/core/src/tools/structure/batch.ts+++ b/packages/core/src/tools/structure/batch.ts@@ -1,4 +1,5 @@import { safeDestr } from 'destr'+import * as v from 'valibot'import type { FigmaNodeProxy } from '#core/figma-api'import { defineTool } from '#core/tools/schema'@@ -91,17 +92,18 @@ function applyBatchProps(node: FigmaNodeProxy, props: Record<string, unknown>):export const batchUpdate = defineTool({name: 'batch_update',- mutates: true,+description:'Execute multiple modifications in one call. Each operation is {id, props} where props can include: spacing, padding, padding_horizontal, padding_vertical, counter_align, sizing_horizontal, sizing_vertical, grow, name, visible, corner_radius, auto_resize (for text), direction. Runs all updates with one layout recompute.',- params: {- operations: {- type: 'string',- description:- 'JSON array: [{"id":"0:5","props":{"spacing":8}},{"id":"0:6","props":{"sizing_horizontal":"FILL","grow":1}}]',- required: true- }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ operations: v.pipe(+ v.string(),+ v.description(+ 'JSON array: [{"id":"0:5","props":{"spacing":8}},{"id":"0:6","props":{"sizing_horizontal":"FILL","grow":1}}]'+ )+ )+ }),execute: (figma, { operations }) => {let ops: BatchOp[]try {diff --git a/packages/core/src/tools/structure/hierarchy.ts b/packages/core/src/tools/structure/hierarchy.tsindex dbde91b16..c59998908 100644--- a/packages/core/src/tools/structure/hierarchy.ts+++ b/packages/core/src/tools/structure/hierarchy.ts@@ -1,13 +1,16 @@+import * as v from 'valibot'+import { defineTool, nodeSummary, requireNodes } from '#core/tools/schema'export const reparentNode = defineTool({name: 'reparent_node',- mutates: true,+description: 'Move a node into a different parent.',- params: {- id: { type: 'string', description: 'Node ID to move', required: true },- parent_id: { type: 'string', description: 'New parent node ID', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ id: v.pipe(v.string(), v.description('Node ID to move')),+ parent_id: v.pipe(v.string(), v.description('New parent node ID'))+ }),execute: (figma, { id, parent_id }) => {const node = figma.getNodeById(id)const parent = figma.getNodeById(parent_id)@@ -20,11 +23,12 @@ export const reparentNode = defineTool({export const groupNodes = defineTool({name: 'group_nodes',- mutates: true,+description: 'Group selected nodes.',- params: {- ids: { type: 'string[]', description: 'Node IDs to group', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ ids: v.pipe(v.array(v.string()), v.minLength(1), v.description('Node IDs to group'))+ }),execute: (figma, { ids }) => {const nodes = requireNodes(figma, ids)if (!nodes || nodes.length < 2) return { error: 'Need at least 2 nodes to group' }@@ -36,11 +40,12 @@ export const groupNodes = defineTool({export const ungroupNode = defineTool({name: 'ungroup_node',- mutates: true,+description: 'Ungroup a group node.',- params: {- id: { type: 'string', description: 'Group node ID', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ id: v.pipe(v.string(), v.description('Group node ID'))+ }),execute: (figma, { id }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }@@ -51,11 +56,12 @@ export const ungroupNode = defineTool({export const flattenNodes = defineTool({name: 'flatten_nodes',- mutates: true,+description: 'Flatten nodes into a single vector.',- params: {- ids: { type: 'string[]', description: 'Node IDs to flatten', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ ids: v.pipe(v.array(v.string()), v.minLength(1), v.description('Node IDs to flatten'))+ }),execute: (figma, { ids }) => {const result = figma.flattenNode(ids)return nodeSummary(result)@@ -64,11 +70,12 @@ export const flattenNodes = defineTool({export const nodeToComponent = defineTool({name: 'node_to_component',- mutates: true,+description: 'Convert one or more frames/groups into components.',- params: {- ids: { type: 'string[]', description: 'Node IDs to convert', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ ids: v.pipe(v.array(v.string()), v.minLength(1), v.description('Node IDs to convert'))+ }),execute: (figma, { ids }) => {const results: { id: string; name: string; originalId: string }[] = []for (const id of ids) {diff --git a/packages/core/src/tools/structure/replace.ts b/packages/core/src/tools/structure/replace.tsindex d649f7dd7..b19c966f9 100644--- a/packages/core/src/tools/structure/replace.ts+++ b/packages/core/src/tools/structure/replace.ts@@ -1,13 +1,16 @@+import * as v from 'valibot'+import { defineTool } from '#core/tools/schema'export const nodeReplaceWith = defineTool({name: 'node_replace_with',- mutates: true,+description: 'Replace a node with JSX content.',- params: {- id: { type: 'string', description: 'Node ID to replace', required: true },- jsx: { type: 'string', description: 'JSX string for the replacement', required: true }- },+ execution: { kind: 'async', mutation: 'document' },+ input: v.object({+ id: v.pipe(v.string(), v.description('Node ID to replace')),+ jsx: v.pipe(v.string(), v.description('JSX string for the replacement'))+ }),execute: async (figma, args) => {const node = figma.getNodeById(args.id)if (!node) return { error: `Node "${args.id}" not found` }diff --git a/packages/core/src/tools/structure/tree.ts b/packages/core/src/tools/structure/tree.tsindex ce997799a..1049d1574 100644--- a/packages/core/src/tools/structure/tree.ts+++ b/packages/core/src/tools/structure/tree.ts@@ -1,13 +1,17 @@+import * as v from 'valibot'+import type { FigmaNodeProxy } from '#core/figma-api'+import { toolNumber, nodeIdInput, nodeInput } from '#core/tools/input'import { defineTool, getRawNodeOrError, nodeNotFound, nodeSummary } from '#core/tools/schema'export const nodeAncestors = defineTool({name: 'node_ancestors',description: 'Get the ancestor chain from a node to the page root.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- depth: { type: 'number', description: 'Max depth to traverse' }- },+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({+ id: nodeIdInput,+ depth: v.optional(toolNumber(v.pipe(v.number(), v.description('Max depth to traverse'))))+ }),execute: (figma, args) => {const node = figma.getNodeById(args.id)if (!node) return { error: `Node "${args.id}" not found` }@@ -26,9 +30,8 @@ export const nodeAncestors = defineTool({export const nodeChildren = defineTool({name: 'node_children',description: 'Get direct children of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true }- },+ execution: { kind: 'sync', mutation: 'none' },+ input: nodeInput,execute: (figma, { id }) => {const node = figma.getNodeById(id)if (!node) return nodeNotFound(id)@@ -39,10 +42,13 @@ export const nodeChildren = defineTool({export const nodeTree = defineTool({name: 'node_tree',description: 'Get a node tree with types and hierarchy.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- depth: { type: 'number', description: 'Max depth (default: unlimited)' }- },+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({+ id: nodeIdInput,+ depth: v.optional(+ toolNumber(v.pipe(v.number(), v.description('Max depth (default: unlimited)')))+ )+ }),execute: (figma, args) => {const node = figma.getNodeById(args.id)if (!node) return { error: `Node "${args.id}" not found` }@@ -66,9 +72,8 @@ export const nodeTree = defineTool({export const nodeBindings = defineTool({name: 'node_bindings',description: 'Get variable bindings for a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true }- },+ execution: { kind: 'sync', mutation: 'none' },+ input: nodeInput,execute: (figma, { id }) => {const result = getRawNodeOrError(figma, id)if ('error' in result) return resultdiff --git a/packages/core/src/tools/validation.ts b/packages/core/src/tools/validation.tsdeleted file mode 100644index 2e0bc6ccf..000000000--- a/packages/core/src/tools/validation.ts+++ /dev/null@@ -1,45 +0,0 @@-import type * as valibot from 'valibot'--import type { ParamDef } from './schema'--/** Shared input contract for AI, MCP, and browser tool adapters. */-export function toolInputEntries(- v: typeof valibot,- params: Record<string, ParamDef>,- options: { coerceNumbers?: boolean } = {}-): valibot.ObjectEntries {- return Object.fromEntries(- Object.entries(params).map(([name, param]) => [name, paramSchema(v, param, options)])- )-}--function paramSchema(- v: typeof valibot,- param: ParamDef,- options: { coerceNumbers?: boolean }-): valibot.GenericSchema {- let schema: valibot.GenericSchema- switch (param.type) {- case 'string':- schema = param.enum ? v.picklist(param.enum) : v.string()- break- case 'number': {- let number: valibot.GenericSchema<number, number> = v.number()- if (param.min !== undefined) number = v.pipe(number, v.minValue(param.min))- if (param.max !== undefined) number = v.pipe(number, v.maxValue(param.max))- schema = options.coerceNumbers ? v.pipe(v.unknown(), v.transform(Number), number) : number- break- }- case 'boolean':- schema = v.boolean()- break- case 'color':- schema = v.string()- break- case 'string[]':- schema = v.pipe(v.array(v.string()), v.minLength(1))- break- }- schema = v.pipe(schema, v.description(param.description))- return param.required ? schema : v.optional(schema, param.default)-}diff --git a/packages/core/src/tools/variables/bindings.ts b/packages/core/src/tools/variables/bindings.tsindex 0b25c813d..7d6fe33a5 100644--- a/packages/core/src/tools/variables/bindings.ts+++ b/packages/core/src/tools/variables/bindings.ts@@ -1,27 +1,32 @@+import * as v from 'valibot'++import { nodeIdInput } from '#core/tools/input'import { defineTool } from '#core/tools/schema'export const bindVariable = defineTool({name: 'bind_variable',- mutates: true,+description:'Bind a variable to a node property. For fills/strokes color bindings use indexed format like "fills/0/color".',- params: {- node_id: { type: 'string', description: 'Node ID', required: true },- field: {- type: 'string',- description:+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ node_id: nodeIdInput,+ field: v.pipe(+ v.string(),+ v.description('Property field path. For fills/strokes use indexed format: "fills/0/color", "strokes/0/color". ' +- 'For FLOAT scalars: "opacity", "width", "height", "cornerRadius", "fontSize", "letterSpacing", ' +- '"lineHeight", "itemSpacing", "strokeWeight", "paddingLeft/Right/Top/Bottom", "counterAxisSpacing", ' +- '"rotation", "x", "y", "minWidth", "maxWidth", "minHeight", "maxHeight", ' +- '"topLeftRadius", "topRightRadius", "bottomLeftRadius", "bottomRightRadius", ' +- '"borderTopWeight", "borderBottomWeight", "borderLeftWeight", "borderRightWeight", ' +- '"gridRowGap", "gridColumnGap". ' +- 'For STRING: "fontFamily". For BOOLEAN: "visible".',- required: true- },- variable_id: { type: 'string', description: 'Variable ID', required: true }- },+ 'For FLOAT scalars: "opacity", "width", "height", "cornerRadius", "fontSize", "letterSpacing", ' ++ '"lineHeight", "itemSpacing", "strokeWeight", "paddingLeft/Right/Top/Bottom", "counterAxisSpacing", ' ++ '"rotation", "x", "y", "minWidth", "maxWidth", "minHeight", "maxHeight", ' ++ '"topLeftRadius", "topRightRadius", "bottomLeftRadius", "bottomRightRadius", ' ++ '"borderTopWeight", "borderBottomWeight", "borderLeftWeight", "borderRightWeight", ' ++ '"gridRowGap", "gridColumnGap". ' ++ 'For STRING: "fontFamily". For BOOLEAN: "visible".'+ )+ ),+ variable_id: v.pipe(v.string(), v.description('Variable ID'))+ }),execute: (figma, args) => {const node = figma.getNodeById(args.node_id)if (!node) return { error: `Node "${args.node_id}" not found` }diff --git a/packages/core/src/tools/variables/collections.ts b/packages/core/src/tools/variables/collections.tsindex 30b206b29..de96c93f4 100644--- a/packages/core/src/tools/variables/collections.ts+++ b/packages/core/src/tools/variables/collections.ts@@ -1,9 +1,13 @@+import * as v from 'valibot'+import { defineTool } from '#core/tools/schema'export const listCollections = defineTool({name: 'list_collections',description: 'List all variable collections.',- params: {},+ execution: { kind: 'sync', mutation: 'none' },+ exposure: { webmcp: true },+ input: v.object({}),execute: (figma) => {const collections = figma.getLocalVariableCollections()return { count: collections.length, collections }@@ -13,9 +17,10 @@ export const listCollections = defineTool({export const getCollection = defineTool({name: 'get_collection',description: 'Get a variable collection by ID.',- params: {- id: { type: 'string', description: 'Collection ID', required: true }- },+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({+ id: v.pipe(v.string(), v.description('Collection ID'))+ }),execute: (figma, { id }) => {const collection = figma.getVariableCollectionById(id)if (!collection) return { error: `Collection "${id}" not found` }@@ -28,11 +33,12 @@ export const getCollection = defineTool({export const createCollection = defineTool({name: 'create_collection',- mutates: true,+description: 'Create a new variable collection.',- params: {- name: { type: 'string', description: 'Collection name', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ name: v.pipe(v.string(), v.description('Collection name'))+ }),execute: (figma, { name }) => {return figma.createVariableCollection(name)}@@ -40,11 +46,12 @@ export const createCollection = defineTool({export const deleteCollection = defineTool({name: 'delete_collection',- mutates: true,+description: 'Delete a variable collection and all its variables.',- params: {- id: { type: 'string', description: 'Collection ID', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ id: v.pipe(v.string(), v.description('Collection ID'))+ }),execute: (figma, { id }) => {figma.deleteVariableCollection(id)return { deleted: id }diff --git a/packages/core/src/tools/variables/read.ts b/packages/core/src/tools/variables/read.tsindex 3c52dba80..09b9ebd56 100644--- a/packages/core/src/tools/variables/read.ts+++ b/packages/core/src/tools/variables/read.ts@@ -1,15 +1,20 @@+import * as v from 'valibot'+import { defineTool } from '#core/tools/schema'export const listVariables = defineTool({name: 'list_variables',description: 'List all design variables (colors, numbers, strings, booleans).',- params: {- type: {- type: 'string',- description: 'Filter by variable type',- enum: ['COLOR', 'FLOAT', 'STRING', 'BOOLEAN']- }- },+ execution: { kind: 'sync', mutation: 'none' },+ exposure: { webmcp: true },+ input: v.object({+ type: v.optional(+ v.pipe(+ v.picklist(['COLOR', 'FLOAT', 'STRING', 'BOOLEAN']),+ v.description('Filter by variable type')+ )+ )+ }),execute: (figma, args) => {const variables = figma.getLocalVariables(args.type)return { count: variables.length, variables }@@ -19,9 +24,11 @@ export const listVariables = defineTool({export const getVariable = defineTool({name: 'get_variable',description: 'Get a variable by ID.',- params: {- id: { type: 'string', description: 'Variable ID', required: true }- },+ execution: { kind: 'sync', mutation: 'none' },+ exposure: { webmcp: true },+ input: v.object({+ id: v.pipe(v.string(), v.description('Variable ID'))+ }),execute: (figma, { id }) => {const variable = figma.getVariableById(id)if (!variable) return { error: `Variable "${id}" not found` }@@ -32,14 +39,14 @@ export const getVariable = defineTool({export const findVariables = defineTool({name: 'find_variables',description: 'Find variables by name pattern.',- params: {- query: { type: 'string', description: 'Name substring (case-insensitive)', required: true },- type: {- type: 'string',- description: 'Filter by type',- enum: ['COLOR', 'FLOAT', 'STRING', 'BOOLEAN']- }- },+ execution: { kind: 'sync', mutation: 'none' },+ exposure: { webmcp: true },+ input: v.object({+ query: v.pipe(v.string(), v.description('Name substring (case-insensitive)')),+ type: v.optional(+ v.pipe(v.picklist(['COLOR', 'FLOAT', 'STRING', 'BOOLEAN']), v.description('Filter by type'))+ )+ }),execute: (figma, args) => {let variables = figma.getLocalVariables(args.type)variables = variables.filter((variable) =>diff --git a/packages/core/src/tools/variables/unbind.ts b/packages/core/src/tools/variables/unbind.tsindex a22ba350c..06ec7f75e 100644--- a/packages/core/src/tools/variables/unbind.ts+++ b/packages/core/src/tools/variables/unbind.ts@@ -1,25 +1,30 @@+import * as v from 'valibot'++import { nodeIdInput } from '#core/tools/input'import { defineTool } from '#core/tools/schema'export const unbindVariable = defineTool({name: 'unbind_variable',- mutates: true,+description: 'Remove a variable binding from a node property.',- params: {- node_id: { type: 'string', description: 'Node ID', required: true },- field: {- type: 'string',- description:+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ node_id: nodeIdInput,+ field: v.pipe(+ v.string(),+ v.description('Property field path to unbind. For fills/strokes use indexed format: "fills/0/color", "strokes/0/color". ' +- 'For FLOAT scalars: "opacity", "width", "height", "cornerRadius", "fontSize", "letterSpacing", ' +- '"lineHeight", "itemSpacing", "strokeWeight", "paddingLeft/Right/Top/Bottom", "counterAxisSpacing", ' +- '"rotation", "x", "y", "minWidth", "maxWidth", "minHeight", "maxHeight", ' +- '"topLeftRadius", "topRightRadius", "bottomLeftRadius", "bottomRightRadius", ' +- '"borderTopWeight", "borderBottomWeight", "borderLeftWeight", "borderRightWeight", ' +- '"gridRowGap", "gridColumnGap". ' +- 'For STRING: "fontFamily". For BOOLEAN: "visible".',- required: true- }- },+ 'For FLOAT scalars: "opacity", "width", "height", "cornerRadius", "fontSize", "letterSpacing", ' ++ '"lineHeight", "itemSpacing", "strokeWeight", "paddingLeft/Right/Top/Bottom", "counterAxisSpacing", ' ++ '"rotation", "x", "y", "minWidth", "maxWidth", "minHeight", "maxHeight", ' ++ '"topLeftRadius", "topRightRadius", "bottomLeftRadius", "bottomRightRadius", ' ++ '"borderTopWeight", "borderBottomWeight", "borderLeftWeight", "borderRightWeight", ' ++ '"gridRowGap", "gridColumnGap". ' ++ 'For STRING: "fontFamily". For BOOLEAN: "visible".'+ )+ )+ }),execute: (figma, args) => {// Access raw scene node for boundVariables (not exposed on the proxy)const rawNode = figma.graph.getNode(args.node_id)diff --git a/packages/core/src/tools/variables/values.ts b/packages/core/src/tools/variables/values.tsindex 30451b03c..d8100500e 100644--- a/packages/core/src/tools/variables/values.ts+++ b/packages/core/src/tools/variables/values.ts@@ -1,3 +1,5 @@+import * as v from 'valibot'+import type { VariableType, VariableValue } from '@open-pencil/scene-graph'import { parseColor } from '#core/color'@@ -12,19 +14,20 @@ function parseVariableValue(type: VariableType, value: string): VariableValue {export const createVariable = defineTool({name: 'create_variable',- mutates: true,+description: 'Create a new variable in a collection.',- params: {- name: { type: 'string', description: 'Variable name', required: true },- type: {- type: 'string',- description: 'Variable type',- required: true,- enum: ['COLOR', 'FLOAT', 'STRING', 'BOOLEAN']- },- collection_id: { type: 'string', description: 'Collection ID', required: true },- value: { type: 'string', description: 'Initial value (hex for COLOR, number for FLOAT, etc.)' }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ name: v.pipe(v.string(), v.description('Variable name')),+ type: v.pipe(+ v.picklist(['COLOR', 'FLOAT', 'STRING', 'BOOLEAN']),+ v.description('Variable type')+ ),+ collection_id: v.pipe(v.string(), v.description('Collection ID')),+ value: v.optional(+ v.pipe(v.string(), v.description('Initial value (hex for COLOR, number for FLOAT, etc.)'))+ )+ }),execute: (figma, args) => {const type = args.type as VariableTypeconst parsedValue = args.value === undefined ? undefined : parseVariableValue(type, args.value)@@ -34,17 +37,15 @@ export const createVariable = defineTool({export const setVariable = defineTool({name: 'set_variable',- mutates: true,+description: 'Set the value of a variable for a specific mode.',- params: {- id: { type: 'string', description: 'Variable ID', required: true },- mode: { type: 'string', description: 'Mode ID', required: true },- value: {- type: 'string',- description: 'Value (hex for COLOR, number for FLOAT, etc.)',- required: true- }- },+ execution: { kind: 'sync', mutation: 'properties' },+ exposure: { webmcp: true },+ input: v.object({+ id: v.pipe(v.string(), v.description('Variable ID')),+ mode: v.pipe(v.string(), v.description('Mode ID')),+ value: v.pipe(v.string(), v.description('Value (hex for COLOR, number for FLOAT, etc.)'))+ }),execute: (figma, args) => {const variable = figma.getVariableById(args.id)if (!variable) return { error: `Variable "${args.id}" not found` }@@ -56,11 +57,12 @@ export const setVariable = defineTool({export const deleteVariable = defineTool({name: 'delete_variable',- mutates: true,+description: 'Delete a variable.',- params: {- id: { type: 'string', description: 'Variable ID', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ id: v.pipe(v.string(), v.description('Variable ID'))+ }),execute: (figma, { id }) => {figma.deleteVariable(id)return { deleted: id }diff --git a/packages/core/src/tools/vector/boolean.ts b/packages/core/src/tools/vector/boolean.tsindex 05d6f3520..991d1c11f 100644--- a/packages/core/src/tools/vector/boolean.ts+++ b/packages/core/src/tools/vector/boolean.ts@@ -1,12 +1,15 @@+import * as v from 'valibot'+import { defineTool, nodeSummary } from '#core/tools/schema'export const booleanUnion = defineTool({name: 'boolean_union',- mutates: true,+description: 'Union (combine) multiple nodes.',- params: {- ids: { type: 'string[]', description: 'Node IDs to union', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ ids: v.pipe(v.array(v.string()), v.minLength(1), v.description('Node IDs to union'))+ }),execute: (figma, { ids }) => {const result = figma.booleanOperation('UNION', ids)return nodeSummary(result)@@ -15,11 +18,12 @@ export const booleanUnion = defineTool({export const booleanSubtract = defineTool({name: 'boolean_subtract',- mutates: true,+description: 'Subtract the second node from the first.',- params: {- ids: { type: 'string[]', description: 'Node IDs (first minus rest)', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ ids: v.pipe(v.array(v.string()), v.minLength(1), v.description('Node IDs (first minus rest)'))+ }),execute: (figma, { ids }) => {const result = figma.booleanOperation('SUBTRACT', ids)return nodeSummary(result)@@ -28,11 +32,12 @@ export const booleanSubtract = defineTool({export const booleanIntersect = defineTool({name: 'boolean_intersect',- mutates: true,+description: 'Intersect multiple nodes.',- params: {- ids: { type: 'string[]', description: 'Node IDs to intersect', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ ids: v.pipe(v.array(v.string()), v.minLength(1), v.description('Node IDs to intersect'))+ }),execute: (figma, { ids }) => {const result = figma.booleanOperation('INTERSECT', ids)return nodeSummary(result)@@ -41,11 +46,12 @@ export const booleanIntersect = defineTool({export const booleanExclude = defineTool({name: 'boolean_exclude',- mutates: true,+description: 'Exclude (XOR) multiple nodes.',- params: {- ids: { type: 'string[]', description: 'Node IDs to exclude', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ ids: v.pipe(v.array(v.string()), v.minLength(1), v.description('Node IDs to exclude'))+ }),execute: (figma, { ids }) => {const result = figma.booleanOperation('EXCLUDE', ids)return nodeSummary(result)diff --git a/packages/core/src/tools/vector/export.ts b/packages/core/src/tools/vector/export.tsindex cb92a5195..de419bb14 100644--- a/packages/core/src/tools/vector/export.ts+++ b/packages/core/src/tools/vector/export.ts@@ -1,20 +1,33 @@+import * as v from 'valibot'+import { encodeBase64 } from '#core/bytes'import type { RasterExportFormat } from '#core/io/formats/raster'+import { toolNumber } from '#core/tools/input'import { defineTool } from '#core/tools/schema'+const exportInputs = {+ ids: v.optional(+ v.pipe(+ v.array(v.string()),+ v.minLength(1),+ v.description('Node IDs to export. Omit to export all top-level nodes on the current page.')+ )+ ),+ path: v.optional(+ v.pipe(+ v.string(),+ v.description(+ 'Write exported data to this path instead of returning it (requires OPENPENCIL_MCP_ROOT)'+ )+ )+ )+}+export const exportSVG = defineTool({name: 'export_svg',description: 'Export nodes as SVG markup. Returns the SVG string.',- params: {- 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)'- }- },+ execution: { kind: 'async', mutation: 'none' },+ input: v.object({ ...exportInputs }),execute: async (figma, args) => {const { renderNodesToSVG } = await import('#core/io/formats/svg')const pageId = figma.currentPageId@@ -30,17 +43,8 @@ export const exportPDF = defineTool({name: 'export_pdf',description:'Export nodes as a vector PDF document. Text remains selectable, paths stay sharp at any zoom. Returns base64-encoded PDF data.',- params: {- ids: {- type: 'string[]',- description: 'Node IDs to export. Omit to export all top-level nodes on the current page.'- },- path: {- type: 'string',- description:- 'Write PDF to this path instead of returning base64 (requires OPENPENCIL_MCP_ROOT)'- }- },+ execution: { kind: 'async', mutation: 'none' },+ input: v.object({ ...exportInputs }),execute: async (figma, args) => {const { renderNodesToPDF } = await import('#core/io/formats/pdf')const pageId = figma.currentPageId@@ -57,47 +61,49 @@ export const exportImage = defineTool({name: 'export_image',description:'Export nodes as a raster image (PNG, JPG, or WEBP). Returns base64-encoded image data. Use to visually verify designs.',- params: {- ids: {- type: 'string[]',- description: 'Node IDs to export. Omit to export all top-level nodes on the current page.'- },- format: {- type: 'string',- description: 'Image format',- enum: ['PNG', 'JPG', 'WEBP'],- default: 'PNG'- },- scale: {- type: 'number',- description: 'Export scale multiplier before the maximum-edge limit is applied (default: 1)',- default: 1,- min: 0.1,- max: 4- },- maxEdge: {- type: 'number',- description:- 'Maximum output width or height in pixels. Preserves aspect ratio and never upscales. Defaults to 1280 for bounded model input.',- default: 1280,- min: 64,- max: 4096- },- path: {- type: 'string',- description:- 'Write image to this path instead of returning base64 (requires OPENPENCIL_MCP_ROOT)'- }- },+ execution: { kind: 'async', mutation: 'none' },+ input: v.object({+ ...exportInputs,+ format: v.optional(+ v.pipe(v.picklist(['PNG', 'JPG', 'WEBP']), v.description('Image format')),+ 'PNG'+ ),+ scale: v.optional(+ toolNumber(+ v.pipe(+ v.number(),+ v.minValue(0.1),+ v.maxValue(4),+ v.description(+ 'Export scale multiplier before the maximum-edge limit is applied (default: 1)'+ )+ )+ ),+ 1+ ),+ maxEdge: v.optional(+ toolNumber(+ v.pipe(+ v.number(),+ v.minValue(64),+ v.maxValue(4096),+ v.description(+ 'Maximum output width or height in pixels. Preserves aspect ratio and never upscales. Defaults to 1280 for bounded model input.'+ )+ )+ ),+ 1280+ )+ }),execute: async (figma, args) => {if (!figma.exportImage) {return { error: 'Image export is not available in this environment' }}const ids =args.ids && args.ids.length > 0 ? args.ids : figma.currentPage.children.map((node) => node.id)- const format = (args.format ?? 'PNG').toUpperCase() as RasterExportFormat- const requestedScale = args.scale ?? 1- const maxEdge = args.maxEdge ?? 1280+ const format = args.format.toUpperCase() as RasterExportFormat+ const requestedScale = args.scale+ const maxEdge = args.maxEdgeconst nodes = ids.map((id) => figma.getNodeById(id)).filter((node) => node !== null)if (nodes.length === 0) return { error: 'No visible nodes to export' }const bounds = nodes.reduce(diff --git a/packages/core/src/tools/vector/path.ts b/packages/core/src/tools/vector/path.tsindex c5763db90..997d2827f 100644--- a/packages/core/src/tools/vector/path.ts+++ b/packages/core/src/tools/vector/path.ts@@ -1,7 +1,10 @@+import * as v from 'valibot'+import { cloneVectorNetwork } from '@open-pencil/scene-graph'import type { SceneNode, VectorNetwork } from '@open-pencil/scene-graph'import type { FigmaAPI } from '#core/figma-api'+import { toolNumber, nodeIdInput, nodeInput } from '#core/tools/input'import { defineTool } from '#core/tools/schema'function getVectorNode(@@ -17,9 +20,8 @@ function getVectorNode(export const pathGet = defineTool({name: 'path_get',description: 'Get vector path data of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true }- },+ execution: { kind: 'sync', mutation: 'none' },+ input: nodeInput,execute: (figma, { id }) => {const raw = figma.graph.getNode(id)if (!raw) return { error: `Node "${id}" not found` }@@ -30,12 +32,13 @@ export const pathGet = defineTool({export const pathSet = defineTool({name: 'path_set',- mutates: true,+description: 'Set vector path data on a node. Provide a VectorNetwork JSON.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- path: { type: 'string', description: 'VectorNetwork JSON', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ id: nodeIdInput,+ path: v.pipe(v.string(), v.description('VectorNetwork JSON'))+ }),execute: (figma, args) => {const raw = figma.graph.getNode(args.id)if (!raw) return { error: `Node "${args.id}" not found` }@@ -47,12 +50,13 @@ export const pathSet = defineTool({export const pathScale = defineTool({name: 'path_scale',- mutates: true,+description: 'Scale vector path from center.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- factor: { type: 'number', description: 'Scale factor (e.g. 2 for double)', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ id: nodeIdInput,+ factor: toolNumber(v.pipe(v.number(), v.description('Scale factor (e.g. 2 for double)')))+ }),execute: (figma, { id, factor }) => {const result = getVectorNode(figma, id)if ('error' in result) return result@@ -77,17 +81,13 @@ export const pathScale = defineTool({export const pathFlip = defineTool({name: 'path_flip',- mutates: true,+description: 'Flip vector path horizontally or vertically.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- axis: {- type: 'string',- description: 'Flip axis',- required: true,- enum: ['horizontal', 'vertical']- }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ id: nodeIdInput,+ axis: v.pipe(v.picklist(['horizontal', 'vertical']), v.description('Flip axis'))+ }),execute: (figma, { id, axis }) => {const result = getVectorNode(figma, id)if ('error' in result) return result@@ -112,13 +112,14 @@ export const pathFlip = defineTool({export const pathMove = defineTool({name: 'path_move',- mutates: true,+description: 'Move all path points by an offset.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- dx: { type: 'number', description: 'X offset', required: true },- dy: { type: 'number', description: 'Y offset', required: true }- },+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ id: nodeIdInput,+ dx: toolNumber(v.pipe(v.number(), v.description('X offset'))),+ dy: toolNumber(v.pipe(v.number(), v.description('Y offset')))+ }),execute: (figma, { id, dx, dy }) => {const result = getVectorNode(figma, id)if ('error' in result) return resultdiff --git a/packages/core/src/tools/vector/viewport.ts b/packages/core/src/tools/vector/viewport.tsindex cc2d46905..76fee53fc 100644--- a/packages/core/src/tools/vector/viewport.ts+++ b/packages/core/src/tools/vector/viewport.ts@@ -1,9 +1,13 @@+import * as v from 'valibot'++import { toolNumber } from '#core/tools/input'import { defineTool } from '#core/tools/schema'export const viewportGet = defineTool({name: 'viewport_get',description: 'Get current viewport position and zoom level.',- params: {},+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({}),execute: (figma) => {return figma.viewport}@@ -11,14 +15,14 @@ export const viewportGet = defineTool({export const viewportSet = defineTool({name: 'viewport_set',- mutates: true,- changesDocument: false,+description: 'Set viewport position and zoom.',- params: {- x: { type: 'number', description: 'Center X', required: true },- y: { type: 'number', description: 'Center Y', required: true },- zoom: { type: 'number', description: 'Zoom level', required: true, min: 0.01 }- },+ execution: { kind: 'sync', mutation: 'view' },+ input: v.object({+ x: toolNumber(v.pipe(v.number(), v.description('Center X'))),+ y: toolNumber(v.pipe(v.number(), v.description('Center Y'))),+ zoom: toolNumber(v.pipe(v.number(), v.minValue(0.01), v.description('Zoom level')))+ }),execute: (figma, { x, y, zoom }) => {figma.viewport = { center: { x, y }, zoom }return { x, y, zoom }@@ -27,12 +31,12 @@ export const viewportSet = defineTool({export const viewportZoomToFit = defineTool({name: 'viewport_zoom_to_fit',- mutates: true,- changesDocument: false,+description: 'Zoom viewport to fit specified nodes.',- params: {- ids: { type: 'string[]', description: 'Node IDs to fit in view', required: true }- },+ execution: { kind: 'sync', mutation: 'view' },+ input: v.object({+ ids: v.pipe(v.array(v.string()), v.minLength(1), v.description('Node IDs to fit in view'))+ }),execute: (figma, { ids }) => {let minX = Infinitylet minY = Infinitydiff --git a/packages/docs/programmable/mcp-server.md b/packages/docs/programmable/mcp-server.mdindex e1be970fa..84555ab07 100644--- a/packages/docs/programmable/mcp-server.md+++ b/packages/docs/programmable/mcp-server.md@@ -9,6 +9,8 @@ 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.+Tool definitions own native Valibot input schemas, execution/mutation metadata, capabilities, and explicit browser exposure. AI and MCP consume the same schema through Standard Schema; WebMCP derives its JSON Schema from that input. Numeric strings are accepted consistently across adapters, while non-finite values are rejected. Programmatic integrations use MCP SDK v2; custom tools replace the former `params`/`ParamDef` contract with `input` and execution metadata.+## 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.diff --git a/packages/mcp/src/tool/manifest.ts b/packages/mcp/src/tool/manifest.tsindex fb7961df7..81117f6d0 100644--- a/packages/mcp/src/tool/manifest.ts+++ b/packages/mcp/src/tool/manifest.ts@@ -8,26 +8,16 @@ import type {ToolEffect} from '#mcp/tool/metadata'-const TOOL_CAPABILITY_OVERRIDES: Readonly<Partial<Record<string, readonly ToolCapability[]>>> = {- eval: ['document:read', 'document:write', 'code:execute'],- fetch_icons: ['network:access'],- insert_icon: ['document:write', 'network:access'],- list_available_fonts: ['document:read'],- search_icons: ['network:access'],- stock_photo: ['document:write', 'network:access']-}-export function coreToolEffect(def: ToolDef): ToolEffect {return toolChangesDocument(def) ? 'write' : 'read'}export function coreToolCapabilities(def: ToolDef): ToolCapability[] {- const override = TOOL_CAPABILITY_OVERRIDES[def.name]- return override ? [...override] : [toolChangesDocument(def) ? 'document:write' : 'document:read']+ return [...def.capabilities]}export function coreToolAvailability(def: ToolDef): ToolAvailability {- return def.name === 'eval' ? 'eval' : 'default'+ return def.availability}function coreToolDescriptor(def: ToolDef): ToolDescriptor {diff --git a/packages/mcp/src/tool/metadata.ts b/packages/mcp/src/tool/metadata.tsindex cbd78fde5..8191c5cfe 100644--- a/packages/mcp/src/tool/metadata.ts+++ b/packages/mcp/src/tool/metadata.ts@@ -1,13 +1,8 @@+import type { ToolCapability } from '@open-pencil/core/tools'+export type { ToolCapability } from '@open-pencil/core/tools'+export type ToolEffect = 'read' | 'write'export type ToolAvailability = 'default' | 'eval' | 'filesystem'-export type ToolCapability =- | 'document:read'- | 'document:write'- | 'filesystem:read'- | 'filesystem:write'- | 'network:access'- | 'code:execute'-export interface ToolDescriptor {name: stringdescription: stringdiff --git a/packages/mcp/src/tool/registration.ts b/packages/mcp/src/tool/registration.tsindex 44e1eae87..41ebbcbda 100644--- a/packages/mcp/src/tool/registration.ts+++ b/packages/mcp/src/tool/registration.ts@@ -6,7 +6,7 @@ import type { McpServer, ToolCallback, ToolAnnotations } from '@modelcontextprotimport { toStandardJsonSchema as toStandardJSONSchema } from '@valibot/to-json-schema'import * as v from 'valibot'-import { ALL_TOOLS, CODEGEN_PROMPT, toolInputEntries } from '@open-pencil/core/tools'+import { ALL_TOOLS, CODEGEN_PROMPT } from '@open-pencil/core/tools'import type { RPCJSONObject } from '#mcp/json'import { MAX_RESULT_BYTES, fail, ok, resultTooLargeMessage } from '#mcp/result'@@ -14,7 +14,6 @@ import { createToolDescriptors } from '#mcp/tool/manifest'import type { ToolDescriptor, ToolEffect, ToolPolicy } from '#mcp/tool/metadata'import { resolveSafePath, writeToolOutput } from '#mcp/tool/output'import { isToolEnabled } from '#mcp/tool/policy'-import { toolSchema } from '#mcp/tool/schema'export type RPCSender = (body: Record<string, unknown>) => Promise<unknown>@@ -80,12 +79,11 @@ export function registerTools(mcpServer: McpServer, options: RegisterToolsOption}for (const def of ALL_TOOLS) {- const shape = toolInputEntries(v, def.params)register(def.name,{description: def.description,- inputSchema: toolSchema(def.params, shape, automationTargetSchema)+ inputSchema: v.object({ ...def.input.entries, ...automationTargetSchema })},async (args: Record<string, unknown>) => {try {diff --git a/packages/mcp/src/tool/schema.ts b/packages/mcp/src/tool/schema.tsdeleted file mode 100644index ede45cc40..000000000--- a/packages/mcp/src/tool/schema.ts+++ /dev/null@@ -1,23 +0,0 @@-import * as v from 'valibot'--import { toolInputEntries, type ParamDef } from '@open-pencil/core/tools'--/** Advertise canonical numeric inputs while preserving MCP's numeric coercion. */-export function toolSchema(- params: Record<string, ParamDef>,- entries: v.ObjectEntries,- targetEntries: v.ObjectEntries-): v.ObjectSchema<v.ObjectEntries, undefined> {- const schema = v.object({ ...entries, ...targetEntries })- const parser = v.object({- ...toolInputEntries(v, params, { coerceNumbers: true }),- ...targetEntries- })- return {- ...schema,- '~standard': {- ...schema['~standard'],- validate: parser['~standard'].validate- }- }-}diff --git a/packages/scene-graph/src/checkpoint.ts b/packages/scene-graph/src/checkpoint.tsnew file mode 100644index 000000000..247da077d--- /dev/null+++ b/packages/scene-graph/src/checkpoint.ts@@ -0,0 +1,120 @@+import { isEqual } from 'es-toolkit'++import type { SceneGraph } from './index'++/** Capture rollback state without changing graph or surviving object identities. */+export function captureGraphCheckpoint(graph: SceneGraph) {+ const nodeRefs = new Map(graph.nodes)+ const variableRefs = new Map(graph.variables)+ const collectionRefs = new Map(graph.variableCollections)+ const snapshot = structuredClone({+ nodes: graph.nodes,+ variables: graph.variables,+ variableCollections: graph.variableCollections,+ activeMode: graph.activeMode,+ instanceIndex: graph.instanceIndex,+ enabledLibraries: graph.enabledLibraries,+ rootId: graph.rootId,+ figKiwiVersion: graph.figKiwiVersion,+ figSchemaDeflated: graph.figSchemaDeflated,+ documentColorSpace: graph.documentColorSpace+ })+ // Atomic property tools cannot edit assets. Retain existing buffers, not copies of every bitmap.+ const images = new Map(graph.images)++ function assertPropertiesOnly() {+ if (+ snapshot.nodes.size !== graph.nodes.size ||+ snapshot.variables.size !== graph.variables.size+ )+ throw new Error('Atomic tools must not create or remove nodes or variables')+ for (const [id, before] of snapshot.nodes) {+ const after = graph.nodes.get(id)+ if (+ !after ||+ before.id !== after.id ||+ before.type !== after.type ||+ before.parentId !== after.parentId ||+ before.componentId !== after.componentId ||+ !isEqual(before.childIds, after.childIds)+ ) {+ throw new Error('Atomic tools must not change node hierarchy or identity')+ }+ }+ for (const [id, before] of snapshot.variables) {+ const after = graph.variables.get(id)+ if (+ !after ||+ before.id !== after.id ||+ before.collectionId !== after.collectionId ||+ before.type !== after.type+ )+ throw new Error('Atomic tools must not change variable identity')+ }+ assertDocumentUnchanged()+ }++ function assertDocumentUnchanged() {+ if (+ !isEqual(snapshot.variableCollections, graph.variableCollections) ||+ !isEqual(snapshot.activeMode, graph.activeMode) ||+ !isEqual(snapshot.enabledLibraries, graph.enabledLibraries) ||+ images.size !== graph.images.size ||+ [...images].some(([id, bytes]) => graph.images.get(id) !== bytes) ||+ graph.rootId !== snapshot.rootId ||+ graph.documentColorSpace !== snapshot.documentColorSpace ||+ graph.figKiwiVersion !== snapshot.figKiwiVersion ||+ !isEqual(graph.figSchemaDeflated, snapshot.figSchemaDeflated)+ ) {+ throw new Error('Atomic tools must not change collections, assets or document metadata')+ }+ }++ function restore() {+ const failedNodes = new Map(graph.nodes)+ restoreObjects(graph.nodes, snapshot.nodes, nodeRefs)+ restoreObjects(graph.variables, snapshot.variables, variableRefs)+ restoreObjects(graph.variableCollections, snapshot.variableCollections, collectionRefs)+ restoreMap(graph.activeMode, structuredClone(snapshot.activeMode))+ restoreMap(graph.instanceIndex, structuredClone(snapshot.instanceIndex))+ restoreMap(graph.enabledLibraries, structuredClone(snapshot.enabledLibraries))+ restoreMap(graph.images, images)+ graph.rootId = snapshot.rootId+ graph.figKiwiVersion = snapshot.figKiwiVersion+ graph.figSchemaDeflated = structuredClone(snapshot.figSchemaDeflated)+ graph.documentColorSpace = snapshot.documentColorSpace+ graph.clearAbsPosCache()+ // Notify consumers only after the complete hierarchy and indexes have been restored.+ for (const [id, node] of failedNodes) {+ if (!graph.nodes.has(id)) graph.emitter.emit('node:deleted', id, node.parentId)+ }+ for (const [id, node] of graph.nodes) {+ if (failedNodes.has(id)) graph.emitter.emit('node:updated', id, node)+ else graph.emitter.emit('node:created', node)+ }+ }++ return { nodes: snapshot.nodes, variables: snapshot.variables, assertPropertiesOnly, restore }+}++function restoreObjects<T extends object>(+ target: Map<string, T>,+ snapshot: Map<string, T>,+ refs: Map<string, T>+) {+ target.clear()+ for (const [id, saved] of snapshot) {+ const original = refs.get(id)+ if (!original) throw new Error(`Missing checkpoint reference: ${id}`)+ for (const key of Object.keys(original) as (keyof T)[]) {+ if (!(key in saved)) Reflect.deleteProperty(original, key)+ }+ Object.assign(original, structuredClone(saved))+ target.set(id, original)+ }+}++function restoreMap<K, V>(target: Map<K, V>, saved: Map<K, V>) {+ target.clear()+ for (const [key, value] of saved) target.set(key, value)+}diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex c578de09a..07e3d747a 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -95,6 +95,8 @@ function stripUndefinedProps<T extends object>(obj: T): T {return result}+export { captureGraphCheckpoint } from './checkpoint'+export class SceneGraph {nodes = new Map<string, SceneNode>()images = new Map<string, Uint8Array>()diff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.mdindex 342060ad1..2340243da 100644--- a/skills/open-pencil/SKILL.md+++ b/skills/open-pencil/SKILL.md@@ -213,7 +213,7 @@ Calls capture the active document/page. Cancellation prevents an edit from start## Tool discovery-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.+Discover available tools and their arguments from the connected server or browser; availability varies by version and mode. Each tool's schema and execution/exposure metadata are authoritative. Numeric inputs accept numbers or numeric strings consistently, but reject non-finite values. 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/ai/tools/index.ts b/src/app/ai/tools/index.tsindex 021fa01e4..c16bf9a1a 100644--- a/src/app/ai/tools/index.ts+++ b/src/app/ai/tools/index.ts@@ -1,18 +1,16 @@-import { valibotSchema } from '@ai-sdk/valibot'import { tool } from 'ai'-import * as v from 'valibot'import {CORE_TOOLS,EXTENDED_TOOLS,registerComponentCatalog,+ isAtomicTool,toolsToAI} from '@open-pencil/core/tools'import type { StepBudget, ToolLogEntry } from '@open-pencil/core/tools'import type { SceneNode } from '@open-pencil/scene-graph'import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'-import { ATOMIC_TOOL_NAMES } from '@/app/automation/execution/atomic'import { executeAtomicEditorTool } from '@/app/automation/execution/editor'import { getActiveEditorStore } from '@/app/editor/active-store'import type { EditorStore } from '@/app/editor/active-store'@@ -87,7 +85,7 @@ export function createAITools(store: EditorStore) {{getFigma: () => makeFigmaFromStore(store),executeTool: async (def, figma, args) => {- if (ATOMIC_TOOL_NAMES.has(def.name)) {+ if (isAtomicTool(def)) {return executeAtomicEditorTool(store, figma, def, args, { label: 'AI' })}if (def.mutates) beforeSnapshot = store.snapshotPage()@@ -103,7 +101,7 @@ export function createAITools(store: EditorStore) {: def.execute(figma, args)},onAfterExecute: async (def) => {- if (ATOMIC_TOOL_NAMES.has(def.name)) return+ if (isAtomicTool(def)) returnif (def.mutates) {store.requestRender()if (beforeSnapshot) {@@ -132,7 +130,7 @@ export function createAITools(store: EditorStore) {max: MAX_AGENT_STEPS})},- { v, valibotSchema, tool }+ { tool })}diff --git a/src/app/automation/bridge/tool-handlers.ts b/src/app/automation/bridge/tool-handlers.tsindex 65f0c4cff..ba17b06ed 100644--- a/src/app/automation/bridge/tool-handlers.ts+++ b/src/app/automation/bridge/tool-handlers.ts@@ -1,10 +1,9 @@import { renderTreeNode } from '@open-pencil/core/design-jsx'import type { FigmaAPI } from '@open-pencil/core/figma-api'-import { ALL_TOOLS, registerComponentCatalog } from '@open-pencil/core/tools'+import { ALL_TOOLS, registerComponentCatalog, isAtomicTool } from '@open-pencil/core/tools'import type { JSONObject } from '@open-pencil/scene-graph/primitives'import type { AutomationTarget } from '@/app/automation/bridge/target'-import { ATOMIC_TOOL_NAMES } from '@/app/automation/execution/atomic'import { executeAtomicEditorTool } from '@/app/automation/execution/editor'import { ensureGraphFonts } from '@/app/editor/fonts'import { useLibraryService } from '@/app/libraries'@@ -55,7 +54,7 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {registerComponentCatalog(store.graph, libraryService)const figma = makeFigma(store, target.pageId)let result: unknown- if (ATOMIC_TOOL_NAMES.has(def.name)) {+ if (isAtomicTool(def)) {result = await executeAtomicEditorTool(store, figma, def, toolArgs)} else if (def.mutates) {result = await store.runMutationWithLayout(diff --git a/src/app/automation/execution/editor.ts b/src/app/automation/execution/editor.tsindex 25832a4ea..9495677c1 100644--- a/src/app/automation/execution/editor.ts+++ b/src/app/automation/execution/editor.ts@@ -1,11 +1,10 @@+import { executeAtomicTool } from '@open-pencil/core/editor'import type { FigmaAPI } from '@open-pencil/core/figma-api'import type { ToolDef } from '@open-pencil/core/tools'import type { EditorStore } from '@/app/editor/active-store'import { ensureGraphFonts } from '@/app/editor/fonts'-import { executeAtomicTool } from './atomic'-/** Commit first; asynchronous font availability is presentation work, not a transaction. */export async function executeAtomicEditorTool(store: EditorStore,diff --git a/src/app/automation/webmcp/registration.ts b/src/app/automation/webmcp/registration.tsindex 43d287868..96ab53483 100644--- a/src/app/automation/webmcp/registration.ts+++ b/src/app/automation/webmcp/registration.ts@@ -3,29 +3,7 @@ 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'-])+import { ALL_TOOLS, type ToolDef } from '@open-pencil/core/tools'const MAX_RESULT_BYTES = 256 * 1024@@ -49,14 +27,14 @@ export function registerWebMCPTools(if (!context) returntry {for (const def of ALL_TOOLS) {- if (!READ_TOOLS.has(def.name) && !ATOMIC_TOOL_NAMES.has(def.name)) continue+ if (!def.exposure.webmcp) continuelifetime.signal.throwIfAborted()- const schema = v.object(toolInputEntries(v, def.params))+ const schema = def.inputawait context.registerTool({name: def.name,description: `${def.description} Targets the active OpenPencil document.`,- inputSchema: toJSONSchema(schema),+ inputSchema: toJSONSchema(schema, { typeMode: 'input' }),annotations: { readOnlyHint: !def.mutates, untrustedContentHint: true },execute: async (input, options?: WebMCP.ToolExecuteCallbackOptions) => {// Early document.modelContext implementations omit execution options.diff --git a/tests/engine/app/automation/atomic-tools.test.ts b/tests/engine/editor/history/atomic-tools.test.tssimilarity index 66%rename from tests/engine/app/automation/atomic-tools.test.tsrename to tests/engine/editor/history/atomic-tools.test.tsindex b341b009a..8baf10016 100644--- a/tests/engine/app/automation/atomic-tools.test.ts+++ b/tests/engine/editor/history/atomic-tools.test.ts@@ -1,13 +1,11 @@import { describe, expect, test } from 'bun:test'-import { createEditor } from '@open-pencil/core/editor'+import { createEditor, executeAtomicTool } from '@open-pencil/core/editor'import { FigmaAPI } from '@open-pencil/core/figma-api'import { ALL_TOOLS, type ToolDef } from '@open-pencil/core/tools'import { SceneGraph } from '@open-pencil/scene-graph'import { UndoManager } from '@open-pencil/scene-graph/undo'-import { executeAtomicTool } from '@/app/automation/execution/atomic'-function setup() {const graph = new SceneGraph()const undo = new UndoManager()@@ -96,12 +94,10 @@ describe('atomic agent tools', () => {})test('partial failures roll back without adding history', () => {- const { figma, editor, undo, rectangle } = setup()+ const { figma, editor, undo, rectangle, tool } = setup()const def: ToolDef = {- name: 'set_opacity',- params: {},+ ...tool('set_opacity'),description: 'failure seam',- mutates: true,execute: () => {rectangle.opacity = 0.25throw new Error('Failed')@@ -112,6 +108,77 @@ describe('atomic agent tools', () => {expect(undo.canUndo).toBe(false)})+ test.each([+ 'create node',+ 'delete node',+ 'create variable',+ 'delete variable',+ 'reparent',+ 'delete collection'+ ])('rolls back forbidden %s and preserves graph bookkeeping', (operation) => {+ const { graph, figma, editor, undo, rectangle, tool } = setup()+ const collection = graph.createCollection('Values')+ const variable = graph.createVariable('Spacing', 'FLOAT', collection.id, 8)+ const component = figma.createComponent()+ const instance = component.createInstance()+ const nodes = structuredClone(graph.nodes)+ const variables = structuredClone(graph.variables)+ const collections = structuredClone(graph.variableCollections)+ const index = structuredClone(graph.instanceIndex)+ const modes = structuredClone(graph.activeMode)+ const original = graph.getNode(instance.id)+ const def: ToolDef = {+ ...tool('set_opacity'),+ execute: () => {+ rectangle.opacity = 0.25+ switch (operation) {+ case 'create node':+ component.createInstance()+ break+ case 'delete node':+ graph.deleteNode(instance.id)+ break+ case 'create variable':+ graph.createVariable('New', 'FLOAT', collection.id, 4)+ break+ case 'delete variable':+ graph.removeVariable(variable.id)+ break+ case 'reparent':+ graph.reparentNode(rectangle.id, component.id)+ break+ case 'delete collection':+ graph.removeCollection(collection.id)+ break+ }+ throw new Error('Original failure')+ }+ }+ expect(() => executeAtomicTool(editor, figma, def, {})).toThrow('Original failure')+ expect(graph.nodes).toEqual(nodes)+ expect(graph.variables).toEqual(variables)+ expect(graph.variableCollections).toEqual(collections)+ expect(graph.instanceIndex).toEqual(index)+ expect(graph.activeMode).toEqual(modes)+ expect(graph.getNode(instance.id)).toBe(original)+ expect(undo.canUndo).toBe(false)+ })++ test('rejects a structural edit even when the callback reports success', () => {+ const { graph, figma, editor, undo, tool } = setup()+ const nodes = structuredClone(graph.nodes)+ const def: ToolDef = {+ ...tool('set_opacity'),+ execute: () => {+ figma.createRectangle()+ return { ok: true }+ }+ }+ expect(() => executeAtomicTool(editor, figma, def, {})).toThrow('must not create or remove')+ expect(graph.nodes).toEqual(nodes)+ expect(undo.canUndo).toBe(false)+ })+test('error results roll back; no-op operations do not create history', () => {const { figma, editor, undo, rectangle, tool } = setup()executeAtomicTool(editor, figma, tool('set_opacity'), { id: rectangle.id, value: 1 })diff --git a/tests/engine/io/svg/import.test.ts b/tests/engine/io/svg/import.test.tsindex c2a4c1000..de88b716d 100644--- a/tests/engine/io/svg/import.test.ts+++ b/tests/engine/io/svg/import.test.ts@@ -198,9 +198,10 @@ describe('import_svg', () => {expect(result.error).toContain('No supported SVG elements')})- test('returns error for missing svg param', async () => {- const result = (await importSVG.execute(figma, {})) as { error: string }- expect(result.error).toContain('required')+ test('rejects a missing svg input before executing', () => {+ const nodeCount = graph.nodes.size+ expect(() => importSVG.execute(figma, {})).toThrow('Expected "svg"')+ expect(graph.nodes.size).toBe(nodeCount)})test('handles polygon and polyline', async () => {diff --git a/tests/engine/mcp/server/security.test.ts b/tests/engine/mcp/server/security.test.tsindex e80c9597b..72422858f 100644--- a/tests/engine/mcp/server/security.test.ts+++ b/tests/engine/mcp/server/security.test.ts@@ -6,11 +6,10 @@ import { dirname, join } from 'node:path'import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'import * as v from 'valibot'-import { toolInputEntries } from '@open-pencil/core/tools'+import { toolNumber } from '@open-pencil/core/tools'import { SceneGraph } from '@open-pencil/scene-graph'import { startServer } from '#mcp/server'-import { toolSchema } from '#mcp/tool/schema'import type { DiscoveryInfo } from '#mcp/transport/discovery'import {@@ -198,10 +197,7 @@ describe('MCP server /rpc auth skip', () => {// ---------------------------------------------------------------------------describe('MCP numeric input coercion', () => {- const params = {- x: { type: 'number' as const, description: 'x', required: true, min: 0, max: 100 }- }- const schema = toolSchema(params, toolInputEntries(v, params), {})+ const schema = v.object({ x: v.pipe(toolNumber(), v.minValue(0), v.maxValue(100)) })test('accepts numeric strings through Standard Schema validation', async () => {expect(await schema['~standard'].validate({ x: '42' })).toMatchObject({ value: { x: 42 } })diff --git a/tests/engine/tools/ai-adapter.test.ts b/tests/engine/tools/ai-adapter.test.tsindex da3453934..632374931 100644--- a/tests/engine/tools/ai-adapter.test.ts+++ b/tests/engine/tools/ai-adapter.test.ts@@ -1,8 +1,6 @@import { describe, expect, test } from 'bun:test'-import { valibotSchema } from '@ai-sdk/valibot'import { tool } from 'ai'-import * as v from 'valibot'import { ALL_TOOLS, FigmaAPI, SceneGraph, toolsToAI } from '@open-pencil/core'@@ -29,7 +27,7 @@ function setup() {getFigma: () => figma,onAfterExecute: () => undefined},- { v, valibotSchema, tool }+ { tool })return { graph, figma, tools }@@ -118,7 +116,7 @@ describe('AI adapter', () => {return def.execute(target, args)}},- { v, valibotSchema, tool }+ { tool })await adapterTool(tools, 'create_shape').execute({ type: 'RECTANGLE' })@@ -138,7 +136,7 @@ describe('AI adapter', () => {onBeforeExecute: () => calls.push('before'),onAfterExecute: () => calls.push('after')},- { v, valibotSchema, tool }+ { tool })const listPages = adapterTool(tools, 'list_pages')@@ -160,7 +158,7 @@ describe('AI adapter', () => {afterCalled = true}},- { v, valibotSchema, tool }+ { tool })const evalTool = adapterTool(tools, 'eval')diff --git a/tests/engine/tools/create.test.ts b/tests/engine/tools/create.test.tsindex c9635a1a2..56e4e82a9 100644--- a/tests/engine/tools/create.test.ts+++ b/tests/engine/tools/create.test.ts@@ -1,5 +1,9 @@import { describe, expect, test } from 'bun:test'+// 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 { expectDefined } from '#tests/helpers/assert'import { getTool, setupToolTest, type ToolResult } from '#tests/helpers/tools'@@ -30,7 +34,11 @@ describe('create_shape', () => {test('names every supported node type in the tool description', () => {const tool = getTool('create_shape')- const supportedTypes = tool.params.type.enum ?? []+ const property = toJSONSchema(tool.input, { typeMode: 'input' }).properties?.type+ const supportedTypes = v.parse(+ v.array(v.string()),+ typeof property === 'object' ? property.enum : undefined+ )expect(supportedTypes.length).toBeGreaterThan(0)expect(supportedTypes.filter((type) => !tool.description.includes(type))).toEqual([])diff --git a/tests/engine/tools/input.test.ts b/tests/engine/tools/input.test.tsnew file mode 100644index 000000000..20c8cfd31--- /dev/null+++ b/tests/engine/tools/input.test.ts@@ -0,0 +1,55 @@+import { describe, expect, test } from 'bun:test'++// eslint-disable-next-line open-pencil/no-mixed-case-acronym-identifiers -- Upstream export spelling.+import { toStandardJsonSchema as toStandardJSONSchema } from '@valibot/to-json-schema'+import * as v from 'valibot'++import { toolNumber } from '@open-pencil/core/tools'++import { getTool, setupToolTest } from '#tests/helpers/tools'++describe('native tool input contracts', () => {+ const schema = v.object({ value: toolNumber(v.pipe(v.number(), v.minValue(0), v.maxValue(100))) })++ test.each([Infinity, -Infinity, Number.NaN, 'Infinity', '-Infinity', 'NaN', '1e999', 'abc'])(+ 'rejects non-finite or invalid numeric input %s',+ async (value) => {+ expect(v.safeParse(schema, { value }).success).toBe(false)+ const standard = toStandardJSONSchema(schema)+ expect((await standard['~standard'].validate({ value })).issues).toBeDefined()+ }+ )++ test('numeric strings share numeric bounds and output types', () => {+ expect(v.parse(schema, { value: '42' })).toEqual({ value: 42 })+ expect(v.safeParse(schema, { value: '101' }).success).toBe(false)+ expect(v.safeParse(schema, { value: '-1' }).success).toBe(false)+ })++ test('JSON Schema advertises canonical numeric bounds and the string compatibility input', () => {+ const standard = toStandardJSONSchema(schema)+ expect(standard['~standard'].jsonSchema.input({ target: 'draft-07' })).toMatchObject({+ properties: {+ value: { anyOf: [{ type: 'number', minimum: 0, maximum: 100 }, { type: 'string' }] }+ }+ })+ })++ test('direct execution validates and normalizes the same declared schema', () => {+ const { figma } = setupToolTest()+ const node = figma.createRectangle()+ const tool = getTool('set_opacity')+ tool.execute(figma, { id: node.id, value: '0.5' })+ expect(node.opacity).toBe(0.5)+ expect(() => tool.execute(figma, { id: node.id, value: 'Infinity' })).toThrow()+ expect(node.opacity).toBe(0.5)+ })++ test('defaults and enum aliases remain schema-owned', () => {+ const tool = getTool('create_shape')+ const args = v.parse(tool.input, { type: 'RECTANGLE', x: 0, y: 0, width: 10, height: 10 })+ expect(args.type).toBe('RECTANGLE')+ expect(v.parse(getTool('get_components').input, {}).source).toBe('all')+ expect(v.safeParse(tool.input, { type: 'not-a-shape' }).success).toBe(false)+ })+})diff --git a/tests/engine/tools/registry.test.ts b/tests/engine/tools/registry.test.tsindex 3dde31fb6..c737bf58c 100644--- a/tests/engine/tools/registry.test.ts+++ b/tests/engine/tools/registry.test.ts@@ -1,28 +1,34 @@import { describe, expect, test } from 'bun:test'+// eslint-disable-next-line open-pencil/no-mixed-case-acronym-identifiers -- Upstream export spelling.+import { toJsonSchema as toJSONSchema } from '@valibot/to-json-schema'++import { isAtomicTool } from '@open-pencil/core/tools'+import { ALL_TOOLS } from '#tests/helpers/tools'describe('tool definitions', () => {- test('all tools have unique names', () => {- const names = ALL_TOOLS.map((t) => t.name)+ test('all tools have unique names and native input schemas', () => {+ const names = ALL_TOOLS.map((tool) => tool.name)expect(new Set(names).size).toBe(names.length)- })-- test('all tools have description and params', () => {- for (const t of ALL_TOOLS) {- expect(t.name).toBeTruthy()- expect(t.description).toBeTruthy()- expect(typeof t.params).toBe('object')- expect(typeof t.execute).toBe('function')+ for (const tool of ALL_TOOLS) {+ expect(tool.name).toBeTruthy()+ expect(tool.description).toBeTruthy()+ expect(typeof tool.execute).toBe('function')+ expect(toJSONSchema(tool.input, { typeMode: 'input' }).type).toBe('object')}})- test('required params are marked', () => {- for (const t of ALL_TOOLS) {- for (const param of Object.values(t.params)) {- expect(typeof param.type).toBe('string')- expect(typeof param.description).toBe('string')- }+ test('browser exposure is explicit and restricted to inspection or atomic property edits', () => {+ for (const tool of ALL_TOOLS) {+ expect(tool.mutates).toBe(tool.execution.mutation !== 'none')+ if (!tool.exposure.webmcp) continue+ expect(tool.execution.mutation === 'none' || isAtomicTool(tool)).toBe(true)+ expect(+ tool.capabilities.every(+ (capability) => capability === 'document:read' || capability === 'document:write'+ )+ ).toBe(true)}})})