@muloka/figma-console-mcp 0.5.6 → 0.6.0

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 (108) hide show
  1. package/README.md +111 -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 +51 -45
  34. package/dist/core/design-code-tools.js.map +1 -1
  35. package/dist/core/design-system-tools.d.ts +1 -1
  36. package/dist/core/design-system-tools.d.ts.map +1 -1
  37. package/dist/core/design-system-tools.js +39 -36
  38. package/dist/core/design-system-tools.js.map +1 -1
  39. package/dist/core/diagnose-tool.d.ts +4 -4
  40. package/dist/core/diagnose-tool.d.ts.map +1 -1
  41. package/dist/core/diagnose-tool.js +12 -14
  42. package/dist/core/diagnose-tool.js.map +1 -1
  43. package/dist/core/figjam-tools.d.ts +2 -2
  44. package/dist/core/figjam-tools.d.ts.map +1 -1
  45. package/dist/core/figjam-tools.js +159 -129
  46. package/dist/core/figjam-tools.js.map +1 -1
  47. package/dist/core/figma-tools.d.ts +1 -1
  48. package/dist/core/figma-tools.d.ts.map +1 -1
  49. package/dist/core/figma-tools.js +280 -253
  50. package/dist/core/figma-tools.js.map +1 -1
  51. package/dist/core/identity.d.ts +49 -9
  52. package/dist/core/identity.d.ts.map +1 -1
  53. package/dist/core/identity.js +137 -28
  54. package/dist/core/identity.js.map +1 -1
  55. package/dist/core/library-tools.d.ts +1 -1
  56. package/dist/core/library-tools.d.ts.map +1 -1
  57. package/dist/core/library-tools.js +45 -36
  58. package/dist/core/library-tools.js.map +1 -1
  59. package/dist/core/logger.d.ts +0 -1
  60. package/dist/core/logger.d.ts.map +1 -1
  61. package/dist/core/logger.js +1 -13
  62. package/dist/core/logger.js.map +1 -1
  63. package/dist/core/slides-tools.d.ts +2 -2
  64. package/dist/core/slides-tools.d.ts.map +1 -1
  65. package/dist/core/slides-tools.js +223 -172
  66. package/dist/core/slides-tools.js.map +1 -1
  67. package/dist/core/slot-tools.d.ts +1 -1
  68. package/dist/core/slot-tools.d.ts.map +1 -1
  69. package/dist/core/slot-tools.js +101 -86
  70. package/dist/core/slot-tools.js.map +1 -1
  71. package/dist/core/tokens/config.d.ts +88 -266
  72. package/dist/core/tokens/config.d.ts.map +1 -1
  73. package/dist/core/tokens/config.js +2 -3
  74. package/dist/core/tokens/config.js.map +1 -1
  75. package/dist/core/tokens/schemas.d.ts +104 -113
  76. package/dist/core/tokens/schemas.d.ts.map +1 -1
  77. package/dist/core/tokens/schemas.js +2 -2
  78. package/dist/core/tokens/schemas.js.map +1 -1
  79. package/dist/core/tokens-tools.d.ts +5 -3
  80. package/dist/core/tokens-tools.d.ts.map +1 -1
  81. package/dist/core/tokens-tools.js +9 -2
  82. package/dist/core/tokens-tools.js.map +1 -1
  83. package/dist/core/types/index.d.ts +1 -1
  84. package/dist/core/types/index.d.ts.map +1 -1
  85. package/dist/core/variable-resolver.d.ts +3 -3
  86. package/dist/core/variable-resolver.js +5 -5
  87. package/dist/core/variable-resolver.js.map +1 -1
  88. package/dist/core/version-tools.d.ts +4 -4
  89. package/dist/core/version-tools.d.ts.map +1 -1
  90. package/dist/core/version-tools.js +162 -144
  91. package/dist/core/version-tools.js.map +1 -1
  92. package/dist/core/websocket-connector.d.ts +2 -3
  93. package/dist/core/websocket-connector.d.ts.map +1 -1
  94. package/dist/core/websocket-connector.js +2 -3
  95. package/dist/core/websocket-connector.js.map +1 -1
  96. package/dist/core/websocket-server.d.ts +39 -2
  97. package/dist/core/websocket-server.d.ts.map +1 -1
  98. package/dist/core/websocket-server.js +138 -18
  99. package/dist/core/websocket-server.js.map +1 -1
  100. package/dist/core/write-tools.d.ts +15 -2
  101. package/dist/core/write-tools.d.ts.map +1 -1
  102. package/dist/core/write-tools.js +589 -477
  103. package/dist/core/write-tools.js.map +1 -1
  104. package/dist/local.d.ts +8 -1
  105. package/dist/local.d.ts.map +1 -1
  106. package/dist/local.js +370 -202
  107. package/dist/local.js.map +1 -1
  108. package/package.json +10 -18
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,9 +37,9 @@ 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 } from "./core/websocket-server.js";
42
+ import { FigmaWebSocketServer, getBundledPluginVersion, heldPinStatusWarning, } from "./core/websocket-server.js";
43
43
  import { WebSocketConnector } from "./core/websocket-connector.js";
