@muloka/figma-console-mcp 0.6.1 → 0.6.3

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 (54) hide show
  1. package/README.md +12 -1
  2. package/dist/core/design-system-tools.d.ts.map +1 -1
  3. package/dist/core/design-system-tools.js +8 -6
  4. package/dist/core/design-system-tools.js.map +1 -1
  5. package/dist/core/figma-tools.d.ts.map +1 -1
  6. package/dist/core/figma-tools.js +74 -16
  7. package/dist/core/figma-tools.js.map +1 -1
  8. package/dist/core/identity.d.ts +30 -6
  9. package/dist/core/identity.d.ts.map +1 -1
  10. package/dist/core/identity.js +60 -10
  11. package/dist/core/identity.js.map +1 -1
  12. package/dist/core/library-tools.d.ts +5 -1
  13. package/dist/core/library-tools.d.ts.map +1 -1
  14. package/dist/core/library-tools.js +35 -11
  15. package/dist/core/library-tools.js.map +1 -1
  16. package/dist/core/logger.d.ts.map +1 -1
  17. package/dist/core/logger.js +5 -2
  18. package/dist/core/logger.js.map +1 -1
  19. package/dist/core/port-discovery.d.ts +7 -3
  20. package/dist/core/port-discovery.d.ts.map +1 -1
  21. package/dist/core/port-discovery.js +49 -7
  22. package/dist/core/port-discovery.js.map +1 -1
  23. package/dist/core/stdin-lifecycle.d.ts +16 -0
  24. package/dist/core/stdin-lifecycle.d.ts.map +1 -0
  25. package/dist/core/stdin-lifecycle.js +32 -0
  26. package/dist/core/stdin-lifecycle.js.map +1 -0
  27. package/dist/core/tokens-tools.d.ts +6 -0
  28. package/dist/core/tokens-tools.d.ts.map +1 -1
  29. package/dist/core/tokens-tools.js +12 -7
  30. package/dist/core/tokens-tools.js.map +1 -1
  31. package/dist/core/tool-annotations.d.ts +64 -0
  32. package/dist/core/tool-annotations.d.ts.map +1 -0
  33. package/dist/core/tool-annotations.js +235 -0
  34. package/dist/core/tool-annotations.js.map +1 -0
  35. package/dist/core/variables-cache.d.ts +45 -0
  36. package/dist/core/variables-cache.d.ts.map +1 -0
  37. package/dist/core/variables-cache.js +90 -0
  38. package/dist/core/variables-cache.js.map +1 -0
  39. package/dist/core/websocket-connector.d.ts.map +1 -1
  40. package/dist/core/websocket-connector.js +14 -1
  41. package/dist/core/websocket-connector.js.map +1 -1
  42. package/dist/core/websocket-server.d.ts +16 -0
  43. package/dist/core/websocket-server.d.ts.map +1 -1
  44. package/dist/core/websocket-server.js +37 -0
  45. package/dist/core/websocket-server.js.map +1 -1
  46. package/dist/core/write-tools.d.ts +1 -1
  47. package/dist/core/write-tools.d.ts.map +1 -1
  48. package/dist/core/write-tools.js +37 -12
  49. package/dist/core/write-tools.js.map +1 -1
  50. package/dist/local.d.ts +4 -0
  51. package/dist/local.d.ts.map +1 -1
  52. package/dist/local.js +64 -25
  53. package/dist/local.js.map +1 -1
  54. package/package.json +1 -1
