@muloka/figma-console-mcp 0.5.7 → 0.6.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.
Files changed (116) hide show
  1. package/README.md +120 -848
  2. package/dist/apps/design-system-dashboard/mcp-app.html +107 -94
  3. package/dist/apps/design-system-dashboard/server.d.ts +1 -1
  4. package/dist/apps/design-system-dashboard/server.d.ts.map +1 -1
  5. package/dist/apps/token-browser/mcp-app.html +95 -82
  6. package/dist/apps/token-browser/server.d.ts +1 -1
  7. package/dist/apps/token-browser/server.d.ts.map +1 -1
  8. package/dist/core/accessibility-tools.d.ts +1 -1
  9. package/dist/core/accessibility-tools.d.ts.map +1 -1
  10. package/dist/core/accessibility-tools.js +18 -15
  11. package/dist/core/accessibility-tools.js.map +1 -1
  12. package/dist/core/annotation-tools.d.ts +1 -1
  13. package/dist/core/annotation-tools.d.ts.map +1 -1
  14. package/dist/core/annotation-tools.js +35 -26
  15. package/dist/core/annotation-tools.js.map +1 -1
  16. package/dist/core/comment-tools.d.ts +2 -2
  17. package/dist/core/comment-tools.d.ts.map +1 -1
  18. package/dist/core/comment-tools.js +60 -51
  19. package/dist/core/comment-tools.js.map +1 -1
  20. package/dist/core/config.d.ts.map +1 -1
  21. package/dist/core/config.js +2 -17
  22. package/dist/core/config.js.map +1 -1
  23. package/dist/core/console-monitor.d.ts +1 -1
  24. package/dist/core/console-monitor.d.ts.map +1 -1
  25. package/dist/core/console-monitor.js +2 -2
  26. package/dist/core/console-monitor.js.map +1 -1
  27. package/dist/core/deep-component-tools.d.ts +1 -1
  28. package/dist/core/deep-component-tools.d.ts.map +1 -1
  29. package/dist/core/deep-component-tools.js +15 -9
  30. package/dist/core/deep-component-tools.js.map +1 -1
  31. package/dist/core/design-code-tools.d.ts +1 -1
  32. package/dist/core/design-code-tools.d.ts.map +1 -1
  33. package/dist/core/design-code-tools.js +53 -47
  34. package/dist/core/design-code-tools.js.map +1 -1
  35. package/dist/core/design-system-manifest.d.ts +37 -2
  36. package/dist/core/design-system-manifest.d.ts.map +1 -1
  37. package/dist/core/design-system-manifest.js +85 -0
  38. package/dist/core/design-system-manifest.js.map +1 -1
  39. package/dist/core/design-system-tools.d.ts +1 -1
  40. package/dist/core/design-system-tools.d.ts.map +1 -1
  41. package/dist/core/design-system-tools.js +39 -36
  42. package/dist/core/design-system-tools.js.map +1 -1
  43. package/dist/core/diagnose-tool.d.ts +8 -4
  44. package/dist/core/diagnose-tool.d.ts.map +1 -1
  45. package/dist/core/diagnose-tool.js +18 -15
  46. package/dist/core/diagnose-tool.js.map +1 -1
  47. package/dist/core/figjam-tools.d.ts +2 -2
  48. package/dist/core/figjam-tools.d.ts.map +1 -1
  49. package/dist/core/figjam-tools.js +159 -129
  50. package/dist/core/figjam-tools.js.map +1 -1
  51. package/dist/core/figma-connector.d.ts +14 -3
  52. package/dist/core/figma-connector.d.ts.map +1 -1
  53. package/dist/core/figma-tools.d.ts +1 -1
  54. package/dist/core/figma-tools.d.ts.map +1 -1
  55. package/dist/core/figma-tools.js +284 -267
  56. package/dist/core/figma-tools.js.map +1 -1
  57. package/dist/core/identity.d.ts +49 -9
  58. package/dist/core/identity.d.ts.map +1 -1
  59. package/dist/core/identity.js +137 -28
  60. package/dist/core/identity.js.map +1 -1
  61. package/dist/core/library-tools.d.ts +1 -1
  62. package/dist/core/library-tools.d.ts.map +1 -1
  63. package/dist/core/library-tools.js +45 -36
  64. package/dist/core/library-tools.js.map +1 -1
  65. package/dist/core/logger.d.ts +0 -1
  66. package/dist/core/logger.d.ts.map +1 -1
  67. package/dist/core/logger.js +1 -13
  68. package/dist/core/logger.js.map +1 -1
  69. package/dist/core/slides-tools.d.ts +2 -2
  70. package/dist/core/slides-tools.d.ts.map +1 -1
  71. package/dist/core/slides-tools.js +223 -172
  72. package/dist/core/slides-tools.js.map +1 -1
  73. package/dist/core/slot-tools.d.ts +1 -1
  74. package/dist/core/slot-tools.d.ts.map +1 -1
  75. package/dist/core/slot-tools.js +101 -86
  76. package/dist/core/slot-tools.js.map +1 -1
  77. package/dist/core/tokens/config.d.ts +88 -266
  78. package/dist/core/tokens/config.d.ts.map +1 -1
  79. package/dist/core/tokens/config.js +2 -3
  80. package/dist/core/tokens/config.js.map +1 -1
  81. package/dist/core/tokens/schemas.d.ts +104 -113
  82. package/dist/core/tokens/schemas.d.ts.map +1 -1
  83. package/dist/core/tokens/schemas.js +2 -2
  84. package/dist/core/tokens/schemas.js.map +1 -1
  85. package/dist/core/tokens-tools.d.ts +5 -3
  86. package/dist/core/tokens-tools.d.ts.map +1 -1
  87. package/dist/core/tokens-tools.js +13 -10
  88. package/dist/core/tokens-tools.js.map +1 -1
  89. package/dist/core/types/index.d.ts +1 -1
  90. package/dist/core/types/index.d.ts.map +1 -1
  91. package/dist/core/variable-resolver.d.ts +3 -3
  92. package/dist/core/variable-resolver.d.ts.map +1 -1
  93. package/dist/core/variable-resolver.js +6 -9
  94. package/dist/core/variable-resolver.js.map +1 -1
  95. package/dist/core/version-tools.d.ts +4 -4
  96. package/dist/core/version-tools.d.ts.map +1 -1
  97. package/dist/core/version-tools.js +162 -144
  98. package/dist/core/version-tools.js.map +1 -1
  99. package/dist/core/websocket-connector.d.ts +4 -7
  100. package/dist/core/websocket-connector.d.ts.map +1 -1
  101. package/dist/core/websocket-connector.js +28 -39
  102. package/dist/core/websocket-connector.js.map +1 -1
  103. package/dist/core/websocket-server.d.ts +36 -2
  104. package/dist/core/websocket-server.d.ts.map +1 -1
  105. package/dist/core/websocket-server.js +69 -8
  106. package/dist/core/websocket-server.js.map +1 -1
  107. package/dist/core/write-tools.d.ts +2 -2
  108. package/dist/core/write-tools.d.ts.map +1 -1
  109. package/dist/core/write-tools.js +564 -471
  110. package/dist/core/write-tools.js.map +1 -1
  111. package/dist/local.d.ts +8 -1
  112. package/dist/local.d.ts.map +1 -1
  113. package/dist/local.js +390 -302
  114. package/dist/local.js.map +1 -1
  115. package/figma-desktop-bridge/code.js +23 -2
  116. package/package.json +11 -19
package/dist/local.js CHANGED
@@ -12,9 +12,9 @@
12
12
  * - Desktop Bridge plugin open in Figma (Plugins → Development → Figma Desktop Bridge)
13
13
  * - FIGMA_ACCESS_TOKEN environment variable for API access
14
14
  */
15
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
16
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
17
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
15
+ import { createMcpHandler, isLegacyRequest, McpServer } from "@modelcontextprotocol/server";
16
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
17
+ import { NodeStreamableHTTPServerTransport, toNodeHandler, toWebRequest } from "@modelcontextprotocol/node";
18
18
  import { createServer } from "node:http";
19
19
  import { guardLocalHttpRequest } from "./core/http-request-guard.js";
20
20
  import { z } from "zod";
@@ -37,10 +37,11 @@ import { registerAccessibilityTools } from "./core/accessibility-tools.js";
37
37
  import { registerDiagnoseTool } from "./core/diagnose-tool.js";
