figma-mcp-console 0.5.4 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,15 +2,15 @@
2
2
  // Receives {id, command, params} from the Go bridge (relayed through ui.html),
3
3
  // executes it against the Figma Plugin API, and replies {id, result|error}.
4
4
 
5
- figma.showUI(__html__, { width: 300, height: 132 });
5
+ figma.showUI(__html__, { width: 280, height: 104 });
6
6
 
7
7
  // Tell the UI which file this plugin window runs in; the UI forwards it to
8
8
  // the bridge on every (re)connect so calls can be routed per file when
9
- // several files run the plugin at once. figma.fileKey is undefined for
10
- // non-published dev plugins, so the file name is the primary identifier.
11
- figma.ui.postMessage({
12
- register: { key: figma.fileKey || undefined, name: figma.root.name },
13
- });
9
+ // several files run the plugin at once. figma.fileKey needs
10
+ // enablePrivatePluginApi in the manifest, so the file name stays the fallback.
11
+ // readOnly rides along so AI sees it in list_files before it plans an edit.
12
+ const register = () =>
13
+ figma.ui.postMessage({ register: { key: figma.fileKey || undefined, name: figma.root.name, read_only: readOnly } });
14
14
 
15
15
  // ---------- helpers ----------
16
16
 
@@ -27,11 +27,92 @@ async function node(id) {
27
27
  return n;
28
28
  }
29
29
 
30
+ // Pages are addressed by id or name. With documentAccess "dynamic-page" a
31
+ // page's children are unreachable until it is loaded, so load it here.
32
+ async function resolvePage(ref) {
33
+ const want = String(ref);
34
+ const lower = want.toLowerCase();
35
+ const pages = figma.root.children;
36
+ let p = pages.find((x) => x.id === want) || pages.find((x) => x.name.toLowerCase() === lower);
37
+ if (!p) {
38
+ const partial = pages.filter((x) => x.name.toLowerCase().indexOf(lower) !== -1);
39
+ if (partial.length > 1) {
40
+ throw new Error("page " + ref + " is ambiguous: " + partial.map((x) => x.name).join(", "));
41
+ }
42
+ p = partial[0];
43
+ }
44
+ if (!p) throw new Error("page not found: " + ref + " (see list_pages)");
45
+ await p.loadAsync();
46
+ return p;
47
+ }
48
+
49
+ // Figma stacks newly combined variants on top of each other and never grows
50
+ // the set to fit them, so the extras are invisible and clipped. Lay them out.
51
+ function arrangeVariants(set) {
52
+ if (set.layoutMode && set.layoutMode !== "NONE") return;
53
+ const gap = 32;
54
+ let y = 0;
55
+ let w = 0;
56
+ for (const v of set.children) {
57
+ v.x = 0;
58
+ v.y = y;
59
+ y += v.height + gap;
60
+ w = Math.max(w, v.width);
61
+ }
62
+ if (y > 0) set.resize(Math.max(w, 1), Math.max(y - gap, 1));
63
+ }
64
+
65
+ // Mutating commands accept one node_id or many node_ids so a bulk edit costs
66
+ // one call instead of one per node.
67
+ async function targets(params) {
68
+ const ids = params.node_ids && params.node_ids.length
69
+ ? params.node_ids
70
+ : params.node_id ? [params.node_id] : [];
71
+ if (!ids.length) throw new Error("node_id or node_ids is required");
72
+ const out = [];
73
+ for (const id of ids) out.push(await node(id));
74
+ return out;
75
+ }
76
+
77
+ // Result of a mutating command. Echoing a full summary per node drowns the
78
+ // caller's context on a 50-node batch, so default to ids and let the caller
79
+ // ask for the rest with verbose.
80
+ function done(params, nodes, extra) {
81
+ const list = Array.isArray(nodes) ? nodes : [nodes];
82
+ const out = params.verbose
83
+ ? { nodes: list.map(summarize) }
84
+ : { ok: true, ids: list.map((n) => n.id) };
85
+ return Object.assign(out, extra || {});
86
+ }
87
+
30
88
  // Mixed values (figma.mixed) are Symbols, which postMessage cannot clone.
31
89
  function val(x) {
32
90
  return x === figma.mixed ? "mixed" : x;
33
91
  }
34
92
 
93
+ function rgbToHex(c) {
94
+ const h = (v) => ("0" + Math.round(v * 255).toString(16)).slice(-2);
95
+ return "#" + h(c.r) + h(c.g) + h(c.b);
96
+ }
97
+
98
+ // A full PaintObject is ~20 lines of JSON (17-digit float channels, complete
99
+ // gradientTransform); compact callers only ever need the color.
100
+ function paintBrief(p) {
101
+ if (p.visible === false) return "hidden";
102
+ if (p.type !== "SOLID") return p.type;
103
+ const hex = rgbToHex(p.color);
104
+ return p.opacity === undefined || p.opacity === 1 ? hex : hex + "@" + p.opacity;
105
+ }
106
+
107
+ // First visible solid fill as hex, for find_nodes' fill filter.
108
+ function solidFillHex(n) {
109
+ if (!("fills" in n) || !Array.isArray(n.fills)) return null;
110
+ for (const p of n.fills) {
111
+ if (p.type === "SOLID" && p.visible !== false) return rgbToHex(p.color);
112
+ }
113
+ return null;
114
+ }
115
+
35
116
  function summarize(n) {
36
117
  const s = { id: n.id, name: n.name, type: n.type };
37
118
  if (n.parent) s.parentId = n.parent.id;
@@ -41,22 +122,9 @@ function summarize(n) {
41
122
  return s;
42
123
  }
43
124
 
44
- // The file key needed to build share links. Published plugins can read it from
45
- // figma.fileKey, but development plugins (imported from a manifest) cannot, so
46
- // we fall back to a key the user pastes once — their file URL — persisted in
47
- // the file via pluginData so it survives reopening.
48
- const FILE_KEY_DATA = "figma-mcp-file-key";
49
- let fileKey = figma.fileKey || "";
50
- try {
51
- if (!fileKey) fileKey = figma.root.getPluginData(FILE_KEY_DATA) || "";
52
- } catch (e) {}
53
-
54
- function setFileKey(key) {
55
- fileKey = key || "";
56
- try {
57
- figma.root.setPluginData(FILE_KEY_DATA, fileKey);
58
- } catch (e) {}
59
- }
125
+ // The file key needed to build share links. Development plugins only get
126
+ // figma.fileKey because the manifest sets enablePrivatePluginApi.
127
+ const fileKey = figma.fileKey || "";
60
128
 
61
129
  // nodeLink builds a shareable figma.com URL that jumps straight to a node (the
62
130
  // same link as Figma's "Copy link to selection"). Returns null when no file
@@ -73,16 +141,29 @@ function nodeLink(id) {
73
141
  );
74
142
  }
75
143
 
