figme-mcp 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,223 +1,226 @@
1
- # figme
2
-
3
- An [MCP](https://modelcontextprotocol.io) server that lets your AI agent read Figma `.fig`
4
- files — offline, with no Figma account or API token.
5
-
6
- [![npm](https://img.shields.io/npm/v/figme-mcp)](https://www.npmjs.com/package/figme-mcp)
7
- [![Node.js](https://img.shields.io/node/v/figme-mcp)](https://nodejs.org)
8
- [![License: MIT](https://img.shields.io/npm/l/figme-mcp)](LICENSE)
9
-
10
- Save a design from Figma as a `.fig` file, and your agent can read everything in it: layers and
11
- layout, colours, text, components, design tokens and images. figme can also draw any frame as a
12
- picture, so the agent can compare what it built with the design.
13
-
14
- ```
15
- you: "what does the tab component in design.fig look like?"
16
-
17
- fig_overview → 10 pages, 2,046 components, 273 variables, 212 images
18
- fig_find → "lv2/tab/large" is 2:1337, on page "Page 1"
19
- fig_style → display:flex, direction:row, gap:8, padding:"8px 16px",
20
- cornerRadius:4, stroke #FFFFFF bound to variable "tab/large/underline"
21
- (active #FFFFFF / inactive #333333)
22
- ```
23
-
24
- ## Why figme
25
-
26
- - **No account, token or network.** figme reads the file on your disk and never contacts
27
- figma.com.
28
- - **Everything in the file.** Layers and geometry, auto-layout, fills, strokes, effects, text with
29
- mixed styles, components and instances, variables, prototype links and images. Layout comes
30
- back as CSS flexbox, colours as hex, and colours bound to variables keep their token names.
31
- - **Pictures as well as numbers.** `fig_render` draws any layer as a PNG or SVG.
32
- - **Small responses.** Even on a 116,000-node file, a response stays around 20 KB. Results are
33
- shallow by default, filterable and paged.
34
- - **Robust to Figma updates.** Every `.fig` carries the schema that describes it, and figme decodes
35
- the file with that schema, so fields Figma adds later don't break it.
36
-
37
- ## Quick start
38
-
39
- You need [Node.js](https://nodejs.org) 22.15 or newer.
40
-
41
- **1. Save the design as a `.fig` file.** In Figma, choose **File → Save local copy…** If it's a
42
- Community file, click **Open in Figma** first.
43
-
44
- **2. Add figme to your agent.** In Claude Code:
45
-
46
- ```bash
47
- claude mcp add figme -- npx -y figme-mcp
48
- ```
49
-
50
- For Cursor, VS Code, Windsurf and other clients, see [Set up your client](#set-up-your-client).
51
-
52
- **3. Ask.** Give the full path to the file, and paste a Figma link if you have one:
53
-
54
- > Using figme, read /Users/me/Desktop/App.fig and build this frame as a React component:
55
- > https://www.figma.com/design/AbC123/App?node-id=3017-121
56
-
57
- The agent picks the tools from there. A few more things to try:
58
-
59
- - *"List the pages and the most-used components in /Users/me/Desktop/App.fig."*
60
- - *"Turn the colour variables in /Users/me/Desktop/App.fig into CSS custom properties."*
61
- - *"Render the sign-in screen in /Users/me/Desktop/App.fig to /Users/me/Desktop/sign-in.png."*
62
-
63
- ## Set up your client
64
-
65
- Every client runs the same command, `npx -y figme-mcp`. Only the place you put it changes.
66
-
67
- <details>
68
- <summary><b>Claude Code</b></summary>
69
-
70
- ```bash
71
- claude mcp add figme -- npx -y figme-mcp # this project
72
- claude mcp add -s user figme -- npx -y figme-mcp # every project
73
- ```
74
-
75
- To share the server with everyone who works on a repository, commit a `.mcp.json` at its root:
76
-
77
- ```json
78
- {
79
- "mcpServers": {
80
- "figme": { "command": "npx", "args": ["-y", "figme-mcp"] }
81
- }
82
- }
83
- ```
84
-
85
- The Claude Code extensions for VS Code and JetBrains use this same configuration. They don't read
86
- the editor's own MCP settings.
87
-
88
- </details>
89
-
90
- <details>
91
- <summary><b>Cursor</b></summary>
92
-
93
- Add this to `~/.cursor/mcp.json` for every project, or to `.cursor/mcp.json` for one:
94
-
95
- ```json
96
- {
97
- "mcpServers": {
98
- "figme": { "command": "npx", "args": ["-y", "figme-mcp"] }
99
- }
100
- }
101
- ```
102
-
103
- </details>
104
-
105
- <details>
106
- <summary><b>VS Code (GitHub Copilot)</b></summary>
107
-
108
- From a terminal:
109
-
110
- ```bash
111
- code --add-mcp '{"name":"figme","command":"npx","args":["-y","figme-mcp"]}'
112
- ```
113
-
114
- Or add this to `.vscode/mcp.json`. VS Code uses the key `servers`, not `mcpServers`:
115
-
116
- ```json
117
- {
118
- "servers": {
119
- "figme": { "type": "stdio", "command": "npx", "args": ["-y", "figme-mcp"] }
120
- }
121
- }
122
- ```
123
-
124
- Then switch the Chat view to **Agent** mode.
125
-
126
- </details>
127
-
128
- <details>
129
- <summary><b>Windsurf</b></summary>
130
-
131
- Add this to `~/.codeium/windsurf/mcp_config.json`:
132
-
133
- ```json
134
- {
135
- "mcpServers": {
136
- "figme": { "command": "npx", "args": ["-y", "figme-mcp"] }
137
- }
138
- }
139
- ```
140
-
141
- </details>
142
-
143
- <details>
144
- <summary><b>Other clients</b></summary>
145
-
146
- Any client that can start a local (stdio) MCP server works. Give it:
147
-
148
- ```json
149
- { "command": "npx", "args": ["-y", "figme-mcp"] }
150
- ```
151
-
152
- Config file locations change between client releases. If a path above doesn't match what you
153
- see, check your client's MCP documentation.
154
-
155
- </details>
156
-
157
- **On Windows**, some clients can't find `npx` by themselves. If the server doesn't start, run it
158
- through `cmd`:
159
-
160
- ```json
161
- { "command": "cmd", "args": ["/c", "npx", "-y", "figme-mcp"] }
162
- ```
163
-
164
- ## Tips
165
-
166
- - **Always give the full path to the file, even with a link.** A Figma link can't tell figme which
167
- file on your disk it belongs to, and a relative path is resolved from wherever your client
168
- started the server.
169
- - **Don't let the agent open the Figma link.** The page needs a login, so the agent gets nothing
170
- useful back, and it may then invent a design from the words in the URL. figme tells agents not
171
- to; if yours tries anyway, stop it.
172
- - **"Node not found"** usually means the saved file isn't the one the link points to. Compare the
173
- document name that `fig_overview` reports with the name in the link, or ask the agent to find
174
- the layer by name instead.
175
- - **Big files need memory.** A 39 MB `.fig` takes about 900 MB of RAM once parsed, and figme keeps
176
- up to 4 parsed files. On a smaller machine, keep just one:
177
-
178
- ```json
179
- { "command": "npx", "args": ["-y", "figme-mcp", "--max-files", "1"] }
180
- ```
181
-
182
- ## Tools
183
-
184
- Your agent picks these on its own; you don't need to name them.
185
-
186
- | Tool | What it gives the agent |
187
- |---|---|
188
- | `fig_overview` | The pages, node counts, and how many components, variables and images the file has |
189
- | `fig_tree` | The layer tree under a node, a few levels at a time |
190
- | `fig_node` | One layer in detail: size, position, corner radii, auto-layout, children |
191
- | `fig_find` | Layers whose name or text contains a string |
192
- | `fig_text` | All the text, with fonts and mixed styles |
193
- | `fig_style` | Fills, strokes, effects and typography, with auto-layout as CSS flexbox |
194
- | `fig_components` | The components, their properties, and how often each is used |
195
- | `fig_instance` | What an instance changes from its component |
196
- | `fig_variables` | Design tokens: every collection, mode and value |
197
- | `fig_image` | Embedded images, and the file's thumbnail |
198
- | `fig_blob` | Raw vector data, for anything the other tools don't decode |
199
- | `fig_render` | A PNG or SVG picture of any layer or page |
200
-
201
- Parameters and example responses for each are in [docs/tools.md](docs/tools.md).
202
-
203
- ## Limitations
204
-
205
- - **Read-only.** figme never changes your `.fig`. It writes a file only when you ask `fig_image`
206
- or `fig_render` to save one.
207
- - **A snapshot, not a live link.** A `.fig` holds the design as it was when you saved it. When the
208
- design changes, save it again; figme picks up the new file.
209
- - **Rendering is close, not pixel-perfect.** `fig_render` approximates a few effects, such as
210
- background blur and angular gradients, and skips a few things, such as emoji. Every render
211
- lists what it approximated or skipped. See [docs/rendering.md](docs/rendering.md).
212
- - **Libraries from other files aren't included.** Styles, variables and components published from
213
- another file show up as references, without their values.
214
- - **Vector paths aren't decoded.** `fig_blob` returns their raw bytes.
215
-
216
- ## Contributing
217
-
218
- Issues and pull requests are welcome. [CONTRIBUTING.md](CONTRIBUTING.md) explains how to build
219
- from source and run the tests, and how the parser works.
220
-
221
- ## License
222
-
223
- [MIT](LICENSE)
1
+ # figme
2
+
3
+ An [MCP](https://modelcontextprotocol.io) server that lets your AI agent read Figma `.fig`
4
+ files — offline, with no Figma account or API token.
5
+
6
+ [![npm](https://img.shields.io/npm/v/figme-mcp)](https://www.npmjs.com/package/figme-mcp)
7
+ [![Node.js](https://img.shields.io/node/v/figme-mcp)](https://nodejs.org)
8
+ [![License: MIT](https://img.shields.io/npm/l/figme-mcp)](LICENSE)
9
+
10
+ Save a design from Figma as a `.fig` file, and your agent can read everything in it: layers and
11
+ layout, colours, text, components, design tokens and images. figme can also draw any frame as a
12
+ picture, so the agent can compare what it built with the design.
13
+
14
+ ```
15
+ you: "what does the tab component in design.fig look like?"
16
+
17
+ fig_overview → 10 pages, 2,046 components, 273 variables, 212 images
18
+ fig_find → "lv2/tab/large" is 2:1337, on page "Page 1"
19
+ fig_style → display:flex, direction:row, gap:8, padding:"8px 16px",
20
+ cornerRadius:4, stroke #FFFFFF bound to variable "tab/large/underline"
21
+ (active #FFFFFF / inactive #333333)
22
+ ```
23
+
24
+ ## Why figme
25
+
26
+ - **No account, token or network.** figme reads the file on your disk and never contacts
27
+ figma.com.
28
+ - **Everything in the file.** Layers and geometry, auto-layout, fills, strokes, effects, text with
29
+ mixed styles, components and instances, variables, prototype links and images. Layout comes
30
+ back as CSS flexbox, colours as hex, and colours bound to variables keep their token names.
31
+ - **What Figma shows, not just what it stores.** The layers inside a component instance come
32
+ back with the instance's overrides applied, under the ids Figma itself gives them, and a
33
+ shared style reports its live value rather than the stale copy cached beside it.
34
+ - **Pictures as well as numbers.** `fig_render` draws any layer as a PNG or SVG.
35
+ - **Small responses.** Even on a 116,000-node file, a response stays around 20 KB. Results are
36
+ shallow by default, filterable and paged.
37
+ - **Robust to Figma updates.** Every `.fig` carries the schema that describes it, and figme decodes
38
+ the file with that schema, so fields Figma adds later don't break it.
39
+
40
+ ## Quick start
41
+
42
+ You need [Node.js](https://nodejs.org) 22.15 or newer.
43
+
44
+ **1. Save the design as a `.fig` file.** In Figma, choose **File → Save local copy…** If it's a
45
+ Community file, click **Open in Figma** first.
46
+
47
+ **2. Add figme to your agent.** In Claude Code:
48
+
49
+ ```bash
50
+ claude mcp add figme -- npx -y figme-mcp
51
+ ```
52
+
53
+ For Cursor, VS Code, Windsurf and other clients, see [Set up your client](#set-up-your-client).
54
+
55
+ **3. Ask.** Give the full path to the file, and paste a Figma link if you have one:
56
+
57
+ > Using figme, read /Users/me/Desktop/App.fig and build this frame as a React component:
58
+ > https://www.figma.com/design/AbC123/App?node-id=3017-121
59
+
60
+ The agent picks the tools from there. A few more things to try:
61
+
62
+ - *"List the pages and the most-used components in /Users/me/Desktop/App.fig."*
63
+ - *"Turn the colour variables in /Users/me/Desktop/App.fig into CSS custom properties."*
64
+ - *"Render the sign-in screen in /Users/me/Desktop/App.fig to /Users/me/Desktop/sign-in.png."*
65
+
66
+ ## Set up your client
67
+
68
+ Every client runs the same command, `npx -y figme-mcp`. Only the place you put it changes.
69
+
70
+ <details>
71
+ <summary><b>Claude Code</b></summary>
72
+
73
+ ```bash
74
+ claude mcp add figme -- npx -y figme-mcp # this project
75
+ claude mcp add -s user figme -- npx -y figme-mcp # every project
76
+ ```
77
+
78
+ To share the server with everyone who works on a repository, commit a `.mcp.json` at its root:
79
+
80
+ ```json
81
+ {
82
+ "mcpServers": {
83
+ "figme": { "command": "npx", "args": ["-y", "figme-mcp"] }
84
+ }
85
+ }
86
+ ```
87
+
88
+ The Claude Code extensions for VS Code and JetBrains use this same configuration. They don't read
89
+ the editor's own MCP settings.
90
+
91
+ </details>
92
+
93
+ <details>
94
+ <summary><b>Cursor</b></summary>
95
+
96
+ Add this to `~/.cursor/mcp.json` for every project, or to `.cursor/mcp.json` for one:
97
+
98
+ ```json
99
+ {
100
+ "mcpServers": {
101
+ "figme": { "command": "npx", "args": ["-y", "figme-mcp"] }
102
+ }
103
+ }
104
+ ```
105
+
106
+ </details>
107
+
108
+ <details>
109
+ <summary><b>VS Code (GitHub Copilot)</b></summary>
110
+
111
+ From a terminal:
112
+
113
+ ```bash
114
+ code --add-mcp '{"name":"figme","command":"npx","args":["-y","figme-mcp"]}'
115
+ ```
116
+
117
+ Or add this to `.vscode/mcp.json`. VS Code uses the key `servers`, not `mcpServers`:
118
+
119
+ ```json
120
+ {
121
+ "servers": {
122
+ "figme": { "type": "stdio", "command": "npx", "args": ["-y", "figme-mcp"] }
123
+ }
124
+ }
125
+ ```
126
+
127
+ Then switch the Chat view to **Agent** mode.
128
+
129
+ </details>
130
+
131
+ <details>
132
+ <summary><b>Windsurf</b></summary>
133
+
134
+ Add this to `~/.codeium/windsurf/mcp_config.json`:
135
+
136
+ ```json
137
+ {
138
+ "mcpServers": {
139
+ "figme": { "command": "npx", "args": ["-y", "figme-mcp"] }
140
+ }
141
+ }
142
+ ```
143
+
144
+ </details>
145
+
146
+ <details>
147
+ <summary><b>Other clients</b></summary>
148
+
149
+ Any client that can start a local (stdio) MCP server works. Give it:
150
+
151
+ ```json
152
+ { "command": "npx", "args": ["-y", "figme-mcp"] }
153
+ ```
154
+
155
+ Config file locations change between client releases. If a path above doesn't match what you
156
+ see, check your client's MCP documentation.
157
+
158
+ </details>
159
+
160
+ **On Windows**, some clients can't find `npx` by themselves. If the server doesn't start, run it
161
+ through `cmd`:
162
+
163
+ ```json
164
+ { "command": "cmd", "args": ["/c", "npx", "-y", "figme-mcp"] }
165
+ ```
166
+
167
+ ## Tips
168
+
169
+ - **Always give the full path to the file, even with a link.** A Figma link can't tell figme which
170
+ file on your disk it belongs to, and a relative path is resolved from wherever your client
171
+ started the server.
172
+ - **Don't let the agent open the Figma link.** The page needs a login, so the agent gets nothing
173
+ useful back, and it may then invent a design from the words in the URL. figme tells agents not
174
+ to; if yours tries anyway, stop it.
175
+ - **"Node not found"** usually means the saved file isn't the one the link points to. Compare the
176
+ document name that `fig_overview` reports with the name in the link, or ask the agent to find
177
+ the layer by name instead.
178
+ - **Big files need memory.** A 39 MB `.fig` takes about 900 MB of RAM once parsed, and figme keeps
179
+ up to 4 parsed files. On a smaller machine, keep just one:
180
+
181
+ ```json
182
+ { "command": "npx", "args": ["-y", "figme-mcp", "--max-files", "1"] }
183
+ ```
184
+
185
+ ## Tools
186
+
187
+ Your agent picks these on its own; you don't need to name them.
188
+
189
+ | Tool | What it gives the agent |
190
+ |---|---|
191
+ | `fig_overview` | The pages, node counts, and how many components, variables and images the file has |
192
+ | `fig_tree` | The layer tree under a node, a few levels at a time, instances opened |
193
+ | `fig_node` | One layer in detail: size, position, corner radii, auto-layout, children |
194
+ | `fig_find` | Layers whose name or text contains a string |
195
+ | `fig_text` | All the text, with fonts and mixed styles |
196
+ | `fig_style` | Fills, strokes, effects and typography, with auto-layout as CSS flexbox |
197
+ | `fig_components` | The components, their properties, and how often each is used |
198
+ | `fig_instance` | What an instance changes from its component |
199
+ | `fig_variables` | Design tokens: every collection, mode and value |
200
+ | `fig_image` | Embedded images, and the file's thumbnail |
201
+ | `fig_blob` | Raw vector data, for anything the other tools don't decode |
202
+ | `fig_render` | A PNG or SVG picture of any layer or page |
203
+
204
+ Parameters and example responses for each are in [docs/tools.md](docs/tools.md).
205
+
206
+ ## Limitations
207
+
208
+ - **Read-only.** figme never changes your `.fig`. It writes a file only when you ask `fig_image`
209
+ or `fig_render` to save one.
210
+ - **A snapshot, not a live link.** A `.fig` holds the design as it was when you saved it. When the
211
+ design changes, save it again; figme picks up the new file.
212
+ - **Rendering is close, not pixel-perfect.** `fig_render` approximates a few effects, such as
213
+ background blur and angular gradients, and skips a few things, such as emoji. Every render
214
+ lists what it approximated or skipped. See [docs/rendering.md](docs/rendering.md).
215
+ - **Libraries from other files aren't included.** Styles, variables and components published from
216
+ another file show up as references, without their values.
217
+ - **Vector paths aren't decoded.** `fig_blob` returns their raw bytes.
218
+
219
+ ## Contributing
220
+
221
+ Issues and pull requests are welcome. [CONTRIBUTING.md](CONTRIBUTING.md) explains how to build
222
+ from source and run the tests, and how the parser works.
223
+
224
+ ## License
225
+
226
+ [MIT](LICENSE)
@@ -45,6 +45,9 @@ export const INSTRUCTIONS = [
45
45
  'Node guids are "sessionID:localID" strings such as "2:1339". A Figma link spells the same',
46
46
  'id with a dash - node-id=3017-121 is guid "3017:121" - and every guid argument also accepts',
47
47
  'that form, the percent-encoded form, or the whole link, so pass along whatever the user had.',
48
+ 'A layer inside a component instance has an id like "I2:1329;0:2528" - the instance, then the',
49
+ 'layer - exactly as Figma names it. fig_tree lists those layers with their overrides applied,',
50
+ 'and every tool accepts their ids; fig_text with a scope includes the text instances show.',
48
51
  '',
49
52
  'These tools read a .fig saved on disk and cannot open a figma.com URL. Given a link but no',
50
53
  'file path, ask the user for the path. Never fetch the link, and never infer the design from',
@@ -6,6 +6,7 @@ import { z } from 'zod';
6
6
  import type { FileCache, CacheEntry } from '../../cache.js';
7
7
  import type { FileIndex } from '../../model/index.js';
8
8
  import { type TreeNode } from '../../model/tree.js';
9
+ import { type SceneNode } from '../../model/scene.js';
9
10
  import { type CallToolResult } from '../respond.js';
10
11
  export interface ToolContext {
11
12
  readonly cache: FileCache;
@@ -16,6 +17,15 @@ export declare function load(ctx: ToolContext, file: string): CacheEntry;
16
17
  export declare function requireNode(index: FileIndex, guid: string): TreeNode;
17
18
  /** Resolve an optional scope argument to a subtree root, defaulting to the DOCUMENT. */
18
19
  export declare function resolveRoot(index: FileIndex, guid: string | undefined): TreeNode;
20
+ /**
21
+ * A stored node, or a layer inside a component instance (`I<instance>;<layer>…`), as Figma shows
22
+ * it: instances expand into their layers (model/scene.ts).
23
+ */
24
+ export declare function requireScene(index: FileIndex, guid: string): SceneNode;
25
+ /** `requireScene` for an optional scope argument, defaulting to the DOCUMENT. */
26
+ export declare function resolveSceneRoot(index: FileIndex, guid: string | undefined): SceneNode;
27
+ /** Shared description of the `instances` argument of the traversing tools. */
28
+ export declare const instancesArg: (fallback: string) => z.ZodOptional<z.ZodBoolean>;
19
29
  /**
20
30
  * Uniform handler wrapper: turns thrown errors into an MCP error result instead of crashing the
21
31
  * server, and keeps the message actionable (the thrown text is already user-facing).
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { z } from 'zod';
6
6
  import { canonicalGuid, guidNotFound } from '../../model/tree.js';
7
+ import { resolveScene, sceneOf } from '../../model/scene.js';
7
8
  import { errorResult } from '../respond.js';
8
9
  export const fileArg = z
9
10
  .string()
@@ -31,6 +32,32 @@ export function resolveRoot(index, guid) {
31
32
  throw new Error('this file has no DOCUMENT node');
32
33
  return root;
33
34
  }
35
+ /**
36
+ * A stored node, or a layer inside a component instance (`I<instance>;<layer>…`), as Figma shows
37
+ * it: instances expand into their layers (model/scene.ts).
38
+ */
39
+ export function requireScene(index, guid) {
40
+ const key = canonicalGuid(guid);
41
+ const s = resolveScene(index, key);
42
+ if (!s)
43
+ throw new Error(guidNotFound(guid, key));
44
+ return s;
45
+ }
46
+ /** `requireScene` for an optional scope argument, defaulting to the DOCUMENT. */
47
+ export function resolveSceneRoot(index, guid) {
48
+ if (guid)
49
+ return requireScene(index, guid);
50
+ const root = index.root;
51
+ if (!root)
52
+ throw new Error('this file has no DOCUMENT node');
53
+ return sceneOf(index, root);
54
+ }
55
+ /** Shared description of the `instances` argument of the traversing tools. */
56
+ export const instancesArg = (fallback) => z
57
+ .boolean()
58
+ .optional()
59
+ .describe('Walk into component instances and list the layers they show, with their overrides ' +
60
+ `applied (ids like "I2:1329;0:2528"). ${fallback}`);
34
61
  /**
35
62
  * Uniform handler wrapper: turns thrown errors into an MCP error result instead of crashing the
36
63
  * server, and keeps the message actionable (the thrown text is already user-facing).
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { cursorArg, fileArg, handler, load, requireNode } from './context.js';
2
+ import { cursorArg, fileArg, handler, instancesArg, load, requireNode, resolveSceneRoot, } from './context.js';
3
3
  import { Packer, decodeCursor, encodeCursor, jsonResult, measure } from '../respond.js';
4
4
  import { summarize } from '../../model/summarize.js';
5
5
  import { breadcrumb } from '../../model/tree.js';
@@ -10,9 +10,33 @@ export const DESCRIPTION = [
10
10
  'restricted to node types and/or a subtree. Each hit comes back with the page it lives on, a',
11
11
  'breadcrumb of ancestor names, and which field matched — so you can jump straight to a guid',
12
12
  'and then call fig_node / fig_style. Omit `query` to list every node of the given types.',
13
+ 'instances:true also searches the layers component instances show, with their overrides.',
13
14
  ].join(' ');
14
15
  const DEFAULT_LIMIT = 50;
15
16
  const TEXT_PREVIEW = 160;
17
+ /** The prebuilt search index over the stored nodes, restricted to a stored subtree. */
18
+ function* storedCandidates(index, scope) {
19
+ const range = scope ? index.subtreeRange(scope) : { start: 0, end: index.nodeCount };
20
+ const entries = index.search();
21
+ for (let i = range.start; i < range.end; i++)
22
+ yield entries[i];
23
+ }
24
+ /** Every layer under `root` as Figma shows it, instances opened, depth-first and pre-order. */
25
+ function* sceneCandidates(root) {
26
+ const stack = [root];
27
+ while (stack.length) {
28
+ const t = stack.pop();
29
+ const characters = str(obj(t.node, 'textData'), 'characters');
30
+ yield {
31
+ t,
32
+ nameLower: (str(t.node, 'name') ?? '').toLowerCase(),
33
+ textLower: characters?.toLowerCase(),
34
+ };
35
+ const kids = t.children;
36
+ for (let i = kids.length - 1; i >= 0; i--)
37
+ stack.push(kids[i]);
38
+ }
39
+ }
16
40
  export function register(server, ctx) {
17
41
  server.registerTool(NAME, {
18
42
  title: 'Search layers and text',
@@ -26,6 +50,7 @@ export function register(server, ctx) {
26
50
  types: z.array(z.string()).optional().describe('Restrict to node types, e.g. ["TEXT"].'),
27
51
  scope: z.string().optional().describe('Only search inside this guid subtree. A Figma node-id or link works too.'),
28
52
  limit: z.number().int().min(1).max(300).optional().describe(`Default ${DEFAULT_LIMIT}.`),
53
+ instances: instancesArg('Default false: the search covers the layers stored in the file. Best with a `scope`.'),
29
54
  cursor: cursorArg,
30
55
  },
31
56
  annotations: { readOnlyHint: true, openWorldHint: false },
@@ -36,16 +61,21 @@ export function register(server, ctx) {
36
61
  }
37
62
  const needle = args.query?.toLowerCase();
38
63
  const typeFilter = args.types?.length ? new Set(args.types) : undefined;
39
- const scope = args.scope ? requireNode(index, args.scope) : undefined;
40
- const range = scope ? index.subtreeRange(scope) : { start: 0, end: index.nodeCount };
64
+ const expand = args.instances === true;
65
+ const scope = args.scope
66
+ ? expand
67
+ ? resolveSceneRoot(index, args.scope)
68
+ : requireNode(index, args.scope)
69
+ : undefined;
70
+ const candidates = expand
71
+ ? sceneCandidates(scope ?? resolveSceneRoot(index, undefined))
72
+ : storedCandidates(index, scope);
41
73
  const { after } = decodeCursor(args.cursor);
42
74
  const packer = new Packer({ limit: args.limit ?? DEFAULT_LIMIT });
43
- const entries = index.search();
44
75
  let skipping = after !== undefined;
45
76
  let lastGuid;
46
77
  let totalMatches = 0;
47
- for (let i = range.start; i < range.end; i++) {
48
- const e = entries[i];
78
+ for (const e of candidates) {
49
79
  if (typeFilter && !typeFilter.has(str(e.t.node, 'type') ?? ''))
50
80
  continue;
51
81
  let matchedOn;
@@ -2,7 +2,7 @@
2
2
  import * as fs from 'node:fs';
3
3
  import * as path from 'node:path';
4
4
  import { z } from 'zod';
5
- import { fileArg, handler, load, requireNode } from './context.js';
5
+ import { fileArg, handler, load, requireScene } from './context.js';
6
6
  import { jsonResult } from '../respond.js';
7
7
  import { sniffImage } from '../../fig/imagemeta.js';
8
8
  import { nodeImageHashes } from '../../model/index.js';
@@ -44,7 +44,8 @@ export function register(server, ctx) {
44
44
  }
45
45
  let hash = args.hash;
46
46
  if (!hash && args.guid) {
47
- const t = requireNode(index, args.guid);
47
+ // A layer inside an instance carries the image paints its overrides gave it.
48
+ const t = requireScene(index, args.guid);
48
49
  const hashes = nodeImageHashes(t.node);
49
50
  if (hashes.length === 0) {
50
51
  throw new Error(`node ${args.guid} (${str(t.node, 'type') ?? '?'}) has no image fills — ` +