38
38
  import { registerWriteTools } from "./core/write-tools.js";
39
39
  import { registerTokensTools } from "./core/tokens-tools.js";
40
- import { wrapServerForIdentity } from "./core/identity.js";
40
+ import { withToolIdentity } from "./core/identity.js";
41
41
  import { PACKAGE_ROOT } from "./core/resolve-package-root.js";
42
- import { FigmaWebSocketServer, getBundledPluginVersion, heldPinStatusWarning, } from "./core/websocket-server.js";
42
+ import { FigmaWebSocketServer, getBundledPluginVersion, getBundledForkPluginRevision, heldPinStatusWarning, } from "./core/websocket-server.js";
43
43
  import { WebSocketConnector } from "./core/websocket-connector.js";
44
+ import { invalidateAfterVariableWrite } from "./core/design-system-manifest.js";
44
45
  import { DEFAULT_WS_PORT, getPortRange, advertisePort, unadvertisePort, registerPortCleanup, startPeriodicReaper, discoverActiveInstances, cleanupStalePortFiles, cleanupOrphanedProcesses, evictOldestInstance, refreshPortAdvertisement, setAdvertisedMcpHttpPort, HEARTBEAT_INTERVAL_MS, } from "./core/port-discovery.js";
45
46
  import { registerTokenBrowserApp } from "./apps/token-browser/server.js";
46
47
  import { registerDesignSystemDashboardApp } from "./apps/design-system-dashboard/server.js";
@@ -48,6 +49,43 @@ import { registerFigJamTools } from "./core/figjam-tools.js";
48
49
  import { registerSlidesTools } from "./core/slides-tools.js";
49
50
  import { registerSlotTools } from "./core/slot-tools.js";
50
51
  const logger = createChildLogger({ component: "local-server" });
52
+ // Every McpServer this process builds (stdio and per-request HTTP) stamps tool
53
+ // responses and thrown errors with our MCP identity, so LLMs can attribute
54
+ // output unambiguously when several Figma-related MCPs are connected.
55
+ const IdentifiedMcpServer = withToolIdentity(McpServer);
56
+ /** Largest JSON-RPC body the MCP_HTTP_PORT endpoint reads (both protocol eras). */
57
+ const MAX_HTTP_BODY_BYTES = 4 * 1024 * 1024;
58
+ /** Read and parse a JSON request body, refusing oversized or malformed ones. */
59
+ function readJsonBody(req) {
60
+ return new Promise((resolve, reject) => {
61
+ const chunks = [];
62
+ let size = 0;
63
+ let tooLarge = false;
64
+ req.on("data", (chunk) => {
65
+ if (tooLarge)
66
+ return; // drain and discard the rest
67
+ size += chunk.length;
68
+ if (size > MAX_HTTP_BODY_BYTES) {
69
+ // Stop buffering, but keep reading: destroying the socket here would
70
+ // reset the connection before the 413 can be written.
71
+ tooLarge = true;
72
+ chunks.length = 0;
73
+ reject(Object.assign(new Error("Request body too large"), { status: 413, code: -32000 }));
74
+ return;
75
+ }
76
+ chunks.push(chunk);
77
+ });
78
+ req.on("end", () => {
79
+ try {
80
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
81
+ }
82
+ catch {
83
+ reject(Object.assign(new Error("Parse error: request body is not valid JSON"), { status: 400, code: -32700 }));
84
+ }
85
+ });
86
+ req.on("error", reject);
87
+ });
88
+ }
51
89
  /**
52
90
  * Copy plugin files to a stable directory (~/.figma-console-mcp/plugin/).
53
91
  * This gives users a permanent, predictable path to import from instead of
@@ -168,7 +206,7 @@ For component-specific design guidance (sizing, proportions, accessibility, etc.
168
206
  If Design Systems Assistant MCP is not available, install it from: https://github.com/southleft/design-systems-mcp`;
169
207
  /**
170
208
  * Local MCP Server
171
- * Connects to Figma Desktop and provides identical tools to Cloudflare mode
209
+ * Connects to Figma Desktop through the Desktop Bridge plugin and serves the tools over stdio (and HTTP with MCP_HTTP_PORT)
172
210
  */