76
- function serialize(n, depth) {
144
+ // compact drops defaults (visible, full opacity, empty fills) and renders
145
+ // paints as hex: depth 1 on a 27-child frame is ~15k tokens otherwise.
146
+ // visibleOnly drops hidden layers (and their subtrees): QC scripts would
147
+ // otherwise report them as missing on the web.
148
+ function serialize(n, depth, compact, visibleOnly) {
77
149
  const s = summarize(n);
78
- if ("visible" in n) s.visible = n.visible;
79
- if ("opacity" in n) s.opacity = n.opacity;
80
- if ("fills" in n && Array.isArray(n.fills)) s.fills = n.fills;
150
+ if (compact) {
151
+ for (const k of ["x", "y", "width", "height"]) {
152
+ if (typeof s[k] === "number") s[k] = Math.round(s[k] * 100) / 100;
153
+ }
154
+ }
155
+ if ("visible" in n && (!compact || !n.visible)) s.visible = n.visible;
156
+ if ("opacity" in n && (!compact || n.opacity !== 1)) s.opacity = n.opacity;
157
+ if ("fills" in n && Array.isArray(n.fills) && (!compact || n.fills.length)) {
158
+ s.fills = compact ? n.fills.map(paintBrief) : n.fills;
159
+ }
81
160
  if ("strokes" in n && n.strokes.length) {
82
- s.strokes = n.strokes;
83
- s.strokeWeight = val(n.strokeWeight);
161
+ s.strokes = compact ? n.strokes.map(paintBrief) : n.strokes;
162
+ if (!compact || val(n.strokeWeight) !== 1) s.strokeWeight = val(n.strokeWeight);
163
+ }
164
+ if ("effects" in n && n.effects.length) {
165
+ s.effects = compact ? n.effects.map((e) => e.type) : n.effects;
84
166
  }
85
- if ("effects" in n && n.effects.length) s.effects = n.effects;
86
167
  if ("cornerRadius" in n && n.cornerRadius !== 0) s.cornerRadius = val(n.cornerRadius);
87
168
  if (n.type === "TEXT") {
88
169
  s.fontSize = val(n.fontSize);
@@ -98,13 +179,109 @@ function serialize(n, depth) {
98
179
  s.primaryAxisAlignItems = n.primaryAxisAlignItems;
99
180
  s.counterAxisAlignItems = n.counterAxisAlignItems;
100
181
  }
182
+ // Sizes auto layout computes (fill, hug) and layers pinned outside the flow,
183
+ // so diff_design reports only what the designer set. FIXED is the default, left out.
184
+ try {
185
+ if (n.layoutSizingHorizontal && n.layoutSizingHorizontal !== "FIXED") s.layoutSizingHorizontal = n.layoutSizingHorizontal;
186
+ if (n.layoutSizingVertical && n.layoutSizingVertical !== "FIXED") s.layoutSizingVertical = n.layoutSizingVertical;
187
+ if (n.layoutPositioning === "ABSOLUTE") s.layoutPositioning = "ABSOLUTE";
188
+ } catch (e) {}
189
+ // Designer notes and variant values; each getter can throw on node types or
190
+ // plans that lack it, which must not sink the whole tree.
191
+ try {
192
+ if ("annotations" in n && n.annotations.length) {
193
+ s.annotations = n.annotations.map((a) => ({
194
+ label: a.labelMarkdown || a.label || "",
195
+ properties: (a.properties || []).map((p) => p.type),
196
+ }));
197
+ }
198
+ } catch (e) {}
199
+ try {
200
+ if ((n.type === "INSTANCE" || n.type === "COMPONENT") && n.variantProperties) {
201
+ s.variant = n.variantProperties;
202
+ }
203
+ } catch (e) {}
204
+ if (n.type === "COMPONENT_SET") {
205
+ const opts = variantOptions(n);
206
+ if (opts) s.variantOptions = opts;
207
+ }
208
+ // Dashed vs solid borders, and the tokens/styles behind the raw values: ids
209
+ // here, swapped for names by resolveRefs once the (sync) walk is done.
210
+ if ("dashPattern" in n && n.dashPattern.length) s.dashPattern = n.dashPattern;
211
+ try {
212
+ if (n.boundVariables && Object.keys(n.boundVariables).length) s.boundVariables = Object.assign({}, n.boundVariables); // a copy: resolveRefs rewrites it
213
+ } catch (e) {}
214
+ for (const k of STYLE_KEYS) {
215
+ if (k in n && typeof n[k] === "string" && n[k]) s[k] = n[k];
216
+ }
217
+ // Text mixing fonts, sizes or colors (one bold word, a red asterisk) reads
218
+ // as "mixed" above; list the runs so nothing hides behind it.
219
+ if (n.type === "TEXT" && [n.fontName, n.fontSize, n.fills, n.textDecoration].includes(figma.mixed)) {
220
+ try {
221
+ s.segments = n.getStyledTextSegments(["fontName", "fontSize", "fills", "textDecoration"]).map((g) => {
222
+ const seg = { text: g.characters, font: g.fontName.family + " " + g.fontName.style, size: g.fontSize, fill: g.fills.map(paintBrief).join(", ") };
223
+ if (g.textDecoration !== "NONE") seg.decoration = g.textDecoration;
224
+ return seg;
225
+ });
226
+ } catch (e) {}
227
+ }
101
228
  if ("children" in n) {
102
- s.childCount = n.children.length;
103
- if (depth > 0) s.children = n.children.map((c) => serialize(c, depth - 1));
229
+ const kids = visibleOnly ? n.children.filter((c) => c.visible !== false) : n.children;
230
+ if (!compact || kids.length) {
231
+ s.childCount = kids.length;
232
+ if (depth > 0) s.children = kids.map((c) => serialize(c, depth - 1, compact, visibleOnly));
233
+ }
104
234
  }
105
235
  return s;
106
236
  }
107
237
 
238
+ const STYLE_KEYS = ["fillStyleId", "strokeStyleId", "textStyleId", "effectStyleId"];
239
+
240
+ // Replace variable and style ids in a serialized tree with their names
241
+ // ("color/primary/500", "Heading/H1"), so a reader can match them to tokens.
242
+ async function resolveRefs(root) {
243
+ const cache = new Map();
244
+ const name = async (id, style) => {
245
+ if (!cache.has(id)) {
246
+ let x = null;
247
+ try {
248
+ x = style ? await figma.getStyleByIdAsync(id) : await figma.variables.getVariableByIdAsync(id);
249
+ } catch (e) {}
250
+ cache.set(id, x ? x.name : id);
251
+ }
252
+ return cache.get(id);
253
+ };
254
+ const alias = async (v) =>
255
+ Array.isArray(v) ? Promise.all(v.map(alias)) : v && v.type === "VARIABLE_ALIAS" ? name(v.id) : v;
256
+ const walk = async (s) => {
257
+ if (s.boundVariables) {
258
+ for (const k of Object.keys(s.boundVariables)) s.boundVariables[k] = await alias(s.boundVariables[k]);
259
+ }
260
+ for (const k of STYLE_KEYS) {
261
+ if (s[k]) {
262
+ s[k.slice(0, -2)] = await name(s[k], true); // fillStyleId -> fillStyle
263
+ delete s[k];
264
+ }
265
+ }
266
+ if (s.children) for (const c of s.children) await walk(c);
267
+ };
268
+ await walk(root);
269
+ return root;
270
+ }
271
+
272
+ // {property: [values]} for a component set's variant properties, or null.
273
+ function variantOptions(set) {
274
+ try {
275
+ const out = {};
276
+ for (const [k, d] of Object.entries(set.componentPropertyDefinitions)) {
277
+ if (d.type === "VARIANT") out[k.replace(/#.*$/, "")] = d.variantOptions || [];
278
+ }
279
+ return Object.keys(out).length ? out : null;
280
+ } catch (e) {
281
+ return null;
282
+ }
283
+ }
284
+
108
285
  async function parentOf(params) {
109
286
  if (params.parent_id) {
110
287
  const p = await node(params.parent_id);
@@ -171,13 +348,221 @@ function buildEffects(list) {
171
348
  }
172
349
 
173
350
  function applyShapeParams(n, params) {
174
- n.x = params.x;
175
- n.y = params.y;
351
+ n.x = params.x || 0;
352
+ n.y = params.y || 0;
176
353
  if (params.width > 0 && params.height > 0) n.resize(params.width, params.height);
177
354
  if (params.name) n.name = params.name;
178
- if (params.fill_color) n.fills = [{ type: "SOLID", color: hexToRGB(params.fill_color) }];
355
+ if (params.fill_color && params.fill_color !== "none") {
356
+ n.fills = [{ type: "SOLID", color: hexToRGB(params.fill_color) }];
357
+ }
358
+ }
359
+
360
+ // Optional extras find_nodes can attach per node, so callers can filter on
361
+ // style without a get_design_context round-trip per hit.
362
+ const FIELD_GETTERS = {
363
+ fills: (n) => ("fills" in n && Array.isArray(n.fills) ? n.fills.map(paintBrief) : undefined),
364
+ strokes: (n) => ("strokes" in n && Array.isArray(n.strokes) && n.strokes.length ? n.strokes.map(paintBrief) : undefined),
365
+ fontSize: (n) => (n.type === "TEXT" ? val(n.fontSize) : undefined),
366
+ fontName: (n) => (n.type === "TEXT" ? val(n.fontName) : undefined),
367
+ cornerRadius: (n) => ("cornerRadius" in n ? val(n.cornerRadius) : undefined),
368
+ effects: (n) => ("effects" in n && n.effects.length ? n.effects.map((e) => e.type) : undefined),
369
+ opacity: (n) => ("opacity" in n ? n.opacity : undefined),
370
+ characters: (n) => (n.type === "TEXT" ? n.characters : undefined),
371
+ };
372
+
373
+ // ---------- prototyping ----------
374
+
375
+ const TRIGGERS = ["ON_CLICK", "ON_HOVER", "ON_PRESS", "ON_DRAG"];
376
+ const NAVIGATIONS = ["NAVIGATE", "SWAP", "OVERLAY", "BACK", "CLOSE"];
377
+ // Directional transitions carry a direction; the rest only easing/duration.
378
+ const DIRECTIONAL_TRANSITIONS = ["MOVE_IN", "MOVE_OUT", "PUSH", "SLIDE_IN", "SLIDE_OUT"];
379
+ const SIMPLE_TRANSITIONS = ["DISSOLVE", "SMART_ANIMATE", "SCROLL_ANIMATE"];
380
+
381
+ function buildTransition(item) {
382
+ const type = (item.transition || "").toUpperCase();
383
+ if (!type || type === "NONE" || type === "INSTANT") return null;
384
+ const directional = DIRECTIONAL_TRANSITIONS.indexOf(type) !== -1;
385
+ if (!directional && SIMPLE_TRANSITIONS.indexOf(type) === -1) {
386
+ throw new Error(
387
+ "unsupported transition: " + type + " (use " +
388
+ SIMPLE_TRANSITIONS.concat(DIRECTIONAL_TRANSITIONS).join(", ") + ")",
389
+ );
390
+ }
391
+ const t = {
392
+ type,
393
+ easing: { type: (item.easing || "EASE_OUT").toUpperCase() },
394
+ duration: item.duration === undefined || item.duration === null ? 0.3 : item.duration,
395
+ };
396
+ if (directional) {
397
+ t.direction = (item.direction || "LEFT").toUpperCase();
398
+ t.matchLayers = false;
399
+ }
400
+ return t;
179
401
  }
180
402
 
403
+ async function buildReaction(item) {
404
+ const trigger = (item.trigger || "ON_CLICK").toUpperCase();
405
+ if (TRIGGERS.indexOf(trigger) === -1) {
406
+ throw new Error("unsupported trigger: " + trigger + " (use " + TRIGGERS.join(", ") + ")");
407
+ }
408
+ const navigation = (item.navigation || "NAVIGATE").toUpperCase();
409
+ if (NAVIGATIONS.indexOf(navigation) === -1) {
410
+ throw new Error("unsupported navigation: " + navigation + " (use " + NAVIGATIONS.join(", ") + ")");
411
+ }
412
+ const needsDestination = navigation !== "BACK" && navigation !== "CLOSE";
413
+ if (needsDestination && !item.destination_id) {
414
+ throw new Error("destination_id is required for " + navigation + "; only BACK and CLOSE take none");
415
+ }
416
+ // BACK and CLOSE are action types of their own, not navigations of a NODE
417
+ // action; sending them as a navigation fails validation.
418
+ if (!needsDestination) {
419
+ return { trigger: { type: trigger }, actions: [{ type: navigation }] };
420
+ }
421
+ // Resolve the destination here so a stale id fails by name, not as an
422
+ // opaque setReactionsAsync rejection.
423
+ await node(item.destination_id);
424
+ return {
425
+ trigger: { type: trigger },
426
+ actions: [{
427
+ type: "NODE",
428
+ destinationId: item.destination_id,
429
+ navigation,
430
+ transition: buildTransition(item),
431
+ preserveScrollPosition: false,
432
+ }],
433
+ };
434
+ }
435
+
436
+ // The page owning a node; flowStartingPoints lives on the page, which is not
437
+ // necessarily the open one.
438
+ function pageOf(n) {
439
+ while (n && n.type !== "PAGE") n = n.parent;
440
+ if (!n) throw new Error("node is not on a page");
441
+ return n;
442
+ }
443
+
444
+
445
+ // Right of everything already on the page, top-aligned with it.
446
+ function placeInFreeSpace(n, page) {
447
+ const others = page.children.filter((c) => c !== n && "width" in c);
448
+ if (!others.length) return;
449
+ n.x = Math.max.apply(null, others.map((c) => c.x + c.width)) + 100;
450
+ n.y = Math.min.apply(null, others.map((c) => c.y));
451
+ }
452
+
453
+ // ---------- design audit ----------
454
+
455
+ const EPS = 1; // sub-pixel noise from auto layout, rotation and vector bounds: never visible
456
+
457
+ function intersect(a, b) {
458
+ const x = Math.max(a.x, b.x), y = Math.max(a.y, b.y);
459
+ const r = Math.min(a.x + a.width, b.x + b.width), bt = Math.min(a.y + a.height, b.y + b.height);
460
+ return { x, y, width: Math.max(0, r - x), height: Math.max(0, bt - y) };
461
+ }
462
+
463
+ // How far box a sticks out of box b, per side; null when it does not.
464
+ function spill(a, b) {
465
+ const o = {
466
+ left: b.x - a.x, top: b.y - a.y,
467
+ right: a.x + a.width - (b.x + b.width), bottom: a.y + a.height - (b.y + b.height),
468
+ };
469
+ const out = {};
470
+ for (const k in o) if (o[k] > EPS) out[k] = Math.round(o[k] * 10) / 10;
471
+ return Object.keys(out).length ? out : null;
472
+ }
473
+
474
+ // Topmost visible paint: an {r,g,b} color when it is an opaque solid, "unknown"
475
+ // for images, gradients and translucent fills (no single color to measure
476
+ // against), null when the node paints nothing.
477
+ function topFill(n) {
478
+ if (!("fills" in n) || !Array.isArray(n.fills)) return null;
479
+ for (let i = n.fills.length - 1; i >= 0; i--) {
480
+ const p = n.fills[i];
481
+ if (p.visible === false) continue;
482
+ if (p.type !== "SOLID" || (p.opacity !== undefined && p.opacity < 1) || ("opacity" in n && n.opacity < 1)) return "unknown";
483
+ return p.color;
484
+ }
485
+ return null;
486
+ }
487
+
488
+ // What a text layer is drawn on: the nearest thing behind it that paints,
489
+ // either a sibling lower in the stack that covers it (the hand-drawn
490
+ // "rectangle as background") or an ancestor's own fill.
491
+ function backgroundOf(t) {
492
+ const box = t.absoluteBoundingBox;
493
+ for (let n = t; n.parent && n.parent.type !== "DOCUMENT"; n = n.parent) {
494
+ const sibs = n.parent.children || [];
495
+ for (let i = sibs.indexOf(n) - 1; i >= 0; i--) {
496
+ const s = sibs[i];
497
+ if (s.visible === false || !s.absoluteBoundingBox || spill(box, s.absoluteBoundingBox)) continue;
498
+ const f = topFill(s);
499
+ if (f) return f;
500
+ }
501
+ const f = n.parent.type === "PAGE" ? null : topFill(n.parent);
502
+ if (f) return f;
503
+ }
504
+ return "unknown";
505
+ }
506
+
507
+ // WCAG 2.x relative luminance and contrast ratio.
508
+ function luminance(c) {
509
+ const f = (v) => (v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4));
510
+ return 0.2126 * f(c.r) + 0.7152 * f(c.g) + 0.0722 * f(c.b);
511
+ }
512
+
513
+ function contrastRatio(a, b) {
514
+ const la = luminance(a), lb = luminance(b);
515
+ return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);
516
+ }
517
+
518
+ // WCAG exempts inactive controls from contrast: text inside an instance whose
519
+ // variant says Disabled (State=Disabled, Disabled=true, ...) is not measured.
520
+ function inDisabledControl(n) {
521
+ for (let p = n.parent; p && p.type !== "PAGE"; p = p.parent) {
522
+ if (p.type !== "INSTANCE") continue;
523
+ let v = null;
524
+ try {
525
+ v = p.variantProperties;
526
+ } catch (e) {}
527
+ for (const k in v || {}) {
528
+ if (/^(disabled?|inactive)$/i.test(v[k]) || (/disabled/i.test(k) && /^(true|yes|on)$/i.test(v[k]))) return true;
529
+ }
530
+ }
531
+ return false;
532
+ }
533
+
534
+ // Layers a finger is expected to hit: anything wired in the prototype, or
535
+ // named like a control.
536
+ const CONTROL_NAME = /\b(button|btn|link|tab|chip|checkbox|radio|switch|toggle|icon[-_ ]?button)\b/i;
537
+
538
+ function isControl(n) {
539
+ if ("reactions" in n && n.reactions && n.reactions.length) return true;
540
+ return (n.type === "INSTANCE" || n.type === "FRAME" || n.type === "COMPONENT") && CONTROL_NAME.test(n.name);
541
+ }
542
+
543
+ // "$2" in a batch op's params stands for the id of the node op 2 produced,
544
+ // so a frame and its children can be created in one call.
545
+ function resolveBatchRefs(v, results) {
546
+ if (Array.isArray(v)) return v.map((x) => resolveBatchRefs(x, results));
547
+ if (v && typeof v === "object") {
548
+ const out = {};
549
+ for (const k in v) out[k] = resolveBatchRefs(v[k], results);
550
+ return out;
551
+ }
552
+ const m = typeof v === "string" ? /^\$(\d+)$/.exec(v) : null;
553
+ if (!m) return v;
554
+ const r = results[+m[1]];
555
+ if (!r) throw new Error(v + " refers to an op that has not run yet; refs only point backwards");
556
+ const res = r.result || {};
557
+ const id = res.id || (res.ids && res.ids[0]) || (res.nodes && res.nodes[0] && res.nodes[0].id);
558
+ if (!id) throw new Error(v + " has no node id: op " + m[1] + (r.error ? " failed" : " did not return a node"));
559
+ return id;
560
+ }
561
+
562
+ // These carry megabytes of base64 or need the server's filesystem/network, so
563
+ // they only work as their own tool call.
564
+ const NOT_BATCHABLE = ["batch", "download_assets", "import_image", "get_screenshot"];
565
+
181
566
  // ---------- command handlers (names match MCP tool names) ----------
182
567
 
183
568
  const handlers = {
@@ -189,6 +574,23 @@ const handlers = {
189
574
  };
190
575
  },
191
576
 
577
+ async list_pages() {
578
+ return {
579
+ currentPage: figma.currentPage.name,
580
+ pages: figma.root.children.map((p) => ({
581
+ id: p.id,
582
+ name: p.name,
583
+ current: p.id === figma.currentPage.id,
584
+ })),
585
+ };
586
+ },
587
+
588
+ async set_current_page(params) {
589
+ const p = await resolvePage(params.page);
590
+ await figma.setCurrentPageAsync(p);
591
+ return { id: p.id, name: p.name, childCount: p.children.length };
592
+ },
593
+
192
594
  async get_selection() {
193
595
  return figma.currentPage.selection.map((n) => {
194
596
  const s = summarize(n);
@@ -200,16 +602,219 @@ const handlers = {
200
602
 
201
603
  async get_design_context(params) {
202
604
  const depth = params.depth === undefined ? 2 : params.depth;
203
- return serialize(await node(params.node_id), depth);
605
+ return resolveRefs(serialize(await node(params.node_id), depth, !!params.compact, !!params.visible_only));
606
+ },
607
+
608
+ // Every component used under node_id, grouped by component (set), with all
609
+ // the states its set defines and the state each instance is in, so testers
610
+ // can write a case per state. Library components resolve too when Figma
611
+ // has their set loaded.
612
+ async get_component_states(params) {
613
+ const root = await node(params.node_id);
614
+ const instances = "findAllWithCriteria" in root ? root.findAllWithCriteria({ types: ["INSTANCE"] }) : [];
615
+ if (root.type === "INSTANCE") instances.unshift(root);
616
+ const groups = new Map();
617
+ for (const inst of instances) {
618
+ if (!inst.visible) continue;
619
+ const main = await inst.getMainComponentAsync();
620
+ if (!main) continue;
621
+ const set = main.parent && main.parent.type === "COMPONENT_SET" ? main.parent : null;
622
+ const owner = set || main;
623
+ let g = groups.get(owner.id);
624
+ if (!g) {
625
+ g = { component: owner.name, id: owner.id, library: !!main.remote, count: 0, used: [] };
626
+ if (set) {
627
+ const opts = variantOptions(set);
628
+ if (opts) g.states = opts;
629
+ else g.statesError = "variant list not readable";
630
+ }
631
+ groups.set(owner.id, g);
632
+ }
633
+ g.count++;
634
+ let state = null;
635
+ try {
636
+ state = inst.variantProperties;
637
+ } catch (e) {}
638
+ if (state) {
639
+ g.usedStates = g.usedStates || {};
640
+ for (const [k, v] of Object.entries(state)) {
641
+ const vals = (g.usedStates[k] = g.usedStates[k] || []);
642
+ if (!vals.includes(v)) vals.push(v);
643
+ }
644
+ }
645
+ if (g.used.length < 10) {
646
+ const u = { id: inst.id, name: inst.name };
647
+ if (state) u.state = state;
648
+ g.used.push(u);
649
+ }
650
+ // Hand edits on top of the component (a "Disabled" button recolored by
651
+ // hand) are what testers miss; list which layer and which fields.
652
+ let ovs = [];
653
+ try {
654
+ ovs = inst.overrides || [];
655
+ } catch (e) {}
656
+ if (ovs.length) {
657
+ g.overridden = (g.overridden || 0) + 1;
658
+ g.overrides = g.overrides || [];
659
+ if (g.overrides.length < 10) {
660
+ const layers = [];
661
+ for (const o of ovs) {
662
+ const n = o.id === inst.id ? inst : await figma.getNodeByIdAsync(o.id);
663
+ layers.push({ layer: n ? n.name : o.id, fields: o.overriddenFields });
664
+ }
665
+ g.overrides.push({ id: inst.id, name: inst.name, layers });
666
+ }
667
+ }
668
+ }
669
+ return [...groups.values()].sort((a, b) => b.count - a.count);
204
670
  },
205
671
 
206
672
  async create_frame(params) {
207
673
  const f = figma.createFrame();
674
+ const parent = await parentOf(params);
675
+ const topLevel = parent.type === "PAGE" || parent.type === "SECTION";
676
+ // A frame inside another is almost always a layout wrapper, and Figma's
677
+ // white default turns every wrapper into a white slab over the design.
678
+ // Top-level frames are screens and keep it.
679
+ if (params.fill_color === "none" || (!params.fill_color && !topLevel)) f.fills = [];
208
680
  applyShapeParams(f, params);
209
- (await parentOf(params)).appendChild(f);
681
+ parent.appendChild(f);
682
+ // A screen created without a position goes beside the existing work
683
+ // instead of on top of it at 0,0.
684
+ if (parent.type === "PAGE" && params.x == null && params.y == null) placeInFreeSpace(f, parent);
210
685
  return summarize(f);
211
686
  },
212
687
 
688
+ // Findings only: what a screenshot shows but a model reading it tends to
689
+ // miss. Reads the rendered geometry, never changes the document.
690
+ async audit_design(params) {
691
+ const root = await node(params.node_id);
692
+ if (!root.absoluteBoundingBox) throw new Error("node " + root.id + " is " + root.type + " and has no box to audit; pass a frame, section or component");
693
+ const want = params.checks && params.checks.length ? params.checks : ["layout", "contrast"];
694
+ for (const c of want) {
695
+ if (["layout", "contrast"].indexOf(c) === -1) throw new Error("unknown check: " + c + " (use layout, contrast)");
696
+ }
697
+ const layout = want.indexOf("layout") !== -1, contrast = want.indexOf("contrast") !== -1;
698
+ const minTouch = params.min_touch > 0 ? params.min_touch : 0;
699
+ const max = params.max_results || 100;
700
+ const issues = [], summary = {};
701
+ let checked = 0, contrastUnknown = 0, disabledSkipped = 0;
702
+ const report = (n, issue, detail) => {
703
+ summary[issue] = (summary[issue] || 0) + 1;
704
+ if (issues.length < max) issues.push(Object.assign({ id: n.id, name: n.name, issue }, detail));
705
+ };
706
+ let insideInstances = 0;
707
+ // clip: the visible window left by every clipping ancestor, or null.
708
+ // inInstance: geometry inside an instance belongs to its component and
709
+ // cannot be fixed on this screen (an icon's vector parts poking out of its
710
+ // own frame), so only contrast and touch size are checked there.
711
+ const walk = (n, clip, parentCut, inInstance) => {
712
+ if (n.visible === false) return;
713
+ const box = n.absoluteBoundingBox;
714
+ if (!box) return;
715
+ checked++;
716
+ let cut = parentCut;
717
+ if (inInstance) insideInstances++;
718
+ if (layout && n !== root && !inInstance) {
719
+ const seen = clip ? intersect(box, clip) : box;
720
+ if (clip && !parentCut && (seen.width <= EPS || seen.height <= EPS)) {
721
+ // Nothing of it shows, so nothing inside it is worth reporting.
722
+ report(n, "hidden_by_clip", { clippedBy: clip.id });
723
+ return;
724
+ }
725
+ const over = clip && !parentCut ? spill(box, clip) : null;
726
+ if (over) {
727
+ report(n, "clipped", { clippedBy: clip.id, cutOff: over });
728
+ cut = true;
729
+ } else if (n.parent && n.parent.absoluteBoundingBox && n.parent.type !== "GROUP" && !parentCut) {
730
+ const out = spill(box, n.parent.absoluteBoundingBox);
731
+ if (out) report(n, "overflows_parent", { parent: n.parent.id, by: out });
732
+ }
733
+ }
734
+ if (n.type === "TEXT") {
735
+ if (layout && !inInstance) {
736
+ // A fixed-size text box does not grow with its content: the glyphs
737
+ // either spill out of it or are cut with an ellipsis.
738
+ const rb = n.absoluteRenderBounds;
739
+ const fixed = n.textAutoResize === "NONE" || n.textAutoResize === "TRUNCATE";
740
+ const out = fixed && rb ? spill(rb, box) : null;
741
+ if (out && (out.right || out.bottom)) report(n, "text_overflows_box", { by: out });
742
+ const size = typeof n.fontSize === "number" ? n.fontSize : 14;
743
+ const lines = n.maxLines > 0 ? n.maxLines : Math.max(1, Math.floor(box.height / (size * 1.2)));
744
+ // shortcut: half the font size per character is a lower bound on
745
+ // width, so this only catches clear cases; measuring needs a clone,
746
+ // and an audit must not touch the document.
747
+ if ((n.textTruncation === "ENDING" || n.textAutoResize === "TRUNCATE") &&
748
+ (n.characters || "").length * size * 0.5 > box.width * lines) {
749
+ report(n, "text_truncated", { text: n.characters.slice(0, 60) });
750
+ }
751
+ }
752
+ if (contrast && (n.characters || "").trim()) {
753
+ const fg = topFill(n), bg = fg && fg !== "unknown" ? backgroundOf(n) : "unknown";
754
+ if (!fg || inDisabledControl(n)) {
755
+ // paints nothing, or a disabled control's label: exempt
756
+ if (fg) disabledSkipped++;
757
+ } else if (fg === "unknown" || bg === "unknown") {
758
+ contrastUnknown++;
759
+ } else {
760
+ const size = typeof n.fontSize === "number" ? n.fontSize : 0;
761
+ const bold = n.fontName && n.fontName !== figma.mixed && /bold|black|heavy/i.test(n.fontName.style || "");
762
+ // WCAG AA: 3:1 for large text (24px, or 18.66px bold), else 4.5:1.
763
+ const need = size >= 24 || (bold && size >= 18.66) ? 3 : 4.5;
764
+ const ratio = contrastRatio(fg, bg);
765
+ if (ratio < need) {
766
+ report(n, "low_contrast", { ratio: Math.round(ratio * 100) / 100, required: need, text: rgbToHex(fg), background: rgbToHex(bg) });
767
+ }
768
+ }
769
+ }
770
+ }
771
+ if (minTouch && isControl(n) && (box.width < minTouch - EPS || box.height < minTouch - EPS)) {
772
+ report(n, "small_touch_target", { width: Math.round(box.width), height: Math.round(box.height), required: minTouch });
773
+ }
774
+ if (!("children" in n) || n.type === "BOOLEAN_OPERATION") return;
775
+ let inner = clip;
776
+ if (n.clipsContent) {
777
+ inner = clip ? intersect(box, clip) : { x: box.x, y: box.y, width: box.width, height: box.height };
778
+ inner.id = n.id;
779
+ }
780
+ for (const c of n.children) walk(c, inner, cut, inInstance || n.type === "INSTANCE");
781
+ };
782
+ walk(root, null, false, root.type === "INSTANCE");
783
+ const total = Object.keys(summary).reduce((a, k) => a + summary[k], 0);
784
+ const out = { scope: root.name, checks: want.concat(minTouch ? ["touch"] : []), nodesChecked: checked, total, summary, issues };
785
+ if (total > issues.length) out.truncated = true;
786
+ if (layout && insideInstances) out.layoutNotChecked = insideInstances + " layers inside instances; audit their main component to check those";
787
+ if (disabledSkipped) out.contrastSkippedDisabled = disabledSkipped + " text layers in disabled controls (WCAG exempts them)";
788
+ if (contrastUnknown) out.contrastNotMeasured = contrastUnknown + " text layers sit on an image, gradient or translucent fill; check those by screenshot";
789
+ return out;
790
+ },
791
+
792
+ // Several commands in one round-trip. A failed op is reported in place and
793
+ // the rest still run: what already landed in the document stays there.
794
+ async batch(params) {
795
+ const ops = params.ops || [];
796
+ if (!ops.length) throw new Error("ops is required");
797
+ const results = [];
798
+ let failed = 0;
799
+ for (let i = 0; i < ops.length; i++) {
800
+ const op = ops[i] || {};
801
+ try {
802
+ if (NOT_BATCHABLE.indexOf(op.command) !== -1) throw new Error(op.command + " cannot run inside batch; call it as its own tool");
803
+ const h = handlers[op.command];
804
+ if (!h) throw new Error("unknown command: " + op.command + " (batch runs the same commands as the other tools, by tool name)");
805
+ const r = await h(resolveBatchRefs(op.params || {}, results));
806
+ results.push({ result: r === undefined ? null : r });
807
+ } catch (e) {
808
+ failed++;
809
+ results.push({ error: String((e && e.message) || e) });
810
+ if (params.stop_on_error) break;
811
+ }
812
+ }
813
+ const out = { ok: failed === 0, ran: results.length, failed, results };
814
+ if (results.length < ops.length) out.skipped = ops.length - results.length;
815
+ return out;
816
+ },
817
+
213
818
  async create_rectangle(params) {
214
819
  const r = figma.createRectangle();
215
820
  applyShapeParams(r, params);
@@ -283,32 +888,39 @@ const handlers = {
283
888
  },
284
889
 
285
890
  async set_characters(params) {
286
- const t = await node(params.node_id);
287
- if (t.type !== "TEXT") throw new Error("node " + params.node_id + " is " + t.type + ", not TEXT");
288
- if (t.characters.length > 0) {
289
- const fonts = t.getRangeAllFontNames(0, t.characters.length);
290
- await Promise.all(fonts.map(figma.loadFontAsync));
291
- } else {
292
- await figma.loadFontAsync(t.fontName);
891
+ const nodes = await targets(params);
892
+ for (const t of nodes) {
893
+ if (t.type !== "TEXT") throw new Error("node " + t.id + " is " + t.type + ", not TEXT");
894
+ if (t.characters.length > 0) {
895
+ const fonts = t.getRangeAllFontNames(0, t.characters.length);
896
+ await Promise.all(fonts.map(figma.loadFontAsync));
897
+ } else {
898
+ await figma.loadFontAsync(t.fontName);
899
+ }
900
+ t.characters = params.text;
293
901
  }
294
- t.characters = params.text;
295
- return summarize(t);
902
+ return done(params, nodes);
296
903
  },
297
904
 
298
905
  async set_fills(params) {
299
- const n = await node(params.node_id);
300
- if (!("fills" in n)) throw new Error("node " + params.node_id + " has no fills");
301
- let paint;
302
- if (params.gradient) {
303
- paint = buildGradient(params.gradient);
304
- } else if (params.color) {
305
- paint = { type: "SOLID", color: hexToRGB(params.color) };
306
- } else {
307
- throw new Error("set_fills needs color or gradient");
906
+ const nodes = await targets(params);
907
+ const clear = params.color === "none" || params.color === null;
908
+ let paint = null;
909
+ if (!clear) {
910
+ if (params.gradient) {
911
+ paint = buildGradient(params.gradient);
912
+ } else if (params.color) {
913
+ paint = { type: "SOLID", color: hexToRGB(params.color) };
914
+ } else {
915
+ throw new Error('set_fills needs color, gradient, or color: "none" to clear');
916
+ }
917
+ if (params.opacity !== undefined && params.opacity !== null) paint.opacity = params.opacity;
308
918
  }
309
- if (params.opacity !== undefined && params.opacity !== null) paint.opacity = params.opacity;
310
- n.fills = [paint];
311
- return summarize(n);
919
+ for (const n of nodes) {
920
+ if (!("fills" in n)) throw new Error("node " + n.id + " has no fills");
921
+ n.fills = clear ? [] : [paint];
922
+ }
923
+ return done(params, nodes);
312
924
  },
313
925
 
314
926
  async move_nodes(params) {
@@ -318,9 +930,9 @@ const handlers = {
318
930
  if (!("x" in n)) throw new Error("node " + item.node_id + " cannot be moved");
319
931
  n.x = item.x;
320
932
  n.y = item.y;
321
- out.push(summarize(n));
933
+ out.push(n);
322
934
  }
323
- return out;
935
+ return done(params, out);
324
936
  },
325
937
 
326
938
  async resize_nodes(params) {
@@ -329,16 +941,16 @@ const handlers = {
329
941
  const n = await node(item.node_id);
330
942
  if (!("resize" in n)) throw new Error("node " + item.node_id + " cannot be resized");
331
943
  n.resize(item.width, item.height);
332
- out.push(summarize(n));
944
+ out.push(n);
333
945
  }
334
- return out;
946
+ return done(params, out);
335
947
  },
336
948
 
337
949
  async remove_nodes(params) {
338
950
  const deleted = [];
339
951
  for (const id of params.node_ids) {
340
952
  const n = await node(id);
341
- deleted.push(summarize(n));
953
+ deleted.push({ id: n.id, name: n.name, type: n.type });
342
954
  n.remove();
343
955
  }
344
956
  return { deleted };
@@ -348,7 +960,7 @@ const handlers = {
348
960
  const n = await node(params.node_id);
349
961
  if (!("layoutMode" in n)) throw new Error("node " + params.node_id + " does not support auto-layout");
350
962
  n.layoutMode = params.layout_mode;
351
- if (params.layout_mode === "NONE") return summarize(n);
963
+ if (params.layout_mode === "NONE") return done(params, n);
352
964
  if (params.item_spacing !== undefined) n.itemSpacing = params.item_spacing;
353
965
  if (params.padding !== undefined) {
354
966
  n.paddingTop = n.paddingRight = n.paddingBottom = n.paddingLeft = params.padding;
@@ -361,46 +973,97 @@ const handlers = {
361
973
  if (params.counter_axis_align) n.counterAxisAlignItems = params.counter_axis_align;
362
974
  if (params.primary_axis_sizing) n.primaryAxisSizingMode = params.primary_axis_sizing;
363
975
  if (params.counter_axis_sizing) n.counterAxisSizingMode = params.counter_axis_sizing;
364
- return summarize(n);
976
+ return done(params, n);
365
977
  },
366
978
 
367
979
  async set_corner_radius(params) {
368
- const n = await node(params.node_id);
369
- if (params.radius !== undefined) {
370
- if (!("cornerRadius" in n)) throw new Error("node " + params.node_id + " has no corner radius");
371
- n.cornerRadius = params.radius;
372
- }
373
- if (!("topLeftRadius" in n)) {
374
- if (params.radius === undefined) throw new Error("node " + params.node_id + " has no per-corner radius");
375
- return summarize(n);
376
- }
377
- if (params.top_left !== undefined) n.topLeftRadius = params.top_left;
378
- if (params.top_right !== undefined) n.topRightRadius = params.top_right;
379
- if (params.bottom_right !== undefined) n.bottomRightRadius = params.bottom_right;
380
- if (params.bottom_left !== undefined) n.bottomLeftRadius = params.bottom_left;
381
- return summarize(n);
980
+ const nodes = await targets(params);
981
+ for (const n of nodes) {
982
+ if (params.radius !== undefined) {
983
+ if (!("cornerRadius" in n)) throw new Error("node " + n.id + " has no corner radius");
984
+ n.cornerRadius = params.radius;
985
+ }
986
+ if (!("topLeftRadius" in n)) {
987
+ if (params.radius === undefined) throw new Error("node " + n.id + " has no per-corner radius");
988
+ continue;
989
+ }
990
+ if (params.top_left !== undefined) n.topLeftRadius = params.top_left;
991
+ if (params.top_right !== undefined) n.topRightRadius = params.top_right;
992
+ if (params.bottom_right !== undefined) n.bottomRightRadius = params.bottom_right;
993
+ if (params.bottom_left !== undefined) n.bottomLeftRadius = params.bottom_left;
994
+ }
995
+ return done(params, nodes);
382
996
  },
383
997
 
384
998
  async set_strokes(params) {
385
- const n = await node(params.node_id);
386
- if (!("strokes" in n)) throw new Error("node " + params.node_id + " has no strokes");
387
- if (params.color) {
388
- const paint = { type: "SOLID", color: hexToRGB(params.color) };
389
- if (params.opacity !== undefined && params.opacity !== null) paint.opacity = params.opacity;
390
- n.strokes = [paint];
391
- } else {
392
- n.strokes = [];
999
+ const nodes = await targets(params);
1000
+ for (const n of nodes) {
1001
+ if (!("strokes" in n)) throw new Error("node " + n.id + " has no strokes");
1002
+ if (params.color && params.color !== "none") {
1003
+ const paint = { type: "SOLID", color: hexToRGB(params.color) };
1004
+ if (params.opacity !== undefined && params.opacity !== null) paint.opacity = params.opacity;
1005
+ n.strokes = [paint];
1006
+ } else {
1007
+ n.strokes = [];
1008
+ }
1009
+ if (params.weight !== undefined && "strokeWeight" in n) n.strokeWeight = params.weight;
1010
+ if (params.align && "strokeAlign" in n) n.strokeAlign = params.align;
393
1011
  }
394
- if (params.weight !== undefined && "strokeWeight" in n) n.strokeWeight = params.weight;
395
- if (params.align && "strokeAlign" in n) n.strokeAlign = params.align;
396
- return summarize(n);
1012
+ return done(params, nodes);
397
1013
  },
398
1014
 
399
1015
  async set_effects(params) {
400
- const n = await node(params.node_id);
401
- if (!("effects" in n)) throw new Error("node " + params.node_id + " has no effects");
402
- n.effects = buildEffects(params.effects);
403
- return summarize(n);
1016
+ const nodes = await targets(params);
1017
+ const effects = buildEffects(params.effects);
1018
+ for (const n of nodes) {
1019
+ if (!("effects" in n)) throw new Error("node " + n.id + " has no effects");
1020
+ n.effects = effects;
1021
+ }
1022
+ return done(params, nodes);
1023
+ },
1024
+
1025
+ async rename_nodes(params) {
1026
+ const renamed = [];
1027
+ for (const item of params.items) {
1028
+ const n = await node(item.node_id);
1029
+ n.name = item.name;
1030
+ renamed.push(n);
1031
+ }
1032
+ return done(params, renamed);
1033
+ },
1034
+
1035
+ // Restyle text in place. create_text sets the font once; variants (Bold vs
1036
+ // Regular of the same label) need this.
1037
+ async set_text_properties(params) {
1038
+ const nodes = await targets(params);
1039
+ for (const n of nodes) {
1040
+ if (n.type !== "TEXT") throw new Error("node " + n.id + " is " + n.type + ", not TEXT");
1041
+ // Every font already in the node must be loaded before any edit, and
1042
+ // the new one before it can be applied.
1043
+ const current = n.characters.length
1044
+ ? n.getRangeAllFontNames(0, n.characters.length)
1045
+ : [n.fontName];
1046
+ await Promise.all(current.filter((f) => f !== figma.mixed).map(figma.loadFontAsync));
1047
+ if (params.font_family || params.font_style) {
1048
+ const base = current[0] === figma.mixed ? { family: "Inter", style: "Regular" } : current[0];
1049
+ const font = {
1050
+ family: params.font_family || base.family,
1051
+ style: params.font_style || base.style,
1052
+ };
1053
+ await figma.loadFontAsync(font);
1054
+ n.fontName = font;
1055
+ }
1056
+ if (params.font_size) n.fontSize = params.font_size;
1057
+ if (params.line_height !== undefined && params.line_height !== null) {
1058
+ n.lineHeight = { value: params.line_height, unit: "PIXELS" };
1059
+ }
1060
+ if (params.letter_spacing !== undefined && params.letter_spacing !== null) {
1061
+ n.letterSpacing = { value: params.letter_spacing, unit: "PIXELS" };
1062
+ }
1063
+ if (params.text_align) n.textAlignHorizontal = params.text_align;
1064
+ if (params.fill_color) n.fills = [{ type: "SOLID", color: hexToRGB(params.fill_color) }];
1065
+ }
1066
+ return done(params, nodes);
404
1067
  },
405
1068
 
406
1069
  async download_assets(params) {
@@ -419,6 +1082,7 @@ const handlers = {
419
1082
  let scale = item.scale || 1;
420
1083
  scale = Math.max(0.5, Math.min(scale, 4));
421
1084
  settings = { format, constraint: { type: "SCALE", value: scale } };
1085
+ if (item.exact) settings.useAbsoluteBounds = true;
422
1086
  } else {
423
1087
  throw new Error("unsupported format: " + format + " (use PNG, JPG or SVG)");
424
1088
  }
@@ -445,22 +1109,57 @@ const handlers = {
445
1109
  },
446
1110
 
447
1111
  async find_nodes(params) {
448
- const scope = params.node_id ? await node(params.node_id) : figma.currentPage;
1112
+ let scope;
1113
+ if (params.node_id) scope = await node(params.node_id);
1114
+ else if (params.page) scope = await resolvePage(params.page);
1115
+ else scope = figma.currentPage;
449
1116
  if (!("findAll" in scope)) throw new Error("node " + scope.id + " has no children to search");
450
1117
  const name = params.name ? params.name.toLowerCase() : null;
451
1118
  const text = params.text ? params.text.toLowerCase() : null;
452
1119
  const types = params.types && params.types.length ? params.types : null;
1120
+ // Style filters let callers target "every white card" directly instead of
1121
+ // guessing a node's role from its size.
1122
+ const fill = params.fill ? ("#" + params.fill.replace(/^#/, "")).toLowerCase() : null;
1123
+ const fontSize = params.font_size;
1124
+ const fontStyle = params.font_style ? params.font_style.toLowerCase() : null;
453
1125
  const matches = scope.findAll((n) => {
454
1126
  if (types && types.indexOf(n.type) === -1) return false;
455
1127
  if (name && n.name.toLowerCase().indexOf(name) === -1) return false;
456
1128
  if (text && (n.type !== "TEXT" || n.characters.toLowerCase().indexOf(text) === -1)) return false;
1129
+ if (fill) {
1130
+ const hex = solidFillHex(n);
1131
+ if (!hex || hex.toLowerCase() !== fill) return false;
1132
+ }
1133
+ if (fontSize !== undefined && fontSize !== null) {
1134
+ if (n.type !== "TEXT" || val(n.fontSize) !== fontSize) return false;
1135
+ }
1136
+ if (fontStyle) {
1137
+ if (n.type !== "TEXT") return false;
1138
+ const f = val(n.fontName);
1139
+ if (f === "mixed" || f.style.toLowerCase() !== fontStyle) return false;
1140
+ }
457
1141
  return true;
458
1142
  });
459
1143
  const max = params.max_results || 50;
1144
+ const fields = params.fields && params.fields.length ? params.fields : null;
1145
+ // Name the scope: with no node_id or page this searches whatever page the
1146
+ // user happens to have open, which silently changes under a long session.
1147
+ const page = (function (n) {
1148
+ while (n && n.type !== "PAGE") n = n.parent;
1149
+ return n ? n.name : undefined;
1150
+ })(scope);
460
1151
  return {
1152
+ scope: scope.type === "PAGE" ? "page " + scope.name : scope.name + " (page " + page + ")",
461
1153
  total: matches.length,
462
1154
  truncated: matches.length > max,
463
- nodes: matches.slice(0, max).map(summarize),
1155
+ nodes: matches.slice(0, max).map((n) => {
1156
+ const s = summarize(n);
1157
+ for (const f of fields || []) {
1158
+ const v = FIELD_GETTERS[f] ? FIELD_GETTERS[f](n) : undefined;
1159
+ if (v !== undefined) s[f] = v;
1160
+ }
1161
+ return s;
1162
+ }),
464
1163
  };
465
1164
  },
466
1165
 
@@ -486,18 +1185,27 @@ const handlers = {
486
1185
  async append_children(params) {
487
1186
  const parent = await node(params.parent_id);
488
1187
  if (!("appendChild" in parent)) throw new Error("node " + params.parent_id + " cannot have children");
489
- const out = [];
1188
+ const moved = [];
1189
+ const warnings = [];
490
1190
  let index = params.index;
491
1191
  for (const id of params.node_ids) {
492
1192
  const n = await node(id);
1193
+ // Figma silently pulls a variant out of its set and renames it
1194
+ // "<Set>/<Variant>" — easy to miss until the variants stop working.
1195
+ if (n.type === "COMPONENT" && n.parent && n.parent.type === "COMPONENT_SET") {
1196
+ warnings.push(
1197
+ "node " + n.id + " (" + n.name + ") left component set " + n.parent.name +
1198
+ "; Figma renames detached variants to <Set>/<Variant>",
1199
+ );
1200
+ }
493
1201
  if (index === undefined || index === null) {
494
1202
  parent.appendChild(n);
495
1203
  } else {
496
1204
  parent.insertChild(index++, n);
497
1205
  }
498
- out.push(summarize(n));
1206
+ moved.push(n);
499
1207
  }
500
- return out;
1208
+ return done(params, moved, warnings.length ? { warnings } : null);
501
1209
  },
502
1210
 
503
1211
  async clone_node(params) {
@@ -567,6 +1275,57 @@ const handlers = {
567
1275
  return summarize(inst);
568
1276
  },
569
1277
 
1278
+ async combine_as_variants(params) {
1279
+ if (!params.node_ids || !params.node_ids.length) throw new Error("node_ids is required");
1280
+ const nodes = await Promise.all(params.node_ids.map((id) => node(id)));
1281
+ for (const n of nodes) {
1282
+ if (n.type !== "COMPONENT") throw new Error("node " + n.id + " is " + n.type + ", not a COMPONENT");
1283
+ }
1284
+ const parent = params.parent_id ? await node(params.parent_id) : nodes[0].parent;
1285
+ const set = figma.combineAsVariants(nodes, parent);
1286
+ if (params.name) set.name = params.name;
1287
+ arrangeVariants(set);
1288
+ return summarize(set);
1289
+ },
1290
+
1291
+ // Component properties live on the component (or set); binding the property
1292
+ // to a child layer is what makes it editable from the instance panel, so do
1293
+ // both in one call.
1294
+ async add_component_property(params) {
1295
+ const c = await node(params.component_id);
1296
+ if (c.type !== "COMPONENT" && c.type !== "COMPONENT_SET") {
1297
+ throw new Error("node " + c.id + " is " + c.type + ", not a COMPONENT or COMPONENT_SET");
1298
+ }
1299
+ const type = (params.type || "TEXT").toUpperCase();
1300
+ // Figma requires a default of the matching kind; pick the empty one
1301
+ // rather than failing a call that only omitted it.
1302
+ let def = params.default_value;
1303
+ if (def === undefined || def === null) def = type === "BOOLEAN" ? false : "";
1304
+ const t = params.bind_node_id ? await node(params.bind_node_id) : null;
1305
+ const key = c.addComponentProperty(params.name, type, def);
1306
+ if (t) {
1307
+ const field = type === "TEXT" ? "characters" : type === "BOOLEAN" ? "visible" : "mainComponent";
1308
+ const refs = {};
1309
+ for (const k in t.componentPropertyReferences || {}) refs[k] = t.componentPropertyReferences[k];
1310
+ refs[field] = key;
1311
+ t.componentPropertyReferences = refs;
1312
+ }
1313
+ return { key, name: params.name, type, boundTo: params.bind_node_id || null };
1314
+ },
1315
+
1316
+ async set_instance_properties(params) {
1317
+ const inst = await node(params.instance_id);
1318
+ if (inst.type !== "INSTANCE") throw new Error("node " + params.instance_id + " is " + inst.type + ", not an INSTANCE");
1319
+ const known = Object.keys(inst.componentProperties || {});
1320
+ for (const k in params.properties) {
1321
+ if (known.indexOf(k) === -1) {
1322
+ throw new Error("unknown property " + k + "; this instance accepts: " + (known.join(", ") || "(none)"));
1323
+ }
1324
+ }
1325
+ inst.setProperties(params.properties);
1326
+ return { id: inst.id, properties: inst.componentProperties };
1327
+ },
1328
+
570
1329
  async swap_component(params) {
571
1330
  const inst = await node(params.instance_id);
572
1331
  if (inst.type !== "INSTANCE") throw new Error("node " + params.instance_id + " is " + inst.type + ", not an INSTANCE");
@@ -627,27 +1386,29 @@ const handlers = {
627
1386
  },
628
1387
 
629
1388
  async apply_style(params) {
630
- const n = await node(params.node_id);
1389
+ const nodes = await targets(params);
631
1390
  const style = await figma.getStyleByIdAsync(params.style_id);
632
1391
  if (!style) throw new Error("style not found: " + params.style_id);
633
- if (style.type === "PAINT") {
634
- if (params.target === "stroke") {
635
- await n.setStrokeStyleIdAsync(style.id);
1392
+ if (style.type === "TEXT") await figma.loadFontAsync(style.fontName);
1393
+ for (const n of nodes) {
1394
+ if (style.type === "PAINT") {
1395
+ if (params.target === "stroke") {
1396
+ await n.setStrokeStyleIdAsync(style.id);
1397
+ } else {
1398
+ await n.setFillStyleIdAsync(style.id);
1399
+ }
1400
+ } else if (style.type === "TEXT") {
1401
+ if (n.type !== "TEXT") throw new Error("node " + n.id + " is " + n.type + ", not TEXT");
1402
+ await n.setTextStyleIdAsync(style.id);
1403
+ } else if (style.type === "EFFECT") {
1404
+ await n.setEffectStyleIdAsync(style.id);
1405
+ } else if (style.type === "GRID") {
1406
+ await n.setGridStyleIdAsync(style.id);
636
1407
  } else {
637
- await n.setFillStyleIdAsync(style.id);
638
- }
639
- } else if (style.type === "TEXT") {
640
- if (n.type !== "TEXT") throw new Error("node " + params.node_id + " is " + n.type + ", not TEXT");
641
- await figma.loadFontAsync(style.fontName);
642
- await n.setTextStyleIdAsync(style.id);
643
- } else if (style.type === "EFFECT") {
644
- await n.setEffectStyleIdAsync(style.id);
645
- } else if (style.type === "GRID") {
646
- await n.setGridStyleIdAsync(style.id);
647
- } else {
648
- throw new Error("unsupported style type: " + style.type);
1408
+ throw new Error("unsupported style type: " + style.type);
1409
+ }
649
1410
  }
650
- return summarize(n);
1411
+ return done(params, nodes);
651
1412
  },
652
1413
 
653
1414
  // ---------- variables (design tokens) ----------
@@ -712,18 +1473,107 @@ const handlers = {
712
1473
  },
713
1474
 
714
1475
  async set_bound_variable(params) {
715
- const n = await node(params.node_id);
1476
+ const nodes = await targets(params);
716
1477
  const v = await figma.variables.getVariableByIdAsync(params.variable_id);
717
1478
  if (!v) throw new Error("variable not found: " + params.variable_id);
718
1479
  const field = params.field;
719
- if (field === "fills" || field === "strokes") {
720
- if (!(field in n)) throw new Error("node " + params.node_id + " has no " + field);
721
- const paints = n[field].length ? n[field] : [{ type: "SOLID", color: { r: 0, g: 0, b: 0 } }];
722
- n[field] = [figma.variables.setBoundVariableForPaint(paints[0], "color", v)].concat(paints.slice(1));
723
- } else {
724
- n.setBoundVariable(field, v);
1480
+ for (const n of nodes) {
1481
+ if (field === "fills" || field === "strokes") {
1482
+ if (!(field in n)) throw new Error("node " + n.id + " has no " + field);
1483
+ const paints = n[field].length ? n[field] : [{ type: "SOLID", color: { r: 0, g: 0, b: 0 } }];
1484
+ n[field] = [figma.variables.setBoundVariableForPaint(paints[0], "color", v)].concat(paints.slice(1));
1485
+ } else {
1486
+ n.setBoundVariable(field, v);
1487
+ }
725
1488
  }
726
- return summarize(n);
1489
+ return done(params, nodes);
1490
+ },
1491
+
1492
+ // ---------- prototyping ----------
1493
+
1494
+ // setReactionsAsync replaces a node's reactions wholesale, so items for the
1495
+ // same node are grouped and written once instead of overwriting each other.
1496
+ async set_prototype_links(params) {
1497
+ const items = params.items || [];
1498
+ if (!items.length) throw new Error("items is required");
1499
+ const order = [];
1500
+ const groups = {};
1501
+ for (const item of items) {
1502
+ if (!item.node_id) throw new Error("node_id is required for every item");
1503
+ if (!groups[item.node_id]) {
1504
+ groups[item.node_id] = [];
1505
+ order.push(item.node_id);
1506
+ }
1507
+ groups[item.node_id].push(await buildReaction(item));
1508
+ }
1509
+ const out = [];
1510
+ for (const id of order) {
1511
+ const n = await node(id);
1512
+ if (!("setReactionsAsync" in n)) {
1513
+ throw new Error("node " + id + " is " + n.type + " and cannot carry prototype reactions");
1514
+ }
1515
+ await n.setReactionsAsync(groups[id]);
1516
+ out.push(n);
1517
+ }
1518
+ return done(params, out);
1519
+ },
1520
+
1521
+ async get_prototype_links(params) {
1522
+ const scope = params.node_id ? await node(params.node_id) : figma.currentPage;
1523
+ const withReactions = [];
1524
+ const has = (n) => "reactions" in n && n.reactions && n.reactions.length;
1525
+ if (has(scope)) withReactions.push(scope);
1526
+ if ("findAll" in scope) withReactions.push(...scope.findAll(has));
1527
+ const names = {};
1528
+ const nameOf = async (id) => {
1529
+ if (!(id in names)) {
1530
+ const d = await figma.getNodeByIdAsync(id);
1531
+ names[id] = d ? d.name : null;
1532
+ }
1533
+ return names[id];
1534
+ };
1535
+ const links = [];
1536
+ for (const n of withReactions) {
1537
+ for (const r of n.reactions) {
1538
+ for (const a of r.actions || []) {
1539
+ const link = { id: n.id, name: n.name, trigger: r.trigger ? r.trigger.type : null, action: a.type };
1540
+ if (a.navigation) link.navigation = a.navigation;
1541
+ if (a.url) link.url = a.url;
1542
+ if (a.destinationId) {
1543
+ link.destinationId = a.destinationId;
1544
+ const dn = await nameOf(a.destinationId);
1545
+ if (dn) link.destinationName = dn;
1546
+ }
1547
+ if (a.transition) link.transition = a.transition.type;
1548
+ links.push(link);
1549
+ }
1550
+ }
1551
+ }
1552
+ return {
1553
+ scope: scope.type === "PAGE" ? "page " + scope.name : scope.name,
1554
+ total: links.length,
1555
+ links,
1556
+ };
1557
+ },
1558
+
1559
+ // flowStartingPoints is a page-level array, so read-modify-write it.
1560
+ async set_flow_starting_point(params) {
1561
+ const n = await node(params.node_id);
1562
+ const page = pageOf(n);
1563
+ const kept = page.flowStartingPoints.filter((p) => p.nodeId !== n.id);
1564
+ const changed = params.remove
1565
+ ? kept.length !== page.flowStartingPoints.length
1566
+ : true;
1567
+ page.flowStartingPoints = params.remove
1568
+ ? kept
1569
+ : kept.concat([{ nodeId: n.id, name: params.name || n.name }]);
1570
+ return {
1571
+ ok: true,
1572
+ id: n.id,
1573
+ page: page.name,
1574
+ changed,
1575
+ flowStartingPoints: page.flowStartingPoints.map((p) => ({ nodeId: p.nodeId, name: p.name })),
1576
+ };
727
1577
  },
728
1578
 
729
1579
  async get_screenshot(params) {
@@ -736,17 +1586,27 @@ const handlers = {
736
1586
  target = figma.currentPage;
737
1587
  }
738
1588
  if (!("exportAsync" in target)) throw new Error("node " + target.id + " cannot be exported");
739
- let scale = params.scale || 1;
740
- scale = Math.max(0.5, Math.min(scale, 4));
1589
+ // With dynamic-page access a node can be reachable before its page is
1590
+ // loaded, and exporting then yields a blank image with no error.
1591
+ let owner = target;
1592
+ while (owner && owner.type !== "PAGE") owner = owner.parent;
1593
+ if (owner && typeof owner.loadAsync === "function") await owner.loadAsync();
1594
+ const requested = Math.max(0.5, Math.min(params.scale || 1, 4));
1595
+ let scale = requested;
741
1596
  // Cap the output size: huge pages at high scale produce multi-MB base64
742
1597
  // payloads that are slow to ship and waste the AI's context.
1598
+ const cap = params.max_dimension > 0 ? Math.min(params.max_dimension, 4096) : 2000;
743
1599
  const maxDim = Math.max("width" in target ? target.width : 0, "height" in target ? target.height : 0);
744
- if (maxDim * scale > 2000) scale = 2000 / maxDim;
1600
+ const clamped = maxDim * scale > cap;
1601
+ if (clamped) scale = cap / maxDim;
745
1602
  const bytes = await target.exportAsync({ format: "PNG", constraint: { type: "SCALE", value: scale } });
746
1603
  return {
747
1604
  data: figma.base64Encode(bytes),
748
1605
  width: ("width" in target ? target.width : 0) * scale,
749
1606
  height: ("height" in target ? target.height : 0) * scale,
1607
+ scale,
1608
+ clamped,
1609
+ sourceHeight: "height" in target ? target.height : 0,
750
1610
  };
751
1611
  },
752
1612
  };
@@ -764,7 +1624,7 @@ async function postSelection() {
764
1624
  const sel = figma.currentPage.selection;
765
1625
  const items = [];
766
1626
  for (const n of sel) {
767
- const item = { name: n.name, type: n.type, link: nodeLink(n.id) };
1627
+ const item = { id: n.id, name: n.name, type: n.type, link: nodeLink(n.id) };
768
1628
  // Frames are copied as links; every other element (vectors, instances, …)
769
1629
  // is copied as SVG, so pre-export it now to keep the UI copy synchronous
770
1630
  // (clipboard writes must happen inside the click gesture). Skip huge
@@ -779,37 +1639,68 @@ async function postSelection() {
779
1639
  }
780
1640
  items.push(item);
781
1641
  }
782
- const needsKey = !fileKey && items.some((it) => it.type === "FRAME");
783
- figma.ui.postMessage({ selection: items, hasKey: !!fileKey });
784
- // Room for: base card + filter bar (30) + optional Copy-all header (22) +
785
- // the paste-URL prompt when a frame needs a key (64) + up to 6 visible rows
786
- // (the list scrolls beyond that).
787
- const rows = Math.min(items.length, 6);
788
- const h = items.length
789
- ? 162 + (items.length > 1 ? 22 : 0) + (needsKey ? 64 : 0) + rows * 30
790
- : 132;
791
- figma.ui.resize(300, h);
1642
+ figma.ui.postMessage({ selection: items });
792
1643
  }
793
1644
  figma.on("selectionchange", postSelection);
794
1645
  postSelection();
795
1646
 
1647
+ // ---------- activity log clicks ----------
1648
+
1649
+ async function uiAction(msg) {
1650
+ if (msg.uiAction !== "select") throw new Error("unknown action: " + msg.uiAction);
1651
+ const n = await node(msg.nodeId);
1652
+ figma.currentPage.selection = [n];
1653
+ figma.viewport.scrollAndZoomIntoView([n]);
1654
+ return null;
1655
+ }
1656
+
1657
+ // ---------- read-only switch ----------
1658
+ // Commands that leave the document as it is (selection and the open page are
1659
+ // view state). With the switch on, everything else is refused, so a tester can
1660
+ // let AI read a file it must not change. On at every start and never
1661
+ // remembered, so AI edits only while the user has this window unlocked.
1662
+ const READ_COMMANDS = /^(get_|list_|find_|audit_|download_assets$|set_selection$|set_current_page$)/;
1663
+ let readOnly = true;
1664
+ register();
1665
+ // Checkpoint buttons are for people who can edit this file. Dev Mode and
1666
+ // view-only windows (should the plugin ever run there) do not get them.
1667
+ figma.ui.postMessage({ canEdit: figma.editorType === "figma" && figma.mode !== "inspect" });
1668
+
796
1669
  // ---------- dispatch ----------
797
1670
 
798
1671
  figma.ui.onmessage = async (msg) => {
799
1672
  if (!msg) return;
800
- // Control message from the UI: the user pasted the file URL to enable links.
801
- if (typeof msg.setFileKey === "string") {
802
- setFileKey(msg.setFileKey);
803
- postSelection();
1673
+ // The window measures its content after every render.
1674
+ if (msg.resize) {
1675
+ figma.ui.resize(280, Math.max(104, Math.min(600, Math.round(msg.resize))));
1676
+ return;
1677
+ }
1678
+ if (msg.uiAction) {
1679
+ // A log row whose layer was deleted since: nothing to select.
1680
+ await uiAction(msg).catch(() => {});
1681
+ return;
1682
+ }
1683
+ if (msg.setReadOnly !== undefined) {
1684
+ readOnly = !!msg.setReadOnly;
1685
+ register();
804
1686
  return;
805
1687
  }
806
1688
  if (!msg.id || !msg.command) return;
807
1689
  const h = handlers[msg.command];
1690
+ const p = msg.params || {};
1691
+ const act = { command: msg.command, write: !READ_COMMANDS.test(msg.command), node: p.node_id || (p.node_ids && p.node_ids[0]) || null };
808
1692
  try {
809
1693
  if (!h) throw new Error("unknown command: " + msg.command);
810
- const result = await h(msg.params || {});
1694
+ if (readOnly && act.write) {
1695
+ figma.notify("AI tried to edit this file (" + msg.command + ") and was blocked. Untick Read-only in Figma MCP Console to allow edits.", { timeout: 8000 });
1696
+ throw new Error(msg.command + " was blocked: read-only mode is on in this file's Figma MCP Console window. " +
1697
+ "Tell the user; they can turn it off there if the edit is intended.");
1698
+ }
1699
+ const result = await h(p);
811
1700
  figma.ui.postMessage({ id: msg.id, result: result === undefined ? null : result });
812
1701
  } catch (e) {
813
- figma.ui.postMessage({ id: msg.id, error: String((e && e.message) || e) });
1702
+ act.error = String((e && e.message) || e);
1703
+ figma.ui.postMessage({ id: msg.id, error: act.error });
814
1704
  }
1705
+ figma.ui.postMessage({ activity: act });
815
1706
  };