@muloka/figma-console-mcp 0.6.3 → 0.6.5

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 (52) hide show
  1. package/README.md +12 -0
  2. package/dist/core/cache-invalidation.d.ts +30 -0
  3. package/dist/core/cache-invalidation.d.ts.map +1 -0
  4. package/dist/core/cache-invalidation.js +90 -0
  5. package/dist/core/cache-invalidation.js.map +1 -0
  6. package/dist/core/call-context.d.ts +13 -0
  7. package/dist/core/call-context.d.ts.map +1 -0
  8. package/dist/core/call-context.js +20 -0
  9. package/dist/core/call-context.js.map +1 -0
  10. package/dist/core/design-system-manifest.d.ts +37 -17
  11. package/dist/core/design-system-manifest.d.ts.map +1 -1
  12. package/dist/core/design-system-manifest.js +73 -22
  13. package/dist/core/design-system-manifest.js.map +1 -1
  14. package/dist/core/design-system-tools.js +1 -1
  15. package/dist/core/design-system-tools.js.map +1 -1
  16. package/dist/core/figma-api.d.ts +12 -0
  17. package/dist/core/figma-api.d.ts.map +1 -1
  18. package/dist/core/figma-api.js +15 -0
  19. package/dist/core/figma-api.js.map +1 -1
  20. package/dist/core/figma-tools.d.ts.map +1 -1
  21. package/dist/core/figma-tools.js +13 -26
  22. package/dist/core/figma-tools.js.map +1 -1
  23. package/dist/core/file-generations.d.ts +18 -0
  24. package/dist/core/file-generations.d.ts.map +1 -0
  25. package/dist/core/file-generations.js +44 -0
  26. package/dist/core/file-generations.js.map +1 -0
  27. package/dist/core/manifest-build.d.ts +41 -0
  28. package/dist/core/manifest-build.d.ts.map +1 -0
  29. package/dist/core/manifest-build.js +135 -0
  30. package/dist/core/manifest-build.js.map +1 -0
  31. package/dist/core/tokens/schemas.d.ts +1 -1
  32. package/dist/core/tool-annotations.js +2 -2
  33. package/dist/core/tool-annotations.js.map +1 -1
  34. package/dist/core/variables-cache.d.ts +28 -24
  35. package/dist/core/variables-cache.d.ts.map +1 -1
  36. package/dist/core/variables-cache.js +63 -35
  37. package/dist/core/variables-cache.js.map +1 -1
  38. package/dist/core/websocket-connector.d.ts.map +1 -1
  39. package/dist/core/websocket-connector.js +7 -1
  40. package/dist/core/websocket-connector.js.map +1 -1
  41. package/dist/core/websocket-server.d.ts +9 -4
  42. package/dist/core/websocket-server.d.ts.map +1 -1
  43. package/dist/core/websocket-server.js +20 -5
  44. package/dist/core/websocket-server.js.map +1 -1
  45. package/dist/core/write-tools.d.ts.map +1 -1
  46. package/dist/core/write-tools.js +152 -39
  47. package/dist/core/write-tools.js.map +1 -1
  48. package/dist/local.d.ts +1 -0
  49. package/dist/local.d.ts.map +1 -1
  50. package/dist/local.js +79 -293
  51. package/dist/local.js.map +1 -1
  52. package/package.json +1 -1
package/dist/local.js CHANGED
@@ -24,8 +24,9 @@ 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 { attachCacheInvalidation, attachWriteInvalidation } from "./core/cache-invalidation.js";
27
28
  import { onStdinClosed } from "./core/stdin-lifecycle.js";
28
- import { FigmaAPI, extractFileKey, extractFigmaUrlInfo, formatVariables, } from "./core/figma-api.js";
29
+ import { FigmaAPI, extractFileKey, extractFigmaUrlInfo, restVariablesCacheData, } from "./core/figma-api.js";
29
30
  import { registerFigmaAPITools } from "./core/figma-tools.js";
30
31
  import { registerDesignCodeTools } from "./core/design-code-tools.js";
31
32
  import { registerCommentTools } from "./core/comment-tools.js";