44
44
  import { DEFAULT_WS_PORT, getPortRange, advertisePort, unadvertisePort, registerPortCleanup, startPeriodicReaper, discoverActiveInstances, cleanupStalePortFiles, cleanupOrphanedProcesses, evictOldestInstance, refreshPortAdvertisement, setAdvertisedMcpHttpPort, HEARTBEAT_INTERVAL_MS, } from "./core/port-discovery.js";
45
45
  import { registerTokenBrowserApp } from "./apps/token-browser/server.js";
@@ -48,6 +48,43 @@ import { registerFigJamTools } from "./core/figjam-tools.js";
48
48
  import { registerSlidesTools } from "./core/slides-tools.js";
49
49
  import { registerSlotTools } from "./core/slot-tools.js";
50
50
  const logger = createChildLogger({ component: "local-server" });
51
+ // Every McpServer this process builds (stdio and per-request HTTP) stamps tool
52
+ // responses and thrown errors with our MCP identity, so LLMs can attribute
53
+ // output unambiguously when several Figma-related MCPs are connected.
54
+ const IdentifiedMcpServer = withToolIdentity(McpServer);
55
+ /** Largest JSON-RPC body the MCP_HTTP_PORT endpoint reads (both protocol eras). */
56
+ const MAX_HTTP_BODY_BYTES = 4 * 1024 * 1024;
57
+ /** Read and parse a JSON request body, refusing oversized or malformed ones. */
58
+ function readJsonBody(req) {
59
+ return new Promise((resolve, reject) => {
60
+ const chunks = [];
61
+ let size = 0;
62
+ let tooLarge = false;
63
+ req.on("data", (chunk) => {
64
+ if (tooLarge)
65
+ return; // drain and discard the rest
66
+ size += chunk.length;
67
+ if (size > MAX_HTTP_BODY_BYTES) {
68
+ // Stop buffering, but keep reading: destroying the socket here would
69
+ // reset the connection before the 413 can be written.
70
+ tooLarge = true;
71
+ chunks.length = 0;
72
+ reject(Object.assign(new Error("Request body too large"), { status: 413, code: -32000 }));
73
+ return;
74
+ }
75
+ chunks.push(chunk);
76
+ });
77
+ req.on("end", () => {
78
+ try {
79
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
80
+ }
81
+ catch {
82
+ reject(Object.assign(new Error("Parse error: request body is not valid JSON"), { status: 400, code: -32700 }));
83
+ }
84
+ });
85
+ req.on("error", reject);
86
+ });
87
+ }
51
88
  /**
52
89
  * Copy plugin files to a stable directory (~/.figma-console-mcp/plugin/).
53
90
  * This gives users a permanent, predictable path to import from instead of
@@ -168,7 +205,7 @@ For component-specific design guidance (sizing, proportions, accessibility, etc.
168
205
  If Design Systems Assistant MCP is not available, install it from: https://github.com/southleft/design-systems-mcp`;
169
206
  /**
170
207
  * Local MCP Server
171
- * Connects to Figma Desktop and provides identical tools to Cloudflare mode
208
+ * Connects to Figma Desktop through the Desktop Bridge plugin and serves the tools over stdio (and HTTP with MCP_HTTP_PORT)
172
209
  */
