@muloka/figma-console-mcp 0.6.2 → 0.6.4
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.
- package/README.md +17 -2
- package/dist/core/cache-invalidation.d.ts +14 -0
- package/dist/core/cache-invalidation.d.ts.map +1 -0
- package/dist/core/cache-invalidation.js +39 -0
- package/dist/core/cache-invalidation.js.map +1 -0
- package/dist/core/design-system-manifest.d.ts +30 -14
- package/dist/core/design-system-manifest.d.ts.map +1 -1
- package/dist/core/design-system-manifest.js +61 -19
- package/dist/core/design-system-manifest.js.map +1 -1
- package/dist/core/design-system-tools.d.ts.map +1 -1
- package/dist/core/design-system-tools.js +8 -6
- package/dist/core/design-system-tools.js.map +1 -1
- package/dist/core/figma-tools.d.ts.map +1 -1
- package/dist/core/figma-tools.js +27 -15
- package/dist/core/figma-tools.js.map +1 -1
- package/dist/core/file-generations.d.ts +18 -0
- package/dist/core/file-generations.d.ts.map +1 -0
- package/dist/core/file-generations.js +44 -0
- package/dist/core/file-generations.js.map +1 -0
- package/dist/core/library-tools.d.ts +5 -1
- package/dist/core/library-tools.d.ts.map +1 -1
- package/dist/core/library-tools.js +35 -11
- package/dist/core/library-tools.js.map +1 -1
- package/dist/core/logger.d.ts.map +1 -1
- package/dist/core/logger.js +5 -2
- package/dist/core/logger.js.map +1 -1
- package/dist/core/manifest-build.d.ts +41 -0
- package/dist/core/manifest-build.d.ts.map +1 -0
- package/dist/core/manifest-build.js +135 -0
- package/dist/core/manifest-build.js.map +1 -0
- package/dist/core/port-discovery.d.ts +7 -3
- package/dist/core/port-discovery.d.ts.map +1 -1
- package/dist/core/port-discovery.js +49 -7
- package/dist/core/port-discovery.js.map +1 -1
- package/dist/core/stdin-lifecycle.d.ts +16 -0
- package/dist/core/stdin-lifecycle.d.ts.map +1 -0
- package/dist/core/stdin-lifecycle.js +32 -0
- package/dist/core/stdin-lifecycle.js.map +1 -0
- package/dist/core/tokens-tools.d.ts +6 -0
- package/dist/core/tokens-tools.d.ts.map +1 -1
- package/dist/core/tokens-tools.js +12 -7
- package/dist/core/tokens-tools.js.map +1 -1
- package/dist/core/tool-annotations.d.ts +16 -5
- package/dist/core/tool-annotations.d.ts.map +1 -1
- package/dist/core/tool-annotations.js +27 -6
- package/dist/core/tool-annotations.js.map +1 -1
- package/dist/core/variables-cache.d.ts +49 -0
- package/dist/core/variables-cache.d.ts.map +1 -0
- package/dist/core/variables-cache.js +118 -0
- package/dist/core/variables-cache.js.map +1 -0
- package/dist/core/websocket-connector.d.ts.map +1 -1
- package/dist/core/websocket-connector.js +21 -2
- package/dist/core/websocket-connector.js.map +1 -1
- package/dist/core/websocket-server.d.ts +21 -0
- package/dist/core/websocket-server.d.ts.map +1 -1
- package/dist/core/websocket-server.js +50 -0
- package/dist/core/websocket-server.js.map +1 -1
- package/dist/core/write-tools.d.ts +1 -1
- package/dist/core/write-tools.d.ts.map +1 -1
- package/dist/core/write-tools.js +189 -51
- package/dist/core/write-tools.js.map +1 -1
- package/dist/local.d.ts +4 -0
- package/dist/local.d.ts.map +1 -1
- package/dist/local.js +83 -263
- package/dist/local.js.map +1 -1
- package/package.json +1 -1
package/dist/local.js
CHANGED
|
@@ -24,6 +24,8 @@ 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 } from "./core/cache-invalidation.js";
|
|
28
|
+
import { onStdinClosed } from "./core/stdin-lifecycle.js";
|
|
27
29
|
import { FigmaAPI, extractFileKey, extractFigmaUrlInfo, formatVariables, } from "./core/figma-api.js";
|
|
28
30
|
import { registerFigmaAPITools } from "./core/figma-tools.js";
|
|
29
31
|
import { registerDesignCodeTools } from "./core/design-code-tools.js";
|
|
@@ -41,7 +43,9 @@ import { MAX_TOOL_RESPONSE_BYTES, withToolIdentity } from "./core/identity.js";
|
|
|
41
43
|
import { PACKAGE_ROOT } from "./core/resolve-package-root.js";
|
|
42
44
|
import { FigmaWebSocketServer, getBundledPluginVersion, getBundledForkPluginRevision, heldPinStatusWarning, } from "./core/websocket-server.js";
|
|
43
45
|
import { WebSocketConnector } from "./core/websocket-connector.js";
|
|
44
|
-
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";
|
|
48
|
+
import { VariablesCache, cacheGeneration, setCacheIfCurrent } from "./core/variables-cache.js";
|
|
45
49
|
import { DEFAULT_WS_PORT, getPortRange, advertisePort, unadvertisePort, registerPortCleanup, startPeriodicReaper, discoverActiveInstances, cleanupStalePortFiles, cleanupOrphanedProcesses, evictOldestInstance, refreshPortAdvertisement, setAdvertisedMcpHttpPort, HEARTBEAT_INTERVAL_MS, } from "./core/port-discovery.js";
|
|
46
50
|
import { registerTokenBrowserApp } from "./apps/token-browser/server.js";
|
|
47
51
|
import { registerDesignSystemDashboardApp } from "./apps/design-system-dashboard/server.js";
|
|
@@ -224,7 +228,7 @@ class LocalFigmaConsoleMCP {
|
|
|
224
228
|
// touches no node fires no documentChange, so nothing else would, and the
|
|
225
229
|
// summary / token-value tools would serve pre-write tokens (#14).
|
|
226
230
|
const hadVariables = this.variablesCache.size > 0;
|
|
227
|
-
invalidateAfterVariableWrite(this.variablesCache);
|
|
231
|
+
invalidateAfterVariableWrite(this.variablesCache, this.manifestCache);
|
|
228
232
|
if (hadVariables)
|
|
229
233
|
logger.info('Variables cache invalidated after write operation');
|
|
230
234
|
}
|
|
@@ -234,6 +238,7 @@ class LocalFigmaConsoleMCP {
|
|
|
234
238
|
this.wsStartupError = null;
|
|
235
239
|
/** The port the WebSocket server actually bound to (may differ from preferred if fallback occurred) */
|
|
236
240
|
this.wsActualPort = null;
|
|
241
|
+
this.unregisterPortCleanup = null;
|
|
237
242
|
/** The preferred port requested (from env var or default) */
|
|
238
243
|
this.wsPreferredPort = DEFAULT_WS_PORT;
|
|
239
244
|
/** Stops the periodic background reaper (set once the WS port is bound) */
|
|
@@ -249,7 +254,16 @@ class LocalFigmaConsoleMCP {
|
|
|
249
254
|
this.config = getConfig();
|
|
250
255
|
// In-memory cache for variables data to avoid MCP token limits
|
|
251
256
|
// Maps fileKey -> {data, timestamp}
|
|
252
|
-
|
|
257
|
+
//
|
|
258
|
+
// Every invalidation also ends in-flight read sharing, for the files it
|
|
259
|
+
// invalidates: a read that starts after the invalidation must not join a
|
|
260
|
+
// read that started before it, or it would store pre-change data under the
|
|
261
|
+
// new generation. A write's clear() ends every file's shared reads. Document
|
|
262
|
+
// changes and disconnects invalidate per file, through attachCacheInvalidation
|
|
263
|
+
// (src/core/cache-invalidation.ts), and end only that file's shared reads.
|
|
264
|
+
this.variablesCache = new VariablesCache((fileKey) => this.wsServer?.forgetSharedReads(fileKey));
|
|
265
|
+
// Design-system manifests, one per file; its invalidations end shared reads the same way.
|
|
266
|
+
this.manifestCache = new DesignSystemManifestCache((fileKey) => this.wsServer?.forgetSharedReads(fileKey));
|
|
253
267
|
/** Stable plugin directory path (set during startup) */
|
|
254
268
|
this.stablePluginPath = null;
|
|
255
269
|
this.server = new StdioMcpServer({
|
|
@@ -1622,122 +1636,24 @@ class LocalFigmaConsoleMCP {
|
|
|
1622
1636
|
// These tools provide progressive disclosure of design system data
|
|
1623
1637
|
// to minimize context window usage. Start with summary, then search,
|
|
1624
1638
|
// then get details for specific components.
|
|
1625
|
-
// Helper function to ensure design system cache is loaded (auto-loads if needed)
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
const
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
const
|
|
1635
|
-
// Check cache first
|
|
1636
|
-
let cacheEntry = cache.get(fileKey);
|
|
1637
|
-
if (cacheEntry) {
|
|
1638
|
-
return { cacheEntry, fileKey, wasLoaded: false };
|
|
1639
|
-
}
|
|
1640
|
-
// Need to extract fresh data - do this silently without returning an error
|
|
1641
|
-
logger.info({ fileKey }, "Auto-loading design system cache");
|
|
1642
|
-
const connector = await this.getDesktopConnector();
|
|
1643
|
-
const manifest = createEmptyManifest(fileKey);
|
|
1644
|
-
manifest.fileUrl = currentUrl || undefined;
|
|
1645
|
-
// Get variables (tokens). A failed read is reported, and the manifest
|
|
1646
|
-
// is not cached, so a transient plugin error can't serve "0 tokens"
|
|
1647
|
-
// for the full TTL.
|
|
1648
|
-
const variablesFetchError = await loadManifestVariables(manifest, () => connector.readVariables(fileKey));
|
|
1649
|
-
if (variablesFetchError) {
|
|
1650
|
-
logger.warn({ error: variablesFetchError }, "Could not fetch variables during auto-load");
|
|
1651
|
-
}
|
|
1652
|
-
// Get components
|
|
1653
|
-
// Maps are keyed by component key (unique) rather than name — same-named
|
|
1654
|
-
// components on different pages would silently overwrite each other.
|
|
1655
|
-
let rawComponents;
|
|
1656
|
-
let componentsFetchError = null;
|
|
1657
|
-
try {
|
|
1658
|
-
const componentsResult = await connector.getLocalComponents();
|
|
1659
|
-
if (componentsResult.success && componentsResult.data) {
|
|
1660
|
-
rawComponents = {
|
|
1661
|
-
components: componentsResult.data.components || [],
|
|
1662
|
-
componentSets: componentsResult.data.componentSets || [],
|
|
1663
|
-
};
|
|
1664
|
-
for (const comp of rawComponents.components) {
|
|
1665
|
-
manifest.components[comp.key || comp.nodeId] = {
|
|
1666
|
-
key: comp.key,
|
|
1667
|
-
nodeId: comp.nodeId,
|
|
1668
|
-
name: comp.name,
|
|
1669
|
-
description: comp.description || undefined,
|
|
1670
|
-
defaultSize: { width: comp.width, height: comp.height },
|
|
1671
|
-
};
|
|
1672
|
-
}
|
|
1673
|
-
for (const compSet of rawComponents.componentSets) {
|
|
1674
|
-
manifest.componentSets[compSet.key || compSet.nodeId] = {
|
|
1675
|
-
key: compSet.key,
|
|
1676
|
-
nodeId: compSet.nodeId,
|
|
1677
|
-
name: compSet.name,
|
|
1678
|
-
description: compSet.description || undefined,
|
|
1679
|
-
variants: compSet.variants?.map((v) => ({
|
|
1680
|
-
key: v.key,
|
|
1681
|
-
nodeId: v.nodeId,
|
|
1682
|
-
name: v.name,
|
|
1683
|
-
})) || [],
|
|
1684
|
-
variantAxes: compSet.variantAxes?.map((a) => ({
|
|
1685
|
-
name: a.name,
|
|
1686
|
-
values: a.values,
|
|
1687
|
-
})) || [],
|
|
1688
|
-
};
|
|
1689
|
-
}
|
|
1690
|
-
}
|
|
1691
|
-
else {
|
|
1692
|
-
componentsFetchError =
|
|
1693
|
-
componentsResult?.error || "getLocalComponents returned no data";
|
|
1694
|
-
}
|
|
1695
|
-
}
|
|
1696
|
-
catch (error) {
|
|
1697
|
-
componentsFetchError =
|
|
1698
|
-
error instanceof Error ? error.message : String(error);
|
|
1699
|
-
logger.warn({ error }, "Could not fetch components during auto-load");
|
|
1700
|
-
}
|
|
1701
|
-
// Update summary
|
|
1702
|
-
manifest.summary = {
|
|
1703
|
-
totalTokens: Object.keys(manifest.tokens.colors).length +
|
|
1704
|
-
Object.keys(manifest.tokens.spacing).length,
|
|
1705
|
-
totalComponents: Object.keys(manifest.components).length,
|
|
1706
|
-
totalComponentSets: Object.keys(manifest.componentSets).length,
|
|
1707
|
-
colorPalette: Object.keys(manifest.tokens.colors).slice(0, 10),
|
|
1708
|
-
spacingScale: Object.values(manifest.tokens.spacing)
|
|
1709
|
-
.map((s) => s.value)
|
|
1710
|
-
.filter((v) => typeof v === "number")
|
|
1711
|
-
.sort((a, b) => a - b)
|
|
1712
|
-
.slice(0, 10),
|
|
1713
|
-
typographyScale: [],
|
|
1714
|
-
componentCategories: [],
|
|
1715
|
-
};
|
|
1716
|
-
// Cache the result — but never cache a manifest built from a FAILED
|
|
1717
|
-
// components fetch: serving an empty manifest as "cached" for the full
|
|
1718
|
-
// TTL is exactly the "search returns 0 components" poisoning bug.
|
|
1719
|
-
if (!componentsFetchError && !variablesFetchError) {
|
|
1720
|
-
cache.set(fileKey, manifest, rawComponents);
|
|
1721
|
-
cacheEntry = cache.get(fileKey);
|
|
1722
|
-
}
|
|
1723
|
-
else {
|
|
1724
|
-
cacheEntry = {
|
|
1725
|
-
manifest,
|
|
1726
|
-
timestamp: Date.now(),
|
|
1727
|
-
fileKey,
|
|
1728
|
-
rawComponents,
|
|
1729
|
-
};
|
|
1730
|
-
}
|
|
1639
|
+
// Helper function to ensure design system cache is loaded (auto-loads if needed).
|
|
1640
|
+
// The build itself, shared by the four manifest tools, is ensureManifest
|
|
1641
|
+
// (core/manifest-build.ts); this joins its fetch errors into one warning.
|
|
1642
|
+
const ensureDesignSystemCache = async (opts) => {
|
|
1643
|
+
const result = await ensureManifest({
|
|
1644
|
+
manifestCache: this.manifestCache,
|
|
1645
|
+
getConnector: (fileKey) => this.getDesktopConnector(fileKey),
|
|
1646
|
+
getCurrentFileUrl: () => this.getCurrentFileUrl(),
|
|
1647
|
+
}, opts);
|
|
1648
|
+
const { componentsError, variablesError } = result;
|
|
1731
1649
|
return {
|
|
1732
|
-
|
|
1733
|
-
fileKey,
|
|
1734
|
-
wasLoaded: true,
|
|
1650
|
+
...result,
|
|
1735
1651
|
warning: [
|
|
1736
|
-
|
|
1737
|
-
? `Components fetch failed (${
|
|
1652
|
+
componentsError
|
|
1653
|
+
? `Components fetch failed (${componentsError}) — results may be incomplete and were NOT cached; retry after checking the Desktop Bridge plugin.`
|
|
1738
1654
|
: null,
|
|
1739
|
-
|
|
1740
|
-
? `Variables fetch failed (${
|
|
1655
|
+
variablesError
|
|
1656
|
+
? `Variables fetch failed (${variablesError}) — tokens are missing and the result was NOT cached; retry after checking the Desktop Bridge plugin.`
|
|
1741
1657
|
: null,
|
|
1742
1658
|
]
|
|
1743
1659
|
.filter(Boolean)
|
|
@@ -1760,16 +1676,11 @@ class LocalFigmaConsoleMCP {
|
|
|
1760
1676
|
}),
|
|
1761
1677
|
}, async ({ forceRefresh }) => {
|
|
1762
1678
|
try {
|
|
1763
|
-
const {
|
|
1764
|
-
const
|
|
1765
|
-
const
|
|
1766
|
-
const
|
|
1767
|
-
|
|
1768
|
-
// Check cache first
|
|
1769
|
-
let cacheEntry = cache.get(fileKey);
|
|
1770
|
-
if (cacheEntry && !forceRefresh) {
|
|
1771
|
-
const categories = getCategories(cacheEntry.manifest);
|
|
1772
|
-
const tokenSummary = getTokenSummary(cacheEntry.manifest);
|
|
1679
|
+
const { getCategories, getTokenSummary } = await import("./core/design-system-manifest.js");
|
|
1680
|
+
const { cacheEntry, fileKey, wasLoaded, componentsError, variablesError } = await ensureDesignSystemCache({ forceRefresh });
|
|
1681
|
+
const categories = getCategories(cacheEntry.manifest);
|
|
1682
|
+
const tokenSummary = getTokenSummary(cacheEntry.manifest);
|
|
1683
|
+
if (!wasLoaded) {
|
|
1773
1684
|
return {
|
|
1774
1685
|
content: [
|
|
1775
1686
|
{
|
|
@@ -1792,83 +1703,7 @@ class LocalFigmaConsoleMCP {
|
|
|
1792
1703
|
],
|
|
1793
1704
|
};
|
|
1794
1705
|
}
|
|
1795
|
-
|
|
1796
|
-
const connector = await this.getDesktopConnector();
|
|
1797
|
-
const manifest = createEmptyManifest(fileKey);
|
|
1798
|
-
manifest.fileUrl = currentUrl || undefined;
|
|
1799
|
-
// Get variables (tokens); see ensureDesignSystemCache for the failure guard.
|
|
1800
|
-
const variablesFetchError = await loadManifestVariables(manifest, () => connector.readVariables(fileKey));
|
|
1801
|
-
// Get components (can be slow for large files)
|
|
1802
|
-
// Keyed by component key (unique) — name keys drop same-named
|
|
1803
|
-
// components on other pages.
|
|
1804
|
-
let rawComponents;
|
|
1805
|
-
let componentsFetchError = null;
|
|
1806
|
-
try {
|
|
1807
|
-
const componentsResult = await connector.getLocalComponents();
|
|
1808
|
-
if (componentsResult.success && componentsResult.data) {
|
|
1809
|
-
rawComponents = {
|
|
1810
|
-
components: componentsResult.data.components || [],
|
|
1811
|
-
componentSets: componentsResult.data.componentSets || [],
|
|
1812
|
-
};
|
|
1813
|
-
for (const comp of rawComponents.components) {
|
|
1814
|
-
manifest.components[comp.key || comp.nodeId] = {
|
|
1815
|
-
key: comp.key,
|
|
1816
|
-
nodeId: comp.nodeId,
|
|
1817
|
-
name: comp.name,
|
|
1818
|
-
description: comp.description || undefined,
|
|
1819
|
-
defaultSize: { width: comp.width, height: comp.height },
|
|
1820
|
-
};
|
|
1821
|
-
}
|
|
1822
|
-
for (const compSet of rawComponents.componentSets) {
|
|
1823
|
-
manifest.componentSets[compSet.key || compSet.nodeId] = {
|
|
1824
|
-
key: compSet.key,
|
|
1825
|
-
nodeId: compSet.nodeId,
|
|
1826
|
-
name: compSet.name,
|
|
1827
|
-
description: compSet.description || undefined,
|
|
1828
|
-
variants: compSet.variants?.map((v) => ({
|
|
1829
|
-
key: v.key,
|
|
1830
|
-
nodeId: v.nodeId,
|
|
1831
|
-
name: v.name,
|
|
1832
|
-
})) || [],
|
|
1833
|
-
variantAxes: compSet.variantAxes?.map((a) => ({
|
|
1834
|
-
name: a.name,
|
|
1835
|
-
values: a.values,
|
|
1836
|
-
})) || [],
|
|
1837
|
-
};
|
|
1838
|
-
}
|
|
1839
|
-
}
|
|
1840
|
-
else {
|
|
1841
|
-
componentsFetchError =
|
|
1842
|
-
componentsResult?.error || "getLocalComponents returned no data";
|
|
1843
|
-
}
|
|
1844
|
-
}
|
|
1845
|
-
catch (error) {
|
|
1846
|
-
componentsFetchError =
|
|
1847
|
-
error instanceof Error ? error.message : String(error);
|
|
1848
|
-
logger.warn({ error }, "Could not fetch components");
|
|
1849
|
-
}
|
|
1850
|
-
// Update summary
|
|
1851
|
-
manifest.summary = {
|
|
1852
|
-
totalTokens: Object.keys(manifest.tokens.colors).length +
|
|
1853
|
-
Object.keys(manifest.tokens.spacing).length,
|
|
1854
|
-
totalComponents: Object.keys(manifest.components).length,
|
|
1855
|
-
totalComponentSets: Object.keys(manifest.componentSets).length,
|
|
1856
|
-
colorPalette: Object.keys(manifest.tokens.colors).slice(0, 10),
|
|
1857
|
-
spacingScale: Object.values(manifest.tokens.spacing)
|
|
1858
|
-
.map((s) => s.value)
|
|
1859
|
-
.filter((v) => typeof v === "number")
|
|
1860
|
-
.sort((a, b) => a - b)
|
|
1861
|
-
.slice(0, 10),
|
|
1862
|
-
typographyScale: [],
|
|
1863
|
-
componentCategories: [],
|
|
1864
|
-
};
|
|
1865
|
-
// Cache the result — never cache a manifest built from a failed
|
|
1866
|
-
// components fetch (would serve empty results for the full TTL).
|
|
1867
|
-
if (!componentsFetchError && !variablesFetchError) {
|
|
1868
|
-
cache.set(fileKey, manifest, rawComponents);
|
|
1869
|
-
}
|
|
1870
|
-
const categories = getCategories(manifest);
|
|
1871
|
-
const tokenSummary = getTokenSummary(manifest);
|
|
1706
|
+
const { manifest } = cacheEntry;
|
|
1872
1707
|
return {
|
|
1873
1708
|
content: [
|
|
1874
1709
|
{
|
|
@@ -1884,13 +1719,13 @@ class LocalFigmaConsoleMCP {
|
|
|
1884
1719
|
componentSets: manifest.summary.totalComponentSets,
|
|
1885
1720
|
tokens: manifest.summary.totalTokens,
|
|
1886
1721
|
},
|
|
1887
|
-
warnings:
|
|
1722
|
+
warnings: componentsError || variablesError
|
|
1888
1723
|
? [
|
|
1889
|
-
|
|
1890
|
-
? `Components fetch failed (${
|
|
1724
|
+
componentsError
|
|
1725
|
+
? `Components fetch failed (${componentsError}) — component data is incomplete and was NOT cached. Check the Desktop Bridge plugin and retry.`
|
|
1891
1726
|
: null,
|
|
1892
|
-
|
|
1893
|
-
? `Variables fetch failed (${
|
|
1727
|
+
variablesError
|
|
1728
|
+
? `Variables fetch failed (${variablesError}) — tokens are missing and the result was NOT cached. Check the Desktop Bridge plugin and retry.`
|
|
1894
1729
|
: null,
|
|
1895
1730
|
].filter(Boolean)
|
|
1896
1731
|
: undefined,
|
|
@@ -2631,7 +2466,9 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
|
|
|
2631
2466
|
// popular styling methods (DTCG canonical — legacy + 2025.10 dialects —
|
|
2632
2467
|
// plus CSS/Tailwind/SCSS/TS/JSON/Style Dictionary/Tokens Studio, all
|
|
2633
2468
|
// derived from a single internal token model).
|
|
2634
|
-
registerTokensTools(server, () => this.getDesktopConnector()
|
|
2469
|
+
registerTokensTools(server, () => this.getDesktopConnector(), {
|
|
2470
|
+
onVariableWrite: () => this.invalidateVariablesCache(),
|
|
2471
|
+
});
|
|
2635
2472
|
// Register Figma API tools (Tools 8-11)
|
|
2636
2473
|
registerFigmaAPITools(server, () => this.getFigmaAPI(), () => this.getCurrentFileUrl(), this.variablesCache, // Pass cache for efficient variable queries
|
|
2637
2474
|
undefined, // options (use default)
|
|
@@ -2663,7 +2500,9 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
|
|
|
2663
2500
|
registerLibraryTools(server, () => this.getFigmaAPI());
|
|
2664
2501
|
// Register Library Variable Tools (Plugin-API based — list + import variables
|
|
2665
2502
|
// from subscribed team libraries; works on every Figma plan, no Enterprise needed)
|
|
2666
|
-
registerLibraryVariableTools(server, () => this.getDesktopConnector()
|
|
2503
|
+
registerLibraryVariableTools(server, () => this.getDesktopConnector(), {
|
|
2504
|
+
onVariableWrite: () => this.invalidateVariablesCache(),
|
|
2505
|
+
});
|
|
2667
2506
|
// Register code-side accessibility scanning (axe-core + JSDOM)
|
|
2668
2507
|
registerAccessibilityTools(server);
|
|
2669
2508
|
// Register figma_diagnose — designer-readable health check + cross-MCP disambiguator.
|
|
@@ -2777,17 +2616,19 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
|
|
|
2777
2616
|
}
|
|
2778
2617
|
// Priority 1: Try Desktop Bridge via transport-agnostic connector
|
|
2779
2618
|
try {
|
|
2619
|
+
const startedAt = cacheGeneration(this.variablesCache, fileKey);
|
|
2780
2620
|
const connector = await this.getDesktopConnector();
|
|
2781
2621
|
const desktopResult = await connector.readVariables(fileKey);
|
|
2782
2622
|
if (desktopResult.success && desktopResult.variables) {
|
|
2783
|
-
// Cache the desktop result
|
|
2784
|
-
|
|
2623
|
+
// Cache the desktop result, unless the cache was invalidated
|
|
2624
|
+
// while it was read
|
|
2625
|
+
setCacheIfCurrent(this.variablesCache, fileKey, {
|
|
2785
2626
|
data: {
|
|
2786
2627
|
variables: desktopResult.variables,
|
|
2787
2628
|
variableCollections: desktopResult.variableCollections,
|
|
2788
2629
|
},
|
|
2789
2630
|
timestamp: Date.now(),
|
|
2790
|
-
});
|
|
2631
|
+
}, startedAt);
|
|
2791
2632
|
return {
|
|
2792
2633
|
variables: desktopResult.variables,
|
|
2793
2634
|
collections: desktopResult.variableCollections || [],
|
|
@@ -2803,16 +2644,17 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
|
|
|
2803
2644
|
}, "Desktop Bridge failed for token browser, trying REST API");
|
|
2804
2645
|
}
|
|
2805
2646
|
// Priority 2: Fall back to REST API (requires Enterprise plan)
|
|
2647
|
+
const restStartedAt = cacheGeneration(this.variablesCache, fileKey);
|
|
2806
2648
|
const api = await this.getFigmaAPI();
|
|
2807
2649
|
const { local, localError } = await api.getAllVariables(fileKey);
|
|
2808
2650
|
if (localError) {
|
|
2809
2651
|
throw new Error(`Could not fetch variables. Desktop Bridge unavailable and REST API returned: ${localError}`);
|
|
2810
2652
|
}
|
|
2811
|
-
// Cache raw REST API data
|
|
2812
|
-
this.variablesCache
|
|
2653
|
+
// Cache raw REST API data, unless the cache was invalidated while it was read
|
|
2654
|
+
setCacheIfCurrent(this.variablesCache, fileKey, {
|
|
2813
2655
|
data: local,
|
|
2814
2656
|
timestamp: Date.now(),
|
|
2815
|
-
});
|
|
2657
|
+
}, restStartedAt);
|
|
2816
2658
|
const formatted = formatVariables(local);
|
|
2817
2659
|
return {
|
|
2818
2660
|
variables: formatted.variables,
|
|
@@ -2860,16 +2702,17 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
|
|
|
2860
2702
|
if (variables.length === 0) {
|
|
2861
2703
|
desktopBridgeAttempted = true;
|
|
2862
2704
|
try {
|
|
2705
|
+
const startedAt = cacheGeneration(this.variablesCache, fileKey);
|
|
2863
2706
|
const connector = await this.getDesktopConnector();
|
|
2864
2707
|
const desktopResult = await connector.readVariables(fileKey);
|
|
2865
2708
|
if (desktopResult.success && desktopResult.variables) {
|
|
2866
|
-
this.variablesCache
|
|
2709
|
+
setCacheIfCurrent(this.variablesCache, fileKey, {
|
|
2867
2710
|
data: {
|
|
2868
2711
|
variables: desktopResult.variables,
|
|
2869
2712
|
variableCollections: desktopResult.variableCollections,
|
|
2870
2713
|
},
|
|
2871
2714
|
timestamp: Date.now(),
|
|
2872
|
-
});
|
|
2715
|
+
}, startedAt);
|
|
2873
2716
|
variables = desktopResult.variables;
|
|
2874
2717
|
collections = desktopResult.variableCollections || [];
|
|
2875
2718
|
variablesAvailable = true;
|
|
@@ -2891,13 +2734,14 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
|
|
|
2891
2734
|
if (variables.length === 0) {
|
|
2892
2735
|
restApiAttempted = true;
|
|
2893
2736
|
try {
|
|
2737
|
+
const startedAt = cacheGeneration(this.variablesCache, fileKey);
|
|
2894
2738
|
const api = await this.getFigmaAPI();
|
|
2895
2739
|
const { local, localError } = await api.getAllVariables(fileKey);
|
|
2896
2740
|
if (!localError && local) {
|
|
2897
|
-
this.variablesCache
|
|
2741
|
+
setCacheIfCurrent(this.variablesCache, fileKey, {
|
|
2898
2742
|
data: local,
|
|
2899
2743
|
timestamp: Date.now(),
|
|
2900
|
-
});
|
|
2744
|
+
}, startedAt);
|
|
2901
2745
|
const formatted = formatVariables(local);
|
|
2902
2746
|
variables = formatted.variables;
|
|
2903
2747
|
collections = formatted.collections;
|
|
@@ -3134,6 +2978,10 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
|
|
|
3134
2978
|
});
|
|
3135
2979
|
});
|
|
3136
2980
|
}
|
|
2981
|
+
/** True once the Streamable HTTP listener is up (MCP_HTTP_PORT set and listen succeeded). */
|
|
2982
|
+
isHttpServing() {
|
|
2983
|
+
return this.mcpHttpPort !== null;
|
|
2984
|
+
}
|
|
3137
2985
|
/**
|
|
3138
2986
|
* Start the MCP server
|
|
3139
2987
|
*/
|
|
@@ -3190,7 +3038,7 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
|
|
|
3190
3038
|
}
|
|
3191
3039
|
// Advertise the port so the Figma plugin and other tools can discover us
|
|
3192
3040
|
advertisePort(boundPort, wsHost);
|
|
3193
|
-
registerPortCleanup(boundPort);
|
|
3041
|
+
this.unregisterPortCleanup = registerPortCleanup(boundPort);
|
|
3194
3042
|
// Start heartbeat — periodically refresh the port file to prove this server is active.
|
|
3195
3043
|
// Other instances use this to detect zombie processes on startup.
|
|
3196
3044
|
const heartbeatPort = boundPort;
|
|
@@ -3229,7 +3077,7 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
|
|
|
3229
3077
|
this.wsActualPort = boundPort;
|
|
3230
3078
|
logger.info({ wsPort: boundPort, eviction: true }, "WebSocket bridge server started after evicting stale instance");
|
|
3231
3079
|
advertisePort(boundPort, wsHost);
|
|
3232
|
-
registerPortCleanup(boundPort);
|
|
3080
|
+
this.unregisterPortCleanup = registerPortCleanup(boundPort);
|
|
3233
3081
|
const heartbeatPort = boundPort;
|
|
3234
3082
|
this.wsHeartbeatTimer = setInterval(() => refreshPortAdvertisement(heartbeatPort), HEARTBEAT_INTERVAL_MS);
|
|
3235
3083
|
this.wsHeartbeatTimer.unref();
|
|
@@ -3263,47 +3111,11 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
|
|
|
3263
3111
|
this.wsServer.on("fileConnected", (data) => {
|
|
3264
3112
|
logger.info({ fileKey: data.fileKey, fileName: data.fileName }, "Desktop Bridge plugin connected via WebSocket");
|
|
3265
3113
|
});
|
|
3266
|
-
//
|
|
3267
|
-
//
|
|
3268
|
-
|
|
3269
|
-
// Invalidate the cache for the disconnected file so the next read is fresh.
|
|
3114
|
+
// Cache invalidation on disconnect and document changes lives in
|
|
3115
|
+
// core/cache-invalidation.ts so it can be tested by behaviour.
|
|
3116
|
+
attachCacheInvalidation(this.wsServer, { variablesCache: this.variablesCache, manifestCache: this.manifestCache });
|
|
3270
3117
|
this.wsServer.on("fileDisconnected", (data) => {
|
|
3271
3118
|
logger.info({ fileKey: data.fileKey, fileName: data.fileName }, "Desktop Bridge plugin disconnected from WebSocket");
|
|
3272
|
-
if (data.fileKey) {
|
|
3273
|
-
this.variablesCache.delete(data.fileKey);
|
|
3274
|
-
// design-system-tools.ts stores token data under a prefixed key
|
|
3275
|
-
this.variablesCache.delete(`vars:${data.fileKey}`);
|
|
3276
|
-
void import("./core/design-system-manifest.js").then(({ DesignSystemManifestCache }) => {
|
|
3277
|
-
DesignSystemManifestCache.getInstance().invalidate(data.fileKey);
|
|
3278
|
-
}).catch(() => { });
|
|
3279
|
-
}
|
|
3280
|
-
});
|
|
3281
|
-
// Invalidate variable cache when document changes are reported.
|
|
3282
|
-
// Figma's documentchange API doesn't expose a specific variable change type —
|
|
3283
|
-
// variable operations manifest as node PROPERTY_CHANGE events, so we invalidate
|
|
3284
|
-
// on any style or node change to be safe.
|
|
3285
|
-
this.wsServer.on("documentChange", (data) => {
|
|
3286
|
-
if (data.hasStyleChanges || data.hasNodeChanges) {
|
|
3287
|
-
if (data.fileKey) {
|
|
3288
|
-
// Per-file cache invalidation — only clear the affected file's cache.
|
|
3289
|
-
// Also clear the design-system-tools token entry (prefixed key)
|
|
3290
|
-
// and the component manifest, so searches see new components
|
|
3291
|
-
// and the design-system kit sees edited variables.
|
|
3292
|
-
this.variablesCache.delete(data.fileKey);
|
|
3293
|
-
this.variablesCache.delete(`vars:${data.fileKey}`);
|
|
3294
|
-
void import("./core/design-system-manifest.js").then(({ DesignSystemManifestCache }) => {
|
|
3295
|
-
DesignSystemManifestCache.getInstance().invalidate(data.fileKey);
|
|
3296
|
-
}).catch(() => { });
|
|
3297
|
-
logger.debug({ fileKey: data.fileKey, changeCount: data.changeCount, hasStyleChanges: data.hasStyleChanges, hasNodeChanges: data.hasNodeChanges }, "Variable cache invalidated due to document changes");
|
|
3298
|
-
}
|
|
3299
|
-
else {
|
|
3300
|
-
// Unidentified file (event arrived before FILE_INFO handshake completed).
|
|
3301
|
-
// We don't know which cache entry to invalidate; do nothing rather than
|
|
3302
|
-
// blanket-clear other files' caches. FILE_INFO will arrive shortly and
|
|
3303
|
-
// any subsequent document changes will route correctly.
|
|
3304
|
-
logger.debug({ changeCount: data.changeCount }, "Document change received before file identification — cache untouched");
|
|
3305
|
-
}
|
|
3306
|
-
}
|
|
3307
3119
|
});
|
|
3308
3120
|
}
|
|
3309
3121
|
// Periodically reap orphaned/zombie servers for the whole run, not just
|
|
@@ -3332,8 +3144,8 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
|
|
|
3332
3144
|
// back to initialize; it discards the probe's instance, which is pinned
|
|
3333
3145
|
// to the modern era, so a re-pin must get a fresh server.
|
|
3334
3146
|
// On stdin EOF the SDK closes the connection but never exits the
|
|
3335
|
-
// process
|
|
3336
|
-
//
|
|
3147
|
+
// process. Without HTTP, main() exits on EOF (nothing else can reach
|
|
3148
|
+
// this server); with MCP_HTTP_PORT active it keeps serving.
|
|
3337
3149
|
let stdioServerHandedOut = false;
|
|
3338
3150
|
serveStdio(() => {
|
|
3339
3151
|
if (stdioServerHandedOut)
|
|
@@ -3375,6 +3187,8 @@ Without libraryFileKey/libraryFileUrl, searches the currently open file (local c
|
|
|
3375
3187
|
// Clean up port advertisement before stopping the server
|
|
3376
3188
|
if (this.wsActualPort) {
|
|
3377
3189
|
unadvertisePort(this.wsActualPort);
|
|
3190
|
+
this.unregisterPortCleanup?.();
|
|
3191
|
+
this.unregisterPortCleanup = null;
|
|
3378
3192
|
}
|
|
3379
3193
|
if (this.modernHttpHandler) {
|
|
3380
3194
|
await this.modernHttpHandler.close();
|
|
@@ -3427,6 +3241,12 @@ async function main() {
|
|
|
3427
3241
|
process.on("SIGTERM", () => { void gracefulExit(0); });
|
|
3428
3242
|
// Start the server
|
|
3429
3243
|
await server.start();
|
|
3244
|
+
// Without an HTTP transport, stdin is the only way a client reaches this
|
|
3245
|
+
// process: when it closes, nothing can use the server, so exit and release
|
|
3246
|
+
// the WebSocket port. With HTTP serving, EOF leaves the daemon running.
|
|
3247
|
+
if (!server.isHttpServing()) {
|
|
3248
|
+
onStdinClosed(() => { void gracefulExit(0); });
|
|
3249
|
+
}
|
|
3430
3250
|
}
|
|
3431
3251
|
// Run if executed directly
|
|
3432
3252
|
// Note: On Windows, import.meta.url uses file:/// (3 slashes) while process.argv uses backslashes
|