openfig-mcp 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 openfig-mcp contributors
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.
22
+
23
+ src/vendor/svg-builder.mjs is from openfig-cli (MIT) — see src/vendor/LICENSE-openfig-cli.
package/README.md CHANGED
@@ -1,3 +1,208 @@
1
- # Temporary Holding Version
1
+ # openfig-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Figma `.fig` files → LLM-ready design data, over MCP.** No Figma account, API token or plugin: point it
4
+ at a downloaded `.fig` file and your coding agent (GitHub Copilot, Claude, Cursor, …) can list the
5
+ screens, pull any frame as HTML + CSS, see it as an image, and get the design tokens, components,
6
+ hover/press states, animations, prototype links, icons (SVG), images and fonts.
7
+
8
+ Built on [OpenFig](https://github.com/OpenFig-org)'s `.fig` parser ([openfig-core](https://github.com/OpenFig-org/openfig-core)) and SVG renderer.
9
+
10
+ ## Quick start — VS Code + GitHub Copilot
11
+
12
+ 1. Save your Figma file into the project as `design.fig`
13
+ (Figma: *Main menu → File → Save local copy…*, or *Download* on a Community file).
14
+ 2. Add `.vscode/mcp.json`:
15
+
16
+ ```json
17
+ {
18
+ "servers": {
19
+ "openfig": {
20
+ "type": "stdio",
21
+ "command": "npx",
22
+ "args": ["-y", "openfig-mcp", "${workspaceFolder}/design.fig"]
23
+ }
24
+ }
25
+ }
26
+ ```
27
+
28
+ 3. Open Copilot Chat in **Agent** mode and describe what you want built. For example:
29
+
30
+ > Implement the "Login" screen from the design in React + Tailwind.
31
+
32
+ > Use openfig to build `https://www.figma.com/design/…?node-id=12-345` as a Vue component.
33
+
34
+ These are only examples: ask in your own words, for your own stack.
35
+
36
+ The file given in `args` is the default for every tool. Frames can be referenced by **name** (`"Login"`),
37
+ **id** (`"12:345"`) or a **Figma URL** with `node-id`. Working with several files? Pass a folder
38
+ (`"${workspaceFolder}/designs"`) instead, and name the file in the prompt ("…from `designs/app.fig`").
39
+
40
+ ### Other clients
41
+
42
+ <details><summary>Claude Desktop / Claude Code / Cursor / Windsurf</summary>
43
+
44
+ ```json
45
+ { "mcpServers": { "openfig": { "command": "npx", "args": ["-y", "openfig-mcp", "/absolute/path/to/design.fig"] } } }
46
+ ```
47
+ Claude Code: `claude mcp add openfig -- npx -y openfig-mcp ./design.fig`
48
+ </details>
49
+
50
+ ## Tools
51
+
52
+ | Tool | What the agent gets |
53
+ |---|---|
54
+ | `list_fig_files` | `.fig` files in the workspace |
55
+ | `list_frames` | pages → sections → screens / frames / component sets, with ids, sizes, prototype start points |
56
+ | `get_frame` | **the main tool.** Summary (fonts, components + variants, tokens, `:hover`/`:active` states, auto-playing animations, navigation & modals) **plus** an HTML + CSS reproduction. Writes an export folder (below) |
57
+ | `render_frame` | PNG image of any frame/node so the model can *see* it |
58
+ | `get_design_tokens` | color / text / effect styles **and Figma Variables (all modes, e.g. light/dark)** as CSS custom properties + typography classes, or JSON |
59
+ | `list_components` | components & variant sets with their properties (`State=Hover`, `Size=lg`…) and usage counts |
60
+ | `get_component` | every variant, the CSS diff between interactive states, HTML/CSS of the set |
61
+ | `search_nodes` | find layers by name or text ("Sign in", "price") |
62
+ | `get_prototype_flows` | flows and every click/hover/timer link between screens, overlays (modals), URLs |
63
+ | `export_svg` | any icon / logo / vector as SVG |
64
+
65
+ Plus an MCP prompt **`implement_frame`** (in VS Code: `/mcp.openfig.implement_frame`).
66
+
67
+ ### What `get_frame` writes
68
+
69
+ ```
70
+ figma-export/<frame>-<id>/
71
+ DESIGN.md summary: fonts, components, states, animations, links, modals
72
+ index.html HTML reproduction (flex where Figma used auto-layout, absolute elsewhere)
73
+ styles.css one class per unique style + :hover / :active rules from variant interactions
74
+ tokens.css CSS variables for the tokens this frame uses (styles + variables, per mode)
75
+ spec.json full tree: box, style, text runs, constraints, component/variant info, interactions
76
+ preview.png rendering of the frame
77
+ assets/ SVG icons & vectors, images (png/jpg/gif/webp), masked groups as PNG
78
+ ```
79
+
80
+ The inline response is budgeted (`maxChars`, default 40k): deep subtrees are collapsed with a pointer
81
+ to drill in (`get_frame` on a section id), and the full files are always on disk.
82
+
83
+ ## What is extracted
84
+
85
+ | Figma | Output |
86
+ |---|---|
87
+ | Auto layout (direction, gap, padding, alignment, wrap, hug / fill / fixed, absolute children, margins) | `display:flex`, `gap`, `padding`, `justify-content`, `align-items`, `flex: 1`, `align-self`, `fit-content` |
88
+ | Frames without auto layout, constraints | absolute positioning (+ constraints in `spec.json`) |
89
+ | Fills: solid, linear/radial/angular gradients, images (fill/fit/tile/crop), multiple layers | `background` (stacked), `<img object-fit>` |
90
+ | Strokes (inside/center/outside, per-side, dashed), corner radii (per corner) | `outline`/`border-*`, `border-radius` |
91
+ | Effects: drop/inner shadow, layer & background blur | `box-shadow`, `text-shadow`, `filter`, `backdrop-filter` |
92
+ | Opacity, blend modes, clip content, scrolling frames | `opacity`, `mix-blend-mode`, `overflow` |
93
+ | Text: font, weight, size, line height, letter spacing, case, decoration, alignment, truncation, mixed-style runs, links | full typography, `<span>` runs, `<a>` |
94
+ | Color / text / effect styles, Figma Variables + modes | `var(--color-primary-600)`, `.ts-text-md-semibold`, `[data-theme="dark"]` blocks |
95
+ | Components, variants, instance overrides, component properties (text / boolean / instance swap) | resolved per instance; `data-component` / `data-variant` attributes |
96
+ | Prototype interactions, variants, states | see [Interactivity](#interactivity) |
97
+ | Vectors, icons, boolean ops, masks | SVG files (icons deduplicated), masked groups → PNG |
98
+ | Fonts | reported, not bundled: family, weights and styles of every font used, with a warning to add them to the project (and whether each is installed locally) |
99
+
100
+ Ids of nodes inside component instances use Figma's own format (`I<instance>;<child>`).
101
+
102
+ ## Interactivity
103
+
104
+ Everything Figma's prototype model can express is extracted, and turned into CSS where CSS can express it:
105
+
106
+ | Figma | Output |
107
+ |---|---|
108
+ | **Triggers**: on click, while hovering, while pressing, mouse enter / leave / down / up, after delay, key press (key names, e.g. `Escape`), drag, video events | per element in `spec.json`, `data-on-click="…"` / `data-on-hover="…"` / `data-on-key="…"` attributes, and a plain-English list in the summary |
109
+ | **Navigate to** another frame, **back**, **scroll to** a layer (+ offset), **open URL** (new tab or not) | "click → navigates to "Checkout" (12:34) [smart animate 300ms ease-out]" |
110
+ | **Overlays / modals**: open, swap, close; position, backdrop color, close-on-outside-click | "click → opens overlay/modal "Share" — position center, closes on outside click, backdrop rgba(0,0,0,0.5)" |
111
+ | **Variant swaps** ("change to") | CSS diff between the two variants, plus exactly **which layers appear and disappear** (`shows "Dropdown menu"`, `hides "Badge"`) |
112
+ | **Variables**: set variable (with expressions like `!menuOpen`), set mode (theme / language), **conditionals** (if / else) | "click → sets menuOpen = !menuOpen → toggles visibility of "Dropdown menu" (hidden by default)" (layers whose visibility is bound to the variable are resolved) |
113
+ | **Pseudo-classes** | `:hover`, `:active` (from hover / press interactions, chains like Default → Hover → Pressed included) and, from variant naming (`State=Hover / Pressed / Focused / Disabled`, `Selected / Checked / Open = True`, `State=Error / Loading`): `:hover`, `:active`, `:focus-visible`, `:disabled` + `[aria-disabled]`, `[aria-selected]`, `:checked` + `[aria-checked]`, `[aria-expanded]`, `[aria-invalid]`, `[aria-busy]`. Layers hidden in the target state get `display: none`; layers that only exist in the target state are listed so they can be rendered conditionally |
114
+ | **Timers** (after delay → change variant) | grouped into auto-playing animations (carousels, marquees, loaders) with each step's delay, transition and easing |
115
+ | **Transitions** | type (instant, dissolve, slide/push/move in/out, smart animate), duration, easing as `cubic-bezier()` |
116
+ | **Scrolling**: scroll direction, fixed and sticky layers | `overflow`, `data-scroll="fixed|sticky"`, listed in the summary |
117
+ | **Prototype flows** | `get_prototype_flows`: starting points and every link between screens |
118
+
119
+ Hover and press states become CSS rules. Click toggles, key handlers, variables and conditionals are
120
+ described precisely (trigger, effect, timing) for the agent to implement in the app's framework.
121
+
122
+ ## Fidelity
123
+
124
+ `npm run fidelity -- <file.fig>` lays every generated `index.html` out in a real browser and compares
125
+ each element's box with the layout **Figma stored in the file**, checks every text string and asset,
126
+ and computes SSIM against the rendered preview. Results on the 33 non-empty screens of a 134 MB
127
+ community file (8 interactive UI designs, 23k layers; 4,797 elements compared):
128
+
129
+ | Metric | Fonts as-is | Text boxes at Figma's size (`--pin-text`) |
130
+ |---|---|---|
131
+ | Elements within 8 px of Figma's position & size | 93.2 % (median screen 97.8 %) | **99.5 %** (median screen 100 %) |
132
+ | Elements within 2 px | 87.9 % | 99.5 % |
133
+ | Text strings present | 100 % | 100 % |
134
+ | Broken asset references (2,337 images / SVGs) | 0 | 0 |
135
+
136
+ **Why not 100 %?** The design uses fonts the test browser doesn't have (*Satoshi*, *Clash Display*,
137
+ *Zen Dots*). The fallback font has different glyph widths and line heights, so every text box that
138
+ hugs its content gets a different size, and that shifts its containers and siblings in auto-layout.
139
+ Pin the text boxes to the sizes Figma measured (`--pin-text`) and that whole category disappears:
140
+ 99.5 % of elements land within 2 px. The remaining 0.5 % are a handful of rotated/skewed mockup layers
141
+ and masked decorative groups. With the design's real fonts installed in your app, you get the
142
+ right-hand column.
143
+
144
+ The metric is strict: an element counts as wrong if *any* of x, y, width or height is off, and one
145
+ mis-sized parent marks all its descendants as wrong too. See `examples/fidelity-report.md`.
146
+
147
+ ## CLI
148
+
149
+ The same package is a CLI (handy for CI or a quick look):
150
+
151
+ ```bash
152
+ npx -y openfig-mcp frames design.fig # list frames
153
+ npx -y openfig-mcp export design.fig "Login" -o out/ # export bundle
154
+ npx -y openfig-mcp render design.fig 12:345 -o login.png
155
+ npx -y openfig-mcp tokens design.fig [--json]
156
+ npx -y openfig-mcp components design.fig [query]
157
+ npx -y openfig-mcp search design.fig "Sign in"
158
+ npx -y openfig-mcp flows design.fig
159
+ ```
160
+
161
+ ## Library
162
+
163
+ ```js
164
+ import { FigFile } from 'openfig-mcp';
165
+ const fig = await FigFile.open('design.fig');
166
+ fig.listFrames(); // [{ id, name, kind, page, size, ... }]
167
+ const r = await fig.getFrame('Login', { outDir: 'out/login' });
168
+ r.summary; r.fullHtml; r.fullCss; r.spec; r.meta.states;
169
+ const { png } = await fig.render('12:345');
170
+ fig.tokens().css;
171
+ ```
172
+
173
+ ## Configuration
174
+
175
+ | Env var | |
176
+ |---|---|
177
+ | `OPENFIG_MCP_FONT_DIRS=dir1;dir2` | optional extra local font folders used for preview renders (`render_frame`, `preview.png`). Otherwise installed system fonts are used, with a common UI font as fallback |
178
+
179
+ ## Fonts
180
+
181
+ openfig-mcp never downloads or bundles fonts. Providing them is the project's job. Every `get_frame` /
182
+ `render_frame` response lists the fonts the design needs (family, weights, styles) with a warning, and
183
+ says which ones aren't installed on the machine. Generated CSS uses `font-family: 'Family', sans-serif`.
184
+
185
+ ## Limitations
186
+
187
+ - `.fig` is Figma's private format. openfig follows it closely, but a new Figma release can add fields
188
+ before the parser knows them. Everything unknown is passed through to `spec.json` as-is.
189
+ - `render_frame` / `preview.png` come from openfig's renderer, not Figma: good for layout and color,
190
+ but text uses installed fonts (or a fallback), and complex blend modes and some effects (noise, glass,
191
+ progressive blur) are approximate.
192
+ - Components from **unpublished external libraries** only exist in the file as the copies Figma
193
+ embeds (that is usually all that is needed).
194
+ - Smart-animate transitions are described (from/to state, duration, easing). The generated CSS
195
+ covers hover/press states. Click toggles, carousels and page transitions are listed for the agent
196
+ to implement in JS.
197
+ - Figma Variables support follows the file schema and is covered by tests with synthetic data. The
198
+ sample community file uses styles, not variables.
199
+
200
+ ## Development
201
+
202
+ ```bash
203
+ npm install
204
+ npm test # unit + end-to-end MCP tests (FIG_SAMPLE=/path/to.fig for the big ones)
205
+ npm run fidelity -- design.fig [frameId…] # browser-based fidelity report (needs Edge/Chrome or CHROME_PATH)
206
+ ```
207
+
208
+ MIT. Figma is a trademark of Figma, Inc. This project is not affiliated with Figma.
@@ -0,0 +1,71 @@
1
+ #!/usr/bin/env node
2
+ // openfig-mcp — MCP server (default) + a small CLI for humans/CI.
3
+ import { resolve } from 'path';
4
+ import { writeFileSync } from 'fs';
5
+
6
+ const HELP = `openfig-mcp — Figma .fig files as LLM-ready design data (MCP server + CLI)
7
+
8
+ MCP server (stdio):
9
+ openfig-mcp [file.fig | folder ...] Serve the given .fig files / folders (default: workspace roots, then cwd)
10
+
11
+ CLI:
12
+ openfig-mcp frames <file.fig> [query] List pages / frames
13
+ openfig-mcp export <file.fig> <frame> [-o dir] Export frame → index.html, styles.css, tokens.css, assets/, spec.json, preview.png
14
+ openfig-mcp render <file.fig> <frame> [-o out.png] [--max 1600]
15
+ openfig-mcp tokens <file.fig> [--json] Design tokens as CSS variables (or JSON)
16
+ openfig-mcp components <file.fig> [query]
17
+ openfig-mcp search <file.fig> <query>
18
+ openfig-mcp flows <file.fig>
19
+
20
+ <frame> = node id ("1:234"), Figma URL with node-id, or frame name.
21
+ Env: OPENFIG_MCP_FONT_DIRS=dir1;dir2 (extra local font folders used for preview renders)`;
22
+
23
+ const argv = process.argv.slice(2);
24
+ const CMDS = new Set(['frames', 'export', 'render', 'tokens', 'components', 'search', 'flows']);
25
+ const flag = (name, def) => { const i = argv.indexOf(name); if (i < 0) return def; const v = argv[i + 1]; argv.splice(i, 2); return v; };
26
+ const bool = name => { const i = argv.indexOf(name); if (i < 0) return false; argv.splice(i, 1); return true; };
27
+
28
+ if (argv[0] === '-h' || argv[0] === '--help') { console.log(HELP); process.exit(0); }
29
+ if (argv[0] === '-v' || argv[0] === '--version') { const { createRequire } = await import('module'); console.log(createRequire(import.meta.url)('../package.json').version); process.exit(0); }
30
+
31
+ if (!CMDS.has(argv[0])) {
32
+ // ---------------- MCP server
33
+ const { StdioServerTransport } = await import('@modelcontextprotocol/sdk/server/stdio.js');
34
+ const { createServer } = await import('../src/server.mjs');
35
+ const server = createServer({ paths: argv.filter(a => !a.startsWith('-')) });
36
+ await server.connect(new StdioServerTransport());
37
+ process.stderr.write(`[openfig-mcp] ready (${argv.length ? argv.join(', ') : 'workspace roots / cwd'})\n`);
38
+ } else {
39
+ // ---------------- CLI
40
+ const { FigFile } = await import('../src/api.mjs');
41
+ const cmd = argv.shift();
42
+ const out = flag('-o') ?? flag('--out');
43
+ const max = +flag('--max', 1600);
44
+ const asJson = bool('--json');
45
+ const [file, arg] = argv;
46
+ if (!file) { console.error(HELP); process.exit(1); }
47
+ const f = await FigFile.open(file);
48
+ try {
49
+ if (cmd === 'frames') {
50
+ for (const fr of f.listFrames({ query: arg })) console.log(`${fr.id.padEnd(10)} ${fr.kind.padEnd(13)} ${fr.size.padEnd(10)} ${fr.page}${fr.group ? ' / ' + fr.group : ''} / ${fr.name}${fr.flowStart ? ' ▶ ' + fr.flowStart : ''}`);
51
+ } else if (cmd === 'export') {
52
+ const r = await f.getFrame(arg, { outDir: out });
53
+ console.log(r.summary);
54
+ console.log(`Exported to ${r.dir}`);
55
+ } else if (cmd === 'render') {
56
+ const { png, node } = await f.render(arg, { maxDim: max });
57
+ const p = resolve(out || `${node.id.replace(':', '-')}.png`);
58
+ writeFileSync(p, png); console.log(`Wrote ${p}`);
59
+ } else if (cmd === 'tokens') {
60
+ const t = f.tokens();
61
+ if (asJson) { const { css, ...rest } = t; console.log(JSON.stringify(rest, null, 1)); } else console.log(t.css);
62
+ } else if (cmd === 'components') {
63
+ for (const c of f.components({ query: arg })) console.log(`${c.id.padEnd(10)} ${c.name} — ${c.variants} variant(s), used ${c.uses}× ${Object.entries(c.properties).map(([k, v]) => `${k}=${Array.isArray(v) ? v.join('|') : v}`).join('; ')}`);
64
+ } else if (cmd === 'search') {
65
+ for (const h of f.search(arg)) console.log(`${h.id.padEnd(10)} ${h.type.padEnd(10)} ${h.name}${h.text ? ` "${h.text}"` : ''} (${h.page}${h.path ? ' / ' + h.path : ''})`);
66
+ } else if (cmd === 'flows') {
67
+ console.log(JSON.stringify(f.flows(), null, 1));
68
+ }
69
+ } catch (e) { console.error(`Error: ${e.message}`); process.exit(1); }
70
+ process.exit(0);
71
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "openfig-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "MCP server that turns Figma .fig files into LLM-ready design specs: frames, HTML/CSS, tokens, components, hover states, animations, SVG icons, images and fonts. Works offline, no Figma API token.",
5
+ "type": "module",
6
+ "bin": {
7
+ "openfig-mcp": "bin/openfig-mcp.mjs"
8
+ },
9
+ "exports": {
10
+ ".": "./src/index.mjs",
11
+ "./package.json": "./package.json"
12
+ },
13
+ "files": [
14
+ "bin/",
15
+ "src/",
16
+ "README.md",
17
+ "LICENSE"
18
+ ],
19
+ "engines": {
20
+ "node": ">=20"
21
+ },
22
+ "scripts": {
23
+ "start": "node bin/openfig-mcp.mjs",
24
+ "test": "node --test test/unit.test.mjs test/mcp.test.mjs",
25
+ "fidelity": "node test/fidelity.mjs"
26
+ },
27
+ "keywords": [
28
+ "figma",
29
+ "fig",
30
+ "mcp",
31
+ "model-context-protocol",
32
+ "design-tokens",
33
+ "copilot",
34
+ "llm",
35
+ "design-to-code"
36
+ ],
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/AmirShokry/openfig-mcp.git"
40
+ },
41
+ "homepage": "https://github.com/AmirShokry/openfig-mcp#readme",
42
+ "bugs": {
43
+ "url": "https://github.com/AmirShokry/openfig-mcp/issues"
44
+ },
45
+ "license": "MIT",
46
+ "dependencies": {
47
+ "@modelcontextprotocol/sdk": "^1.27.1",
48
+ "@resvg/resvg-wasm": "^2.6.2",
49
+ "openfig-core": "^0.4.1",
50
+ "zod": "^3.25.0 || ^4.0.0"
51
+ },
52
+ "devDependencies": {
53
+ "playwright-core": "^1.59.1",
54
+ "pngjs": "^7.0.0",
55
+ "ssim.js": "^3.5.0"
56
+ }
57
+ }