173
210
  class LocalFigmaConsoleMCP {
174
211
  /**
@@ -198,22 +235,20 @@ class LocalFigmaConsoleMCP {
198
235
  this.httpServer = null;
199
236
  /** The port the HTTP MCP server is listening on, if enabled */
200
237
  this.mcpHttpPort = null;
238
+ /** MCP_HTTP_PORT's 2026-07-28 leg (one fresh server per request). */
239
+ this.modernHttpHandler = null;
201
240
  this.config = getConfig();
202
241
  // In-memory cache for variables data to avoid MCP token limits
203
242
  // Maps fileKey -> {data, timestamp}
204
243
  this.variablesCache = new Map();
205
244
  /** Stable plugin directory path (set during startup) */
206
245
  this.stablePluginPath = null;
207
- this.server = new McpServer({
246
+ this.server = new IdentifiedMcpServer({
208
247
  name: "Figma Console MCP (Local)",
209
248
  version: SERVER_VERSION,
210
249
  }, {
211
250
  instructions: MCP_SERVER_INSTRUCTIONS,
212
251
  });
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
252
  }
218
253
  /**
219
254
  * Get or create Figma API client
@@ -389,21 +424,24 @@ class LocalFigmaConsoleMCP {
389
424
  registerTools(target) {
390
425
  const server = target ?? this.server;
391
426
  // 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)"),
427
+ server.registerTool("figma_get_console_logs", {
428
+ 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.",
429
+ inputSchema: z.object({
430
+ count: z
431
+ .number()
432
+ .optional()
433
+ .default(100)
434
+ .describe("Number of recent logs to retrieve"),
435
+ level: z
436
+ .enum(["log", "info", "warn", "error", "debug", "all"])
437
+ .optional()
438
+ .default("all")
439
+ .describe("Filter by log level"),
440
+ since: z
441
+ .number()
442
+ .optional()
443
+ .describe("Only logs after this timestamp (Unix ms)"),
444
+ }),
407
445
  }, async ({ count, level, since }) => {
408
446
  try {
409
447
  // Try console monitor first, fall back to WebSocket console buffer
@@ -482,23 +520,26 @@ class LocalFigmaConsoleMCP {
482
520
  // Bridge-first: the plugin's exportAsync works on any Figma plan with no REST
483
521
  // token, and reflects the current runtime state (no cloud-sync lag).
484
522
  // 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)"),
523
+ server.registerTool("figma_take_screenshot", {
524
+ 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.`,
525
+ inputSchema: z.object({
526
+ nodeId: z
527
+ .string()
528
+ .optional()
529
+ .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)."),
530
+ scale: z
531
+ .number()
532
+ .min(0.01)
533
+ .max(4)
534
+ .optional()
535
+ .default(2)
536
+ .describe("Image scale factor (0.01-4, default: 2 for high quality)"),
537
+ format: z
538
+ .enum(["png", "jpg", "svg", "pdf"])
539
+ .optional()
540
+ .default("png")
541
+ .describe("Image format (default: png)"),
542
+ }),
502
543
  }, async ({ nodeId, scale, format }) => {
503
544
  // Callers routinely paste URL-format ids (123-456); both the Plugin
504
545
  // API and REST response maps use colon format (123:456).
@@ -667,17 +708,20 @@ class LocalFigmaConsoleMCP {
667
708
  }
668
709
  });
669
710
  // 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"),
711
+ server.registerTool("figma_watch_console", {
712
+ 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.",
713
+ inputSchema: z.object({
714
+ duration: z
715
+ .number()
716
+ .optional()
717
+ .default(30)
718
+ .describe("How long to watch in seconds"),
719
+ level: z
720
+ .enum(["log", "info", "warn", "error", "debug", "all"])
721
+ .optional()
722
+ .default("all")
723
+ .describe("Filter by log level"),
724
+ }),
681
725
  }, async ({ duration, level }) => {
682
726
  if (!this.wsServer?.isClientConnected()) {
683
727
  throw new Error("No console monitoring available. Open the Desktop Bridge plugin in Figma for console capture.");
@@ -717,12 +761,15 @@ class LocalFigmaConsoleMCP {
717
761
  };
718
762
  });
719
763
  // 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"),
764
+ server.registerTool("figma_reload_plugin", {
765
+ 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.",
766
+ inputSchema: z.object({
767
+ clearConsole: z
768
+ .boolean()
769
+ .optional()
770
+ .default(true)
771
+ .describe("Clear console logs before reload"),
772
+ }),
726
773
  }, async ({ clearConsole: clearConsoleBefore }) => {
727
774
  try {
728
775
  let transport = "websocket";
@@ -785,7 +832,10 @@ class LocalFigmaConsoleMCP {
785
832
  }
786
833
  });
787
834
  // 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 () => {
835
+ server.registerTool("figma_clear_console", {
836
+ description: "Clear the console log buffer. Safely clears the buffer without disrupting the connection. Returns number of logs cleared.",
837
+ inputSchema: z.object({}),
838
+ }, async () => {
789
839
  try {
790
840
  let clearedCount = 0;
791
841
  let transport = "websocket";
@@ -837,15 +887,18 @@ class LocalFigmaConsoleMCP {
837
887
  }
838
888
  });
839
889
  // 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 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. Switching to another file (or lock: false) releases the pin; it also releases automatically if the pinned file disconnects.", {
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."),
890
+ server.registerTool("figma_navigate", {
891
+ 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.",
892
+ inputSchema: z.object({
893
+ url: z
894
+ .string()
895
+ .url()
896
+ .describe("Figma URL to navigate to (e.g., https://www.figma.com/design/abc123)"),
897
+ lock: z
898
+ .boolean()
899
+ .optional()
900
+ .describe("Pin this file as the active target so connections, reconnects, and user interaction in other files won't move it. Defaults to false."),
901
+ }),
849
902
  }, async ({ url, lock }) => {
850
903
  try {
851
904
  // Phase 3: local mode now talks to Figma exclusively through the
@@ -910,7 +963,7 @@ class LocalFigmaConsoleMCP {
910
963
  isActive: f.fileKey === requestedFileKey,
911
964
  })),
912
965
  message: `Switched active file to "${targetFile.fileName}". All tools now target this file.` +
913
- (lock ? " Target is pinned — it won't move until you switch files or the plugin disconnects." : ""),
966
+ (lock ? " Target is pinned — it won't move until you switch files or unlock." : ""),
914
967
  ai_instruction: "Active file has been switched via WebSocket. All subsequent tool calls (figma_get_variables, figma_execute, etc.) will target this file. No browser navigation needed." +
915
968
  (lock ? " The target is now pinned to this file." : ""),
916
969
  }),
@@ -919,14 +972,28 @@ class LocalFigmaConsoleMCP {
919
972
  };
920
973
  }
921
974
  }
975
+ // Pinning a file that isn't open holds commands for it, so they can't
976
+ // fall through to whichever file is active. Without lock the target
977
+ // stays where it was; either way this is an error the agent must see.
978
+ const heldFor = lock && requestedFileKey ? requestedFileKey : null;
979
+ if (heldFor)
980
+ this.wsServer.holdPin(heldFor);
981
+ const stillActive = heldFor ? null : this.wsServer.getConnectedFileInfo();
922
982
  return {
983
+ isError: true,
923
984
  content: [
924
985
  {
925
986
  type: "text",
926
987
  text: JSON.stringify({
927
988
  status: "websocket_file_not_connected",
989
+ code: "FILE_NOT_CONNECTED",
990
+ target: heldFor
991
+ ? `Pinned to ${requestedFileKey}, which isn't connected: commands without a fileKey are refused until it connects or you switch files.`
992
+ : stillActive
993
+ ? `Unchanged: tools still target "${stillActive.fileName}" (${stillActive.fileKey}), not the requested file.`
994
+ : "No file is active.",
928
995
  timestamp: Date.now(),
929
- connectedFile: fileInfo
996
+ connectedFile: !heldFor && fileInfo
930
997
  ? {
931
998
  fileName: fileInfo.fileName,
932
999
  fileKey: fileInfo.fileKey,
@@ -974,8 +1041,11 @@ class LocalFigmaConsoleMCP {
974
1041
  }
975
1042
  });
976
1043
  // Tool 7: Get Status (with setup validation)
977
- 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.", {
978
- 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."),
1044
+ server.registerTool("figma_get_status", {
1045
+ 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.",
1046
+ inputSchema: z.object({
1047
+ 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
+ }),
979
1049
  }, async ({ probe }) => {
980
1050
  try {
981
1051
  // Check WebSocket availability
@@ -1080,6 +1150,11 @@ class LocalFigmaConsoleMCP {
1080
1150
  bundledPluginVersion: getBundledPluginVersion(),
1081
1151
  port: this.wsActualPort ? String(this.wsActualPort) : null,
1082
1152
  preferredPort: String(this.wsPreferredPort),
1153
+ ...(this.wsServer?.loopbackFallback
1154
+ ? {
1155
+ loopbackFallback: `IPv6 loopback (::1) wasn't accepting connections, so the bridge listens on ${this.wsServer.loopbackFallback}. On a Mac this usually means it has run out of local ports (closed connections stuck after a long uptime); restarting the Mac fixes it.`,
1156
+ }
1157
+ : {}),
1083
1158
  portFallbackUsed: this.wsActualPort !== null && this.wsActualPort !== this.wsPreferredPort,
1084
1159
  startupError: this.wsStartupError ? {
1085
1160
  code: this.wsStartupError.code,
@@ -1201,7 +1276,10 @@ class LocalFigmaConsoleMCP {
1201
1276
  // CONNECTION MANAGEMENT TOOLS
1202
1277
  // ============================================================================
1203
1278
  // Tool: Force reconnect to Figma Desktop
1204
- server.tool("figma_reconnect", "Force a complete reconnection to Figma Desktop. Use when connection seems stale or after switching files.", {}, async () => {
1279
+ server.registerTool("figma_reconnect", {
1280
+ description: "Force a complete reconnection to Figma Desktop. Use when connection seems stale or after switching files.",
1281
+ inputSchema: z.object({}),
1282
+ }, async () => {
1205
1283
  try {
1206
1284
  // figma_reconnect is informational in WebSocket-only mode — the
1207
1285
  // plugin handles its own reconnect logic. A TCP-open socket is not
@@ -1284,12 +1362,15 @@ class LocalFigmaConsoleMCP {
1284
1362
  // REAL-TIME AWARENESS TOOLS (WebSocket-only)
1285
1363
  // ============================================================================
1286
1364
  // Tool: Get current user selection in Figma
1287
- 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.", {
1288
- verbose: z
1289
- .boolean()
1290
- .optional()
1291
- .default(false)
1292
- .describe("If true, fetches additional details (fills, strokes, styles) for each selected node via figma_execute"),
1365
+ server.registerTool("figma_get_selection", {
1366
+ 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.",
1367
+ inputSchema: z.object({
1368
+ verbose: z
1369
+ .boolean()
1370
+ .optional()
1371
+ .default(false)
1372
+ .describe("If true, fetches additional details (fills, strokes, styles) for each selected node via figma_execute"),
1373
+ }),
1293
1374
  }, async ({ verbose }) => {
1294
1375
  try {
1295
1376
  const selection = this.wsServer?.getCurrentSelection() ?? null;
@@ -1377,20 +1458,23 @@ class LocalFigmaConsoleMCP {
1377
1458
  }
1378
1459
  });
1379
1460
  // Tool: Get recent design changes
1380
- 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.", {
1381
- since: z
1382
- .number()
1383
- .optional()
1384
- .describe("Only return changes after this Unix timestamp (ms). Useful for incremental polling."),
1385
- count: z
1386
- .number()
1387
- .optional()
1388
- .describe("Maximum number of change events to return (chronological order, oldest to newest; returns the last N events)"),
1389
- clear: z
1390
- .boolean()
1391
- .optional()
1392
- .default(false)
1393
- .describe("Clear the change buffer after reading. Set to true for polling workflows."),
1461
+ server.registerTool("figma_get_design_changes", {
1462
+ 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.",
1463
+ inputSchema: z.object({
1464
+ since: z
1465
+ .number()
1466
+ .optional()
1467
+ .describe("Only return changes after this Unix timestamp (ms). Useful for incremental polling."),
1468
+ count: z
1469
+ .number()
1470
+ .optional()
1471
+ .describe("Maximum number of change events to return (chronological order, oldest to newest; returns the last N events)"),
1472
+ clear: z
1473
+ .boolean()
1474
+ .optional()
1475
+ .default(false)
1476
+ .describe("Clear the change buffer after reading. Set to true for polling workflows."),
1477
+ }),
1394
1478
  }, async ({ since, count, clear }) => {
1395
1479
  try {
1396
1480
  if (!this.wsServer?.isClientConnected()) {
@@ -1454,7 +1538,10 @@ class LocalFigmaConsoleMCP {
1454
1538
  }
1455
1539
  });
1456
1540
  // Tool: List all open files connected via WebSocket
1457
- 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 () => {
1541
+ server.registerTool("figma_list_open_files", {
1542
+ 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.",
1543
+ inputSchema: z.object({}),
1544
+ }, async () => {
1458
1545
  try {
1459
1546
  if (!this.wsServer?.isClientConnected()) {
1460
1547
  return {
@@ -1471,6 +1558,7 @@ class LocalFigmaConsoleMCP {
1471
1558
  const connectedFiles = this.wsServer.getConnectedFiles();
1472
1559
  const activeFileKey = this.wsServer.getActiveFileKey();
1473
1560
  const targetLocked = this.wsServer.isTargetLocked();
1561
+ const heldPin = this.wsServer.getHeldPin();
1474
1562
  return {
1475
1563
  content: [{
1476
1564
  type: "text",
@@ -1478,6 +1566,12 @@ class LocalFigmaConsoleMCP {
1478
1566
  transport: "websocket",
1479
1567
  activeFileKey,
1480
1568
  targetLocked,
1569
+ ...(heldPin
1570
+ ? {
1571
+ pinnedFileNotConnected: heldPin,
1572
+ warning: heldPinStatusWarning(heldPin),
1573
+ }
1574
+ : {}),
1481
1575
  files: connectedFiles.map(f => ({
1482
1576
  fileName: f.fileName,
1483
1577
  fileKey: f.fileKey,
@@ -1671,12 +1765,15 @@ class LocalFigmaConsoleMCP {
1671
1765
  // (Previously interleaved with write tools in local.ts; restored after the
1672
1766
  // Phase-2 write-tools dedupe excised them along with the surrounding writes.)
1673
1767
  // ============================================================================
1674
- 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.", {
1675
- forceRefresh: z
1676
- .boolean()
1677
- .optional()
1678
- .default(false)
1679
- .describe("Force refresh the cached data (use sparingly - extraction can take minutes for large files)"),
1768
+ server.registerTool("figma_get_design_system_summary", {
1769
+ 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.",
1770
+ inputSchema: z.object({
1771
+ forceRefresh: z
1772
+ .boolean()
1773
+ .optional()
1774
+ .default(false)
1775
+ .describe("Force refresh the cached data (use sparingly - extraction can take minutes for large files)"),
1776
+ }),
1680
1777
  }, async ({ forceRefresh }) => {
1681
1778
  try {
1682
1779
  const { DesignSystemManifestCache, createEmptyManifest, figmaColorToHex, getCategories, getTokenSummary, } = await import("./core/design-system-manifest.js");
@@ -1871,38 +1968,41 @@ class LocalFigmaConsoleMCP {
1871
1968
  }
1872
1969
  });
1873
1970
  // Tool 2: Search Components (~3000 tokens response max, paginated)
1874
- 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.
1971
+ server.registerTool("figma_search_components", {
1972
+ 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.
1875
1973
 
1876
1974
  **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.
1877
1975
 
1878
- Without libraryFileKey/libraryFileUrl, searches the currently open file (local components via Plugin API).`, {
1879
- query: z
1880
- .string()
1881
- .optional()
1882
- .default("")
1883
- .describe("Search query to match component names or descriptions"),
1884
- category: z
1885
- .string()
1886
- .optional()
1887
- .describe("Filter by category (e.g., 'Button', 'Input', 'Card')"),
1888
- libraryFileKey: z
1889
- .string()
1890
- .optional()
1891
- .describe("File key of a published library to search in (for cross-file library access). Overrides local search."),
1892
- libraryFileUrl: z
1893
- .string()
1894
- .optional()
1895
- .describe("URL of a published library file to search in (e.g., https://www.figma.com/design/abc123/...). Alternative to libraryFileKey."),
1896
- limit: z
1897
- .number()
1898
- .optional()
1899
- .default(10)
1900
- .describe("Maximum results to return (default: 10, max: 25)"),
1901
- offset: z
1902
- .number()
1903
- .optional()
1904
- .default(0)
1905
- .describe("Offset for pagination"),
1976
+ Without libraryFileKey/libraryFileUrl, searches the currently open file (local components via Plugin API).`,
1977
+ inputSchema: z.object({
1978
+ query: z
1979
+ .string()
1980
+ .optional()
1981
+ .default("")
1982
+ .describe("Search query to match component names or descriptions"),
1983
+ category: z
1984
+ .string()
1985
+ .optional()
1986
+ .describe("Filter by category (e.g., 'Button', 'Input', 'Card')"),
1987
+ libraryFileKey: z
1988
+ .string()
1989
+ .optional()
1990
+ .describe("File key of a published library to search in (for cross-file library access). Overrides local search."),
1991
+ libraryFileUrl: z
1992
+ .string()
1993
+ .optional()
1994
+ .describe("URL of a published library file to search in (e.g., https://www.figma.com/design/abc123/...). Alternative to libraryFileKey."),
1995
+ limit: z
1996
+ .number()
1997
+ .optional()
1998
+ .default(10)
1999
+ .describe("Maximum results to return (default: 10, max: 25)"),
2000
+ offset: z
2001
+ .number()
2002
+ .optional()
2003
+ .default(0)
2004
+ .describe("Offset for pagination"),
2005
+ }),
1906
2006
  }, async ({ query, category, libraryFileKey, libraryFileUrl, limit, offset }) => {
1907
2007
  try {
1908
2008
  // Determine if this is a library search or local search
@@ -2093,15 +2193,18 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2093
2193
  }
2094
2194
  });
2095
2195
  // Tool 3: Get Component Details (~500 tokens per component)
2096
- 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.", {
2097
- componentKey: z
2098
- .string()
2099
- .optional()
2100
- .describe("The component key (preferred for exact match)"),
2101
- componentName: z
2102
- .string()
2103
- .optional()
2104
- .describe("The component name (used if key not provided)"),
2196
+ server.registerTool("figma_get_component_details", {
2197
+ 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.",
2198
+ inputSchema: z.object({
2199
+ componentKey: z
2200
+ .string()
2201
+ .optional()
2202
+ .describe("The component key (preferred for exact match)"),
2203
+ componentName: z
2204
+ .string()
2205
+ .optional()
2206
+ .describe("The component name (used if key not provided)"),
2207
+ }),
2105
2208
  }, async ({ componentKey, componentName }) => {
2106
2209
  try {
2107
2210
  if (!componentKey && !componentName) {
@@ -2203,21 +2306,24 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2203
2306
  }
2204
2307
  });
2205
2308
  // Tool 4: Get Token Values (~2000 tokens response max)
2206
- 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.", {
2207
- type: z
2208
- .enum(["colors", "spacing", "all"])
2209
- .optional()
2210
- .default("all")
2211
- .describe("Type of tokens to retrieve"),
2212
- filter: z
2213
- .string()
2214
- .optional()
2215
- .describe("Filter token names (e.g., 'primary' to get all primary colors)"),
2216
- limit: z
2217
- .number()
2218
- .optional()
2219
- .default(50)
2220
- .describe("Maximum tokens to return (default: 50)"),
2309
+ server.registerTool("figma_get_token_values", {
2310
+ description: "Get actual values for design tokens (colors, spacing, etc). Use after figma_get_design_system_summary to get specific token values for implementation.",
2311
+ inputSchema: z.object({
2312
+ type: z
2313
+ .enum(["colors", "spacing", "all"])
2314
+ .optional()
2315
+ .default("all")
2316
+ .describe("Type of tokens to retrieve"),
2317
+ filter: z
2318
+ .string()
2319
+ .optional()
2320
+ .describe("Filter token names (e.g., 'primary' to get all primary colors)"),
2321
+ limit: z
2322
+ .number()
2323
+ .optional()
2324
+ .default(50)
2325
+ .describe("Maximum tokens to return (default: 50)"),
2326
+ }),
2221
2327
  }, async ({ type, filter, limit }) => {
2222
2328
  try {
2223
2329
  // Auto-load design system cache if needed
@@ -2296,7 +2402,8 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2296
2402
  }
2297
2403
  });
2298
2404
  // Tool 5: Instantiate Component
2299
- server.tool("figma_get_library_components", `Discover published components from a shared/team library file.
2405
+ server.registerTool("figma_get_library_components", {
2406
+ description: `Discover published components from a shared/team library file.
2300
2407
 
2301
2408
  **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.
2302
2409
 
@@ -2309,34 +2416,36 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2309
2416
 
2310
2417
  **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.
2311
2418
 
2312
- **NOTE:** Requires FIGMA_ACCESS_TOKEN to be set (uses the Figma REST API to read the library file).`, {
2313
- libraryFileUrl: z
2314
- .string()
2315
- .optional()
2316
- .describe("The URL of the library file (e.g., https://www.figma.com/design/abc123/My-Design-System). Either this or libraryFileKey is required."),
2317
- libraryFileKey: z
2318
- .string()
2319
- .optional()
2320
- .describe("The file key of the library file (e.g., 'abc123'). Either this or libraryFileUrl is required."),
2321
- query: z
2322
- .string()
2323
- .optional()
2324
- .describe("Search query to filter components by name (e.g., 'Button', 'Card'). Leave empty to get all components."),
2325
- limit: z
2326
- .number()
2327
- .optional()
2328
- .default(25)
2329
- .describe("Maximum results to return (default: 25, max: 100)"),
2330
- offset: z
2331
- .number()
2332
- .optional()
2333
- .default(0)
2334
- .describe("Offset for pagination"),
2335
- includeVariants: z
2336
- .boolean()
2337
- .optional()
2338
- .default(false)
2339
- .describe("Include individual variant components (default: false, only returns component sets)"),
2419
+ **NOTE:** Requires FIGMA_ACCESS_TOKEN to be set (uses the Figma REST API to read the library file).`,
2420
+ inputSchema: z.object({
2421
+ libraryFileUrl: z
2422
+ .string()
2423
+ .optional()
2424
+ .describe("The URL of the library file (e.g., https://www.figma.com/design/abc123/My-Design-System). Either this or libraryFileKey is required."),
2425
+ libraryFileKey: z
2426
+ .string()
2427
+ .optional()
2428
+ .describe("The file key of the library file (e.g., 'abc123'). Either this or libraryFileUrl is required."),
2429
+ query: z
2430
+ .string()
2431
+ .optional()
2432
+ .describe("Search query to filter components by name (e.g., 'Button', 'Card'). Leave empty to get all components."),
2433
+ limit: z
2434
+ .number()
2435
+ .optional()
2436
+ .default(25)
2437
+ .describe("Maximum results to return (default: 25, max: 100)"),
2438
+ offset: z
2439
+ .number()
2440
+ .optional()
2441
+ .default(0)
2442
+ .describe("Offset for pagination"),
2443
+ includeVariants: z
2444
+ .boolean()
2445
+ .optional()
2446
+ .default(false)
2447
+ .describe("Include individual variant components (default: false, only returns component sets)"),
2448
+ }),
2340
2449
  }, async ({ libraryFileUrl, libraryFileKey, query, limit, offset, includeVariants, }) => {
2341
2450
  try {
2342
2451
  // Resolve file key from URL or direct key
@@ -2564,8 +2673,7 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2564
2673
  // ============================================================================
2565
2674
  // Tool: Set Node Description
2566
2675
  // Register all write/manipulation tools (figma_execute, variable CRUD, node mutations,
2567
- // design-token setup, accessibility audits, etc.). Sourced from src/core/write-tools.ts
2568
- // so local mode and cloud mode share the same 30 implementations — no risk of drift.
2676
+ // design-token setup, accessibility audits, etc.), sourced from src/core/write-tools.ts.
2569
2677
  registerWriteTools(server, (fileKey) => this.getDesktopConnector(fileKey), {
2570
2678
  onVariableWrite: () => this.invalidateVariablesCache(),
2571
2679
  });
@@ -2953,6 +3061,15 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2953
3061
  }
2954
3062
  logger.info("All MCP tools registered successfully (including write operations)");
2955
3063
  }
3064
+ /**
3065
+ * A fresh, fully registered server: one per MCP_HTTP_PORT request (either
3066
+ * era), or for a stdio connection that serveStdio re-pins to another era.
3067
+ */
3068
+ createRequestServer() {
3069
+ const server = new IdentifiedMcpServer({ name: "Figma Console MCP (Local)", version: SERVER_VERSION }, { instructions: MCP_SERVER_INSTRUCTIONS });
3070
+ this.registerTools(server);
3071
+ return server;
3072
+ }
2956
3073
  /**
2957
3074
  * Start an optional Streamable HTTP MCP server.
2958
3075
  * Only starts if MCP_HTTP_PORT env var is set. This provides an HTTP-based
@@ -2968,30 +3085,65 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2968
3085
  logger.warn({ portStr }, "Invalid MCP_HTTP_PORT, skipping HTTP server");
2969
3086
  return;
2970
3087
  }
3088
+ // Both protocol eras are served at /mcp, each by a fresh server per request
3089
+ // (IdentifiedMcpServer: every handler gets `_mcp` tagging and
3090
+ // `[figma-console-mcp]` error prefixing):
3091
+ // - 2026-07-28 requests (per-request `_meta`, no initialize) go to the SDK's
3092
+ // createMcpHandler. `legacy: "reject"` keeps its own stateless fallback
3093
+ // from ever answering 2025-era traffic, which is routed below instead.
3094
+ // - 2025-era requests keep this endpoint's stateless Streamable HTTP
3095
+ // contract: no session id, one transport per request.
3096
+ const reportModernError = (error) => logger.warn({ err: error.message }, "HTTP MCP (2026-07-28) request error");
3097
+ this.modernHttpHandler = createMcpHandler(() => this.createRequestServer(), {
3098
+ legacy: "reject",
3099
+ onerror: reportModernError,
3100
+ maxRequestBodySize: MAX_HTTP_BODY_BYTES,
3101
+ });
3102
+ const serveModern = toNodeHandler(this.modernHttpHandler, {
3103
+ onerror: reportModernError,
3104
+ maxRequestBodySize: MAX_HTTP_BODY_BYTES,
3105
+ });
2971
3106
  this.httpServer = createServer(async (req, res) => {
2972
- // Before any routing: DNS-rebinding and cross-site requests get a 403.
3107
+ // Before any routing — and so before the era split, for both eras:
3108
+ // DNS-rebinding and cross-site requests get a 403.
2973
3109
  if (!guardLocalHttpRequest(req, res, port))
2974
3110
  return;
2975
3111
  const url = new URL(req.url ?? "/", `http://localhost:${port}`);
2976
3112
  if (url.pathname === "/mcp") {
2977
3113
  try {
2978
- // The MCP SDK enforces one-request-per-transport in stateless mode
2979
- // ("Stateless transport cannot be reused across requests"), so we
2980
- // create a fresh transport + server per request — same pattern as
2981
- // the Cloudflare entry point (src/index.ts).
2982
- const transport = new StreamableHTTPServerTransport({
3114
+ // Only a POST carries a JSON-RPC body to classify. GET/DELETE are
3115
+ // 2025-era verbs; the stateless transport answers them.
3116
+ let body;
3117
+ if (req.method === "POST") {
3118
+ try {
3119
+ body = await readJsonBody(req);
3120
+ }
3121
+ catch (err) {
3122
+ const e = err;
3123
+ if (!res.headersSent) {
3124
+ // Connection: close — an oversized body may still be arriving.
3125
+ res.writeHead(e.status ?? 400, { "Content-Type": "application/json", Connection: "close" });
3126
+ res.end(JSON.stringify({ jsonrpc: "2.0", error: { code: e.code ?? -32000, message: e.message }, id: null }));
3127
+ }
3128
+ return;
3129
+ }
3130
+ // The SDK's own era predicate, so routing can't disagree with createMcpHandler.
3131
+ if (!(await isLegacyRequest(await toWebRequest(req, body), body))) {
3132
+ await serveModern(req, res, body);
3133
+ return;
3134
+ }
3135
+ }
3136
+ // 2025 era. The SDK enforces one-request-per-transport in stateless
3137
+ // mode, so each request gets a fresh transport + server.
3138
+ const transport = new NodeStreamableHTTPServerTransport({
2983
3139
  sessionIdGenerator: undefined,
2984
3140
  });
2985
- const reqServer = new McpServer({ name: "Figma Console MCP (Local)", version: SERVER_VERSION }, { instructions: MCP_SERVER_INSTRUCTIONS });
2986
- // Must wrap BEFORE registerTools() so every registered handler gets
2987
- // `_mcp` tagging and `[figma-console-mcp]` error prefixing.
2988
- wrapServerForIdentity(reqServer);
2989
- this.registerTools(reqServer);
3141
+ const reqServer = this.createRequestServer();
2990
3142
  await reqServer.connect(transport);
2991
3143
  res.once("close", () => {
2992
3144
  reqServer.close().catch(() => { });
2993
3145
  });
2994
- await transport.handleRequest(req, res);
3146
+ await transport.handleRequest(req, res, body);
2995
3147
  }
2996
3148
  catch (error) {
2997
3149
  logger.error({ error }, "Error handling HTTP MCP request");
@@ -3217,10 +3369,22 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
3217
3369
  if (this.mcpHttpPort && this.wsActualPort) {
3218
3370
  setAdvertisedMcpHttpPort(this.wsActualPort, this.mcpHttpPort);
3219
3371
  }
3220
- // Create stdio transport
3221
- const transport = new StdioServerTransport();
3222
- // Connect server to transport
3223
- await this.server.connect(transport);
3372
+ // Serve stdio for both protocol eras: 2025-era clients (initialize
3373
+ // handshake) and 2026-07-28 clients (server/discover + per-request
3374
+ // _meta). serveStdio usually calls the factory once, but calls it again
3375
+ // when a connection opens with a server/discover probe and then falls
3376
+ // back to initialize; it discards the probe's instance, which is pinned
3377
+ // to the modern era, so a re-pin must get a fresh server.
3378
+ // On stdin EOF the SDK closes the connection but never exits the
3379
+ // process: with MCP_HTTP_PORT active (and the WebSocket bridge
3380
+ // listening) it keeps serving.
3381
+ let stdioServerHandedOut = false;
3382
+ serveStdio(() => {
3383
+ if (stdioServerHandedOut)
3384
+ return this.createRequestServer();
3385
+ stdioServerHandedOut = true;
3386
+ return this.server;
3387
+ }, { onerror: (error) => logger.error({ error }, "stdio transport error") });
3224
3388
  logger.info("MCP server started successfully on stdio transport");
3225
3389
  // 🆕 AUTO-CONNECT: Start monitoring immediately if Figma Desktop is available
3226
3390
  // This enables "get latest logs" workflow without requiring manual setup
@@ -3256,6 +3420,10 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
3256
3420
  if (this.wsActualPort) {
3257
3421
  unadvertisePort(this.wsActualPort);
3258
3422
  }
3423
+ if (this.modernHttpHandler) {
3424
+ await this.modernHttpHandler.close();
3425
+ this.modernHttpHandler = null;
3426
+ }
3259
3427
  if (this.httpServer) {
3260
3428
  this.httpServer.close();
3261
3429
  this.httpServer = null;