Figma Local Bridge
Server Configuration
Describes the environment variables required to run the server.
| Name | Required | Description | Default |
|---|---|---|---|
| FIGMA_BRIDGE_PORT | No | Daemon port. Default is from plugin/manifest.json (8787). | 8787 |
| FIGMA_BRIDGE_HOSTS | No | Interfaces to listen on. | 127.0.0.1,::1 |
| FIGMA_BRIDGE_WRITE | No | 0 — read-only: mutation tools are not even registered. | 1 |
| FIGMA_BRIDGE_INFO_FILE | No | State file: pid, port, clientKey, plugin token. | ~/.local/share/opencode/figma-bridge-daemon.json |
| FIGMA_BRIDGE_TOKEN_FILE | No | Persistent plugin token (0600). | ~/.local/share/opencode/figma-bridge-daemon.secret |
| FIGMA_BRIDGE_DESTRUCTIVE | No | 1 — allow figma_use (raw Plugin API snippets). | 0 |
Instructions
Guidance the server publishes about itself, which clients place ahead of the tool catalog so the model reads it before choosing anything.
figma-local-bridge — operating guide
The bridge drives the Figma desktop app through a plugin panel. This is the
part that tool schemas cannot say: which file a call lands in, what rev and
replayed mean, and which failure may be retried. The schemas stay
authoritative about arguments.
Connecting a new install
macOS 0.35.1 ships a self-contained release: unzip it and double-click
Install.command. It installs a per-user LaunchAgent, backs up and configures
the MCP clients it detects, and copies the token to the clipboard without
printing it. Figma has no API for registering a development plugin, so the
user must still choose Plugins → Development → Import plugin from
manifest… on ~/Library/Application Support/Figma Local Bridge/app/plugin/manifest.json,
run the plugin, and paste the token. The installer is unsigned in 0.35.1;
Gatekeeper may require right-click → Open. Uninstall.command removes the app,
LaunchAgent and this bridge's entries. From a source checkout, npm run setup
does the same after npm run build.
Which file a call lands in
Every local tool takes an optional fileKey; the cloud tools take a required
fileKey naming the REST file to read.
Call
figma_pingfirst when you do not know what is open: it reports the daemon, the active page and every connected file (fileKey+ name).One file connected:
fileKeymay be omitted.Several files connected: a call without
fileKeyis refused before it is sent, with the list of candidates. Pass the key — never guess and never "pick the most recent". A file that has never been saved gets a session key likeunsaved-a1b2c3d4.An unroutable request is answered immediately. A timeout therefore means the plugin is connected but slow, not that the wrong file was addressed.
Local capabilities, optional cloud tools, and what is not available
figma_ping is also the capability report. It returns capabilities.local.mode
(read-only, write, or write+destructive) and capabilities.cloud:
figma_pingalso returns amotionobject: whetherfigma.motionis present, the current playhead (or null), and whether local custom animation styles can be listed. Node-level methods are checked per node byfigma_motion_inspect; a missing Beta API isMOTION_UNAVAILABLE.The cloud adapter is off by default.
cloud.availableis false unless the MCP process hasFIGMA_CLOUD=1and exactly one ofFIGMA_CLOUD_TOKEN(PAT) orFIGMA_CLOUD_OAUTH_TOKEN(OAuth). A token alone is not consent to cloud calls.When
cloud.availableis true, the five registered tools arefigma_cloud_ping,figma_cloud_get_file,figma_cloud_get_nodes,figma_cloud_get_imageandfigma_cloud_download_image. They read documented Figma RESTGETendpoints and work without the local daemon. Use them for a file that is not open; use the local tools for the open document.Cloud is read-only with respect to Figma. It cannot create or edit a file, generate a design or image, run a shader, a generative plugin or Weave. If a user asks for one of those, say it is not available here and point to the official remote Figma MCP or the Figma UI. Never imitate it with a local workaround and call the result the same thing. The one local write is
figma_cloud_download_image, which saves rendered bytes tooutDir; the Figma document is untouched.figma_cloud_pingrequirescurrent_user:read; file/node/image reads and downloads needfile_content:read.401/403areCLOUD_UNAUTHORIZED/CLOUD_FORBIDDEN, not a reason to retry. A429carriesretryAfterSecondsand is not retried automatically.CLOUD_RESPONSE_TOO_LARGEmeans narrownodeIds/depth, lower the render scale, or raisemaxBytes/maxTotalBytesdeliberately; the reply or file is refused, never truncated.figma_cloud_get_imagereturns temporary URLs, not downloaded files.figma_cloud_download_imageis the explicit byte path: it calls the image endpoint, fetches each signed URL without the Figma token, verifies the PNG/JPEG/SVG/PDF signature, caps each image and the call total, writesfigma-<nodeId>.<ext>underoutDir, and refuses to overwrite unlessoverwrite:true. A non-HTTPS URL, a redirect, a bad signature or a local write failure isCLOUD_DOWNLOAD_BLOCKED,CLOUD_BAD_IMAGEorCLOUD_DOWNLOAD_FAILED; it never claims a partial set was complete.The adapter does not run an OAuth authorization flow or refresh an expired token; the caller supplies a valid access token.
Tools the official server marks remote-only but that the open file can answer —
download_assets,get_libraries,whoami,search_design_system— are real local reads here, not cloud calls.The cloud boundary is part of the answer, not an error: a missing hosted capability is a deliberate limit, not something to paper over.
rev, replayed, and what may be retried
Every answer that came from the plugin carries two facts on its envelope:
rev— the document revision the answer was produced at. It advances on failed writes too: a write that failed and rolled back is not the state you last saw. Identical screenshot bytes with a higherrevmean Figma's export cache is stale, not that your edit did nothing.replayed— the answer came from the plugin'sopIdcache, so the method did not run again. Retries reuse the sameopIdby design: a replay is safe, and it is proof that nothing was applied twice.
When an error says a call may or may not have been applied, do not retry
blindly — re-check with figma_inspect and only then decide. When it says the
call was not sent, retrying is free.
FIGMA_BRIDGE_OFFLINE means the plugin is not running: say so and stop instead
of looping on retries.
FIGMA_BRIDGE_UNKNOWN_FILE means the key is not (or no longer) connected — an
unsaved file's key changes when its panel reloads. Do not retry the same key:
the error lists what is connected, take one of those.
Writes
Mutations are serialized by the bridge, one at a time, because Figma's undo barrier is global. Prefer the specific tools over raw code:
figma_inspectwithcompareWithanswersEQUIVALENT/DIFFERENT/INCONCLUSIVEbefore you mutate.includeFingerprint:falseskips the semantic whole-subtree snapshot when you only need the compact structure; acompareWithrequest still computes it.figma_replace_repeated_with_componentis transactional and refuses unless every target is provably equivalent; run it withdryRun: truefirst.figma_useis the raw Plugin API. It requiresallowDestructive: trueand ascopeNodeIdnaming the only subtree it may touch (unlessallowPageWide); anything created, deleted, reparented or altered outside that scope is rolled back, and page-global changes (variables, styles) needallowGlobalChanges. One call = one undo step. Return the ids you create and keep calls small.Work that escapes the call (a fire-and-forget promise) escapes the diff too — a timeout does not roll back, and the error says so.
Writes can be off:
FIGMA_BRIDGE_WRITE=0leaves the mutating tools unregistered, andfigma_useadditionally needsFIGMA_BRIDGE_DESTRUCTIVE=1.
Declarative editing and component swap: build, patch, batch, swap
The first three tools are the preferred way to change a tree. They resolve every target and every resource before the first write, so a typo cannot leave half a design applied.
figma_buildtakes abuildIdand a full tree. The root gets that id inpluginData; every node gets a stable key (parent/slug#indexunless you supply one). Re-send the same buildId and it updates in place — never duplicates.prune:truemakes the tree exact by deleting keyed children the spec no longer contains; protected nodes are skipped and reported. The tree also carries rotation (degrees), per-corner radii, stroke cap/join/miter, masks, layout grids, layout inclusion flags, text case/decoration/paragraph spacing, text hyperlinks (URL, or NODE by node id), text runs (ordered character ranges with their own font, size, text style, fills, fill style, variable bindings, case, decoration, line height, letter spacing and hyperlink), whole-texttextVariablebindings, an exactLINElength, PATTERN paints (a file-local source node id plus tile type, scaling factor, spacing and horizontal alignment), SHADER paints (a shader id plus optional property assignments keyed by definition id; an unimported fill shader is imported on apply; effect shaders are refused), and boolean operations. ABOOLEAN_OPERATIONcarriesbooleanOperation(UNION,SUBTRACT,INTERSECTorEXCLUDE) and at least two children in spec order. Its operands are built first and combined into one boolean; the operation can change in place on a repeat build, and its size is derived from the operands (a supplied size is warned about and ignored). Nested booleans build inside-out.figma_patchtakes a sparse tree underrootNodeId,buildIdorrootKey. Children match by key. A missing key is refused unlessallowCreate:true; a key under the wrong parent is refused rather than duplicated.prune:truedeletes omitted keyed children at patched levels. A boolean patch may list only the operands it changes whenpruneis false; pruning a boolean requires at least two operands in the patch. A sparse boolean patch keeps the existing operand order and appends a new operand; send the complete ordered list withprune:trueto enforce order.figma_batch_edittakes up to 200 small ops on many targets in one transaction. Targets arenodeIdor stablekey. Ops:set_text,set_name/rename,set_fill,set_stroke,resize,move,set_visible,set_opacity,set_rotation,set_layout,set_variant,set_constraints,duplicate,reparent.duplicateandreparenttake a destinationparentIdorparentKey; the key is resolved on the current page. The dry run returns the resolved destination and adds its non-page fingerprint to the samefingerprintsmap as the targets — pass that whole map on apply, or a changed destination is not guarded. Areparent.indexis the final child index; omitted appends. Reordering inside the current parent keepslayoutPositioning; moving into auto-layout usesABSOLUTEwhen preserving the canvas position (default) andAUTOwithpreserveAbsolute:false. A destination inside anINSTANCEorCOMPONENT_SETis refused; inside aCOMPONENTit is reported as an edit to the component definition. To extend an existing set, usefigma_variant_setadd, not a batch reparent. Moving into or out of a protected parent is refused, because that changes the parent's children. A duplicate whosenewKeyalready exists is a no-op and reports an existing node under a different parent. Every target, destination, font, paint style and variant property is resolved first; a failed op rolls the whole batch back unlessstopOnError:false, which reports the exact failure and what did apply.
Authoring a variant set
figma_variant_set treats a COMPONENT_SET as a matrix. There is no direct
variantProperties setter: a variant's Property=Value name is what Figma
parses into the matrix, so the tool writes names and then reads the API fields
back to prove the matrix landed.
action:"combine"takes standaloneCOMPONENTs, a setname, and the properties each component should represent. Every component must use the same property names, no combination may repeat, and a component already in a set, inside anINSTANCE, or nested in another listed component is refused. Components are renamed, thenfigma.combineAsVariantsmoves them into a new set appended toparentId/parentKey(or their common parent).action:"add"takessourceId/sourceKey(an existing variant) and a complete newpropertiesmap. It clones the source's structure — not its instances — inserts the clone (optionally atindex) and verifies the new combination. An existing combination is refused; useedit.action:"edit"takesvariantId/variantKeyand the complete newproperties. It renames the variant in place, so its id and instances survive; their variant property values follow. The same combination is a no-op.Property names and values cannot contain comma, equals or a newline. All variants must expose the same property names; a set whose variants do not expose
variantPropertiesis refused instead of guessed at.A dry run (the default) returns
fingerprintsfor every component and the set, plus the destination layout for combine. Apply withdryRun:false, the returnedplanIdand that whole map. After writing, the tool verifiesvariantPropertiesandvariantGroupProperties; if Figma did not accept the names, the transaction is rolled back rather than reported as an applied matrix. If the undo itself fails, the error saysROLLBACK FAILEDand tells you to inspect before retrying.A combine destination inside an
INSTANCE, anyCOMPONENT_SET(including a variant) or aCOMPONENTdefinition is refused: Figma will not reparent a component into a component definition.addandeditstill operate on an existing set inside a component and name that edit. A combine appends the set; move it afterwards withfigma_batch_editif placement matters.
Swapping an instance's component
figma_swap_component changes one or more INSTANCEs to another main
component. It does not assign mainComponent directly: it calls
swapComponent inside one undo transaction, then replays what that editor
heuristic does not promise to keep.
Target the component by
componentId,componentKey,componentName,componentSetIdorcomponentSetKey. A set needsvariantProperties(for example{ "Size": "L" }); omit it and the default variant is used with a warning. An ambiguous component name is refused with the candidates.A dry run (the default) compares the old and new structures and returns a per-target fingerprint of the instance and the target component, the mapped overrides, the root-level state it will preserve, every named loss and every remapped path (
compatibility.changes;compatibility.lossesholds only actual losses). Apply withdryRun:false, the returnedplanIdandexpectedFingerprints. Apply re-plans before the first write and refuses if the instance, its properties or the target component moved since the dry run.A direct override path is exact index+name first, then a unique name in the new component (reported as
override-remapped). A changed node type, a missing layer, a changed nested component or an unsupported override field is a loss. It is never applied to a different node type.Component properties are mapped by display name and type.
BOOLEAN,TEXTandINSTANCE_SWAPvalues are replayed;VARIANTproperties belong to the chosen target, andSLOTproperties cannot be set through the Plugin API. A renamed or type-changed property is reported, not invented.Root-level state that differs from the old main component is preserved: custom name, manually resized geometry, opacity, visibility, paints/strokes/ effects and their style links, layout placement, constraints, rotation and min/max size.
preserveSize:falseadopts the new component's size;preserveRootOverrides:falseadopts all root defaults.allowLoss:trueis required to apply a swap whose plan names a loss; the apply report carries the predicted losses separately from what was restored.allowUnverified:trueis required for a library key whose structure could not be checked before import. Any unexpected loss during apply rolls the whole transaction back.A target that is itself nested inside another
INSTANCEis refused: that is an override of the outer instance. Nested instance overrides deeper than 12 levels block the swap rather than being silently truncated.
A no-op (the target already points at that component) writes nothing. The tool is registered in read-only mode for dry runs; only apply checks write access.
On a TEXT node, runs are absolute UTF-16 character offsets (start
inclusive, end exclusive), sorted and non-overlapping. Each run needs at
least one field; fields it omits inherit the node's base text properties.
textStyle and fillStyle take a local style name or id and link that range;
null clears a link inherited from the base, and fillStyle and fills are
mutually exclusive on one run. A TEXT node's textVariable binds base text
fields, and a run's variable binds that range; both are objects keyed by
Figma's field names (fontFamily, fontStyle, fontWeight, fontSize,
letterSpacing, lineHeight, paragraphSpacing, paragraphIndent). The value
is a local variable name/id, and null clears a binding inherited from the
base. A literal run value does not remove a base binding; set that field to
null in the run's variable map when the range should be unbound. Build
resolves the variable and checks its STRING/FLOAT type before writing. A
fontFamily/fontStyle binding changes the font, so Figma may need that font
loaded; the build rolls back and names the font error if it is not.
Send text with runs, because the engine validates every range against the
characters it is about to write. figma_batch_edit's set_text still sets one
font per op; use figma_build / figma_patch for per-range styling and
bindings.
An INSTANCE's overrides map changes layers inside the instance without
detaching it. The map key is a layer name or build key; when names repeat, give
the override a path: [{name, index}, ...] and use any unique label as the
key. Fields cover text, font and size, text style and formatting, hyperlink,
fills/strokes and their styles, effects and effect style, visibility, opacity,
blend mode, rotation, corner radii, stroke weight, size and name. A path is
resolved against the recreated instance before writing; a stale name or index
is a warning and that override is skipped, never applied to a guessed layer.
The safe sequence for build, patch, batch and swap:
Call with
dryRun:true(the default). Read the plan,planId,fingerprints/fingerprint, and any warnings.If the plan is right, call again with
dryRun:false, the returnedplanId, and the returned fingerprint(s).The apply refuses a different plan or a target that moved since the dry run before the plugin writes anything. A failed apply is rolled back and says so; never retry a blind write.
A batch cannot target a node created by an earlier duplicate in the same
batch — its key does not exist at plan time. Split that into two calls.
figma_build / figma_patch do not implicitly move a keyed node to another
parent; use batch with reparent, parentKey and (when order matters) a
final index. Pass the destination fingerprint from the dry run with the
target fingerprints.
To bring a hand-made tree into this language, figma_export_build_spec
returns a spec that figma_build accepts. It keeps keys that already exist,
derives the same key the build engine would for nodes without one, and turns
style/variable links into fillStyle/strokeStyle/textStyle/effectStyle,
variable or textVariable. URL text links travel in the spec; a NODE link is
exported with a file-local warning. Mixed text becomes a base style plus
ordered runs, so mixed fonts, sizes, text/fill style links, text variable
bindings, case, decoration, spacing and links survive a rebuild. An IMAGE or
VIDEO paint carries its crop transform, tile scaling, rotation and filters (a
video hash is file-local, like an image hash); a PATTERN paint carries its
source node id, tile type, scaling factor, spacing and horizontal alignment
(the source node is file-local); a SHADER paint carries its shader id and
property assignments keyed by definition id, including variable aliases, which
must resolve in the target file (the shader must be available in the target
file and is imported on apply); every supported paint carries
visible and blendMode, including an invisible paint that stays in the
stack. Direct
instance overrides become overrides entries
with structural paths built from
the main component's layer names, so a renamed layer still resolves; the
instance interior itself is recreated from the main component, not carried in
the spec. A BOOLEAN_OPERATION is exported as a live boolean with its operation
and children, not as a flattened SVG. A node the build cannot express — an
unsupported type, a frame created from SVG, a detached instance — is exported
as its inline SVG render when svgFallback is on (the default). The rebuild is
a flattened frame: appearance
survives, but the original child layers, component identity, overrides and
style/variable links do not and text becomes outlines; every fallback is named
in warnings and counted in counts.svgFallbacks. Slices are never flattened; svgFallback: false lists
those nodes as unsupported instead. A fallback that cannot be rendered or does
not fit the 128 KiB per-node / 192 KiB total budget is listed as unsupported
with the reason. A built SVG leaf is re-recognised as SVG on the next build,
so re-sending it updates in place; a changed svg replaces its interior while
keeping the frame's id and key, and an unchanged source is not touched. Read unsupported and warnings before building it: an
override field the build cannot express or a mixed value has no exact
representation. truncated: true means the spec is
incomplete and must not be built as-is.
Finding things, and checking the result
figma_indexreturns a compact flat index of a page/subtree: id, stable key, name, type, path, depth, size, child count, build root. Use it to learn the shape before inspecting one subtree. It stops atmaxNodesand says so. It deliberately does not resolve an INSTANCE's main component: under dynamic-page the synchronous getter throws, and one async lookup per instance would turn the index into N round trips. Usefigma_inspectorflb.mainfor one node.figma_searchfinds nodes by name, stable key or text — substring, regex or glob — withtypes,keyPrefixandhasKeyfilters. It returns the match fields, a text snippet and the path, not the whole tree.figma_auditis read-only. It reports duplicate keys, unkeyed nodes inside a built tree, literal fills/strokes that are neither a paint style nor a variable, text without a text style, placeholder copy, detached instances, WCAG AA contrast against the effective background, default names, and opt-in off-scale spacing/radius, empty text and literal effects. A contrast finding is exact for solid text on a solid effective background; gradients/images are reported as unknown, not guessed. Withsuggest:true(default) a hardcoded colour names exact local paint-style and colour-variable candidates, unstyled text names exact local text-style candidates, and spacing/radius names the nearest on-scale value. These are candidates, not bindings: check the mode and apply the token deliberately.figma_design_systemsnapshots styles, variables (with modes and values) and components.inventoryreturns it,exportwrites a JSON file with a sha256, anddiffcompares that file to the live file by stable key. It is read-only: syncing values back into Figma still goes through the specific write tools.figma_reviewis the before/after measurement for an iteration: save a baseline, edit, compare. It reports new/resolved audit findings and pixel/ structural changes together; see the section below. Usefigma_comparefor a mockup, andfigma_checkpointwhen a subtree must be restorable.
Design tokens: variables, not styles
figma_tokens is the write path for variables. It does not invent paint/text/
effect styles from token names; those still go through figma_build,
figma_batch_edit or figma_use.
exportwrites the nativefigma-tokens/v1form: every local collection, its modes, and every variable's type, description, per-mode value and alias.diffcompares that file with the live file. Both are reads; neither writes to Figma.importdefaults todryRun:true. Readsummary,changes,warningsandblocking; then apply with the returnedplanIdandexpectedFingerprint(the dry run'sfingerprintvalue — the argument name differs on purpose). TheplanIdcovers the file bytes, target file and options; the fingerprint covers the file identity plus the live variable collections/modes/values/descriptions/aliases, and the server refuses a changed file before the plugin is called. A prune dry run must also useallowDestructive:trueto enumerate the deletes, and the same value is part of the planId; apply with the same argument.A native alias is
{"alias":{"collection":"Theme","name":"color/bg"}}. It is applied withcreateVariableAlias; it is not flattened into a copy. A remote/library alias is{"alias":{"collection":"Library","name":"text","remote":true,"id":"VariableID:…"}}; the id is required so an unchanged binding can be recognized, and a new or different one is refused rather than guessed. DTCG{color.bg}aliases are accepted inside the one collection being imported. A minimal native document:{ "schema": "figma-tokens/v1", "collections": [{ "name": "Theme", "modes": ["Light", "Dark"], "defaultMode": "Light", "variables": [{ "name": "color/bg", "type": "COLOR", "description": "page background", "values": { "Light": "#ffffff", "Dark": "#000000" } }, { "name": "color/text", "type": "COLOR", "values": { "Light": "#111111", "Dark": "#eeeeee" } }] }] }A plain DTCG tree is accepted with
collectionandmode. Supported types:color,number,dimension(px becomes a unitless FLOAT, with a warning),string,boolean,fontFamily(an array becomes one comma-joined STRING) andfontWeight.shadow,gradient,typography,cubicBezier,transitionand other composite types are blocking: the import does not silently skip them.A variable's type cannot change in Figma. A document that asks for COLOR over an existing FLOAT is a blocking finding, not a recreate.
Collections, modes and variables are matched by name. Renaming one is a create plus (with prune) a delete, not an identity-preserving rename. A mode rename creates a new mode and leaves the old one: modes are never deleted.
Modes not named by the document are preserved on existing variables. A new variable gets those modes filled from the default managed mode, and the plan lists them under
fillsUnmanagedModes.pruneis off by default. Withprune:trueandallowDestructive:trueit deletes variables in the named collections that the document no longer has. It never deletes a collection or a mode. A variable alias pointing at a variable being pruned blocks the plan; node bindings cannot be enumerated and are named as a breakage risk, not silently protected.Apply is one undo transaction and reads every collection, mode, description, literal and alias back from fresh state. A mismatch rolls it back. If Figma refuses the undo, the error says
ROLLBACK FAILED; do not retry blindly.Export carries the fields above, but only for variables. A variable
EASINGorTIMINGis named and skipped; styles, variable scopes, code syntax, hidden-from-publishing flags, publish keys and extended-collection parentage are not carried. A remote/library alias is exported withremote:true, its name and its live variable id; an unchanged value round-trips and is preserved, while a new or different remote binding is refused instead of being rebound by name. Colours are 8-bit hex; matching is by name inside a collection, so a rename is a delete plus a create, not a preserved identity.
Motion (Beta)
Motion is the Figma timeline API, not an animation engine inside this bridge.
Every command probes figma.motion and the target node's methods at call time.
On a build where they are missing, the answer is MOTION_UNAVAILABLE — never an
empty style list, a pluginData imitation, or a locally interpolated animation.
figma_ping reports whether figma.motion is present; figma_motion_inspect
reports which node-level methods this particular node exposes.
figma_motion_styleslistsfigma.motion.figmaAnimationStyles()and local custom animation styles, plus the current playhead. Use the returnedstyleId(Figma style) orid(custom style) withfigma_motion_apply_style.figma_motion_inspectreturnsanimationStyles,manualKeyframeTracks,animationsandtimelinesfor one node. This is where to find the applied style instance id, timeline id and current track before writing.Writes are
figma_motion_apply_style,figma_motion_remove_style,figma_motion_set_keyframes,figma_motion_remove_keyframesandfigma_motion_set_duration. Each defaults todryRun:true, returns aplanIdbuilt from the operation and the node's live Motion-state fingerprint, and refuses apply with any other plan.Apply is one undo transaction. The plugin reads the style/keyframes/timeline back after writing; a missing style, a changed duration/offset, a changed keyframe position/value/easing or a track that did not disappear makes the call fail and roll back. Removing something that is already absent is a verified no-op.
A Figma style accepts
duration,timelineOffsetandprops. A custom style accepts onlytimelineOffset;durationandpropsare refused rather than silently dropped.A keyframe track is
{ baseValue?, keyframes:[{ id?, timelinePosition, easing?, value }] }. Positions are seconds, unique, and every value in one track must share a type (FLOAT,COLOR,VECTOR,BOOL, …). A field is either{type:"PROPERTY",name:"OPACITY"}or an indexed paint/stroke/effect descriptor, for example{type:"INDEXED_ITEM",collection:"effects",index:0,field:"RADIUS"}.figma_motion_inspectshows the exact field names and existing ids.figma_motion_set_durationneeds atimelineIdfrom the node'stimelines; the plugin verifies that the same id still lists the new duration.There is no Motion GIF/MP4/WebM export in the Plugin API used here. Render or record in Figma if a movie file is required; do not expect a file from these tools.
The snippet standard library (flb)
use_figma runs its body with three arguments: figma, console and flb.
flb is not a second API — it is the Plugin API with this manifest's traps
named (plugin/helpers.ts), so a snippet does not rediscover them by failing:
the manifest declares
"documentAccess": "dynamic-page", wherefigma.getNodeByIdthrows and an INSTANCE's synchronousnode.mainComponentgetter throws too (Figma logs it even if the snippet catches it).await flb.byId(id)uses the async form;await flb.main(node)(orawait node.getMainComponentAsync()) is the only safe main-component read. A detached instance returnsnull.flb.find({within, name, match, type})andflb.one(...)search descendants (matchis a RegExp or a pattern string). Neither will answer with a silently truncated list;onerefuses an ambiguous pick and names what else matched.flb.bbox(node, {render: true})returns absolute bounds.render: trueis what is actually drawn — shadows and strokes included — and that is what packing sprites has to use, because layout bounds stop at the node's box. A node with nothing to draw reports layout bounds and says the render bounds were null.flb.clear(node)removes the children and returns what was removed.flb.flatten(node)detaches every instance in the subtree, outermost first (Figma's owndetachInstance, so overrides survive) — the flat-sprite step. It throws if anything could not be detached instead of reporting a half-flat tree. The node you passed in is dead afterwards: Figma invalidates a detached instance, so even reading itsnamethrowsThe node with id … does not exist. Carry on with the returnedroot(ordetached[i].frame) — a snippet that kept the old node to report on later dies on the way out.flb.grid(nodes, {parent, cell, columns, gap, origin, fit})arranges nodes in uniform cells — the atlas layout.originand the returned cell boxes are ABSOLUTE document coordinates;celldefaults to the largest render bounds;fit: truescales sprites DOWN into their cells (never up). It refuses the three cases where placement would quietly not happen: an auto-layout parent (unless the children arelayoutPositioning = "ABSOLUTE"), a node that cannot be resized (an INSTANCE — flatten it first; a HUG-sized frame), and nodes living in different parents.await flb.text(content, {parent, x, y, size, font, fills})loads the font before writing characters — the step whose absence reads as a font error.fills: "#ffcc00"becomes a paint throughfigma.util.solidPaint.The write helpers refuse a target outside the declared scope, and a node on another page (the scope guard indexes one page), before writing: a call that would be rolled back at the end fails at the line that caused it.
An atlas, end to end, in one call:
const sheet = flb.one({ name: "Atlas" });
const sprites = flb.find({ type: "INSTANCE", match: "^sym_" }).map((s) => flb.flatten(s).root);
flb.clear(sheet);
const placed = flb.grid(sprites, { parent: sheet, cell: 128, columns: 4, fit: true });
return { cells: placed.cells, resized: placed.resized, notes: placed.notes };Code Mode recipes: driving the bridge from the agent runtime
The agent calls bridge tools from a JavaScript-only code-mode runtime
(the execute tool), not from a shell and not from Python. Everything below
was learned by failing in a real session.
The runtime is JS. Python idioms throw immediately:
import,print,exec, keyword arguments (fileKey="…") →Unknown identifier 'fileKey','import' and 'export' may appear only with 'sourceType: module'. Call tools asawait tools["figmaBridge"]["figma_use"]({…})with plain object literals.console.logis the output channel; thereturnvalue is not. A snippet that returns an object may answerresult: nullon the tool envelope, so put everything you need into logged strings. Also wrap the tool call itself intry/catchin the wrapper: a failed call yieldsundefined, andv.logs.join()crashing is the symptom, not the error.Snippet API traps (dynamic-page manifest):
figma.loadFontAsync("Barlow")throws — pass{family, style}.node.indexdoes not exist. Useparent.children.indexOf(node).Set the parent's
layoutModebefore setting a child'slayoutSizingHorizontal/VerticaltoFILL/HUG, otherwisenode must be an auto-layout frame or a child of an auto-layout frame.Figma auto-deletes a GROUP when its last child moves out; a later
group.remove()then throwsThe node with id … does not exist. Wrap shell removals intry/catch.src.clone()on a child of an auto-layout row lands beside the source; reparent (newParent.appendChild(clone)) immediately afterwards.rescale(scale)works on INSTANCEs and is uniform only; there is no non-uniform scale API, and resizing an instance stretches the frame without scaling its children.A node inside an INSTANCE cannot be resized or moved:
node.x = …throwsrelative-transform, andresize()is a silent no-op. Only text, fills, strokes, visibility, opacity, effects and corner radius can be overridden. For per-instance geometry use a component variant, or detach (flb.flatten) and edit the returned frame — then set the size/position.Never type an enum value from memory. Enum setters are validated by the runtime: one unknown string throws
Invalid optionand rolls the whole snippet back — including every write before it.frame.overflowDirectionaccepts only"NONE" | "HORIZONTAL" | "VERTICAL" | "BOTH"; there is no"VERTICAL_SCROLLING". Use the prelude'ssetEnum(node, property, value)orsetOverflow(frame, "vertical"), and setclipsContent = truealongside a scrolling value. The typings agree with the runtime for these enums —node_modules/@figma/plugin-typings/plugin-api-standalone.d.tsis the place to copy a value from, not memory.figma_useadditionally refuses a known-bad enum spelling (or a value one typo away) before sending, naming the line and the accepted list, so nothing is applied and there is nothing to roll back. A value that is merely unfamiliar is passed through: the runtime stays the authority, and an older bridge cannot block a newer enum value.Component properties:
set.addComponentProperty(name, type, defaultValue)on theCOMPONENT_SETreturns a suffixed key ("Price#1529:0"). Link nodes with that exact key (node.componentPropertyReferences = {characters: key}/{mainComponent: key}). TheINSTANCE_SWAPdefault and theinstance.setPropertiesvalue are the component id.
Rollback discipline (the expensive lesson). A snippet that ends with
.catch(e => console.error(e))and returnsundefinedis a successful call to the bridge: partial changes are committed and nothing rolls back. Log and rethrow (console.error(...); throw e;) so the transaction rolls back whole. Then verify the live state with a read-only snippet instead of assuming the rollback happened — bothchangedPage:falseand an unchanged node count can be lies when the error was swallowed.Split big structural work. "Convert to component + replace instances + re-layout + rename" is four
figma_usecalls with a read between them, not one giant snippet: a snippet that throws at step 9 of 12 leaves a half-moved tree that still logs fine.Instances accept no new layers.
insertChild/appendChildwith an INSTANCE as the parent throwsCannot move node. New parent is an instance. An icon that has to sit on an instance root goes in as an absolutely positioned sibling (layoutPositioning = "ABSOLUTE"), or into the main component as a slot exposed through a component property. Per-instance padding, alignment and font size are overridable — that is how you make room for a sibling icon.Size changes go through
resize(). Assigningnode.width/heightcan be a silent no-op (nothing thrown, value unchanged) —resize(w,h)applies. Read the value back before reporting it, and prefer explicit widths overFILLwhen several instance roots must end up equal."Rolled back" is information. A
failedjournal line that ends in(rolled back)restored the document; one that does not may have committed whatever was created before the throw (a stray instance at page(0,0)is the usual trace). After such a failure, scan and clean up instead of assuming.One server per task. Call
figma_pingfirst and stay on the local bridge for the open file. The cloudtools.figma.*server can answer read calls about the same file key and quietly creates two sources of truth.
Safe-snippet prelude (start every figma_use code with it)
assets/prelude.js in this skill is a plain-JS prelude — paste it at the top of
the code string. It removes the whole class of errors catalogued below by
construction: colour tokens become validated hex (paint("textAccent") throws a
named error instead of feeding solidPaint a number/object/undefined), text is
written through .characters after the font is loaded, frames set layoutMode
before sizing modes, PaintStyle.paints is used instead of .fills, style
binding goes through the async setters, and node access uses getNodeByIdAsync.
Call preflight([...tokens]) before the first write; a snippet that throws there
rolls back having touched nothing.
This whole skill travels with the bridge, so no client needs a separate skill
install: GUIDE.md is both the handshake instructions and the resource
figma-local://guide/skill, and every file under the skill directory is a
resource under figma-local://skill/<path> — the prelude is
figma-local://skill/assets/prelude.js, the short playbook
figma-local://skill/SKILL.md. Resource bodies are read from disk per request,
so an edit lands without a restart; a client that only shows the handshake can
still fetch the prelude instead of retyping it.
Failure catalogue (symptom → cause → fix) — all seen in one session
Symptom in the envelope / log | Cause | Fix |
|
| pass |
| a constant that was already | keep tokens as hex strings; convert only at assignment. One representation per token |
|
|
|
text nodes render empty; | used |
|
|
|
|
| family has no | Space Mono ships |
| sync setter used for a style link |
|
|
| write |
sync |
|
|
reading | same reason (the getter is sync) |
|
node is 100×100 / icon stretched to 100 | a child got | set |
|
| decide hug-vs-fixed first; for hug set |
slider fill/knob drift after a resize | resizing a frame scales children by constraints |
|
| tried to set | change the main component, add a variant, or detach ( |
instance child |
| same fix: variant or detach. Never trust the post-call |
| the parent's | set |
| an enum spelling recalled from memory ( | use |
| the id came from another file or an older answer (ids are file-scoped and do not survive a rebuild) | re-read ids with |
| tried to add a layer into an INSTANCE — an instance accepts no new children, only property/text/fill overrides | put the layer as an absolutely-positioned sibling ( |
| the width/height setters can be a silent no-op (seen on a component's child rect); nothing is thrown, so a whole batch of edits quietly does nothing | use |
two bars rotated ±45° render as |
| draw diagonals as one |
tabs set to FILL came out 1 px, 76 px, 127 px … |
| compute |
bare | a method was called on a node type that does not have it (or an API absent from this manifest) | guard with |
|
| scope such calls to the page ( |
a failed call left a node behind (stray INSTANCE at page 0,0) | the error carried no | after any failure whose message lacks |
| the dump read that property on a variant COMPONENT (a section/component set that contains one) | fixed in 0.36.0 by guarding the read; reload the development plugin so the rebuilt |
| iterated a | remove only top-level roots ( |
bound | the | test |
| plan page cap hit | reuse an existing page; do not create one |
| Variables API absent in this manifest/plan | use Paint Styles ( |
|
| the parameter is |
write tool: |
| pass |
| a tab reacted to its own frame ( | skip self: build the reaction only when |
a whole batch of created components vanished | the snippet threw at item N and the bridge rolled back the transaction | split into small snippets; |
| the code-mode runtime has no Node/ESM globals | no |
| a mangled/stray fragment pasted into the | keep the snippet in one block; when it is big, write it to a file and re-paste verbatim |
empty section around frames | a |
|
a new | every variant was created at the same | place variants on a grid ( |
after replacing a child in a master, instances flip a layer that used to be hidden | overrides on a removed child are dropped (only some are remapped), so visibility overrides silently vanish | snapshot per-instance state ( |
an icon component still depends on a font / a glyph renders differently when the font is missing | a text glyph was used as artwork inside the component |
|
| flatten converts strokes into filled outlines and unions overlapping shapes, so a 2 px | do not flatten icon artwork. Rebuild the variant from the source component's children, scaling each one ( |
a cloned icon instance jumps to | the target frame is auto-layout, so the new instance enters the flow; the originals were | set |
scaling a 32×32 icon down to 24 with |
|
|
Rule of thumb for this bridge: every colour is a hex string, every text write
follows a loadFontAsync, every frame fixes its sizing mode before it is filled,
every style/fillStyleId/mainComponent read-write is async, every enum value
comes from the runtime's accepted list (the prelude's ENUMS / setEnum) rather
than memory, and every snippet is small enough that a rollback costs one step,
not one session.
Exporting for a build or the web: atlas, 9-slice, states, handoff
figma_export_ui_atlas takes the sheet you just built and returns ONE PNG plus a
manifest of rects in that PNG's own pixels, written next to it
(.atlas.json) and re-read from disk before the answer. Nothing is repacked: the
frame's direct children are the sprites, in their document order. What the
manifest refuses to hide:
sheet.sizeMatches: false— Figma produced something other thanround(size × scale); the rects follow the FILE, andexportWidth/Heightis what they are measured against.overlaps,offSheet,bleed— rects that overlap (an engine slicing by rect cannot tell whose pixel it is), sprites outside the image, and drawing that reaches past its own box (a shadow or a stroke the neighbouring cell cuts off).repeated names: keys become
coin#1,coin#2; a child with no bounds at all lands inskippedwith a reason instead of quietly missing.basis: "nodeBox"— the frame has a stroke, so the image is the frame's own box and the rects are measured from the node's top-left. Which box the image is is decided by the exported size, not assumed.
So the order is: build the sheet (flb.grid), read verification and
warnings, and only then wire the engine up — the rects in the reply are what
the engine needs; the JSON on disk is what a build pipeline reads.
figma_export_9slice returns insets in the file's pixels, the stretchable
middle, and CSS values ready for border-image (borderImageSlice in image
pixels, borderImageWidth in design pixels — the pair a @2x image needs).
Insets come from insets or from a child layer named exactly 9slice; insets
that leave no middle are refused with the numbers that caused them.
figma_export_ui_states writes one file per state. A COMPONENT_SET names them
by its variant property — the only one it declares, or the one passed as
property; several properties without property is a refusal that lists them,
because State=hover and Size=L are both plausible names and one would be a
lie. A frame names states by layer name. States with identical bytes are
reported: a hover that draws exactly like normal is usually a variant that is not
what its name says, and this is the cheapest place to find that out.
figma_export_web_handoff writes the folder a web developer opens:
preview.png (1x) plus preview@Nx.png, spec.json (flat, document order —
every layer's box relative to the frame, text, paints, effects and layout
fields), tokens.json/tokens.css (solid colours named by their paint styles
when one value has one style, fonts, text classes, spacing) and a README.md
that says what the bundle is not: production HTML, responsive layout,
image fills as separate files, gradient tokens, embedded fonts, masks and
effects applied by the CSS, paragraph spacing or vertical alignment. A colour
bound to several styles, a gradient, an
image fill or a mixed text layer is never averaged into an invented value: it
is named as missing, or carried as stops/segments. handoff.json keeps the
hashes and counts, every file is re-read from disk, and one call owns one
folder — it refuses to reuse it for another node. Above 2,500 nodes, 24 MP per
preview or 8 MiB per PNG it refuses rather than truncating; lower the scale or
pick a smaller frame. The 24 MP preflight runs before the rasteriser: a preview
that would take minutes is named, with the largest scale that fits
(pass scale: 1 (6.4 MP)), instead of burning the bridge's timeout. A font that the document uses but the machine cannot load is listed in
the README; it is not assumed present. That check is time-boxed (2 s per
style, 12 s in total), because loading a font this machine does not have is a
network round trip that can take minutes: a style that does not answer in time
is listed separately as unchecked — whether the machine can render it is
unknown, and the bundle says so instead of implying either way. The reply
divides the time by phase — walkMs reading the tree, checkMs the check
above, exportMs rasterising — so a call that took minutes names the phase
that took them; a cold font service lands in exportMs even when the check
already called the style unchecked.
All four are reads of the document (usable with FIGMA_BRIDGE_WRITE=0), and
their files go to outDir, a temp directory by default.
Reading
figma_get_metadatais the cheap way to find ids;figma_inspectgives the structure and a semantic fingerprint;figma_get_layout_treereturns absolute geometry for a whole subtree in one call.figma_download_assetswrites bytes to disk and returns paths — prefer it over moving base64 through the conversation.figma_get_selectionis answered from memory (the plugin pushes selection changes), so it costs no round trip.figma_set_selectionalso pans the viewport, which is the only way to move the user's cursor.figma_comparechecks a render against a PNG on disk (a mockup, an earlier export, another node written out withfigma_download_assets) and reports where it differs, not just whether: differing area, bounding box (in the reference's own pixels), largest clusters, plus a heatmap. It is how a rebuild is proven to have landed instead of eyeballed — and a size mismatch is a finding, while a clean 2×/3×/4× ratio means you passed the wrongscale.
Iterating on a subtree with a baseline
figma_review is the loop tool: save a baseline, edit, compare, repeat. It is
read-only for the document; the baseline and heatmap are local files.
saverenders the node, audits it with the requested rules, and records the semantic fingerprint alongside the PNG and the full audit report:{ action: "save", nodeId, name?, rules?, suggest?, scale? }. The reply has the reviewid, paths and the audit counts. Save before the edit.comparere-renders, re-audits and re-inspects the live node and diffs it against the baseline:{ action: "compare", id? }. With noidit uses the newest baseline for the file. It reportsvisual(bbox, clusters, heatmap),structure.fingerprintEqual,audit.new/resolved/changed, severitydelta,regressions,improvementsandnext.Read
statusbefore anything else:regressedmeans a new error/warning finding or a render-size change;improvedmeans a previous problem is gone;changedis a neutral pixel/structural/finding change;unchangedpermits walking away. Never describe a neutralchangedas an improvement.The baseline's rules,
includeHiddenandsuggestare reused bycompare(and its scale unless you override it), so a delta is not caused by different audit settings. To ask a different audit question, save a new baseline.If
audit.completeis false, the new/resolved lists may be incomplete even though the severity counts are complete; raisemaxFindingsand redo the baseline. A new error/warning may be a previously truncated finding.A capture that sees different
revvalues for image, audit and structure is refused: the three would not describe one state. Retry when the file is quiet.Accept a step by saving a new baseline (the id changes). Keep the old one if you may need to compare against it;
listshows them anddropremoves the PNG, JSON and heatmap.latestis the default.A rebuilt node has a new id: pass
nodeIdtocompare. If the id is gone, the plugin says so; this is not a visual regression.This is not
figma_checkpoint: a review baseline cannot restore a subtree. Usefigma_checkpointbefore a risky rebuild, thenfigma_reviewto judge the result. Usefigma_comparewhen the reference is a mockup rather than an earlier iteration.
A safe loop:
figma_review { action:"save", nodeId }.Apply one guarded edit (
figma_build/figma_patch/figma_batch_edit).figma_review { action:"compare" }; readstatus,regressions,next.If
regressed, fix the named new finding or restore the checkpoint; then compare again. If accepted, save a fresh baseline and continue.
A call that timed out, and the write nobody is waiting for
Writes are chained in the plugin: a write waits behind the write ahead of it. Its caller does not wait that long — and when the caller gives up, the queued write still runs. That is the one case where an edit lands after everyone has stopped watching, so it has its own two tools.
figma_opsanswers "what is still going to write?": per file, the call that isrunning, the writesqueuedbehind it, and what finishedrecently— plus, for this session, the calls it is still waiting for and the ones it gave up on. A timeout error names itsopId: pass that tofigma_opsto get the operation's state and the answer recorded for it. That settles a call that timed out — "it finished at rev 412 with this result" — instead of leaving "may or may not have been applied" standing.figma_cancelstops a call whose state isqueued: nothing of it has run, its caller is answered at once with OP_CANCELLED, and the revision does not move because the document did not. Arunningcall is refused with OP_RUNNING — Figma runs plugin code to the end and nothing can interrupt it from inside the plugin. OP_DONE means it already ran, and the message names the revision.Both are read-only and work in a read-only bridge: cancelling only ever prevents a write, never causes one.
When the process that timed out is gone — or the plugin was reloaded, taking its opId cache with it —
figma_journalis the part of the trail that survives: a local append-only file with every call this bridge sent, itssend/ok/failed/timeout/retry/dropped/latelines, the revision and the target.unsettled: trueshows only the calls that did not end cleanly. It never records code, text or images — method names, target ids, revisions and outcomes only — sofigma_use'sdescriptionis the one place a human note enters it. Edits a human makes in Figma are not in the file, and neither is a call refused before sending: nothing was sent, nothing changed.
Checkpoints — the substitute for an undo stack
Figma's undo barrier is global and one step deep, so "put it back" cannot be a
saved undo step. figma_checkpoint is a description plus a rebuild:
action: "save"records a subtree as data (nodeId; a page is refused) into one JSON file per file key. The reply carries asummaryand thelimitationsa rebuild cannot carry — an INSTANCE's interior structure beyond its direct overrides, component identity, and the identity and existing instances of a component set. Read them before telling anyone the subtree will come back exactly.action: "show"diffs the live subtree against the file field by field and reports the semantic fingerprint next to it. That is how "has this drifted already?" gets answered before a rebuild is chosen.action: "restore"replaces the target's children from the checkpoint in ONE transaction. It is a dry run by default and names what would be deleted and created; a real rebuild needsdryRun: false,allowDestructive: trueand a bridge started withFIGMA_BRIDGE_DESTRUCTIVE=1.An INSTANCE's direct per-layer overrides travel in
state.instance.overrides: a structural path built from the main component's layer names, the fields Figma reports as overridden, a snapshot of the layer and its style/variable links. Restore recreates the instance from its main component, re-applies component properties, then replays each override field by field. A path that no longer matches the main component is named inoverridesMissingand skipped — never applied to whatever now sits at that index.overridesRestoredcounts the ones that landed, and a field this version cannot rebuild is named inoverridesUnsupportedinstead of being dropped. A direct override that changed per-run text styling is replayed range by range: every run font is loaded before the character setter, then sizes, fills, text/fill style links, variable bindings, case, decoration, line height, letter spacing and hyperlinks go back through the range setters. When the override touched range styling, the snapshot is treated as the final state: inherited per-run text/fill style links and range variable bindings are cleared before the snapshot is replayed, so a link or binding the override removed does not survive from the main component. A clear the file refuses is named innotes. The interior's structure itself is still the main component's current structure.STAR and POLYGON are rebuilt natively:
pointCount(and STAR'sinnerRadius) are applied before the final size, and a direct override of those fields is replayed too. ABOOLEAN_OPERATIONtree is rebuilt from its children with the recorded operation (union/subtract/intersect/exclude), including nested operations; fewer than two rebuildable children is named and skipped. ASLICEcomes back with its geometry andexportSettings. ACOMPONENT_SETis rebuilt from its variantCOMPONENTs withfigma.combineAsVariants; non-variant component properties are added back by type and default value, theirSLOTdescription/preferred values/slot settings andINSTANCE_SWAPpreferred values are restored, and a definition-leveldefaultValuevariable binding onBOOLEAN/TEXT/INSTANCE_SWAPis re-linked when the variable exists. Layer-levelcomponentPropertyReferencesare remapped to the new names. Variant options come from the variant names, but component and property ids, component keys and existing instances do not come back. The#idsuffix is assigned by Figma, so verification compares definitions and layer references by display name. A metadata edit or binding the file refuses is named inpropertiesFailed/bindingsMissing; the property and its literal default stay.Style ids, node-level variable bindings and explicit variable modes travel in
meta; per-run text bindings and style ids travel inside the runs. Restore re-links a style, variable, collection or mode when it still exists and reports every one that does not:stylesMissing,bindingsMissingandmodesMissing. The recorded value is written either way, so a missing link leaves a correct-looking but unlinked node instead of a missing colour or size.Paint-level variable bindings travel with the paint. They survive when their variable exists; when it does not, the paint returns by value and
bindingsDroppednames it.Per-run text and fill style ids and text variable bindings travel inside the runs and are re-linked by id when the style or variable still exists; a missing one is reported with the run's path, and the recorded literal value remains. The text style's font is loaded before the range link is applied.
A whole-text hyperlink is saved and restored by value. Mixed per-run links travel inside the runs, so
nullon a run clears it for that range. A NODE link stays file-local.Afterwards the server dumps the subtree again and diffs it against the checkpoint:
verification.verified: truemeans no field differs. When it is false,verification.diffnames every field with both values andverification.notessays which differences checkpoint-v1 knows it causes (HUG sizing, text-run values). Say so — never call a rebuild "restored" when it is not.Refused with a reason: a truncated dump (restoring it would delete whatever the dump never reached), a
GROUP/INSTANCE/ page target, and node types checkpoint-v1 cannot rebuild — unlessallowPartial: true, which rebuilds the rest and lists every skipped node.Recording is cheap: take a checkpoint before a risky rebuild of a subtree, then
showorcompareto judge the result, and keep itsidso a restore is one call away.
The panel
The plugin panel is decoration plus status: the mascot's mood, the status line
and the chips (page, selection, MCP sessions, call count) restate the same
facts in different ways. No task should depend on interpreting the mascot.
Capabilities
Features and capabilities supported by this server
Protocol revision2025-11-25
| Capability | Details |
|---|---|
| tools | {
"listChanged": true
} |
| resources | {
"listChanged": true
} |
Tools
Functions exposed to the LLM to take actions
| Name | Description |
|---|---|
| figma_pingA | Health check and capability report. Verifies the plugin is paired, reports the active page and connected files (fileKey + name), and states what this process can do: local read/write/destructive mode, Motion (Beta) availability and playhead, whether the optional read-only Figma REST adapter is enabled, and the Figma-hosted features even that adapter does not proxy. Call it first when you do not know what is open or whether an operation is available. |
| figma_get_selectionB | Current selection. Answered from memory — the plugin pushes selectionchange, so this costs no round trip into Figma. With several files connected, pass fileKey. |
| figma_inspectA | Inspect a node: compact structure plus its semantic fingerprint. Pass compareWith to get EQUIVALENT / DIFFERENT / INCONCLUSIVE against other nodes BEFORE asking for any mutation. Set includeFingerprint:false when only the structure is needed — the fingerprint walks the whole subtree even at depth 1. |
| figma_whoamiB | Current Figma user, open file (name/key/editor type), pages and viewport. With several files connected, pass fileKey — its reply names the file it actually read. |
| figma_get_metadataA | Sparse XML outline of a node/page/selection: type, id, name, position and size. Cheap; use it to find ids before get_design_context or get_screenshot. |
| figma_get_design_contextB | Full design description of a node for implementing it in code: layout (auto layout, padding, gap, sizing), fills/strokes/effects as hex, text runs with font/size/weight/line-height, style and variable names, component/instance info and properties. |
| figma_get_layout_treeA | Absolute-geometry snapshot of a subtree in ONE call: per node — parent, size, absoluteTransform (2x3 matrix), absolute layout and render bounds, clip flag. Measured in document-absolute space, the same space a PNG export uses, so it is what you check a rebuild or an atlas against instead of one get_node per layer. The screenshot is a SEPARATE call ( |
| figma_get_screenshotB | Render a node as PNG/JPG (returned as an image) or SVG (returned as text). |
| figma_get_variable_defsA | Variables (design tokens) used by a node's subtree, or all local variables when nothing is selected/given. Returns a flat name→value map plus per-mode values. |
| figma_get_librariesC | Variable collections available in this file: local ones and those enabled from team libraries. |
| figma_search_design_systemB | Search components, styles and variables (local file, plus library variable collections) by name/description. All words in the query must match. |
| figma_get_figjamA | Read a FigJam board: stickies, shapes with text, connectors (with endpoints), sections and text. Fails in a regular Figma file. |
| figma_download_assetsC | Export nodes to files on disk (PNG/JPG/SVG/PDF) and return the paths. |
| figma_get_code_connect_mapB | Local Code Connect mapping stored on a node (and on its main component for instances). Stored in this file's shared plugin data; not synced with Figma's cloud Code Connect. |
| figma_set_selectionA | Select nodes in the Figma editor and scroll them into view. The only way to move the user's cursor — use it to hand work over ('look at what I just built') instead of making them hunt for it on a huge canvas. Editor state only; the document is not modified. |
| figma_set_pageA | Switch the Figma editor to another page. Editor state only; the document is not modified. |
| figma_list_file_components_for_code_connectA | Every component and component set in the file, with ids, names, page and size — the inventory you need before wiring up Code Connect mappings. |
| figma_get_font_inventoryA | Which fonts the file actually uses, counted by text node (family / style). Consistency work needs this: a design system that claims one typeface and quietly uses three is the usual failure. |
| figma_useA | Run Plugin API JavaScript inside the open Figma file (async function body; |
| figma_upload_assetsA | Import local image files (PNG/JPG/GIF/WEBP) into Figma as rectangles with an image fill, or apply one as the fill of an existing node. |
| figma_add_code_connect_mapC | Attach a local Code Connect mapping (source file + component name) to a node. Stored in shared plugin data in this file. |
| figma_compareA | Render a node and diff it against a PNG on disk — a mockup, an earlier export, or another node exported with figma_download_assets. Reports the differing area, its bounding box in the reference's own pixels (top-left origin, so a box can be cropped straight out of that PNG) and the largest clusters, and writes a heatmap. Anti-aliasing is absorbed by |
| figma_reviewA | A reproducible iteration harness for one subtree: save a visual + audit + structure baseline, edit, then compare the live node and see exactly what changed. action "save" writes a local PNG plus the audit findings and the semantic fingerprint. "compare" re-renders, re-audits and re-inspects, diffs the pixels, and reports new/resolved/changed findings, severity deltas, size/fingerprint changes and a verdict: unchanged, changed, improved or regressed. A new error/warning or a size change is a regression; resolved problems are an improvement; a visual or structural difference without either is a neutral change. The document is never written: only local review files. Use |
| figma_checkpointA | Save a subtree as data, compare it against the live document, and rebuild it — the alternative to an undo stack the Plugin API does not offer. action "save" writes an inspectable JSON file; "show" diffs the live subtree against it; "restore" replaces the target's children from it in ONE transaction, dry run first, and verifies itself by dumping the subtree again. Refuses what it cannot promise: node types it cannot rebuild, truncated dumps, a group or instance target, and any restore not asked for out loud. STAR and POLYGON are rebuilt natively with their point count (and STAR's inner radius); BOOLEAN_OPERATION trees are rebuilt from their children with the recorded operation; SLICE nodes come back with their geometry and exportSettings; COMPONENT_SETs are rebuilt from their variant components, with non-variant properties added back by type and default value, their supported metadata and default-value variable bindings restored, and layer references remapped, while other unsupported node types are still refused by name. A save says what a checkpoint-v1 rebuild does not carry (an INSTANCE's interior structure beyond its direct overrides, and component and component-set identity/instances); direct per-layer overrides are captured and replayed by path after the main component is re-instantiated, including per-run text styling inside an overridden text layer, where a link or binding the override removed is cleared before the run snapshot is replayed, and style ids and node-level and run-level variable bindings are re-linked when still present. Every missing link or stale override path is reported. |
| figma_opsA | What the Figma plugin is doing right now, per file: the call that is RUNNING, the writes QUEUED behind it, and what finished recently — plus, for this MCP session, the calls it is still waiting for and the ones it gave up on. Pass an opId (timeout errors name it) to get that operation's state and its recorded answer, which is how a call that timed out is settled without re-reading the document. Read-only. |
| figma_cancelA | Stop a Figma operation that has NOT started (state |
| figma_export_ui_atlasA | Export a sprite sheet for a game build: ONE PNG plus a JSON manifest whose rects are in that PNG's own pixels. The sheet frame's DIRECT children are the sprites; nothing is repacked, so the layout stays the designer's. The manifest names what would make the sheet unsliceable — overlapping rects, sprites off the image, drawing that bleeds out of its cell, repeated names, coordinates that had to be rounded — and the file is re-read from disk afterwards to check the manifest describes it. Returns the rects, so the caller can wire an engine up without opening the file. |
| figma_export_9sliceA | Export one sprite with its 9-slice insets: a PNG plus a descriptor (insets in the file's pixels, the stretchable middle, and CSS |
| figma_export_ui_statesB | Export the states of a button/component as one file per state, plus a manifest naming them. A COMPONENT_SET names its variants by property (the only property, or the one you pass as |
| figma_export_web_handoffA | Write a web handoff bundle for one frame: preview.png (1x), an optional preview@Nx.png, spec.json with every layer's absolute box, text, paints and effects, tokens.json and tokens.css (colours, fonts, text classes, spacing), a README that states what the bundle does NOT carry, and handoff.json with hashes and counts. One call writes one folder and every file is re-read from disk. Read-only for the document — it works with write access off. Refuses above 2,500 nodes, 24 MP per preview or 8 MiB per PNG instead of truncating; font availability is checked within a time budget, and a font the check could not confirm is reported as unchecked, not assumed present. The reply separates the phases by time — walkMs reading the tree, checkMs pinging fonts, exportMs rasterising — so a call that took minutes names the phase that took them. This is a specification, not generated production HTML. |
| figma_journalA | The bridge's own history, from a local append-only JSONL file: every call it sent to a Figma plugin — method, target, outcome, revision — and above all the ones that did not end cleanly: |
| figma_buildA | Create or update a declarative, keyed UI tree in ONE transaction. The spec is validated and resolved (fonts, styles, local variables, components) before anything is written; every node gets a stable key in pluginData, so re-sending the same buildId updates instead of duplicating. dryRun defaults to TRUE and returns a real plan plus a scope fingerprint. Pass dryRun:false with that fingerprint to apply. An existing root with the same buildId is patched in place; prune:true makes the tree exact by deleting keyed children the spec no longer contains. An SVG leaf is created as a frame; re-sending it updates that frame in place, and a changed svg source replaces its interior while keeping the id and key. A BOOLEAN_OPERATION is created from at least two operands in spec order (first operand is the subtract/intersect base) and can change its operation in place; its size is derived from the operands and is ignored. A PATTERN paint resolves its file-local source node id before writing and is refused when that node is missing. A SHADER paint must resolve to an available fill shader; an unimported shader is imported inside the write transaction. Refuses type changes, ambiguous component names, unknown keys, position inside auto-layout, component swaps, and unsupported node types. |
| figma_patchA | Update an existing keyed tree by stable key, in ONE transaction. A dry run is a real diff: it reports create/update/delete counts and a scope fingerprint without writing. Missing keys are refused unless allowCreate:true; a key that lives under a different parent is refused rather than duplicated; prune:true deletes keyed children omitted from the patch at each patched level. An SVG leaf keeps its frame id and key while a changed svg source replaces its interior. A BOOLEAN_OPERATION patch may list only the operands it changes when prune is false; pruning a boolean requires at least two operands in the patch. A sparse boolean patch keeps the existing operand order and appends a new operand; send the complete ordered list with prune:true to enforce order. Text updates load their fonts before writing, and any failure rolls the whole patch back. Target with rootNodeId, buildId or rootKey. |
| figma_batch_editA | Apply many small edits to many targets in ONE undo transaction, after resolving every target, font, style and component property in a dry run. Targets are nodeId or stable key; a key is the better identity because it survives node re-creation. Ops: set_text, set_name/rename, set_fill, set_stroke, resize, move, set_visible, set_opacity, set_rotation, set_layout, set_variant, set_constraints, duplicate, reparent. duplicate and reparent accept a destination parentId or parentKey; the key is resolved on the current page. dryRun defaults to TRUE and returns per-op plans plus a fingerprint per target and per non-page destination; apply with dryRun:false and the same expectedFingerprints. A reparent index is the final child index; omitted appends. A same-parent reorder keeps layoutPositioning unchanged. A failed op rolls the whole batch back unless stopOnError:false, which reports partial success and exactly which op failed. |
| figma_swap_componentA | Swap one or more INSTANCEs to another main component in ONE transaction, preserving the overrides that still fit. The dry run (default) compares the old and new structures and returns, per target: a fingerprint of the instance and the target component, an exact or name-remapped path for every direct layer override, mapped component properties (by display name and type), root-level instance overrides (custom name, resized geometry, opacity, fills/strokes/effects and style links, layout placement) and every named loss. Apply with the returned planId and expectedFingerprints; it refuses a document that moved, a lossy swap unless allowLoss:true, and a library component whose structure could not be checked unless allowUnverified:true. Variant properties are not replayed — the chosen target component decides them. A layer whose node type changed, a missing layer, a changed nested component and a SLOT property are reported, never applied to a guessed layer. A target nested inside another INSTANCE is refused: that is an override of the outer instance, not an independent swap. The apply is one undo step; a failure rolls the whole call back, and the report says what rolled back. Plugin API swapComponent is the mechanism; Figma's own override heuristics are re-checked, not trusted. |
| figma_variant_setA | Author a COMPONENT_SET as a property matrix in ONE transaction. action "combine" turns standalone COMPONENTs into a new set (names are replaced by the requested variant names), "add" clones an existing variant with a new property combination, and "edit" renames one variant in place. The dry run (default) validates the whole matrix: every variant has the same property names, no combination is duplicated, the destination is not an INSTANCE, another set or a COMPONENT definition, and a combine destination is not inside one of its own variants. It returns per-component and per-set fingerprints plus the destination layout, so a changed document is refused before writing. Apply with the returned planId and expectedFingerprints; it is one undo transaction. After writing, component names are read back as variantProperties and the set matrix is verified — a Figma that did not accept the name is rolled back, not reported as a success; if the undo itself fails, the error says ROLLBACK FAILED. Components already in a set are refused by combine; components inside an INSTANCE are refused. A combine destination inside a COMPONENT is refused because Figma will not reparent a component into a component definition; add and edit still operate on an existing set. |
| figma_auditA | Read-only design-system audit of a page or subtree. Reports stable-key problems (duplicate keys, nodes added to a built tree without a key), literal fills/strokes that are neither a style nor a variable, text without a text style, placeholder copy, detached instances, WCAG AA contrast against the effective background, default layer names, and (opt-in) empty text, literal effects, off-scale spacing and off-scale radius. Every finding carries nodeId, stable key, name, type, path, rule, severity and the value that caused it. With suggest:true (default) a hardcoded colour also carries exact local paint-style and colour-variable candidates, and unstyled text carries exact local text-style candidates; spacing/radius findings name the nearest on-scale value. It never edits the document. |
| figma_indexA | A compact flat index of a page or subtree, in document order: id, stable key, name, type, path, depth, visibility, size, child count, and the build root when the node is inside a figma_build/patch tree. Use it to find the shape of a page before inspecting one subtree. Read-only; stops at maxNodes and says so rather than returning a partial index that looks complete. |
| figma_searchA | Find nodes by name, stable key or text without fetching the whole tree. Substring (default), regex or glob matching; filter by node type, key prefix, hasKey, or use no query with a filter. Returns compact node records with path, matched fields, a text snippet, build root and size. Read-only; maxNodes and maxResults are reported when hit. |
| figma_design_systemA | Export or diff the file's local design system as one comparable snapshot: paint/text/effect/grid styles, variable collections with modes and per-mode values, and components/component sets with their property definitions. "inventory" returns the snapshot; "export" writes it to a JSON file and returns the path, byte count and sha256; "diff" compares that file with the live file and reports added/removed/changed by stable key, not by name. Read-only: it never creates or changes a style, variable or component. |
| figma_tokensA | Export, diff or sync the file's local variables as a design-token document. "export" writes figma-tokens/v1 with every collection, mode, value, description and alias; "diff" compares a document with the live file; "import" (dry run by default) creates missing collections, modes and variables, updates values/descriptions, and verifies every mode after writing. A plain DTCG tree is accepted on import with collection/mode (default Tokens / Mode 1); supported types are color, number, dimension (px is dropped into a unitless FLOAT), string, boolean, fontFamily and fontWeight. Unsupported DTCG types block the import instead of being dropped. Import is one undo transaction and requires the fingerprint from a dry run plus the planId; a changed file or changed live variables is refused before writing. A remote/library alias carries remote:true and its live variable id; only an unchanged binding is preserved, never rebound by name. prune is off by default and, when enabled, deletes only variables in the named collections and only with allowDestructive:true; aliases pointing at a pruned variable block the plan. Modes that the document does not name are preserved for existing variables and filled from the default managed mode for new variables, with that fact in the plan. |
| figma_export_build_specA | Turn a live subtree into a figma_build spec. Keys that are already stored are kept; nodes without one get the same derived key the build engine would choose. Fills, strokes and effects use styles or variables when the node is linked to them, and plain values otherwise; rotation, per-corner radii, stroke shape, layout grids, LINE length and text formatting are carried. A BOOLEAN_OPERATION is exported as a live boolean with its operation and ordered operands, not as a flattened SVG. A PATTERN paint carries its file-local source node id and tiling fields; a SHADER paint carries its shader id and property assignments. A node the build cannot express — an unsupported type, a frame created from SVG, a detached instance — is exported as an inline SVG render when svgFallback is on (the default): its appearance survives, but the rebuild is a flattened frame with no original child layers, component identity, overrides, style or variable links and with text outlined, and every fallback is named in warnings. Slices are never flattened. The reply is deliberately lossy and says where: mixed fonts and unrepresentable paints are listed under unsupported/warnings, and direct instance overrides travel as paths plus the fields a rebuild can express while unsupported override fields are named. Read-only; never modifies the file. A truncated export is marked truncated and must not be built as-is. |
| figma_motion_stylesA | Read-only Motion (Beta) catalogue: Figma animation styles and local custom animation styles, plus the animation playhead position. Every entry carries the id to pass to figma_motion_apply_style. On a Figma build without the Motion API this fails with MOTION_UNAVAILABLE; it does not return an empty catalogue that looks like a file with no styles. |
| figma_motion_inspectA | Read-only Motion (Beta) state of one node: applied animation styles, manual keyframe tracks, computed animations, timelines and which node-level Motion methods this build exposes. Use it before any Motion write; the ids and track shapes it returns are the inputs to the write tools. |
| figma_motion_apply_styleA | Apply a Figma or custom animation style to a node (Motion Beta). dryRun defaults to TRUE and returns a planId plus the node's current styles/timelines. Apply with dryRun:false and that planId: the plugin re-reads the node, refuses a changed state, then verifies the applied style id, duration, offset and props by reading them back; any mismatch rolls the transaction back. A custom style accepts only timelineOffset, not duration or props. |
| figma_motion_remove_styleA | Remove one applied animation style by its applied instance id (not the style definition id) from a node (Motion Beta). dryRun defaults to TRUE. Removing a style that is not present is a verified no-op, not an error. Apply verifies the id is gone after the write and rolls back otherwise. |
| figma_motion_set_keyframesA | Set one manual keyframe track on a node (Motion Beta): a property such as OPACITY/TRANSLATION_X/SCALE_XY, a paint/stroke, or an effect field. The track carries baseValue and keyframes with timelinePosition in seconds; positions must be unique and all values in one track must share a type. dryRun defaults to TRUE; apply re-reads and verifies every keyframe's position, value and easing, then rolls back on any mismatch. This writes Motion data; it never fabricates a local animation. |
| figma_motion_remove_keyframesA | Remove the manual keyframe track on one field of a node (Motion Beta). dryRun defaults to TRUE and reports the current track. Removing an absent track is a verified no-op. Apply verifies the field no longer has a manual track and rolls back otherwise. |
| figma_motion_set_durationA | Set a Motion timeline's duration in seconds (Motion Beta). Pass the timeline id from figma_motion_inspect; the node must list that timeline. dryRun defaults to TRUE. Apply reads the timeline back and rolls back if Figma reports a different duration or the timeline disappears. |
| figma_replace_repeated_with_componentA | Replace a repeated group of identical nodes with instances of one master component, in a single transactional call. Refuses to act unless every target is provably equivalent (COUNT_MISMATCH / TARGETS_NOT_EQUIVALENT / TARGETS_NOT_PROVABLE all abort with mutated:false). Verifies placement afterwards and rolls back on failure. Run with dryRun:true first. |
Prompts
Interactive templates invoked by user choice
| Name | Description |
|---|---|
No prompts | |
Resources
Contextual data attached and managed by the client
| Name | Description |
|---|---|
| guide | How to drive the bridge: fileKey rules, rev/replayed, what may be retried, guarded edits, figma_review baselines, figma_use scope and rollback, write gating. |
| skill:SKILL.md | figma-local-bridge skill (short playbook): first call, read-before-write, guarded edits, flb helpers, Code Mode recipes. |
| skill:assets/prelude.js | Safe-snippet prelude (plain JS, no import/require): paste at the top of every figma_use code string — validated colour tokens, font loading, frame sizing order, PaintStyle.paints, async style/node getters. |
TDQS
Scored across 50 tools
The descriptions go out of their way to separate near-neighbours (inspect vs get_design_context vs get_metadata vs get_layout_tree; build vs patch vs batch_edit vs use; compare vs review vs checkpoint), each stating when to prefer it and what the other costs. Residual overlap remains: an agent can plausibly pick figma_build when it wants figma_patch, or figma_inspect when it wants figma_get_design_context, and the declarative-write family plus the six Motion tools create real misselection risk. Boundaries are mostly clear, but the density of similar read/export tools keeps it short of a 5.
Names are uniformly snake_case under a single figma_ prefix and mostly follow verb_noun (get_screenshot, set_selection, export_ui_atlas, download_assets, search_design_system). Deviations are the bare one-word names (figma_use, figma_ping, figma_whoami, figma_ops, figma_journal, figma_checkpoint, figma_tokens), which are less self-describing, and the long outlier figma_list_file_components_for_code_connect. Still predictable overall, with only minor inconsistencies.
Fifty tools is very heavy for an MCP surface even given the breadth of the domain (reads, inspections, transactional writes, exports, tokens, Motion, Code Connect, diagnostics). Several families are internally redundant in count — six Motion tools, four export_* tools, five inspection tools — and an agent must carry a large decision table just to choose a call. Each tool is justified in isolation, but the aggregate is over-scoped for reliable selection.
Coverage is unusually thorough: read/inspect/search/index, verified transactional writes (build, patch, batch_edit, swap_component, variant_set, use), export in many formats, tokens/design-system export+import+diff, Motion, Code Connect, and self-diagnostics (ops, cancel, journal). Gaps are minor and workable: there is no explicit node-delete op (deletion only via prune in build/patch), and nothing for comments/annotations, prototyping interactions, or component-creation outside a variant matrix. Agents can route around these, so no dead ends of consequence.