package/dist/local.d.ts CHANGED
@@ -23,6 +23,7 @@ declare class LocalFigmaConsoleMCP {
23
23
  private wsStartupError;
24
24
  /** The port the WebSocket server actually bound to (may differ from preferred if fallback occurred) */
25
25
  private wsActualPort;
26
+ private unregisterPortCleanup;
26
27
  /** The preferred port requested (from env var or default) */
27
28
  private wsPreferredPort;
28
29
  /** Stops the periodic background reaper (set once the WS port is bound) */
@@ -91,6 +92,7 @@ declare class LocalFigmaConsoleMCP {
91
92
  /**
92
93
  * A fresh, fully registered server: one per MCP_HTTP_PORT request (either
93
94
  * era), or for a stdio connection that serveStdio re-pins to another era.
95
+ * Only stdio servers cap oversized results.
94
96
  */
95
97
  private createRequestServer;
96
98
  /**
@@ -100,6 +102,8 @@ declare class LocalFigmaConsoleMCP {
100
102
  * clients (Cursor, web UIs, etc.).
101
103
  */
102
104
  private startHttpServer;
105
+ /** True once the Streamable HTTP listener is up (MCP_HTTP_PORT set and listen succeeded). */
106
+ isHttpServing(): boolean;
103
107
  /**
104
108
  * Start the MCP server
105
109
  */
@@ -1 +1 @@
1
- {"version":3,"file":"local.d.ts","sourceRoot":"","sources":["../src/local.ts"],"names":[],"mappings":";AAEA;;;;;;;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AO,CAAC,IAAI,CAAC;CAyC/B;AAyGD,OAAO,EAAE,oBAAoB,EAAE,CAAC"}
package/dist/local.js CHANGED
@@ -24,6 +24,7 @@ import { realpathSync, existsSync, readFileSync, mkdirSync, copyFileSync, writeF
24
24
  import { homedir } from "os";
25
25
  import { getConfig } from "./core/config.js";
26
26
  import { createChildLogger } from "./core/logger.js";
27
+ import { onStdinClosed } from "./core/stdin-lifecycle.js";
27
28
  import { FigmaAPI, extractFileKey, extractFigmaUrlInfo, formatVariables, } from "./core/figma-api.js";
28
29
  import { registerFigmaAPITools } from "./core/figma-tools.js";
29
30
  import { registerDesignCodeTools } from "./core/design-code-tools.js";
@@ -37,22 +38,28 @@ import { registerAccessibilityTools } from "./core/accessibility-tools.js";
37
38
  import { registerDiagnoseTool } from "./core/diagnose-tool.js";
38
39
  import { registerWriteTools } from "./core/write-tools.js";
39
40
  import { registerTokensTools } from "./core/tokens-tools.js";
40
- import { withToolIdentity } from "./core/identity.js";
41
+ import { MAX_TOOL_RESPONSE_BYTES, withToolIdentity } from "./core/identity.js";
41
42
  import { PACKAGE_ROOT } from "./core/resolve-package-root.js";
42
43
  import { FigmaWebSocketServer, getBundledPluginVersion, getBundledForkPluginRevision, heldPinStatusWarning, } from "./core/websocket-server.js";
43
44
  import { WebSocketConnector } from "./core/websocket-connector.js";
44
45
  import { invalidateAfterVariableWrite } from "./core/design-system-manifest.js";
46
+ import { VariablesCache, cacheGeneration, setCacheIfCurrent } from "./core/variables-cache.js";
45
47
  import { DEFAULT_WS_PORT, getPortRange, advertisePort, unadvertisePort, registerPortCleanup, startPeriodicReaper, discoverActiveInstances, cleanupStalePortFiles, cleanupOrphanedProcesses, evictOldestInstance, refreshPortAdvertisement, setAdvertisedMcpHttpPort, HEARTBEAT_INTERVAL_MS, } from "./core/port-discovery.js";
46
48
  import { registerTokenBrowserApp } from "./apps/token-browser/server.js";
47
49
  import { registerDesignSystemDashboardApp } from "./apps/design-system-dashboard/server.js";
48
50
  import { registerFigJamTools } from "./core/figjam-tools.js";
49
51
  import { registerSlidesTools } from "./core/slides-tools.js";
50
52
  import { registerSlotTools } from "./core/slot-tools.js";
53
+ import { applyToolAnnotations } from "./core/tool-annotations.js";
51
54
  const logger = createChildLogger({ component: "local-server" });
52
55
  // Every McpServer this process builds (stdio and per-request HTTP) stamps tool
53
56
  // responses and thrown errors with our MCP identity, so LLMs can attribute
54
57
  // output unambiguously when several Figma-related MCPs are connected.
55
58
  const IdentifiedMcpServer = withToolIdentity(McpServer);
59
+ // stdio additionally withholds a result above MAX_TOOL_RESPONSE_BYTES: an MCP
60
+ // client drops the connection when one message gets too large. HTTP is not
61
+ // capped (IdentifiedMcpServer).
62
+ const StdioMcpServer = withToolIdentity(McpServer, { maxResponseBytes: MAX_TOOL_RESPONSE_BYTES });
56
63
  /** Largest JSON-RPC body the MCP_HTTP_PORT endpoint reads (both protocol eras). */
57
64
  const MAX_HTTP_BODY_BYTES = 4 * 1024 * 1024;
58
65
  /** Read and parse a JSON request body, refusing oversized or malformed ones. */
@@ -229,6 +236,7 @@ class LocalFigmaConsoleMCP {
229
236
  this.wsStartupError = null;
230
237
  /** The port the WebSocket server actually bound to (may differ from preferred if fallback occurred) */
231
238
  this.wsActualPort = null;
239
+ this.unregisterPortCleanup = null;
232
240
  /** The preferred port requested (from env var or default) */
233
241
  this.wsPreferredPort = DEFAULT_WS_PORT;
234
242
  /** Stops the periodic background reaper (set once the WS port is bound) */
@@ -244,10 +252,15 @@ class LocalFigmaConsoleMCP {
244
252
  this.config = getConfig();
245
253
  // In-memory cache for variables data to avoid MCP token limits
246
254
  // Maps fileKey -> {data, timestamp}
247
- this.variablesCache = new Map();
255
+ //
256
+ // Every invalidation (a write's clear(), the documentChange and
257
+ // fileDisconnected deletes) also ends in-flight read sharing: a read that
258
+ // starts after the invalidation must not join a read that started before
259
+ // it, or it would store pre-change data under the new generation.
260
+ this.variablesCache = new VariablesCache(() => this.wsServer?.forgetSharedReads());
248
261
  /** Stable plugin directory path (set during startup) */
249
262
  this.stablePluginPath = null;
250
- this.server = new IdentifiedMcpServer({
263
+ this.server = new StdioMcpServer({
251
264
  name: "Figma Console MCP (Local)",
252
265
  version: SERVER_VERSION,
253
266
  }, {
@@ -2626,7 +2639,9 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2626
2639
  // popular styling methods (DTCG canonical — legacy + 2025.10 dialects —
2627
2640
  // plus CSS/Tailwind/SCSS/TS/JSON/Style Dictionary/Tokens Studio, all
2628
2641
  // derived from a single internal token model).
2629
- registerTokensTools(server, () => this.getDesktopConnector());
2642
+ registerTokensTools(server, () => this.getDesktopConnector(), {
2643
+ onVariableWrite: () => this.invalidateVariablesCache(),
2644
+ });
2630
2645
  // Register Figma API tools (Tools 8-11)
2631
2646
  registerFigmaAPITools(server, () => this.getFigmaAPI(), () => this.getCurrentFileUrl(), this.variablesCache, // Pass cache for efficient variable queries
2632
2647
  undefined, // options (use default)
@@ -2658,7 +2673,9 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2658
2673
  registerLibraryTools(server, () => this.getFigmaAPI());
2659
2674
  // Register Library Variable Tools (Plugin-API based — list + import variables
2660
2675
  // from subscribed team libraries; works on every Figma plan, no Enterprise needed)
2661
- registerLibraryVariableTools(server, () => this.getDesktopConnector());
2676
+ registerLibraryVariableTools(server, () => this.getDesktopConnector(), {
2677
+ onVariableWrite: () => this.invalidateVariablesCache(),
2678
+ });
2662
2679
  // Register code-side accessibility scanning (axe-core + JSDOM)
2663
2680
  registerAccessibilityTools(server);
2664
2681
  // Register figma_diagnose — designer-readable health check + cross-MCP disambiguator.
@@ -2772,17 +2789,19 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2772
2789
  }
2773
2790
  // Priority 1: Try Desktop Bridge via transport-agnostic connector
2774
2791
  try {
2792
+ const startedAt = cacheGeneration(this.variablesCache);
2775
2793
  const connector = await this.getDesktopConnector();
2776
2794
  const desktopResult = await connector.readVariables(fileKey);
2777
2795
  if (desktopResult.success && desktopResult.variables) {
2778
- // Cache the desktop result
2779
- this.variablesCache.set(fileKey, {
2796
+ // Cache the desktop result, unless the cache was invalidated
2797
+ // while it was read
2798
+ setCacheIfCurrent(this.variablesCache, fileKey, {
2780
2799
  data: {
2781
2800
  variables: desktopResult.variables,
2782
2801
  variableCollections: desktopResult.variableCollections,
2783
2802
  },
2784
2803
  timestamp: Date.now(),
2785
- });
2804
+ }, startedAt);
2786
2805
  return {
2787
2806
  variables: desktopResult.variables,
2788
2807
  collections: desktopResult.variableCollections || [],
@@ -2798,16 +2817,17 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2798
2817
  }, "Desktop Bridge failed for token browser, trying REST API");
2799
2818
  }
2800
2819
  // Priority 2: Fall back to REST API (requires Enterprise plan)
2820
+ const restStartedAt = cacheGeneration(this.variablesCache);
2801
2821
  const api = await this.getFigmaAPI();
2802
2822
  const { local, localError } = await api.getAllVariables(fileKey);
2803
2823
  if (localError) {
2804
2824
  throw new Error(`Could not fetch variables. Desktop Bridge unavailable and REST API returned: ${localError}`);
2805
2825
  }
2806
- // Cache raw REST API data
2807
- this.variablesCache.set(fileKey, {
2826
+ // Cache raw REST API data, unless the cache was invalidated while it was read
2827
+ setCacheIfCurrent(this.variablesCache, fileKey, {
2808
2828
  data: local,
2809
2829
  timestamp: Date.now(),
2810
- });
2830
+ }, restStartedAt);
2811
2831
  const formatted = formatVariables(local);
2812
2832
  return {
2813
2833
  variables: formatted.variables,
@@ -2855,16 +2875,17 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2855
2875
  if (variables.length === 0) {
2856
2876
  desktopBridgeAttempted = true;
2857
2877
  try {
2878
+ const startedAt = cacheGeneration(this.variablesCache);
2858
2879
  const connector = await this.getDesktopConnector();
2859
2880
  const desktopResult = await connector.readVariables(fileKey);
2860
2881
  if (desktopResult.success && desktopResult.variables) {
2861
- this.variablesCache.set(fileKey, {
2882
+ setCacheIfCurrent(this.variablesCache, fileKey, {
2862
2883
  data: {
2863
2884
  variables: desktopResult.variables,
2864
2885
  variableCollections: desktopResult.variableCollections,
2865
2886
  },
2866
2887
  timestamp: Date.now(),
2867
- });
2888
+ }, startedAt);
2868
2889
  variables = desktopResult.variables;
2869
2890
  collections = desktopResult.variableCollections || [];
2870
2891
  variablesAvailable = true;
@@ -2886,13 +2907,14 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2886
2907
  if (variables.length === 0) {
2887
2908
  restApiAttempted = true;
2888
2909
  try {
2910
+ const startedAt = cacheGeneration(this.variablesCache);
2889
2911
  const api = await this.getFigmaAPI();
2890
2912
  const { local, localError } = await api.getAllVariables(fileKey);
2891
2913
  if (!localError && local) {
2892
- this.variablesCache.set(fileKey, {
2914
+ setCacheIfCurrent(this.variablesCache, fileKey, {
2893
2915
  data: local,
2894
2916
  timestamp: Date.now(),
2895
- });
2917
+ }, startedAt);
2896
2918
  const formatted = formatVariables(local);
2897
2919
  variables = formatted.variables;
2898
2920
  collections = formatted.collections;
@@ -3005,14 +3027,19 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
3005
3027
  () => this.getCurrentFileUrl());
3006
3028
  logger.info("MCP Apps registered (ENABLE_MCP_APPS=true)");
3007
3029
  }
3030
+ const unclassified = applyToolAnnotations(server);
3031
+ if (unclassified.length > 0)
3032
+ logger.warn({ unclassified }, "Tools registered without annotation hints");
3008
3033
  logger.info("All MCP tools registered successfully (including write operations)");
3009
3034
  }
3010
3035
  /**
3011
3036
  * A fresh, fully registered server: one per MCP_HTTP_PORT request (either
3012
3037
  * era), or for a stdio connection that serveStdio re-pins to another era.
3038
+ * Only stdio servers cap oversized results.
3013
3039
  */
3014
- createRequestServer() {
3015
- const server = new IdentifiedMcpServer({ name: "Figma Console MCP (Local)", version: SERVER_VERSION }, { instructions: MCP_SERVER_INSTRUCTIONS });
3040
+ createRequestServer(transport) {
3041
+ const ServerClass = transport === "stdio" ? StdioMcpServer : IdentifiedMcpServer;
3042
+ const server = new ServerClass({ name: "Figma Console MCP (Local)", version: SERVER_VERSION }, { instructions: MCP_SERVER_INSTRUCTIONS });
3016
3043
  this.registerTools(server);
3017
3044
  return server;
3018
3045
  }
@@ -3033,14 +3060,14 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
3033
3060
  }
3034
3061
  // Both protocol eras are served at /mcp, each by a fresh server per request
3035
3062
  // (IdentifiedMcpServer: every handler gets `_mcp` tagging and
3036
- // `[figma-console-mcp]` error prefixing):
3063
+ // `[figma-console-mcp]` error prefixing, and results are never capped):
3037
3064
  // - 2026-07-28 requests (per-request `_meta`, no initialize) go to the SDK's
3038
3065
  // createMcpHandler. `legacy: "reject"` keeps its own stateless fallback
3039
3066
  // from ever answering 2025-era traffic, which is routed below instead.
3040
3067
  // - 2025-era requests keep this endpoint's stateless Streamable HTTP
3041
3068
  // contract: no session id, one transport per request.
3042
3069
  const reportModernError = (error) => logger.warn({ err: error.message }, "HTTP MCP (2026-07-28) request error");
3043
- this.modernHttpHandler = createMcpHandler(() => this.createRequestServer(), {
3070
+ this.modernHttpHandler = createMcpHandler(() => this.createRequestServer("http"), {
3044
3071
  legacy: "reject",
3045
3072
  onerror: reportModernError,
3046
3073
  maxRequestBodySize: MAX_HTTP_BODY_BYTES,
@@ -3084,7 +3111,7 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
3084
3111
  const transport = new NodeStreamableHTTPServerTransport({
3085
3112
  sessionIdGenerator: undefined,
3086
3113
  });
3087
- const reqServer = this.createRequestServer();
3114
+ const reqServer = this.createRequestServer("http");
3088
3115
  await reqServer.connect(transport);
3089
3116
  res.once("close", () => {
3090
3117
  reqServer.close().catch(() => { });
@@ -3124,6 +3151,10 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
3124
3151
  });
3125
3152
  });
3126
3153
  }
3154
+ /** True once the Streamable HTTP listener is up (MCP_HTTP_PORT set and listen succeeded). */
3155
+ isHttpServing() {
3156
+ return this.mcpHttpPort !== null;
3157
+ }
3127
3158
  /**
3128
3159
  * Start the MCP server
3129
3160
  */
@@ -3180,7 +3211,7 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
3180
3211
  }
3181
3212
  // Advertise the port so the Figma plugin and other tools can discover us
3182
3213
  advertisePort(boundPort, wsHost);
3183
- registerPortCleanup(boundPort);
3214
+ this.unregisterPortCleanup = registerPortCleanup(boundPort);
3184
3215
  // Start heartbeat — periodically refresh the port file to prove this server is active.
3185
3216
  // Other instances use this to detect zombie processes on startup.
3186
3217
  const heartbeatPort = boundPort;
@@ -3219,7 +3250,7 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
3219
3250
  this.wsActualPort = boundPort;
3220
3251
  logger.info({ wsPort: boundPort, eviction: true }, "WebSocket bridge server started after evicting stale instance");
3221
3252
  advertisePort(boundPort, wsHost);
3222
- registerPortCleanup(boundPort);
3253
+ this.unregisterPortCleanup = registerPortCleanup(boundPort);
3223
3254
  const heartbeatPort = boundPort;
3224
3255
  this.wsHeartbeatTimer = setInterval(() => refreshPortAdvertisement(heartbeatPort), HEARTBEAT_INTERVAL_MS);
3225
3256
  this.wsHeartbeatTimer.unref();
@@ -3322,12 +3353,12 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
3322
3353
  // back to initialize; it discards the probe's instance, which is pinned
3323
3354
  // to the modern era, so a re-pin must get a fresh server.
3324
3355
  // 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.
3356
+ // process. Without HTTP, main() exits on EOF (nothing else can reach
3357
+ // this server); with MCP_HTTP_PORT active it keeps serving.
3327
3358
  let stdioServerHandedOut = false;
3328
3359
  serveStdio(() => {
3329
3360
  if (stdioServerHandedOut)
3330
- return this.createRequestServer();
3361
+ return this.createRequestServer("stdio");
3331
3362
  stdioServerHandedOut = true;
3332
3363
  return this.server;
3333
3364
  }, { onerror: (error) => logger.error({ error }, "stdio transport error") });
@@ -3365,6 +3396,8 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
3365
3396
  // Clean up port advertisement before stopping the server
3366
3397
  if (this.wsActualPort) {
3367
3398
  unadvertisePort(this.wsActualPort);
3399
+ this.unregisterPortCleanup?.();
3400
+ this.unregisterPortCleanup = null;
3368
3401
  }
3369
3402
  if (this.modernHttpHandler) {
3370
3403
  await this.modernHttpHandler.close();
@@ -3417,6 +3450,12 @@ async function main() {
3417
3450
  process.on("SIGTERM", () => { void gracefulExit(0); });
3418
3451
  // Start the server
3419
3452
  await server.start();
3453
+ // Without an HTTP transport, stdin is the only way a client reaches this
3454
+ // process: when it closes, nothing can use the server, so exit and release
3455
+ // the WebSocket port. With HTTP serving, EOF leaves the daemon running.
3456
+ if (!server.isHttpServing()) {
3457
+ onStdinClosed(() => { void gracefulExit(0); });
3458
+ }
3420
3459
  }
3421
3460
  // Run if executed directly
3422
3461
  // Note: On Windows, import.meta.url uses file:/// (3 slashes) while process.argv uses backslashes