AI-native design editor. Open-source Figma alternative.
Port analyze/diff tools from figma-use, split tools into domain files
Danila Poyarkov661b83e74914
diff --git a/AGENTS.md b/AGENTS.mdindex e5cdcc57b..77939c985 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -58,7 +58,7 @@ The root app (`src/`) is the Tauri/Vite desktop editor. Its `src/engine/` files### Before committing-Run all quality gates:+Run all quality gates (see [Code quality](#code-quality) for the self-review checklist):```shbun run check # oxlint + typecheck@@ -85,14 +85,23 @@ When adding features, update `CHANGELOG.md` (Unreleased section) and `README.md`## Tools (AI / MCP / CLI)-- Tool operations are defined once in `packages/core/src/tools/schema.ts` as framework-agnostic `ToolDef` objects+- Tool operations live in `packages/core/src/tools/` as framework-agnostic `ToolDef` objects, split by domain:+ - `schema.ts` — `ToolDef` type, `defineTool()`, shared helpers (`nodeSummary`, `nodeToResult`)+ - `read.ts` — query tools: selection, find, pages, fonts, components+ - `create.ts` — shape/component/page creation, JSX render+ - `modify.ts` — property setters: fills, strokes, effects, text, layout+ - `structure.ts` — tree ops: delete, clone, reparent, group, arrange+ - `variables.ts` — variable/collection CRUD and binding+ - `vector.ts` — boolean ops, paths, viewport, SVG/image export+ - `analyze.ts` — analyze (colors, typography, spacing, clusters), diff, eval+ - `registry.ts` — assembles all tools into the `ALL_TOOLS` array- Each tool has: name, description, typed params, and an `execute(figma: FigmaAPI, args)` function- `defineTool()` gives type-safe params in the execute body; the array `ALL_TOOLS` erases the generics for adapters- AI adapter (`packages/core/src/tools/ai-adapter.ts`): `toolsToAI()` converts ToolDefs → valibot schemas + Vercel AI `tool()` wrappers- `src/ai/tools.ts` is just a thin wire: creates FigmaAPI from editor store, calls `toolsToAI()`- CLI commands (`packages/cli/src/commands/`) are **not** generated from ToolDefs — they have custom agentfmt formatting, tree walking, pagination. The `eval` command is the CLI's access to all ToolDef operations via FigmaAPI.- MCP adapter (`packages/mcp/src/server.ts`): `createServer()` converts ToolDefs → zod schemas + MCP `registerTool()`. Adds `open_file`, `save_file`, `new_document` for headless file ops. Two entry points: `index.ts` (stdio), `http.ts` (Hono + Streamable HTTP with sessions).-- To add a new tool: add a `defineTool()` in `schema.ts`, add to `ALL_TOOLS` array — it's instantly available in AI chat, MCP, and via `eval` in CLI+- To add a new tool: add a `defineTool()` in the appropriate domain file, add to `ALL_TOOLS` in `registry.ts` — it's instantly available in AI chat, MCP, and via `eval` in CLI- `FigmaAPI` (`packages/core/src/figma-api.ts`) is the execution target for all tools — Figma Plugin API compatible, uses Symbols for hidden internals## Collaboration@@ -113,14 +122,42 @@ When adding features, update `CHANGELOG.md` (Unreleased section) and `README.md`- No `any` — use proper types, generics, declaration merging- No `!` non-null assertions — use guards, `?.`, `??`- No `Math.random()` — use `crypto.getRandomValues()` everywhere+- No inline type definitions when a named type exists — use `Color` not `{ r: number; g: number; b: number; a: number }`, use `Vector` not `{ x: number; y: number }`, use `SceneNode` / `Effect` / `Fill` / `Stroke` from `scene-graph.ts` instead of re-spelling their shapes inline- Shared types (GUID, Color, Vector, Matrix, Rect) live in `packages/core/src/types.ts`+- Domain types (SceneNode, Fill, Stroke, Effect, BlendMode, etc.) live in `packages/core/src/scene-graph.ts`- Window API extensions (showOpenFilePicker, queryLocalFonts) live in `src/global.d.ts` and `packages/core/src/global.d.ts`- Use `culori` for color conversions — don't reimplement parseColor/colorToRgba-- Use `@vueuse/core` hooks (useEventListener, etc.) — don't do manual addEventListener/removeEventListener+- Use `@vueuse/core` hooks — prefer higher-level composables (`useBreakpoints`, `useEventListener`, `onClickOutside`, etc.) over raw APIs (`useMediaQuery`, manual `addEventListener`)+- No module-level mutable state in components — use the editor store+- Prefer `tw-animate-css` for animations — don't hand-write `<style>` transition keyframes+- No duplicated component logic — if two components share data (icon maps, util functions, constants), export from one place and import in both- `packages/core/src/kiwi/kiwi-schema/` is vendored — don't modify- Core code must guard browser APIs: `typeof window !== 'undefined'`, `typeof document === 'undefined'`- Constants in `src/constants.ts` — no magic numbers in components or composables+## Code quality++Before submitting a PR, run the full quality gate and do a self-review:++```sh+bun run check # oxlint + typecheck — zero errors required+bun run format # oxfmt with import sorting+bun run test:dupes # jscpd — must stay under 3% duplication+bun run test:unit # bun:test+bun run test # Playwright E2E+```++Self-review checklist:+- Run `bun run test:dupes` — if duplication rises, extract shared helpers or use existing types+- No inline type definitions that duplicate named types (Color, Vector, SceneNode, Effect, Fill, Stroke, etc.)+- No copy-pasted logic — extract into functions. If two components share a util, icon map, or data structure, export from one place. If `jscpd` flags it, fix it.+- Use precise union types — `'closed' | 'half' | 'full'` not `number | string | null`+- Files should stay under ~600 lines — split by domain when they grow (see `packages/core/src/tools/` for the pattern)+- `structuredClone` for deep copies, never shallow spread when mutating nested objects+- Don't hand-roll what a dependency already does. Check existing deps first (`package.json`, `packages/*/package.json`). If none covers it, find a quality library instead of inlining an implementation — e.g. use `diff` for unified diffs, not a custom line-by-line loop; use `culori` for color math, not manual RGB parsing+- Check Reka UI for existing components (Dialog, Popover, DropdownMenu, Select, Tooltip, Toast, etc.) before building custom ones — especially dropdowns, popovers, and modals++## Rendering- Canvas is CanvasKit (Skia WASM) on a WebGL surface, not DOMdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 397eb489b..4cd601072 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,15 @@## Unreleased+### Features++- New AI/MCP tools: `analyze_colors`, `analyze_typography`, `analyze_spacing`, `analyze_clusters`, `diff_create`, `diff_show`, `get_components`, `get_current_page`, `arrange`, `node_to_component`++### Improvements++- Split tools into domain files (read, create, modify, structure, variables, vector, analyze) — easier to navigate and extend+- Replace inline type definitions with named types (`Color`, `Vector`, `SceneNode`) across the codebase+## 0.7.0 — 2026-03-05### Featuresdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 972042af9..3221034af 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -23,8 +23,8 @@ Run all of these before submitting a PR:bun run check # oxlint + typecheckbun run format # oxfmt with import sortingbun run test:dupes # jscpd < 3% duplication-bun test tests/engine/ # unit tests-bun run test # Playwright E2E (requires dev server)+bun run test:unit # bun:test (tests/engine/)+bun run test # Playwright E2E (auto-starts dev server)```## Project structure@@ -32,16 +32,21 @@ bun run test # Playwright E2E (requires dev server)- `packages/core` — scene graph, renderer, layout, codec (zero DOM deps)- `packages/cli` — headless CLI for .fig inspection and export- `packages/mcp` — MCP server for AI tools (stdio + HTTP)+- `packages/acp` — ACP (Agent Client Protocol) server+- `packages/docs` — VitePress documentation site (openpencil.dev)- `src/` — Tauri/Vite desktop editor## Conventions+See [`AGENTS.md`](./AGENTS.md) for the full architecture reference, code conventions, and quality checklist. Key points:+- Bun runtime, not Node- Tailwind 4 for styles, no inline CSS or `<style>` blocks- No `any`, no `!` non-null assertions- `@/` import alias for app code, relative imports within core- Use `crypto.getRandomValues()`, never `Math.random()`- Icons via unplugin-icons (`<icon-lucide-*>`)+- Use existing deps and Reka UI components before hand-rolling (see AGENTS.md → Code quality)## Test fixturesdiff --git a/bun.lock b/bun.lockindex dddbec6d7..84c0a0faf 100644--- a/bun.lock+++ b/bun.lock@@ -62,7 +62,7 @@},"packages/acp": {"name": "@open-pencil/acp",- "version": "0.5.1",+ "version": "0.7.0","bin": {"openpencil-acp": "./dist/index.js",},@@ -77,7 +77,7 @@},"packages/cli": {"name": "@open-pencil/cli",- "version": "0.6.0",+ "version": "0.7.0","bin": {"openpencil": "./src/index.ts",},@@ -93,16 +93,18 @@},"packages/core": {"name": "@open-pencil/core",- "version": "0.6.0",+ "version": "0.7.0","dependencies": {"canvaskit-wasm": "^0.40.0","culori": "^4.0.2",+ "diff": "^8.0.3","fflate": "^0.8.2","fzstd": "^0.1.1","yoga-layout": "^3.2.1",},"devDependencies": {"@types/culori": "^4.0.1",+ "@types/diff": "^8.0.0","typescript": "~5.8.3",},},@@ -115,7 +117,7 @@},"packages/mcp": {"name": "@open-pencil/mcp",- "version": "0.6.0",+ "version": "0.7.0","bin": {"openpencil-mcp": "./dist/index.js","openpencil-mcp-http": "./dist/http.js",@@ -742,6 +744,8 @@"@types/debug": ["@types/[email protected]", "", { "dependencies": { "@types/ms": "*" } }, "sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ=="],+ "@types/diff": ["@types/[email protected]", "", { "dependencies": { "diff": "*" } }, "sha512-o7jqJM04gfaYrdCecCVMbZhNdG6T1MHg/oQoRFdERLV+4d+V7FijhiEAbFu0Usww84Yijk9yH58U4Jk4HbtzZw=="],+"@types/estree": ["@types/[email protected]", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="],"@types/hast": ["@types/[email protected]", "", { "dependencies": { "@types/unist": "*" } }, "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ=="],@@ -1006,6 +1010,8 @@"devlop": ["[email protected]", "", { "dependencies": { "dequal": "^2.0.0" } }, "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="],+ "diff": ["[email protected]", "", {}, "sha512-qejHi7bcSD4hQAZE0tNAawRK1ZtafHDmMTMkrrIGgSLl7hTnQHmKCeB45xAcbfTqK2zowkM3j3bHt/4b/ARbYQ=="],+"dns-over-http-resolver": ["[email protected]", "", { "dependencies": { "quick-lru": "^7.0.0", "weald": "^1.0.2" } }, "sha512-Qnq8HhNRuMnA61pf1lVPlStCAv1BVrraCx0umPESWgYKf995tUMF5oNhW59PKdnf7E8d5yqwHlEoFywXjsNMCw=="],"doctypes": ["[email protected]", "", {}, "sha512-LLBi6pEqS6Do3EKQ3J0NqHWV5hhb78Pi8vvESYwyOy2c31ZEZVdtitdzsQsKb7878PEERhzUk0ftqGhG6Mz+pQ=="],diff --git a/packages/core/package.json b/packages/core/package.jsonindex a95abaad5..bac1fafa2 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -30,12 +30,14 @@"dependencies": {"canvaskit-wasm": "^0.40.0","culori": "^4.0.2",+ "diff": "^8.0.3","fflate": "^0.8.2","fzstd": "^0.1.1","yoga-layout": "^3.2.1"},"devDependencies": {"@types/culori": "^4.0.1",+ "@types/diff": "^8.0.0","typescript": "~5.8.3"}}diff --git a/packages/core/src/color.ts b/packages/core/src/color.tsindex ea180f6ea..6f16e3663 100644--- a/packages/core/src/color.ts+++ b/packages/core/src/color.ts@@ -35,7 +35,7 @@ export function colorToRgba255(color: Color) {}}-export function rgba255ToColor(rgba: { r: number; g: number; b: number; a: number }): Color {+export function rgba255ToColor(rgba: Color): Color {return { r: rgba.r / 255, g: rgba.g / 255, b: rgba.b / 255, a: rgba.a }}diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.tsindex e3a2e1bea..4ef728a8d 100644--- a/packages/core/src/constants.ts+++ b/packages/core/src/constants.ts@@ -74,6 +74,15 @@ export const COMPONENT_LABEL_ICON_GAP = 4export const RULER_TARGET_PIXEL_SPACING = 100export const RULER_MAJOR_TOLERANCE = 0.01+export const FLASH_COLOR = SELECTION_COLOR+export const FLASH_ATTACK_MS = 200+export const FLASH_HOLD_MS = 400+export const FLASH_RELEASE_MS = 300+export const FLASH_STROKE_WIDTH = 2+export const FLASH_PADDING = 5+export const FLASH_OVERSHOOT = 30+export const FLASH_RADIUS = 4+export const TEXT_SELECTION_COLOR = { r: 0.26, g: 0.52, b: 0.96, a: 0.3 }export const TEXT_CARET_COLOR = BLACKexport const TEXT_CARET_WIDTH = 1diff --git a/packages/core/src/figma-api.ts b/packages/core/src/figma-api.tsindex 91b1e1a71..9807d606c 100644--- a/packages/core/src/figma-api.ts+++ b/packages/core/src/figma-api.ts@@ -12,7 +12,7 @@ import type {VariableType,VariableValue} from './scene-graph'-import type { Rect } from './types'+import type { Rect, Vector } from './types'const MIXED = Symbol('mixed')@@ -1251,11 +1251,11 @@ export class FigmaAPI {private _viewport = { x: 0, y: 0, zoom: 1 }- get viewport(): { center: { x: number; y: number }; zoom: number } {+ get viewport(): { center: Vector; zoom: number } {return { center: { x: this._viewport.x, y: this._viewport.y }, zoom: this._viewport.zoom }}- set viewport(v: { center: { x: number; y: number }; zoom: number }) {+ set viewport(v: { center: Vector; zoom: number }) {this._viewport = { x: v.center.x, y: v.center.y, zoom: v.zoom }}@@ -1272,6 +1272,11 @@ export class FigmaAPI {commitUndo(): void {}triggerUndo(): void {}++ exportImage?: (+ nodeIds: string[],+ options: { scale?: number; format?: 'PNG' | 'JPG' | 'WEBP'; quality?: number }+ ) => Promise<Uint8Array | null>}export { FigmaNodeProxy }diff --git a/packages/core/src/kiwi/kiwi-convert.ts b/packages/core/src/kiwi/kiwi-convert.tsindex c948a21ab..e90255f47 100644--- a/packages/core/src/kiwi/kiwi-convert.ts+++ b/packages/core/src/kiwi/kiwi-convert.ts@@ -41,9 +41,9 @@ export function guidToString(guid: GUID): string {return `${guid.sessionID}:${guid.localID}`}-function convertColor(color?: { r: number; g: number; b: number; a: number }): Color {+function convertColor(color?: Partial<Color>): Color {if (!color) return { ...BLACK }- return { r: color.r, g: color.g, b: color.b, a: color.a }+ return { r: color.r ?? 0, g: color.g ?? 0, b: color.b ?? 0, a: color.a ?? 1 }}function imageHashToString(hash: Record<string, number>): string {diff --git a/packages/core/src/renderer.ts b/packages/core/src/renderer.tsindex 5485ca435..0169a9be5 100644--- a/packages/core/src/renderer.ts+++ b/packages/core/src/renderer.ts@@ -56,7 +56,15 @@ import {TEXT_SELECTION_COLOR,TEXT_CARET_COLOR,TEXT_CARET_WIDTH,- DEFAULT_FONT_FAMILY+ DEFAULT_FONT_FAMILY,+ FLASH_COLOR,+ FLASH_ATTACK_MS,+ FLASH_HOLD_MS,+ FLASH_RELEASE_MS,+ FLASH_STROKE_WIDTH,+ FLASH_PADDING,+ FLASH_OVERSHOOT,+ FLASH_RADIUS} from './constants'import { isFontLoaded, getCJKFallbackFamily } from './fonts'import { vectorNetworkToPath, geometryBlobToPath } from './vector'@@ -176,6 +184,8 @@ export class SkiaRenderer {private worldViewport = { x: 0, y: 0, w: 0, h: 0 }private _nodeCount = 0private _culledCount = 0+ private _flashes: Array<{ nodeId: string; startTime: number }> = []+ private _flashPaint: Paint | null = nullprivate color4f(r: number, g: number, b: number, a: number): Float32Array {const c = this._tmpColor@@ -367,6 +377,14 @@ export class SkiaRenderer {}}+ flashNode(nodeId: string): void {+ this._flashes.push({ nodeId, startTime: performance.now() })+ }++ get hasActiveFlashes(): boolean {+ return this._flashes.length > 0+ }+hitTestSectionTitle(graph: SceneGraph, canvasX: number, canvasY: number): SceneNode | null {if (!this.sectionTitleFont) return null@@ -584,6 +602,7 @@ export class SkiaRenderer {p.beginPhase('render:selection')this.drawSelection(canvas, graph, selectedIds, overlays)p.endPhase('render:selection')+ this.drawFlashes(canvas, graph)this.drawSnapGuides(canvas, overlays.snapGuides)this.drawMarquee(canvas, overlays.marquee)this.drawLayoutInsertIndicator(canvas, overlays.layoutInsertIndicator)@@ -1008,6 +1027,76 @@ export class SkiaRenderer {canvas.drawRect(rect, this.selectionPaint)}+ // --- Node flash effect ---++ private drawFlashes(canvas: Canvas, graph: SceneGraph): void {+ if (this._flashes.length === 0) return++ const now = performance.now()+ const ck = this.ck+ const totalMs = FLASH_ATTACK_MS + FLASH_HOLD_MS + FLASH_RELEASE_MS++ if (!this._flashPaint) {+ this._flashPaint = new ck.Paint()+ this._flashPaint.setStyle(ck.PaintStyle.Stroke)+ this._flashPaint.setAntiAlias(true)+ }++ const paint = this._flashPaint+ const zoom = this.zoom++ for (let i = this._flashes.length - 1; i >= 0; i--) {+ const flash = this._flashes[i]+ const elapsed = now - flash.startTime+ if (elapsed > totalMs) {+ this._flashes.splice(i, 1)+ continue+ }++ const node = graph.getNode(flash.nodeId)+ if (!node) {+ this._flashes.splice(i, 1)+ continue+ }++ const abs = graph.getAbsolutePosition(flash.nodeId)+ const sx = abs.x * zoom + this.panX+ const sy = abs.y * zoom + this.panY+ const sw = node.width * zoom+ const sh = node.height * zoom++ let opacity: number+ let extraPad: number++ if (elapsed < FLASH_ATTACK_MS) {+ const t = elapsed / FLASH_ATTACK_MS+ const ease = t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2+ opacity = ease+ extraPad = (1 - ease) * FLASH_OVERSHOOT / zoom+ } else if (elapsed < FLASH_ATTACK_MS + FLASH_HOLD_MS) {+ opacity = 1+ extraPad = 0+ } else {+ const t = (elapsed - FLASH_ATTACK_MS - FLASH_HOLD_MS) / FLASH_RELEASE_MS+ opacity = 1 - t * t+ extraPad = 0+ }++ const pad = FLASH_PADDING + extraPad+ const r = FLASH_RADIUS++ paint.setColor(ck.Color4f(FLASH_COLOR.r, FLASH_COLOR.g, FLASH_COLOR.b, opacity))+ paint.setStrokeWidth(FLASH_STROKE_WIDTH)++ const rect = ck.RRectXY(+ ck.LTRBRect(sx - pad, sy - pad, sx + sw + pad, sy + sh + pad),+ r,+ r+ )+ canvas.drawRRect(rect, paint)+ }+ }+// --- Layout insert indicator ---private drawLayoutInsertIndicator(diff --git a/packages/core/src/tools/ai-adapter.ts b/packages/core/src/tools/ai-adapter.tsindex 55eb3d263..bbaf867e6 100644--- a/packages/core/src/tools/ai-adapter.ts+++ b/packages/core/src/tools/ai-adapter.ts@@ -12,6 +12,47 @@ export interface AIAdapterOptions {getFigma: () => FigmaAPIonBeforeExecute?: () => voidonAfterExecute?: () => void+ onFlashNodes?: (nodeIds: string[]) => void+}++const READ_ONLY_TOOLS = new Set([+ 'get_selection',+ 'get_page_tree',+ 'get_node',+ 'find_nodes',+ 'list_pages',+ 'list_variables',+ 'list_collections',+ 'node_bounds',+ 'node_ancestors',+ 'node_children',+ 'node_tree',+ 'node_bindings',+ 'list_fonts',+ 'get_variable',+ 'find_variables',+ 'get_collection',+ 'export_svg',+ 'export_image',+ 'viewport_get',+ 'page_bounds',+ 'eval'+])++function extractNodeIds(result: unknown): string[] {+ if (!result || typeof result !== 'object') return []+ const obj = result as Record<string, unknown>+ const ids: string[] = []+ if (typeof obj.id === 'string') ids.push(obj.id)+ if (typeof obj.deleted === 'string') return []+ if (Array.isArray(obj.selection)) {+ for (const item of obj.selection) {+ if (item && typeof item === 'object' && typeof (item as Record<string, unknown>).id === 'string') {+ ids.push((item as Record<string, unknown>).id as string)+ }+ }+ }+ return ids}export function toolsToAI(@@ -32,13 +73,19 @@ export function toolsToAI(shape[key] = paramToValibot(v, param)}+ const isReadOnly = READ_ONLY_TOOLS.has(def.name)result[def.name] = tool({description: def.description,inputSchema: valibotSchema(v.object(shape as any)),execute: async (args: Record<string, unknown>) => {options.onBeforeExecute?.()try {- return await def.execute(options.getFigma(), args as any)+ const execResult = await def.execute(options.getFigma(), args as any)+ if (!isReadOnly && options.onFlashNodes) {+ const ids = extractNodeIds(execResult)+ if (ids.length > 0) options.onFlashNodes(ids)+ }+ return execResult} finally {options.onAfterExecute?.()}diff --git a/packages/core/src/tools/analyze.ts b/packages/core/src/tools/analyze.tsnew file mode 100644index 000000000..872a47af1--- /dev/null+++ b/packages/core/src/tools/analyze.ts@@ -0,0 +1,600 @@+import { createTwoFilesPatch } from 'diff'++import { colorToHex, parseColor } from '../color'++import { defineTool } from './schema'++import type { Color } from '../types'+import type { SceneNode } from '../scene-graph'+import type { FigmaAPI } from '../figma-api'++// ─── Color analysis helpers ───────────────────────────────────++function colorDistance(c1: Color, c2: Color): number {+ return Math.sqrt(+ ((c1.r - c2.r) * 255) ** 2 + ((c1.g - c2.g) * 255) ** 2 + ((c1.b - c2.b) * 255) ** 2+ )+}++interface ColorEntry {+ hex: string+ color: Color+ count: number+ variableName: string | null+}++function trackColor(+ colorMap: Map<string, ColorEntry>,+ color: Color,+ variableName: string | null+) {+ const hex = colorToHex(color)+ const entry = colorMap.get(hex)+ if (entry) {+ entry.count+++ if (!entry.variableName && variableName) entry.variableName = variableName+ } else {+ colorMap.set(hex, { hex, color, count: 1, variableName })+ }+}++// ─── Diff helpers ─────────────────────────────────────────────++function serializeNodeProps(raw: SceneNode): string {+ const lines: string[] = []+ lines.push(`type: ${raw.type}`)+ lines.push(`size: ${raw.width} ${raw.height}`)+ lines.push(`pos: ${raw.x} ${raw.y}`)++ const solidFill = raw.fills.find((f) => f.type === 'SOLID' && f.visible !== false)+ if (solidFill) lines.push(`fill: ${colorToHex(solidFill.color)}`)++ const solidStroke = raw.strokes.find((s) => s.visible !== false)+ if (solidStroke) {+ lines.push(`stroke: ${colorToHex(solidStroke.color)}`)+ if (solidStroke.weight) lines.push(`strokeWeight: ${solidStroke.weight}`)+ }++ if (raw.opacity !== 1) lines.push(`opacity: ${Math.round(raw.opacity * 100) / 100}`)++ const tl = raw.topLeftRadius+ const tr = raw.topRightRadius+ const br = raw.bottomRightRadius+ const bl = raw.bottomLeftRadius+ if (tl || tr || br || bl) {+ if (tl === tr && tr === br && br === bl) {+ lines.push(`radius: ${tl}`)+ } else {+ lines.push(`radii: ${tl} ${tr} ${br} ${bl}`)+ }+ }++ if (raw.blendMode !== 'NORMAL') lines.push(`blendMode: ${raw.blendMode}`)+ if (raw.rotation !== 0) lines.push(`rotation: ${Math.round(raw.rotation * 100) / 100}`)+ if (raw.clipsContent) lines.push(`clipsContent: true`)++ for (const effect of raw.effects) {+ const parts: string[] = [effect.type]+ if (effect.radius !== undefined) parts.push(`r=${effect.radius}`)+ if (effect.color) parts.push(`c=${colorToHex(effect.color)}`)+ if (effect.offset) parts.push(`x=${effect.offset.x} y=${effect.offset.y}`)+ if (effect.spread !== undefined) parts.push(`s=${effect.spread}`)+ lines.push(`effect: ${parts.join(' ')}`)+ }++ if (raw.type === 'TEXT') {+ if (raw.text) lines.push(`text: ${JSON.stringify(raw.text)}`)+ if (raw.fontSize) lines.push(`fontSize: ${raw.fontSize}`)+ if (raw.fontFamily) lines.push(`fontFamily: ${raw.fontFamily}`)+ if (raw.fontWeight) lines.push(`fontWeight: ${raw.fontWeight}`)+ }++ if (!raw.visible) lines.push(`visible: false`)+ if (raw.locked) lines.push(`locked: true`)++ return lines.join('\n')+}++function collectNodeTree(+ figma: FigmaAPI,+ nodeId: string,+ parentPath: string,+ depth: number,+ maxDepth: number+): Map<string, { path: string; id: string; serialized: string }> {+ const result = new Map<string, { path: string; id: string; serialized: string }>()+ const raw = figma.graph.getNode(nodeId)+ if (!raw) return result++ const path = parentPath ? `${parentPath}/${raw.name}` : `/${raw.name}`+ result.set(path, { path, id: raw.id, serialized: serializeNodeProps(raw) })++ if (depth < maxDepth) {+ for (const childId of raw.childIds) {+ const childNodes = collectNodeTree(figma, childId, path, depth + 1, maxDepth)+ for (const [k, v] of childNodes) result.set(k, v)+ }+ }+ return result+}++function createUnifiedDiff(+ oldFilename: string,+ newFilename: string,+ oldContent: string,+ newContent: string+): string {+ const patch = createTwoFilesPatch(oldFilename, newFilename, oldContent, newContent, '', '')+ return patch+ .split('\n')+ .filter((l) => !l.startsWith('Index:') && l !== '===================================================================')+ .join('\n')+ .trim()+}++// ─── Analyze tools ────────────────────────────────────────────++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)'+ }+ },+ execute: (figma, args) => {+ const limit = args.limit ?? 30+ const threshold = args.threshold ?? 15+ const page = figma.currentPage+ const colorMap = new Map<string, ColorEntry>()+ let totalNodes = 0++ page.findAll((node) => {+ totalNodes+++ const raw = figma.graph.getNode(node.id)+ if (!raw) return false++ const boundVars = raw.boundVariables+ for (const fill of raw.fills) {+ if (fill.type === 'SOLID' && fill.visible !== false) {+ trackColor(colorMap, fill.color, boundVars?.['fills'] ? String(boundVars['fills']) : null)+ }+ }+ for (const stroke of raw.strokes) {+ if (stroke.visible !== false) {+ trackColor(colorMap, stroke.color, boundVars?.['strokes'] ? String(boundVars['strokes']) : null)+ }+ }+ return false+ })++ const colors = [...colorMap.values()].sort((a, b) => b.count - a.count).slice(0, limit)++ const result: Record<string, unknown> = {+ totalNodes,+ uniqueColors: colorMap.size,+ colors: colors.map((c) => ({ hex: c.hex, count: c.count, variableName: c.variableName }))+ }++ if (args.show_similar) {+ const hardcoded = [...colorMap.values()]+ .filter((c) => !c.variableName)+ .sort((a, b) => b.count - a.count)+ const used = new Set<string>()+ const clusters: { colors: string[]; totalCount: number; suggestedHex: string }[] = []++ for (const color of hardcoded) {+ if (used.has(color.hex)) continue+ const cluster = [color]+ used.add(color.hex)+ for (const other of hardcoded) {+ if (used.has(other.hex)) continue+ if (colorDistance(color.color, other.color) <= threshold) {+ cluster.push(other)+ used.add(other.hex)+ }+ }+ if (cluster.length > 1) {+ clusters.push({+ colors: cluster.map((c) => c.hex),+ totalCount: cluster.reduce((sum, c) => sum + c.count, 0),+ suggestedHex: color.hex+ })+ }+ }++ result.similarClusters = clusters.sort((a, b) => b.colors.length - a.colors.length)+ }++ return result+ }+})++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']+ }+ },+ execute: (figma, args) => {+ const limit = args.limit ?? 30+ const page = figma.currentPage+ const styleMap = new Map<+ string,+ { family: string; size: number; weight: number; lineHeight: string; count: number }+ >()+ let totalTextNodes = 0++ page.findAll((node) => {+ if (node.type !== 'TEXT') return false+ totalTextNodes+++ const raw = figma.graph.getNode(node.id)+ if (!raw) return false+ const lh = raw.lineHeight === null ? 'auto' : `${raw.lineHeight}`+ const key = `${raw.fontFamily}|${raw.fontSize}|${raw.fontWeight}|${lh}`+ const entry = styleMap.get(key)+ if (entry) {+ entry.count+++ } else {+ styleMap.set(key, {+ family: raw.fontFamily,+ size: raw.fontSize,+ weight: raw.fontWeight,+ lineHeight: lh,+ count: 1+ })+ }+ return false+ })++ const styles = [...styleMap.values()].sort((a, b) => b.count - a.count)++ if (args.group_by === 'family') {+ const byFamily = new Map<string, number>()+ for (const s of styles) byFamily.set(s.family, (byFamily.get(s.family) ?? 0) + s.count)+ return {+ totalTextNodes,+ groups: [...byFamily.entries()]+ .sort((a, b) => b[1] - a[1])+ .map(([family, count]) => ({ family, count }))+ }+ }++ if (args.group_by === 'size') {+ const bySize = new Map<number, number>()+ for (const s of styles) bySize.set(s.size, (bySize.get(s.size) ?? 0) + s.count)+ return {+ totalTextNodes,+ groups: [...bySize.entries()]+ .sort((a, b) => a[0] - b[0])+ .map(([size, count]) => ({ size, count }))+ }+ }++ if (args.group_by === 'weight') {+ const byWeight = new Map<number, number>()+ for (const s of styles) byWeight.set(s.weight, (byWeight.get(s.weight) ?? 0) + s.count)+ return {+ totalTextNodes,+ groups: [...byWeight.entries()]+ .sort((a, b) => b[1] - a[1])+ .map(([weight, count]) => ({ weight, count }))+ }+ }++ return {+ totalTextNodes,+ uniqueStyles: styleMap.size,+ styles: styles.slice(0, limit)+ }+ }+})++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)' }+ },+ execute: (figma, args) => {+ const gridSize = args.grid ?? 8+ const page = figma.currentPage+ const gapMap = new Map<number, number>()+ const paddingMap = new Map<number, number>()+ let totalNodes = 0++ page.findAll((node) => {+ totalNodes+++ const raw = figma.graph.getNode(node.id)+ if (!raw) return false++ if (raw.layoutMode !== 'NONE' && raw.itemSpacing > 0) {+ gapMap.set(raw.itemSpacing, (gapMap.get(raw.itemSpacing) ?? 0) + 1)+ }++ for (const p of [raw.paddingTop, raw.paddingRight, raw.paddingBottom, raw.paddingLeft]) {+ if (p > 0) {+ paddingMap.set(p, (paddingMap.get(p) ?? 0) + 1)+ }+ }+ return false+ })++ const gaps = [...gapMap.entries()]+ .sort((a, b) => b[1] - a[1])+ .map(([value, count]) => ({ value, count, onGrid: value % gridSize === 0 }))++ const paddings = [...paddingMap.entries()]+ .sort((a, b) => b[1] - a[1])+ .map(([value, count]) => ({ value, count, onGrid: value % gridSize === 0 }))++ const offGridGaps = gaps.filter((g) => !g.onGrid)+ const offGridPaddings = paddings.filter((p) => !p.onGrid)++ return {+ totalNodes,+ gridSize,+ gaps,+ paddings,+ offGridGaps: offGridGaps.map((g) => g.value),+ offGridPaddings: offGridPaddings.map((p) => p.value)+ }+ }+})++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)' }+ },+ execute: (figma, args) => {+ const minCount = args.min_count ?? 2+ const minSize = args.min_size ?? 30+ const limit = args.limit ?? 20+ const page = figma.currentPage++ const signatureMap = new Map<+ string,+ { id: string; name: string; type: string; width: number; height: number; childCount: number }[]+ >()+ let totalNodes = 0++ page.findAll((node) => {+ totalNodes+++ const raw = figma.graph.getNode(node.id)+ if (!raw) return false+ if (raw.width < minSize || raw.height < minSize) return false+ if (raw.type === 'CANVAS' || raw.type === 'INSTANCE') return false++ const childTypes = new Map<string, number>()+ for (const childId of raw.childIds) {+ const child = figma.graph.getNode(childId)+ if (child) childTypes.set(child.type, (childTypes.get(child.type) ?? 0) + 1)+ }++ const w = Math.round(raw.width / 10) * 10+ const h = Math.round(raw.height / 10) * 10+ const childSig = [...childTypes.entries()]+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([t, c]) => `${t}:${c}`)+ .join(',')+ const signature = `${raw.type}:${w}x${h}|${childSig}`++ const list = signatureMap.get(signature) ?? []+ list.push({+ id: raw.id,+ name: raw.name,+ type: raw.type,+ width: raw.width,+ height: raw.height,+ childCount: raw.childIds.length+ })+ signatureMap.set(signature, list)+ return false+ })++ const clusters = [...signatureMap.entries()]+ .filter(([, nodes]) => nodes.length >= minCount)+ .map(([signature, nodes]) => {+ const avgW = nodes.reduce((s, n) => s + n.width, 0) / nodes.length+ const avgH = nodes.reduce((s, n) => s + n.height, 0) / nodes.length+ const widths = nodes.map((n) => n.width)+ const heights = nodes.map((n) => n.height)+ const widthRange = Math.max(...widths) - Math.min(...widths)+ const heightRange = Math.max(...heights) - Math.min(...heights)++ let confidence = 100+ if (nodes.length >= 2) {+ const base = nodes[0]!+ let score = 0+ for (const n of nodes.slice(1)) {+ const sizeDiff = Math.abs(n.width - base.width) + Math.abs(n.height - base.height)+ const childDiff = Math.abs(n.childCount - base.childCount)+ if (sizeDiff <= 4 && childDiff === 0) score+++ else if (sizeDiff <= 10 && childDiff <= 1) score += 0.8+ else if (sizeDiff <= 20 && childDiff <= 2) score += 0.6+ else score += 0.4+ }+ confidence = Math.round((score / (nodes.length - 1)) * 100)+ }++ return {+ signature,+ count: nodes.length,+ avgWidth: Math.round(avgW),+ avgHeight: Math.round(avgH),+ widthRange: Math.round(widthRange),+ heightRange: Math.round(heightRange),+ confidence,+ examples: nodes.slice(0, 3).map((n) => ({ id: n.id, name: n.name }))+ }+ })+ .sort((a, b) => b.count - a.count)+ .slice(0, limit)++ return { totalNodes, clusters }+ }+})++// ─── Diff tools ───────────────────────────────────────────────++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)' }+ },+ execute: (figma, args) => {+ const maxDepth = args.depth ?? 10+ const fromNode = figma.graph.getNode(args.from)+ const toNode = figma.graph.getNode(args.to)+ if (!fromNode) return { error: `Node "${args.from}" not found` }+ if (!toNode) return { error: `Node "${args.to}" not found` }++ const fromNodes = collectNodeTree(figma, args.from, '', 0, maxDepth)+ const toNodes = collectNodeTree(figma, args.to, '', 0, maxDepth)+ const allPaths = new Set([...fromNodes.keys(), ...toNodes.keys()])++ const patches: string[] = []+ for (const path of allPaths) {+ const fromEntry = fromNodes.get(path)+ const toEntry = toNodes.get(path)++ if (!fromEntry && toEntry) {+ const filename = `${path} #${toEntry.id}`+ const newLines = toEntry.serialized.split('\n')+ patches.push(+ `--- /dev/null\n+++ ${filename}\n@@ -0,0 +1,${newLines.length} @@\n${newLines.map((l) => `+${l}`).join('\n')}`+ )+ } else if (fromEntry && !toEntry) {+ const filename = `${path} #${fromEntry.id}`+ const oldLines = fromEntry.serialized.split('\n')+ patches.push(+ `--- ${filename}\n+++ /dev/null\n@@ -1,${oldLines.length} +0,0 @@\n${oldLines.map((l) => `-${l}`).join('\n')}`+ )+ } else if (fromEntry && toEntry && fromEntry.serialized !== toEntry.serialized) {+ patches.push(+ createUnifiedDiff(+ `${path} #${fromEntry.id}`,+ `${path} #${toEntry.id}`,+ fromEntry.serialized,+ toEntry.serialized+ )+ )+ }+ }++ if (patches.length === 0) return { diff: null, message: 'No differences found' }+ return { diff: patches.join('\n') }+ }+})++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+ }+ },+ execute: (figma, args) => {+ const raw = figma.graph.getNode(args.id)+ if (!raw) return { error: `Node "${args.id}" not found` }++ const oldContent = serializeNodeProps(raw)++ let newProps: Record<string, unknown>+ try {+ newProps = JSON.parse(args.props)+ } catch {+ return { error: 'Invalid JSON in props' }+ }++ const modified: SceneNode = structuredClone(raw)+ if (newProps.fill) {+ modified.fills = [+ { type: 'SOLID', color: parseColor(String(newProps.fill)), opacity: 1, visible: true }+ ]+ }+ if (newProps.stroke) {+ modified.strokes = [+ {+ color: parseColor(String(newProps.stroke)),+ weight: modified.strokes[0]?.weight ?? 1,+ opacity: 1,+ visible: true,+ align: modified.strokes[0]?.align ?? 'INSIDE'+ }+ ]+ }+ if (newProps.opacity !== undefined) modified.opacity = Number(newProps.opacity)+ if (newProps.radius !== undefined) {+ const r = Number(newProps.radius)+ modified.cornerRadius = r+ modified.topLeftRadius = r+ modified.topRightRadius = r+ modified.bottomRightRadius = r+ modified.bottomLeftRadius = r+ }+ if (newProps.width !== undefined) modified.width = Number(newProps.width)+ if (newProps.height !== undefined) modified.height = Number(newProps.height)+ if (newProps.x !== undefined) modified.x = Number(newProps.x)+ if (newProps.y !== undefined) modified.y = Number(newProps.y)+ if (newProps.visible !== undefined) modified.visible = Boolean(newProps.visible)+ if (newProps.locked !== undefined) modified.locked = Boolean(newProps.locked)+ if (newProps.rotation !== undefined) modified.rotation = Number(newProps.rotation)+ if (newProps.text !== undefined) modified.text = String(newProps.text)++ const newContent = serializeNodeProps(modified)++ if (oldContent === newContent) return { diff: null, message: 'No changes' }++ const filename = `/${raw.name} #${args.id}`+ return { diff: createUnifiedDiff(filename, filename, oldContent, newContent) }+ }+})++// ─── Eval escape hatch ────────────────────────────────────────++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 }+ },+ execute: async (figma, { code }) => {+ const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor+ const wrapped = code.trim().startsWith('return') ? code : `return (async () => { ${code} })()`+ const fn = new AsyncFunction('figma', wrapped)+ const result = await fn(figma)+ if (result && typeof result === 'object' && 'toJSON' in result) return result.toJSON()+ return result ?? null+ }+})diff --git a/packages/core/src/tools/create.ts b/packages/core/src/tools/create.tsnew file mode 100644index 000000000..a3e224369--- /dev/null+++ b/packages/core/src/tools/create.ts@@ -0,0 +1,181 @@+import { parseColor } from '../color'++import { defineTool, nodeSummary } from './schema'++import type { FigmaNodeProxy } from '../figma-api'++export const createShape = defineTool({+ name: 'create_shape',+ description:+ 'Create a shape on the canvas. Use FRAME for containers/cards, RECTANGLE for solid blocks, ELLIPSE for circles, TEXT for labels, SECTION for page sections.',+ 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' }+ },+ execute: (figma, args) => {+ const parentId = args.parent_id+ const parent = parentId ? figma.getNodeById(parentId) : null+ const createMap: Record<string, () => FigmaNodeProxy> = {+ FRAME: () => figma.createFrame(),+ RECTANGLE: () => figma.createRectangle(),+ ELLIPSE: () => figma.createEllipse(),+ TEXT: () => figma.createText(),+ LINE: () => figma.createLine(),+ STAR: () => figma.createStar(),+ POLYGON: () => figma.createPolygon(),+ SECTION: () => figma.createSection()+ }+ const node = createMap[args.type]!()+ node.x = args.x+ node.y = args.y+ node.resize(args.width, args.height)+ if (args.name) node.name = args.name+ if (parent) parent.appendChild(node)+ return nodeSummary(node)+ }+})++export const render = defineTool({+ name: 'render',+ description:+ 'Render JSX to design nodes. Primary creation tool — creates entire component trees in one call. Example: <Frame name="Card" w={320} h="hug" flex="col" gap={16} p={24} bg="#FFF" rounded={16}><Text size={18} weight="bold">Title</Text></Frame>',+ params: {+ jsx: { type: 'string', description: 'JSX string to render', required: true },+ x: { type: 'number', description: 'X position of the root node' },+ y: { type: 'number', description: 'Y position of the root node' },+ parent_id: { type: 'string', description: 'Parent node ID to render into' }+ },+ execute: async (figma, args) => {+ const { renderJsx } = await import('../render/render-jsx.js')+ const result = await renderJsx(figma.graph, args.jsx, {+ parentId: args.parent_id ?? figma.currentPageId,+ x: args.x,+ y: args.y+ })+ return { id: result.id, name: result.name, type: result.type, children: result.childIds }+ }+})++export const createComponent = defineTool({+ name: 'create_component',+ description: 'Convert a frame/group into a component.',+ params: {+ id: { type: 'string', description: 'Node ID to convert', required: true }+ },+ execute: (figma, { id }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ const comp = figma.createComponentFromNode(node)+ return nodeSummary(comp)+ }+})++export const createInstance = defineTool({+ name: 'create_instance',+ 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' }+ },+ execute: (figma, args) => {+ const comp = figma.getNodeById(args.component_id)+ if (!comp) return { error: `Component "${args.component_id}" not found` }+ const instance = comp.createInstance()+ if (args.x !== undefined) instance.x = args.x+ if (args.y !== undefined) instance.y = args.y+ return nodeSummary(instance)+ }+})++export const createPage = defineTool({+ name: 'create_page',+ description: 'Create a new page.',+ params: {+ name: { type: 'string', description: 'Page name', required: true }+ },+ execute: (figma, { name }) => {+ const page = figma.createPage()+ page.name = name+ return { id: page.id, name }+ }+})++export const createVector = defineTool({+ name: 'create_vector',+ description: 'Create a vector node with optional path data.',+ 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: 'VectorNetwork JSON' },+ 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' }+ },+ execute: (figma, args) => {+ const node = figma.createVector()+ node.x = args.x+ node.y = args.y+ if (args.name) node.name = args.name+ if (args.path) {+ figma.graph.updateNode(node.id, { vectorNetwork: JSON.parse(args.path) } as any)+ }+ if (args.fill) {+ node.fills = [{ type: 'SOLID', color: parseColor(args.fill), opacity: 1, visible: true }]+ }+ if (args.stroke) {+ node.strokes = [+ {+ color: parseColor(args.stroke),+ weight: args.stroke_weight ?? 1,+ opacity: 1,+ visible: true,+ align: 'CENTER'+ }+ ]+ }+ if (args.parent_id) {+ const parent = figma.getNodeById(args.parent_id)+ if (parent) parent.appendChild(node)+ }+ return nodeSummary(node)+ }+})++export const createSlice = defineTool({+ name: 'create_slice',+ 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' }+ },+ execute: (figma, args) => {+ const node = figma.createFrame()+ node.x = args.x+ node.y = args.y+ node.resize(args.width, args.height)+ node.name = args.name ?? 'Slice'+ node.fills = []+ if (args.parent_id) {+ const parent = figma.getNodeById(args.parent_id)+ if (parent) parent.appendChild(node)+ }+ return nodeSummary(node)+ }+})diff --git a/packages/core/src/tools/modify.ts b/packages/core/src/tools/modify.tsnew file mode 100644index 000000000..10306e276--- /dev/null+++ b/packages/core/src/tools/modify.ts@@ -0,0 +1,599 @@+import { parseColor } from '../color'+import { DEFAULT_SHADOW_COLOR } from '../constants'++import { defineTool } from './schema'++export const setFill = defineTool({+ name: 'set_fill',+ description: 'Set the fill color of a node. Accepts hex (#ff0000) or named color.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ color: { type: 'color', description: 'Color value (hex like #ff0000)', required: true }+ },+ execute: (figma, { id, color }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }++ const c = parseColor(color)+ node.fills = [{ type: 'SOLID', color: c, opacity: 1, visible: true }]+ return { id, color: c }+ }+})++export const setStroke = defineTool({+ name: 'set_stroke',+ 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']+ }+ },+ execute: (figma, { id, color, weight, align }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }++ const c = parseColor(color)+ node.strokes = [+ {+ color: c,+ weight: weight ?? 1,+ opacity: 1,+ visible: true,+ align: (align ?? 'INSIDE') as 'INSIDE' | 'CENTER' | 'OUTSIDE'+ }+ ]+ return { id, color: c, weight: weight ?? 1 }+ }+})++export const setEffects = defineTool({+ name: 'set_effects',+ 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 }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return { error: `Node "${args.id}" not found` }++ const isBlur = args.type === 'FOREGROUND_BLUR' || args.type === 'BACKGROUND_BLUR'+ const effect: Record<string, unknown> = {+ type: args.type,+ visible: true,+ radius: args.radius ?? 4+ }++ if (!isBlur) {+ effect.color = args.color ? parseColor(args.color) : { ...DEFAULT_SHADOW_COLOR }+ effect.offset = { x: args.offset_x ?? 0, y: args.offset_y ?? 4 }+ effect.spread = args.spread ?? 0+ }++ node.effects = [...node.effects, effect as any]+ return { id: args.id, effects: node.effects.length }+ }+})++export const updateNode = defineTool({+ name: 'update_node',+ 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)' },+ font_size: { type: 'number', description: 'Font size', min: 1 },+ font_weight: { type: 'number', description: 'Font weight (100-900)' },+ name: { type: 'string', description: 'Layer name' }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return { error: `Node "${args.id}" not found` }+ const updated: string[] = []+ if (args.x !== undefined) {+ node.x = args.x+ updated.push('x')+ }+ if (args.y !== undefined) {+ node.y = args.y+ updated.push('y')+ }+ if (args.width !== undefined || args.height !== undefined) {+ node.resize(args.width ?? node.width, args.height ?? node.height)+ updated.push('size')+ }+ if (args.opacity !== undefined) {+ node.opacity = args.opacity+ updated.push('opacity')+ }+ if (args.corner_radius !== undefined) {+ node.cornerRadius = args.corner_radius+ updated.push('cornerRadius')+ }+ if (args.visible !== undefined) {+ node.visible = args.visible+ updated.push('visible')+ }+ if (args.name !== undefined) {+ node.name = args.name+ updated.push('name')+ }+ if (args.text !== undefined) {+ figma.graph.updateNode(node.id, { text: args.text })+ updated.push('text')+ }+ if (args.font_size !== undefined) {+ figma.graph.updateNode(node.id, { fontSize: args.font_size })+ updated.push('fontSize')+ }+ if (args.font_weight !== undefined) {+ figma.graph.updateNode(node.id, { fontWeight: args.font_weight })+ updated.push('fontWeight')+ }+ return { id: args.id, updated }+ }+})++export const setLayout = defineTool({+ name: 'set_layout',+ 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',+ required: true,+ enum: ['HORIZONTAL', 'VERTICAL']+ },+ spacing: { type: 'number', description: 'Gap between items', default: 0, min: 0 },+ padding: { type: 'number', description: 'Equal padding on all sides', 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',+ default: 'MIN',+ enum: ['MIN', 'CENTER', 'MAX', 'SPACE_BETWEEN']+ },+ counter_align: {+ type: 'string',+ description: 'Cross axis alignment',+ default: 'MIN',+ enum: ['MIN', 'CENTER', 'MAX', 'STRETCH']+ }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return { error: `Node "${args.id}" not found` }++ node.layoutMode = args.direction as 'HORIZONTAL' | 'VERTICAL'+ node.itemSpacing = args.spacing ?? 0+ node.primaryAxisAlignItems = (args.align ?? 'MIN') as any+ node.counterAxisAlignItems = (args.counter_align ?? 'MIN') as any++ const ph = args.padding_horizontal ?? args.padding ?? 0+ const pv = args.padding_vertical ?? args.padding ?? 0+ node.paddingLeft = ph+ node.paddingRight = ph+ node.paddingTop = pv+ node.paddingBottom = pv++ return { id: args.id, direction: args.direction, spacing: args.spacing ?? 0 }+ }+})++export const setConstraints = defineTool({+ name: 'set_constraints',+ 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']+ }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return { error: `Node "${args.id}" not found` }+ if (args.horizontal || args.vertical) {+ node.constraints = {+ horizontal: args.horizontal ?? node.constraints.horizontal,+ vertical: args.vertical ?? node.constraints.vertical+ }+ }+ return { id: args.id, constraints: node.constraints }+ }+})++export const setRotation = defineTool({+ name: 'set_rotation',+ 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 }+ },+ execute: (figma, { id, angle }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.rotation = angle+ return { id, rotation: angle }+ }+})++export const setOpacity = defineTool({+ name: 'set_opacity',+ 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 }+ },+ execute: (figma, { id, value }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.opacity = value+ return { id, opacity: value }+ }+})++export const setRadius = defineTool({+ name: 'set_radius',+ 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 }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return { error: `Node "${args.id}" not found` }+ if (args.radius !== undefined) {+ node.cornerRadius = args.radius+ }+ if (args.top_left !== undefined) node.topLeftRadius = args.top_left+ if (args.top_right !== undefined) node.topRightRadius = args.top_right+ if (args.bottom_right !== undefined) node.bottomRightRadius = args.bottom_right+ if (args.bottom_left !== undefined) node.bottomLeftRadius = args.bottom_left+ return { id: args.id, cornerRadius: node.cornerRadius }+ }+})++export const setMinMax = defineTool({+ name: 'set_minmax',+ 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 }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return { error: `Node "${args.id}" not found` }+ if (args.min_width !== undefined) node.minWidth = args.min_width+ if (args.max_width !== undefined) node.maxWidth = args.max_width+ if (args.min_height !== undefined) node.minHeight = args.min_height+ if (args.max_height !== undefined) node.maxHeight = args.max_height+ return {+ id: args.id,+ minWidth: node.minWidth,+ maxWidth: node.maxWidth,+ minHeight: node.minHeight,+ maxHeight: node.maxHeight+ }+ }+})++export const setText = defineTool({+ name: 'set_text',+ 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 }+ },+ execute: (figma, { id, text }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.characters = text+ return { id, text }+ }+})++export const setFont = defineTool({+ name: 'set_font',+ 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")' }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return { error: `Node "${args.id}" not found` }+ if (args.size !== undefined) node.fontSize = args.size+ if (args.family || args.style) {+ const current = node.fontName+ node.fontName = {+ family: args.family ?? current.family,+ style: args.style ?? current.style+ }+ }+ return { id: args.id, fontName: node.fontName, fontSize: node.fontSize }+ }+})++export const setFontRange = defineTool({+ name: 'set_font_range',+ 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)' }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return { error: `Node "${args.id}" not found` }+ const run: Record<string, unknown> = { start: args.start, end: args.end }+ if (args.family) run.fontFamily = args.family+ if (args.size) run.fontSize = args.size+ if (args.style) run.fontStyle = args.style+ if (args.color) run.color = parseColor(args.color)+ figma.graph.updateNode(node.id, {+ styleRuns: [...(figma.graph.getNode(node.id)?.styleRuns ?? []), run as any]+ })+ return { id: args.id, range: { start: args.start, end: args.end } }+ }+})++export const setTextResize = defineTool({+ name: 'set_text_resize',+ 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']+ }+ },+ execute: (figma, { id, mode }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.textAutoResize = mode+ return { id, textAutoResize: mode }+ }+})++export const setVisible = defineTool({+ name: 'set_visible',+ description: 'Set visibility of a node.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ value: { type: 'boolean', description: 'Visible (true/false)', required: true }+ },+ execute: (figma, { id, value }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.visible = value+ return { id, visible: value }+ }+})++export const setBlend = defineTool({+ name: 'set_blend',+ 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: [+ 'NORMAL',+ 'DARKEN',+ 'MULTIPLY',+ 'COLOR_BURN',+ 'LIGHTEN',+ 'SCREEN',+ 'COLOR_DODGE',+ 'OVERLAY',+ 'SOFT_LIGHT',+ 'HARD_LIGHT',+ 'DIFFERENCE',+ 'EXCLUSION',+ 'HUE',+ 'SATURATION',+ 'COLOR',+ 'LUMINOSITY'+ ]+ }+ },+ execute: (figma, { id, mode }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.blendMode = mode+ return { id, blendMode: mode }+ }+})++export const setLocked = defineTool({+ name: 'set_locked',+ 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 }+ },+ execute: (figma, { id, value }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.locked = value+ return { id, locked: value }+ }+})++export const setStrokeAlign = defineTool({+ name: 'set_stroke_align',+ 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']+ }+ },+ execute: (figma, { id, align }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.strokeAlign = align+ return { id, strokeAlign: align }+ }+})++export const setTextProperties = defineTool({+ name: 'set_text_properties',+ 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']+ },+ text_decoration: {+ type: 'string',+ description: 'Text decoration',+ enum: ['NONE', 'UNDERLINE', 'STRIKETHROUGH']+ }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return { error: `Node "${args.id}" not found` }+ if (node.type !== 'TEXT') return { error: `Node "${args.id}" is not a TEXT node` }+ const updated: string[] = []+ if (args.align_horizontal !== undefined) {+ node.textAlignHorizontal = args.align_horizontal+ updated.push('textAlignHorizontal')+ }+ if (args.align_vertical !== undefined) {+ node.textAlignVertical = args.align_vertical+ updated.push('textAlignVertical')+ }+ if (args.auto_resize !== undefined) {+ node.textAutoResize = args.auto_resize+ updated.push('textAutoResize')+ }+ if (args.text_decoration !== undefined) {+ node.textDecoration = args.text_decoration+ updated.push('textDecoration')+ }+ return { id: args.id, updated }+ }+})++export const setLayoutChild = defineTool({+ name: 'set_layout_child',+ 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',+ enum: ['INHERIT', 'STRETCH']+ },+ positioning: {+ type: 'string',+ description: 'ABSOLUTE to take node out of auto-layout flow',+ enum: ['AUTO', 'ABSOLUTE']+ }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return { error: `Node "${args.id}" not found` }+ const updated: string[] = []+ if (args.sizing_horizontal !== undefined) {+ node.layoutSizingHorizontal = args.sizing_horizontal+ updated.push('layoutSizingHorizontal')+ }+ if (args.sizing_vertical !== undefined) {+ node.layoutSizingVertical = args.sizing_vertical+ updated.push('layoutSizingVertical')+ }+ if (args.grow !== undefined) {+ node.layoutGrow = args.grow+ updated.push('layoutGrow')+ }+ if (args.align_self !== undefined) {+ node.layoutAlign = args.align_self+ updated.push('layoutAlign')+ }+ if (args.positioning !== undefined) {+ node.layoutPositioning = args.positioning+ updated.push('layoutPositioning')+ }+ return { id: args.id, updated }+ }+})diff --git a/packages/core/src/tools/read.ts b/packages/core/src/tools/read.tsnew file mode 100644index 000000000..25479d8b5--- /dev/null+++ b/packages/core/src/tools/read.ts@@ -0,0 +1,206 @@+import { defineTool, nodeSummary, nodeToResult } from './schema'++import type { FigmaNodeProxy } from '../figma-api'++export const getSelection = defineTool({+ name: 'get_selection',+ description: 'Get details about currently selected nodes.',+ params: {},+ execute: (figma) => {+ const sel = figma.currentPage.selection+ return { selection: sel.map(nodeToResult) }+ }+})++export const getPageTree = defineTool({+ name: 'get_page_tree',+ description:+ 'Get the node tree of the current page. Returns all nodes with hierarchy, types, positions, and sizes.',+ params: {},+ execute: (figma) => {+ const page = figma.currentPage+ return {+ page: page.name,+ children: page.children.map(nodeToResult)+ }+ }+})++export const getNode = defineTool({+ name: 'get_node',+ description: 'Get detailed properties of a node by ID.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true }+ },+ execute: (figma, { id }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ return nodeToResult(node)+ }+})++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'+ ]+ }+ },+ execute: (figma, args) => {+ const page = figma.currentPage+ const matches = page.findAll((node) => {+ if (args.type && node.type !== args.type) return false+ if (args.name && !node.name.toLowerCase().includes(args.name.toLowerCase())) return false+ return true+ })+ return { count: matches.length, nodes: matches.map(nodeSummary) }+ }+})++export const getComponents = defineTool({+ name: 'get_components',+ description: 'List all components in the document, optionally filtered by name.',+ params: {+ name: { type: 'string', description: 'Filter by name (case-insensitive substring)' },+ limit: { type: 'number', description: 'Max results (default: 50)' }+ },+ execute: (figma, args) => {+ const limit = args.limit ?? 50+ const nameFilter = args.name?.toLowerCase()+ const components: { id: string; name: string; type: string; page: string }[] = []++ for (const page of figma.root.children) {+ if (components.length >= limit) break+ page.findAll((node) => {+ if (components.length >= limit) return false+ if (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET') return false+ if (nameFilter && !node.name.toLowerCase().includes(nameFilter)) return false+ components.push({ id: node.id, name: node.name, type: node.type, page: page.name })+ return false+ })+ }++ return { count: components.length, components }+ }+})++export const listPages = defineTool({+ name: 'list_pages',+ description: 'List all pages in the document.',+ params: {},+ execute: (figma) => {+ const pages = figma.root.children+ return {+ current: figma.currentPage.name,+ pages: pages.map((p) => ({ id: p.id, name: p.name }))+ }+ }+})++export const switchPage = defineTool({+ name: 'switch_page',+ description: 'Switch to a different page by name or ID.',+ params: {+ page: { type: 'string', description: 'Page name or ID', required: true }+ },+ execute: (figma, { page }) => {+ const target = figma.root.children.find((p) => p.name === page) ?? figma.getNodeById(page)+ if (!target) return { error: `Page "${page}" not found` }+ figma.currentPage = target+ return { page: target.name, id: target.id }+ }+})++export const getCurrentPage = defineTool({+ name: 'get_current_page',+ description: 'Get the current page name and ID.',+ params: {},+ execute: (figma) => {+ return { id: figma.currentPage.id, name: figma.currentPage.name }+ }+})++export const pageBounds = defineTool({+ name: 'page_bounds',+ description: 'Get bounding box of all objects on the current page.',+ params: {},+ execute: (figma) => {+ const page = figma.currentPage+ let minX = Infinity+ let minY = Infinity+ let maxX = -Infinity+ let maxY = -Infinity+ for (const child of page.children) {+ const bounds = child.absoluteBoundingBox+ minX = Math.min(minX, bounds.x)+ minY = Math.min(minY, bounds.y)+ maxX = Math.max(maxX, bounds.x + bounds.width)+ maxY = Math.max(maxY, bounds.y + bounds.height)+ }+ if (minX === Infinity) return { x: 0, y: 0, width: 0, height: 0 }+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }+ }+})++export const selectNodes = defineTool({+ name: 'select_nodes',+ description: 'Select one or more nodes by ID.',+ params: {+ ids: { type: 'string[]', description: 'Node IDs to select', required: true }+ },+ execute: (figma, { ids }) => {+ figma.currentPage.selection = ids+ .map((id) => figma.getNodeById(id))+ .filter((n): n is FigmaNodeProxy => n !== null)+ return { selected: ids }+ }+})++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)' }+ },+ execute: (figma, args) => {+ const fonts = new Map<string, Set<number>>()+ const page = figma.currentPage+ page.findAll((node) => {+ if (node.type === 'TEXT') {+ const raw = figma.graph.getNode(node.id)+ if (raw) {+ const key = raw.fontFamily+ if (!fonts.has(key)) fonts.set(key, new Set())+ fonts.get(key)!.add(raw.fontWeight)+ }+ }+ return false+ })+ let result = [...fonts.entries()].map(([family, weights]) => ({+ family,+ weights: [...weights].sort()+ }))+ if (args.family) {+ const q = args.family.toLowerCase()+ result = result.filter((f) => f.family.toLowerCase().includes(q))+ }+ return { count: result.length, fonts: result }+ }+})diff --git a/packages/core/src/tools/registry.ts b/packages/core/src/tools/registry.tsnew file mode 100644index 000000000..2e9d15c87--- /dev/null+++ b/packages/core/src/tools/registry.ts@@ -0,0 +1,134 @@+import type { ToolDef } from './schema'++import {+ getSelection, getPageTree, getNode, findNodes, getComponents,+ listPages, switchPage, getCurrentPage, pageBounds, selectNodes, listFonts+} from './read'+import {+ createShape, render, createComponent, createInstance,+ createPage, createVector, createSlice+} from './create'+import {+ setFill, setStroke, setEffects, updateNode, setLayout, setConstraints,+ setRotation, setOpacity, setRadius, setMinMax, setText, setFont, setFontRange,+ setTextResize, setVisible, setBlend, setLocked, setStrokeAlign,+ setTextProperties, setLayoutChild+} from './modify'+import {+ deleteNode, cloneNode, renameNode, reparentNode, groupNodes, ungroupNode,+ flattenNodes, nodeToComponent, nodeBounds, nodeMove, nodeResize,+ nodeAncestors, nodeChildren, nodeTree, nodeBindings, nodeReplaceWith, arrangeNodes+} from './structure'+import {+ listVariables, listCollections, getVariable, findVariables,+ createVariable, setVariable, deleteVariable, bindVariable,+ getCollection, createCollection, deleteCollection+} from './variables'+import {+ booleanUnion, booleanSubtract, booleanIntersect, booleanExclude,+ pathGet, pathSet, pathScale, pathFlip, pathMove,+ viewportGet, viewportSet, viewportZoomToFit,+ exportSvg, exportImage+} from './vector'+import {+ analyzeColors, analyzeTypography, analyzeSpacing, analyzeClusters,+ diffCreate, diffShow, evalCode+} from './analyze'++export const ALL_TOOLS: ToolDef[] = [+ // Read+ getSelection,+ getPageTree,+ getNode,+ findNodes,+ getComponents,+ listPages,+ switchPage,+ getCurrentPage,+ pageBounds,+ selectNodes,+ listFonts,+ // Create+ createShape,+ render,+ createComponent,+ createInstance,+ createPage,+ createVector,+ createSlice,+ // Modify+ setFill,+ setStroke,+ setEffects,+ updateNode,+ setLayout,+ setConstraints,+ setRotation,+ setOpacity,+ setRadius,+ setMinMax,+ setText,+ setFont,+ setFontRange,+ setTextResize,+ setVisible,+ setBlend,+ setLocked,+ setStrokeAlign,+ setTextProperties,+ setLayoutChild,+ // Structure+ deleteNode,+ cloneNode,+ renameNode,+ reparentNode,+ groupNodes,+ ungroupNode,+ flattenNodes,+ nodeToComponent,+ nodeBounds,+ nodeMove,+ nodeResize,+ nodeAncestors,+ nodeChildren,+ nodeTree,+ nodeBindings,+ nodeReplaceWith,+ arrangeNodes,+ // Variables+ listVariables,+ listCollections,+ getVariable,+ findVariables,+ createVariable,+ setVariable,+ deleteVariable,+ bindVariable,+ getCollection,+ createCollection,+ deleteCollection,+ // Vector & export+ booleanUnion,+ booleanSubtract,+ booleanIntersect,+ booleanExclude,+ pathGet,+ pathSet,+ pathScale,+ pathFlip,+ pathMove,+ viewportGet,+ viewportSet,+ viewportZoomToFit,+ exportSvg,+ exportImage,+ // Analyze & diff+ analyzeColors,+ analyzeTypography,+ analyzeSpacing,+ analyzeClusters,+ diffCreate,+ diffShow,+ // Eval+ evalCode+]diff --git a/packages/core/src/tools/schema.ts b/packages/core/src/tools/schema.tsindex 260db3d53..28503b67e 100644--- a/packages/core/src/tools/schema.ts+++ b/packages/core/src/tools/schema.ts@@ -6,9 +6,6 @@* and MCP (JSON Schema) are generated from these definitions.*/-import { parseColor } from '../color'-import { DEFAULT_SHADOW_COLOR } from '../constants'-import type { FigmaAPI, FigmaNodeProxy } from '../figma-api'export type ParamType = 'string' | 'number' | 'boolean' | 'color' | 'string[]'@@ -57,1774 +54,12 @@ export function defineTool<P extends Record<string, ParamDef>>(def: {return def as unknown as ToolDef}-function nodeToResult(node: FigmaNodeProxy): Record<string, unknown> {+export function nodeToResult(node: FigmaNodeProxy): Record<string, unknown> {return node.toJSON()}-function nodeSummary(node: FigmaNodeProxy): { id: string; name: string; type: string } {+export function nodeSummary(node: FigmaNodeProxy): { id: string; name: string; type: string } {return { id: node.id, name: node.name, type: node.type }}-// ─── Read tools ───────────────────────────────────────────────--export const getSelection = defineTool({- name: 'get_selection',- description: 'Get details about currently selected nodes.',- params: {},- execute: (figma) => {- const sel = figma.currentPage.selection- return { selection: sel.map(nodeToResult) }- }-})--export const getPageTree = defineTool({- name: 'get_page_tree',- description:- 'Get the node tree of the current page. Returns all nodes with hierarchy, types, positions, and sizes.',- params: {},- execute: (figma) => {- const page = figma.currentPage- return {- page: page.name,- children: page.children.map(nodeToResult)- }- }-})--export const getNode = defineTool({- name: 'get_node',- description: 'Get detailed properties of a node by ID.',- params: {- id: { type: 'string', description: 'Node ID', required: true }- },- execute: (figma, { id }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- return nodeToResult(node)- }-})--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'- ]- }- },- execute: (figma, args) => {- const page = figma.currentPage- const matches = page.findAll((node) => {- if (args.type && node.type !== args.type) return false- if (args.name && !node.name.toLowerCase().includes(args.name.toLowerCase())) return false- return true- })- return { count: matches.length, nodes: matches.map(nodeSummary) }- }-})--// ─── Create tools ─────────────────────────────────────────────--export const createShape = defineTool({- name: 'create_shape',- description:- 'Create a shape on the canvas. Use FRAME for containers/cards, RECTANGLE for solid blocks, ELLIPSE for circles, TEXT for labels, SECTION for page sections.',- 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' }- },- execute: (figma, args) => {- const parentId = args.parent_id- const parent = parentId ? figma.getNodeById(parentId) : null- const createMap: Record<string, () => FigmaNodeProxy> = {- FRAME: () => figma.createFrame(),- RECTANGLE: () => figma.createRectangle(),- ELLIPSE: () => figma.createEllipse(),- TEXT: () => figma.createText(),- LINE: () => figma.createLine(),- STAR: () => figma.createStar(),- POLYGON: () => figma.createPolygon(),- SECTION: () => figma.createSection()- }- const node = createMap[args.type]!()- node.x = args.x- node.y = args.y- node.resize(args.width, args.height)- if (args.name) node.name = args.name- if (parent) parent.appendChild(node)- return nodeSummary(node)- }-})--export const render = defineTool({- name: 'render',- description:- 'Render JSX to design nodes. Primary creation tool — creates entire component trees in one call. Example: <Frame name="Card" w={320} h="hug" flex="col" gap={16} p={24} bg="#FFF" rounded={16}><Text size={18} weight="bold">Title</Text></Frame>',- params: {- jsx: { type: 'string', description: 'JSX string to render', required: true },- x: { type: 'number', description: 'X position of the root node' },- y: { type: 'number', description: 'Y position of the root node' },- parent_id: { type: 'string', description: 'Parent node ID to render into' }- },- execute: async (figma, args) => {- const { renderJsx } = await import('../render/render-jsx.js')- const result = await renderJsx(figma.graph, args.jsx, {- parentId: args.parent_id ?? figma.currentPageId,- x: args.x,- y: args.y- })- return { id: result.id, name: result.name, type: result.type, children: result.childIds }- }-})--// ─── Modify tools ─────────────────────────────────────────────--export const setFill = defineTool({- name: 'set_fill',- description: 'Set the fill color of a node. Accepts hex (#ff0000) or named color.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- color: { type: 'color', description: 'Color value (hex like #ff0000)', required: true }- },- execute: (figma, { id, color }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }-- const c = parseColor(color)- node.fills = [{ type: 'SOLID', color: c, opacity: 1, visible: true }]- return { id, color: c }- }-})--export const setStroke = defineTool({- name: 'set_stroke',- 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']- }- },- execute: (figma, { id, color, weight, align }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }-- const c = parseColor(color)- node.strokes = [- {- color: c,- weight: weight ?? 1,- opacity: 1,- visible: true,- align: (align ?? 'INSIDE') as 'INSIDE' | 'CENTER' | 'OUTSIDE'- }- ]- return { id, color: c, weight: weight ?? 1 }- }-})--export const setEffects = defineTool({- name: 'set_effects',- 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 }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }-- const isBlur = args.type === 'FOREGROUND_BLUR' || args.type === 'BACKGROUND_BLUR'- const effect: Record<string, unknown> = {- type: args.type,- visible: true,- radius: args.radius ?? 4- }-- if (!isBlur) {- effect.color = args.color ? parseColor(args.color) : { ...DEFAULT_SHADOW_COLOR }- effect.offset = { x: args.offset_x ?? 0, y: args.offset_y ?? 4 }- effect.spread = args.spread ?? 0- }-- node.effects = [...node.effects, effect as any]- return { id: args.id, effects: node.effects.length }- }-})--export const updateNode = defineTool({- name: 'update_node',- 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)' },- font_size: { type: 'number', description: 'Font size', min: 1 },- font_weight: { type: 'number', description: 'Font weight (100-900)' },- name: { type: 'string', description: 'Layer name' }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- const updated: string[] = []- if (args.x !== undefined) {- node.x = args.x- updated.push('x')- }- if (args.y !== undefined) {- node.y = args.y- updated.push('y')- }- if (args.width !== undefined || args.height !== undefined) {- node.resize(args.width ?? node.width, args.height ?? node.height)- updated.push('size')- }- if (args.opacity !== undefined) {- node.opacity = args.opacity- updated.push('opacity')- }- if (args.corner_radius !== undefined) {- node.cornerRadius = args.corner_radius- updated.push('cornerRadius')- }- if (args.visible !== undefined) {- node.visible = args.visible- updated.push('visible')- }- if (args.name !== undefined) {- node.name = args.name- updated.push('name')- }- if (args.text !== undefined) {- figma.graph.updateNode(node.id, { text: args.text })- updated.push('text')- }- if (args.font_size !== undefined) {- figma.graph.updateNode(node.id, { fontSize: args.font_size })- updated.push('fontSize')- }- if (args.font_weight !== undefined) {- figma.graph.updateNode(node.id, { fontWeight: args.font_weight })- updated.push('fontWeight')- }- return { id: args.id, updated }- }-})--export const setLayout = defineTool({- name: 'set_layout',- 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',- required: true,- enum: ['HORIZONTAL', 'VERTICAL']- },- spacing: { type: 'number', description: 'Gap between items', default: 0, min: 0 },- padding: { type: 'number', description: 'Equal padding on all sides', 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',- default: 'MIN',- enum: ['MIN', 'CENTER', 'MAX', 'SPACE_BETWEEN']- },- counter_align: {- type: 'string',- description: 'Cross axis alignment',- default: 'MIN',- enum: ['MIN', 'CENTER', 'MAX', 'STRETCH']- }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }-- node.layoutMode = args.direction as 'HORIZONTAL' | 'VERTICAL'- node.itemSpacing = args.spacing ?? 0- node.primaryAxisAlignItems = (args.align ?? 'MIN') as any- node.counterAxisAlignItems = (args.counter_align ?? 'MIN') as any-- const ph = args.padding_horizontal ?? args.padding ?? 0- const pv = args.padding_vertical ?? args.padding ?? 0- node.paddingLeft = ph- node.paddingRight = ph- node.paddingTop = pv- node.paddingBottom = pv-- return { id: args.id, direction: args.direction, spacing: args.spacing ?? 0 }- }-})--export const setConstraints = defineTool({- name: 'set_constraints',- 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']- }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- if (args.horizontal || args.vertical) {- node.constraints = {- horizontal: args.horizontal ?? node.constraints.horizontal,- vertical: args.vertical ?? node.constraints.vertical- }- }- return { id: args.id, constraints: node.constraints }- }-})--// ─── Structure tools ──────────────────────────────────────────--export const deleteNode = defineTool({- name: 'delete_node',- description: 'Delete a node by ID.',- params: {- id: { type: 'string', description: 'Node ID to delete', required: true }- },- execute: (figma, { id }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.remove()- return { deleted: id }- }-})--export const cloneNode = defineTool({- name: 'clone_node',- description: 'Clone (duplicate) a node.',- params: {- id: { type: 'string', description: 'Node ID to clone', required: true }- },- execute: (figma, { id }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- const clone = node.clone()- return nodeSummary(clone)- }-})--export const renameNode = defineTool({- name: 'rename_node',- 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 }- },- execute: (figma, { id, name }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.name = name- return { id, name }- }-})--export const reparentNode = defineTool({- name: 'reparent_node',- 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 }- },- execute: (figma, { id, parent_id }) => {- const node = figma.getNodeById(id)- const parent = figma.getNodeById(parent_id)- if (!node) return { error: `Node "${id}" not found` }- if (!parent) return { error: `Parent "${parent_id}" not found` }- parent.appendChild(node)- return { id, parent_id }- }-})--export const selectNodes = defineTool({- name: 'select_nodes',- description: 'Select one or more nodes by ID.',- params: {- ids: { type: 'string[]', description: 'Node IDs to select', required: true }- },- execute: (figma, { ids }) => {- figma.currentPage.selection = ids- .map((id) => figma.getNodeById(id))- .filter((n): n is FigmaNodeProxy => n !== null)- return { selected: ids }- }-})--export const groupNodes = defineTool({- name: 'group_nodes',- description: 'Group selected nodes.',- params: {- ids: { type: 'string[]', description: 'Node IDs to group', required: true }- },- execute: (figma, { ids }) => {- const nodes = ids- .map((id) => figma.getNodeById(id))- .filter((n): n is FigmaNodeProxy => n !== null)- if (nodes.length < 2) return { error: 'Need at least 2 nodes to group' }- const parent = nodes[0]!.parent ?? figma.currentPage- const group = figma.group(nodes, parent)- return nodeSummary(group)- }-})--export const ungroupNode = defineTool({- name: 'ungroup_node',- description: 'Ungroup a group node.',- params: {- id: { type: 'string', description: 'Group node ID', required: true }- },- execute: (figma, { id }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- figma.ungroup(node)- return { ungrouped: id }- }-})--// ─── Component tools ──────────────────────────────────────────--export const createComponent = defineTool({- name: 'create_component',- description: 'Convert a frame/group into a component.',- params: {- id: { type: 'string', description: 'Node ID to convert', required: true }- },- execute: (figma, { id }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- const comp = figma.createComponentFromNode(node)- return nodeSummary(comp)- }-})--export const createInstance = defineTool({- name: 'create_instance',- 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' }- },- execute: (figma, args) => {- const comp = figma.getNodeById(args.component_id)- if (!comp) return { error: `Component "${args.component_id}" not found` }- const instance = comp.createInstance()- if (args.x !== undefined) instance.x = args.x- if (args.y !== undefined) instance.y = args.y- return nodeSummary(instance)- }-})--// ─── Page tools ───────────────────────────────────────────────--export const listPages = defineTool({- name: 'list_pages',- description: 'List all pages in the document.',- params: {},- execute: (figma) => {- const pages = figma.root.children- return {- current: figma.currentPage.name,- pages: pages.map((p) => ({ id: p.id, name: p.name }))- }- }-})--export const switchPage = defineTool({- name: 'switch_page',- description: 'Switch to a different page by name or ID.',- params: {- page: { type: 'string', description: 'Page name or ID', required: true }- },- execute: (figma, { page }) => {- const target = figma.root.children.find((p) => p.name === page) ?? figma.getNodeById(page)- if (!target) return { error: `Page "${page}" not found` }- figma.currentPage = target- return { page: target.name, id: target.id }- }-})--// ─── Variable tools ───────────────────────────────────────────--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']- }- },- execute: (figma, args) => {- const vars = figma.getLocalVariables(args.type)- return { count: vars.length, variables: vars }- }-})--export const listCollections = defineTool({- name: 'list_collections',- description: 'List all variable collections.',- params: {},- execute: (figma) => {- const cols = figma.getLocalVariableCollections()- return { count: cols.length, collections: cols }- }-})--// ─── Eval escape hatch ────────────────────────────────────────--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 }- },- execute: async (figma, { code }) => {- const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor- const wrapped = code.trim().startsWith('return') ? code : `return (async () => { ${code} })()`- const fn = new AsyncFunction('figma', wrapped)- const result = await fn(figma)- if (result && typeof result === 'object' && 'toJSON' in result) return result.toJSON()- return result ?? null- }-})--// ─── Granular set tools ───────────────────────────────────────--export const setRotation = defineTool({- name: 'set_rotation',- 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 }- },- execute: (figma, { id, angle }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.rotation = angle- return { id, rotation: angle }- }-})--export const setOpacity = defineTool({- name: 'set_opacity',- 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 }- },- execute: (figma, { id, value }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.opacity = value- return { id, opacity: value }- }-})--export const setRadius = defineTool({- name: 'set_radius',- 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 }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- if (args.radius !== undefined) {- node.cornerRadius = args.radius- }- if (args.top_left !== undefined) node.topLeftRadius = args.top_left- if (args.top_right !== undefined) node.topRightRadius = args.top_right- if (args.bottom_right !== undefined) node.bottomRightRadius = args.bottom_right- if (args.bottom_left !== undefined) node.bottomLeftRadius = args.bottom_left- return { id: args.id, cornerRadius: node.cornerRadius }- }-})--export const setMinMax = defineTool({- name: 'set_minmax',- 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 }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- if (args.min_width !== undefined) node.minWidth = args.min_width- if (args.max_width !== undefined) node.maxWidth = args.max_width- if (args.min_height !== undefined) node.minHeight = args.min_height- if (args.max_height !== undefined) node.maxHeight = args.max_height- return {- id: args.id,- minWidth: node.minWidth,- maxWidth: node.maxWidth,- minHeight: node.minHeight,- maxHeight: node.maxHeight- }- }-})--export const setText = defineTool({- name: 'set_text',- 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 }- },- execute: (figma, { id, text }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.characters = text- return { id, text }- }-})--export const setFont = defineTool({- name: 'set_font',- 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")' }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- if (args.size !== undefined) node.fontSize = args.size- if (args.family || args.style) {- const current = node.fontName- node.fontName = {- family: args.family ?? current.family,- style: args.style ?? current.style- }- }- return { id: args.id, fontName: node.fontName, fontSize: node.fontSize }- }-})--export const setFontRange = defineTool({- name: 'set_font_range',- 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)' }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- const run: Record<string, unknown> = { start: args.start, end: args.end }- if (args.family) run.fontFamily = args.family- if (args.size) run.fontSize = args.size- if (args.style) run.fontStyle = args.style- if (args.color) run.color = parseColor(args.color)- figma.graph.updateNode(node.id, {- styleRuns: [...(figma.graph.getNode(node.id)?.styleRuns ?? []), run as any]- })- return { id: args.id, range: { start: args.start, end: args.end } }- }-})--export const setTextResize = defineTool({- name: 'set_text_resize',- 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']- }- },- execute: (figma, { id, mode }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.textAutoResize = mode- return { id, textAutoResize: mode }- }-})--export const setVisible = defineTool({- name: 'set_visible',- description: 'Set visibility of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- value: { type: 'boolean', description: 'Visible (true/false)', required: true }- },- execute: (figma, { id, value }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.visible = value- return { id, visible: value }- }-})--export const setBlend = defineTool({- name: 'set_blend',- 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: [- 'NORMAL',- 'DARKEN',- 'MULTIPLY',- 'COLOR_BURN',- 'LIGHTEN',- 'SCREEN',- 'COLOR_DODGE',- 'OVERLAY',- 'SOFT_LIGHT',- 'HARD_LIGHT',- 'DIFFERENCE',- 'EXCLUSION',- 'HUE',- 'SATURATION',- 'COLOR',- 'LUMINOSITY'- ]- }- },- execute: (figma, { id, mode }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.blendMode = mode- return { id, blendMode: mode }- }-})--export const setLocked = defineTool({- name: 'set_locked',- 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 }- },- execute: (figma, { id, value }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.locked = value- return { id, locked: value }- }-})--export const setStrokeAlign = defineTool({- name: 'set_stroke_align',- 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']- }- },- execute: (figma, { id, align }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.strokeAlign = align- return { id, strokeAlign: align }- }-})--// ─── Node operation tools ─────────────────────────────────────--export const nodeBounds = defineTool({- name: 'node_bounds',- description: 'Get absolute bounding box of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true }- },- execute: (figma, { id }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- return { id, bounds: node.absoluteBoundingBox }- }-})--export const nodeMove = defineTool({- name: 'node_move',- 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 }- },- execute: (figma, { id, x, y }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.x = x- node.y = y- return { id, x, y }- }-})--export const nodeResize = defineTool({- name: 'node_resize',- 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 }- },- execute: (figma, { id, width, height }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.resize(width, height)- return { id, width, height }- }-})--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' }- },- execute: (figma, args) => {- let node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- const ancestors: { id: string; name: string; type: string }[] = []- let current = node.parent- let d = 0- while (current && (!args.depth || d < args.depth)) {- ancestors.push({ id: current.id, name: current.name, type: current.type })- current = current.parent- d++- }- return { id: args.id, ancestors }- }-})--export const nodeChildren = defineTool({- name: 'node_children',- description: 'Get direct children of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true }- },- execute: (figma, { id }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- return {- id,- children: node.children.map((c) => ({ id: c.id, name: c.name, type: c.type }))- }- }-})--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)' }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- function buildTree(n: FigmaNodeProxy, d: number): Record<string, unknown> {- const result: Record<string, unknown> = { id: n.id, name: n.name, type: n.type }- if (args.depth === undefined || d < args.depth) {- const kids = n.children- if (kids.length > 0) result.children = kids.map((c) => buildTree(c, d + 1))- }- return result- }- return buildTree(node, 0)- }-})--export const nodeBindings = defineTool({- name: 'node_bindings',- description: 'Get variable bindings for a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true }- },- execute: (figma, { id }) => {- const raw = figma.graph.getNode(id)- if (!raw) return { error: `Node "${id}" not found` }- return { id, bindings: raw.boundVariables }- }-})--export const nodeReplaceWith = defineTool({- name: 'node_replace_with',- 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 }- },- execute: async (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- const parentId = node.parent?.id ?? figma.currentPageId- const x = node.x- const y = node.y- node.remove()- const { renderJsx } = await import('../render/render-jsx.js')- const result = await renderJsx(figma.graph, args.jsx, { parentId, x, y })- return { id: result.id, name: result.name, type: result.type }- }-})--// ─── Variable CRUD tools ──────────────────────────────────────--export const getVariable = defineTool({- name: 'get_variable',- description: 'Get a variable by ID.',- params: {- id: { type: 'string', description: 'Variable ID', required: true }- },- execute: (figma, { id }) => {- const v = figma.getVariableById(id)- if (!v) return { error: `Variable "${id}" not found` }- return v- }-})--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']- }- },- execute: (figma, args) => {- let vars = figma.getLocalVariables(args.type)- vars = vars.filter((v) => v.name.toLowerCase().includes(args.query.toLowerCase()))- return { count: vars.length, variables: vars }- }-})--export const createVariable = defineTool({- name: 'create_variable',- 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.)' }- },- execute: (figma, args) => {- let parsedValue: unknown- if (args.value !== undefined) {- if (args.type === 'COLOR') parsedValue = parseColor(args.value)- else if (args.type === 'FLOAT') parsedValue = Number(args.value)- else if (args.type === 'BOOLEAN') parsedValue = args.value === 'true'- else parsedValue = args.value- }- const v = figma.createVariable(- args.name,- args.type as any,- args.collection_id,- parsedValue as any- )- return v- }-})--export const setVariable = defineTool({- name: 'set_variable',- 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- }- },- execute: (figma, args) => {- const v = figma.getVariableById(args.id)- if (!v) return { error: `Variable "${args.id}" not found` }- let parsedValue: unknown- if (v.type === 'COLOR') parsedValue = parseColor(args.value)- else if (v.type === 'FLOAT') parsedValue = Number(args.value)- else if (v.type === 'BOOLEAN') parsedValue = args.value === 'true'- else parsedValue = args.value- figma.setVariableValue(args.id, args.mode, parsedValue as any)- return { id: args.id, mode: args.mode, value: parsedValue }- }-})--export const deleteVariable = defineTool({- name: 'delete_variable',- description: 'Delete a variable.',- params: {- id: { type: 'string', description: 'Variable ID', required: true }- },- execute: (figma, { id }) => {- figma.deleteVariable(id)- return { deleted: id }- }-})--export const bindVariable = defineTool({- name: 'bind_variable',- description: 'Bind a variable to a node property (fills, strokes, opacity, width, height, etc.).',- params: {- node_id: { type: 'string', description: 'Node ID', required: true },- field: {- type: 'string',- description: 'Property field (fills, strokes, opacity, width, height, etc.)',- required: true- },- variable_id: { type: 'string', description: 'Variable ID', required: true }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.node_id)- if (!node) return { error: `Node "${args.node_id}" not found` }- const v = figma.getVariableById(args.variable_id)- if (!v) return { error: `Variable "${args.variable_id}" not found` }- figma.bindVariable(args.node_id, args.field, args.variable_id)- return { node_id: args.node_id, field: args.field, variable_id: args.variable_id }- }-})--// ─── Collection CRUD tools ────────────────────────────────────--export const getCollection = defineTool({- name: 'get_collection',- description: 'Get a variable collection by ID.',- params: {- id: { type: 'string', description: 'Collection ID', required: true }- },- execute: (figma, { id }) => {- const c = figma.getVariableCollectionById(id)- if (!c) return { error: `Collection "${id}" not found` }- return c- }-})--export const createCollection = defineTool({- name: 'create_collection',- description: 'Create a new variable collection.',- params: {- name: { type: 'string', description: 'Collection name', required: true }- },- execute: (figma, { name }) => {- return figma.createVariableCollection(name)- }-})--export const deleteCollection = defineTool({- name: 'delete_collection',- description: 'Delete a variable collection and all its variables.',- params: {- id: { type: 'string', description: 'Collection ID', required: true }- },- execute: (figma, { id }) => {- figma.deleteVariableCollection(id)- return { deleted: id }- }-})--// ─── Boolean operation tools ──────────────────────────────────--export const booleanUnion = defineTool({- name: 'boolean_union',- description: 'Union (combine) multiple nodes.',- params: {- ids: { type: 'string[]', description: 'Node IDs to union', required: true }- },- execute: (figma, { ids }) => {- const result = figma.booleanOperation('UNION', ids)- return nodeSummary(result)- }-})--export const booleanSubtract = defineTool({- name: 'boolean_subtract',- description: 'Subtract the second node from the first.',- params: {- ids: { type: 'string[]', description: 'Node IDs (first minus rest)', required: true }- },- execute: (figma, { ids }) => {- const result = figma.booleanOperation('SUBTRACT', ids)- return nodeSummary(result)- }-})--export const booleanIntersect = defineTool({- name: 'boolean_intersect',- description: 'Intersect multiple nodes.',- params: {- ids: { type: 'string[]', description: 'Node IDs to intersect', required: true }- },- execute: (figma, { ids }) => {- const result = figma.booleanOperation('INTERSECT', ids)- return nodeSummary(result)- }-})--export const booleanExclude = defineTool({- name: 'boolean_exclude',- description: 'Exclude (XOR) multiple nodes.',- params: {- ids: { type: 'string[]', description: 'Node IDs to exclude', required: true }- },- execute: (figma, { ids }) => {- const result = figma.booleanOperation('EXCLUDE', ids)- return nodeSummary(result)- }-})--// ─── Vector path tools ────────────────────────────────────────--export const pathGet = defineTool({- name: 'path_get',- description: 'Get vector path data of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true }- },- execute: (figma, { id }) => {- const raw = figma.graph.getNode(id)- if (!raw) return { error: `Node "${id}" not found` }- if (!raw.vectorNetwork) return { error: `Node "${id}" has no vector data` }- return { id, vectorNetwork: raw.vectorNetwork }- }-})--export const pathSet = defineTool({- name: 'path_set',- 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 }- },- execute: (figma, args) => {- const raw = figma.graph.getNode(args.id)- if (!raw) return { error: `Node "${args.id}" not found` }- const network = JSON.parse(args.path)- figma.graph.updateNode(args.id, { vectorNetwork: network } as any)- return { id: args.id }- }-})--export const pathScale = defineTool({- name: 'path_scale',- 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 }- },- execute: (figma, { id, factor }) => {- const raw = figma.graph.getNode(id)- if (!raw) return { error: `Node "${id}" not found` }- if (!raw.vectorNetwork) return { error: `Node "${id}" has no vector data` }- const vn = structuredClone(raw.vectorNetwork)- const cx = raw.width / 2- const cy = raw.height / 2- for (const v of vn.vertices) {- v.x = cx + (v.x - cx) * factor- v.y = cy + (v.y - cy) * factor- }- for (const s of vn.segments) {- if (s.tangentStart) {- s.tangentStart.x *= factor- s.tangentStart.y *= factor- }- if (s.tangentEnd) {- s.tangentEnd.x *= factor- s.tangentEnd.y *= factor- }- }- figma.graph.updateNode(id, { vectorNetwork: vn } as any)- return { id, factor }- }-})--export const pathFlip = defineTool({- name: 'path_flip',- 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']- }- },- execute: (figma, { id, axis }) => {- const raw = figma.graph.getNode(id)- if (!raw) return { error: `Node "${id}" not found` }- if (!raw.vectorNetwork) return { error: `Node "${id}" has no vector data` }- const vn = structuredClone(raw.vectorNetwork)- const w = raw.width- const h = raw.height- for (const v of vn.vertices) {- if (axis === 'horizontal') v.x = w - v.x- else v.y = h - v.y- }- for (const s of vn.segments) {- if (s.tangentStart) {- if (axis === 'horizontal') s.tangentStart.x = -s.tangentStart.x- else s.tangentStart.y = -s.tangentStart.y- }- if (s.tangentEnd) {- if (axis === 'horizontal') s.tangentEnd.x = -s.tangentEnd.x- else s.tangentEnd.y = -s.tangentEnd.y- }- }- figma.graph.updateNode(id, { vectorNetwork: vn } as any)- return { id, axis }- }-})--export const pathMove = defineTool({- name: 'path_move',- 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 }- },- execute: (figma, { id, dx, dy }) => {- const raw = figma.graph.getNode(id)- if (!raw) return { error: `Node "${id}" not found` }- if (!raw.vectorNetwork) return { error: `Node "${id}" has no vector data` }- const vn = structuredClone(raw.vectorNetwork)- for (const v of vn.vertices) {- v.x += dx- v.y += dy- }- figma.graph.updateNode(id, { vectorNetwork: vn } as any)- return { id, dx, dy }- }-})--// ─── Create tools (specific shapes) ──────────────────────────--export const createPage = defineTool({- name: 'create_page',- description: 'Create a new page.',- params: {- name: { type: 'string', description: 'Page name', required: true }- },- execute: (figma, { name }) => {- const page = figma.createPage()- page.name = name- return { id: page.id, name }- }-})--export const createVector = defineTool({- name: 'create_vector',- description: 'Create a vector node with optional path data.',- 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: 'VectorNetwork JSON' },- 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' }- },- execute: (figma, args) => {- const node = figma.createVector()- node.x = args.x- node.y = args.y- if (args.name) node.name = args.name- if (args.path) {- figma.graph.updateNode(node.id, { vectorNetwork: JSON.parse(args.path) } as any)- }- if (args.fill) {- node.fills = [{ type: 'SOLID', color: parseColor(args.fill), opacity: 1, visible: true }]- }- if (args.stroke) {- node.strokes = [- {- color: parseColor(args.stroke),- weight: args.stroke_weight ?? 1,- opacity: 1,- visible: true,- align: 'CENTER'- }- ]- }- if (args.parent_id) {- const parent = figma.getNodeById(args.parent_id)- if (parent) parent.appendChild(node)- }- return nodeSummary(node)- }-})--export const createSlice = defineTool({- name: 'create_slice',- 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' }- },- execute: (figma, args) => {- const node = figma.createFrame()- node.x = args.x- node.y = args.y- node.resize(args.width, args.height)- node.name = args.name ?? 'Slice'- node.fills = []- if (args.parent_id) {- const parent = figma.getNodeById(args.parent_id)- if (parent) parent.appendChild(node)- }- return nodeSummary(node)- }-})--// ─── Group tools ──────────────────────────────────────────────--export const flattenNodes = defineTool({- name: 'flatten_nodes',- description: 'Flatten nodes into a single vector.',- params: {- ids: { type: 'string[]', description: 'Node IDs to flatten', required: true }- },- execute: (figma, { ids }) => {- const result = figma.flattenNode(ids)- return nodeSummary(result)- }-})--// ─── Viewport tools ───────────────────────────────────────────--export const viewportGet = defineTool({- name: 'viewport_get',- description: 'Get current viewport position and zoom level.',- params: {},- execute: (figma) => {- return figma.viewport- }-})--export const viewportSet = defineTool({- name: 'viewport_set',- 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 }- },- execute: (figma, { x, y, zoom }) => {- figma.viewport = { center: { x, y }, zoom }- return { x, y, zoom }- }-})--export const viewportZoomToFit = defineTool({- name: 'viewport_zoom_to_fit',- description: 'Zoom viewport to fit specified nodes.',- params: {- ids: { type: 'string[]', description: 'Node IDs to fit in view', required: true }- },- execute: (figma, { ids }) => {- let minX = Infinity- let minY = Infinity- let maxX = -Infinity- let maxY = -Infinity- for (const id of ids) {- const node = figma.getNodeById(id)- if (!node) continue- const bounds = node.absoluteBoundingBox- minX = Math.min(minX, bounds.x)- minY = Math.min(minY, bounds.y)- maxX = Math.max(maxX, bounds.x + bounds.width)- maxY = Math.max(maxY, bounds.y + bounds.height)- }- if (minX === Infinity) return { error: 'No valid nodes found' }- const cx = (minX + maxX) / 2- const cy = (minY + maxY) / 2- figma.viewport = { center: { x: cx, y: cy }, zoom: 1 }- return {- center: { x: cx, y: cy },- bounds: { x: minX, y: minY, width: maxX - minX, height: maxY - minY }- }- }-})--export const pageBounds = defineTool({- name: 'page_bounds',- description: 'Get bounding box of all objects on the current page.',- params: {},- execute: (figma) => {- const page = figma.currentPage- let minX = Infinity- let minY = Infinity- let maxX = -Infinity- let maxY = -Infinity- for (const child of page.children) {- const bounds = child.absoluteBoundingBox- minX = Math.min(minX, bounds.x)- minY = Math.min(minY, bounds.y)- maxX = Math.max(maxX, bounds.x + bounds.width)- maxY = Math.max(maxY, bounds.y + bounds.height)- }- if (minX === Infinity) return { x: 0, y: 0, width: 0, height: 0 }- return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }- }-})--// ─── Font tools ───────────────────────────────────────────────--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)' }- },- execute: (figma, args) => {- const fonts = new Map<string, Set<number>>()- const page = figma.currentPage- page.findAll((node) => {- if (node.type === 'TEXT') {- const raw = figma.graph.getNode(node.id)- if (raw) {- const key = raw.fontFamily- if (!fonts.has(key)) fonts.set(key, new Set())- fonts.get(key)!.add(raw.fontWeight)- }- }- return false- })- let result = [...fonts.entries()].map(([family, weights]) => ({- family,- weights: [...weights].sort()- }))- if (args.family) {- const q = args.family.toLowerCase()- result = result.filter((f) => f.family.toLowerCase().includes(q))- }- return { count: result.length, fonts: result }- }-})--// ─── Text properties ──────────────────────────────────────────--export const setTextProperties = defineTool({- name: 'set_text_properties',- 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']- },- text_decoration: {- type: 'string',- description: 'Text decoration',- enum: ['NONE', 'UNDERLINE', 'STRIKETHROUGH']- }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- if (node.type !== 'TEXT') return { error: `Node "${args.id}" is not a TEXT node` }- const updated: string[] = []- if (args.align_horizontal !== undefined) {- node.textAlignHorizontal = args.align_horizontal- updated.push('textAlignHorizontal')- }- if (args.align_vertical !== undefined) {- node.textAlignVertical = args.align_vertical- updated.push('textAlignVertical')- }- if (args.auto_resize !== undefined) {- node.textAutoResize = args.auto_resize- updated.push('textAutoResize')- }- if (args.text_decoration !== undefined) {- node.textDecoration = args.text_decoration- updated.push('textDecoration')- }- return { id: args.id, updated }- }-})--// ─── Layout child ─────────────────────────────────────────────--export const setLayoutChild = defineTool({- name: 'set_layout_child',- 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',- enum: ['INHERIT', 'STRETCH']- },- positioning: {- type: 'string',- description: 'ABSOLUTE to take node out of auto-layout flow',- enum: ['AUTO', 'ABSOLUTE']- }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- const updated: string[] = []- if (args.sizing_horizontal !== undefined) {- node.layoutSizingHorizontal = args.sizing_horizontal- updated.push('layoutSizingHorizontal')- }- if (args.sizing_vertical !== undefined) {- node.layoutSizingVertical = args.sizing_vertical- updated.push('layoutSizingVertical')- }- if (args.grow !== undefined) {- node.layoutGrow = args.grow- updated.push('layoutGrow')- }- if (args.align_self !== undefined) {- node.layoutAlign = args.align_self- updated.push('layoutAlign')- }- if (args.positioning !== undefined) {- node.layoutPositioning = args.positioning- updated.push('layoutPositioning')- }- return { id: args.id, updated }- }-})--// ─── Export tools ─────────────────────────────────────────────--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.'- }- },- execute: async (figma, args) => {- const { renderNodesToSVG } = await import('../svg-export.js')- const pageId = figma.currentPageId- const ids =- args.ids && args.ids.length > 0- ? args.ids- : figma.currentPage.children.map((n) => n.id)- const svg = renderNodesToSVG(figma.graph, pageId, ids)- if (!svg) return { error: 'No visible nodes to export' }- return { svg }- }-})--// ─── Registry ─────────────────────────────────────────────────--export const ALL_TOOLS: ToolDef[] = [- getSelection,- getPageTree,- getNode,- findNodes,- createShape,- render,- setFill,- setStroke,- setEffects,- updateNode,- setLayout,- setConstraints,- deleteNode,- cloneNode,- renameNode,- reparentNode,- selectNodes,- groupNodes,- ungroupNode,- createComponent,- createInstance,- listPages,- switchPage,- listVariables,- listCollections,- evalCode,- // Granular set tools- setRotation,- setOpacity,- setRadius,- setMinMax,- setText,- setFont,- setFontRange,- setTextResize,- setVisible,- setBlend,- setLocked,- setStrokeAlign,- // Node operations- nodeBounds,- nodeMove,- nodeResize,- nodeAncestors,- nodeChildren,- nodeTree,- nodeBindings,- nodeReplaceWith,- // Variable CRUD- getVariable,- findVariables,- createVariable,- setVariable,- deleteVariable,- bindVariable,- // Collection CRUD- getCollection,- createCollection,- deleteCollection,- // Boolean operations- booleanUnion,- booleanSubtract,- booleanIntersect,- booleanExclude,- // Vector path tools- pathGet,- pathSet,- pathScale,- pathFlip,- pathMove,- // Create tools- createPage,- createVector,- createSlice,- // Group tools- flattenNodes,- // Viewport tools- viewportGet,- viewportSet,- viewportZoomToFit,- pageBounds,- // Font tools- listFonts,- // Text properties- setTextProperties,- // Layout child- setLayoutChild,- // Export- exportSvg-]+export { ALL_TOOLS } from './registry'diff --git a/packages/core/src/tools/structure.ts b/packages/core/src/tools/structure.tsnew file mode 100644index 000000000..caa7ab35c--- /dev/null+++ b/packages/core/src/tools/structure.ts@@ -0,0 +1,336 @@+import { defineTool, nodeSummary } from './schema'++import type { FigmaNodeProxy } from '../figma-api'++export const deleteNode = defineTool({+ name: 'delete_node',+ description: 'Delete a node by ID.',+ params: {+ id: { type: 'string', description: 'Node ID to delete', required: true }+ },+ execute: (figma, { id }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.remove()+ return { deleted: id }+ }+})++export const cloneNode = defineTool({+ name: 'clone_node',+ description: 'Clone (duplicate) a node.',+ params: {+ id: { type: 'string', description: 'Node ID to clone', required: true }+ },+ execute: (figma, { id }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ const clone = node.clone()+ return nodeSummary(clone)+ }+})++export const renameNode = defineTool({+ name: 'rename_node',+ 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 }+ },+ execute: (figma, { id, name }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.name = name+ return { id, name }+ }+})++export const reparentNode = defineTool({+ name: 'reparent_node',+ 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 }+ },+ execute: (figma, { id, parent_id }) => {+ const node = figma.getNodeById(id)+ const parent = figma.getNodeById(parent_id)+ if (!node) return { error: `Node "${id}" not found` }+ if (!parent) return { error: `Parent "${parent_id}" not found` }+ parent.appendChild(node)+ return { id, parent_id }+ }+})++export const groupNodes = defineTool({+ name: 'group_nodes',+ description: 'Group selected nodes.',+ params: {+ ids: { type: 'string[]', description: 'Node IDs to group', required: true }+ },+ execute: (figma, { ids }) => {+ const nodes = ids+ .map((id) => figma.getNodeById(id))+ .filter((n): n is FigmaNodeProxy => n !== null)+ if (nodes.length < 2) return { error: 'Need at least 2 nodes to group' }+ const parent = nodes[0]!.parent ?? figma.currentPage+ const group = figma.group(nodes, parent)+ return nodeSummary(group)+ }+})++export const ungroupNode = defineTool({+ name: 'ungroup_node',+ description: 'Ungroup a group node.',+ params: {+ id: { type: 'string', description: 'Group node ID', required: true }+ },+ execute: (figma, { id }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ figma.ungroup(node)+ return { ungrouped: id }+ }+})++export const flattenNodes = defineTool({+ name: 'flatten_nodes',+ description: 'Flatten nodes into a single vector.',+ params: {+ ids: { type: 'string[]', description: 'Node IDs to flatten', required: true }+ },+ execute: (figma, { ids }) => {+ const result = figma.flattenNode(ids)+ return nodeSummary(result)+ }+})++export const nodeToComponent = defineTool({+ name: 'node_to_component',+ description: 'Convert one or more frames/groups into components.',+ params: {+ ids: { type: 'string[]', description: 'Node IDs to convert', required: true }+ },+ execute: (figma, { ids }) => {+ const results: { id: string; name: string; originalId: string }[] = []+ for (const id of ids) {+ const node = figma.getNodeById(id)+ if (!node) continue+ const comp = figma.createComponentFromNode(node)+ results.push({ id: comp.id, name: comp.name, originalId: id })+ }+ return { converted: results }+ }+})++export const nodeBounds = defineTool({+ name: 'node_bounds',+ description: 'Get absolute bounding box of a node.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true }+ },+ execute: (figma, { id }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ return { id, bounds: node.absoluteBoundingBox }+ }+})++export const nodeMove = defineTool({+ name: 'node_move',+ 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 }+ },+ execute: (figma, { id, x, y }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.x = x+ node.y = y+ return { id, x, y }+ }+})++export const nodeResize = defineTool({+ name: 'node_resize',+ 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 }+ },+ execute: (figma, { id, width, height }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.resize(width, height)+ return { id, width, height }+ }+})++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' }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return { error: `Node "${args.id}" not found` }+ const ancestors: { id: string; name: string; type: string }[] = []+ let current = node.parent+ let d = 0+ while (current && (!args.depth || d < args.depth)) {+ ancestors.push({ id: current.id, name: current.name, type: current.type })+ current = current.parent+ d+++ }+ return { id: args.id, ancestors }+ }+})++export const nodeChildren = defineTool({+ name: 'node_children',+ description: 'Get direct children of a node.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true }+ },+ execute: (figma, { id }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ return {+ id,+ children: node.children.map((c) => ({ id: c.id, name: c.name, type: c.type }))+ }+ }+})++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)' }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return { error: `Node "${args.id}" not found` }+ function buildTree(n: FigmaNodeProxy, d: number): Record<string, unknown> {+ const result: Record<string, unknown> = { id: n.id, name: n.name, type: n.type }+ if (args.depth === undefined || d < args.depth) {+ const kids = n.children+ if (kids.length > 0) result.children = kids.map((c) => buildTree(c, d + 1))+ }+ return result+ }+ return buildTree(node, 0)+ }+})++export const nodeBindings = defineTool({+ name: 'node_bindings',+ description: 'Get variable bindings for a node.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true }+ },+ execute: (figma, { id }) => {+ const raw = figma.graph.getNode(id)+ if (!raw) return { error: `Node "${id}" not found` }+ return { id, bindings: raw.boundVariables }+ }+})++export const nodeReplaceWith = defineTool({+ name: 'node_replace_with',+ 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 }+ },+ execute: async (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return { error: `Node "${args.id}" not found` }+ const parentId = node.parent?.id ?? figma.currentPageId+ const x = node.x+ const y = node.y+ node.remove()+ const { renderJsx } = await import('../render/render-jsx.js')+ const result = await renderJsx(figma.graph, args.jsx, { parentId, x, y })+ return { id: result.id, name: result.name, type: result.type }+ }+})++export const arrangeNodes = defineTool({+ name: 'arrange',+ 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)' }+ },+ execute: (figma, args) => {+ const gap = args.gap ?? 40+ const mode = args.mode ?? 'grid'+ const page = figma.currentPage++ let nodes: FigmaNodeProxy[]+ if (args.ids && args.ids.length > 0) {+ nodes = args.ids+ .map((id) => figma.getNodeById(id))+ .filter((n): n is FigmaNodeProxy => n !== null)+ } else {+ nodes = [...page.children]+ }++ if (nodes.length === 0) return { error: 'No nodes to arrange' }+ const first = nodes[0]!++ if (mode === 'row') {+ let x = first.x+ const y = first.y+ for (const node of nodes) {+ node.x = x+ node.y = y+ x += node.width + gap+ }+ } else if (mode === 'column') {+ const x = first.x+ let y = first.y+ for (const node of nodes) {+ node.x = x+ node.y = y+ y += node.height + gap+ }+ } else {+ const cols = args.cols ?? Math.ceil(Math.sqrt(nodes.length))+ const startX = first.x+ let x = startX+ let y = first.y+ let rowHeight = 0++ for (let i = 0; i < nodes.length; i++) {+ const node = nodes[i]!+ if (i > 0 && i % cols === 0) {+ x = startX+ y += rowHeight + gap+ rowHeight = 0+ }+ node.x = x+ node.y = y+ x += node.width + gap+ rowHeight = Math.max(rowHeight, node.height)+ }+ }++ return { arranged: nodes.length, mode }+ }+})diff --git a/packages/core/src/tools/variables.ts b/packages/core/src/tools/variables.tsnew file mode 100644index 000000000..53cf9c124--- /dev/null+++ b/packages/core/src/tools/variables.ts@@ -0,0 +1,187 @@+import { parseColor } from '../color'++import { defineTool } from './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']+ }+ },+ execute: (figma, args) => {+ const vars = figma.getLocalVariables(args.type)+ return { count: vars.length, variables: vars }+ }+})++export const listCollections = defineTool({+ name: 'list_collections',+ description: 'List all variable collections.',+ params: {},+ execute: (figma) => {+ const cols = figma.getLocalVariableCollections()+ return { count: cols.length, collections: cols }+ }+})++export const getVariable = defineTool({+ name: 'get_variable',+ description: 'Get a variable by ID.',+ params: {+ id: { type: 'string', description: 'Variable ID', required: true }+ },+ execute: (figma, { id }) => {+ const v = figma.getVariableById(id)+ if (!v) return { error: `Variable "${id}" not found` }+ return v+ }+})++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']+ }+ },+ execute: (figma, args) => {+ let vars = figma.getLocalVariables(args.type)+ vars = vars.filter((v) => v.name.toLowerCase().includes(args.query.toLowerCase()))+ return { count: vars.length, variables: vars }+ }+})++export const createVariable = defineTool({+ name: 'create_variable',+ 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.)' }+ },+ execute: (figma, args) => {+ let parsedValue: unknown+ if (args.value !== undefined) {+ if (args.type === 'COLOR') parsedValue = parseColor(args.value)+ else if (args.type === 'FLOAT') parsedValue = Number(args.value)+ else if (args.type === 'BOOLEAN') parsedValue = args.value === 'true'+ else parsedValue = args.value+ }+ const v = figma.createVariable(+ args.name,+ args.type as any,+ args.collection_id,+ parsedValue as any+ )+ return v+ }+})++export const setVariable = defineTool({+ name: 'set_variable',+ 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+ }+ },+ execute: (figma, args) => {+ const v = figma.getVariableById(args.id)+ if (!v) return { error: `Variable "${args.id}" not found` }+ let parsedValue: unknown+ if (v.type === 'COLOR') parsedValue = parseColor(args.value)+ else if (v.type === 'FLOAT') parsedValue = Number(args.value)+ else if (v.type === 'BOOLEAN') parsedValue = args.value === 'true'+ else parsedValue = args.value+ figma.setVariableValue(args.id, args.mode, parsedValue as any)+ return { id: args.id, mode: args.mode, value: parsedValue }+ }+})++export const deleteVariable = defineTool({+ name: 'delete_variable',+ description: 'Delete a variable.',+ params: {+ id: { type: 'string', description: 'Variable ID', required: true }+ },+ execute: (figma, { id }) => {+ figma.deleteVariable(id)+ return { deleted: id }+ }+})++export const bindVariable = defineTool({+ name: 'bind_variable',+ description: 'Bind a variable to a node property (fills, strokes, opacity, width, height, etc.).',+ params: {+ node_id: { type: 'string', description: 'Node ID', required: true },+ field: {+ type: 'string',+ description: 'Property field (fills, strokes, opacity, width, height, etc.)',+ required: true+ },+ variable_id: { type: 'string', description: 'Variable ID', required: true }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.node_id)+ if (!node) return { error: `Node "${args.node_id}" not found` }+ const v = figma.getVariableById(args.variable_id)+ if (!v) return { error: `Variable "${args.variable_id}" not found` }+ figma.bindVariable(args.node_id, args.field, args.variable_id)+ return { node_id: args.node_id, field: args.field, variable_id: args.variable_id }+ }+})++export const getCollection = defineTool({+ name: 'get_collection',+ description: 'Get a variable collection by ID.',+ params: {+ id: { type: 'string', description: 'Collection ID', required: true }+ },+ execute: (figma, { id }) => {+ const c = figma.getVariableCollectionById(id)+ if (!c) return { error: `Collection "${id}" not found` }+ return c+ }+})++export const createCollection = defineTool({+ name: 'create_collection',+ description: 'Create a new variable collection.',+ params: {+ name: { type: 'string', description: 'Collection name', required: true }+ },+ execute: (figma, { name }) => {+ return figma.createVariableCollection(name)+ }+})++export const deleteCollection = defineTool({+ name: 'delete_collection',+ description: 'Delete a variable collection and all its variables.',+ params: {+ id: { type: 'string', description: 'Collection ID', required: true }+ },+ execute: (figma, { id }) => {+ figma.deleteVariableCollection(id)+ return { deleted: id }+ }+})diff --git a/packages/core/src/tools/vector.ts b/packages/core/src/tools/vector.tsnew file mode 100644index 000000000..1d00cd299--- /dev/null+++ b/packages/core/src/tools/vector.ts@@ -0,0 +1,298 @@+import { defineTool, nodeSummary } from './schema'++export const booleanUnion = defineTool({+ name: 'boolean_union',+ description: 'Union (combine) multiple nodes.',+ params: {+ ids: { type: 'string[]', description: 'Node IDs to union', required: true }+ },+ execute: (figma, { ids }) => {+ const result = figma.booleanOperation('UNION', ids)+ return nodeSummary(result)+ }+})++export const booleanSubtract = defineTool({+ name: 'boolean_subtract',+ description: 'Subtract the second node from the first.',+ params: {+ ids: { type: 'string[]', description: 'Node IDs (first minus rest)', required: true }+ },+ execute: (figma, { ids }) => {+ const result = figma.booleanOperation('SUBTRACT', ids)+ return nodeSummary(result)+ }+})++export const booleanIntersect = defineTool({+ name: 'boolean_intersect',+ description: 'Intersect multiple nodes.',+ params: {+ ids: { type: 'string[]', description: 'Node IDs to intersect', required: true }+ },+ execute: (figma, { ids }) => {+ const result = figma.booleanOperation('INTERSECT', ids)+ return nodeSummary(result)+ }+})++export const booleanExclude = defineTool({+ name: 'boolean_exclude',+ description: 'Exclude (XOR) multiple nodes.',+ params: {+ ids: { type: 'string[]', description: 'Node IDs to exclude', required: true }+ },+ execute: (figma, { ids }) => {+ const result = figma.booleanOperation('EXCLUDE', ids)+ return nodeSummary(result)+ }+})++export const pathGet = defineTool({+ name: 'path_get',+ description: 'Get vector path data of a node.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true }+ },+ execute: (figma, { id }) => {+ const raw = figma.graph.getNode(id)+ if (!raw) return { error: `Node "${id}" not found` }+ if (!raw.vectorNetwork) return { error: `Node "${id}" has no vector data` }+ return { id, vectorNetwork: raw.vectorNetwork }+ }+})++export const pathSet = defineTool({+ name: 'path_set',+ 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 }+ },+ execute: (figma, args) => {+ const raw = figma.graph.getNode(args.id)+ if (!raw) return { error: `Node "${args.id}" not found` }+ const network = JSON.parse(args.path)+ figma.graph.updateNode(args.id, { vectorNetwork: network } as any)+ return { id: args.id }+ }+})++export const pathScale = defineTool({+ name: 'path_scale',+ 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 }+ },+ execute: (figma, { id, factor }) => {+ const raw = figma.graph.getNode(id)+ if (!raw) return { error: `Node "${id}" not found` }+ if (!raw.vectorNetwork) return { error: `Node "${id}" has no vector data` }+ const vn = structuredClone(raw.vectorNetwork)+ const cx = raw.width / 2+ const cy = raw.height / 2+ for (const v of vn.vertices) {+ v.x = cx + (v.x - cx) * factor+ v.y = cy + (v.y - cy) * factor+ }+ for (const s of vn.segments) {+ if (s.tangentStart) {+ s.tangentStart.x *= factor+ s.tangentStart.y *= factor+ }+ if (s.tangentEnd) {+ s.tangentEnd.x *= factor+ s.tangentEnd.y *= factor+ }+ }+ figma.graph.updateNode(id, { vectorNetwork: vn } as any)+ return { id, factor }+ }+})++export const pathFlip = defineTool({+ name: 'path_flip',+ 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']+ }+ },+ execute: (figma, { id, axis }) => {+ const raw = figma.graph.getNode(id)+ if (!raw) return { error: `Node "${id}" not found` }+ if (!raw.vectorNetwork) return { error: `Node "${id}" has no vector data` }+ const vn = structuredClone(raw.vectorNetwork)+ const w = raw.width+ const h = raw.height+ for (const v of vn.vertices) {+ if (axis === 'horizontal') v.x = w - v.x+ else v.y = h - v.y+ }+ for (const s of vn.segments) {+ if (s.tangentStart) {+ if (axis === 'horizontal') s.tangentStart.x = -s.tangentStart.x+ else s.tangentStart.y = -s.tangentStart.y+ }+ if (s.tangentEnd) {+ if (axis === 'horizontal') s.tangentEnd.x = -s.tangentEnd.x+ else s.tangentEnd.y = -s.tangentEnd.y+ }+ }+ figma.graph.updateNode(id, { vectorNetwork: vn } as any)+ return { id, axis }+ }+})++export const pathMove = defineTool({+ name: 'path_move',+ 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 }+ },+ execute: (figma, { id, dx, dy }) => {+ const raw = figma.graph.getNode(id)+ if (!raw) return { error: `Node "${id}" not found` }+ if (!raw.vectorNetwork) return { error: `Node "${id}" has no vector data` }+ const vn = structuredClone(raw.vectorNetwork)+ for (const v of vn.vertices) {+ v.x += dx+ v.y += dy+ }+ figma.graph.updateNode(id, { vectorNetwork: vn } as any)+ return { id, dx, dy }+ }+})++export const viewportGet = defineTool({+ name: 'viewport_get',+ description: 'Get current viewport position and zoom level.',+ params: {},+ execute: (figma) => {+ return figma.viewport+ }+})++export const viewportSet = defineTool({+ name: 'viewport_set',+ 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 }+ },+ execute: (figma, { x, y, zoom }) => {+ figma.viewport = { center: { x, y }, zoom }+ return { x, y, zoom }+ }+})++export const viewportZoomToFit = defineTool({+ name: 'viewport_zoom_to_fit',+ description: 'Zoom viewport to fit specified nodes.',+ params: {+ ids: { type: 'string[]', description: 'Node IDs to fit in view', required: true }+ },+ execute: (figma, { ids }) => {+ let minX = Infinity+ let minY = Infinity+ let maxX = -Infinity+ let maxY = -Infinity+ for (const id of ids) {+ const node = figma.getNodeById(id)+ if (!node) continue+ const bounds = node.absoluteBoundingBox+ minX = Math.min(minX, bounds.x)+ minY = Math.min(minY, bounds.y)+ maxX = Math.max(maxX, bounds.x + bounds.width)+ maxY = Math.max(maxY, bounds.y + bounds.height)+ }+ if (minX === Infinity) return { error: 'No valid nodes found' }+ const cx = (minX + maxX) / 2+ const cy = (minY + maxY) / 2+ figma.viewport = { center: { x: cx, y: cy }, zoom: 1 }+ return {+ center: { x: cx, y: cy },+ bounds: { x: minX, y: minY, width: maxX - minX, height: maxY - minY }+ }+ }+})++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.'+ }+ },+ execute: async (figma, args) => {+ const { renderNodesToSVG } = await import('../svg-export.js')+ const pageId = figma.currentPageId+ const ids =+ args.ids && args.ids.length > 0+ ? args.ids+ : figma.currentPage.children.map((n) => n.id)+ const svg = renderNodesToSVG(figma.graph, pageId, ids)+ if (!svg) return { error: 'No visible nodes to export' }+ return { svg }+ }+})++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 (default: 1)',+ default: 1,+ min: 0.1,+ max: 4+ }+ },+ 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((n) => n.id)+ const format = ((args.format as string) ?? 'PNG').toUpperCase() as 'PNG' | 'JPG' | 'WEBP'+ const data = await figma.exportImage(ids, {+ scale: args.scale ?? 1,+ format+ })+ if (!data || data.length === 0) return { error: 'No visible nodes to export' }+ const base64 =+ typeof Buffer !== 'undefined'+ ? Buffer.from(data).toString('base64')+ : btoa(String.fromCharCode(...data))+ const mimeMap = { PNG: 'image/png', JPG: 'image/jpeg', WEBP: 'image/webp' } as const+ return {+ mimeType: mimeMap[format],+ base64,+ byteLength: data.length+ }+ }+})diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.tsindex 933f95a7f..e332d4259 100644--- a/packages/mcp/src/server.ts+++ b/packages/mcp/src/server.ts@@ -4,11 +4,21 @@ import { isAbsolute, relative, resolve } from 'node:path'import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'import { z } from 'zod'-import { ALL_TOOLS, FigmaAPI, parseFigFile, computeAllLayouts, SceneGraph } from '@open-pencil/core'--import type { ToolDef, ParamDef, ParamType } from '@open-pencil/core'--type McpResult = { content: { type: 'text'; text: string }[]; isError?: boolean }+import {+ ALL_TOOLS,+ FigmaAPI,+ parseFigFile,+ computeAllLayouts,+ SceneGraph,+ renderNodesToImage,+ SkiaRenderer+} from '@open-pencil/core'++import type { ToolDef, ParamDef, ParamType, ExportFormat } from '@open-pencil/core'+import type { CanvasKit } from 'canvaskit-wasm'++type McpContent = { type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }+type McpResult = { content: McpContent[]; isError?: boolean }export interface CreateServerOptions {enableEval?: booleanfileRoot?: string | null@@ -44,6 +54,17 @@ function paramToZod(param: ParamDef): z.ZodTypeAny {return param.required ? schema : schema.optional()}+let ckInstance: CanvasKit | null = null++async function getCanvasKit(): Promise<CanvasKit> {+ if (ckInstance) return ckInstance+ const CanvasKitInit = (await import('canvaskit-wasm/full')).default+ const ckPath = import.meta.resolve('canvaskit-wasm/full')+ const binDir = new URL('.', ckPath).pathname+ ckInstance = await CanvasKitInit({ locateFile: (file: string) => binDir + file })+ return ckInstance+}+export function createServer(version: string, options: CreateServerOptions = {}): McpServer {const server = new McpServer({ name: 'open-pencil', version })const enableEval = options.enableEval ?? true@@ -58,6 +79,19 @@ export function createServer(version: string, options: CreateServerOptions = {})if (!graph) throw new Error('No document loaded. Use open_file or new_document first.')const api = new FigmaAPI(graph)if (currentPageId) api.currentPage = api.wrapNode(currentPageId)+ api.exportImage = async (nodeIds, opts) => {+ const ck = await getCanvasKit()+ const surface = ck.MakeSurface(1, 1)!+ const renderer = new SkiaRenderer(ck, surface)+ renderer.viewportWidth = 1+ renderer.viewportHeight = 1+ renderer.dpr = 1+ const pageId = currentPageId ?? graph!.getPages()[0]?.id ?? graph!.rootId+ return renderNodesToImage(ck, renderer, graph!, pageId, nodeIds, {+ scale: opts.scale ?? 1,+ format: (opts.format ?? 'PNG') as ExportFormat+ })+ }return api}@@ -80,7 +114,12 @@ export function createServer(version: string, options: CreateServerOptions = {})// eslint-disable-next-line @typescript-eslint/no-explicit-any -- dynamic schema from ToolDef paramsserver.registerTool(def.name, { description: def.description, inputSchema: z.object(shape) } as any, async (args: any) => {try {- const result = await def.execute(makeFigma(), args as Record<string, unknown>)+ const result = await def.execute(makeFigma(), args as Record<string, unknown>) as Record<string, unknown>+ if (result && typeof result === 'object' && 'base64' in result && 'mimeType' in result) {+ return {+ content: [{ type: 'image' as const, data: result.base64 as string, mimeType: result.mimeType as string }]+ }+ }return ok(result)} catch (e) {return fail(e)diff --git a/src/ai/tools.ts b/src/ai/tools.tsindex b4cb13b58..277d7fa65 100644--- a/src/ai/tools.ts+++ b/src/ai/tools.ts@@ -4,6 +4,7 @@ import { tool } from 'ai'import * as v from 'valibot'import type { EditorStore } from '@/stores/editor'+import type { ExportFormat } from '@open-pencil/core'export function createAITools(store: EditorStore) {return toolsToAI(@@ -15,10 +16,15 @@ export function createAITools(store: EditorStore) {api.currentPage.selection = [...store.state.selectedIds].map((id) => api.getNodeById(id)).filter((n): n is NonNullable<typeof n> => n !== null)+ api.exportImage = (nodeIds, opts) =>+ store.renderExportImage(nodeIds, opts.scale ?? 1, (opts.format ?? 'PNG') as ExportFormat)return api},onAfterExecute: () => {store.requestRender()+ },+ onFlashNodes: (nodeIds) => {+ store.flashNodes(nodeIds)}},{ v, valibotSchema, tool }diff --git a/src/stores/editor.ts b/src/stores/editor.tsindex b68c6fd81..4201ba5a7 100644--- a/src/stores/editor.ts+++ b/src/stores/editor.ts@@ -243,6 +243,22 @@ export function createEditorStore() {state.renderVersion++}+ let flashRafId = 0+ function flashNodes(nodeIds: string[]) {+ if (!_renderer) return+ for (const id of nodeIds) _renderer.flashNode(id)+ if (!flashRafId) pumpFlashes()+ }++ function pumpFlashes() {+ if (!_renderer?.hasActiveFlashes) {+ flashRafId = 0+ return+ }+ state.renderVersion+++ flashRafId = requestAnimationFrame(pumpFlashes)+ }+function isTopLevel(parentId: string | null): boolean {return !parentId || parentId === graph.rootId || parentId === state.currentPageId}@@ -2052,6 +2068,7 @@ export function createEditorStore() {layerTree,requestRender,requestRepaint,+ flashNodes,setTool,select,clearSelection,