openfig-mcp 0.1.0 → 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/src/server.mjs CHANGED
@@ -1,246 +1,246 @@
1
- // MCP server exposing .fig files as LLM-ready design data.
2
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
- import { z } from 'zod';
4
- import { existsSync, readdirSync, statSync } from 'fs';
5
- import { isAbsolute, join, resolve, basename } from 'path';
6
- import { fileURLToPath } from 'url';
7
- import { FigFile } from './api.mjs';
8
- import { Converter, variantStates } from './convert.mjs';
9
- import { idOf } from './util.mjs';
10
-
11
- const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', '.next', 'figma-export', '.cache', 'coverage', 'fixtures', '__fixtures__']);
12
-
13
- /** Resolves which .fig file a tool call refers to. */
14
- export class Workspace {
15
- constructor({ paths = [], cwd = process.cwd() } = {}) {
16
- this.cwd = cwd;
17
- this.files = []; this.dirs = [];
18
- for (const p of paths) {
19
- const abs = resolve(cwd, p);
20
- if (!existsSync(abs)) { process.stderr.write(`[openfig-mcp] warning: path not found: ${abs}\n`); continue; }
21
- (statSync(abs).isDirectory() ? this.dirs : this.files).push(abs);
22
- }
23
- this.roots = [];
24
- }
25
- setRoots(uris) { this.roots = uris.map(u => { try { return u.startsWith('file:') ? fileURLToPath(u) : u; } catch { return null; } }).filter(Boolean); }
26
- searchDirs() { const s = [...this.dirs, ...this.roots]; if (!s.length) s.push(this.cwd); return [...new Set(s)]; }
27
- discover(limit = 200) {
28
- const found = new Set(this.files);
29
- const walk = (d, depth) => {
30
- if (found.size >= limit) return;
31
- let entries; try { entries = readdirSync(d, { withFileTypes: true }); } catch { return; }
32
- for (const e of entries) {
33
- if (e.isDirectory()) { if (depth < 5 && !SKIP_DIRS.has(e.name) && !e.name.startsWith('.')) walk(join(d, e.name), depth + 1); }
34
- else if (/\.fig$/i.test(e.name)) found.add(join(d, e.name));
35
- }
36
- };
37
- for (const d of this.searchDirs()) walk(d, 0);
38
- return [...found];
39
- }
40
- resolve(file) {
41
- if (file) {
42
- const f = String(file).trim().replace(/^["']|["']$/g, '');
43
- if (isAbsolute(f) && existsSync(f)) return f;
44
- for (const base of [...this.searchDirs(), this.cwd]) { const p = resolve(base, f); if (existsSync(p) && statSync(p).isFile()) return p; }
45
- const all = this.discover();
46
- const q = basename(f).toLowerCase().replace(/\.fig$/, '');
47
- const hits = all.filter(p => basename(p).toLowerCase().includes(q));
48
- if (hits.length === 1) return hits[0];
49
- if (hits.length > 1) throw new Error(`"${file}" matches several files:\n${hits.map(h => ' ' + h).join('\n')}`);
50
- throw new Error(`Could not find "${file}". Known .fig files:\n${all.map(h => ' ' + h).join('\n') || ' (none found — pass an absolute path)'}`);
51
- }
52
- if (this.files.length === 1) return this.files[0];
53
- const all = this.discover();
54
- if (all.length === 1) return all[0];
55
- if (!all.length) throw new Error(`No .fig file found in ${this.searchDirs().join(', ')}. Pass "file" with a path to a .fig file.`);
56
- throw new Error(`Several .fig files available — pass "file" (name or path):\n${all.map(h => ' ' + h).join('\n')}`);
57
- }
58
- }
59
-
60
- const text = s => ({ content: [{ type: 'text', text: s }] });
61
- const json = o => text(JSON.stringify(o, null, 1));
62
- const fail = e => ({ content: [{ type: 'text', text: `Error: ${e.message || e}` }], isError: true });
63
- const fileArg = z.string().optional().describe('Path or name of the .fig file. Optional when the workspace has exactly one .fig file or one was passed on the command line.');
64
- const frameArg = z.string().describe('Frame/node to use: a node id like "1:234", a Figma URL containing node-id=1-234, or the frame name (e.g. "MacBook Pro 14\\" - 4", "Login").');
65
-
66
- const INSTRUCTIONS = `openfig-mcp reads Figma .fig files locally (no Figma API token) and returns design data ready for implementation.
67
- Typical workflow:
68
- 1. list_frames → pick the screen/frame (ids look like "1:234"; Figma URLs with node-id also work).
69
- 2. get_frame → summary (fonts, components, tokens, hover/press states, animations, navigation/modals) + HTML/CSS reproduction. It also writes index.html, styles.css, tokens.css, spec.json, preview.png and assets/ (SVG icons, images) to disk — reference those asset files directly and read the files for full detail.
70
- 3. render_frame to SEE the design (PNG) and compare with your implementation.
71
- Other tools: get_design_tokens (colors/typography/shadows/variables as CSS vars), list_components / get_component (variants + state CSS), search_nodes, get_prototype_flows, export_svg.
72
- Treat the generated HTML as a precise reference for sizes, spacing, colors and structure; rewrite it into idiomatic components (flex layouts, semantic tags, the project's framework) rather than copying absolute positioning verbatim.`;
73
-
74
- export function createServer({ paths = [], cwd } = {}) {
75
- const ws = new Workspace({ paths, cwd });
76
- const pkg = { name: 'openfig-mcp', version: '0.1.0' };
77
- const server = new McpServer(pkg, { instructions: INSTRUCTIONS, capabilities: { logging: {} } });
78
-
79
- let rootsLoaded = false;
80
- async function refreshRoots() {
81
- if (rootsLoaded) return;
82
- rootsLoaded = true;
83
- try {
84
- if (server.server.getClientCapabilities()?.roots) {
85
- const { roots } = await server.server.listRoots();
86
- ws.setRoots(roots.map(r => r.uri));
87
- }
88
- } catch { /* client without roots support */ }
89
- }
90
- /** Open the file the call refers to. With no file and several candidates, pick the one containing `frame`. */
91
- async function open(file, frame) {
92
- await refreshRoots();
93
- try { return await FigFile.open(ws.resolve(file)); }
94
- catch (e) {
95
- if (file || !frame || !/Several \.fig files/.test(e.message)) throw e;
96
- const hits = [];
97
- for (const p of ws.discover()) { const f = await FigFile.open(p); try { f.findNode(frame); hits.push(f); } catch {} }
98
- if (hits.length === 1) return hits[0];
99
- throw hits.length ? new Error(`"${frame}" exists in several files — pass "file":\n${hits.map(h => ' ' + h.path).join('\n')}`) : e;
100
- }
101
- }
102
- const tool = (name, description, shape, fn) => server.registerTool(name, { description, inputSchema: shape }, async args => { try { return await fn(args); } catch (e) { return fail(e); } });
103
-
104
- tool('list_fig_files', 'List the Figma .fig files available in the workspace (or passed on the command line).', {}, async () => {
105
- await refreshRoots();
106
- const files = ws.discover();
107
- return text(files.length ? files.map(f => `- ${f} (${(statSync(f).size / 1e6).toFixed(1)} MB)`).join('\n') : `No .fig files found under ${ws.searchDirs().join(', ')}`);
108
- });
109
-
110
- tool('list_frames', 'List the pages and top-level frames (screens, component sets, frames) in a .fig file, with ids, sizes and prototype flow starting points.', {
111
- file: fileArg,
112
- page: z.string().optional().describe('Only this page (name or id).'),
113
- query: z.string().optional().describe('Filter by frame/section/page name.'),
114
- includeComponents: z.boolean().optional().describe('Include component sets/components placed on pages (default true).'),
115
- }, async ({ file, page, query, includeComponents }) => {
116
- const f = await open(file);
117
- const frames = f.listFrames({ page, query, includeComponents });
118
- const pages = f.doc.pages().map(p => p.name);
119
- const lines = [`File: ${f.path}`, `Pages: ${pages.join(', ')}`, `${frames.length} frames:`];
120
- let last = null;
121
- for (const fr of frames) {
122
- const g = `${fr.page}${fr.group ? ' / ' + fr.group : ''}`;
123
- if (g !== last) { lines.push(`\n## ${g}`); last = g; }
124
- lines.push(`- ${fr.id} ${fr.kind.padEnd(13)} "${fr.name}" ${fr.size}${fr.flowStart ? ` ▶ prototype start (${fr.flowStart})` : ''}`);
125
- }
126
- return text(lines.join('\n'));
127
- });
128
-
129
- tool('get_frame', 'Convert a frame/screen/component (any node) into implementation-ready design data: summary of fonts, components + variants, design tokens, hover/active states, auto-playing animations, navigation and modals, plus an HTML+CSS reproduction. Writes index.html, styles.css, tokens.css, spec.json, DESIGN.md, preview.png and assets/ (SVG icons, images) to disk.', {
130
- file: fileArg,
131
- frame: frameArg,
132
- outDir: z.string().optional().describe('Where to write the export (default: <fig folder>/figma-export/<frame>-<id>/).'),
133
- maxChars: z.number().int().min(4000).max(400000).optional().describe('Budget for the inline response (default 40000). Deep subtrees are collapsed when over budget; full files are always written to disk.'),
134
- includeHtml: z.boolean().optional().describe('Include HTML/CSS inline in the response (default true).'),
135
- }, async ({ file, frame, outDir, maxChars = 40000, includeHtml = true }) => {
136
- const f = await open(file, frame);
137
- const r = await f.getFrame(frame, { outDir, maxChars });
138
- const out = [r.summary];
139
- if (r.sections.length > 1) {
140
- out.push(`## Top-level sections (call get_frame on an id to drill in)\n${r.sections.map(s => `- ${s.id} "${s.name}" (${s.type}, ${s.nodes} nodes) ${s.box}`).join('\n')}`);
141
- }
142
- if (includeHtml) {
143
- out.push(`## tokens.css\n\`\`\`css\n${r.tokensCss}\`\`\``);
144
- out.push(`## styles.css\n\`\`\`css\n${r.css}\n\`\`\``);
145
- out.push(`## index.html (body)${r.truncatedDepth ? ` — collapsed below depth ${r.truncatedDepth} to fit; full HTML in ${r.files.html}` : ''}\n\`\`\`html\n${r.html}\n\`\`\``);
146
- }
147
- return text(out.join('\n\n'));
148
- });
149
-
150
- tool('render_frame', 'Render a frame/node to a PNG image so you can see the design. Returns the image (and saves it if outPath is given).', {
151
- file: fileArg, frame: frameArg,
152
- maxSize: z.number().int().min(200).max(4096).optional().describe('Max width/height of the returned image in px (default 1600).'),
153
- outPath: z.string().optional().describe('Also save the PNG here.'),
154
- }, async ({ file, frame, maxSize = 1600, outPath }) => {
155
- const f = await open(file, frame);
156
- const { png, node, fontWarning: fw } = await f.render(frame, { maxDim: maxSize });
157
- if (outPath) { const { writeFileSync, mkdirSync } = await import('fs'); const { dirname } = await import('path'); mkdirSync(dirname(resolve(outPath)), { recursive: true }); writeFileSync(resolve(outPath), png); }
158
- return { content: [
159
- { type: 'image', data: png.toString('base64'), mimeType: 'image/png' },
160
- { type: 'text', text: `Rendered "${node.name}" (${node.id}, ${Math.round(node.size.x)}×${Math.round(node.size.y)}).${fw ? ` ${fw}` : ''} Note: this is an approximate render by openfig; small differences from Figma are expected.${outPath ? ` Saved to ${resolve(outPath)}` : ''}` },
161
- ] };
162
- });
163
-
164
- tool('get_design_tokens', 'Get the design tokens of the file: color, text (typography), effect (shadow) styles and Figma variables (collections with modes, e.g. light/dark). Returns CSS custom properties + typography classes, or JSON.', {
165
- file: fileArg,
166
- format: z.enum(['css', 'json']).optional().describe('css (default) or json'),
167
- }, async ({ file, format = 'css' }) => {
168
- const f = await open(file);
169
- const t = f.tokens();
170
- if (format === 'json') { const { css, ...rest } = t; return json(rest); }
171
- return text(`${t.colors.length} colors, ${t.typography.length} text styles, ${t.shadows.length} effects, ${t.variables.reduce((a, c) => a + c.variables.length, 0)} variables\n\n\`\`\`css\n${t.css}\`\`\``);
172
- });
173
-
174
- tool('list_components', 'List components and component sets (with variant properties like State=Hover, Size=lg) and how often they are used.', {
175
- file: fileArg, query: z.string().optional().describe('Filter by component name.'),
176
- }, async ({ file, query }) => {
177
- const f = await open(file);
178
- const list = f.components({ query });
179
- return text(list.slice(0, 300).map(c => `- ${c.id} "${c.name}" ${c.kind}, ${c.variants} variant(s), used ${c.uses}×${c.interactive ? ', has interactions' : ''}${Object.keys(c.properties).length ? `\n props: ${Object.entries(c.properties).map(([k, v]) => `${k}=${Array.isArray(v) ? v.join('|') : v}`).join('; ')}` : ''}${c.description ? `\n ${c.description}` : ''}`).join('\n') + (list.length > 300 ? `\n… ${list.length - 300} more (use query)` : ''));
180
- });
181
-
182
- tool('get_component', 'Get one component / component set: every variant with its properties, the CSS differences between interactive states (hover, pressed, …) and an HTML/CSS reproduction of the variants. Also writes an export folder like get_frame.', {
183
- file: fileArg, component: z.string().describe('Component (set) name or id, e.g. "Button".'), outDir: z.string().optional(), maxChars: z.number().int().optional(),
184
- }, async ({ file, component, outDir, maxChars = 30000 }) => {
185
- const f = await open(file, component);
186
- const doc = f.doc;
187
- let node;
188
- try { node = f.findNode(component); } catch { node = null; }
189
- if (!node || !(node.isStateGroup || node.type === 'SYMBOL')) {
190
- const q = component.toLowerCase();
191
- const cands = doc.nodes.filter(n => (n.isStateGroup || (n.type === 'SYMBOL' && !doc.componentSet(n))) && n.name.toLowerCase() === q);
192
- node = cands.find(n => !doc.isInternal(n)) || cands[0] || doc.nodes.find(n => (n.isStateGroup || n.type === 'SYMBOL') && n.name.toLowerCase().includes(q));
193
- }
194
- if (!node) throw new Error(`Component "${component}" not found. Use list_components.`);
195
- const variants = node.isStateGroup ? doc.children(node).filter(c => c.type === 'SYMBOL') : [node];
196
- const conv = new Converter(doc);
197
- for (const v of variants) conv.components.set(idOf(v), { name: doc.componentName(v), setId: idOf(node), symbolId: idOf(v), variant: doc.variantProps(v), uses: 0 });
198
- const states = variantStates(doc, conv);
199
- const lines = [`# Component "${node.name}" (${idOf(node)}) — ${variants.length} variant(s)${doc.isInternal(node) ? ' — from a library (internal canvas)' : ''}`];
200
- const props = {};
201
- for (const d of node.componentPropDefs || []) if (!d.isDeleted) props[d.name.replace(/#.*$/, '')] = d.type;
202
- if (Object.keys(props).length) lines.push(`Properties: ${Object.entries(props).map(([k, v]) => `${k} (${v})`).join(', ')}`);
203
- lines.push(`\n## Variants`);
204
- for (const v of variants) lines.push(`- ${idOf(v)} ${Object.entries(doc.variantProps(v) || { name: v.name }).map(([k, x]) => `${k}=${x}`).join(', ')} ${Math.round(v.size.x)}×${Math.round(v.size.y)}`);
205
- if (states.length) {
206
- lines.push(`\n## Interaction states`);
207
- for (const s of states) lines.push(`- ${s.triggerText || s.trigger}${s.pseudo ? ` (${s.pseudo.join(', ')})` : ''}: [${Object.entries(s.via || s.from).map(([k, x]) => `${k}=${x}`).join(', ')}] → [${Object.entries(s.to).map(([k, x]) => `${k}=${x}`).join(', ')}] ${s.transition || ''} ${s.durationMs ? s.durationMs + 'ms' : ''} ${s.easing || ''}${s.shows ? `\n shows: ${s.shows.join(', ')}` : ''}${s.hides ? `\n hides: ${s.hides.join(', ')}` : ''}\n ${JSON.stringify(s.changes).slice(0, 600)}`);
208
- }
209
- const r = await f.getFrame(node, { outDir, maxChars });
210
- lines.push(`\n## Export\n${r.dir}\n\n## styles.css\n\`\`\`css\n${r.css}\n\`\`\`\n\n## HTML${r.truncatedDepth ? ` (collapsed below depth ${r.truncatedDepth}; full: ${r.files.html})` : ''}\n\`\`\`html\n${r.html}\n\`\`\``);
211
- return text(lines.join('\n'));
212
- });
213
-
214
- tool('search_nodes', 'Find layers by name or text content (e.g. "Sign in", "logo", "price"). Returns ids you can pass to get_frame/render_frame/export_svg.', {
215
- file: fileArg, query: z.string(), limit: z.number().int().optional(),
216
- }, async ({ file, query, limit = 50 }) => {
217
- const f = await open(file);
218
- const hits = f.search(query, { limit });
219
- return text(hits.length ? hits.map(h => `- ${h.id} ${h.type} "${h.name}"${h.text ? ` text="${h.text}"` : ''} in ${h.page}${h.path ? ' / ' + h.path : ''}`).join('\n') : 'No matches.');
220
- });
221
-
222
- tool('get_prototype_flows', 'Prototype navigation graph: flow starting points and every click/hover/timer link between screens, overlays (modals) and URLs.', { file: fileArg }, async ({ file }) => {
223
- const f = await open(file);
224
- const { starts, edges } = f.flows();
225
- return text([`## Flows\n${starts.map(s => `- "${s.flow}" starts at "${s.start}" (${s.startId})`).join('\n') || '(none)'}`,
226
- `## Links (${edges.length})\n${edges.slice(0, 300).map(e => `- [${e.fromScreen}] "${e.fromNode}": ${e.text}`).join('\n')}`].join('\n\n'));
227
- });
228
-
229
- tool('export_svg', 'Export a node (icon, logo, illustration, vector) as SVG markup; optionally save it to a file.', {
230
- file: fileArg, node: frameArg, outPath: z.string().optional(),
231
- }, async ({ file, node, outPath }) => {
232
- const f = await open(file, node);
233
- const svg = await f.svg(node);
234
- if (outPath) { const { writeFileSync, mkdirSync } = await import('fs'); const { dirname } = await import('path'); mkdirSync(dirname(resolve(outPath)), { recursive: true }); writeFileSync(resolve(outPath), svg); }
235
- return text(outPath ? `Saved ${svg.length} bytes to ${resolve(outPath)}\n\n${svg.slice(0, 4000)}` : svg.length > 60000 ? svg.slice(0, 60000) + '\n<!-- truncated: pass outPath to save the full SVG -->' : svg);
236
- });
237
-
238
- server.registerPrompt('implement_frame', {
239
- description: 'Implement a Figma frame from a .fig file in this project',
240
- argsSchema: { frame: z.string().describe('Frame name, id or Figma URL'), file: z.string().optional().describe('.fig file (optional)'), stack: z.string().optional().describe('e.g. "React + Tailwind"') },
241
- }, ({ frame, file, stack }) => ({ messages: [{ role: 'user', content: { type: 'text', text:
242
- `Implement the Figma frame "${frame}"${file ? ` from ${file}` : ''}${stack ? ` using ${stack}` : ' using this project\'s framework and conventions'}.\n` +
243
- `1. Call get_frame for it (and render_frame to see it).\n2. Reuse the exported assets (SVG icons, images) from the export folder and the tokens from tokens.css (map them to the project's theme).\n3. Build reusable components for repeated Figma components (see "Components used") and implement the hover/active states and animations listed in the summary.\n4. Use flexbox/grid layouts instead of absolute positioning where the design uses auto-layout; keep exact spacing, sizes, colors and typography.\n5. Render your result and compare against preview.png; fix differences.` } }] }));
244
-
245
- return server;
246
- }
1
+ // MCP server exposing .fig files as LLM-ready design data.
2
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { z } from 'zod';
4
+ import { existsSync, readdirSync, statSync } from 'fs';
5
+ import { isAbsolute, join, resolve, basename } from 'path';
6
+ import { fileURLToPath } from 'url';
7
+ import { FigFile } from './api.mjs';
8
+ import { Converter, variantStates } from './convert.mjs';
9
+ import { idOf } from './util.mjs';
10
+
11
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', '.next', 'figma-export', '.cache', 'coverage', 'fixtures', '__fixtures__']);
12
+
13
+ /** Resolves which .fig file a tool call refers to. */
14
+ export class Workspace {
15
+ constructor({ paths = [], cwd = process.cwd() } = {}) {
16
+ this.cwd = cwd;
17
+ this.files = []; this.dirs = [];
18
+ for (const p of paths) {
19
+ const abs = resolve(cwd, p);
20
+ if (!existsSync(abs)) { process.stderr.write(`[openfig-mcp] warning: path not found: ${abs}\n`); continue; }
21
+ (statSync(abs).isDirectory() ? this.dirs : this.files).push(abs);
22
+ }
23
+ this.roots = [];
24
+ }
25
+ setRoots(uris) { this.roots = uris.map(u => { try { return u.startsWith('file:') ? fileURLToPath(u) : u; } catch { return null; } }).filter(Boolean); }
26
+ searchDirs() { const s = [...this.dirs, ...this.roots]; if (!s.length) s.push(this.cwd); return [...new Set(s)]; }
27
+ discover(limit = 200) {
28
+ const found = new Set(this.files);
29
+ const walk = (d, depth) => {
30
+ if (found.size >= limit) return;
31
+ let entries; try { entries = readdirSync(d, { withFileTypes: true }); } catch { return; }
32
+ for (const e of entries) {
33
+ if (e.isDirectory()) { if (depth < 5 && !SKIP_DIRS.has(e.name) && !e.name.startsWith('.')) walk(join(d, e.name), depth + 1); }
34
+ else if (/\.fig$/i.test(e.name)) found.add(join(d, e.name));
35
+ }
36
+ };
37
+ for (const d of this.searchDirs()) walk(d, 0);
38
+ return [...found];
39
+ }
40
+ resolve(file) {
41
+ if (file) {
42
+ const f = String(file).trim().replace(/^["']|["']$/g, '');
43
+ if (isAbsolute(f) && existsSync(f)) return f;
44
+ for (const base of [...this.searchDirs(), this.cwd]) { const p = resolve(base, f); if (existsSync(p) && statSync(p).isFile()) return p; }
45
+ const all = this.discover();
46
+ const q = basename(f).toLowerCase().replace(/\.fig$/, '');
47
+ const hits = all.filter(p => basename(p).toLowerCase().includes(q));
48
+ if (hits.length === 1) return hits[0];
49
+ if (hits.length > 1) throw new Error(`"${file}" matches several files:\n${hits.map(h => ' ' + h).join('\n')}`);
50
+ throw new Error(`Could not find "${file}". Known .fig files:\n${all.map(h => ' ' + h).join('\n') || ' (none found — pass an absolute path)'}`);
51
+ }
52
+ if (this.files.length === 1) return this.files[0];
53
+ const all = this.discover();
54
+ if (all.length === 1) return all[0];
55
+ if (!all.length) throw new Error(`No .fig file found in ${this.searchDirs().join(', ')}. Pass "file" with a path to a .fig file.`);
56
+ throw new Error(`Several .fig files available — pass "file" (name or path):\n${all.map(h => ' ' + h).join('\n')}`);
57
+ }
58
+ }
59
+
60
+ const text = s => ({ content: [{ type: 'text', text: s }] });
61
+ const json = o => text(JSON.stringify(o, null, 1));
62
+ const fail = e => ({ content: [{ type: 'text', text: `Error: ${e.message || e}` }], isError: true });
63
+ const fileArg = z.string().optional().describe('Path or name of the .fig file. Optional when the workspace has exactly one .fig file or one was passed on the command line.');
64
+ const frameArg = z.string().describe('Frame/node to use: a node id like "1:234", a Figma URL containing node-id=1-234, or the frame name (e.g. "MacBook Pro 14\\" - 4", "Login").');
65
+
66
+ const INSTRUCTIONS = `openfig-mcp reads Figma .fig files locally (no Figma API token) and returns design data ready for implementation.
67
+ Typical workflow:
68
+ 1. list_frames → pick the screen/frame (ids look like "1:234"; Figma URLs with node-id also work).
69
+ 2. get_frame → summary (fonts, components, tokens, hover/press states, animations, navigation/modals) + HTML/CSS reproduction. It also writes index.html, styles.css, tokens.css, spec.json, preview.png and assets/ (SVG icons, images) to disk — reference those asset files directly and read the files for full detail.
70
+ 3. render_frame to SEE the design (PNG) and compare with your implementation.
71
+ Other tools: get_design_tokens (colors/typography/shadows/variables as CSS vars), list_components / get_component (variants + state CSS), search_nodes, get_prototype_flows, export_svg.
72
+ Treat the generated HTML as a precise reference for sizes, spacing, colors and structure; rewrite it into idiomatic components (flex layouts, semantic tags, the project's framework) rather than copying absolute positioning verbatim.`;
73
+
74
+ export function createServer({ paths = [], cwd } = {}) {
75
+ const ws = new Workspace({ paths, cwd });
76
+ const pkg = { name: 'openfig-mcp', version: '0.1.0' };
77
+ const server = new McpServer(pkg, { instructions: INSTRUCTIONS, capabilities: { logging: {} } });
78
+
79
+ let rootsLoaded = false;
80
+ async function refreshRoots() {
81
+ if (rootsLoaded) return;
82
+ rootsLoaded = true;
83
+ try {
84
+ if (server.server.getClientCapabilities()?.roots) {
85
+ const { roots } = await server.server.listRoots();
86
+ ws.setRoots(roots.map(r => r.uri));
87
+ }
88
+ } catch { /* client without roots support */ }
89
+ }
90
+ /** Open the file the call refers to. With no file and several candidates, pick the one containing `frame`. */
91
+ async function open(file, frame) {
92
+ await refreshRoots();
93
+ try { return await FigFile.open(ws.resolve(file)); }
94
+ catch (e) {
95
+ if (file || !frame || !/Several \.fig files/.test(e.message)) throw e;
96
+ const hits = [];
97
+ for (const p of ws.discover()) { const f = await FigFile.open(p); try { f.findNode(frame); hits.push(f); } catch {} }
98
+ if (hits.length === 1) return hits[0];
99
+ throw hits.length ? new Error(`"${frame}" exists in several files — pass "file":\n${hits.map(h => ' ' + h.path).join('\n')}`) : e;
100
+ }
101
+ }
102
+ const tool = (name, description, shape, fn) => server.registerTool(name, { description, inputSchema: shape }, async args => { try { return await fn(args); } catch (e) { return fail(e); } });
103
+
104
+ tool('list_fig_files', 'List the Figma .fig files available in the workspace (or passed on the command line).', {}, async () => {
105
+ await refreshRoots();
106
+ const files = ws.discover();
107
+ return text(files.length ? files.map(f => `- ${f} (${(statSync(f).size / 1e6).toFixed(1)} MB)`).join('\n') : `No .fig files found under ${ws.searchDirs().join(', ')}`);
108
+ });
109
+
110
+ tool('list_frames', 'List the pages and top-level frames (screens, component sets, frames) in a .fig file, with ids, sizes and prototype flow starting points.', {
111
+ file: fileArg,
112
+ page: z.string().optional().describe('Only this page (name or id).'),
113
+ query: z.string().optional().describe('Filter by frame/section/page name.'),
114
+ includeComponents: z.boolean().optional().describe('Include component sets/components placed on pages (default true).'),
115
+ }, async ({ file, page, query, includeComponents }) => {
116
+ const f = await open(file);
117
+ const frames = f.listFrames({ page, query, includeComponents });
118
+ const pages = f.doc.pages().map(p => p.name);
119
+ const lines = [`File: ${f.path}`, `Pages: ${pages.join(', ')}`, `${frames.length} frames:`];
120
+ let last = null;
121
+ for (const fr of frames) {
122
+ const g = `${fr.page}${fr.group ? ' / ' + fr.group : ''}`;
123
+ if (g !== last) { lines.push(`\n## ${g}`); last = g; }
124
+ lines.push(`- ${fr.id} ${fr.kind.padEnd(13)} "${fr.name}" ${fr.size}${fr.flowStart ? ` ▶ prototype start (${fr.flowStart})` : ''}`);
125
+ }
126
+ return text(lines.join('\n'));
127
+ });
128
+
129
+ tool('get_frame', 'Convert a frame/screen/component (any node) into implementation-ready design data: summary of fonts, components + variants, design tokens, hover/active states, auto-playing animations, navigation and modals, plus an HTML+CSS reproduction. Writes index.html, styles.css, tokens.css, spec.json, DESIGN.md, preview.png and assets/ (SVG icons, images) to disk.', {
130
+ file: fileArg,
131
+ frame: frameArg,
132
+ outDir: z.string().optional().describe('Where to write the export (default: <fig folder>/figma-export/<frame>-<id>/).'),
133
+ maxChars: z.number().int().min(4000).max(400000).optional().describe('Budget for the inline response (default 40000). Deep subtrees are collapsed when over budget; full files are always written to disk.'),
134
+ includeHtml: z.boolean().optional().describe('Include HTML/CSS inline in the response (default true).'),
135
+ }, async ({ file, frame, outDir, maxChars = 40000, includeHtml = true }) => {
136
+ const f = await open(file, frame);
137
+ const r = await f.getFrame(frame, { outDir, maxChars });
138
+ const out = [r.summary];
139
+ if (r.sections.length > 1) {
140
+ out.push(`## Top-level sections (call get_frame on an id to drill in)\n${r.sections.map(s => `- ${s.id} "${s.name}" (${s.type}, ${s.nodes} nodes) ${s.box}`).join('\n')}`);
141
+ }
142
+ if (includeHtml) {
143
+ out.push(`## tokens.css\n\`\`\`css\n${r.tokensCss}\`\`\``);
144
+ out.push(`## styles.css\n\`\`\`css\n${r.css}\n\`\`\``);
145
+ out.push(`## index.html (body)${r.truncatedDepth ? ` — collapsed below depth ${r.truncatedDepth} to fit; full HTML in ${r.files.html}` : ''}\n\`\`\`html\n${r.html}\n\`\`\``);
146
+ }
147
+ return text(out.join('\n\n'));
148
+ });
149
+
150
+ tool('render_frame', 'Render a frame/node to a PNG image so you can see the design. Returns the image (and saves it if outPath is given).', {
151
+ file: fileArg, frame: frameArg,
152
+ maxSize: z.number().int().min(200).max(4096).optional().describe('Max width/height of the returned image in px (default 1600).'),
153
+ outPath: z.string().optional().describe('Also save the PNG here.'),
154
+ }, async ({ file, frame, maxSize = 1600, outPath }) => {
155
+ const f = await open(file, frame);
156
+ const { png, node, fontWarning: fw } = await f.render(frame, { maxDim: maxSize });
157
+ if (outPath) { const { writeFileSync, mkdirSync } = await import('fs'); const { dirname } = await import('path'); mkdirSync(dirname(resolve(outPath)), { recursive: true }); writeFileSync(resolve(outPath), png); }
158
+ return { content: [
159
+ { type: 'image', data: png.toString('base64'), mimeType: 'image/png' },
160
+ { type: 'text', text: `Rendered "${node.name}" (${node.id}, ${Math.round(node.size.x)}×${Math.round(node.size.y)}).${fw ? ` ${fw}` : ''} Note: this is an approximate render by openfig; small differences from Figma are expected.${outPath ? ` Saved to ${resolve(outPath)}` : ''}` },
161
+ ] };
162
+ });
163
+
164
+ tool('get_design_tokens', 'Get the design tokens of the file: color, text (typography), effect (shadow) styles and Figma variables (collections with modes, e.g. light/dark). Returns CSS custom properties + typography classes, or JSON.', {
165
+ file: fileArg,
166
+ format: z.enum(['css', 'json']).optional().describe('css (default) or json'),
167
+ }, async ({ file, format = 'css' }) => {
168
+ const f = await open(file);
169
+ const t = f.tokens();
170
+ if (format === 'json') { const { css, ...rest } = t; return json(rest); }
171
+ return text(`${t.colors.length} colors, ${t.typography.length} text styles, ${t.shadows.length} effects, ${t.variables.reduce((a, c) => a + c.variables.length, 0)} variables\n\n\`\`\`css\n${t.css}\`\`\``);
172
+ });
173
+
174
+ tool('list_components', 'List components and component sets (with variant properties like State=Hover, Size=lg) and how often they are used.', {
175
+ file: fileArg, query: z.string().optional().describe('Filter by component name.'),
176
+ }, async ({ file, query }) => {
177
+ const f = await open(file);
178
+ const list = f.components({ query });
179
+ return text(list.slice(0, 300).map(c => `- ${c.id} "${c.name}" ${c.kind}, ${c.variants} variant(s), used ${c.uses}×${c.interactive ? ', has interactions' : ''}${Object.keys(c.properties).length ? `\n props: ${Object.entries(c.properties).map(([k, v]) => `${k}=${Array.isArray(v) ? v.join('|') : v}`).join('; ')}` : ''}${c.description ? `\n ${c.description}` : ''}`).join('\n') + (list.length > 300 ? `\n… ${list.length - 300} more (use query)` : ''));
180
+ });
181
+
182
+ tool('get_component', 'Get one component / component set: every variant with its properties, the CSS differences between interactive states (hover, pressed, …) and an HTML/CSS reproduction of the variants. Also writes an export folder like get_frame.', {
183
+ file: fileArg, component: z.string().describe('Component (set) name or id, e.g. "Button".'), outDir: z.string().optional(), maxChars: z.number().int().optional(),
184
+ }, async ({ file, component, outDir, maxChars = 30000 }) => {
185
+ const f = await open(file, component);
186
+ const doc = f.doc;
187
+ let node;
188
+ try { node = f.findNode(component); } catch { node = null; }
189
+ if (!node || !(node.isStateGroup || node.type === 'SYMBOL')) {
190
+ const q = component.toLowerCase();
191
+ const cands = doc.nodes.filter(n => (n.isStateGroup || (n.type === 'SYMBOL' && !doc.componentSet(n))) && n.name.toLowerCase() === q);
192
+ node = cands.find(n => !doc.isInternal(n)) || cands[0] || doc.nodes.find(n => (n.isStateGroup || n.type === 'SYMBOL') && n.name.toLowerCase().includes(q));
193
+ }
194
+ if (!node) throw new Error(`Component "${component}" not found. Use list_components.`);
195
+ const variants = node.isStateGroup ? doc.children(node).filter(c => c.type === 'SYMBOL') : [node];
196
+ const conv = new Converter(doc);
197
+ for (const v of variants) conv.components.set(idOf(v), { name: doc.componentName(v), setId: idOf(node), symbolId: idOf(v), variant: doc.variantProps(v), uses: 0 });
198
+ const states = variantStates(doc, conv);
199
+ const lines = [`# Component "${node.name}" (${idOf(node)}) — ${variants.length} variant(s)${doc.isInternal(node) ? ' — from a library (internal canvas)' : ''}`];
200
+ const props = {};
201
+ for (const d of node.componentPropDefs || []) if (!d.isDeleted) props[d.name.replace(/#.*$/, '')] = d.type;
202
+ if (Object.keys(props).length) lines.push(`Properties: ${Object.entries(props).map(([k, v]) => `${k} (${v})`).join(', ')}`);
203
+ lines.push(`\n## Variants`);
204
+ for (const v of variants) lines.push(`- ${idOf(v)} ${Object.entries(doc.variantProps(v) || { name: v.name }).map(([k, x]) => `${k}=${x}`).join(', ')} ${Math.round(v.size.x)}×${Math.round(v.size.y)}`);
205
+ if (states.length) {
206
+ lines.push(`\n## Interaction states`);
207
+ for (const s of states) lines.push(`- ${s.triggerText || s.trigger}${s.pseudo ? ` (${s.pseudo.join(', ')})` : ''}: [${Object.entries(s.via || s.from).map(([k, x]) => `${k}=${x}`).join(', ')}] → [${Object.entries(s.to).map(([k, x]) => `${k}=${x}`).join(', ')}] ${s.transition || ''} ${s.durationMs ? s.durationMs + 'ms' : ''} ${s.easing || ''}${s.shows ? `\n shows: ${s.shows.join(', ')}` : ''}${s.hides ? `\n hides: ${s.hides.join(', ')}` : ''}\n ${JSON.stringify(s.changes).slice(0, 600)}`);
208
+ }
209
+ const r = await f.getFrame(node, { outDir, maxChars });
210
+ lines.push(`\n## Export\n${r.dir}\n\n## styles.css\n\`\`\`css\n${r.css}\n\`\`\`\n\n## HTML${r.truncatedDepth ? ` (collapsed below depth ${r.truncatedDepth}; full: ${r.files.html})` : ''}\n\`\`\`html\n${r.html}\n\`\`\``);
211
+ return text(lines.join('\n'));
212
+ });
213
+
214
+ tool('search_nodes', 'Find layers by name or text content (e.g. "Sign in", "logo", "price"). Returns ids you can pass to get_frame/render_frame/export_svg.', {
215
+ file: fileArg, query: z.string(), limit: z.number().int().optional(),
216
+ }, async ({ file, query, limit = 50 }) => {
217
+ const f = await open(file);
218
+ const hits = f.search(query, { limit });
219
+ return text(hits.length ? hits.map(h => `- ${h.id} ${h.type} "${h.name}"${h.text ? ` text="${h.text}"` : ''} in ${h.page}${h.path ? ' / ' + h.path : ''}`).join('\n') : 'No matches.');
220
+ });
221
+
222
+ tool('get_prototype_flows', 'Prototype navigation graph: flow starting points and every click/hover/timer link between screens, overlays (modals) and URLs.', { file: fileArg }, async ({ file }) => {
223
+ const f = await open(file);
224
+ const { starts, edges } = f.flows();
225
+ return text([`## Flows\n${starts.map(s => `- "${s.flow}" starts at "${s.start}" (${s.startId})`).join('\n') || '(none)'}`,
226
+ `## Links (${edges.length})\n${edges.slice(0, 300).map(e => `- [${e.fromScreen}] "${e.fromNode}": ${e.text}`).join('\n')}`].join('\n\n'));
227
+ });
228
+
229
+ tool('export_svg', 'Export a node (icon, logo, illustration, vector) as SVG markup; optionally save it to a file.', {
230
+ file: fileArg, node: frameArg, outPath: z.string().optional(),
231
+ }, async ({ file, node, outPath }) => {
232
+ const f = await open(file, node);
233
+ const svg = await f.svg(node);
234
+ if (outPath) { const { writeFileSync, mkdirSync } = await import('fs'); const { dirname } = await import('path'); mkdirSync(dirname(resolve(outPath)), { recursive: true }); writeFileSync(resolve(outPath), svg); }
235
+ return text(outPath ? `Saved ${svg.length} bytes to ${resolve(outPath)}\n\n${svg.slice(0, 4000)}` : svg.length > 60000 ? svg.slice(0, 60000) + '\n<!-- truncated: pass outPath to save the full SVG -->' : svg);
236
+ });
237
+
238
+ server.registerPrompt('implement_frame', {
239
+ description: 'Implement a Figma frame from a .fig file in this project',
240
+ argsSchema: { frame: z.string().describe('Frame name, id or Figma URL'), file: z.string().optional().describe('.fig file (optional)'), stack: z.string().optional().describe('e.g. "React + Tailwind"') },
241
+ }, ({ frame, file, stack }) => ({ messages: [{ role: 'user', content: { type: 'text', text:
242
+ `Implement the Figma frame "${frame}"${file ? ` from ${file}` : ''}${stack ? ` using ${stack}` : ' using this project\'s framework and conventions'}.\n` +
243
+ `1. Call get_frame for it (and render_frame to see it).\n2. Reuse the exported assets (SVG icons, images) from the export folder and the tokens from tokens.css (map them to the project's theme).\n3. Build reusable components for repeated Figma components (see "Components used") and implement the hover/active states and animations listed in the summary.\n4. Use flexbox/grid layouts instead of absolute positioning where the design uses auto-layout; keep exact spacing, sizes, colors and typography.\n5. Render your result and compare against preview.png; fix differences.` } }] }));
244
+
245
+ return server;
246
+ }