Repository navigation
Expand file tree
/
Copy pathui.html
More file actions
1933 lines (1749 loc) · 79.2 KB
/
Copy pathui.html
File metadata and controls
1933 lines (1749 loc) · 79.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<style>
:root {
color-scheme: light dark;
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: Inter, "SF Pro Text", -apple-system, sans-serif;
font-size: 12px;
color: #1e1e1e;
background: #fff;
}
.tabs {
display: flex;
border-bottom: 1px solid #e6e6e6;
overflow-x: auto;
}
.tab {
flex: 1;
min-width: 66px;
padding: 10px 0;
text-align: center;
cursor: pointer;
background: none;
border: none;
font-size: 12px;
font-weight: 500;
color: #6b6b6b;
border-bottom: 2px solid transparent;
}
.tab.active {
color: #18a0fb;
border-bottom-color: #18a0fb;
}
.panel { display: none; padding: 12px; }
.panel.active { display: block; }
.node-name {
font-weight: 600;
margin-bottom: 8px;
word-break: break-all;
}
.warning {
background: #fff4e5;
color: #92610a;
border: 1px solid #ffdca0;
border-radius: 4px;
padding: 6px 8px;
margin-bottom: 8px;
font-size: 11px;
}
pre.code-block {
background: #f5f5f5;
border: 1px solid #e6e6e6;
border-radius: 6px;
padding: 10px;
font-family: "SF Mono", Menlo, monospace;
font-size: 11px;
white-space: pre-wrap;
word-break: break-word;
max-height: 380px;
overflow-y: auto;
margin: 0 0 8px 0;
}
.copy-btn {
background: #18a0fb;
color: #fff;
border: none;
border-radius: 6px;
padding: 6px 12px;
font-size: 11px;
cursor: pointer;
}
.copy-btn:hover { background: #0d8ce0; }
.copy-btn:disabled { background: #b8e0fd; cursor: default; }
.empty-state {
padding: 40px 16px;
text-align: center;
color: #8c8c8c;
}
.select-row {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 12px;
border-bottom: 1px solid #e6e6e6;
}
.select-row select {
flex: 1;
padding: 6px 8px;
border: 1px solid #e6e6e6;
border-radius: 6px;
font-size: 11px;
background: #fff;
color: inherit;
}
.responsive-toggle {
display: flex;
align-items: center;
gap: 6px;
font-size: 11px;
font-weight: 500;
cursor: pointer;
white-space: nowrap;
}
.responsive-toggle input { cursor: pointer; }
.hint {
color: #8c8c8c;
font-size: 10px;
margin: -4px 0 8px 0;
}
.status-ok { color: #1a7f37; }
.status-error { color: #b3261e; }
.debug-send-row {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 12px;
border-bottom: 1px solid #e6e6e6;
}
.subtabs {
display: flex;
border-bottom: 1px solid #e6e6e6;
margin: -12px -12px 12px -12px;
}
.subtab {
flex: 1;
padding: 8px 0;
text-align: center;
cursor: pointer;
background: none;
border: none;
font-size: 11px;
font-weight: 500;
color: #6b6b6b;
border-bottom: 2px solid transparent;
}
.subtab.active {
color: #18a0fb;
border-bottom-color: #18a0fb;
}
.subpanel { display: none; }
.subpanel.active { display: block; }
.preview-label {
font-weight: 600;
font-size: 11px;
margin: 8px 0 4px 0;
}
/* Window that crops the Figma export down to the node's own box — the export
itself also covers any shadow/stroke that overhangs it. */
.preview-figma-wrap {
overflow: hidden;
border: 1px solid #e6e6e6;
border-radius: 6px;
background: repeating-conic-gradient(#e6e6e6 0% 25%, #fff 0% 50%) 50% / 16px 16px;
}
.preview-figma-img {
display: block;
transform-origin: top left;
}
.preview-iframe-wrap {
overflow: hidden;
border: 1px solid #e6e6e6;
border-radius: 6px;
/* Same checkerboard as the Figma image above, so a node with transparency
is compared against an identical backdrop instead of plain white. */
background: repeating-conic-gradient(#e6e6e6 0% 25%, #fff 0% 50%) 50% / 16px 16px;
}
.preview-render-host {
transform-origin: top left;
display: block;
}
.system-summary {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-bottom: 10px;
}
.system-stat, .system-card {
border: 1px solid #e6e6e6;
border-radius: 6px;
padding: 8px;
}
.system-stat strong {
display: block;
font-size: 17px;
line-height: 20px;
}
.system-title {
font-weight: 600;
margin: 10px 0 6px;
}
.font-list, .component-list {
display: grid;
gap: 6px;
max-height: 160px;
overflow-y: auto;
}
.system-card-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 8px;
}
.system-card-name { font-weight: 600; }
.system-card-meta {
color: #8c8c8c;
font-size: 10px;
margin-top: 3px;
word-break: break-word;
}
.font-status {
flex-shrink: 0;
border-radius: 999px;
padding: 2px 6px;
font-size: 9px;
}
.font-status.available { background: #dcfce7; color: #166534; }
.font-status.missing { background: #fee2e2; color: #991b1b; }
.font-status.unknown { background: #f3f4f6; color: #6b7280; }
.design-export-row {
display: flex;
gap: 6px;
margin: 10px 0 6px;
}
.design-export-row select {
flex: 1;
padding: 6px 8px;
border: 1px solid #e6e6e6;
border-radius: 6px;
background: #fff;
color: inherit;
font-size: 11px;
}
@media (prefers-color-scheme: dark) {
body { background: #2c2c2c; color: #eaeaea; }
.tabs { border-bottom-color: #444; }
.tab { color: #9a9a9a; }
.subtabs { border-bottom-color: #444; }
.subtab { color: #9a9a9a; }
pre.code-block { background: #1e1e1e; border-color: #444; color: #eaeaea; }
.select-row { border-bottom-color: #444; }
.select-row select { background: #1e1e1e; border-color: #444; color: #eaeaea; }
.warning { background: #3a2e12; color: #f0c060; border-color: #5a4720; }
.status-ok { color: #4ade80; }
.status-error { color: #ff8f85; }
.preview-figma-img { border-color: #444; }
.preview-iframe-wrap { border-color: #444; }
.debug-send-row { border-bottom-color: #444; }
.system-stat, .system-card, .design-export-row select { border-color: #444; }
.design-export-row select { background: #1e1e1e; }
.font-status.available { background: #173b24; color: #86efac; }
.font-status.missing { background: #451a1a; color: #fca5a5; }
.font-status.unknown { background: #374151; color: #d1d5db; }
}
</style>
<div class="tabs">
<button class="tab active" data-tab="css">CSS</button>
<button class="tab" data-tab="flutter">Flutter</button>
<button class="tab" data-tab="html">HTML</button>
<button class="tab" data-tab="design">Design System</button>
<button class="tab" data-tab="preview">Preview</button>
<button class="tab" data-tab="prototype">Prototype</button>
<button class="tab" data-tab="settings">Settings</button>
</div>
<!-- Only shown for a multi-selection: CSS/Flutter/HTML/Preview are per-layer, so
the picker chooses which one those tabs are showing. The Design System tab
always covers the whole selection. -->
<div id="selection-row" class="select-row" style="display:none;">
<select id="node-select"></select>
<span id="selection-note" class="hint" style="margin:0;"></span>
</div>
<!-- Second, opt-in output alongside the fixed-pixel one above — never
replaces it. Only affects CSS/Flutter/HTML text; Preview always shows the
fixed-pixel render since it's compared against a fixed-size Figma export. -->
<div id="responsive-row" class="select-row" style="display:none;">
<label class="responsive-toggle">
<input type="checkbox" id="responsive-toggle" />
Responsive (fluid)
</label>
<span class="hint" style="margin:0;">Uses Figma's own Fill/Hug/Constraints — not a guessed breakpoint.</span>
</div>
<div id="asset-mode-row" class="select-row" style="display:none;">
<label class="responsive-toggle">
<input type="checkbox" id="exclude-base64-toggle" />
External image paths
</label>
<span class="hint" style="margin:0;">Keeps Base64 out of copied code; download the image files before using it.</span>
</div>
<!-- Fixed-geometry-only opt-in — see inlineSvgHtml in code.js. Ignored while
Responsive is on, since that variant was never computed for it. -->
<div id="inline-svg-row" class="select-row" style="display:none;">
<label class="responsive-toggle">
<input type="checkbox" id="inline-svg-toggle" />
Inline SVG icons
</label>
<span class="hint" style="margin:0;">
Flattened vector icons become real, inspectable <svg> markup instead of a background image.
</span>
</div>
<div id="empty-state" class="empty-state">Select an element on the canvas to inspect it.</div>
<div id="panels" style="display:none">
<div class="panel active" id="panel-css">
<div class="node-name" id="css-node-name"></div>
<div class="hint">Full node tree — one CSS rule per generated parent and child element.</div>
<div id="css-warnings"></div>
<pre class="code-block" id="css-output"></pre>
<button class="copy-btn" data-copy="css-output">Copy CSS</button>
</div>
<div class="panel" id="panel-flutter">
<div class="node-name" id="flutter-node-name"></div>
<pre class="code-block" id="flutter-output"></pre>
<button class="copy-btn" data-copy="flutter-output">Copy Dart</button>
<button class="copy-btn" id="flutter-assets-btn" style="display:none;">Download images + copy code</button>
<div id="flutter-assets-hint" class="hint" style="display:none;">
Downloads each image as a real file, then copies the code above with Image.asset('assets/...') paths instead of
inline data — your browser may ask to allow multiple downloads.
</div>
<div id="flutter-pubspec-wrap" style="display:none;">
<div class="system-title">pubspec.yaml additions</div>
<pre class="code-block" id="flutter-pubspec-output"></pre>
<button class="copy-btn" data-copy="flutter-pubspec-output">Copy pubspec snippet</button>
</div>
</div>
<div class="panel" id="panel-html">
<div class="node-name" id="html-node-name"></div>
<div class="hint">Full node tree, recursively — one <div>/<p> per node plus a matching <style> block.</div>
<pre class="code-block" id="html-output"></pre>
<button class="copy-btn" data-copy="html-output">Copy HTML</button>
<button class="copy-btn" id="html-assets-btn" style="display:none;">Download images + copy code</button>
<div id="html-assets-hint" class="hint" style="display:none;">
Downloads each image as a real file, then copies the code above with assets/... paths instead of inline data —
your browser may ask to allow multiple downloads.
</div>
</div>
<div class="panel" id="panel-design">
<div class="node-name" id="design-node-name"></div>
<div class="hint">Everything selected, combined. Variables and styles are read from Figma by name; values are only inferred where a layer has none bound.</div>
<div id="design-summary" class="system-summary"></div>
<div id="design-coverage" class="hint"></div>
<div class="system-title">Figma variables</div>
<div id="design-variables" class="component-list"></div>
<div class="system-title">Figma styles</div>
<div id="design-styles" class="component-list"></div>
<div class="system-title">Components</div>
<div id="design-component-library" class="component-list"></div>
<div class="system-title">Fonts</div>
<div id="design-fonts" class="font-list"></div>
<div class="system-title">Token usage per layer</div>
<div id="design-components" class="component-list"></div>
<div class="design-export-row">
<select id="design-export-format">
<option value="css">CSS variables + tokens</option>
<option value="flutter">Flutter theme + pubspec</option>
<option value="components">Component scaffolds (Dart)</option>
<option value="json">Design tokens JSON</option>
</select>
<button class="copy-btn" data-copy="design-output">Copy</button>
</div>
<pre class="code-block" id="design-output"></pre>
</div>
<div class="panel" id="panel-preview">
<div class="node-name" id="preview-node-name"></div>
<div class="hint">Real Figma render (ground truth) vs. the generated HTML rendered live — for spotting layout drift without leaving the plugin.</div>
<div class="preview-label">Figma</div>
<div id="preview-figma-wrap" class="preview-figma-wrap">
<img id="preview-figma-img" class="preview-figma-img" />
</div>
<div id="preview-figma-missing" class="hint" style="display:none;">Preview export failed for this selection.</div>
<div class="preview-label">Generated HTML (live)</div>
<div id="preview-iframe-wrap" class="preview-iframe-wrap">
<div id="preview-render-host" class="preview-render-host"></div>
</div>
</div>
<div class="panel" id="panel-prototype">
<div class="node-name">Prototype</div>
<div class="hint">
Bundles every top-level frame in the current selection into one clickable HTML file — Navigate/Overlay
reactions become real click/hover behavior, and Smart Animate transitions tween matching layers by name.
</div>
<div id="prototype-empty" class="hint">Select 2 or more frames to build a prototype.</div>
<div id="prototype-warnings"></div>
<div id="prototype-iframe-wrap" class="preview-iframe-wrap" style="display:none;">
<div id="prototype-render-host" class="preview-render-host"></div>
</div>
<pre class="code-block" id="prototype-output" style="display:none;"></pre>
<button class="copy-btn" data-copy="prototype-output" id="prototype-copy-btn" style="display:none;">
Copy HTML
</button>
</div>
</div>
<!-- Outside #panels on purpose: unlike the per-selection tabs above, Settings
has to stay reachable with nothing selected. -->
<div class="panel" id="panel-settings">
<div class="subtabs">
<button class="subtab active" data-subtab="debug">Debug Connect</button>
<button class="subtab" data-subtab="mcp">MCP Connect</button>
</div>
<div class="subpanel active" id="subpanel-debug">
<div class="hint" style="margin-top:0;">
Streams every selection (including the exported preview PNG) to a local debug server for filing bug reports.
Off by default — see README.md for how to start <code>.debug-server/debug-server.py</code>.
</div>
<div id="debug-send-row" class="debug-send-row" style="padding:0; border-bottom:none;">
<button class="copy-btn" id="debug-connect-btn">Connect</button>
<span id="debug-send-status" class="hint" style="margin:0;">Not connected — every selection stays local until you connect.</span>
</div>
</div>
<div class="subpanel" id="subpanel-mcp">
<div class="hint" style="margin-top:0;">
Runs a local MCP server so an AI client (e.g. Claude Desktop) can pull whatever it needs from the current Figma
selection: generated CSS/HTML/Dart (fixed-pixel and responsive), design tokens, the clickable prototype bundle,
and real asset/preview PNG files written straight to disk — enough to build the whole thing, not just read it.
Requires Python 3 on your machine — off by default, and no data leaves it.
</div>
<div class="node-name" style="margin-bottom:4px;">1. Get the script</div>
<div class="hint">
Copy or download <code>mcp_server.py</code>, save it anywhere, then run once in a terminal (a virtual
environment avoids the "externally-managed-environment" error plain <code>pip install</code> hits on modern
macOS/Homebrew Python):
</div>
<pre class="code-block" id="mcp-setup-cmd">python3 -m venv venv
source venv/bin/activate
python3 -m ensurepip --upgrade
pip install mcp websockets
python3 mcp_server.py</pre>
<button class="copy-btn" data-copy="mcp-setup-cmd">Copy commands</button>
<div class="hint">
The <code>ensurepip</code> line is only needed if <code>pip install</code> errors with
<code>command not found: pip</code> (some Python builds don't bootstrap pip into a new venv automatically) —
skip it if <code>pip --version</code> already works. If <code>ensurepip</code> itself then fails too (some
Homebrew Python builds strip pip's bundled installer wheel), fall back to
<code>curl -sS https://bootstrap.pypa.io/get-pip.py -o get-pip.py && python3 get-pip.py</code> instead,
then retry <code>pip install mcp websockets</code>. Next time, just
<code>source venv/bin/activate && python3 mcp_server.py</code> — no need to reinstall. In step 3's
MCP client config, point <code>command</code> at this venv's own <code>venv/bin/python3</code>, not the
system one.
</div>
<pre class="code-block" id="mcp-server-code" style="max-height:160px;">#!/usr/bin/env python3
"""Local MCP server for the FigmaToCode plugin.
Bridges an MCP client (e.g. Claude Desktop) to whatever is currently
selected in Figma. The FigmaToCode plugin's Settings > MCP Connect panel
pushes the live selection to this process over a WebSocket; this script
re-exposes the last snapshot it received as MCP tools over stdio, and can
write real files (code, decoded image assets, the ground-truth preview PNG)
to disk — something the plugin's own browser-sandboxed UI can't do itself.
Setup:
pip install mcp websockets
python3 mcp_server.py
Then, in Figma: FigmaToCode > Settings > MCP Connect > Connect.
And point your MCP client at this script over stdio, e.g. in Claude
Desktop's claude_desktop_config.json:
"figma-to-code": {
"command": "python3",
"args": ["/absolute/path/to/mcp_server.py"]
}
"""
import asyncio
import base64
import json
import os
import tempfile
import threading
import websockets
# mcp 2.x renamed FastMCP to MCPServer (different import path, same .tool()/
# .run() shape used below) — support whichever the user's `pip install mcp`
# actually resolved to instead of pinning a version.
try:
from mcp.server.fastmcp import FastMCP as MCPServer
except ImportError:
from mcp.server.mcpserver import MCPServer
WS_PORT = 8788
# The most recent selection and whole-page-scan payloads pushed by the
# plugin's ui.html over the WebSocket below. Only one Figma tab is ever
# expected to connect at a time, so a single shared value per kind (not a
# per-connection cache) is enough.
_latest_selection = None
_latest_page_overview = None
# Opening several editor windows on this project each spawns its own
# mcp_server.py (one per MCP client instance), and every one of them tries
# to bind WS_PORT for the Figma plugin to talk to — only the first can win
# that race. Rather than have the rest crash on "address already in use",
# whichever one is left holding the port writes every payload it receives
# here; the others poll this file instead of running their own server, so
# every window's MCP tools stay populated regardless of which process the
# plugin actually connects to. Local temp dir only, single-user trust model
# — same as the "only ever accepts connections from localhost" bridge below.
_SHARED_STATE_PATH = os.path.join(tempfile.gettempdir(), "figma-to-code-mcp-bridge-state.json")
_LEADER_RETRY_SECONDS = 5
async def _handle_plugin_connection(websocket):
global _latest_selection, _latest_page_overview
async for message in websocket:
try:
payload = json.loads(message)
except ValueError:
continue
if payload.get("type") == "pageOverview":
_latest_page_overview = payload
else:
_latest_selection = payload
_write_shared_state()
def _write_shared_state():
# Only ever called from the single process that currently holds
# WS_PORT, so a plain write-then-replace (no locking) is enough; the
# temp suffix plus os.replace keeps a concurrent reader from ever
# seeing a half-written file.
tmp_path = f"{_SHARED_STATE_PATH}.tmp-{os.getpid()}"
with open(tmp_path, "w") as f:
json.dump({"selection": _latest_selection, "pageOverview": _latest_page_overview}, f)
os.replace(tmp_path, _SHARED_STATE_PATH)
def _read_shared_state():
global _latest_selection, _latest_page_overview
try:
with open(_SHARED_STATE_PATH) as f:
state = json.load(f)
except (OSError, ValueError):
return
if state.get("selection") is not None:
_latest_selection = state["selection"]
if state.get("pageOverview") is not None:
_latest_page_overview = state["pageOverview"]
def _run_websocket_bridge():
# Own event loop in a background thread so it never blocks the MCP
# server's stdio event loop started from __main__ below.
async def main():
while True:
try:
# websockets' 1 MiB default max_size drops any selection whose
# payload (preview PNG + per-node CSS/HTML/Dart + image assets,
# all base64) runs bigger than that — trivially easy with just
# a couple of image-heavy layers selected. Unbounded is fine
# here: this only ever accepts connections from localhost.
async with websockets.serve(_handle_plugin_connection, "localhost", WS_PORT, max_size=None):
# Winning the bind makes this process the leader for as
# long as it stays alive.
await asyncio.Future()
except OSError:
# A sibling mcp_server.py (another open window) already owns
# WS_PORT. Don't crash — fall back to polling its shared
# state so this process's tools stay populated, and keep
# retrying the bind in case that sibling exits, so leadership
# (and direct plugin data) fails over automatically.
_read_shared_state()
await asyncio.sleep(_LEADER_RETRY_SECONDS)
asyncio.run(main())
# Read by the MCP client as up-front, standing context for this whole
# server — unlike a tool docstring, which the client only sees once it has
# already decided to call that tool. Without this, a client with no other
# signal tends to fall back to asking the user for a screenshot or a written
# description instead of calling these tools, even though the *exact* code,
# layout data, and real assets are one tool call away.
INSTRUCTIONS = """\
This server gives you the live selection from a Figma plugin (FigmaToCode) — \
real generated code, design tokens, and image assets, not a picture to \
reverse-engineer. If you're about to ask the user for a screenshot, a design \
description, or "what should this look like" — stop and call \
list_selected_nodes() first. If it returns nodes, use this server instead of \
guessing.
Planning across a whole app (multiple screens), not just one selection: \
call list_page_screens() first. It's the closest thing to a screenshot of \
the whole file without pulling one — every top-level frame's name, position \
and size, grouped by Figma Section where the designer used one (a \
Section's name is usually the flow/feature it groups, e.g. "Onboarding" or \
"Checkout"). Use it to decide what exists, how screens relate spatially, \
and what order to tackle them in, before following the per-selection \
workflow below for whichever one you pick. Unlike the selection tools, this \
requires the user to have clicked Settings > MCP Connect > Scan page at \
least once — it isn't sent automatically, since it exposes the file's whole \
structure rather than just what's selected.
Standard workflow:
1. list_selected_nodes() — see what's selected, by index.
2. get_node_metadata(index) — width/height/warnings. Compare width/height \
against common device viewports (e.g. ~375-430 wide, ~700-930 tall) to tell \
a full-screen layout from an isolated component/card — a node sized like a \
phone screen should become the screen's root container, not something \
nested inside one.
3. get_design_tokens() / get_design_export(format) — pull real colors, \
type scale, and spacing before inventing any values of your own.
4. export_node(index, output_dir, output) or export_selection(output_dir, \
output) — write ready-to-use code plus a real assets/ folder (images \
already rewritten to real file paths, never left as inline base64) and a \
preview.png. Prefer this over get_node_code when you're actually building \
something, not just inspecting. get_selection_code(indices, output) is the \
lighter-weight option for inspecting several layers at once without writing \
files — it still strips inline base64 to an assets/ placeholder path, so it \
stays safe to use even with a small context window.
5. get_prototype_html() — when 2+ frames were selected together, this is \
the ground truth for navigation between screens (which reactions/links go \
where) — use it instead of guessing screen flow, and to see which layers \
Figma's own prototype keeps fixed across screens (a strong signal for a \
persistent bottom navigation bar or header).
Things Figma's fixed-pixel export does NOT encode, so infer them instead of \
copying pixels blindly:
- Scrolling: nothing marks a layer as scrollable. A tall stack of content \
inside a phone-sized frame almost always means the frame's body scrolls \
and any nav bar / tab bar pinned to the same edge across every screen in \
get_prototype_html should stay fixed (position: sticky/fixed) instead of \
scrolling with it.
- Full-bleed vs. centered: a node whose width/height matches a device \
viewport should fill the screen (100vw/100dvh or equivalent); don't leave \
it boxed in a fixed-pixel container sized to the Figma frame.
- Responsive: request output="responsive_css"/"responsive_html"/\
"responsive_dart" from get_node_code (or export_node/export_selection with \
a *_dart output for Flutter) for a fluid, Fill/Hug/Constraints-based layout \
instead of the fixed-pixel default — use this whenever the target is a real \
app/site meant to run at more than one exact size, not a pixel-perfect \
match of the Figma canvas.
The rule for everything visual — theme, color, type, spacing, reusable \
components, assets — is: it comes from Figma via these tools, always, on \
both web and mobile. Never invent a color/font-size/spacing value, and \
never hand-roll a component Figma already defines once and reuses. \
Everything else (business logic, state, data fetching, routing beyond what \
get_prototype_html encodes, backend integration) is normal engineering \
judgment — this server has no opinion on it.
Theme, once, shared by every platform you're building for:
- Call get_design_tokens() and get_design_export() for the *whole* \
selection before writing any component, not per-node — a theme built once \
and imported everywhere keeps web and mobile visually identical, instead of \
each screen/component silently drifting from the last.
- get_design_export(format="css") → CSS custom properties, for a web \
target (or feed those values into your own Tailwind config / styled-\
components theme / CSS-in-JS tokens object — same values, whichever your \
stack uses). get_design_export(format="flutter") → a ThemeData + pubspec \
font snippet, for a Flutter/mobile target. Same underlying tokens, just two \
renderings — use both if you're building both platforms from one selection.
- Afterwards, every hex color, font-size, and spacing value in the code you \
write should trace back to one of these tokens (a CSS var / Theme property \
/ Dart constant) — not a bare literal typed by hand. If a value doesn't \
appear in get_design_tokens() at all, that's a real signal it's a one-off \
override, not a token — keep it inline rather than inventing a fake token \
for it.
Reusable components:
- get_design_tokens()["componentLibrary"] lists every Figma component used \
in the selection with a usageCount. usageCount > 1 means: build it once (a \
React/Vue/web component, a Flutter widget — whatever your stack's reuse \
unit is) and reuse it everywhere it appears, instead of copy-pasting the \
markup/widget tree at each occurrence.
- get_design_export(format="components") returns ready-made Dart widget \
scaffolds for that same component library — a starting point for the \
Flutter side; port the same componentization to whatever you're building \
for web instead of re-deriving it from scratch.
Assets, on every platform: always go through export_node/export_selection \
(never ship get_node_code's raw output as-is if it contains images) so \
every image lands as a real file under assets/ with the code already \
pointing at it — never inline base64 in anything you actually ship.
Verify before calling it done, every time:
1. Compare your result against the ground-truth render: export_node/\
export_selection already writes preview.png; open it (or save_preview_image \
for a single layer) and check your generated UI actually matches it — \
layout, spacing, colors — not just "looks plausible".
2. Re-check for stray hardcoded values: grep the code you wrote for hex \
colors / raw px-or-pt sizes that aren't one of get_design_tokens()'s \
values — anything left over either belongs in the theme or is a genuine \
one-off, decide which, don't leave it unexamined.
3. Confirm no leftover inline base64 made it into shipped code — only \
export_node/export_selection's rewritten output, never get_node_code's raw \
html/dart, should end up in a component that uses images.
4. Re-read get_node_metadata(index).warnings for every node you used and \
either address what they flag (a flattened layer, a missing font, etc.) or \
consciously decide it doesn't matter here — don't silently drop them.
"""
mcp = MCPServer("figma-to-code", instructions=INSTRUCTIONS)
def _selection_or_raise():
if not _latest_selection or not _latest_selection.get("nodes"):
raise ValueError(
"No selection available yet. In Figma, open the FigmaToCode plugin, "
"select a layer, and toggle Settings > MCP Connect > Connect."
)
return _latest_selection
def _node_or_raise(index: int) -> dict:
nodes = _selection_or_raise()["nodes"]
if index < 0 or index >= len(nodes):
raise ValueError(f"index {index} out of range: selection has {len(nodes)} node(s)")
return nodes[index]
# code/output keys, by the `output` string a caller passes in.
_CODE_FIELDS = {
"css": lambda n: "\n".join(f"{key}: {value};" for key, value in n["css"].items()),
"html": lambda n: n["html"],
"dart": lambda n: n["dart"],
"inline_svg_html": lambda n: n["inlineSvgHtml"],
"responsive_css": lambda n: "\n".join(f"{key}: {value};" for key, value in n["responsive"]["css"].items()),
"responsive_html": lambda n: n["responsive"]["html"],
"responsive_dart": lambda n: n["responsive"]["dart"],
}
# Per-output asset lists and the file extension code should be saved under.
_ASSET_FIELDS = {"html": "htmlAssets", "inline_svg_html": "htmlAssets", "dart": "dartAssets"}
_FILE_EXT = {
"css": "css",
"html": "html",
"dart": "dart",
"inline_svg_html": "html",
"responsive_css": "css",
"responsive_html": "html",
"responsive_dart": "dart",
}
def _safe_dir(output_dir: str) -> str:
path = os.path.abspath(os.path.expanduser(output_dir))
os.makedirs(path, exist_ok=True)
return path
def _get_assets(node: dict, output: str) -> list:
key = _ASSET_FIELDS.get(output)
return node.get(key, []) if key else []
def _write_assets(assets: list, assets_dir: str) -> list:
if not assets:
return []
os.makedirs(assets_dir, exist_ok=True)
written = []
for asset in assets:
# basename() strips any accidental path segments out of a filename
# that ultimately came from a Figma layer name.
filename = os.path.basename(asset["filename"])
file_path = os.path.join(assets_dir, filename)
with open(file_path, "wb") as f:
f.write(base64.b64decode(asset["base64"]))
written.append(file_path)
return written
# Mirrors rewriteHtmlWithAssetPaths/rewriteDartWithAssetPaths in ui.html
# exactly, so code exported here matches what the plugin's own "Download
# images + copy code" button produces — real files, not inline base64. The
# data URI (or, for Dart, the whole Image.memory/MemoryImage call) is unique
# per asset, so a literal string replace is exact and needs no regex.
def _rewrite_html_with_asset_paths(html: str, assets: list) -> str:
result = html
for asset in assets:
result = result.replace(asset["dataUri"], f"assets/{asset['filename']}")
return result
def _rewrite_dart_with_asset_paths(dart: str, assets: list) -> str:
result = dart
for asset in assets:
if asset.get("fillOnly"):
old_provider = f"MemoryImage(base64Decode('{asset['base64']}'))"
new_provider = f"AssetImage('assets/{asset['filename']}')"
result = result.replace(old_provider, new_provider)
continue
old_call = (
f"Image.memory(base64Decode('{asset['base64']}'), width: {asset['width']}, "
f"height: {asset['height']}, fit: BoxFit.fill, gaplessPlayback: true)"
)
new_call = (
f"Image.asset('assets/{asset['filename']}', width: {asset['width']}, "
f"height: {asset['height']}, fit: BoxFit.fill)"
)
result = result.replace(old_call, new_call)
if "base64Decode(" not in result:
result = result.replace("import 'dart:convert';\n", "")
return result
def _rewrite_code_with_asset_paths(code: str, output: str, assets: list) -> str:
if output == "dart":
return _rewrite_dart_with_asset_paths(code, assets)
return _rewrite_html_with_asset_paths(code, assets)
@mcp.tool()
def list_page_screens() -> dict:
"""Return a lightweight map of every top-level frame on the current
Figma page, grouped by Figma Section where the designer used one — name,
position (x/y), size (width/height), and visibility only, no generated
code. Use this before diving into any one screen, to see how many
screens the whole app has, which ones are grouped together (a Section's
name is usually the flow/feature it groups), and how they're laid out on
the canvas. Requires the user to have clicked Settings > MCP Connect >
Scan page at least once — it isn't pushed automatically like the
selection is, since it exposes the file's whole structure rather than
just what's selected."""
if not _latest_page_overview:
raise ValueError(
"No page overview yet. In Figma, open the FigmaToCode plugin and "
"click Settings > MCP Connect > Scan page."
)
return {
"pageName": _latest_page_overview["pageName"],
"sections": _latest_page_overview["sections"],
"ungroupedScreens": _latest_page_overview["ungroupedScreens"],
}
@mcp.tool()
def list_selected_nodes() -> list:
"""List every currently-selected layer's index, name, and type. Call this
first to see what's selected before calling other tools by index."""
selection = _selection_or_raise()
return [
{"index": i, "name": node["nodeName"], "type": node["nodeType"]}
for i, node in enumerate(selection["nodes"])
]
@mcp.tool()
def get_node_metadata(index: int = 0) -> dict:
"""Return a selected layer's size and any generation warnings, without the
full generated code — use this to reason about layout before pulling code."""
node = _node_or_raise(index)
return {
"nodeId": node["nodeId"],
"nodeName": node["nodeName"],
"nodeType": node["nodeType"],
"width": node["width"],
"height": node["height"],
"warnings": node["warnings"],
}
@mcp.tool()
def get_node_code(index: int = 0, output: str = "css") -> str:
"""Return generated code for one selected layer. `output` is one of: css,
html, dart, inline_svg_html, responsive_css, responsive_html,
responsive_dart. `index` picks which selected layer (see
list_selected_nodes). The non-responsive variants match the fixed-pixel
size captured from Figma; the responsive_* variants are the fluid,
Fill/Hug/Constraints-based layout instead."""
node = _node_or_raise(index)
getter = _CODE_FIELDS.get(output)
if getter is None:
raise ValueError(f"output must be one of: {', '.join(_CODE_FIELDS)}")
return getter(node)
@mcp.tool()
def get_selection_code(indices: list = None, output: str = "html") -> list:
"""Return generated code for several (or, by default, all) selected
layers in one call, with any image assets replaced by an
`assets/<filename>` placeholder path instead of inline base64 — safe to
use with a low-context client, unlike raw get_node_code on an
image-heavy selection. Each result also lists the assets that code
references (filename + mimeType, no bytes); fetch the real files
afterward with export_node_assets or export_node if you need them.
`output` accepts the same values as get_node_code. `indices` (default:
every selected node) picks which layers to include — see
list_selected_nodes."""
nodes = _selection_or_raise()["nodes"]
if indices is None:
indices = list(range(len(nodes)))
if output not in _CODE_FIELDS:
raise ValueError(f"output must be one of: {', '.join(_CODE_FIELDS)}")
getter = _CODE_FIELDS[output]
# Responsive variants reuse the same top-level asset lists as their
# fixed-pixel counterpart — ui.html's own copy/download buttons do the
# same lookup (see rewriteHtmlWithAssetPaths call sites).
asset_key = _ASSET_FIELDS.get(output.replace("responsive_", "", 1))
results = []
for i in indices:
node = _node_or_raise(i)
code = getter(node)
assets = node.get(asset_key, []) if asset_key else []
if assets:
code = _rewrite_code_with_asset_paths(code, "dart" if "dart" in output else "html", assets)
results.append({
"index": i,
"name": node["nodeName"],
"code": code,
"assets": [{"filename": a["filename"], "mimeType": a["mimeType"]} for a in assets],
})
return results
@mcp.tool()
def list_node_assets(index: int = 0, output: str = "html") -> list:
"""List the image assets a selected layer's generated code references
(filename + MIME type, no image bytes) — use export_node_assets to
actually save them as files."""
node = _node_or_raise(index)
key = _ASSET_FIELDS.get(output)
if key is None:
raise ValueError(f"output must be one of: {', '.join(sorted(set(_ASSET_FIELDS)))}")
return [{"filename": a["filename"], "mimeType": a["mimeType"]} for a in node.get(key, [])]
@mcp.tool()
def export_node_assets(index: int, output_dir: str, output: str = "html") -> list:
"""Decode a selected layer's image assets and write them as real files
under output_dir (created if missing). Returns the absolute paths written."""
node = _node_or_raise(index)
return _write_assets(_get_assets(node, output), _safe_dir(output_dir))
@mcp.tool()
def export_node(index: int, output_dir: str, output: str = "html") -> dict:
"""Export one selected layer as a ready-to-use folder under output_dir:
a code file (html or dart) with every image it uses already rewritten to
point at real files in an assets/ subfolder — not left as inline base64 —
plus preview.png, the ground-truth Figma render. Use this for "pull this
one component, images and all" requests; use export_selection instead for
the whole current selection at once."""
node = _node_or_raise(index)
if output not in ("html", "dart"):
raise ValueError("output must be 'html' or 'dart'")
node_dir = _safe_dir(output_dir)
assets = _get_assets(node, output)
code = _rewrite_code_with_asset_paths(node[output], output, assets)
code_path = os.path.join(node_dir, f"code.{_FILE_EXT[output]}")
with open(code_path, "w") as f:
f.write(code)
written_assets = _write_assets(assets, os.path.join(node_dir, "assets"))
preview_path = None
if node.get("previewImage"):
_, _, b64 = node["previewImage"].partition(",")
preview_path = os.path.join(node_dir, "preview.png")
with open(preview_path, "wb") as f:
f.write(base64.b64decode(b64))
return {"code": code_path, "assets": written_assets, "preview": preview_path}
@mcp.tool()
def save_preview_image(index: int, output_dir: str, filename: str = "preview.png") -> str:
"""Save the ground-truth Figma render (the same PNG the plugin's Preview
tab compares generated code against) for a selected layer to output_dir.
Returns the absolute path written."""
node = _node_or_raise(index)
uri = node.get("previewImage")
if not uri:
raise ValueError("This node has no preview image (export may have failed).")
_, _, b64 = uri.partition(",")
path = os.path.join(_safe_dir(output_dir), os.path.basename(filename))
with open(path, "wb") as f:
f.write(base64.b64decode(b64))
return path
@mcp.tool()
def get_design_tokens() -> dict:
"""Return the raw design system collected from the current selection:
Figma variables, styles, colors, gradients, typography, radii, shadows,
spacing, fonts, and the component library — everything needed to build a
consistent theme, not just one layer's code."""
selection = _selection_or_raise()
ds = selection["designSystem"]
return {k: v for k, v in ds.items() if k != "exports"}
@mcp.tool()