figma-proxy-mcp 0.0.0-stage → 1.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/.env.example +9 -0
- package/CHANGELOG.md +43 -0
- package/LICENSE +21 -0
- package/README.md +149 -2
- package/SECURITY.md +70 -0
- package/package.json +54 -4
- package/proxy-mcp.js +1240 -0
- package/scripts/check-setup.js +125 -0
- package/src/components/index.js +476 -0
- package/src/components/registry.js +145 -0
- package/src/config.js +106 -0
- package/src/figma/client.js +46 -0
- package/src/instructions.js +19 -0
- package/src/ir/color.js +70 -0
- package/src/ir/flatten.js +75 -0
- package/src/ir/transform.js +203 -0
- package/src/prune/index.js +226 -0
- package/src/tokens/index.js +484 -0
- package/src/tokens/naming.js +204 -0
- package/src/tokens/varmap.js +217 -0
- package/src/visual/verify.js +393 -0
package/proxy-mcp.js
ADDED
|
@@ -0,0 +1,1240 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
|
|
6
|
+
// Key is read from the environment / .env (see src/config.js). Never hardcode it,
|
|
7
|
+
// never log it. All error text that may reach a client passes through redact().
|
|
8
|
+
const { requireApiKey, redact, PATHS } = require('./src/config');
|
|
9
|
+
const { INSTRUCTIONS } = require('./src/instructions');
|
|
10
|
+
const PKG_VERSION = require('./package.json').version;
|
|
11
|
+
const SUPPORTED_PROTOCOLS = ['2025-06-18', '2025-03-26', '2024-11-05'];
|
|
12
|
+
|
|
13
|
+
/** Figma file keys are alphanumeric; reject anything else before it reaches a URL path. */
|
|
14
|
+
function assertFileKey(fileId) {
|
|
15
|
+
if (typeof fileId !== 'string' || !/^[A-Za-z0-9]{10,64}$/.test(fileId)) {
|
|
16
|
+
throw new Error('Invalid Figma file key. Copy it from the file URL: figma.com/design/<fileKey>/...');
|
|
17
|
+
}
|
|
18
|
+
return fileId;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Render/export URLs come from Figma's /v1/images response (short-lived signed
|
|
23
|
+
* URLs on Figma's image storage, currently Amazon S3). They are fetched without
|
|
24
|
+
* the token. Only https URLs are accepted.
|
|
25
|
+
*/
|
|
26
|
+
function assertHttpsUrl(u) {
|
|
27
|
+
let parsed;
|
|
28
|
+
try { parsed = new URL(u); } catch (_) { parsed = null; }
|
|
29
|
+
if (!parsed || parsed.protocol !== 'https:') throw new Error('Figma returned a non-https image URL; refusing to fetch it');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Turn a non-2xx Figma response into an actionable message (no secrets). */
|
|
33
|
+
function figmaHttpError(status) {
|
|
34
|
+
const hints = {
|
|
35
|
+
400: 'bad request (check node-id / parameters)',
|
|
36
|
+
403: 'token missing, invalid, expired, or lacks the "File content: read" scope',
|
|
37
|
+
404: 'file or node not found, or your account has no access to the file',
|
|
38
|
+
429: 'rate limited by Figma, wait and retry',
|
|
39
|
+
};
|
|
40
|
+
return new Error(`Figma API error: ${status}${hints[status] ? ' - ' + hints[status] : ''}`);
|
|
41
|
+
}
|
|
42
|
+
const { toIR, fileToIR } = require('./src/ir/transform');
|
|
43
|
+
const { flattenIR } = require('./src/ir/flatten');
|
|
44
|
+
const { prune } = require('./src/prune');
|
|
45
|
+
const { tokenize, toTailwindTheme } = require('./src/tokens');
|
|
46
|
+
const { componentize } = require('./src/components');
|
|
47
|
+
|
|
48
|
+
class MCPProxyServer {
|
|
49
|
+
constructor() {
|
|
50
|
+
this.figmaData = null;
|
|
51
|
+
this.svgCache = new Map(); // Cache for SVG exports
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Parse Figma URL to extract fileId and nodeId
|
|
55
|
+
parseFigmaUrl(url) {
|
|
56
|
+
try {
|
|
57
|
+
const urlObj = new URL(url);
|
|
58
|
+
|
|
59
|
+
if (!/(^|\.)figma\.com$/i.test(urlObj.hostname)) {
|
|
60
|
+
throw new Error('not a figma.com URL');
|
|
61
|
+
}
|
|
62
|
+
// Path: /design/{fileKey}/... (also /file/, /proto/, and
|
|
63
|
+
// /design/{fileKey}/branch/{branchKey}/... where the branch key is used).
|
|
64
|
+
const pathParts = urlObj.pathname.split('/');
|
|
65
|
+
let fileId = pathParts[2];
|
|
66
|
+
if (pathParts[3] === 'branch' && pathParts[4]) fileId = pathParts[4];
|
|
67
|
+
|
|
68
|
+
// Query: ?node-id=123-456 -> API form 123:456 (instances: I1-2;3-4 -> I1:2;3:4)
|
|
69
|
+
const rawNodeId = urlObj.searchParams.get('node-id');
|
|
70
|
+
const nodeId = rawNodeId ? rawNodeId.replace(/-/g, ':') : null;
|
|
71
|
+
|
|
72
|
+
return { fileId, nodeId };
|
|
73
|
+
} catch (error) {
|
|
74
|
+
throw new Error(`Invalid Figma URL: ${redact(error.message)}`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Fetch data directly from Figma API
|
|
79
|
+
async fetchFigmaData(fileId) {
|
|
80
|
+
try {
|
|
81
|
+
// Limit the request to avoid "too large" errors
|
|
82
|
+
const params = new URLSearchParams({
|
|
83
|
+
depth: '2', // Limit traversal depth
|
|
84
|
+
geometry: 'paths' // Get geometry but not full path data
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
const response = await fetch(`https://api.figma.com/v1/files/${assertFileKey(fileId)}?${params}`, {
|
|
88
|
+
headers: {
|
|
89
|
+
'X-Figma-Token': requireApiKey()
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
if (!response.ok) {
|
|
94
|
+
throw figmaHttpError(response.status);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const data = await response.json();
|
|
98
|
+
// Canonical IR (null-safe colors, no empty objects).
|
|
99
|
+
this.figmaData = fileToIR(data);
|
|
100
|
+
return this.figmaData;
|
|
101
|
+
} catch (error) {
|
|
102
|
+
console.error('Error fetching Figma data:', redact(error && error.message));
|
|
103
|
+
throw error;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Fetch specific node/component from Figma with full depth.
|
|
108
|
+
// maxDepth (optional) caps how deep the IR tree is built — useful to keep a
|
|
109
|
+
// large section's response compact without resorting to manual decomposition.
|
|
110
|
+
async fetchFigmaComponent(fileId, nodeId, maxDepth) {
|
|
111
|
+
try {
|
|
112
|
+
// First, get the node with deeper structure
|
|
113
|
+
const params = new URLSearchParams({
|
|
114
|
+
ids: nodeId,
|
|
115
|
+
depth: '10', // Get deeper nesting
|
|
116
|
+
geometry: 'paths' // Include geometry data
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
const response = await fetch(`https://api.figma.com/v1/files/${assertFileKey(fileId)}/nodes?${params}`, {
|
|
120
|
+
headers: {
|
|
121
|
+
'X-Figma-Token': requireApiKey()
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
if (!response.ok) {
|
|
126
|
+
throw figmaHttpError(response.status);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const data = await response.json();
|
|
130
|
+
const nodeData = data.nodes[nodeId];
|
|
131
|
+
|
|
132
|
+
if (!nodeData || !nodeData.document) {
|
|
133
|
+
throw new Error(`Node ${nodeId} not found or has no document data`);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// New canonical IR (null-safe colors, omits empty fields, preserves
|
|
137
|
+
// boundVariables/componentId for later stages).
|
|
138
|
+
return toIR(nodeData.document, typeof maxDepth === 'number' ? { maxDepth } : {});
|
|
139
|
+
} catch (error) {
|
|
140
|
+
console.error('Error fetching Figma component:', redact(error && error.message));
|
|
141
|
+
throw error;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// MCP Protocol Implementation
|
|
146
|
+
async handleRequest(request) {
|
|
147
|
+
const { method, params, id } = request;
|
|
148
|
+
|
|
149
|
+
try {
|
|
150
|
+
switch (method) {
|
|
151
|
+
case 'initialize': {
|
|
152
|
+
const requested = params && params.protocolVersion;
|
|
153
|
+
return {
|
|
154
|
+
jsonrpc: '2.0',
|
|
155
|
+
id,
|
|
156
|
+
result: {
|
|
157
|
+
protocolVersion: SUPPORTED_PROTOCOLS.includes(requested) ? requested : '2024-11-05',
|
|
158
|
+
capabilities: {
|
|
159
|
+
tools: {}
|
|
160
|
+
},
|
|
161
|
+
serverInfo: {
|
|
162
|
+
name: 'figma-proxy-mcp',
|
|
163
|
+
version: PKG_VERSION
|
|
164
|
+
},
|
|
165
|
+
instructions: INSTRUCTIONS
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
case 'ping':
|
|
171
|
+
return { jsonrpc: '2.0', id, result: {} };
|
|
172
|
+
|
|
173
|
+
case 'tools/list':
|
|
174
|
+
return {
|
|
175
|
+
jsonrpc: '2.0',
|
|
176
|
+
id,
|
|
177
|
+
result: {
|
|
178
|
+
tools: [
|
|
179
|
+
{
|
|
180
|
+
name: 'get_figma_file',
|
|
181
|
+
description: 'Get Figma file data by file ID and transform it for development',
|
|
182
|
+
inputSchema: {
|
|
183
|
+
type: 'object',
|
|
184
|
+
properties: {
|
|
185
|
+
fileId: {
|
|
186
|
+
type: 'string',
|
|
187
|
+
description: 'Figma file ID (from the URL: figma.com/file/{fileId}/...)'
|
|
188
|
+
}
|
|
189
|
+
},
|
|
190
|
+
required: ['fileId']
|
|
191
|
+
}
|
|
192
|
+
},
|
|
193
|
+
{
|
|
194
|
+
name: 'get_figma_component',
|
|
195
|
+
description: 'Get a Figma node by URL. Returns a deterministic, pruned + tokenized + componentized IR with a :root{} CSS-variable block, a Tailwind theme, and a component registry. Colors/spacing/fonts are already resolved to $--var references — the caller does NOT need to re-match raw RGBA against :root. For large sections, call with summary:true FIRST to get a compact { cssVars, tailwindTheme, registry, sections[] } object (top-level children with bounding boxes) WITHOUT the full node tree; this replaces manual get_figma_file decomposition. Then fetch individual sections (optionally with maxDepth) to build them.',
|
|
196
|
+
inputSchema: {
|
|
197
|
+
type: 'object',
|
|
198
|
+
properties: {
|
|
199
|
+
figmaUrl: {
|
|
200
|
+
type: 'string',
|
|
201
|
+
description: 'Full Figma URL to a specific node (e.g., https://www.figma.com/design/{fileId}/...?node-id={nodeId})'
|
|
202
|
+
},
|
|
203
|
+
summary: {
|
|
204
|
+
type: 'boolean',
|
|
205
|
+
description: 'When true, return a compact summary (component meta, CSS vars, Tailwind theme, component registry, and top-level sections with bounding boxes) instead of the full annotated IR tree. Recommended first call for large frames/sections — avoids reading a multi-thousand-line IR.',
|
|
206
|
+
default: false
|
|
207
|
+
},
|
|
208
|
+
maxDepth: {
|
|
209
|
+
type: 'number',
|
|
210
|
+
description: 'Cap the IR tree depth (e.g. 3-4) to keep a large section compact without manual decomposition. Omit for full depth.'
|
|
211
|
+
},
|
|
212
|
+
minFreq: {
|
|
213
|
+
type: 'number',
|
|
214
|
+
description: 'Minimum occurrences for a value to become a design token during tokenization (default 2).',
|
|
215
|
+
default: 2
|
|
216
|
+
},
|
|
217
|
+
prune: {
|
|
218
|
+
type: 'boolean',
|
|
219
|
+
description: 'Run the deterministic noise-pruning pass (collapse decorative wrappers, drop invisible/zero-size nodes). Default true; set false for raw IR (debug).',
|
|
220
|
+
default: true
|
|
221
|
+
},
|
|
222
|
+
tokenize: {
|
|
223
|
+
type: 'boolean',
|
|
224
|
+
description: 'Run frequency-analysis tokenization: emit :root CSS vars + Tailwind theme and replace raw color/spacing/font values in the IR with $--var references. Default true.',
|
|
225
|
+
default: true
|
|
226
|
+
},
|
|
227
|
+
componentize: {
|
|
228
|
+
type: 'boolean',
|
|
229
|
+
description: 'Cluster repeated nodes into a component registry with variant axes and named text styles. Default true.',
|
|
230
|
+
default: true
|
|
231
|
+
},
|
|
232
|
+
lean: {
|
|
233
|
+
type: 'boolean',
|
|
234
|
+
description: 'Omit the global blocks (CSS vars, Tailwind theme, component registry) that are identical on every call. Pass true on per-section fetches AFTER the summary call to avoid re-sending ~15KB of duplicated tokens/registry each time. The annotated IR still carries $--var references. Default false.',
|
|
235
|
+
default: false
|
|
236
|
+
},
|
|
237
|
+
format: {
|
|
238
|
+
type: 'string',
|
|
239
|
+
enum: ['nested', 'flat'],
|
|
240
|
+
description: '(non-summary) IR shape. "nested" (default) = full annotated tree. "flat" = a flat array of compact node records (render fields only, coords RELATIVE to the root frame) — much smaller and machine-readable. Use format:"flat" + lean:true for per-section fetches so you NEVER hand-read a deep multi-thousand-line tree.',
|
|
241
|
+
default: 'nested'
|
|
242
|
+
}
|
|
243
|
+
},
|
|
244
|
+
required: ['figmaUrl']
|
|
245
|
+
}
|
|
246
|
+
},
|
|
247
|
+
{
|
|
248
|
+
name: 'export_svg',
|
|
249
|
+
description: 'Export a specific Figma node as SVG and optionally save it',
|
|
250
|
+
inputSchema: {
|
|
251
|
+
type: 'object',
|
|
252
|
+
properties: {
|
|
253
|
+
fileId: {
|
|
254
|
+
type: 'string',
|
|
255
|
+
description: 'Figma file ID'
|
|
256
|
+
},
|
|
257
|
+
nodeId: {
|
|
258
|
+
type: 'string',
|
|
259
|
+
description: 'Node ID to export as SVG'
|
|
260
|
+
},
|
|
261
|
+
scale: {
|
|
262
|
+
type: 'number',
|
|
263
|
+
description: 'Scale factor for export (default: 1)',
|
|
264
|
+
default: 1
|
|
265
|
+
},
|
|
266
|
+
save: {
|
|
267
|
+
type: 'boolean',
|
|
268
|
+
description: 'Whether to save the SVG to disk (default: false)',
|
|
269
|
+
default: false
|
|
270
|
+
},
|
|
271
|
+
fileName: {
|
|
272
|
+
type: 'string',
|
|
273
|
+
description: 'Custom filename for saved SVG (optional)'
|
|
274
|
+
},
|
|
275
|
+
outputDir: {
|
|
276
|
+
type: 'string',
|
|
277
|
+
description: 'Output directory for saved SVGs (default: $FIGMA_PROXY_SVG_DIR or ./exported-svgs relative to the server working directory; pass an absolute path to be explicit)'
|
|
278
|
+
}
|
|
279
|
+
},
|
|
280
|
+
required: ['fileId', 'nodeId']
|
|
281
|
+
}
|
|
282
|
+
},
|
|
283
|
+
{
|
|
284
|
+
name: 'render_node_png',
|
|
285
|
+
description: 'Export a specific Figma node as PNG and return base64-encoded image data',
|
|
286
|
+
inputSchema: {
|
|
287
|
+
type: 'object',
|
|
288
|
+
properties: {
|
|
289
|
+
figmaUrl: {
|
|
290
|
+
type: 'string',
|
|
291
|
+
description: 'Full Figma URL to a specific node (e.g., https://www.figma.com/design/{fileId}/...?node-id={nodeId})'
|
|
292
|
+
},
|
|
293
|
+
fileId: {
|
|
294
|
+
type: 'string',
|
|
295
|
+
description: 'Figma file ID (alternative to figmaUrl)'
|
|
296
|
+
},
|
|
297
|
+
nodeId: {
|
|
298
|
+
type: 'string',
|
|
299
|
+
description: 'Node ID to export (alternative to figmaUrl, use colon format: 12:34)'
|
|
300
|
+
},
|
|
301
|
+
scale: {
|
|
302
|
+
type: 'number',
|
|
303
|
+
description: 'Scale factor for PNG export (default: 2)',
|
|
304
|
+
default: 2
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
},
|
|
309
|
+
{
|
|
310
|
+
name: 'migrate_all_svgs',
|
|
311
|
+
description: 'Automatically find and export all SVG icons from a Figma file',
|
|
312
|
+
inputSchema: {
|
|
313
|
+
type: 'object',
|
|
314
|
+
properties: {
|
|
315
|
+
fileId: {
|
|
316
|
+
type: 'string',
|
|
317
|
+
description: 'Figma file ID to migrate SVGs from'
|
|
318
|
+
},
|
|
319
|
+
outputDir: {
|
|
320
|
+
type: 'string',
|
|
321
|
+
description: 'Output directory for exported SVGs (default: $FIGMA_PROXY_SVG_DIR or ./exported-svgs relative to the server working directory; pass an absolute path to be explicit)'
|
|
322
|
+
}
|
|
323
|
+
},
|
|
324
|
+
required: ['fileId']
|
|
325
|
+
}
|
|
326
|
+
},
|
|
327
|
+
{
|
|
328
|
+
name: 'get_cached_components',
|
|
329
|
+
description: 'Get previously fetched Figma components data',
|
|
330
|
+
inputSchema: {
|
|
331
|
+
type: 'object',
|
|
332
|
+
properties: {},
|
|
333
|
+
required: []
|
|
334
|
+
}
|
|
335
|
+
},
|
|
336
|
+
{
|
|
337
|
+
name: 'get_component_by_name',
|
|
338
|
+
description: 'Get a specific Figma component by name from cached data',
|
|
339
|
+
inputSchema: {
|
|
340
|
+
type: 'object',
|
|
341
|
+
properties: {
|
|
342
|
+
name: {
|
|
343
|
+
type: 'string',
|
|
344
|
+
description: 'Name of the component to find'
|
|
345
|
+
}
|
|
346
|
+
},
|
|
347
|
+
required: ['name']
|
|
348
|
+
}
|
|
349
|
+
},
|
|
350
|
+
{
|
|
351
|
+
name: 'list_svg_cache',
|
|
352
|
+
description: 'List all cached SVG exports',
|
|
353
|
+
inputSchema: {
|
|
354
|
+
type: 'object',
|
|
355
|
+
properties: {},
|
|
356
|
+
required: []
|
|
357
|
+
}
|
|
358
|
+
},
|
|
359
|
+
{
|
|
360
|
+
name: 'verify_render',
|
|
361
|
+
description: 'Visual verification (MEASUREMENT ONLY): render an HTML file with headless Chromium INSIDE this server (does NOT use the user\'s own browser) and compare it to the Figma design PNG. Returns SSIM (0-1, higher = closer), pixel-diff %, and clustered diff regions (bounding boxes of disagreement, in logical px). Provide the reference PNG via figmaUrl (auto-fetched), figmaPngPath, or figmaPngBase64. Use after generating HTML to objectively check fidelity, then fix only the reported regions — this tool never changes code. Requires Playwright Chromium: `npx playwright install chromium`.',
|
|
362
|
+
inputSchema: {
|
|
363
|
+
type: 'object',
|
|
364
|
+
properties: {
|
|
365
|
+
htmlPath: { type: 'string', description: 'Absolute path to the generated .html file to render.' },
|
|
366
|
+
frameWidth: { type: 'number', description: 'Figma frame width in CSS px (e.g. 1440 or 1920). HTML is rendered at this width.' },
|
|
367
|
+
figmaUrl: { type: 'string', description: 'Figma node URL — reference PNG fetched automatically at the given scale.' },
|
|
368
|
+
figmaPngPath: { type: 'string', description: 'Alternative to figmaUrl: local path to an already-saved reference PNG.' },
|
|
369
|
+
figmaPngBase64: { type: 'string', description: 'Alternative: base64 of the reference PNG.' },
|
|
370
|
+
scale: { type: 'number', description: 'Device scale factor for render and reference (default 2 — match render_node_png).', default: 2 },
|
|
371
|
+
threshold: { type: 'number', description: 'SSIM pass threshold (default 0.95).', default: 0.95 },
|
|
372
|
+
bg: { type: 'array', items: { type: 'number' }, description: 'Background [r,g,b] to flatten transparent reference-PNG pixels onto before comparing. Default [255,255,255]. For dark designs pass the real background (e.g. [13,17,23]) — otherwise transparent areas read as a false full diff.' },
|
|
373
|
+
clip: { type: 'array', items: { type: 'number' }, description: 'Optional [x,y,w,h] in CSS/logical px to compare ONLY the content area. Use it to exclude dead margins / parent-canvas background that the isolated frame cannot reproduce (that noise otherwise dominates the regions and masks real content diffs). Region coords are reported back in full-frame coords.' },
|
|
374
|
+
outDir: { type: 'string', description: 'Directory for the diff image (default: $FIGMA_PROXY_VERIFY_DIR or <os temp dir>/figma-proxy-mcp/verify-out).' }
|
|
375
|
+
},
|
|
376
|
+
required: ['htmlPath', 'frameWidth']
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
]
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
|
|
383
|
+
case 'tools/call':
|
|
384
|
+
return await this.handleToolCall(params, id);
|
|
385
|
+
|
|
386
|
+
case 'notifications/initialized':
|
|
387
|
+
return; // No response needed for notifications
|
|
388
|
+
|
|
389
|
+
default:
|
|
390
|
+
// JSON-RPC notifications (no id) must never get a response.
|
|
391
|
+
if (id === undefined || id === null) return;
|
|
392
|
+
return {
|
|
393
|
+
jsonrpc: '2.0',
|
|
394
|
+
id,
|
|
395
|
+
error: {
|
|
396
|
+
code: -32601,
|
|
397
|
+
message: `Method not found: ${method}`
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
} catch (error) {
|
|
402
|
+
return {
|
|
403
|
+
jsonrpc: '2.0',
|
|
404
|
+
id,
|
|
405
|
+
error: {
|
|
406
|
+
code: -32603,
|
|
407
|
+
message: redact(error.message)
|
|
408
|
+
}
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
async handleToolCall(params, id) {
|
|
414
|
+
const { name } = params || {};
|
|
415
|
+
const args = (params && params.arguments) || {};
|
|
416
|
+
|
|
417
|
+
switch (name) {
|
|
418
|
+
case 'get_figma_file':
|
|
419
|
+
const fileId = args?.fileId;
|
|
420
|
+
if (!fileId) {
|
|
421
|
+
throw new Error('Figma file ID is required');
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
try {
|
|
425
|
+
const data = await this.fetchFigmaData(fileId);
|
|
426
|
+
return {
|
|
427
|
+
jsonrpc: '2.0',
|
|
428
|
+
id,
|
|
429
|
+
result: {
|
|
430
|
+
content: [
|
|
431
|
+
{
|
|
432
|
+
type: 'text',
|
|
433
|
+
text: `Figma file data fetched and transformed:\n\n${JSON.stringify(data, null, 2)}`
|
|
434
|
+
}
|
|
435
|
+
]
|
|
436
|
+
}
|
|
437
|
+
};
|
|
438
|
+
} catch (error) {
|
|
439
|
+
return {
|
|
440
|
+
jsonrpc: '2.0',
|
|
441
|
+
id,
|
|
442
|
+
result: {
|
|
443
|
+
content: [
|
|
444
|
+
{
|
|
445
|
+
type: 'text',
|
|
446
|
+
text: `Error fetching Figma file: ${redact(error.message)}\n\nMake sure:\n1. The file ID is correct\n2. The file is public or you have access\n3. The API key is valid`
|
|
447
|
+
}
|
|
448
|
+
]
|
|
449
|
+
}
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
case 'get_figma_component':
|
|
454
|
+
const figmaUrl = args?.figmaUrl;
|
|
455
|
+
if (!figmaUrl) {
|
|
456
|
+
throw new Error('Figma URL is required');
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
try {
|
|
460
|
+
const { fileId: componentFileId, nodeId } = this.parseFigmaUrl(figmaUrl);
|
|
461
|
+
|
|
462
|
+
if (!componentFileId) {
|
|
463
|
+
throw new Error('Could not extract file ID from URL');
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
if (!nodeId) {
|
|
467
|
+
throw new Error('Could not extract node ID from URL. Make sure the URL contains ?node-id= parameter');
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
const maxDepth = args && typeof args.maxDepth === 'number' ? args.maxDepth : undefined;
|
|
471
|
+
const rawIR = await this.fetchFigmaComponent(componentFileId, nodeId, maxDepth);
|
|
472
|
+
|
|
473
|
+
// Phase 1: deterministic pruning pass.
|
|
474
|
+
// Pass args.prune = false to skip (debug mode, returns raw IR).
|
|
475
|
+
const skipPrune = args && args.prune === false;
|
|
476
|
+
let prunedIR = rawIR;
|
|
477
|
+
let pruneStats = null;
|
|
478
|
+
if (!skipPrune) {
|
|
479
|
+
const { pruned, stats } = prune(rawIR, { verbose: true });
|
|
480
|
+
prunedIR = pruned;
|
|
481
|
+
pruneStats = stats;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// Phase 2: tokenisation — frequency analysis → CSS vars + annotated IR.
|
|
485
|
+
// Pass args.tokenize = false to skip.
|
|
486
|
+
const skipTokenize = args && args.tokenize === false;
|
|
487
|
+
let tokenizedIR = prunedIR;
|
|
488
|
+
let cssVars = null;
|
|
489
|
+
let tokenStats = null;
|
|
490
|
+
let tailwindTheme = null;
|
|
491
|
+
if (!skipTokenize) {
|
|
492
|
+
const minFreq = (args && args.minFreq) || 2;
|
|
493
|
+
const result = tokenize(prunedIR, { minFreq, annotate: true, resolveVars: true });
|
|
494
|
+
tokenizedIR = result.annotatedIR;
|
|
495
|
+
cssVars = result.cssVars;
|
|
496
|
+
tokenStats = result.stats;
|
|
497
|
+
tailwindTheme = toTailwindTheme(result.tokenTable);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// Phase 3: componentization — text styles + component registry.
|
|
501
|
+
// Pass args.componentize = false to skip.
|
|
502
|
+
const skipComponentize = args && args.componentize === false;
|
|
503
|
+
let componentData = tokenizedIR;
|
|
504
|
+
let componentRegistry = null;
|
|
505
|
+
let componentStats = null;
|
|
506
|
+
if (!skipComponentize) {
|
|
507
|
+
const dataDir = PATHS.dataDir;
|
|
508
|
+
const result = componentize(tokenizedIR, {
|
|
509
|
+
dataDir,
|
|
510
|
+
fileId: componentFileId,
|
|
511
|
+
persist: true,
|
|
512
|
+
});
|
|
513
|
+
componentData = result.annotatedIR;
|
|
514
|
+
componentRegistry = result.registry;
|
|
515
|
+
componentStats = result.stats;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
// Build response header
|
|
519
|
+
const pruneHeader = pruneStats
|
|
520
|
+
? `**Prune (Phase 1):** ${pruneStats.before} → ${pruneStats.after} nodes (−${pruneStats.reduction}% | collapsed:${pruneStats.collapsed})`
|
|
521
|
+
: '';
|
|
522
|
+
const tokenHeader = tokenStats
|
|
523
|
+
? `**Tokens (Phase 2):** ${tokenStats.tokenColors} colors, ${tokenStats.tokenSpacing} spacing, ${tokenStats.fontSizes} font-sizes | varMap:${tokenStats.varMapSize} aliases`
|
|
524
|
+
: '';
|
|
525
|
+
const componentHeader = componentStats
|
|
526
|
+
? `**Components (Phase 3):** ${componentStats.componentIds} components (${componentStats.variantComponents} with variants) | ${componentStats.textStyles} text styles | ${componentStats.instanceNodes} instances`
|
|
527
|
+
: '';
|
|
528
|
+
const statsBlock = [pruneHeader, tokenHeader, componentHeader].filter(Boolean).join('\n');
|
|
529
|
+
|
|
530
|
+
const cssBlock = cssVars
|
|
531
|
+
? `\n\n**Design Tokens (CSS variables):**\n\`\`\`css\n${cssVars}\n\`\`\``
|
|
532
|
+
: '';
|
|
533
|
+
|
|
534
|
+
const registryBlock = componentRegistry
|
|
535
|
+
? `\n\n**Component Registry:**\n\`\`\`json\n${JSON.stringify(componentRegistry, null, 2)}\n\`\`\``
|
|
536
|
+
: '';
|
|
537
|
+
|
|
538
|
+
const tailwindBlock = tailwindTheme
|
|
539
|
+
? `\n\n**Tailwind Theme (theme.extend):**\n\`\`\`json\n${JSON.stringify(tailwindTheme, null, 2)}\n\`\`\``
|
|
540
|
+
: '';
|
|
541
|
+
|
|
542
|
+
// Lean mode: omit the global blocks (CSS vars / Tailwind / registry) that
|
|
543
|
+
// are IDENTICAL on every call for the same file. The agent already has them
|
|
544
|
+
// from the summary call, so re-emitting ~15KB per section fetch is pure
|
|
545
|
+
// duplication. Pass lean:true on per-section fetches after the summary.
|
|
546
|
+
const lean = args && args.lean === true;
|
|
547
|
+
const gCss = lean ? '' : cssBlock;
|
|
548
|
+
const gTw = lean ? '' : tailwindBlock;
|
|
549
|
+
const gReg = lean ? '' : registryBlock;
|
|
550
|
+
const leanNote = lean
|
|
551
|
+
? '\n\n_(lean: CSS vars / Tailwind / registry omitted — reuse them from the summary call)_'
|
|
552
|
+
: '';
|
|
553
|
+
|
|
554
|
+
// Summary mode: skip full annotated IR, return compact object instead
|
|
555
|
+
const summaryMode = args && args.summary === true;
|
|
556
|
+
if (summaryMode) {
|
|
557
|
+
const rootBox = componentData.box || {
|
|
558
|
+
w: componentData.width,
|
|
559
|
+
h: componentData.height,
|
|
560
|
+
x: componentData.x,
|
|
561
|
+
y: componentData.y,
|
|
562
|
+
};
|
|
563
|
+
const rx = typeof rootBox.x === 'number' ? rootBox.x : 0;
|
|
564
|
+
const ry = typeof rootBox.y === 'number' ? rootBox.y : 0;
|
|
565
|
+
const sections = (componentData.children || []).map((child) => {
|
|
566
|
+
const cb = child.box || { w: child.width, h: child.height, x: child.x, y: child.y };
|
|
567
|
+
const relativeBox = (typeof cb.x === 'number' && typeof cb.y === 'number')
|
|
568
|
+
? { x: Math.round((cb.x - rx) * 100) / 100, y: Math.round((cb.y - ry) * 100) / 100, w: cb.w, h: cb.h }
|
|
569
|
+
: undefined;
|
|
570
|
+
return {
|
|
571
|
+
id: child.id,
|
|
572
|
+
name: child.name,
|
|
573
|
+
type: child.type,
|
|
574
|
+
box: cb, // absolute canvas coords (raw)
|
|
575
|
+
relativeBox, // origin-corrected against root — USE THIS for layout
|
|
576
|
+
childCount: Array.isArray(child.children) ? child.children.length : 0,
|
|
577
|
+
...(child._componentName ? { _componentName: child._componentName } : {}),
|
|
578
|
+
...(child._textStyle ? { _textStyle: child._textStyle } : {}),
|
|
579
|
+
};
|
|
580
|
+
});
|
|
581
|
+
|
|
582
|
+
return {
|
|
583
|
+
jsonrpc: '2.0',
|
|
584
|
+
id,
|
|
585
|
+
result: {
|
|
586
|
+
content: [
|
|
587
|
+
{
|
|
588
|
+
type: 'text',
|
|
589
|
+
text: `Figma component (summary mode):\n\n**Component:** ${componentData.name}\n**Type:** ${componentData.type}\n**ID:** ${componentData.id}\n**Root frame box:** x=${rx}, y=${ry}, w=${rootBox.w ?? '?'}, h=${rootBox.h ?? '?'} (origin = x,y; size = w,h)\n\n${statsBlock}${gCss}${gTw}${gReg}\n\n> For HTML top/left use each section's \`relativeBox\` (already origin-corrected against the root) — NOT the absolute \`box.x/y\`. frameWidth for verify_render = root w (${rootBox.w ?? '?'}).\n\n**Top-level sections (${sections.length}):**\n\`\`\`json\n${JSON.stringify(sections, null, 2)}\n\`\`\``
|
|
590
|
+
}
|
|
591
|
+
],
|
|
592
|
+
structuredContent: {
|
|
593
|
+
component: { name: componentData.name, type: componentData.type, id: componentData.id, box: rootBox },
|
|
594
|
+
stats: { prune: pruneStats, tokens: tokenStats, components: componentStats },
|
|
595
|
+
cssVars,
|
|
596
|
+
tailwindTheme,
|
|
597
|
+
registry: componentRegistry,
|
|
598
|
+
sections,
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
const flatMode = args && args.format === 'flat';
|
|
605
|
+
let irBlock;
|
|
606
|
+
if (flatMode) {
|
|
607
|
+
const flat = flattenIR(componentData);
|
|
608
|
+
irBlock = `**Flat node list (${flat.length} nodes — \`rel\` = coords relative to root, render fields only; reuse $--var tokens from the summary call):**\n\`\`\`json\n${JSON.stringify(flat)}\n\`\`\``;
|
|
609
|
+
} else {
|
|
610
|
+
irBlock = `**Annotated IR:**\n\`\`\`json\n${JSON.stringify(componentData, null, 2)}\n\`\`\``;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
return {
|
|
614
|
+
jsonrpc: '2.0',
|
|
615
|
+
id,
|
|
616
|
+
result: {
|
|
617
|
+
content: [
|
|
618
|
+
{
|
|
619
|
+
type: 'text',
|
|
620
|
+
text: `Figma component fetched successfully:\n\n**Component:** ${componentData.name}\n**Type:** ${componentData.type}\n**ID:** ${componentData.id}\n\n${statsBlock}${gCss}${gTw}${gReg}${leanNote}\n\n${irBlock}`
|
|
621
|
+
}
|
|
622
|
+
]
|
|
623
|
+
}
|
|
624
|
+
};
|
|
625
|
+
} catch (error) {
|
|
626
|
+
return {
|
|
627
|
+
jsonrpc: '2.0',
|
|
628
|
+
id,
|
|
629
|
+
result: {
|
|
630
|
+
content: [
|
|
631
|
+
{
|
|
632
|
+
type: 'text',
|
|
633
|
+
text: `Error fetching Figma component: ${redact(error.message)}\n\nMake sure:\n1. The URL is a valid Figma design URL\n2. The URL contains node-id parameter\n3. You have access to the file\n4. The component exists\n\nExample URL format:\nhttps://www.figma.com/design/{fileId}/...?node-id={nodeId}`
|
|
634
|
+
}
|
|
635
|
+
]
|
|
636
|
+
}
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
case 'export_svg':
|
|
641
|
+
const { fileId: svgFileId, nodeId: svgNodeId, scale = 1, save = false, fileName, outputDir = PATHS.svgDir } = args;
|
|
642
|
+
|
|
643
|
+
if (!svgFileId || !svgNodeId) {
|
|
644
|
+
throw new Error('Both fileId and nodeId are required');
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
try {
|
|
648
|
+
const svgContent = await this.exportSVG(svgFileId, svgNodeId, scale);
|
|
649
|
+
|
|
650
|
+
let result = {
|
|
651
|
+
nodeId: svgNodeId,
|
|
652
|
+
svgContent: svgContent,
|
|
653
|
+
size: svgContent.length
|
|
654
|
+
};
|
|
655
|
+
|
|
656
|
+
if (save) {
|
|
657
|
+
const name = fileName || `node_${svgNodeId}`;
|
|
658
|
+
const filePath = await this.saveSVG(svgContent, name, outputDir);
|
|
659
|
+
result.savedTo = filePath;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
return {
|
|
663
|
+
jsonrpc: '2.0',
|
|
664
|
+
id,
|
|
665
|
+
result: {
|
|
666
|
+
content: [
|
|
667
|
+
{
|
|
668
|
+
type: 'text',
|
|
669
|
+
text: `SVG exported successfully:\n\n**Node ID:** ${svgNodeId}\n**Size:** ${result.size} characters\n${result.savedTo ? `**Saved to:** ${result.savedTo}\n` : ''}**Scale:** ${scale}\n\n**SVG Content Preview (first 500 chars):**\n\`\`\`svg\n${svgContent.substring(0, 500)}${svgContent.length > 500 ? '...' : ''}\n\`\`\``
|
|
670
|
+
}
|
|
671
|
+
]
|
|
672
|
+
}
|
|
673
|
+
};
|
|
674
|
+
} catch (error) {
|
|
675
|
+
return {
|
|
676
|
+
jsonrpc: '2.0',
|
|
677
|
+
id,
|
|
678
|
+
result: {
|
|
679
|
+
content: [
|
|
680
|
+
{
|
|
681
|
+
type: 'text',
|
|
682
|
+
text: `Error exporting SVG: ${redact(error.message)}\n\nMake sure:\n1. The file ID and node ID are correct\n2. The node can be exported as SVG\n3. You have access to the file`
|
|
683
|
+
}
|
|
684
|
+
]
|
|
685
|
+
}
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
case 'render_node_png': {
|
|
690
|
+
// Accept either figmaUrl OR {fileId, nodeId}
|
|
691
|
+
let pngFileId, pngNodeId;
|
|
692
|
+
if (args && args.figmaUrl) {
|
|
693
|
+
const parsed = this.parseFigmaUrl(args.figmaUrl);
|
|
694
|
+
pngFileId = parsed.fileId;
|
|
695
|
+
pngNodeId = parsed.nodeId;
|
|
696
|
+
} else {
|
|
697
|
+
pngFileId = args && args.fileId;
|
|
698
|
+
pngNodeId = args && args.nodeId;
|
|
699
|
+
}
|
|
700
|
+
const pngScale = (args && args.scale) || 2;
|
|
701
|
+
|
|
702
|
+
if (!pngFileId || !pngNodeId) {
|
|
703
|
+
throw new Error('figmaUrl (or fileId + nodeId) is required for render_node_png');
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
try {
|
|
707
|
+
const { imageUrl, base64, size } = await this.exportPNG(pngFileId, pngNodeId, pngScale);
|
|
708
|
+
|
|
709
|
+
return {
|
|
710
|
+
jsonrpc: '2.0',
|
|
711
|
+
id,
|
|
712
|
+
result: {
|
|
713
|
+
content: [
|
|
714
|
+
{
|
|
715
|
+
type: 'text',
|
|
716
|
+
text: `PNG exported successfully:\n\n**Node ID:** ${pngNodeId}\n**Scale:** ${pngScale}x\n**Size:** ${size} bytes\n**Image URL:** ${imageUrl}\n\n**Base64 (data URI):**\ndata:image/png;base64,${base64.substring(0, 80)}...`
|
|
717
|
+
}
|
|
718
|
+
],
|
|
719
|
+
structuredContent: {
|
|
720
|
+
nodeId: pngNodeId,
|
|
721
|
+
imageUrl,
|
|
722
|
+
base64,
|
|
723
|
+
size,
|
|
724
|
+
scale: pngScale,
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
};
|
|
728
|
+
} catch (error) {
|
|
729
|
+
return {
|
|
730
|
+
jsonrpc: '2.0',
|
|
731
|
+
id,
|
|
732
|
+
result: {
|
|
733
|
+
content: [
|
|
734
|
+
{
|
|
735
|
+
type: 'text',
|
|
736
|
+
text: `Error exporting PNG: ${redact(error.message)}\n\nMake sure:\n1. The file ID and node ID are correct\n2. You have access to the file`
|
|
737
|
+
}
|
|
738
|
+
]
|
|
739
|
+
}
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
case 'migrate_all_svgs':
|
|
745
|
+
const { fileId: migrateFileId, outputDir: migrateOutputDir = PATHS.svgDir } = args;
|
|
746
|
+
|
|
747
|
+
if (!migrateFileId) {
|
|
748
|
+
throw new Error('File ID is required');
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
try {
|
|
752
|
+
const results = await this.migrateAllSVGs(migrateFileId, migrateOutputDir);
|
|
753
|
+
const successful = results.filter(r => r.success);
|
|
754
|
+
const failed = results.filter(r => !r.success);
|
|
755
|
+
|
|
756
|
+
return {
|
|
757
|
+
jsonrpc: '2.0',
|
|
758
|
+
id,
|
|
759
|
+
result: {
|
|
760
|
+
content: [
|
|
761
|
+
{
|
|
762
|
+
type: 'text',
|
|
763
|
+
text: `SVG Migration Complete!\n\n**Summary:**\n- Total nodes processed: ${results.length}\n- Successfully exported: ${successful.length}\n- Failed: ${failed.length}\n- Output directory: ${migrateOutputDir}\n\n**Successful exports:**\n${successful.map(r => `✅ ${r.name} → ${r.filePath}`).join('\n')}\n\n${failed.length > 0 ? `**Failed exports:**\n${failed.map(r => `❌ ${r.name}: ${r.error}`).join('\n')}` : ''}\n\n**Detailed Results:**\n\`\`\`json\n${JSON.stringify(results, null, 2)}\n\`\`\``
|
|
764
|
+
}
|
|
765
|
+
]
|
|
766
|
+
}
|
|
767
|
+
};
|
|
768
|
+
} catch (error) {
|
|
769
|
+
return {
|
|
770
|
+
jsonrpc: '2.0',
|
|
771
|
+
id,
|
|
772
|
+
result: {
|
|
773
|
+
content: [
|
|
774
|
+
{
|
|
775
|
+
type: 'text',
|
|
776
|
+
text: `Error migrating SVGs: ${redact(error.message)}\n\nMake sure:\n1. The file ID is correct\n2. You have access to the file\n3. The output directory is writable`
|
|
777
|
+
}
|
|
778
|
+
]
|
|
779
|
+
}
|
|
780
|
+
};
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
case 'list_svg_cache':
|
|
784
|
+
const cacheEntries = Array.from(this.svgCache.entries()).map(([nodeId, content]) => ({
|
|
785
|
+
nodeId,
|
|
786
|
+
size: content.length,
|
|
787
|
+
preview: content.substring(0, 100) + (content.length > 100 ? '...' : '')
|
|
788
|
+
}));
|
|
789
|
+
|
|
790
|
+
return {
|
|
791
|
+
jsonrpc: '2.0',
|
|
792
|
+
id,
|
|
793
|
+
result: {
|
|
794
|
+
content: [
|
|
795
|
+
{
|
|
796
|
+
type: 'text',
|
|
797
|
+
text: cacheEntries.length > 0 ?
|
|
798
|
+
`Cached SVG exports (${cacheEntries.length}):\n\n${cacheEntries.map(entry => `**${entry.nodeId}**: ${entry.size} chars\n\`${entry.preview}\`\n`).join('\n')}` :
|
|
799
|
+
'No SVG exports cached yet.'
|
|
800
|
+
}
|
|
801
|
+
]
|
|
802
|
+
}
|
|
803
|
+
};
|
|
804
|
+
|
|
805
|
+
case 'get_cached_components':
|
|
806
|
+
return {
|
|
807
|
+
jsonrpc: '2.0',
|
|
808
|
+
id,
|
|
809
|
+
result: {
|
|
810
|
+
content: [
|
|
811
|
+
{
|
|
812
|
+
type: 'text',
|
|
813
|
+
text: this.figmaData ?
|
|
814
|
+
`Cached Figma components:\n\n${JSON.stringify(this.figmaData, null, 2)}` :
|
|
815
|
+
'No Figma data cached yet. Use get_figma_file first with a file ID.'
|
|
816
|
+
}
|
|
817
|
+
]
|
|
818
|
+
}
|
|
819
|
+
};
|
|
820
|
+
|
|
821
|
+
case 'get_component_by_name':
|
|
822
|
+
const componentName = args?.name;
|
|
823
|
+
if (!componentName) {
|
|
824
|
+
throw new Error('Component name is required');
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
if (!this.figmaData) {
|
|
828
|
+
return {
|
|
829
|
+
jsonrpc: '2.0',
|
|
830
|
+
id,
|
|
831
|
+
result: {
|
|
832
|
+
content: [
|
|
833
|
+
{
|
|
834
|
+
type: 'text',
|
|
835
|
+
text: 'No Figma data cached yet. Use get_figma_file first with a file ID.'
|
|
836
|
+
}
|
|
837
|
+
]
|
|
838
|
+
}
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
const component = this.figmaData?.find(comp =>
|
|
843
|
+
comp.name?.toLowerCase().includes(componentName.toLowerCase())
|
|
844
|
+
);
|
|
845
|
+
|
|
846
|
+
return {
|
|
847
|
+
jsonrpc: '2.0',
|
|
848
|
+
id,
|
|
849
|
+
result: {
|
|
850
|
+
content: [
|
|
851
|
+
{
|
|
852
|
+
type: 'text',
|
|
853
|
+
text: component ?
|
|
854
|
+
`Found component "${componentName}":\n\n${JSON.stringify(component, null, 2)}` :
|
|
855
|
+
`No component found with name containing "${componentName}"`
|
|
856
|
+
}
|
|
857
|
+
]
|
|
858
|
+
}
|
|
859
|
+
};
|
|
860
|
+
|
|
861
|
+
case 'verify_render': {
|
|
862
|
+
const { verifyRender } = require('./src/visual/verify');
|
|
863
|
+
const vHtmlPath = args && args.htmlPath;
|
|
864
|
+
const vFrameWidth = args && args.frameWidth;
|
|
865
|
+
if (!vHtmlPath || !vFrameWidth) {
|
|
866
|
+
throw new Error('verify_render requires htmlPath and frameWidth');
|
|
867
|
+
}
|
|
868
|
+
const vScale = (args && args.scale) || 2;
|
|
869
|
+
const vThreshold = (args && typeof args.threshold === 'number') ? args.threshold : 0.95;
|
|
870
|
+
const vOutDir = (args && args.outDir) || PATHS.verifyDir;
|
|
871
|
+
|
|
872
|
+
try {
|
|
873
|
+
// Resolve the reference PNG buffer
|
|
874
|
+
let referencePngBuffer;
|
|
875
|
+
if (args.figmaUrl) {
|
|
876
|
+
const { fileId: vFileId, nodeId: vNodeId } = this.parseFigmaUrl(args.figmaUrl);
|
|
877
|
+
const { base64 } = await this.exportPNG(vFileId, vNodeId, vScale);
|
|
878
|
+
referencePngBuffer = Buffer.from(base64, 'base64');
|
|
879
|
+
} else if (args.figmaPngPath) {
|
|
880
|
+
referencePngBuffer = fs.readFileSync(args.figmaPngPath);
|
|
881
|
+
} else if (args.figmaPngBase64) {
|
|
882
|
+
referencePngBuffer = Buffer.from(args.figmaPngBase64, 'base64');
|
|
883
|
+
} else {
|
|
884
|
+
throw new Error('Provide a reference PNG: figmaUrl, figmaPngPath, or figmaPngBase64');
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
const label = path.basename(vHtmlPath).replace(/\.html?$/i, '');
|
|
888
|
+
const result = await verifyRender({
|
|
889
|
+
htmlPath: vHtmlPath,
|
|
890
|
+
referencePngBuffer,
|
|
891
|
+
frameWidth: vFrameWidth,
|
|
892
|
+
scale: vScale,
|
|
893
|
+
threshold: vThreshold,
|
|
894
|
+
outDir: vOutDir,
|
|
895
|
+
label,
|
|
896
|
+
bg: Array.isArray(args.bg) ? args.bg : undefined,
|
|
897
|
+
clip: Array.isArray(args.clip) ? args.clip : undefined,
|
|
898
|
+
});
|
|
899
|
+
|
|
900
|
+
const regions = result.diffRegions.map((r, i) =>
|
|
901
|
+
` ${i + 1}. [${r.type}] (${r.x},${r.y}) ${r.w}×${r.h} — render ${r.renderColor} vs design ${r.refColor} (Δ${r.colorDelta}), ${r.diffPixels}px`).join('\n')
|
|
902
|
+
|| ' (no regions above threshold)';
|
|
903
|
+
|
|
904
|
+
return {
|
|
905
|
+
jsonrpc: '2.0',
|
|
906
|
+
id,
|
|
907
|
+
result: {
|
|
908
|
+
content: [
|
|
909
|
+
{
|
|
910
|
+
type: 'text',
|
|
911
|
+
text: `Visual verification — ${label}:\n\n**SSIM:** ${result.ssim} (threshold ${result.threshold} → ${result.pass ? 'PASS ✅' : 'BELOW ❌'})\n**Pixel diff:** ${result.pixelDiffPct}% (${result.diffPixels} px of ${result.dims.w}×${result.dims.h})\n**Diff image:** ${result.diffImagePath || '(not saved)'}\n\n**Diff regions (logical px, largest first):**\n${regions}\n\nRead the regions and fix only those areas — this tool does not change code.`
|
|
912
|
+
}
|
|
913
|
+
],
|
|
914
|
+
structuredContent: result,
|
|
915
|
+
}
|
|
916
|
+
};
|
|
917
|
+
} catch (error) {
|
|
918
|
+
return {
|
|
919
|
+
jsonrpc: '2.0',
|
|
920
|
+
id,
|
|
921
|
+
result: {
|
|
922
|
+
content: [
|
|
923
|
+
{ type: 'text', text: `Error in verify_render: ${redact(error.message)}\n\nIf this mentions playwright or a missing executable, run \`npx playwright install chromium\` once, then retry. Diagnose with \`npx figma-proxy-mcp --check\`.` }
|
|
924
|
+
]
|
|
925
|
+
}
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
default:
|
|
931
|
+
throw new Error(`Unknown tool: ${name}`);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
// Export SVG from Figma node
|
|
936
|
+
async exportSVG(fileId, nodeId, scale = 1) {
|
|
937
|
+
try {
|
|
938
|
+
const params = new URLSearchParams({
|
|
939
|
+
ids: nodeId,
|
|
940
|
+
format: 'svg',
|
|
941
|
+
scale: scale.toString()
|
|
942
|
+
});
|
|
943
|
+
|
|
944
|
+
const response = await fetch(`https://api.figma.com/v1/images/${assertFileKey(fileId)}?${params}`, {
|
|
945
|
+
headers: {
|
|
946
|
+
'X-Figma-Token': requireApiKey()
|
|
947
|
+
}
|
|
948
|
+
});
|
|
949
|
+
|
|
950
|
+
if (!response.ok) {
|
|
951
|
+
throw figmaHttpError(response.status);
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
const data = await response.json();
|
|
955
|
+
const svgUrl = data.images[nodeId];
|
|
956
|
+
|
|
957
|
+
if (!svgUrl) {
|
|
958
|
+
throw new Error('No SVG URL returned from Figma API');
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
// Fetch the actual SVG content
|
|
962
|
+
assertHttpsUrl(svgUrl);
|
|
963
|
+
const svgResponse = await fetch(svgUrl);
|
|
964
|
+
if (!svgResponse.ok) {
|
|
965
|
+
throw new Error(`Failed to fetch SVG content: ${svgResponse.status}`);
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
const svgContent = await svgResponse.text();
|
|
969
|
+
|
|
970
|
+
// Cache the SVG
|
|
971
|
+
this.svgCache.set(nodeId, svgContent);
|
|
972
|
+
|
|
973
|
+
return svgContent;
|
|
974
|
+
} catch (error) {
|
|
975
|
+
console.error('Error exporting SVG:', redact(error && error.message));
|
|
976
|
+
throw error;
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
// Export PNG from Figma node — returns { imageUrl, base64, size }
|
|
981
|
+
async exportPNG(fileId, nodeId, scale = 2) {
|
|
982
|
+
try {
|
|
983
|
+
const params = new URLSearchParams({
|
|
984
|
+
ids: nodeId,
|
|
985
|
+
format: 'png',
|
|
986
|
+
scale: scale.toString(),
|
|
987
|
+
});
|
|
988
|
+
|
|
989
|
+
const response = await fetch(`https://api.figma.com/v1/images/${assertFileKey(fileId)}?${params}`, {
|
|
990
|
+
headers: { 'X-Figma-Token': requireApiKey() },
|
|
991
|
+
});
|
|
992
|
+
|
|
993
|
+
if (!response.ok) {
|
|
994
|
+
throw figmaHttpError(response.status);
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
const data = await response.json();
|
|
998
|
+
|
|
999
|
+
// Figma returns { images: { [nodeId]: url } }
|
|
1000
|
+
// The nodeId key in the response uses the original format from the request
|
|
1001
|
+
const imageUrl = data.images && (data.images[nodeId] || Object.values(data.images)[0]);
|
|
1002
|
+
|
|
1003
|
+
if (!imageUrl) {
|
|
1004
|
+
throw new Error('No PNG URL returned from Figma API');
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
// Download the PNG and convert to base64
|
|
1008
|
+
assertHttpsUrl(imageUrl);
|
|
1009
|
+
const imgResponse = await fetch(imageUrl);
|
|
1010
|
+
if (!imgResponse.ok) {
|
|
1011
|
+
throw new Error(`Failed to fetch PNG: ${imgResponse.status}`);
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
const arrayBuffer = await imgResponse.arrayBuffer();
|
|
1015
|
+
const buffer = Buffer.from(arrayBuffer);
|
|
1016
|
+
const base64 = buffer.toString('base64');
|
|
1017
|
+
|
|
1018
|
+
return { imageUrl, base64, size: buffer.length };
|
|
1019
|
+
} catch (error) {
|
|
1020
|
+
console.error('Error exporting PNG:', redact(error && error.message));
|
|
1021
|
+
throw error;
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
// Save SVG to file system
|
|
1026
|
+
async saveSVG(svgContent, fileName, outputDir = PATHS.svgDir) {
|
|
1027
|
+
try {
|
|
1028
|
+
// Ensure output directory exists
|
|
1029
|
+
if (!fs.existsSync(outputDir)) {
|
|
1030
|
+
fs.mkdirSync(outputDir, { recursive: true });
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
// Clean filename
|
|
1034
|
+
const cleanFileName = fileName.replace(/[^a-z0-9]/gi, '_').toLowerCase();
|
|
1035
|
+
const filePath = path.join(outputDir, `${cleanFileName}.svg`);
|
|
1036
|
+
|
|
1037
|
+
fs.writeFileSync(filePath, svgContent, 'utf8');
|
|
1038
|
+
|
|
1039
|
+
return filePath;
|
|
1040
|
+
} catch (error) {
|
|
1041
|
+
console.error('Error saving SVG:', redact(error && error.message));
|
|
1042
|
+
throw error;
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
// Migrate all SVG icons from a Figma file
|
|
1047
|
+
async migrateAllSVGs(fileId, outputDir = PATHS.svgDir) {
|
|
1048
|
+
try {
|
|
1049
|
+
const figmaData = await this.fetchFigmaData(fileId);
|
|
1050
|
+
const svgNodes = this.findSVGNodes(figmaData);
|
|
1051
|
+
const results = [];
|
|
1052
|
+
|
|
1053
|
+
for (const node of svgNodes) {
|
|
1054
|
+
try {
|
|
1055
|
+
const svgContent = await this.exportSVG(fileId, node.id);
|
|
1056
|
+
const filePath = await this.saveSVG(svgContent, node.name, outputDir);
|
|
1057
|
+
|
|
1058
|
+
results.push({
|
|
1059
|
+
nodeId: node.id,
|
|
1060
|
+
name: node.name,
|
|
1061
|
+
filePath: filePath,
|
|
1062
|
+
success: true
|
|
1063
|
+
});
|
|
1064
|
+
|
|
1065
|
+
// Small delay to avoid rate limiting
|
|
1066
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
1067
|
+
} catch (error) {
|
|
1068
|
+
results.push({
|
|
1069
|
+
nodeId: node.id,
|
|
1070
|
+
name: node.name,
|
|
1071
|
+
error: error.message,
|
|
1072
|
+
success: false
|
|
1073
|
+
});
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
return results;
|
|
1078
|
+
} catch (error) {
|
|
1079
|
+
console.error('Error migrating SVGs:', redact(error && error.message));
|
|
1080
|
+
throw error;
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
// Find potential SVG nodes in Figma data
|
|
1085
|
+
findSVGNodes(data) {
|
|
1086
|
+
const svgNodes = [];
|
|
1087
|
+
|
|
1088
|
+
const traverseNode = (node) => {
|
|
1089
|
+
// Check if node could be an icon/SVG
|
|
1090
|
+
if (node && (
|
|
1091
|
+
node.type === 'VECTOR' ||
|
|
1092
|
+
node.type === 'BOOLEAN_OPERATION' ||
|
|
1093
|
+
(node.name && node.name.toLowerCase().includes('icon')) ||
|
|
1094
|
+
(node.name && node.name.toLowerCase().includes('svg')) ||
|
|
1095
|
+
(node.exportSettings && node.exportSettings.some(s => s.format === 'SVG'))
|
|
1096
|
+
)) {
|
|
1097
|
+
svgNodes.push({
|
|
1098
|
+
id: node.id,
|
|
1099
|
+
name: node.name,
|
|
1100
|
+
type: node.type
|
|
1101
|
+
});
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
// Recursively check children (canonical IR uses `children`)
|
|
1105
|
+
const kids = node.children || node.childrenData;
|
|
1106
|
+
if (Array.isArray(kids)) {
|
|
1107
|
+
kids.forEach(traverseNode);
|
|
1108
|
+
}
|
|
1109
|
+
};
|
|
1110
|
+
|
|
1111
|
+
if (Array.isArray(data)) {
|
|
1112
|
+
data.forEach(traverseNode);
|
|
1113
|
+
} else {
|
|
1114
|
+
traverseNode(data);
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
return svgNodes;
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
function printHelp() {
|
|
1122
|
+
process.stdout.write(`figma-proxy-mcp ${PKG_VERSION} - read-only Figma -> code MCP server
|
|
1123
|
+
|
|
1124
|
+
Usage:
|
|
1125
|
+
figma-proxy-mcp --stdio run as an MCP server over stdio (for MCP clients)
|
|
1126
|
+
figma-proxy-mcp run the HTTP JSON-RPC endpoint on 127.0.0.1:4444/mcp
|
|
1127
|
+
figma-proxy-mcp --check diagnose setup (Node, token, Figma API, Chromium)
|
|
1128
|
+
figma-proxy-mcp --version print version
|
|
1129
|
+
|
|
1130
|
+
Environment:
|
|
1131
|
+
FIGMA_API_KEY Figma personal access token (required; read-only scope is enough)
|
|
1132
|
+
FIGMA_PROXY_PORT HTTP port (default 4444)
|
|
1133
|
+
FIGMA_PROXY_HOST HTTP bind address (default 127.0.0.1)
|
|
1134
|
+
FIGMA_PROXY_CACHE_DIR base dir for writes (default <os temp>/figma-proxy-mcp)
|
|
1135
|
+
See SECURITY.md for every host contacted and every file written.
|
|
1136
|
+
`);
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
function startStdio() {
|
|
1140
|
+
const server = new MCPProxyServer();
|
|
1141
|
+
let buffer = '';
|
|
1142
|
+
|
|
1143
|
+
const handleLine = async (line) => {
|
|
1144
|
+
let request;
|
|
1145
|
+
try {
|
|
1146
|
+
request = JSON.parse(line);
|
|
1147
|
+
} catch (error) {
|
|
1148
|
+
process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }) + '\n');
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
1151
|
+
try {
|
|
1152
|
+
const response = await server.handleRequest(request);
|
|
1153
|
+
if (response) process.stdout.write(JSON.stringify(response) + '\n');
|
|
1154
|
+
} catch (error) {
|
|
1155
|
+
console.error('Error processing request:', redact(error && error.message));
|
|
1156
|
+
}
|
|
1157
|
+
};
|
|
1158
|
+
|
|
1159
|
+
process.stdin.setEncoding('utf8');
|
|
1160
|
+
process.stdin.on('data', (chunk) => {
|
|
1161
|
+
// Messages are newline-delimited; a chunk may hold several or a partial one.
|
|
1162
|
+
buffer += chunk;
|
|
1163
|
+
let nl;
|
|
1164
|
+
while ((nl = buffer.indexOf('\n')) !== -1) {
|
|
1165
|
+
const line = buffer.slice(0, nl).trim();
|
|
1166
|
+
buffer = buffer.slice(nl + 1);
|
|
1167
|
+
if (line) handleLine(line);
|
|
1168
|
+
}
|
|
1169
|
+
});
|
|
1170
|
+
process.stdin.on('end', () => {
|
|
1171
|
+
const line = buffer.trim();
|
|
1172
|
+
buffer = '';
|
|
1173
|
+
if (line) handleLine(line);
|
|
1174
|
+
});
|
|
1175
|
+
|
|
1176
|
+
process.on('SIGINT', () => process.exit(0));
|
|
1177
|
+
process.on('SIGTERM', () => process.exit(0));
|
|
1178
|
+
|
|
1179
|
+
console.error(`figma-proxy-mcp ${PKG_VERSION} started in stdio mode`);
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
function startHttp() {
|
|
1183
|
+
const express = require('express');
|
|
1184
|
+
const app = express();
|
|
1185
|
+
const port = Number(process.env.FIGMA_PROXY_PORT || 4444);
|
|
1186
|
+
// Loopback only by default: the endpoint uses your Figma token and must not
|
|
1187
|
+
// be reachable from the network unless you explicitly opt in.
|
|
1188
|
+
const host = process.env.FIGMA_PROXY_HOST || '127.0.0.1';
|
|
1189
|
+
const server = new MCPProxyServer();
|
|
1190
|
+
|
|
1191
|
+
app.use(express.json({ limit: '25mb' }));
|
|
1192
|
+
|
|
1193
|
+
app.post('/mcp', async (req, res) => {
|
|
1194
|
+
try {
|
|
1195
|
+
const response = await server.handleRequest(req.body || {});
|
|
1196
|
+
if (response) {
|
|
1197
|
+
res.json(response);
|
|
1198
|
+
} else {
|
|
1199
|
+
res.status(204).send();
|
|
1200
|
+
}
|
|
1201
|
+
} catch (error) {
|
|
1202
|
+
res.status(500).json({
|
|
1203
|
+
jsonrpc: '2.0',
|
|
1204
|
+
id: (req.body && req.body.id) ?? null,
|
|
1205
|
+
error: {
|
|
1206
|
+
code: -32603,
|
|
1207
|
+
message: redact(error.message)
|
|
1208
|
+
}
|
|
1209
|
+
});
|
|
1210
|
+
}
|
|
1211
|
+
});
|
|
1212
|
+
|
|
1213
|
+
const httpServer = app.listen(port, host, () => {
|
|
1214
|
+
console.log(`figma-proxy-mcp ${PKG_VERSION} HTTP endpoint: http://${host}:${port}/mcp`);
|
|
1215
|
+
console.log('For MCP clients use stdio instead: npx -y figma-proxy-mcp --stdio');
|
|
1216
|
+
});
|
|
1217
|
+
httpServer.on('error', (err) => {
|
|
1218
|
+
console.error(`HTTP server error: ${err.code || err.message}${err.code === 'EADDRINUSE' ? ` (port ${port} busy; set FIGMA_PROXY_PORT)` : ''}`);
|
|
1219
|
+
process.exit(1);
|
|
1220
|
+
});
|
|
1221
|
+
return httpServer;
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
if (require.main === module) {
|
|
1225
|
+
const argv = process.argv.slice(2);
|
|
1226
|
+
if (argv.includes('--help') || argv.includes('-h')) {
|
|
1227
|
+
printHelp();
|
|
1228
|
+
} else if (argv.includes('--version') || argv.includes('-v')) {
|
|
1229
|
+
process.stdout.write(PKG_VERSION + '\n');
|
|
1230
|
+
} else if (argv.includes('--check') || argv.includes('--doctor')) {
|
|
1231
|
+
require('./scripts/check-setup').main().then((code) => process.exit(code));
|
|
1232
|
+
} else if (argv.includes('--stdio')) {
|
|
1233
|
+
startStdio();
|
|
1234
|
+
} else {
|
|
1235
|
+
startHttp();
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
// Export for testing
|
|
1240
|
+
module.exports = { MCPProxyServer };
|