@@ -42,7 +43,8 @@ import { MAX_TOOL_RESPONSE_BYTES, withToolIdentity } from "./core/identity.js";
42
43
  import { PACKAGE_ROOT } from "./core/resolve-package-root.js";
43
44
  import { FigmaWebSocketServer, getBundledPluginVersion, getBundledForkPluginRevision, heldPinStatusWarning, } from "./core/websocket-server.js";
44
45
  import { WebSocketConnector } from "./core/websocket-connector.js";
45
- import { invalidateAfterVariableWrite } from "./core/design-system-manifest.js";
46
+ import { DesignSystemManifestCache, invalidateAfterVariableWrite } from "./core/design-system-manifest.js";
47
+ import { ensureManifest } from "./core/manifest-build.js";
46
48
  import { VariablesCache, cacheGeneration, setCacheIfCurrent } from "./core/variables-cache.js";
47
49
  import { DEFAULT_WS_PORT, getPortRange, advertisePort, unadvertisePort, registerPortCleanup, startPeriodicReaper, discoverActiveInstances, cleanupStalePortFiles, cleanupOrphanedProcesses, evictOldestInstance, refreshPortAdvertisement, setAdvertisedMcpHttpPort, HEARTBEAT_INTERVAL_MS, } from "./core/port-discovery.js";
48
50
  import { registerTokenBrowserApp } from "./apps/token-browser/server.js";
@@ -51,6 +53,7 @@ import { registerFigJamTools } from "./core/figjam-tools.js";
51
53
  import { registerSlidesTools } from "./core/slides-tools.js";
52
54
  import { registerSlotTools } from "./core/slot-tools.js";
53
55
  import { applyToolAnnotations } from "./core/tool-annotations.js";
56
+ import { currentCallFiles } from "./core/call-context.js";
54
57
  const logger = createChildLogger({ component: "local-server" });
55
58
  // Every McpServer this process builds (stdio and per-request HTTP) stamps tool
56
59
  // responses and thrown errors with our MCP identity, so LLMs can attribute
