figma-use by figma/mcp-server-guide
npx skills add https://github.com/figma/mcp-server-guide --skill figma-use使用 use_figma MCP 通过插件 API 在 Figma 文件中执行 JavaScript。所有详细的参考文档位于 references/ 目录中。
调用 use_figma 时,务必传递 skillNames: "figma-use"。 这是一个用于追踪技能使用情况的日志参数——它不影响执行。
如果任务涉及从代码构建或更新 Figma 中的完整页面、屏幕或多区域布局,请同时加载 figma-generate-design。它提供了通过 search_design_system 发现设计系统组件、导入它们并逐步组装屏幕的工作流程。这两个技能协同工作:本技能用于 API 规则,另一个用于屏幕构建工作流程。
在开始之前,请先加载 plugin-api-standalone.index.md 以了解可以实现的功能。当被要求编写插件 API 代码时,请使用此上下文来 grep plugin-api-standalone.d.ts 以查找相关类型、方法和属性。这是 API 表面的权威信息来源。它是一个大型类型定义文件,因此不要一次性全部加载,根据需要 grep 相关部分。
重要提示:每当处理设计系统时,请从 开始,以了解在 Figma 中处理设计系统的关键概念、流程和指南。然后根据需要加载更具体的组件、变量、文本样式和效果样式参考文档。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
return 返回数据。 返回值会自动进行 JSON 序列化(对象、数组、字符串、数字)。请勿调用 figma.closePlugin() 或将代码包装在异步 IIFE 中——这已为您处理。await 和 return 的纯 JavaScript。 代码会自动包装在异步上下文中。请勿包装在 (async () => { ... })() 中。figma.notify() 会抛出 "not implemented" 错误——永远不要使用它。3a. getPluginData() / setPluginData() 在 use_figma 中不受支持——不要使用它们。请改用 getSharedPluginData() / setSharedPluginData()(这些是受支持的),或者通过返回节点 ID 并将其传递给后续调用来跟踪节点 ID。console.log() 不会被返回——使用 return 进行输出。use_figma 调用。每一步之后进行验证。这是避免错误的最重要实践。{r: 1, g: 0, b: 0} = 红色。await figma.loadFontAsync({family, style})。await figma.setCurrentPageAsync(page) 来切换页面并加载其内容(见下文页面规则)。setBoundVariableForPaint 返回一个新的 paint 对象——必须捕获并重新赋值。createVariable 接受集合对象或 ID 字符串(推荐使用对象)。layoutSizingHorizontal/Vertical = 'FILL' 必须在 parent.appendChild(child) 之后设置——在追加之前设置会抛出错误。对于非自动布局节点,'HUG' 同理。figma.currentPage.children 以找到一个清晰的位置(例如,在最右侧节点的右侧)。这仅适用于页面级节点——嵌套在其他框架或自动布局容器内的节点由其父级定位。参见 Gotchas。use_figma 出错时,停止。不要立即重试。 失败的脚本是原子性的——如果脚本出错,它根本不会执行,也不会对文件进行任何更改。仔细阅读错误信息,修复脚本,然后重试。参见错误恢复。return 所有创建/修改的节点 ID。 每当脚本在画布上创建新节点或修改现有节点时,收集每个受影响的节点 ID,并在结构化对象中返回它们(例如 return { createdNodeIds: [...], mutatedNodeIds: [...] })。这对于后续调用以引用、验证或清理这些节点至关重要。variable.scopes。 默认的 ALL_SCOPES 会污染每个属性选择器——这几乎从来都不是你想要的。使用特定的作用域,例如背景用 ["FRAME_FILL", "SHAPE_FILL"],文本颜色用 ["TEXT_FILL"],间距用 ["GAP"] 等。完整列表参见 variable-patterns.md。await 每一个 Promise。 永远不要让 Promise 处于未等待状态——未等待的异步调用(例如没有 await 的 figma.loadFontAsync(...),或者没有 await 的 figma.setCurrentPageAsync(page))将会“发射后不管”,导致静默失败或竞态条件。脚本可能在异步操作完成之前返回,导致数据丢失或更改未完全应用。关于每条规则的详细错误/正确示例,请参见 Gotchas & Common Mistakes。
页面上下文在 use_figma 调用之间重置——每次开始时 figma.currentPage 都位于第一页。
使用 await figma.setCurrentPageAsync(page) 来切换页面并加载其内容。同步设置器 figma.currentPage = page 在 use_figma 运行时中会抛出错误。
// 切换到特定页面(加载其内容)
const targetPage = figma.root.children.find((p) => p.name === "My Page");
await figma.setCurrentPageAsync(targetPage);
// targetPage.children 现在已填充
// 遍历所有页面
for (const page of figma.root.children) {
await figma.setCurrentPageAsync(page);
// page.children 现在已加载——在此处读取或修改它们
}
figma.currentPage 在每次 use_figma 调用开始时重置为第一页。如果你的工作流程跨越多个调用并针对非默认页面,请在每次调用开始时调用 await figma.setCurrentPageAsync(page)。
你可以多次调用 use_figma 来增量构建文件状态,或者在编写另一个脚本之前检索信息。例如,编写一个脚本来获取现有节点的元数据,return 该数据,然后在后续脚本中使用它来修改这些节点。
return 是你的输出通道代理只能看到你 return 的值。其他所有内容都是不可见的。
return { createdNodeIds: [...], mutatedNodeIds: [...] }。这是一个硬性要求,不是可选的。return { createdNodeIds: [...], count: 5, errors: [] }throw。console.log() 的输出永远不会返回给代理。use_figma 在设计模式下工作(editorType "figma",默认值)。FigJam("figjam")有一套不同的可用节点类型——大多数设计节点在那里被阻止。
设计模式下可用:Rectangle、Frame、Component、Text、Ellipse、Star、Line、Vector、Polygon、BooleanOperation、Slice、Page、Section、TextPath。
设计模式下被阻止:Sticky、Connector、ShapeWithText、CodeBlock、Slide、SlideRow、Webpage。
最常见的错误原因是在单个 use_figma 调用中尝试做太多事情。以小步骤工作,并在每一步之后进行验证。
use_figma 来发现文件中已存在的内容——页面、组件、变量、命名约定。匹配已有的内容。return(例如 return { createdNodeIds: [...] })。你将需要这些作为后续调用的输入。get_metadata 验证结构(计数、名称、层次结构、位置)。在主要里程碑之后使用 get_screenshot 来发现视觉问题。步骤 1:检查文件——发现现有页面、组件、变量、约定
步骤 2:创建令牌/变量(如果需要)
→ 使用 get_metadata 验证
步骤 3:创建单个组件
→ 使用 get_metadata + get_screenshot 验证
步骤 4:从组件实例组合布局
→ 使用 get_screenshot 验证
步骤 5:最终验证
| 在...之后 | 使用 get_metadata 检查 | 使用 get_screenshot 检查 |
|---|---|---|
| 创建变量 | 集合计数、变量计数、模式名称 | — |
| 创建组件 | 子节点计数、变体名称、属性定义 | 变体可见、未折叠、网格可读 |
| 绑定变量 | 节点属性反映绑定 | 颜色/令牌正确解析 |
| 组合布局 | 实例节点具有 mainComponent,层次结构正确 | 无裁剪/截断的文本,无重叠元素,间距正确 |
use_figma 是原子性的——失败的脚本不会执行。 如果脚本出错,不会对文件进行任何更改。文件保持与调用前相同的状态。这意味着没有部分节点,没有来自失败脚本的孤立元素,修复后重试是安全的。
use_figma 返回错误时get_metadata 或 get_screenshot 来了解当前文件状态。| 错误信息 | 可能原因 | 如何修复 |
|---|---|---|
"not implemented" | 使用了 figma.notify() | 移除它——使用 return 进行输出 |
"node must be an auto-layout frame..." | 在追加到自动布局父级之前设置了 FILL/HUG | 将 appendChild 移到 layoutSizingX = 'FILL' 之前 |
"Setting figma.currentPage is not supported" | 使用了同步页面设置器 | 使用 await figma.setCurrentPageAsync(page) |
| 属性值超出范围 | 颜色通道 > 1(使用了 0–255 而不是 0–1) | 除以 255 |
"Cannot read properties of null" | 节点不存在(错误的 ID,错误的页面) | 检查页面上下文,验证 ID |
| 脚本挂起 / 无响应 | 无限循环或未解决的 promise | 检查 while(true) 或缺少 await;确保代码终止 |
"The node with id X does not exist" | 父实例被子节点的 detachInstance() 隐式分离,改变了 ID | 从稳定(非实例)的父框架开始遍历,重新发现节点 |
get_metadata 检查结构正确性(层次结构、计数、位置)。get_screenshot 检查视觉正确性。仔细查看是否有裁剪/截断的文本(行高切断内容)和重叠元素——这些很常见且容易被忽略。完整的验证工作流程,请参见 Validation & Error Recovery。
在提交任何 use_figma 调用之前,请验证:
return 返回数据(不是 figma.closePlugin())return 值包含带有可操作信息的结构化数据(ID、计数)figma.notify()console.log() 作为输出(改用 return)await figma.setCurrentPageAsync(page)(同步设置器会抛出错误)layoutSizingVertical/Horizontal = 'FILL' 在 parent.appendChild(child) 之后设置loadFontAsync() 在任何文本属性更改之前调用lineHeight/letterSpacing 使用 {unit, value} 格式(不是裸数字)resize() 在设置尺寸模式之前调用(resize 会将它们重置为 FIXED)return 值中loadFontAsync、setCurrentPageAsync、importComponentByKeyAsync 等)都进行了 await——没有“发射后不管”的 Promise在创建任何内容之前,始终检查 Figma 文件。 不同的文件使用不同的命名约定、变量结构和组件模式。你的代码应该匹配已有的内容,而不是强加新的约定。
当对任何约定(命名、作用域、结构)有疑问时,先检查 Figma 文件,然后检查用户的代码库。只有当两者都不存在时,才退回到常见模式。
列出所有页面和顶层节点:
const pages = figma.root.children.map(p => `${p.name} id=${p.id} children=${p.children.length}`);
return pages.join('\n');
列出所有页面中的现有组件:
const results = [];
for (const page of figma.root.children) {
await figma.setCurrentPageAsync(page);
page.findAll(n => {
if (n.type === 'COMPONENT' || n.type === 'COMPONENT_SET')
results.push(`[${page.name}] ${n.name} (${n.type}) id=${n.id}`);
return false;
});
}
return results.join('\n');
列出现有的变量集合及其约定:
const collections = await figma.variables.getLocalVariableCollectionsAsync();
const results = collections.map(c => ({
name: c.name, id: c.id,
varCount: c.variableIds.length,
modes: c.modes.map(m => m.name)
}));
return results;
根据任务需要加载这些文档:
| 文档 | 何时加载 | 涵盖内容 |
|---|---|---|
| gotchas.md | 在任何 use_figma 之前 | 每个已知的陷阱,带有错误/正确的代码示例 |
| common-patterns.md | 需要工作代码示例 | 脚本脚手架:形状、文本、自动布局、变量、组件、多步骤工作流程 |
| plugin-api-patterns.md | 创建/编辑节点 | 填充、描边、自动布局、效果、分组、克隆、样式 |
| api-reference.md | 需要确切的 API 表面 | 节点创建、变量 API、核心属性、什么有效什么无效 |
| validation-and-recovery.md | 多步骤写入或错误恢复 | get_metadata 与 get_screenshot 工作流程,强制性的错误恢复步骤 |
| component-patterns.md | 创建组件/变体 | combineAsVariants、组件属性、INSTANCE_SWAP、变体布局、发现现有组件、元数据遍历 |
| variable-patterns.md | 创建/绑定变量 | 集合、模式、作用域、别名、绑定模式、发现现有变量 |
| text-style-patterns.md | 创建/应用文本样式 | 字体阶梯、字体探测、列出样式、将样式应用于节点 |
| effect-style-patterns.md | 创建/应用效果样式 | 投影、列出样式、将样式应用于节点 |
| plugin-api-standalone.index.md | 需要了解完整的 API 表面 | 插件 API 中所有类型、方法和属性的索引 |
| plugin-api-standalone.d.ts | 需要确切的类型签名 | 完整的类型定义文件——grep 特定符号,不要一次性全部加载 |
你将在此处的文档中看到代码片段。这些片段包含有用的插件 API 代码,可以重新利用。按原样使用它们,或者作为你前进过程中的起始代码。如果有最好作为通用代码片段记录的关键概念,请将它们提取出来并写入磁盘,以便将来重用。
每周安装次数
221
仓库
GitHub 星标数
540
首次出现
2 天前
安全审计
安装在
opencode215
codex206
gemini-cli204
github-copilot204
amp204
kimi-cli204
Use use_figma MCP to execute JavaScript in Figma files via the Plugin API. All detailed reference docs live in references/.
Always passskillNames: "figma-use" when calling use_figma. This is a logging parameter used to track skill usage — it does not affect execution.
If the task involves building or updating a full page, screen, or multi-section layout in Figma from code , also load figma-generate-design. It provides the workflow for discovering design system components via search_design_system, importing them, and assembling screens incrementally. Both skills work together: this one for the API rules, that one for the screen-building workflow.
Before anything, load plugin-api-standalone.index.md to understand what is possible. When you are asked to write plugin API code, use this context to grep plugin-api-standalone.d.ts for relevant types, methods, and properties. This is the definitive source of truth for the API surface. It is a large typings file, so do not load it all at once, grep for relevant sections as needed.
IMPORTANT: Whenever you work with design systems, start with working-with-design-systems/wwds.md to understand the key concepts, processes, and guidelines for working with design systems in Figma. Then load the more specific references for components, variables, text styles, and effect styles as needed.
return to send data back. The return value is JSON-serialized automatically (objects, arrays, strings, numbers). Do NOT call figma.closePlugin() or wrap code in an async IIFE — this is handled for you.await and return. Code is automatically wrapped in an async context. Do NOT wrap in (async () => { ... })().figma.notify() throws "not implemented" — never use it 3a. getPluginData() / setPluginData() are not supported in use_figma — do not use them. Use / instead (these ARE supported), or track node IDs by returning them and passing them to subsequent calls.For detailed WRONG/CORRECT examples of each rule, see Gotchas & Common Mistakes.
Page context resets betweenuse_figma calls — figma.currentPage starts on the first page each time.
Use await figma.setCurrentPageAsync(page) to switch pages and load their content. The sync setter figma.currentPage = page throws an error in use_figma runtimes.
// Switch to a specific page (loads its content)
const targetPage = figma.root.children.find((p) => p.name === "My Page");
await figma.setCurrentPageAsync(targetPage);
// targetPage.children is now populated
// Iterate over all pages
for (const page of figma.root.children) {
await figma.setCurrentPageAsync(page);
// page.children is now loaded — read or modify them here
}
figma.currentPage resets to the first page at the start of each use_figma call. If your workflow spans multiple calls and targets a non-default page, call await figma.setCurrentPageAsync(page) at the start of each invocation.
You can call use_figma multiple times to incrementally build on the file state, or to retrieve information before writing another script. For example, write a script to get metadata about existing nodes, return that data, then use it in a subsequent script to modify those nodes.
return Is Your Output ChannelThe agent sees ONLY the value you return. Everything else is invisible.
return { createdNodeIds: [...], mutatedNodeIds: [...] }. This is a hard requirement, not optional.return { createdNodeIds: [...], count: 5, errors: [] }throw explicitly.console.log() output is never returned to the agentuse_figma works in design mode (editorType "figma", the default). FigJam ("figjam") has a different set of available node types — most design nodes are blocked there.
Available in design mode: Rectangle, Frame, Component, Text, Ellipse, Star, Line, Vector, Polygon, BooleanOperation, Slice, Page, Section, TextPath.
Blocked in design mode: Sticky, Connector, ShapeWithText, CodeBlock, Slide, SlideRow, Webpage.
The most common cause of bugs is trying to do too much in a single use_figma call. Work in small steps and validate after each one.
use_figma to discover what already exists in the file — pages, components, variables, naming conventions. Match what's there.return created node IDs, variable IDs, collection IDs as objects (e.g. return { createdNodeIds: [...] }). You'll need these as inputs to subsequent calls.get_metadata to verify structure (counts, names, hierarchy, positions). Use get_screenshot after major milestones to catch visual issues.Step 1: Inspect file — discover existing pages, components, variables, conventions
Step 2: Create tokens/variables (if needed)
→ validate with get_metadata
Step 3: Create individual components
→ validate with get_metadata + get_screenshot
Step 4: Compose layouts from component instances
→ validate with get_screenshot
Step 5: Final verification
| After... | Check with get_metadata | Check with get_screenshot |
|---|---|---|
| Creating variables | Collection count, variable count, mode names | — |
| Creating components | Child count, variant names, property definitions | Variants visible, not collapsed, grid readable |
| Binding variables | Node properties reflect bindings | Colors/tokens resolved correctly |
| Composing layouts | Instance nodes have mainComponent, hierarchy correct | No cropped/clipped text, no overlapping elements, correct spacing |
use_figma is atomic — failed scripts do not execute. If a script errors, no changes are made to the file. The file remains in the same state as before the call. This means there are no partial nodes, no orphaned elements from the failed script, and retrying after a fix is safe.
use_figma returns an errorget_metadata or get_screenshot to understand the current file state.| Error message | Likely cause | How to fix |
|---|---|---|
"not implemented" | Used figma.notify() | Remove it — use return for output |
"node must be an auto-layout frame..." | Set FILL/HUG before appending to auto-layout parent | Move appendChild before layoutSizingX = 'FILL' |
get_metadata to check structural correctness (hierarchy, counts, positions).get_screenshot to check visual correctness. Look closely for cropped/clipped text (line heights cutting off content) and overlapping elements — these are common and easy to miss.For the full validation workflow, see Validation & Error Recovery.
Before submitting ANY use_figma call, verify:
return to send data back (NOT figma.closePlugin())return value includes structured data with actionable info (IDs, counts)figma.notify() anywhereconsole.log() as output (use return instead)await figma.setCurrentPageAsync(page) (sync setter throws)layoutSizingVertical/Horizontal = 'FILL' is set AFTER parent.appendChild(child)Always inspect the Figma file before creating anything. Different files use different naming conventions, variable structures, and component patterns. Your code should match what's already there, not impose new conventions.
When in doubt about any convention (naming, scoping, structure), check the Figma file first, then the user's codebase. Only fall back to common patterns when neither exists.
List all pages and top-level nodes:
const pages = figma.root.children.map(p => `${p.name} id=${p.id} children=${p.children.length}`);
return pages.join('\n');
List existing components across all pages:
const results = [];
for (const page of figma.root.children) {
await figma.setCurrentPageAsync(page);
page.findAll(n => {
if (n.type === 'COMPONENT' || n.type === 'COMPONENT_SET')
results.push(`[${page.name}] ${n.name} (${n.type}) id=${n.id}`);
return false;
});
}
return results.join('\n');
List existing variable collections and their conventions:
const collections = await figma.variables.getLocalVariableCollectionsAsync();
const results = collections.map(c => ({
name: c.name, id: c.id,
varCount: c.variableIds.length,
modes: c.modes.map(m => m.name)
}));
return results;
Load these as needed based on what your task involves:
| Doc | When to load | What it covers |
|---|---|---|
| gotchas.md | Before any use_figma | Every known pitfall with WRONG/CORRECT code examples |
| common-patterns.md | Need working code examples | Script scaffolds: shapes, text, auto-layout, variables, components, multi-step workflows |
| plugin-api-patterns.md | Creating/editing nodes | Fills, strokes, Auto Layout, effects, grouping, cloning, styles |
| api-reference.md | Need exact API surface | Node creation, variables API, core properties, what works and what doesn't |
| validation-and-recovery.md |
You will see snippets throughout documentation here. These snippets contain useful plugin API code that can be repurposed. Use them as is, or as starter code as you go. If there are key concepts that are best documented as generic snippets, call them out and write to disk so you can reuse in the future.
Weekly Installs
221
Repository
GitHub Stars
540
First Seen
2 days ago
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode215
codex206
gemini-cli204
github-copilot204
amp204
kimi-cli204
shadcn/ui 框架:React 组件库与 UI 设计系统,Tailwind CSS 最佳实践
54,000 周安装
getSharedPluginData()setSharedPluginData()console.log() is NOT returned — use return for outputuse_figma calls. Validate after each step. This is the single most important practice for avoiding bugs.{r: 1, g: 0, b: 0} = redawait figma.loadFontAsync({family, style})await figma.setCurrentPageAsync(page) to switch pages and load their content (see Page Rules below)setBoundVariableForPaint returns a NEW paint — must capture and reassigncreateVariable accepts collection object or ID string (object preferred)layoutSizingHorizontal/Vertical = 'FILL' MUST be set AFTER parent.appendChild(child) — setting before append throws. Same applies to 'HUG' on non-auto-layout nodes.figma.currentPage.children to find a clear position (e.g., to the right of the rightmost node). This only applies to page-level nodes — nodes nested inside other frames or auto-layout containers are positioned by their parent. See Gotchas.use_figma error, STOP. Do NOT immediately retry. Failed scripts are atomic — if a script errors, it is not executed at all and no changes are made to the file. Read the error message carefully, fix the script, then retry. See Error Recovery.return ALL created/mutated node IDs. Whenever a script creates new nodes or mutates existing ones on the canvas, collect every affected node ID and return them in a structured object (e.g. return { createdNodeIds: [...], mutatedNodeIds: [...] }). This is essential for subsequent calls to reference, validate, or clean up those nodes.variable.scopes explicitly when creating variables. The default ALL_SCOPES pollutes every property picker — almost never what you want. Use specific scopes like ["FRAME_FILL", "SHAPE_FILL"] for backgrounds, ["TEXT_FILL"] for text colors, ["GAP"] for spacing, etc. See variable-patterns.md for the full list.await every Promise. Never leave a Promise unawaited — unawaited async calls (e.g. figma.loadFontAsync(...) without await, or figma.setCurrentPageAsync(page) without await) will fire-and-forget, causing silent failures or race conditions. The script may return before the async operation completes, leading to missing data or half-applied changes."Setting figma.currentPage is not supported" | Used sync page setter | Use await figma.setCurrentPageAsync(page) |
| Property value out of range | Color channel > 1 (used 0–255 instead of 0–1) | Divide by 255 |
"Cannot read properties of null" | Node doesn't exist (wrong ID, wrong page) | Check page context, verify ID |
| Script hangs / no response | Infinite loop or unresolved promise | Check for while(true) or missing await; ensure code terminates |
"The node with id X does not exist" | Parent instance was implicitly detached by a child detachInstance(), changing IDs | Re-discover nodes by traversal from a stable (non-instance) parent frame |
loadFontAsync() called BEFORE any text property changeslineHeight/letterSpacing use {unit, value} format (not bare numbers)resize() is called BEFORE setting sizing modes (resize resets them to FIXED)return valueloadFontAsync, setCurrentPageAsync, importComponentByKeyAsync, etc.) is awaited — no fire-and-forget Promises| Multi-step writes or error recovery |
get_metadata vs get_screenshot workflow, mandatory error recovery steps |
| component-patterns.md | Creating components/variants | combineAsVariants, component properties, INSTANCE_SWAP, variant layout, discovering existing components, metadata traversal |
| variable-patterns.md | Creating/binding variables | Collections, modes, scopes, aliasing, binding patterns, discovering existing variables |
| text-style-patterns.md | Creating/applying text styles | Type ramps, font probing, listing styles, applying styles to nodes |
| effect-style-patterns.md | Creating/applying effect styles | Drop shadows, listing styles, applying styles to nodes |
| plugin-api-standalone.index.md | Need to understand the full API surface | Index of all types, methods, and properties in the Plugin API |
| plugin-api-standalone.d.ts | Need exact type signatures | Full typings file — grep for specific symbols, don't load all at once |