figme-mcp 1.0.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.
Files changed (97) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +447 -0
  3. package/dist/cache.d.ts +29 -0
  4. package/dist/cache.js +68 -0
  5. package/dist/fig/bytebuffer.d.ts +31 -0
  6. package/dist/fig/bytebuffer.js +98 -0
  7. package/dist/fig/container.d.ts +32 -0
  8. package/dist/fig/container.js +80 -0
  9. package/dist/fig/imagemeta.d.ts +17 -0
  10. package/dist/fig/imagemeta.js +96 -0
  11. package/dist/fig/invariants.d.ts +10 -0
  12. package/dist/fig/invariants.js +63 -0
  13. package/dist/fig/kiwi.d.ts +38 -0
  14. package/dist/fig/kiwi.js +144 -0
  15. package/dist/fig/parse.d.ts +37 -0
  16. package/dist/fig/parse.js +91 -0
  17. package/dist/fig/zip.d.ts +23 -0
  18. package/dist/fig/zip.js +95 -0
  19. package/dist/mcp/create.d.ts +12 -0
  20. package/dist/mcp/create.js +48 -0
  21. package/dist/mcp/respond.d.ts +76 -0
  22. package/dist/mcp/respond.js +124 -0
  23. package/dist/mcp/server.d.ts +3 -0
  24. package/dist/mcp/server.js +22 -0
  25. package/dist/mcp/tools/blob.d.ts +7 -0
  26. package/dist/mcp/tools/blob.js +55 -0
  27. package/dist/mcp/tools/components.d.ts +7 -0
  28. package/dist/mcp/tools/components.js +54 -0
  29. package/dist/mcp/tools/context.d.ts +24 -0
  30. package/dist/mcp/tools/context.js +48 -0
  31. package/dist/mcp/tools/find.d.ts +7 -0
  32. package/dist/mcp/tools/find.js +97 -0
  33. package/dist/mcp/tools/image.d.ts +6 -0
  34. package/dist/mcp/tools/image.js +100 -0
  35. package/dist/mcp/tools/instance.d.ts +7 -0
  36. package/dist/mcp/tools/instance.js +44 -0
  37. package/dist/mcp/tools/node.d.ts +7 -0
  38. package/dist/mcp/tools/node.js +49 -0
  39. package/dist/mcp/tools/overview.d.ts +7 -0
  40. package/dist/mcp/tools/overview.js +45 -0
  41. package/dist/mcp/tools/render.d.ts +6 -0
  42. package/dist/mcp/tools/render.js +128 -0
  43. package/dist/mcp/tools/style.d.ts +7 -0
  44. package/dist/mcp/tools/style.js +38 -0
  45. package/dist/mcp/tools/text.d.ts +7 -0
  46. package/dist/mcp/tools/text.js +89 -0
  47. package/dist/mcp/tools/tree.d.ts +7 -0
  48. package/dist/mcp/tools/tree.js +100 -0
  49. package/dist/mcp/tools/variables.d.ts +7 -0
  50. package/dist/mcp/tools/variables.js +71 -0
  51. package/dist/model/access.d.ts +28 -0
  52. package/dist/model/access.js +106 -0
  53. package/dist/model/components.d.ts +72 -0
  54. package/dist/model/components.js +157 -0
  55. package/dist/model/index.d.ts +73 -0
  56. package/dist/model/index.js +192 -0
  57. package/dist/model/instance.d.ts +87 -0
  58. package/dist/model/instance.js +208 -0
  59. package/dist/model/summarize.d.ts +83 -0
  60. package/dist/model/summarize.js +541 -0
  61. package/dist/model/text.d.ts +29 -0
  62. package/dist/model/text.js +61 -0
  63. package/dist/model/tree.d.ts +47 -0
  64. package/dist/model/tree.js +89 -0
  65. package/dist/model/variables.d.ts +50 -0
  66. package/dist/model/variables.js +141 -0
  67. package/dist/render/bounds.d.ts +64 -0
  68. package/dist/render/bounds.js +173 -0
  69. package/dist/render/color.d.ts +20 -0
  70. package/dist/render/color.js +41 -0
  71. package/dist/render/effects.d.ts +34 -0
  72. package/dist/render/effects.js +196 -0
  73. package/dist/render/export.d.ts +51 -0
  74. package/dist/render/export.js +573 -0
  75. package/dist/render/index.d.ts +42 -0
  76. package/dist/render/index.js +94 -0
  77. package/dist/render/instance.d.ts +12 -0
  78. package/dist/render/instance.js +72 -0
  79. package/dist/render/matrix.d.ts +46 -0
  80. package/dist/render/matrix.js +94 -0
  81. package/dist/render/node.d.ts +41 -0
  82. package/dist/render/node.js +95 -0
  83. package/dist/render/paint.d.ts +27 -0
  84. package/dist/render/paint.js +301 -0
  85. package/dist/render/path.d.ts +42 -0
  86. package/dist/render/path.js +156 -0
  87. package/dist/render/raster.d.ts +31 -0
  88. package/dist/render/raster.js +69 -0
  89. package/dist/render/report.d.ts +72 -0
  90. package/dist/render/report.js +106 -0
  91. package/dist/render/style.d.ts +31 -0
  92. package/dist/render/style.js +67 -0
  93. package/dist/render/svg.d.ts +60 -0
  94. package/dist/render/svg.js +150 -0
  95. package/dist/render/text.d.ts +50 -0
  96. package/dist/render/text.js +90 -0
  97. package/package.json +47 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ntson9p
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,447 @@
1
+ # figme — read local Figma `.fig` files from an AI agent
2
+
3
+ `figme` is an [MCP](https://modelcontextprotocol.io) server that lets an AI agent read
4
+ **everything inside a local `.fig` / `.figma` file** — document structure, geometry, fills,
5
+ strokes, effects, auto-layout, text (including mixed-format runs), components and instances,
6
+ variables, prototype links and embedded bitmaps.
7
+
8
+ It is **fully offline**. No Figma account, no access token, no REST API, no network at runtime.
9
+ It parses the file's own bytes, using the Kiwi schema that Figma ships *inside* every `.fig`.
10
+
11
+ It is also **token-aware**: the reference file used to develop it holds 116,142 nodes, and no
12
+ tool response ever exceeds ~20 KB. Everything is shallow by default, filterable, and paginated
13
+ with cursors.
14
+
15
+ ```
16
+ you: "what does the tab component in design.fig look like?"
17
+
18
+ fig_overview → 10 pages, 2,046 components, 273 variables, 212 images
19
+ fig_find → "lv2/tab/large" is 2:1337, on page "Page 1"
20
+ fig_style → display:flex, direction:row, gap:8, padding:"8px 16px",
21
+ cornerRadius:4, stroke #FFFFFF bound to variable "tab/large/underline"
22
+ (active #FFFFFF / inactive #333333)
23
+ ```
24
+
25
+ ---
26
+
27
+ ## Non-goals
28
+
29
+ These are deliberate, permanent limits — not missing features:
30
+
31
+ - **Rendering is best-effort, not pixel-perfect.** A `.fig` contains no rendered pixels of your
32
+ frames, but it does contain everything needed to draw them again: Figma bakes outlined
33
+ strokes, combined booleans, per-glyph outlines and per-instance geometry into the file at save
34
+ time. `fig_render` uses that to produce a real picture offline — see
35
+ [Rendering](#rendering-fig_render) for exactly what is exact and what is approximated. It is
36
+ not a screenshot of Figma and never will be: read the report before trusting fine detail.
37
+ - **No writing.** Nothing is ever written back into a `.fig`. The only write paths in the whole
38
+ server are `fig_image { savePath }` and `fig_render { savePath }`, which write to a path you
39
+ name.
40
+ - **No Figma API and no network.** Nothing here talks to figma.com. Library assets published
41
+ from *other* files (styles, variables, components) cannot be resolved offline; they come back
42
+ as their opaque `assetRef` so you can see that they exist and where they point.
43
+ - **No vector-network decoding (v1).** Vector geometry lives in a separate binary blob format.
44
+ `fig_node` reports the blob indices and `fig_blob` hands you the raw bytes, but this server
45
+ does not interpret them.
46
+ - **Not a diffing or version-history tool.** A saved `.fig` is a full snapshot, not a delta.
47
+
48
+ ## Requirements
49
+
50
+ - **Node.js ≥ 22.15** (needs `zlib.zstdDecompressSync`; developed on Node 24).
51
+ - Runtime dependencies: `@modelcontextprotocol/sdk` and `zod`. The parser itself uses only
52
+ Node built-ins.
53
+
54
+ ## Install and build
55
+
56
+ ```bash
57
+ npm install
58
+ npm run build # tsc -> dist/
59
+ npm test # builds, then runs the full node:test suite
60
+ ```
61
+
62
+ ## Registering the server
63
+
64
+ **Claude Code (project scope)** — this repo already contains a `.mcp.json`:
65
+
66
+ ```json
67
+ {
68
+ "mcpServers": {
69
+ "figme": {
70
+ "command": "node",
71
+ "args": ["dist/mcp/server.js"]
72
+ }
73
+ }
74
+ }
75
+ ```
76
+
77
+ **Claude Code (CLI, user scope)** — use an absolute path so it works from any directory:
78
+
79
+ ```bash
80
+ claude mcp add figme -- node /abs/path/to/figme/dist/mcp/server.js
81
+ ```
82
+
83
+ **Any other MCP client** — spawn `node /abs/path/to/figme/dist/mcp/server.js` and talk stdio.
84
+
85
+ Optional flag: `--max-files N` (default 4) caps how many parsed files stay cached. A 39 MB
86
+ `.fig` decodes to roughly 900 MB of live objects, so raise it only with memory to spare.
87
+
88
+ Paths passed as the `file` argument may be absolute, or relative to the server's working
89
+ directory.
90
+
91
+ ---
92
+
93
+ ## Tools
94
+
95
+ Every tool takes `file` (path to the `.fig`). Node references are **guid strings** of the form
96
+ `"sessionID:localID"`, e.g. `"2:1339"`. Responses that were cut set `truncated: true` and return
97
+ an opaque `nextCursor` you can pass back.
98
+
99
+ The intended workflow: **`fig_overview` → `fig_tree` a page → `fig_node` / `fig_style` a guid**,
100
+ with `fig_find` to jump straight to something by name or copy, and `fig_render` whenever seeing
101
+ the thing is faster than reading it.
102
+
103
+ ### 1. `fig_overview` — orient yourself
104
+
105
+ Document name, export date, format version, node counts by type, the page list, and how many
106
+ components / variables / images the file holds.
107
+
108
+ ```jsonc
109
+ // → fig_overview { "file": "figma-input/sample.fig" }
110
+ {
111
+ "name": "Sample Design", "formatVersion": 106, "nodes": 116142,
112
+ "pages": [ { "guid": "0:2", "name": "Page 1", "children": 1137 }, /* … */ ],
113
+ "nodeTypes": { "INSTANCE": 38164, "FRAME": 32160, "TEXT": 16894, /* … */ },
114
+ "components": 2046, "variables": 273, "images": 212, "blobs": 9651
115
+ }
116
+ ```
117
+
118
+ ### 2. `fig_tree` — explore structure
119
+
120
+ `root` (default DOCUMENT), `depth` (default 2, max 6), `types` filter, `format`, `cursor`.
121
+ Returns a **flat list in document order**; each entry has `depth` (relative to the root) and
122
+ `parent`, so the hierarchy is reconstructable, plus `children` (a count) so you can see where
123
+ it is worth going deeper.
124
+
125
+ ```
126
+ // → fig_tree { "file": "…", "root": "2:1339", "depth": 3, "format": "outline" }
127
+ root 2:1339 "Frame 39" depth<=3
128
+ [FRAME] 134x40 "Frame 39" (2:1339) x4
129
+ [INSTANCE] 16x16 "lv1/ic/setting" (2:1340)
130
+ [TEXT] 64x24 "text" (2:1341)
131
+ [INSTANCE] 6x6 "lv1/ic/arrow-down" (2:1342)
132
+ [FRAME] 28x24 "Frame 6" (2:1343) x1
133
+ [INSTANCE] 28x22 "lv2/notification" (2:1344)
134
+ ```
135
+
136
+ `format: "outline"` is roughly 4× denser than JSON and is the best way to browse.
137
+
138
+ ### 3. `fig_node` — inspect one node
139
+
140
+ `detail` is `summary`, `full` (default) or `raw`.
141
+
142
+ ```jsonc
143
+ // → fig_node { "file": "…", "guid": "2:1339" }
144
+ {
145
+ "guid": "2:1339", "type": "FRAME", "name": "Frame 39",
146
+ "page": "Page 1", "path": "Page 1 / lv2/tab/large",
147
+ "geometry": { "width": 134, "height": 40, "x": 0, "y": 0, "absoluteX": 0, "absoluteY": 0 },
148
+ "cornerRadius": 4, "strokeWeight": 1,
149
+ "strokes": [ { "type": "SOLID", "color": "#FFFFFF",
150
+ "colorVar": { "variable": "tab/large/underline", "guid": "2:1319",
151
+ "values": { "active": "#FFFFFF", "inactive": "#333333" } } } ],
152
+ "autoLayout": { "mode": "HORIZONTAL", "spacing": 8,
153
+ "padding": { "top": 8, "right": 16, "bottom": 8, "left": 16 },
154
+ "primaryAlign": "CENTER", "counterAlign": "CENTER" },
155
+ "children": [ { "guid": "2:1340", "type": "INSTANCE", "name": "lv1/ic/setting", "size": "16x16" } ]
156
+ }
157
+ ```
158
+
159
+ `detail: "raw"` returns the decoded Figma record verbatim (bytes as hex, int64 as strings). It
160
+ is the forward-compatibility escape hatch: anything the mappers do not understand yet is still
161
+ reachable there. Limited to one node per call.
162
+
163
+ ### 4. `fig_find` — search names and copy
164
+
165
+ `query` (case-insensitive substring, matched against layer names **and** text content), plus
166
+ optional `types`, `scope`, `limit`, `cursor`. Omit `query` to list all nodes of some types.
167
+
168
+ ```jsonc
169
+ // → fig_find { "file": "…", "query": "sample", "types": ["TEXT"], "limit": 3 }
170
+ { "totalMatches": 1428, "returned": 3, "results": [
171
+ { "guid": "8917:139951", "type": "TEXT", "name": "#number1", "size": "224x24",
172
+ "matchedOn": "text", "page": "Page 1",
173
+ "path": "Page 1 / Popup/Variant 7 / Frame 2608806 / …",
174
+ "text": "Sample notification text" } ] }
175
+ ```
176
+
177
+ ### 5. `fig_text` — copy inventory
178
+
179
+ All text in the file or in one `scope`, in document order, with a compact style block.
180
+ `includeRuns: true` adds the **styled runs** — the mixed-format spans Figma stores per UTF-16
181
+ code unit — each showing only the fields it overrides.
182
+
183
+ ```jsonc
184
+ // → fig_text { "file": "…", "scope": "2:7098", "includeRuns": true }
185
+ { "totalTextNodes": 2, "texts": [
186
+ { "guid": "2:7099", "name": "✏️ Time", "characters": "Yesterday 9:41",
187
+ "page": "Page 1", "hasStyledRuns": true,
188
+ "style": { "font": "SF Pro Text Regular", "size": 11, "lineHeight": "13px", "color": "#3C3C43" },
189
+ "runs": [ { "start": 0, "end": 9, "text": "Yesterday", "styleID": 12,
190
+ "style": { "styles": { "text": { "name": "Caption2/Medium" } } } },
191
+ { "start": 9, "end": 10, "text": " ", "styleID": 10, /* … */ },
192
+ { "start": 10, "end": 11, "text": "9", "styleID": 9, /* … */ },
193
+ { "start": 11, "end": 14, "text": ":41", "styleID": 10 } ] } ] }
194
+ ```
195
+
196
+ ### 6. `fig_style` — resolved style, shaped for code
197
+
198
+ Auto-layout translated into CSS flexbox terms, paints as hex, typography flattened, plus how
199
+ the node behaves inside its parent's layout.
200
+
201
+ ```jsonc
202
+ // → fig_style { "file": "…", "guid": "2:1339" }
203
+ { "style": {
204
+ "guid": "2:1339", "type": "FRAME", "width": 134, "height": 40, "cornerRadius": 4,
205
+ "strokes": [ { "type": "SOLID", "color": "#FFFFFF", "colorVar": { "variable": "tab/large/underline" } } ],
206
+ "strokeWeight": 1, "strokeAlign": "INSIDE",
207
+ "layout": { "display": "flex", "direction": "row", "gap": 8, "padding": "8px 16px",
208
+ "justifyContent": "center", "alignItems": "center", "primarySizing": "fixed" },
209
+ "inParentLayout": { "flexGrow": 1, "alignSelf": "stretch" } } }
210
+ ```
211
+
212
+ For TEXT nodes it also returns `typography` and resolves shared text/fill styles to the values
213
+ they define (`styles.text.defines`).
214
+
215
+ ### 7. `fig_components` — the component catalogue
216
+
217
+ SYMBOL nodes with their component set, property definitions and defaults, and instance counts —
218
+ most-used first, so the load-bearing parts of the design system come back first.
219
+
220
+ ```jsonc
221
+ // → fig_components { "file": "…", "query": "lv2/tab/large" }
222
+ { "totalComponents": 2046, "components": [
223
+ { "guid": "2:1337", "name": "lv2/tab/large", "page": "Page 1",
224
+ "size": "134x40", "instances": 599,
225
+ "propDefs": [ { "name": "show badge(🔴)", "type": "BOOL", "default": false },
226
+ { "name": "icon", "type": "INSTANCE_SWAP" } ] } ] }
227
+ ```
228
+
229
+ ### 8. `fig_instance` — how an instance differs from its component
230
+
231
+ ```jsonc
232
+ // → fig_instance { "file": "…", "guid": "2:1329" }
233
+ { "instance": { "guid": "2:1329", "name": "lv1/color/GL/#FFFFFF",
234
+ "page": "Page 1",
235
+ "symbol": { "guid": "2:1325", "name": "lv1/color/GL/#FFFFFF", "inFile": true } },
236
+ "overrideCount": 1,
237
+ "overrides": [ { "path": ["0:2528"], "targetGuid": "2:1325", "targetName": "lv1/color/GL/#FFFFFF",
238
+ "fields": { "size": "22x22", "fillsCleared": true } } ] }
239
+ ```
240
+
241
+ An instance that sets component properties reports them with the names resolved, e.g.
242
+ `propAssignments: [ { "defID": "108:1543", "name": "text", "type": "TEXT", "value": "Back" } ]`.
243
+ A path segment is the target's `overrideKey` when it has one and its guid otherwise, and a
244
+ nested path is walked through swapped instances exactly as the renderer expands them.
245
+
246
+ ### 9. `fig_variables` — design tokens
247
+
248
+ Every collection with its modes, and every variable with a value per mode. Alias chains are
249
+ followed when the target lives in the same file.
250
+
251
+ ```jsonc
252
+ // → fig_variables { "file": "…", "query": "tab/large" }
253
+ { "totalSets": 27, "totalVariables": 273,
254
+ "sets": [ { "guid": "2:1312", "name": "active/inactive",
255
+ "modes": [ { "id": "509:1300", "name": "active" }, { "id": "509:1301", "name": "inactive" } ],
256
+ "variableCount": 38 } ],
257
+ "variables": [ { "guid": "2:1313", "name": "tab/large/bg", "type": "COLOR", "set": "active/inactive",
258
+ "values": { "active": "#FFFFFF", "inactive": "#EEEEEE" } } ] }
259
+ ```
260
+
261
+ ### 10. `fig_image` — embedded bitmaps
262
+
263
+ Pass `hash` (the 40-hex id that `fig_node` / `fig_style` report on image paints), or `guid` to
264
+ use the images on a node, or `hash: "thumbnail"` for the document preview. Images ≤ 2 MB come
265
+ back as viewable image content; larger ones return metadata, and `savePath` writes the exact
266
+ bytes to disk.
267
+
268
+ ```jsonc
269
+ // → fig_image { "file": "…", "hash": "01ef2f8cd2d276901473acb9ddd7afb2421198e3" }
270
+ // [image content] + { "mime": "image/png", "byteLength": 4553, "width": 88, "height": 84 }
271
+ ```
272
+
273
+ ### 11. `fig_blob` — raw payload bytes
274
+
275
+ `index` into the file's blob table (`fig_node` reports these as `vector.networkBlob` /
276
+ `vector.fillBlobs`), `encoding` (`base64` | `hex`), `maxBytes` (default 65536).
277
+
278
+ ```jsonc
279
+ // → fig_blob { "file": "…", "index": 16, "maxBytes": 8, "encoding": "hex" }
280
+ { "index": 16, "byteLength": 96, "returnedBytes": 8, "data": "0100000000020080",
281
+ "truncated": true, "blobCount": 9651 }
282
+ ```
283
+
284
+ ### 12. `fig_render` — a picture of a node
285
+
286
+ `guid` (any node, or a page), `format` (`png` | `svg`, default `png`), `scale` (default 2),
287
+ `maxSize` (longest edge, default 1568), `background` (`transparent` | `page`), `savePath`,
288
+ `maxNodes` (default 20000, counted in layers).
289
+
290
+ ```jsonc
291
+ // → fig_render { "file": "…", "guid": "2:1339" }
292
+ // [image content, 268x80 PNG]
293
+ { "root": { "guid": "2:1339", "name": "Frame 39", "type": "FRAME" },
294
+ "bounds": { "x": 0, "y": 0, "w": 134, "h": 40 }, "width": 268, "height": 80, "scale": 2,
295
+ "nodesVisited": 9, "nodesDrawn": 8, "svgBytes": 4757, "renderMs": 4.6, "rasterMs": 55.3,
296
+ "unsupported": [], "approximated": [], "format": "png" }
297
+ ```
298
+
299
+ ---
300
+
301
+ ## Rendering (`fig_render`)
302
+
303
+ Nothing is fetched and no font is needed: Figma stores outlined strokes, combined booleans,
304
+ per-glyph outlines and per-instance resolved geometry in the file, so the renderer consumes
305
+ what Figma already computed. The SVG it builds is rasterized by
306
+ [`@resvg/resvg-wasm`](https://github.com/yisibl/resvg-js), an **optional** dependency — with it
307
+ uninstalled, everything still works and `fig_render` returns SVG instead of PNG.
308
+
309
+ **Exact**: solid fills, linear and radial gradients, image fills in all four scale modes,
310
+ strokes including inside/outside alignment, boolean operations, text (glyph outlines, per-run
311
+ colours, underline and strikethrough, truncation with an ellipsis), component instances with
312
+ their overrides, their component properties (text, visibility, instance swap) and the sizes the
313
+ enclosing instance gives them, colour and effect styles resolved to their live definition, frame
314
+ clipping, layer opacity, the fifteen shared blend modes, drop and inner shadows, layer blur,
315
+ and all three mask types.
316
+
317
+ **Approximated, and always reported**: background blur (drawn flat — a backdrop filter cannot
318
+ see behind an isolated subtree), `LINEAR_DODGE` and `LINEAR_BURN` (drawn as `screen` and
319
+ `multiply`), angular and diamond gradients (drawn as their average colour), image crop and
320
+ image rotation.
321
+
322
+ **Skipped, and always reported**: emoji glyphs, FigJam-style nodes (`WIDGET`, `CONNECTOR`,
323
+ `SHAPE_WITH_TEXT`), text without stored outlines (including a text property whose words have
324
+ no outlines in the file), and strokes on text.
325
+
326
+ Fidelity was measured against a Figma export of a 1440×3026 form built from component
327
+ instances: 0.18 % of pixels differ, all anti-aliasing. That export came from a design that
328
+ is not public, so it is not distributed here — `npm run visual` runs levels 1-2 until you
329
+ supply your own export.
330
+
331
+ Every response carries `unsupported` and `approximated` lists naming the feature and up to five
332
+ example guids. An empty pair means the renderer believes it drew the node exactly. Exact values
333
+ always remain available from `fig_node`, `fig_style` and `fig_text`.
334
+
335
+ There is also a CLI for the same thing:
336
+
337
+ ```bash
338
+ npm run build
339
+ node scripts/render.mjs figma-input/sample.fig 2:1339 out.png --scale 2 --background page
340
+ ```
341
+
342
+ ---
343
+
344
+ ## How it stays inside a context window
345
+
346
+ - Default response budget **20,000 characters**, hard cap **50,000**.
347
+ - Never more than **300 nodes** per response, and never more than **one** `raw` node per call.
348
+ - Trees are **shallow by default** (depth 2) and every entry carries a child count, so the agent
349
+ chooses where to spend tokens.
350
+ - Unset fields are omitted, floats are rounded to 2 decimals, colours become `#RRGGBB`, and
351
+ sizes collapse to `"134x40"`.
352
+ - Anything cut sets `truncated: true` and returns an opaque `nextCursor`; paging is stable
353
+ because it follows document order.
354
+ - There is deliberately **no "dump everything" tool**.
355
+
356
+ ## How it works
357
+
358
+ ```
359
+ .fig bytes
360
+ ├─ Stage A container ZIP? unwrap canvas.fig (+ meta.json, thumbnail.png, images/<sha1>)
361
+ ├─ Stage B framing "fig-kiwi" magic, u32 version, length-prefixed chunks
362
+ ├─ Stage C codec sniffed per chunk: zstd / raw deflate / zlib / stored
363
+ ├─ Stage D Kiwi chunk[0] = the binary SCHEMA, chunk[1] = the data decoded WITH it
364
+ └─ Stage E tree rebuild the layer tree from parentIndex + fractional-index order
365
+ ```
366
+
367
+ The decisive detail is Stage D: **the schema ships inside the file**. Nothing here hardcodes a
368
+ field id, so Figma's constant schema additions do not break the reader.
369
+
370
+ ```
371
+ src/
372
+ fig/ LAYER 1 — mechanical decode, knows bytes, knows nothing about design
373
+ bytebuffer.ts Kiwi primitives (varuint, zigzag, the rotated float32, NUL strings)
374
+ zip.ts central-directory ZIP reader (Figma zeroes the local-header sizes)
375
+ container.ts container sniffing, chunk framing, per-chunk decompression
376
+ kiwi.ts binary-schema decode + schema-driven data decode
377
+ imagemeta.ts image magic-byte + dimension sniffing
378
+ invariants.ts post-parse checks; warnings, not failures
379
+ parse.ts the whole pipeline in one call
380
+ model/ LAYER 2 — Figma semantics, never touches bytes
381
+ tree.ts guid keys, tree build, fractional-index sibling order
382
+ index.ts FileIndex: by-guid, by-type, by-asset-key, override keys, prop defs, search
383
+ access.ts typed accessors over open records + presentation helpers
384
+ summarize.ts node summary / full detail / style block builders
385
+ text.ts characters + styled-run resolution
386
+ instance.ts what an instance looks like: identity paths, records, property assignments
387
+ components.ts symbols, instances, the fig_instance view
388
+ variables.ts collections, modes, alias chains
389
+ render/ LAYER 2½ — fig_render: node subtree → SVG → (optional) PNG
390
+ export.ts the traversal; instance.ts / style.ts / bounds.ts / text.ts / paint.ts /
391
+ effects.ts each own one concern; report.ts the frozen feature vocabulary
392
+ mcp/ LAYER 3 — protocol
393
+ create.ts server factory (used by the entry point and by tests)
394
+ server.ts stdio entry point
395
+ respond.ts budgets, cursors, truncation
396
+ tools/*.ts one file per tool
397
+ cache.ts LRU of parsed files, invalidated on mtime/size change
398
+ ```
399
+
400
+ `mcp/` and `model/` never touch bytes; `fig/` knows nothing about Figma semantics.
401
+
402
+ ## Testing
403
+
404
+ ```bash
405
+ npm test # build + full node:test suite (unit + golden)
406
+ npm run typecheck # type-checks src, test and scripts
407
+ npm run smoke # spawns the built server and walks the demo script over real stdio
408
+ npm run crosscheck # deep-compares our decode against the official kiwi-schema package
409
+ ```
410
+
411
+ - **Unit tests** need no asset: Kiwi primitives against a transcribed reference encoder, a
412
+ synthetic ZIP with data-descriptor entries, fractional-index ordering, the response budgeter,
413
+ image sniffing, and corrupt-input handling.
414
+ - **Golden tests** run against `figma-input/sample.fig` and assert measured values (116,142
415
+ nodes, 638 schema definitions, 10 pages, specific node geometry, …). They **skip with a clear
416
+ message** if the asset is absent.
417
+ - **Fixture identifiers are placeholders.** The design this was developed against is not
418
+ public. Page, component, variable and layer names in this README, in `docs/` and in the
419
+ golden tests were replaced with neutral stand-ins, and node guids were renumbered. The
420
+ structure and the measured numbers are real; the names are not, so the string assertions
421
+ will not match your own `.fig` until you update them.
422
+ - **Cross-check** decodes the same buffers with Evan Wallace's official `kiwi-schema` package and
423
+ deep-compares every field: currently **0 differences across 17,353,242 compared values**. It
424
+ skips cleanly if `kiwi-schema` is not installed.
425
+
426
+ `tools/fig2json.mjs` is the original dependency-free reference CLI that Layer 1 was ported from.
427
+ It is kept working as a debugging aid:
428
+
429
+ ```bash
430
+ node tools/fig2json.mjs figma-input/sample.fig /tmp/out
431
+ # writes schema.kiwi.txt, nodes.ndjson, tree-outline.txt, meta.json
432
+ ```
433
+
434
+ Dumping `schema.kiwi.txt` is the fastest way to look up a field this server does not map yet;
435
+ then read it with `fig_node detail:"raw"`.
436
+
437
+ ## Documentation
438
+
439
+ - [`docs/fig-reading-solution.md`](docs/fig-reading-solution.md) — the byte-level reading
440
+ procedure, verified end to end.
441
+ - [`docs/mcp-implementation-plan.md`](docs/mcp-implementation-plan.md) — the plan this server
442
+ implements, including the golden values in Appendix A.
443
+ - [`docs/fig-file-format.md`](docs/fig-file-format.md) — the measurement log and evidence.
444
+
445
+ ## License
446
+
447
+ MIT.
@@ -0,0 +1,29 @@
1
+ import { type ParsedFig } from './fig/parse.js';
2
+ import { FileIndex } from './model/index.js';
3
+ export interface CacheEntry {
4
+ readonly path: string;
5
+ readonly mtimeMs: number;
6
+ readonly size: number;
7
+ readonly fig: ParsedFig;
8
+ readonly index: FileIndex;
9
+ readonly loadedAt: number;
10
+ }
11
+ export interface CacheStats {
12
+ /** Files decoded from bytes since the process started. */
13
+ parses: number;
14
+ /** Tool calls served from an already-decoded file. */
15
+ hits: number;
16
+ cached: number;
17
+ maxFiles: number;
18
+ }
19
+ export declare class FileCache {
20
+ private readonly entries;
21
+ private readonly maxFiles;
22
+ readonly stats: CacheStats;
23
+ constructor(maxFiles?: number);
24
+ /** Absolute path for a user-supplied `file` argument; relative paths resolve from CWD. */
25
+ static resolve(file: string): string;
26
+ get(file: string): CacheEntry;
27
+ clear(): void;
28
+ }
29
+ //# sourceMappingURL=cache.d.ts.map
package/dist/cache.js ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Parsed-file cache.
3
+ *
4
+ * A 39 MB .fig decodes to roughly 900 MB of live JS objects, so entries are precious: keep a
5
+ * small LRU (4 by default), key on the absolute path, and re-parse whenever mtime or size
6
+ * changes. Parsing is lazy — nothing is read until a tool actually touches a path.
7
+ */
8
+ import * as fs from 'node:fs';
9
+ import * as path from 'node:path';
10
+ import { parseFig } from './fig/parse.js';
11
+ import { FileIndex } from './model/index.js';
12
+ export class FileCache {
13
+ entries = new Map();
14
+ maxFiles;
15
+ stats;
16
+ constructor(maxFiles = 4) {
17
+ this.maxFiles = Math.max(1, maxFiles);
18
+ this.stats = { parses: 0, hits: 0, cached: 0, maxFiles: this.maxFiles };
19
+ }
20
+ /** Absolute path for a user-supplied `file` argument; relative paths resolve from CWD. */
21
+ static resolve(file) {
22
+ return path.resolve(file);
23
+ }
24
+ get(file) {
25
+ const abs = FileCache.resolve(file);
26
+ let stat;
27
+ try {
28
+ stat = fs.statSync(abs);
29
+ }
30
+ catch {
31
+ throw new Error(`file not found: ${abs}`);
32
+ }
33
+ if (!stat.isFile())
34
+ throw new Error(`not a file: ${abs}`);
35
+ const existing = this.entries.get(abs);
36
+ if (existing && existing.mtimeMs === stat.mtimeMs && existing.size === stat.size) {
37
+ // Refresh LRU position.
38
+ this.entries.delete(abs);
39
+ this.entries.set(abs, existing);
40
+ this.stats.hits++;
41
+ return existing;
42
+ }
43
+ const fig = parseFig(fs.readFileSync(abs));
44
+ const entry = {
45
+ path: abs,
46
+ mtimeMs: stat.mtimeMs,
47
+ size: stat.size,
48
+ fig,
49
+ index: new FileIndex(fig),
50
+ loadedAt: Date.now(),
51
+ };
52
+ this.entries.delete(abs);
53
+ this.entries.set(abs, entry);
54
+ this.stats.parses++;
55
+ while (this.entries.size > this.maxFiles) {
56
+ const oldest = this.entries.keys().next().value;
57
+ if (oldest === undefined)
58
+ break;
59
+ this.entries.delete(oldest);
60
+ }
61
+ this.stats.cached = this.entries.size;
62
+ return entry;
63
+ }
64
+ clear() {
65
+ this.entries.clear();
66
+ this.stats.cached = 0;
67
+ }
68
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Kiwi primitive decoders (fig-reading-solution.md §4).
3
+ *
4
+ * Direct port of class `BB` in tools/fig2json.mjs, which was validated byte-for-byte against
5
+ * the official `kiwi-schema` package. Do not "improve" these — every later stage desynchronizes
6
+ * within a few fields if a primitive is off by one byte.
7
+ */
8
+ export declare class ByteBuffer {
9
+ readonly b: Buffer;
10
+ i: number;
11
+ constructor(buf: Buffer, offset?: number);
12
+ get remaining(): number;
13
+ byte(): number;
14
+ bytes(n: number): Buffer;
15
+ /** Unsigned LEB128, max 5 bytes (32-bit) — mirrors kiwi readVarUint. */
16
+ varUint(): number;
17
+ /** Zigzag-encoded signed 32-bit — mirrors kiwi readVarInt. */
18
+ varInt(): number;
19
+ /** Unsigned LEB128 up to 9 bytes; the 9th byte contributes all 8 bits. */
20
+ varUint64(): bigint;
21
+ varInt64(): bigint;
22
+ /**
23
+ * Kiwi float32: a single 0x00 byte means 0.0, otherwise 4 bytes bit-rotated so the exponent
24
+ * lands in the first byte (better entropy for compression) — mirrors kiwi readVarFloat.
25
+ * Values decode as float32, so 0.2 legitimately reads back as 0.20000000298023224.
26
+ */
27
+ varFloat(): number;
28
+ /** UTF-8 bytes up to (not including) the next NUL; the cursor advances past the NUL. */
29
+ string(): string;
30
+ }
31
+ //# sourceMappingURL=bytebuffer.d.ts.map