173
211
  class LocalFigmaConsoleMCP {
174
212
  /**
@@ -177,10 +215,13 @@ class LocalFigmaConsoleMCP {
177
215
  * to ensure the next figma_get_variables call returns fresh data.
178
216
  */
179
217
  invalidateVariablesCache() {
180
- if (this.variablesCache.size > 0) {
181
- this.variablesCache.clear();
218
+ // Also drops every cached design-system manifest: a variable write that
219
+ // touches no node fires no documentChange, so nothing else would, and the
220
+ // summary / token-value tools would serve pre-write tokens (#14).
221
+ const hadVariables = this.variablesCache.size > 0;
222
+ invalidateAfterVariableWrite(this.variablesCache);
223
+ if (hadVariables)
182
224
  logger.info('Variables cache invalidated after write operation');
183
- }
184
225
  }
185
226
  constructor() {
186
227
  this.figmaAPI = null;
@@ -198,22 +239,20 @@ class LocalFigmaConsoleMCP {
198
239
  this.httpServer = null;
199
240
  /** The port the HTTP MCP server is listening on, if enabled */
200
241
  this.mcpHttpPort = null;
242
+ /** MCP_HTTP_PORT's 2026-07-28 leg (one fresh server per request). */
243
+ this.modernHttpHandler = null;
201
244
  this.config = getConfig();
202
245
  // In-memory cache for variables data to avoid MCP token limits
203
246
  // Maps fileKey -> {data, timestamp}
204
247
  this.variablesCache = new Map();
205
248
  /** Stable plugin directory path (set during startup) */
206
249
  this.stablePluginPath = null;
207
- this.server = new McpServer({
250
+ this.server = new IdentifiedMcpServer({
208
251
  name: "Figma Console MCP (Local)",
209
252
  version: SERVER_VERSION,
210
253
  }, {
211
254
  instructions: MCP_SERVER_INSTRUCTIONS,
212
255
  });
213
- // Stamp every tool response (and every thrown error) with our MCP identity
214
- // so LLMs can attribute output unambiguously when multiple Figma-related
215
- // MCPs are connected. Idempotent for already-tagged responses.
216
- wrapServerForIdentity(this.server);
217
256
  }
218
257
  /**
219
258
  * Get or create Figma API client
@@ -389,21 +428,24 @@ class LocalFigmaConsoleMCP {
389
428
  registerTools(target) {
390
429
  const server = target ?? this.server;
391
430
  // Tool 1: Get Console Logs
392
- server.tool("figma_get_console_logs", "Retrieve console logs from Figma Desktop. FOR PLUGIN DEVELOPERS: This works immediately - no navigation needed! Just check logs, run your plugin in Figma Desktop, check logs again. All plugin logs ([Main], [Swapper], etc.) appear instantly.", {
393
- count: z
394
- .number()
395
- .optional()
396
- .default(100)
397
- .describe("Number of recent logs to retrieve"),
398
- level: z
399
- .enum(["log", "info", "warn", "error", "debug", "all"])
400
- .optional()
401
- .default("all")
402
- .describe("Filter by log level"),
403
- since: z
404
- .number()
405
- .optional()
406
- .describe("Only logs after this timestamp (Unix ms)"),
431
+ server.registerTool("figma_get_console_logs", {
432
+ description: "Retrieve console logs from Figma Desktop. FOR PLUGIN DEVELOPERS: This works immediately - no navigation needed! Just check logs, run your plugin in Figma Desktop, check logs again. All plugin logs ([Main], [Swapper], etc.) appear instantly.",
433
+ inputSchema: z.object({
434
+ count: z
435
+ .number()
436
+ .optional()
437
+ .default(100)
438
+ .describe("Number of recent logs to retrieve"),
439
+ level: z
440
+ .enum(["log", "info", "warn", "error", "debug", "all"])
441
+ .optional()
442
+ .default("all")
443
+ .describe("Filter by log level"),
444
+ since: z
445
+ .number()
446
+ .optional()
447
+ .describe("Only logs after this timestamp (Unix ms)"),
448
+ }),
407
449
  }, async ({ count, level, since }) => {
408
450
  try {
409
451
  // Try console monitor first, fall back to WebSocket console buffer
@@ -482,23 +524,26 @@ class LocalFigmaConsoleMCP {
482
524
  // Bridge-first: the plugin's exportAsync works on any Figma plan with no REST
483
525
  // token, and reflects the current runtime state (no cloud-sync lag).
484
526
  // Note: For screenshots of specific components, use figma_get_component_image instead
485
- server.tool("figma_take_screenshot", `Export an image of the current Figma page or specific node. Uses the Desktop Bridge plugin (exportAsync) when connected — works on any plan, no REST token needed, reflects current runtime state. Falls back to the Figma REST API when the bridge is unavailable or for PDF format. Use for visual validation after design changes — check alignment, spacing, proportions. Pass nodeId to target specific elements. For components, prefer figma_get_component_image.`, {
486
- nodeId: z
487
- .string()
488
- .optional()
489
- .describe("Optional node ID to screenshot (e.g., '123:456'). If omitted, uses the node-id from the Desktop Bridge plugin's reported file URL when present. To screenshot what the user is currently looking at on the canvas, prefer figma_capture_screenshot (uses the plugin's exportAsync and reflects the current state)."),
490
- scale: z
491
- .number()
492
- .min(0.01)
493
- .max(4)
494
- .optional()
495
- .default(2)
496
- .describe("Image scale factor (0.01-4, default: 2 for high quality)"),
497
- format: z
498
- .enum(["png", "jpg", "svg", "pdf"])
499
- .optional()
500
- .default("png")
501
- .describe("Image format (default: png)"),
527
+ server.registerTool("figma_take_screenshot", {
528
+ description: `Export an image of the current Figma page or specific node. Uses the Desktop Bridge plugin (exportAsync) when connected — works on any plan, no REST token needed, reflects current runtime state. Falls back to the Figma REST API when the bridge is unavailable or for PDF format. Use for visual validation after design changes — check alignment, spacing, proportions. Pass nodeId to target specific elements. For components, prefer figma_get_component_image.`,
529
+ inputSchema: z.object({
530
+ nodeId: z
531
+ .string()
532
+ .optional()
533
+ .describe("Optional node ID to screenshot (e.g., '123:456'). If omitted, uses the node-id from the Desktop Bridge plugin's reported file URL when present. To screenshot what the user is currently looking at on the canvas, prefer figma_capture_screenshot (uses the plugin's exportAsync and reflects the current state)."),
534
+ scale: z
535
+ .number()
536
+ .min(0.01)
537
+ .max(4)
538
+ .optional()
539
+ .default(2)
540
+ .describe("Image scale factor (0.01-4, default: 2 for high quality)"),
541
+ format: z
542
+ .enum(["png", "jpg", "svg", "pdf"])
543
+ .optional()
544
+ .default("png")
545
+ .describe("Image format (default: png)"),
546
+ }),
502
547
  }, async ({ nodeId, scale, format }) => {
503
548
  // Callers routinely paste URL-format ids (123-456); both the Plugin
504
549
  // API and REST response maps use colon format (123:456).
@@ -667,17 +712,20 @@ class LocalFigmaConsoleMCP {
667
712
  }
668
713
  });
669
714
  // Tool 3: Watch Console (Real-time streaming)
670
- server.tool("figma_watch_console", "Stream console logs in real-time for a specified duration (max 5 minutes). Use for monitoring plugin execution while user tests manually. Returns all logs captured during watch period with summary statistics. NOT for retrieving past logs (use figma_get_console_logs). Best for: watching plugin output during manual testing, debugging race conditions, monitoring async operations.", {
671
- duration: z
672
- .number()
673
- .optional()
674
- .default(30)
675
- .describe("How long to watch in seconds"),
676
- level: z
677
- .enum(["log", "info", "warn", "error", "debug", "all"])
678
- .optional()
679
- .default("all")
680
- .describe("Filter by log level"),
715
+ server.registerTool("figma_watch_console", {
716
+ description: "Stream console logs in real-time for a specified duration (max 5 minutes). Use for monitoring plugin execution while user tests manually. Returns all logs captured during watch period with summary statistics. NOT for retrieving past logs (use figma_get_console_logs). Best for: watching plugin output during manual testing, debugging race conditions, monitoring async operations.",
717
+ inputSchema: z.object({
718
+ duration: z
719
+ .number()
720
+ .optional()
721
+ .default(30)
722
+ .describe("How long to watch in seconds"),
723
+ level: z
724
+ .enum(["log", "info", "warn", "error", "debug", "all"])
725
+ .optional()
726
+ .default("all")
727
+ .describe("Filter by log level"),
728
+ }),
681
729
  }, async ({ duration, level }) => {
682
730
  if (!this.wsServer?.isClientConnected()) {
683
731
  throw new Error("No console monitoring available. Open the Desktop Bridge plugin in Figma for console capture.");
@@ -717,12 +765,15 @@ class LocalFigmaConsoleMCP {
717
765
  };
718
766
  });
719
767
  // Tool 4: Reload Plugin
720
- server.tool("figma_reload_plugin", "Reload the current Figma page/plugin to test code changes. Optionally clears console logs before reload. Use when user says: 'reload plugin', 'refresh page', 'restart plugin', 'test my changes'. Returns reload confirmation and current URL. Best for rapid iteration during plugin development.", {
721
- clearConsole: z
722
- .boolean()
723
- .optional()
724
- .default(true)
725
- .describe("Clear console logs before reload"),
768
+ server.registerTool("figma_reload_plugin", {
769
+ description: "Reload the current Figma page/plugin to test code changes. Optionally clears console logs before reload. Use when user says: 'reload plugin', 'refresh page', 'restart plugin', 'test my changes'. Returns reload confirmation and current URL. Best for rapid iteration during plugin development.",
770
+ inputSchema: z.object({
771
+ clearConsole: z
772
+ .boolean()
773
+ .optional()
774
+ .default(true)
775
+ .describe("Clear console logs before reload"),
776
+ }),
726
777
  }, async ({ clearConsole: clearConsoleBefore }) => {
727
778
  try {
728
779
  let transport = "websocket";
@@ -785,7 +836,10 @@ class LocalFigmaConsoleMCP {
785
836
  }
786
837
  });
787
838
  // Tool 5: Clear Console
788
- server.tool("figma_clear_console", "Clear the console log buffer. Safely clears the buffer without disrupting the connection. Returns number of logs cleared.", {}, async () => {
839
+ server.registerTool("figma_clear_console", {
840
+ description: "Clear the console log buffer. Safely clears the buffer without disrupting the connection. Returns number of logs cleared.",
841
+ inputSchema: z.object({}),
842
+ }, async () => {
789
843
  try {
790
844
  let clearedCount = 0;
791
845
  let transport = "websocket";
@@ -837,15 +891,18 @@ class LocalFigmaConsoleMCP {
837
891
  }
838
892
  });
839
893
  // Tool 6: Navigate / switch active file
840
- server.tool("figma_navigate", "Switch the active Figma file target among files that already have the Desktop Bridge plugin running. Local mode is WebSocket-only — this tool does NOT launch a browser or open files. If the requested URL is already the active file, it confirms the connection. If another connected plugin matches the URL, it switches the active target so subsequent tool calls hit that file. If no connected plugin matches, returns an error with guidance for the user to open the Desktop Bridge plugin in the target file. Use figma_list_open_files to see all connected files.\n\nPass lock: true to PIN this file as the target — new connections, reconnects, and the user's own selection/page changes in other files will no longer move the target. Use this for parallel work (agent edits one file while the user works in another) so commands can't silently route to the wrong file. If the pinned file disconnects, the pin is held (untargeted commands are refused rather than routed elsewhere) until it reconnects, you switch files, or you unlock with lock: false.", {
841
- url: z
842
- .string()
843
- .url()
844
- .describe("Figma URL to navigate to (e.g., https://www.figma.com/design/abc123)"),
845
- lock: z
846
- .boolean()
847
- .optional()
848
- .describe("Pin this file as the active target so connections, reconnects, and user interaction in other files won't move it. Defaults to false."),
894
+ server.registerTool("figma_navigate", {
895
+ description: "Switch the active Figma file target among files that already have the Desktop Bridge plugin running. Local mode is WebSocket-only — this tool does NOT launch a browser or open files. If the requested URL is already the active file, it confirms the connection. If another connected plugin matches the URL, it switches the active target so subsequent tool calls hit that file. If no connected plugin matches, returns an error with guidance for the user to open the Desktop Bridge plugin in the target file. Use figma_list_open_files to see all connected files.\n\nPass lock: true to PIN this file as the target — new connections, reconnects, and the user's own selection/page changes in other files will no longer move the target. Use this for parallel work (agent edits one file while the user works in another) so commands can't silently route to the wrong file. If the pinned file disconnects, the pin is held (untargeted commands are refused rather than routed elsewhere) until it reconnects, you switch files, or you unlock with lock: false.",
896
+ inputSchema: z.object({
897
+ url: z
898
+ .string()
899
+ .url()
900
+ .describe("Figma URL to navigate to (e.g., https://www.figma.com/design/abc123)"),
901
+ lock: z
902
+ .boolean()
903
+ .optional()
904
+ .describe("Pin this file as the active target so connections, reconnects, and user interaction in other files won't move it. Defaults to false."),
905
+ }),
849
906
  }, async ({ url, lock }) => {
850
907
  try {
851
908
  // Phase 3: local mode now talks to Figma exclusively through the
@@ -988,8 +1045,11 @@ class LocalFigmaConsoleMCP {
988
1045
  }
989
1046
  });
990
1047
  // Tool 7: Get Status (with setup validation)
991
- server.tool("figma_get_status", "Check connection status to Figma Desktop. Reports transport status and connection health via the Desktop Bridge plugin (WebSocket transport). Use probe:true for an active roundtrip verification that the plugin is actually responding.", {
992
- probe: z.boolean().optional().describe("When true, sends a live roundtrip command to the plugin to verify the connection is actually responsive (not just TCP-open). Returns probeResult with success/latency. Recommended for health checks."),
1048
+ server.registerTool("figma_get_status", {
1049
+ description: "Check connection status to Figma Desktop. Reports transport status and connection health via the Desktop Bridge plugin (WebSocket transport). Use probe:true for an active roundtrip verification that the plugin is actually responding.",
1050
+ inputSchema: z.object({
1051
+ probe: z.boolean().optional().describe("When true, sends a live roundtrip command to the plugin to verify the connection is actually responsive (not just TCP-open). Returns probeResult with success/latency. Recommended for health checks."),
1052
+ }),
993
1053
  }, async ({ probe }) => {
994
1054
  try {
995
1055
  // Check WebSocket availability
@@ -1092,6 +1152,7 @@ class LocalFigmaConsoleMCP {
1092
1152
  // connected files compares against THIS, not the server
1093
1153
  // version (which can be newer on server-only releases).
1094
1154
  bundledPluginVersion: getBundledPluginVersion(),
1155
+ bundledForkPluginRevision: getBundledForkPluginRevision(),
1095
1156
  port: this.wsActualPort ? String(this.wsActualPort) : null,
1096
1157
  preferredPort: String(this.wsPreferredPort),
1097
1158
  ...(this.wsServer?.loopbackFallback
@@ -1127,6 +1188,7 @@ class LocalFigmaConsoleMCP {
1127
1188
  currentPage: wsFileInfo.currentPage,
1128
1189
  connectedAt: new Date(wsFileInfo.connectedAt).toISOString(),
1129
1190
  pluginVersion: wsFileInfo.pluginVersion ?? undefined,
1191
+ forkPluginRevision: wsFileInfo.forkPluginRevision ?? null,
1130
1192
  pluginUpdateAvailable: wsFileInfo.pluginUpdateAvailable || undefined,
1131
1193
  } : undefined,
1132
1194
  connectedFiles: (() => {
@@ -1141,6 +1203,7 @@ class LocalFigmaConsoleMCP {
1141
1203
  isActive: f.isActive,
1142
1204
  connectedAt: new Date(f.connectedAt).toISOString(),
1143
1205
  pluginVersion: f.pluginVersion ?? undefined,
1206
+ forkPluginRevision: f.forkPluginRevision ?? null,
1144
1207
  pluginUpdateAvailable: f.pluginUpdateAvailable || undefined,
1145
1208
  }));
1146
1209
  })(),
@@ -1220,7 +1283,10 @@ class LocalFigmaConsoleMCP {
1220
1283
  // CONNECTION MANAGEMENT TOOLS
1221
1284
  // ============================================================================
1222
1285
  // Tool: Force reconnect to Figma Desktop
1223
- server.tool("figma_reconnect", "Force a complete reconnection to Figma Desktop. Use when connection seems stale or after switching files.", {}, async () => {
1286
+ server.registerTool("figma_reconnect", {
1287
+ description: "Force a complete reconnection to Figma Desktop. Use when connection seems stale or after switching files.",
1288
+ inputSchema: z.object({}),
1289
+ }, async () => {
1224
1290
  try {
1225
1291
  // figma_reconnect is informational in WebSocket-only mode — the
1226
1292
  // plugin handles its own reconnect logic. A TCP-open socket is not
@@ -1303,12 +1369,15 @@ class LocalFigmaConsoleMCP {
1303
1369
  // REAL-TIME AWARENESS TOOLS (WebSocket-only)
1304
1370
  // ============================================================================
1305
1371
  // Tool: Get current user selection in Figma
1306
- server.tool("figma_get_selection", "Get the currently selected nodes in Figma. Returns node IDs, names, types, and dimensions. WebSocket-only — requires Desktop Bridge plugin. Use this to understand what the user is pointing at instead of asking them to describe it.", {
1307
- verbose: z
1308
- .boolean()
1309
- .optional()
1310
- .default(false)
1311
- .describe("If true, fetches additional details (fills, strokes, styles) for each selected node via figma_execute"),
1372
+ server.registerTool("figma_get_selection", {
1373
+ description: "Get the currently selected nodes in Figma. Returns node IDs, names, types, and dimensions. WebSocket-only — requires Desktop Bridge plugin. Use this to understand what the user is pointing at instead of asking them to describe it.",
1374
+ inputSchema: z.object({
1375
+ verbose: z
1376
+ .boolean()
1377
+ .optional()
1378
+ .default(false)
1379
+ .describe("If true, fetches additional details (fills, strokes, styles) for each selected node via figma_execute"),
1380
+ }),
1312
1381
  }, async ({ verbose }) => {
1313
1382
  try {
1314
1383
  const selection = this.wsServer?.getCurrentSelection() ?? null;
@@ -1396,20 +1465,23 @@ class LocalFigmaConsoleMCP {
1396
1465
  }
1397
1466
  });
1398
1467
  // Tool: Get recent design changes
1399
- server.tool("figma_get_design_changes", "Get recent document changes detected in Figma. Returns buffered change events including which nodes changed, whether styles were modified, and change counts. WebSocket-only — events are captured via Desktop Bridge plugin. Use this to understand what changed since you last checked.", {
1400
- since: z
1401
- .number()
1402
- .optional()
1403
- .describe("Only return changes after this Unix timestamp (ms). Useful for incremental polling."),
1404
- count: z
1405
- .number()
1406
- .optional()
1407
- .describe("Maximum number of change events to return (chronological order, oldest to newest; returns the last N events)"),
1408
- clear: z
1409
- .boolean()
1410
- .optional()
1411
- .default(false)
1412
- .describe("Clear the change buffer after reading. Set to true for polling workflows."),
1468
+ server.registerTool("figma_get_design_changes", {
1469
+ description: "Get recent document changes detected in Figma. Returns buffered change events including which nodes changed, whether styles were modified, and change counts. WebSocket-only — events are captured via Desktop Bridge plugin. Use this to understand what changed since you last checked.",
1470
+ inputSchema: z.object({
1471
+ since: z
1472
+ .number()
1473
+ .optional()
1474
+ .describe("Only return changes after this Unix timestamp (ms). Useful for incremental polling."),
1475
+ count: z
1476
+ .number()
1477
+ .optional()
1478
+ .describe("Maximum number of change events to return (chronological order, oldest to newest; returns the last N events)"),
1479
+ clear: z
1480
+ .boolean()
1481
+ .optional()
1482
+ .default(false)
1483
+ .describe("Clear the change buffer after reading. Set to true for polling workflows."),
1484
+ }),
1413
1485
  }, async ({ since, count, clear }) => {
1414
1486
  try {
1415
1487
  if (!this.wsServer?.isClientConnected()) {
@@ -1473,7 +1545,10 @@ class LocalFigmaConsoleMCP {
1473
1545
  }
1474
1546
  });
1475
1547
  // Tool: List all open files connected via WebSocket
1476
- server.tool("figma_list_open_files", "List all Figma files currently connected via the Desktop Bridge plugin. Shows which files have the plugin open and which one is the active target for tool calls. Use figma_navigate to switch between files. WebSocket multi-client mode — each file with the Desktop Bridge plugin maintains its own connection.", {}, async () => {
1548
+ server.registerTool("figma_list_open_files", {
1549
+ description: "List all Figma files currently connected via the Desktop Bridge plugin. Shows which files have the plugin open and which one is the active target for tool calls. Use figma_navigate to switch between files. WebSocket multi-client mode — each file with the Desktop Bridge plugin maintains its own connection.",
1550
+ inputSchema: z.object({}),
1551
+ }, async () => {
1477
1552
  try {
1478
1553
  if (!this.wsServer?.isClientConnected()) {
1479
1554
  return {
@@ -1544,7 +1619,7 @@ class LocalFigmaConsoleMCP {
1544
1619
  // then get details for specific components.
1545
1620
  // Helper function to ensure design system cache is loaded (auto-loads if needed)
1546
1621
  const ensureDesignSystemCache = async () => {
1547
- const { DesignSystemManifestCache, createEmptyManifest, figmaColorToHex, } = await import("./core/design-system-manifest.js");
1622
+ const { DesignSystemManifestCache, createEmptyManifest, loadManifestVariables, } = await import("./core/design-system-manifest.js");
1548
1623
  const cache = DesignSystemManifestCache.getInstance();
1549
1624
  const currentUrl = this.getCurrentFileUrl();
1550
1625
  // extractFileKey is branch-aware: on /design/KEY/branch/BRANCH_KEY/…
@@ -1562,48 +1637,12 @@ class LocalFigmaConsoleMCP {
1562
1637
  const connector = await this.getDesktopConnector();
1563
1638
  const manifest = createEmptyManifest(fileKey);
1564
1639
  manifest.fileUrl = currentUrl || undefined;
1565
- // Get variables (tokens)
1566
- try {
1567
- const variablesResult = await connector.getVariables(fileKey);
1568
- if (variablesResult.success && variablesResult.data) {
1569
- for (const collection of variablesResult.data.variableCollections ||
1570
- []) {
1571
- manifest.collections.push({
1572
- id: collection.id,
1573
- name: collection.name,
1574
- modes: collection.modes.map((m) => ({
1575
- modeId: m.modeId,
1576
- name: m.name,
1577
- })),
1578
- defaultModeId: collection.defaultModeId,
1579
- });
1580
- }
1581
- for (const variable of variablesResult.data.variables || []) {
1582
- const tokenName = variable.name;
1583
- const defaultModeId = manifest.collections.find((c) => c.id === variable.variableCollectionId)?.defaultModeId;
1584
- const defaultValue = defaultModeId
1585
- ? variable.valuesByMode?.[defaultModeId]
1586
- : undefined;
1587
- if (variable.resolvedType === "COLOR") {
1588
- manifest.tokens.colors[tokenName] = {
1589
- name: tokenName,
1590
- value: figmaColorToHex(defaultValue),
1591
- variableId: variable.id,
1592
- scopes: variable.scopes,
1593
- };
1594
- }
1595
- else if (variable.resolvedType === "FLOAT") {
1596
- manifest.tokens.spacing[tokenName] = {
1597
- name: tokenName,
1598
- value: typeof defaultValue === "number" ? defaultValue : 0,
1599
- variableId: variable.id,
1600
- };
1601
- }
1602
- }
1603
- }
1604
- }
1605
- catch (error) {
1606
- logger.warn({ error }, "Could not fetch variables during auto-load");
1640
+ // Get variables (tokens). A failed read is reported, and the manifest
1641
+ // is not cached, so a transient plugin error can't serve "0 tokens"
1642
+ // for the full TTL.
1643
+ const variablesFetchError = await loadManifestVariables(manifest, () => connector.readVariables(fileKey));
1644
+ if (variablesFetchError) {
1645
+ logger.warn({ error: variablesFetchError }, "Could not fetch variables during auto-load");
1607
1646
  }
1608
1647
  // Get components
1609
1648
  // Maps are keyed by component key (unique) rather than name — same-named
@@ -1663,6 +1702,7 @@ class LocalFigmaConsoleMCP {
1663
1702
  colorPalette: Object.keys(manifest.tokens.colors).slice(0, 10),
1664
1703
  spacingScale: Object.values(manifest.tokens.spacing)
1665
1704
  .map((s) => s.value)
1705
+ .filter((v) => typeof v === "number")
1666
1706
  .sort((a, b) => a - b)
1667
1707
  .slice(0, 10),
1668
1708
  typographyScale: [],
@@ -1671,7 +1711,7 @@ class LocalFigmaConsoleMCP {
1671
1711
  // Cache the result — but never cache a manifest built from a FAILED
1672
1712
  // components fetch: serving an empty manifest as "cached" for the full
1673
1713
  // TTL is exactly the "search returns 0 components" poisoning bug.
1674
- if (!componentsFetchError) {
1714
+ if (!componentsFetchError && !variablesFetchError) {
1675
1715
  cache.set(fileKey, manifest, rawComponents);
1676
1716
  cacheEntry = cache.get(fileKey);
1677
1717
  }
@@ -1687,9 +1727,16 @@ class LocalFigmaConsoleMCP {
1687
1727
  cacheEntry,
1688
1728
  fileKey,
1689
1729
  wasLoaded: true,
1690
- warning: componentsFetchError
1691
- ? `Components fetch failed (${componentsFetchError}) — results may be incomplete and were NOT cached; retry after checking the Desktop Bridge plugin.`
1692
- : undefined,
1730
+ warning: [
1731
+ componentsFetchError
1732
+ ? `Components fetch failed (${componentsFetchError}) — results may be incomplete and were NOT cached; retry after checking the Desktop Bridge plugin.`
1733
+ : null,
1734
+ variablesFetchError
1735
+ ? `Variables fetch failed (${variablesFetchError}) — tokens are missing and the result was NOT cached; retry after checking the Desktop Bridge plugin.`
1736
+ : null,
1737
+ ]
1738
+ .filter(Boolean)
1739
+ .join(" ") || undefined,
1693
1740
  };
1694
1741
  };
1695
1742
  // ============================================================================
@@ -1697,15 +1744,18 @@ class LocalFigmaConsoleMCP {
1697
1744
  // (Previously interleaved with write tools in local.ts; restored after the
1698
1745
  // Phase-2 write-tools dedupe excised them along with the surrounding writes.)
1699
1746
  // ============================================================================
1700
- server.tool("figma_get_design_system_summary", "Get a compact overview of the design system. Returns categories, component counts, and token collection names WITHOUT full details. Use this first to understand what's available, then use figma_search_components to find specific components. This tool is optimized for minimal token usage.", {
1701
- forceRefresh: z
1702
- .boolean()
1703
- .optional()
1704
- .default(false)
1705
- .describe("Force refresh the cached data (use sparingly - extraction can take minutes for large files)"),
1747
+ server.registerTool("figma_get_design_system_summary", {
1748
+ description: "Get a compact overview of the design system. Returns categories, component counts, and token collection names WITHOUT full details. Use this first to understand what's available, then use figma_search_components to find specific components. This tool is optimized for minimal token usage.",
1749
+ inputSchema: z.object({
1750
+ forceRefresh: z
1751
+ .boolean()
1752
+ .optional()
1753
+ .default(false)
1754
+ .describe("Force refresh the cached data (use sparingly - extraction can take minutes for large files)"),
1755
+ }),
1706
1756
  }, async ({ forceRefresh }) => {
1707
1757
  try {
1708
- const { DesignSystemManifestCache, createEmptyManifest, figmaColorToHex, getCategories, getTokenSummary, } = await import("./core/design-system-manifest.js");
1758
+ const { DesignSystemManifestCache, createEmptyManifest, loadManifestVariables, getCategories, getTokenSummary, } = await import("./core/design-system-manifest.js");
1709
1759
  const cache = DesignSystemManifestCache.getInstance();
1710
1760
  const currentUrl = this.getCurrentFileUrl();
1711
1761
  const fileKeyMatch = currentUrl?.match(/\/(file|design|board|slides)\/([a-zA-Z0-9]+)/);
@@ -1741,49 +1791,8 @@ class LocalFigmaConsoleMCP {
1741
1791
  const connector = await this.getDesktopConnector();
1742
1792
  const manifest = createEmptyManifest(fileKey);
1743
1793
  manifest.fileUrl = currentUrl || undefined;
1744
- // Get variables (tokens)
1745
- try {
1746
- const variablesResult = await connector.getVariables(fileKey);
1747
- if (variablesResult.success && variablesResult.data) {
1748
- for (const collection of variablesResult.data
1749
- .variableCollections || []) {
1750
- manifest.collections.push({
1751
- id: collection.id,
1752
- name: collection.name,
1753
- modes: collection.modes.map((m) => ({
1754
- modeId: m.modeId,
1755
- name: m.name,
1756
- })),
1757
- defaultModeId: collection.defaultModeId,
1758
- });
1759
- }
1760
- for (const variable of variablesResult.data.variables || []) {
1761
- const tokenName = variable.name;
1762
- const defaultModeId = manifest.collections.find((c) => c.id === variable.variableCollectionId)?.defaultModeId;
1763
- const defaultValue = defaultModeId
1764
- ? variable.valuesByMode?.[defaultModeId]
1765
- : undefined;
1766
- if (variable.resolvedType === "COLOR") {
1767
- manifest.tokens.colors[tokenName] = {
1768
- name: tokenName,
1769
- value: figmaColorToHex(defaultValue),
1770
- variableId: variable.id,
1771
- scopes: variable.scopes,
1772
- };
1773
- }
1774
- else if (variable.resolvedType === "FLOAT") {
1775
- manifest.tokens.spacing[tokenName] = {
1776
- name: tokenName,
1777
- value: typeof defaultValue === "number" ? defaultValue : 0,
1778
- variableId: variable.id,
1779
- };
1780
- }
1781
- }
1782
- }
1783
- }
1784
- catch (error) {
1785
- logger.warn({ error }, "Could not fetch variables");
1786
- }
1794
+ // Get variables (tokens); see ensureDesignSystemCache for the failure guard.
1795
+ const variablesFetchError = await loadManifestVariables(manifest, () => connector.readVariables(fileKey));
1787
1796
  // Get components (can be slow for large files)
1788
1797
  // Keyed by component key (unique) — name keys drop same-named
1789
1798
  // components on other pages.
@@ -1842,6 +1851,7 @@ class LocalFigmaConsoleMCP {
1842
1851
  colorPalette: Object.keys(manifest.tokens.colors).slice(0, 10),
1843
1852
  spacingScale: Object.values(manifest.tokens.spacing)
1844
1853
  .map((s) => s.value)
1854
+ .filter((v) => typeof v === "number")
1845
1855
  .sort((a, b) => a - b)
1846
1856
  .slice(0, 10),
1847
1857
  typographyScale: [],
@@ -1849,7 +1859,7 @@ class LocalFigmaConsoleMCP {
1849
1859
  };
1850
1860
  // Cache the result — never cache a manifest built from a failed
1851
1861
  // components fetch (would serve empty results for the full TTL).
1852
- if (!componentsFetchError) {
1862
+ if (!componentsFetchError && !variablesFetchError) {
1853
1863
  cache.set(fileKey, manifest, rawComponents);
1854
1864
  }
1855
1865
  const categories = getCategories(manifest);
@@ -1869,10 +1879,15 @@ class LocalFigmaConsoleMCP {
1869
1879
  componentSets: manifest.summary.totalComponentSets,
1870
1880
  tokens: manifest.summary.totalTokens,
1871
1881
  },
1872
- warnings: componentsFetchError
1882
+ warnings: componentsFetchError || variablesFetchError
1873
1883
  ? [
1874
- `Components fetch failed (${componentsFetchError}) — component data is incomplete and was NOT cached. Check the Desktop Bridge plugin and retry.`,
1875
- ]
1884
+ componentsFetchError
1885
+ ? `Components fetch failed (${componentsFetchError}) — component data is incomplete and was NOT cached. Check the Desktop Bridge plugin and retry.`
1886
+ : null,
1887
+ variablesFetchError
1888
+ ? `Variables fetch failed (${variablesFetchError}) — tokens are missing and the result was NOT cached. Check the Desktop Bridge plugin and retry.`
1889
+ : null,
1890
+ ].filter(Boolean)
1876
1891
  : undefined,
1877
1892
  hint: "Use figma_search_components to find specific components by name or category.",
1878
1893
  }),
@@ -1897,38 +1912,41 @@ class LocalFigmaConsoleMCP {
1897
1912
  }
1898
1913
  });
1899
1914
  // Tool 2: Search Components (~3000 tokens response max, paginated)
1900
- server.tool("figma_search_components", `Search for components by name, category, or description. Returns paginated results with component keys for instantiation. Automatically loads the design system cache if needed.
1915
+ server.registerTool("figma_search_components", {
1916
+ description: `Search for components by name, category, or description. Returns paginated results with component keys for instantiation. Automatically loads the design system cache if needed.
1901
1917
 
1902
1918
  **NEW: Cross-file library search!** Pass a libraryFileKey or libraryFileUrl to search for components in a published shared library (different file). This uses the REST API and requires FIGMA_ACCESS_TOKEN.
1903
1919
 
1904
- Without libraryFileKey/libraryFileUrl, searches the currently open file (local components via Plugin API).`, {
1905
- query: z
1906
- .string()
1907
- .optional()
1908
- .default("")
1909
- .describe("Search query to match component names or descriptions"),
1910
- category: z
1911
- .string()
1912
- .optional()
1913
- .describe("Filter by category (e.g., 'Button', 'Input', 'Card')"),
1914
- libraryFileKey: z
1915
- .string()
1916
- .optional()
1917
- .describe("File key of a published library to search in (for cross-file library access). Overrides local search."),
1918
- libraryFileUrl: z
1919
- .string()
1920
- .optional()
1921
- .describe("URL of a published library file to search in (e.g., https://www.figma.com/design/abc123/...). Alternative to libraryFileKey."),
1922
- limit: z
1923
- .number()
1924
- .optional()
1925
- .default(10)
1926
- .describe("Maximum results to return (default: 10, max: 25)"),
1927
- offset: z
1928
- .number()
1929
- .optional()
1930
- .default(0)
1931
- .describe("Offset for pagination"),
1920
+ Without libraryFileKey/libraryFileUrl, searches the currently open file (local components via Plugin API).`,
1921
+ inputSchema: z.object({
1922
+ query: z
1923
+ .string()
1924
+ .optional()
1925
+ .default("")
1926
+ .describe("Search query to match component names or descriptions"),
1927
+ category: z
1928
+ .string()
1929
+ .optional()
1930
+ .describe("Filter by category (e.g., 'Button', 'Input', 'Card')"),
1931
+ libraryFileKey: z
1932
+ .string()
1933
+ .optional()
1934
+ .describe("File key of a published library to search in (for cross-file library access). Overrides local search."),
1935
+ libraryFileUrl: z
1936
+ .string()
1937
+ .optional()
1938
+ .describe("URL of a published library file to search in (e.g., https://www.figma.com/design/abc123/...). Alternative to libraryFileKey."),
1939
+ limit: z
1940
+ .number()
1941
+ .optional()
1942
+ .default(10)
1943
+ .describe("Maximum results to return (default: 10, max: 25)"),
1944
+ offset: z
1945
+ .number()
1946
+ .optional()
1947
+ .default(0)
1948
+ .describe("Offset for pagination"),
1949
+ }),
1932
1950
  }, async ({ query, category, libraryFileKey, libraryFileUrl, limit, offset }) => {
1933
1951
  try {
1934
1952
  // Determine if this is a library search or local search
@@ -2119,15 +2137,18 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2119
2137
  }
2120
2138
  });
2121
2139
  // Tool 3: Get Component Details (~500 tokens per component)
2122
- server.tool("figma_get_component_details", "Get full details for a specific component including all variants, properties, and keys needed for instantiation. Use the component key or name from figma_search_components.", {
2123
- componentKey: z
2124
- .string()
2125
- .optional()
2126
- .describe("The component key (preferred for exact match)"),
2127
- componentName: z
2128
- .string()
2129
- .optional()
2130
- .describe("The component name (used if key not provided)"),
2140
+ server.registerTool("figma_get_component_details", {
2141
+ description: "Get full details for a specific component including all variants, properties, and keys needed for instantiation. Use the component key or name from figma_search_components.",
2142
+ inputSchema: z.object({
2143
+ componentKey: z
2144
+ .string()
2145
+ .optional()
2146
+ .describe("The component key (preferred for exact match)"),
2147
+ componentName: z
2148
+ .string()
2149
+ .optional()
2150
+ .describe("The component name (used if key not provided)"),
2151
+ }),
2131
2152
  }, async ({ componentKey, componentName }) => {
2132
2153
  try {
2133
2154
  if (!componentKey && !componentName) {
@@ -2229,21 +2250,24 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2229
2250
  }
2230
2251
  });
2231
2252
  // Tool 4: Get Token Values (~2000 tokens response max)
2232
- server.tool("figma_get_token_values", "Get actual values for design tokens (colors, spacing, etc). Use after figma_get_design_system_summary to get specific token values for implementation.", {
2233
- type: z
2234
- .enum(["colors", "spacing", "all"])
2235
- .optional()
2236
- .default("all")
2237
- .describe("Type of tokens to retrieve"),
2238
- filter: z
2239
- .string()
2240
- .optional()
2241
- .describe("Filter token names (e.g., 'primary' to get all primary colors)"),
2242
- limit: z
2243
- .number()
2244
- .optional()
2245
- .default(50)
2246
- .describe("Maximum tokens to return (default: 50)"),
2253
+ server.registerTool("figma_get_token_values", {
2254
+ description: "Get actual values for design tokens (colors, spacing, etc). Use after figma_get_design_system_summary to get specific token values for implementation.",
2255
+ inputSchema: z.object({
2256
+ type: z
2257
+ .enum(["colors", "spacing", "all"])
2258
+ .optional()
2259
+ .default("all")
2260
+ .describe("Type of tokens to retrieve"),
2261
+ filter: z
2262
+ .string()
2263
+ .optional()
2264
+ .describe("Filter token names (e.g., 'primary' to get all primary colors)"),
2265
+ limit: z
2266
+ .number()
2267
+ .optional()
2268
+ .default(50)
2269
+ .describe("Maximum tokens to return (default: 50)"),
2270
+ }),
2247
2271
  }, async ({ type, filter, limit }) => {
2248
2272
  try {
2249
2273
  // Auto-load design system cache if needed
@@ -2272,7 +2296,7 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2272
2296
  if (count >= effectiveLimit)
2273
2297
  break;
2274
2298
  if (!filterLower || name.toLowerCase().includes(filterLower)) {
2275
- colors[name] = { value: token.value, scopes: token.scopes };
2299
+ colors[name] = { value: token.value, scopes: token.scopes, ...(token.aliasOf ? { aliasOf: token.aliasOf } : {}) };
2276
2300
  count++;
2277
2301
  }
2278
2302
  }
@@ -2285,7 +2309,7 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2285
2309
  if (count >= effectiveLimit)
2286
2310
  break;
2287
2311
  if (!filterLower || name.toLowerCase().includes(filterLower)) {
2288
- spacing[name] = { value: token.value };
2312
+ spacing[name] = { value: token.value, ...(token.aliasOf ? { aliasOf: token.aliasOf } : {}) };
2289
2313
  count++;
2290
2314
  }
2291
2315
  }
@@ -2322,7 +2346,8 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2322
2346
  }
2323
2347
  });
2324
2348
  // Tool 5: Instantiate Component
2325
- server.tool("figma_get_library_components", `Discover published components from a shared/team library file.
2349
+ server.registerTool("figma_get_library_components", {
2350
+ description: `Discover published components from a shared/team library file.
2326
2351
 
2327
2352
  **USE THIS when you need to use components from a published design system library** (a different file than the one currently open). This bridges the gap between library discovery and instantiation.
2328
2353
 
@@ -2335,34 +2360,36 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2335
2360
 
2336
2361
  **MULTI-FILE TIP:** If you need to find a specific component and REST API search returns too many results, you can switch to the library file via figma_navigate, use figma_execute to find the exact component and its variant key, then switch back.
2337
2362
 
2338
- **NOTE:** Requires FIGMA_ACCESS_TOKEN to be set (uses the Figma REST API to read the library file).`, {
2339
- libraryFileUrl: z
2340
- .string()
2341
- .optional()
2342
- .describe("The URL of the library file (e.g., https://www.figma.com/design/abc123/My-Design-System). Either this or libraryFileKey is required."),
2343
- libraryFileKey: z
2344
- .string()
2345
- .optional()
2346
- .describe("The file key of the library file (e.g., 'abc123'). Either this or libraryFileUrl is required."),
2347
- query: z
2348
- .string()
2349
- .optional()
2350
- .describe("Search query to filter components by name (e.g., 'Button', 'Card'). Leave empty to get all components."),
2351
- limit: z
2352
- .number()
2353
- .optional()
2354
- .default(25)
2355
- .describe("Maximum results to return (default: 25, max: 100)"),
2356
- offset: z
2357
- .number()
2358
- .optional()
2359
- .default(0)
2360
- .describe("Offset for pagination"),
2361
- includeVariants: z
2362
- .boolean()
2363
- .optional()
2364
- .default(false)
2365
- .describe("Include individual variant components (default: false, only returns component sets)"),
2363
+ **NOTE:** Requires FIGMA_ACCESS_TOKEN to be set (uses the Figma REST API to read the library file).`,
2364
+ inputSchema: z.object({
2365
+ libraryFileUrl: z
2366
+ .string()
2367
+ .optional()
2368
+ .describe("The URL of the library file (e.g., https://www.figma.com/design/abc123/My-Design-System). Either this or libraryFileKey is required."),
2369
+ libraryFileKey: z
2370
+ .string()
2371
+ .optional()
2372
+ .describe("The file key of the library file (e.g., 'abc123'). Either this or libraryFileUrl is required."),
2373
+ query: z
2374
+ .string()
2375
+ .optional()
2376
+ .describe("Search query to filter components by name (e.g., 'Button', 'Card'). Leave empty to get all components."),
2377
+ limit: z
2378
+ .number()
2379
+ .optional()
2380
+ .default(25)
2381
+ .describe("Maximum results to return (default: 25, max: 100)"),
2382
+ offset: z
2383
+ .number()
2384
+ .optional()
2385
+ .default(0)
2386
+ .describe("Offset for pagination"),
2387
+ includeVariants: z
2388
+ .boolean()
2389
+ .optional()
2390
+ .default(false)
2391
+ .describe("Include individual variant components (default: false, only returns component sets)"),
2392
+ }),
2366
2393
  }, async ({ libraryFileUrl, libraryFileKey, query, limit, offset, includeVariants, }) => {
2367
2394
  try {
2368
2395
  // Resolve file key from URL or direct key
@@ -2590,8 +2617,7 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2590
2617
  // ============================================================================
2591
2618
  // Tool: Set Node Description
2592
2619
  // Register all write/manipulation tools (figma_execute, variable CRUD, node mutations,
2593
- // design-token setup, accessibility audits, etc.). Sourced from src/core/write-tools.ts
2594
- // so local mode and cloud mode share the same 30 implementations — no risk of drift.
2620
+ // design-token setup, accessibility audits, etc.), sourced from src/core/write-tools.ts.
2595
2621
  registerWriteTools(server, (fileKey) => this.getDesktopConnector(fileKey), {
2596
2622
  onVariableWrite: () => this.invalidateVariablesCache(),
2597
2623
  });
@@ -2650,6 +2676,7 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2650
2676
  }
2651
2677
  },
2652
2678
  getBundledPluginVersion,
2679
+ getBundledForkPluginRevision,
2653
2680
  getPluginState: () => {
2654
2681
  if (!this.wsServer)
2655
2682
  return null;
@@ -2664,6 +2691,7 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2664
2691
  port: this.wsActualPort ?? undefined,
2665
2692
  portFallbackFrom: this.wsPreferredPort,
2666
2693
  pluginVersion: fileInfo?.pluginVersion,
2694
+ forkPluginRevision: fileInfo?.forkPluginRevision ?? null,
2667
2695
  pluginUpdateAvailable: fileInfo?.pluginUpdateAvailable,
2668
2696
  };
2669
2697
  },
@@ -2745,7 +2773,7 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2745
2773
  // Priority 1: Try Desktop Bridge via transport-agnostic connector
2746
2774
  try {
2747
2775
  const connector = await this.getDesktopConnector();
2748
- const desktopResult = await connector.getVariablesFromPluginUI(fileKey);
2776
+ const desktopResult = await connector.readVariables(fileKey);
2749
2777
  if (desktopResult.success && desktopResult.variables) {
2750
2778
  // Cache the desktop result
2751
2779
  this.variablesCache.set(fileKey, {
@@ -2828,7 +2856,7 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2828
2856
  desktopBridgeAttempted = true;
2829
2857
  try {
2830
2858
  const connector = await this.getDesktopConnector();
2831
- const desktopResult = await connector.getVariablesFromPluginUI(fileKey);
2859
+ const desktopResult = await connector.readVariables(fileKey);
2832
2860
  if (desktopResult.success && desktopResult.variables) {
2833
2861
  this.variablesCache.set(fileKey, {
2834
2862
  data: {
@@ -2979,6 +3007,15 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2979
3007
  }
2980
3008
  logger.info("All MCP tools registered successfully (including write operations)");
2981
3009
  }
3010
+ /**
3011
+ * A fresh, fully registered server: one per MCP_HTTP_PORT request (either
3012
+ * era), or for a stdio connection that serveStdio re-pins to another era.
3013
+ */
3014
+ createRequestServer() {
3015
+ const server = new IdentifiedMcpServer({ name: "Figma Console MCP (Local)", version: SERVER_VERSION }, { instructions: MCP_SERVER_INSTRUCTIONS });
3016
+ this.registerTools(server);
3017
+ return server;
3018
+ }
2982
3019
  /**
2983
3020
  * Start an optional Streamable HTTP MCP server.
2984
3021
  * Only starts if MCP_HTTP_PORT env var is set. This provides an HTTP-based
@@ -2994,30 +3031,65 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2994
3031
  logger.warn({ portStr }, "Invalid MCP_HTTP_PORT, skipping HTTP server");
2995
3032
  return;
2996
3033
  }
3034
+ // Both protocol eras are served at /mcp, each by a fresh server per request
3035
+ // (IdentifiedMcpServer: every handler gets `_mcp` tagging and
3036
+ // `[figma-console-mcp]` error prefixing):
3037
+ // - 2026-07-28 requests (per-request `_meta`, no initialize) go to the SDK's
3038
+ // createMcpHandler. `legacy: "reject"` keeps its own stateless fallback
3039
+ // from ever answering 2025-era traffic, which is routed below instead.
3040
+ // - 2025-era requests keep this endpoint's stateless Streamable HTTP
3041
+ // contract: no session id, one transport per request.
3042
+ const reportModernError = (error) => logger.warn({ err: error.message }, "HTTP MCP (2026-07-28) request error");
3043
+ this.modernHttpHandler = createMcpHandler(() => this.createRequestServer(), {
3044
+ legacy: "reject",
3045
+ onerror: reportModernError,
3046
+ maxRequestBodySize: MAX_HTTP_BODY_BYTES,
3047
+ });
3048
+ const serveModern = toNodeHandler(this.modernHttpHandler, {
3049
+ onerror: reportModernError,
3050
+ maxRequestBodySize: MAX_HTTP_BODY_BYTES,
3051
+ });
2997
3052
  this.httpServer = createServer(async (req, res) => {
2998
- // Before any routing: DNS-rebinding and cross-site requests get a 403.
3053
+ // Before any routing — and so before the era split, for both eras:
3054
+ // DNS-rebinding and cross-site requests get a 403.
2999
3055
  if (!guardLocalHttpRequest(req, res, port))
3000
3056
  return;
3001
3057
  const url = new URL(req.url ?? "/", `http://localhost:${port}`);
3002
3058
  if (url.pathname === "/mcp") {
3003
3059
  try {
3004
- // The MCP SDK enforces one-request-per-transport in stateless mode
3005
- // ("Stateless transport cannot be reused across requests"), so we
3006
- // create a fresh transport + server per request — same pattern as
3007
- // the Cloudflare entry point (src/index.ts).
3008
- const transport = new StreamableHTTPServerTransport({
3060
+ // Only a POST carries a JSON-RPC body to classify. GET/DELETE are
3061
+ // 2025-era verbs; the stateless transport answers them.
3062
+ let body;
3063
+ if (req.method === "POST") {
3064
+ try {
3065
+ body = await readJsonBody(req);
3066
+ }
3067
+ catch (err) {
3068
+ const e = err;
3069
+ if (!res.headersSent) {
3070
+ // Connection: close — an oversized body may still be arriving.
3071
+ res.writeHead(e.status ?? 400, { "Content-Type": "application/json", Connection: "close" });
3072
+ res.end(JSON.stringify({ jsonrpc: "2.0", error: { code: e.code ?? -32000, message: e.message }, id: null }));
3073
+ }
3074
+ return;
3075
+ }
3076
+ // The SDK's own era predicate, so routing can't disagree with createMcpHandler.
3077
+ if (!(await isLegacyRequest(await toWebRequest(req, body), body))) {
3078
+ await serveModern(req, res, body);
3079
+ return;
3080
+ }
3081
+ }
3082
+ // 2025 era. The SDK enforces one-request-per-transport in stateless
3083
+ // mode, so each request gets a fresh transport + server.
3084
+ const transport = new NodeStreamableHTTPServerTransport({
3009
3085
  sessionIdGenerator: undefined,
3010
3086
  });
3011
- const reqServer = new McpServer({ name: "Figma Console MCP (Local)", version: SERVER_VERSION }, { instructions: MCP_SERVER_INSTRUCTIONS });
3012
- // Must wrap BEFORE registerTools() so every registered handler gets
3013
- // `_mcp` tagging and `[figma-console-mcp]` error prefixing.
3014
- wrapServerForIdentity(reqServer);
3015
- this.registerTools(reqServer);
3087
+ const reqServer = this.createRequestServer();
3016
3088
  await reqServer.connect(transport);
3017
3089
  res.once("close", () => {
3018
3090
  reqServer.close().catch(() => { });
3019
3091
  });
3020
- await transport.handleRequest(req, res);
3092
+ await transport.handleRequest(req, res, body);
3021
3093
  }
3022
3094
  catch (error) {
3023
3095
  logger.error({ error }, "Error handling HTTP MCP request");
@@ -3243,10 +3315,22 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
3243
3315
  if (this.mcpHttpPort && this.wsActualPort) {
3244
3316
  setAdvertisedMcpHttpPort(this.wsActualPort, this.mcpHttpPort);
3245
3317
  }
3246
- // Create stdio transport
3247
- const transport = new StdioServerTransport();
3248
- // Connect server to transport
3249
- await this.server.connect(transport);
3318
+ // Serve stdio for both protocol eras: 2025-era clients (initialize
3319
+ // handshake) and 2026-07-28 clients (server/discover + per-request
3320
+ // _meta). serveStdio usually calls the factory once, but calls it again
3321
+ // when a connection opens with a server/discover probe and then falls
3322
+ // back to initialize; it discards the probe's instance, which is pinned
3323
+ // to the modern era, so a re-pin must get a fresh server.
3324
+ // On stdin EOF the SDK closes the connection but never exits the
3325
+ // process: with MCP_HTTP_PORT active (and the WebSocket bridge
3326
+ // listening) it keeps serving.
3327
+ let stdioServerHandedOut = false;
3328
+ serveStdio(() => {
3329
+ if (stdioServerHandedOut)
3330
+ return this.createRequestServer();
3331
+ stdioServerHandedOut = true;
3332
+ return this.server;
3333
+ }, { onerror: (error) => logger.error({ error }, "stdio transport error") });
3250
3334
  logger.info("MCP server started successfully on stdio transport");
3251
3335
  // 🆕 AUTO-CONNECT: Start monitoring immediately if Figma Desktop is available
3252
3336
  // This enables "get latest logs" workflow without requiring manual setup
@@ -3282,6 +3366,10 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
3282
3366
  if (this.wsActualPort) {
3283
3367
  unadvertisePort(this.wsActualPort);
3284
3368
  }
3369
+ if (this.modernHttpHandler) {
3370
+ await this.modernHttpHandler.close();
3371
+ this.modernHttpHandler = null;
3372
+ }
3285
3373
  if (this.httpServer) {
3286
3374
  this.httpServer.close();
3287
3375
  this.httpServer = null;