@@ -222,13 +225,19 @@ class LocalFigmaConsoleMCP {
222
225
  * to ensure the next figma_get_variables call returns fresh data.
223
226
  */
224
227
  invalidateVariablesCache() {
225
- // Also drops every cached design-system manifest: a variable write that
226
- // touches no node fires no documentChange, so nothing else would, and the
227
- // summary / token-value tools would serve pre-write tokens (#14).
228
- const hadVariables = this.variablesCache.size > 0;
229
- invalidateAfterVariableWrite(this.variablesCache);
230
- if (hadVariables)
231
- logger.info('Variables cache invalidated after write operation');
228
+ // Inside a tool call, clears only the files that call reached; outside
229
+ // one, every file. Also drops the design-system manifests: a variable
230
+ // write that touches no node fires no documentChange, so nothing else
231
+ // would, and the summary / token-value tools would serve pre-write
232
+ // tokens (#14).
233
+ const files = currentCallFiles();
234
+ invalidateAfterVariableWrite(this.variablesCache, this.manifestCache, files);
235
+ if (!files) {
236
+ logger.info('Caches invalidated after write operation: all files');
237
+ }
238
+ else if (files.size > 0) {
239
+ logger.info({ files: [...files] }, 'Caches invalidated after write operation');
240
+ }
232
241
  }
233
242
  constructor() {
234
243
  this.figmaAPI = null;
@@ -253,11 +262,15 @@ class LocalFigmaConsoleMCP {
253
262
  // In-memory cache for variables data to avoid MCP token limits
254
263
  // Maps fileKey -> {data, timestamp}
255
264
  //
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());
265
+ // Every invalidation also ends in-flight read sharing, for the files it
266
+ // invalidates: a read that starts after the invalidation must not join a
267
+ // read that started before it, or it would store pre-change data under the
268
+ // new generation. Writes, document changes and disconnects invalidate per
269
+ // file (a variable write outside a tool call, every file), through
270
+ // src/core/cache-invalidation.ts, and end only those files' shared reads.
271
+ this.variablesCache = new VariablesCache((fileKey) => this.wsServer?.forgetSharedReads(fileKey));
272
+ // Design-system manifests, one per file; its invalidations end shared reads the same way.
273
+ this.manifestCache = new DesignSystemManifestCache((fileKey) => this.wsServer?.forgetSharedReads(fileKey));
261
274
  /** Stable plugin directory path (set during startup) */
262
275
  this.stablePluginPath = null;
263
276
  this.server = new StdioMcpServer({
@@ -1630,122 +1643,24 @@ class LocalFigmaConsoleMCP {
1630
1643
  // These tools provide progressive disclosure of design system data
1631
1644
  // to minimize context window usage. Start with summary, then search,
1632
1645
  // then get details for specific components.
1633
- // Helper function to ensure design system cache is loaded (auto-loads if needed)
1634
- const ensureDesignSystemCache = async () => {
1635
- const { DesignSystemManifestCache, createEmptyManifest, loadManifestVariables, } = await import("./core/design-system-manifest.js");
1636
- const cache = DesignSystemManifestCache.getInstance();
1637
- const currentUrl = this.getCurrentFileUrl();
1638
- // extractFileKey is branch-aware: on /design/KEY/branch/BRANCH_KEY/…
1639
- // URLs the branch key is the effective file key — an ad-hoc regex
1640
- // here returned the main key and cached the wrong manifest for
1641
- // branch files.
1642
- const fileKey = (currentUrl ? extractFileKey(currentUrl) : null) ?? "unknown";
1643
- // Check cache first
1644
- let cacheEntry = cache.get(fileKey);
1645
- if (cacheEntry) {
1646
- return { cacheEntry, fileKey, wasLoaded: false };
1647
- }
1648
- // Need to extract fresh data - do this silently without returning an error
1649
- logger.info({ fileKey }, "Auto-loading design system cache");
1650
- const connector = await this.getDesktopConnector();
1651
- const manifest = createEmptyManifest(fileKey);
1652
- manifest.fileUrl = currentUrl || undefined;
1653
- // Get variables (tokens). A failed read is reported, and the manifest
1654
- // is not cached, so a transient plugin error can't serve "0 tokens"
1655
- // for the full TTL.
1656
- const variablesFetchError = await loadManifestVariables(manifest, () => connector.readVariables(fileKey));
1657
- if (variablesFetchError) {
1658
- logger.warn({ error: variablesFetchError }, "Could not fetch variables during auto-load");
1659
- }
1660
- // Get components
1661
- // Maps are keyed by component key (unique) rather than name — same-named
1662
- // components on different pages would silently overwrite each other.
1663
- let rawComponents;
1664
- let componentsFetchError = null;
1665
- try {
1666
- const componentsResult = await connector.getLocalComponents();
1667
- if (componentsResult.success && componentsResult.data) {
1668
- rawComponents = {
1669
- components: componentsResult.data.components || [],
1670
- componentSets: componentsResult.data.componentSets || [],
1671
- };
1672
- for (const comp of rawComponents.components) {
1673
- manifest.components[comp.key || comp.nodeId] = {
1674
- key: comp.key,
1675
- nodeId: comp.nodeId,
1676
- name: comp.name,
1677
- description: comp.description || undefined,
1678
- defaultSize: { width: comp.width, height: comp.height },
1679
- };
1680
- }
1681
- for (const compSet of rawComponents.componentSets) {
1682
- manifest.componentSets[compSet.key || compSet.nodeId] = {
1683
- key: compSet.key,
1684
- nodeId: compSet.nodeId,
1685
- name: compSet.name,
1686
- description: compSet.description || undefined,
1687
- variants: compSet.variants?.map((v) => ({
1688
- key: v.key,
1689
- nodeId: v.nodeId,
1690
- name: v.name,
1691
- })) || [],
1692
- variantAxes: compSet.variantAxes?.map((a) => ({
1693
- name: a.name,
1694
- values: a.values,
1695
- })) || [],
1696
- };
1697
- }
1698
- }
1699
- else {
1700
- componentsFetchError =
1701
- componentsResult?.error || "getLocalComponents returned no data";
1702
- }
1703
- }
1704
- catch (error) {
1705
- componentsFetchError =
1706
- error instanceof Error ? error.message : String(error);
1707
- logger.warn({ error }, "Could not fetch components during auto-load");
1708
- }
1709
- // Update summary
1710
- manifest.summary = {
1711
- totalTokens: Object.keys(manifest.tokens.colors).length +
1712
- Object.keys(manifest.tokens.spacing).length,
1713
- totalComponents: Object.keys(manifest.components).length,
1714
- totalComponentSets: Object.keys(manifest.componentSets).length,
1715
- colorPalette: Object.keys(manifest.tokens.colors).slice(0, 10),
1716
- spacingScale: Object.values(manifest.tokens.spacing)
1717
- .map((s) => s.value)
1718
- .filter((v) => typeof v === "number")
1719
- .sort((a, b) => a - b)
1720
- .slice(0, 10),
1721
- typographyScale: [],
1722
- componentCategories: [],
1723
- };
1724
- // Cache the result — but never cache a manifest built from a FAILED
1725
- // components fetch: serving an empty manifest as "cached" for the full
1726
- // TTL is exactly the "search returns 0 components" poisoning bug.
1727
- if (!componentsFetchError && !variablesFetchError) {
1728
- cache.set(fileKey, manifest, rawComponents);
1729
- cacheEntry = cache.get(fileKey);
1730
- }
1731
- else {
1732
- cacheEntry = {
1733
- manifest,
1734
- timestamp: Date.now(),
1735
- fileKey,
1736
- rawComponents,
1737
- };
1738
- }
1646
+ // Helper function to ensure design system cache is loaded (auto-loads if needed).
1647
+ // The build itself, shared by the four manifest tools, is ensureManifest
1648
+ // (core/manifest-build.ts); this joins its fetch errors into one warning.
1649
+ const ensureDesignSystemCache = async (opts) => {
1650
+ const result = await ensureManifest({
1651
+ manifestCache: this.manifestCache,
1652
+ getConnector: (fileKey) => this.getDesktopConnector(fileKey),
1653
+ getCurrentFileUrl: () => this.getCurrentFileUrl(),
1654
+ }, opts);
1655
+ const { componentsError, variablesError } = result;
1739
1656
  return {
1740
- cacheEntry,
1741
- fileKey,
1742
- wasLoaded: true,
1657
+ ...result,
1743
1658
  warning: [
1744
- componentsFetchError
1745
- ? `Components fetch failed (${componentsFetchError}) — results may be incomplete and were NOT cached; retry after checking the Desktop Bridge plugin.`
1659
+ componentsError
1660
+ ? `Components fetch failed (${componentsError}) — results may be incomplete and were NOT cached; retry after checking the Desktop Bridge plugin.`
1746
1661
  : null,
1747
- variablesFetchError
1748
- ? `Variables fetch failed (${variablesFetchError}) — tokens are missing and the result was NOT cached; retry after checking the Desktop Bridge plugin.`
1662
+ variablesError
1663
+ ? `Variables fetch failed (${variablesError}) — tokens are missing and the result was NOT cached; retry after checking the Desktop Bridge plugin.`
1749
1664
  : null,
1750
1665
  ]
1751
1666
  .filter(Boolean)
@@ -1768,16 +1683,11 @@ class LocalFigmaConsoleMCP {
1768
1683
  }),
1769
1684
  }, async ({ forceRefresh }) => {
1770
1685
  try {
1771
- const { DesignSystemManifestCache, createEmptyManifest, loadManifestVariables, getCategories, getTokenSummary, } = await import("./core/design-system-manifest.js");
1772
- const cache = DesignSystemManifestCache.getInstance();
1773
- const currentUrl = this.getCurrentFileUrl();
1774
- const fileKeyMatch = currentUrl?.match(/\/(file|design|board|slides)\/([a-zA-Z0-9]+)/);
1775
- const fileKey = fileKeyMatch ? fileKeyMatch[2] : "unknown";
1776
- // Check cache first
1777
- let cacheEntry = cache.get(fileKey);
1778
- if (cacheEntry && !forceRefresh) {
1779
- const categories = getCategories(cacheEntry.manifest);
1780
- const tokenSummary = getTokenSummary(cacheEntry.manifest);
1686
+ const { getCategories, getTokenSummary } = await import("./core/design-system-manifest.js");
1687
+ const { cacheEntry, fileKey, wasLoaded, componentsError, variablesError } = await ensureDesignSystemCache({ forceRefresh });
1688
+ const categories = getCategories(cacheEntry.manifest);
1689
+ const tokenSummary = getTokenSummary(cacheEntry.manifest);
1690
+ if (!wasLoaded) {
1781
1691
  return {
1782
1692
  content: [
1783
1693
  {
@@ -1800,83 +1710,7 @@ class LocalFigmaConsoleMCP {
1800
1710
  ],
1801
1711
  };
1802
1712
  }
1803
- // Need to extract fresh data
1804
- const connector = await this.getDesktopConnector();
1805
- const manifest = createEmptyManifest(fileKey);
1806
- manifest.fileUrl = currentUrl || undefined;
1807
- // Get variables (tokens); see ensureDesignSystemCache for the failure guard.
1808
- const variablesFetchError = await loadManifestVariables(manifest, () => connector.readVariables(fileKey));
1809
- // Get components (can be slow for large files)
1810
- // Keyed by component key (unique) — name keys drop same-named
1811
- // components on other pages.
1812
- let rawComponents;
1813
- let componentsFetchError = null;
1814
- try {
1815
- const componentsResult = await connector.getLocalComponents();
1816
- if (componentsResult.success && componentsResult.data) {
1817
- rawComponents = {
1818
- components: componentsResult.data.components || [],
1819
- componentSets: componentsResult.data.componentSets || [],
1820
- };
1821
- for (const comp of rawComponents.components) {
1822
- manifest.components[comp.key || comp.nodeId] = {
1823
- key: comp.key,
1824
- nodeId: comp.nodeId,
1825
- name: comp.name,
1826
- description: comp.description || undefined,
1827
- defaultSize: { width: comp.width, height: comp.height },
1828
- };
1829
- }
1830
- for (const compSet of rawComponents.componentSets) {
1831
- manifest.componentSets[compSet.key || compSet.nodeId] = {
1832
- key: compSet.key,
1833
- nodeId: compSet.nodeId,
1834
- name: compSet.name,
1835
- description: compSet.description || undefined,
1836
- variants: compSet.variants?.map((v) => ({
1837
- key: v.key,
1838
- nodeId: v.nodeId,
1839
- name: v.name,
1840
- })) || [],
1841
- variantAxes: compSet.variantAxes?.map((a) => ({
1842
- name: a.name,
1843
- values: a.values,
1844
- })) || [],
1845
- };
1846
- }
1847
- }
1848
- else {
1849
- componentsFetchError =
1850
- componentsResult?.error || "getLocalComponents returned no data";
1851
- }
1852
- }
1853
- catch (error) {
1854
- componentsFetchError =
1855
- error instanceof Error ? error.message : String(error);
1856
- logger.warn({ error }, "Could not fetch components");
1857
- }
1858
- // Update summary
1859
- manifest.summary = {
1860
- totalTokens: Object.keys(manifest.tokens.colors).length +
1861
- Object.keys(manifest.tokens.spacing).length,
1862
- totalComponents: Object.keys(manifest.components).length,
1863
- totalComponentSets: Object.keys(manifest.componentSets).length,
1864
- colorPalette: Object.keys(manifest.tokens.colors).slice(0, 10),
1865
- spacingScale: Object.values(manifest.tokens.spacing)
1866
- .map((s) => s.value)
1867
- .filter((v) => typeof v === "number")
1868
- .sort((a, b) => a - b)
1869
- .slice(0, 10),
1870
- typographyScale: [],
1871
- componentCategories: [],
1872
- };
1873
- // Cache the result — never cache a manifest built from a failed
1874
- // components fetch (would serve empty results for the full TTL).
1875
- if (!componentsFetchError && !variablesFetchError) {
1876
- cache.set(fileKey, manifest, rawComponents);
1877
- }
1878
- const categories = getCategories(manifest);
1879
- const tokenSummary = getTokenSummary(manifest);
1713
+ const { manifest } = cacheEntry;
1880
1714
  return {
1881
1715
  content: [
1882
1716
  {
@@ -1892,13 +1726,13 @@ class LocalFigmaConsoleMCP {
1892
1726
  componentSets: manifest.summary.totalComponentSets,
1893
1727
  tokens: manifest.summary.totalTokens,
1894
1728
  },
1895
- warnings: componentsFetchError || variablesFetchError
1729
+ warnings: componentsError || variablesError
1896
1730
  ? [
1897
- componentsFetchError
1898
- ? `Components fetch failed (${componentsFetchError}) — component data is incomplete and was NOT cached. Check the Desktop Bridge plugin and retry.`
1731
+ componentsError
1732
+ ? `Components fetch failed (${componentsError}) — component data is incomplete and was NOT cached. Check the Desktop Bridge plugin and retry.`
1899
1733
  : null,
1900
- variablesFetchError
1901
- ? `Variables fetch failed (${variablesFetchError}) — tokens are missing and the result was NOT cached. Check the Desktop Bridge plugin and retry.`
1734
+ variablesError
1735
+ ? `Variables fetch failed (${variablesError}) — tokens are missing and the result was NOT cached. Check the Desktop Bridge plugin and retry.`
1902
1736
  : null,
1903
1737
  ].filter(Boolean)
1904
1738
  : undefined,
@@ -2178,7 +2012,7 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2178
2012
  };
2179
2013
  }
2180
2014
  // Auto-load design system cache if needed
2181
- const { cacheEntry } = await ensureDesignSystemCache();
2015
+ const { cacheEntry, warning } = await ensureDesignSystemCache();
2182
2016
  if (!cacheEntry) {
2183
2017
  return {
2184
2018
  content: [
@@ -2224,6 +2058,7 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2224
2058
  text: JSON.stringify({
2225
2059
  error: `Component not found: ${componentKey || componentName}`,
2226
2060
  hint: "Use figma_search_components to find available components.",
2061
+ warnings: warning ? [warning] : undefined,
2227
2062
  }),
2228
2063
  },
2229
2064
  ],
@@ -2242,6 +2077,7 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2242
2077
  key: component.key,
2243
2078
  example: `Use figma_instantiate_component with componentKey: "${component.key}"`,
2244
2079
  },
2080
+ warnings: warning ? [warning] : undefined,
2245
2081
  }),
2246
2082
  },
2247
2083
  ],
@@ -2284,7 +2120,7 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2284
2120
  }, async ({ type, filter, limit }) => {
2285
2121
  try {
2286
2122
  // Auto-load design system cache if needed
2287
- const { cacheEntry } = await ensureDesignSystemCache();
2123
+ const { cacheEntry, warning } = await ensureDesignSystemCache();
2288
2124
  if (!cacheEntry) {
2289
2125
  return {
2290
2126
  content: [
@@ -2338,6 +2174,7 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2338
2174
  filter: filter || "(none)",
2339
2175
  tokens: result,
2340
2176
  hint: "Use these exact token names and values when generating designs.",
2177
+ warnings: warning ? [warning] : undefined,
2341
2178
  }),
2342
2179
  },
2343
2180
  ],
@@ -2772,24 +2609,15 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2772
2609
  const cacheEntry = this.variablesCache.get(fileKey);
2773
2610
  if (cacheEntry && Date.now() - cacheEntry.timestamp < 5 * 60 * 1000) {
2774
2611
  const cached = cacheEntry.data;
2775
- // Desktop Bridge caches arrays directly; REST API data needs formatVariables
2776
- if (Array.isArray(cached.variables)) {
2777
- return {
2778
- variables: cached.variables,
2779
- collections: cached.variableCollections || [],
2780
- fileInfo,
2781
- };
2782
- }
2783
- const formatted = formatVariables(cached);
2784
2612
  return {
2785
- variables: formatted.variables,
2786
- collections: formatted.collections,
2613
+ variables: cached.variables,
2614
+ collections: cached.variableCollections || [],
2787
2615
  fileInfo,
2788
2616
  };
2789
2617
  }
2790
2618
  // Priority 1: Try Desktop Bridge via transport-agnostic connector
2791
2619
  try {
2792
- const startedAt = cacheGeneration(this.variablesCache);
2620
+ const startedAt = cacheGeneration(this.variablesCache, fileKey);
2793
2621
  const connector = await this.getDesktopConnector();
2794
2622
  const desktopResult = await connector.readVariables(fileKey);
2795
2623
  if (desktopResult.success && desktopResult.variables) {
@@ -2817,21 +2645,21 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2817
2645
  }, "Desktop Bridge failed for token browser, trying REST API");
2818
2646
  }
2819
2647
  // Priority 2: Fall back to REST API (requires Enterprise plan)
2820
- const restStartedAt = cacheGeneration(this.variablesCache);
2648
+ const restStartedAt = cacheGeneration(this.variablesCache, fileKey);
2821
2649
  const api = await this.getFigmaAPI();
2822
2650
  const { local, localError } = await api.getAllVariables(fileKey);
2823
2651
  if (localError) {
2824
2652
  throw new Error(`Could not fetch variables. Desktop Bridge unavailable and REST API returned: ${localError}`);
2825
2653
  }
2826
- // Cache raw REST API data, unless the cache was invalidated while it was read
2654
+ // Cache in the shared array shape, unless the cache was invalidated while it was read
2655
+ const restData = restVariablesCacheData(fileKey, local);
2827
2656
  setCacheIfCurrent(this.variablesCache, fileKey, {
2828
- data: local,
2657
+ data: restData,
2829
2658
  timestamp: Date.now(),
2830
2659
  }, restStartedAt);
2831
- const formatted = formatVariables(local);
2832
2660
  return {
2833
- variables: formatted.variables,
2834
- collections: formatted.collections,
2661
+ variables: restData.variables,
2662
+ collections: restData.variableCollections,
2835
2663
  fileInfo,
2836
2664
  };
2837
2665
  });
@@ -2860,22 +2688,15 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2860
2688
  const cacheEntry = this.variablesCache.get(fileKey);
2861
2689
  if (cacheEntry && Date.now() - cacheEntry.timestamp < 5 * 60 * 1000) {
2862
2690
  const cached = cacheEntry.data;
2863
- if (Array.isArray(cached.variables)) {
2864
- variables = cached.variables;
2865
- collections = cached.variableCollections || [];
2866
- }
2867
- else {
2868
- const formatted = formatVariables(cached);
2869
- variables = formatted.variables;
2870
- collections = formatted.collections;
2871
- }
2691
+ variables = cached.variables;
2692
+ collections = cached.variableCollections || [];
2872
2693
  variablesAvailable = variables.length > 0;
2873
2694
  }
2874
2695
  // 2. Try Desktop Bridge via transport-agnostic connector
2875
2696
  if (variables.length === 0) {
2876
2697
  desktopBridgeAttempted = true;
2877
2698
  try {
2878
- const startedAt = cacheGeneration(this.variablesCache);
2699
+ const startedAt = cacheGeneration(this.variablesCache, fileKey);
2879
2700
  const connector = await this.getDesktopConnector();
2880
2701
  const desktopResult = await connector.readVariables(fileKey);
2881
2702
  if (desktopResult.success && desktopResult.variables) {
@@ -2907,17 +2728,17 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
2907
2728
  if (variables.length === 0) {
2908
2729
  restApiAttempted = true;
2909
2730
  try {
2910
- const startedAt = cacheGeneration(this.variablesCache);
2731
+ const startedAt = cacheGeneration(this.variablesCache, fileKey);
2911
2732
  const api = await this.getFigmaAPI();
2912
2733
  const { local, localError } = await api.getAllVariables(fileKey);
2913
2734
  if (!localError && local) {
2735
+ const restData = restVariablesCacheData(fileKey, local);
2914
2736
  setCacheIfCurrent(this.variablesCache, fileKey, {
2915
- data: local,
2737
+ data: restData,
2916
2738
  timestamp: Date.now(),
2917
2739
  }, startedAt);
2918
- const formatted = formatVariables(local);
2919
- variables = formatted.variables;
2920
- collections = formatted.collections;
2740
+ variables = restData.variables;
2741
+ collections = restData.variableCollections;
2921
2742
  variablesAvailable = true;
2922
2743
  }
2923
2744
  else {
@@ -3028,6 +2849,7 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
3028
2849
  logger.info("MCP Apps registered (ENABLE_MCP_APPS=true)");
3029
2850
  }
3030
2851
  const unclassified = applyToolAnnotations(server);
2852
+ attachWriteInvalidation(server, { variablesCache: this.variablesCache, manifestCache: this.manifestCache });
3031
2853
  if (unclassified.length > 0)
3032
2854
  logger.warn({ unclassified }, "Tools registered without annotation hints");
3033
2855
  logger.info("All MCP tools registered successfully (including write operations)");
@@ -3284,47 +3106,11 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
3284
3106
  this.wsServer.on("fileConnected", (data) => {
3285
3107
  logger.info({ fileKey: data.fileKey, fileName: data.fileName }, "Desktop Bridge plugin connected via WebSocket");
3286
3108
  });
3287
- // Plugin disconnect leaves cached variables stale — when the plugin reconnects
3288
- // after a sleep/wake or network blip, the file may have edits we missed
3289
- // (no DOCUMENT_CHANGE event was delivered while we were disconnected).
3290
- // Invalidate the cache for the disconnected file so the next read is fresh.
3109
+ // Cache invalidation on disconnect and document changes lives in
3110
+ // core/cache-invalidation.ts so it can be tested by behaviour.
3111
+ attachCacheInvalidation(this.wsServer, { variablesCache: this.variablesCache, manifestCache: this.manifestCache });
3291
3112
  this.wsServer.on("fileDisconnected", (data) => {
3292
3113
  logger.info({ fileKey: data.fileKey, fileName: data.fileName }, "Desktop Bridge plugin disconnected from WebSocket");
3293
- if (data.fileKey) {
3294
- this.variablesCache.delete(data.fileKey);
3295
- // design-system-tools.ts stores token data under a prefixed key
3296
- this.variablesCache.delete(`vars:${data.fileKey}`);
3297
- void import("./core/design-system-manifest.js").then(({ DesignSystemManifestCache }) => {
3298
- DesignSystemManifestCache.getInstance().invalidate(data.fileKey);
3299
- }).catch(() => { });
3300
- }
3301
- });
3302
- // Invalidate variable cache when document changes are reported.
3303
- // Figma's documentchange API doesn't expose a specific variable change type —
3304
- // variable operations manifest as node PROPERTY_CHANGE events, so we invalidate
3305
- // on any style or node change to be safe.
3306
- this.wsServer.on("documentChange", (data) => {
3307
- if (data.hasStyleChanges || data.hasNodeChanges) {
3308
- if (data.fileKey) {
3309
- // Per-file cache invalidation — only clear the affected file's cache.
3310
- // Also clear the design-system-tools token entry (prefixed key)
3311
- // and the component manifest, so searches see new components
3312
- // and the design-system kit sees edited variables.
3313
- this.variablesCache.delete(data.fileKey);
3314
- this.variablesCache.delete(`vars:${data.fileKey}`);
3315
- void import("./core/design-system-manifest.js").then(({ DesignSystemManifestCache }) => {
3316
- DesignSystemManifestCache.getInstance().invalidate(data.fileKey);
3317
- }).catch(() => { });
3318
- logger.debug({ fileKey: data.fileKey, changeCount: data.changeCount, hasStyleChanges: data.hasStyleChanges, hasNodeChanges: data.hasNodeChanges }, "Variable cache invalidated due to document changes");
3319
- }
3320
- else {
3321
- // Unidentified file (event arrived before FILE_INFO handshake completed).
3322
- // We don't know which cache entry to invalidate; do nothing rather than
3323
- // blanket-clear other files' caches. FILE_INFO will arrive shortly and
3324
- // any subsequent document changes will route correctly.
3325
- logger.debug({ changeCount: data.changeCount }, "Document change received before file identification — cache untouched");
3326
- }
3327
- }
3328
3114
  });
3329
3115
  }
3330
3116
  // Periodically reap orphaned/zombie servers for the whole run, not just