@mp3wizard/figma-console-mcp 1.14.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.
- package/LICENSE +21 -0
- package/README.md +816 -0
- package/dist/apps/design-system-dashboard/scoring/accessibility.d.ts +14 -0
- package/dist/apps/design-system-dashboard/scoring/accessibility.d.ts.map +1 -0
- package/dist/apps/design-system-dashboard/scoring/accessibility.js +278 -0
- package/dist/apps/design-system-dashboard/scoring/accessibility.js.map +1 -0
- package/dist/apps/design-system-dashboard/scoring/component-metadata.d.ts +29 -0
- package/dist/apps/design-system-dashboard/scoring/component-metadata.d.ts.map +1 -0
- package/dist/apps/design-system-dashboard/scoring/component-metadata.js +358 -0
- package/dist/apps/design-system-dashboard/scoring/component-metadata.js.map +1 -0
- package/dist/apps/design-system-dashboard/scoring/consistency.d.ts +14 -0
- package/dist/apps/design-system-dashboard/scoring/consistency.d.ts.map +1 -0
- package/dist/apps/design-system-dashboard/scoring/consistency.js +342 -0
- package/dist/apps/design-system-dashboard/scoring/consistency.js.map +1 -0
- package/dist/apps/design-system-dashboard/scoring/coverage.d.ts +14 -0
- package/dist/apps/design-system-dashboard/scoring/coverage.d.ts.map +1 -0
- package/dist/apps/design-system-dashboard/scoring/coverage.js +231 -0
- package/dist/apps/design-system-dashboard/scoring/coverage.js.map +1 -0
- package/dist/apps/design-system-dashboard/scoring/engine.d.ts +27 -0
- package/dist/apps/design-system-dashboard/scoring/engine.d.ts.map +1 -0
- package/dist/apps/design-system-dashboard/scoring/engine.js +93 -0
- package/dist/apps/design-system-dashboard/scoring/engine.js.map +1 -0
- package/dist/apps/design-system-dashboard/scoring/naming-semantics.d.ts +14 -0
- package/dist/apps/design-system-dashboard/scoring/naming-semantics.d.ts.map +1 -0
- package/dist/apps/design-system-dashboard/scoring/naming-semantics.js +309 -0
- package/dist/apps/design-system-dashboard/scoring/naming-semantics.js.map +1 -0
- package/dist/apps/design-system-dashboard/scoring/token-architecture.d.ts +14 -0
- package/dist/apps/design-system-dashboard/scoring/token-architecture.d.ts.map +1 -0
- package/dist/apps/design-system-dashboard/scoring/token-architecture.js +350 -0
- package/dist/apps/design-system-dashboard/scoring/token-architecture.js.map +1 -0
- package/dist/apps/design-system-dashboard/scoring/types.d.ts +89 -0
- package/dist/apps/design-system-dashboard/scoring/types.d.ts.map +1 -0
- package/dist/apps/design-system-dashboard/scoring/types.js +41 -0
- package/dist/apps/design-system-dashboard/scoring/types.js.map +1 -0
- package/dist/apps/design-system-dashboard/server.d.ts +24 -0
- package/dist/apps/design-system-dashboard/server.d.ts.map +1 -0
- package/dist/apps/design-system-dashboard/server.js +160 -0
- package/dist/apps/design-system-dashboard/server.js.map +1 -0
- package/dist/apps/token-browser/server.d.ts +26 -0
- package/dist/apps/token-browser/server.d.ts.map +1 -0
- package/dist/apps/token-browser/server.js +137 -0
- package/dist/apps/token-browser/server.js.map +1 -0
- package/dist/browser/base.d.ts +58 -0
- package/dist/browser/base.d.ts.map +1 -0
- package/dist/browser/base.js +6 -0
- package/dist/browser/base.js.map +1 -0
- package/dist/browser/local.d.ts +87 -0
- package/dist/browser/local.d.ts.map +1 -0
- package/dist/browser/local.js +318 -0
- package/dist/browser/local.js.map +1 -0
- package/dist/cloudflare/apps/design-system-dashboard/scoring/accessibility.js +277 -0
- package/dist/cloudflare/apps/design-system-dashboard/scoring/component-metadata.js +357 -0
- package/dist/cloudflare/apps/design-system-dashboard/scoring/consistency.js +341 -0
- package/dist/cloudflare/apps/design-system-dashboard/scoring/coverage.js +230 -0
- package/dist/cloudflare/apps/design-system-dashboard/scoring/engine.js +92 -0
- package/dist/cloudflare/apps/design-system-dashboard/scoring/naming-semantics.js +308 -0
- package/dist/cloudflare/apps/design-system-dashboard/scoring/token-architecture.js +349 -0
- package/dist/cloudflare/apps/design-system-dashboard/scoring/types.js +40 -0
- package/dist/cloudflare/apps/design-system-dashboard/server.js +159 -0
- package/dist/cloudflare/apps/token-browser/server.js +136 -0
- package/dist/cloudflare/browser/base.js +5 -0
- package/dist/cloudflare/browser/cloudflare.js +156 -0
- package/dist/cloudflare/browser-manager.js +157 -0
- package/dist/cloudflare/core/cloud-websocket-connector.js +267 -0
- package/dist/cloudflare/core/cloud-websocket-relay.js +199 -0
- package/dist/cloudflare/core/comment-tools.js +292 -0
- package/dist/cloudflare/core/config.js +161 -0
- package/dist/cloudflare/core/console-monitor.js +427 -0
- package/dist/cloudflare/core/design-code-tools.js +2504 -0
- package/dist/cloudflare/core/design-system-manifest.js +260 -0
- package/dist/cloudflare/core/design-system-tools.js +863 -0
- package/dist/cloudflare/core/enrichment/enrichment-service.js +272 -0
- package/dist/cloudflare/core/enrichment/index.js +7 -0
- package/dist/cloudflare/core/enrichment/relationship-mapper.js +351 -0
- package/dist/cloudflare/core/enrichment/style-resolver.js +326 -0
- package/dist/cloudflare/core/figma-api.js +409 -0
- package/dist/cloudflare/core/figma-connector.js +7 -0
- package/dist/cloudflare/core/figma-desktop-connector.js +1184 -0
- package/dist/cloudflare/core/figma-reconstruction-spec.js +402 -0
- package/dist/cloudflare/core/figma-style-extractor.js +311 -0
- package/dist/cloudflare/core/figma-tools.js +2947 -0
- package/dist/cloudflare/core/logger.js +53 -0
- package/dist/cloudflare/core/port-discovery.js +282 -0
- package/dist/cloudflare/core/snippet-injector.js +96 -0
- package/dist/cloudflare/core/types/design-code.js +4 -0
- package/dist/cloudflare/core/types/enriched.js +5 -0
- package/dist/cloudflare/core/types/index.js +4 -0
- package/dist/cloudflare/core/websocket-connector.js +256 -0
- package/dist/cloudflare/core/websocket-server.js +646 -0
- package/dist/cloudflare/core/write-tools.js +2091 -0
- package/dist/cloudflare/index.js +2899 -0
- package/dist/cloudflare/test-browser.js +88 -0
- package/dist/core/comment-tools.d.ts +11 -0
- package/dist/core/comment-tools.d.ts.map +1 -0
- package/dist/core/comment-tools.js +293 -0
- package/dist/core/comment-tools.js.map +1 -0
- package/dist/core/config.d.ts +17 -0
- package/dist/core/config.d.ts.map +1 -0
- package/dist/core/config.js +162 -0
- package/dist/core/config.js.map +1 -0
- package/dist/core/console-monitor.d.ts +82 -0
- package/dist/core/console-monitor.d.ts.map +1 -0
- package/dist/core/console-monitor.js +428 -0
- package/dist/core/console-monitor.js.map +1 -0
- package/dist/core/design-code-tools.d.ts +127 -0
- package/dist/core/design-code-tools.d.ts.map +1 -0
- package/dist/core/design-code-tools.js +2505 -0
- package/dist/core/design-code-tools.js.map +1 -0
- package/dist/core/design-system-manifest.d.ts +272 -0
- package/dist/core/design-system-manifest.d.ts.map +1 -0
- package/dist/core/design-system-manifest.js +261 -0
- package/dist/core/design-system-manifest.js.map +1 -0
- package/dist/core/design-system-tools.d.ts +17 -0
- package/dist/core/design-system-tools.d.ts.map +1 -0
- package/dist/core/design-system-tools.js +864 -0
- package/dist/core/design-system-tools.js.map +1 -0
- package/dist/core/enrichment/enrichment-service.d.ts +52 -0
- package/dist/core/enrichment/enrichment-service.d.ts.map +1 -0
- package/dist/core/enrichment/enrichment-service.js +273 -0
- package/dist/core/enrichment/enrichment-service.js.map +1 -0
- package/dist/core/enrichment/index.d.ts +8 -0
- package/dist/core/enrichment/index.d.ts.map +1 -0
- package/dist/core/enrichment/index.js +8 -0
- package/dist/core/enrichment/index.js.map +1 -0
- package/dist/core/enrichment/relationship-mapper.d.ts +106 -0
- package/dist/core/enrichment/relationship-mapper.d.ts.map +1 -0
- package/dist/core/enrichment/relationship-mapper.js +352 -0
- package/dist/core/enrichment/relationship-mapper.js.map +1 -0
- package/dist/core/enrichment/style-resolver.d.ts +80 -0
- package/dist/core/enrichment/style-resolver.d.ts.map +1 -0
- package/dist/core/enrichment/style-resolver.js +327 -0
- package/dist/core/enrichment/style-resolver.js.map +1 -0
- package/dist/core/figma-api.d.ts +201 -0
- package/dist/core/figma-api.d.ts.map +1 -0
- package/dist/core/figma-api.js +410 -0
- package/dist/core/figma-api.js.map +1 -0
- package/dist/core/figma-connector.d.ts +48 -0
- package/dist/core/figma-connector.d.ts.map +1 -0
- package/dist/core/figma-connector.js +8 -0
- package/dist/core/figma-connector.js.map +1 -0
- package/dist/core/figma-desktop-connector.d.ts +265 -0
- package/dist/core/figma-desktop-connector.d.ts.map +1 -0
- package/dist/core/figma-desktop-connector.js +1184 -0
- package/dist/core/figma-desktop-connector.js.map +1 -0
- package/dist/core/figma-reconstruction-spec.d.ts +166 -0
- package/dist/core/figma-reconstruction-spec.d.ts.map +1 -0
- package/dist/core/figma-reconstruction-spec.js +403 -0
- package/dist/core/figma-reconstruction-spec.js.map +1 -0
- package/dist/core/figma-style-extractor.d.ts +76 -0
- package/dist/core/figma-style-extractor.d.ts.map +1 -0
- package/dist/core/figma-style-extractor.js +312 -0
- package/dist/core/figma-style-extractor.js.map +1 -0
- package/dist/core/figma-tools.d.ts +23 -0
- package/dist/core/figma-tools.d.ts.map +1 -0
- package/dist/core/figma-tools.js +2948 -0
- package/dist/core/figma-tools.js.map +1 -0
- package/dist/core/logger.d.ts +22 -0
- package/dist/core/logger.d.ts.map +1 -0
- package/dist/core/logger.js +54 -0
- package/dist/core/logger.js.map +1 -0
- package/dist/core/port-discovery.d.ts +110 -0
- package/dist/core/port-discovery.d.ts.map +1 -0
- package/dist/core/port-discovery.js +283 -0
- package/dist/core/port-discovery.js.map +1 -0
- package/dist/core/snippet-injector.d.ts +24 -0
- package/dist/core/snippet-injector.d.ts.map +1 -0
- package/dist/core/snippet-injector.js +97 -0
- package/dist/core/snippet-injector.js.map +1 -0
- package/dist/core/types/design-code.d.ts +262 -0
- package/dist/core/types/design-code.d.ts.map +1 -0
- package/dist/core/types/design-code.js +5 -0
- package/dist/core/types/design-code.js.map +1 -0
- package/dist/core/types/enriched.d.ts +213 -0
- package/dist/core/types/enriched.d.ts.map +1 -0
- package/dist/core/types/enriched.js +6 -0
- package/dist/core/types/enriched.js.map +1 -0
- package/dist/core/types/index.d.ts +112 -0
- package/dist/core/types/index.d.ts.map +1 -0
- package/dist/core/types/index.js +5 -0
- package/dist/core/types/index.js.map +1 -0
- package/dist/core/websocket-connector.d.ts +55 -0
- package/dist/core/websocket-connector.d.ts.map +1 -0
- package/dist/core/websocket-connector.js +257 -0
- package/dist/core/websocket-connector.js.map +1 -0
- package/dist/core/websocket-server.d.ts +191 -0
- package/dist/core/websocket-server.d.ts.map +1 -0
- package/dist/core/websocket-server.js +647 -0
- package/dist/core/websocket-server.js.map +1 -0
- package/dist/core/write-tools.d.ts +7 -0
- package/dist/core/write-tools.d.ts.map +1 -0
- package/dist/core/write-tools.js +2092 -0
- package/dist/core/write-tools.js.map +1 -0
- package/dist/local.d.ts +84 -0
- package/dist/local.d.ts.map +1 -0
- package/dist/local.js +5039 -0
- package/dist/local.js.map +1 -0
- package/figma-desktop-bridge/README.md +313 -0
- package/figma-desktop-bridge/code.js +2818 -0
- package/figma-desktop-bridge/manifest.json +67 -0
- package/figma-desktop-bridge/ui.html +1236 -0
- package/package.json +87 -0
|
@@ -0,0 +1,2947 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Figma API MCP Tools
|
|
3
|
+
* MCP tool definitions for Figma REST API data extraction
|
|
4
|
+
*/
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { extractFileKey, extractFigmaUrlInfo, formatVariables, formatComponentData, withTimeout } from "./figma-api.js";
|
|
7
|
+
import { createChildLogger } from "./logger.js";
|
|
8
|
+
import { EnrichmentService } from "./enrichment/index.js";
|
|
9
|
+
import { SnippetInjector } from "./snippet-injector.js";
|
|
10
|
+
import { extractNodeSpec, validateReconstructionSpec, listVariants } from "./figma-reconstruction-spec.js";
|
|
11
|
+
const logger = createChildLogger({ component: "figma-tools" });
|
|
12
|
+
// Initialize enrichment service
|
|
13
|
+
const enrichmentService = new EnrichmentService(logger);
|
|
14
|
+
// Initialize snippet injector
|
|
15
|
+
const snippetInjector = new SnippetInjector();
|
|
16
|
+
// ============================================================================
|
|
17
|
+
// Cache Management & Data Processing Helpers
|
|
18
|
+
// ============================================================================
|
|
19
|
+
/**
|
|
20
|
+
* Cache configuration
|
|
21
|
+
*/
|
|
22
|
+
const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
|
|
23
|
+
const MAX_CACHE_ENTRIES = 10; // LRU eviction
|
|
24
|
+
/**
|
|
25
|
+
* Check if cache entry is still valid based on TTL
|
|
26
|
+
*/
|
|
27
|
+
function isCacheValid(timestamp, ttlMs = CACHE_TTL_MS) {
|
|
28
|
+
return Date.now() - timestamp < ttlMs;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Rough token estimation for response size checking
|
|
32
|
+
* Approximation: 1 token ≈ 4 characters for JSON
|
|
33
|
+
*/
|
|
34
|
+
function estimateTokens(data) {
|
|
35
|
+
const jsonString = JSON.stringify(data);
|
|
36
|
+
return Math.ceil(jsonString.length / 4);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Response size thresholds for adaptive verbosity
|
|
40
|
+
* Based on typical Claude Desktop context window limits
|
|
41
|
+
*/
|
|
42
|
+
const RESPONSE_SIZE_THRESHOLDS = {
|
|
43
|
+
// Conservative thresholds to leave room for conversation context
|
|
44
|
+
IDEAL_SIZE_KB: 100, // Target size for optimal performance
|
|
45
|
+
WARNING_SIZE_KB: 200, // Start considering compression
|
|
46
|
+
CRITICAL_SIZE_KB: 500, // Must compress to avoid context exhaustion
|
|
47
|
+
MAX_SIZE_KB: 1000, // Absolute maximum before emergency compression
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Calculate JSON string size in KB
|
|
51
|
+
*/
|
|
52
|
+
function calculateSizeKB(data) {
|
|
53
|
+
const jsonString = JSON.stringify(data);
|
|
54
|
+
return jsonString.length / 1024;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Generic adaptive response wrapper - automatically compresses responses that exceed size thresholds
|
|
58
|
+
* Can be used by any tool to prevent context window exhaustion
|
|
59
|
+
*
|
|
60
|
+
* @param responseData - The response data to potentially compress
|
|
61
|
+
* @param options - Configuration options for compression behavior
|
|
62
|
+
* @returns Response content array with optional AI instruction
|
|
63
|
+
*/
|
|
64
|
+
function adaptiveResponse(responseData, options) {
|
|
65
|
+
const sizeKB = calculateSizeKB(responseData);
|
|
66
|
+
// No compression needed
|
|
67
|
+
if (sizeKB <= RESPONSE_SIZE_THRESHOLDS.IDEAL_SIZE_KB) {
|
|
68
|
+
return {
|
|
69
|
+
content: [
|
|
70
|
+
{
|
|
71
|
+
type: "text",
|
|
72
|
+
text: JSON.stringify(responseData),
|
|
73
|
+
},
|
|
74
|
+
],
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
// Determine compression level and message
|
|
78
|
+
let compressionLevel = "info";
|
|
79
|
+
let aiInstruction = "";
|
|
80
|
+
let shouldCompress = false;
|
|
81
|
+
if (sizeKB > RESPONSE_SIZE_THRESHOLDS.MAX_SIZE_KB) {
|
|
82
|
+
compressionLevel = "emergency";
|
|
83
|
+
shouldCompress = true;
|
|
84
|
+
aiInstruction =
|
|
85
|
+
`⚠️ RESPONSE AUTO-COMPRESSED: The ${options.toolName} response was automatically reduced because the full response would be ${sizeKB.toFixed(0)}KB, which would exhaust Claude Desktop's context window.\n\n`;
|
|
86
|
+
}
|
|
87
|
+
else if (sizeKB > RESPONSE_SIZE_THRESHOLDS.CRITICAL_SIZE_KB) {
|
|
88
|
+
compressionLevel = "critical";
|
|
89
|
+
shouldCompress = true;
|
|
90
|
+
aiInstruction =
|
|
91
|
+
`⚠️ RESPONSE AUTO-COMPRESSED: The ${options.toolName} response was automatically reduced because it would be ${sizeKB.toFixed(0)}KB, risking context window exhaustion.\n\n`;
|
|
92
|
+
}
|
|
93
|
+
else if (sizeKB > RESPONSE_SIZE_THRESHOLDS.WARNING_SIZE_KB) {
|
|
94
|
+
compressionLevel = "warning";
|
|
95
|
+
shouldCompress = true;
|
|
96
|
+
aiInstruction =
|
|
97
|
+
`ℹ️ RESPONSE OPTIMIZED: The ${options.toolName} response was automatically reduced because it would be ${sizeKB.toFixed(0)}KB.\n\n`;
|
|
98
|
+
}
|
|
99
|
+
// Map compression level to verbosity level
|
|
100
|
+
const verbosityMap = {
|
|
101
|
+
"info": "standard",
|
|
102
|
+
"warning": "summary",
|
|
103
|
+
"critical": "summary",
|
|
104
|
+
"emergency": "inventory"
|
|
105
|
+
};
|
|
106
|
+
// If compression needed, apply callback to reduce data
|
|
107
|
+
let finalData = responseData;
|
|
108
|
+
if (shouldCompress && options.compressionCallback) {
|
|
109
|
+
const targetVerbosity = verbosityMap[compressionLevel] || "summary";
|
|
110
|
+
finalData = options.compressionCallback(targetVerbosity);
|
|
111
|
+
// Add compression metadata
|
|
112
|
+
finalData.compression = {
|
|
113
|
+
originalSizeKB: Math.round(sizeKB),
|
|
114
|
+
finalSizeKB: Math.round(calculateSizeKB(finalData)),
|
|
115
|
+
compressionLevel,
|
|
116
|
+
};
|
|
117
|
+
logger.info({
|
|
118
|
+
tool: options.toolName,
|
|
119
|
+
originalSizeKB: sizeKB.toFixed(2),
|
|
120
|
+
finalSizeKB: calculateSizeKB(finalData).toFixed(2),
|
|
121
|
+
compressionLevel,
|
|
122
|
+
}, "Response compressed to prevent context exhaustion");
|
|
123
|
+
}
|
|
124
|
+
// Build AI instruction with suggested actions
|
|
125
|
+
if (shouldCompress) {
|
|
126
|
+
if (options.suggestedActions && options.suggestedActions.length > 0) {
|
|
127
|
+
aiInstruction += `To get more detail:\n`;
|
|
128
|
+
options.suggestedActions.forEach(action => {
|
|
129
|
+
aiInstruction += `• ${action}\n`;
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
// Build response content
|
|
134
|
+
const content = [
|
|
135
|
+
{
|
|
136
|
+
type: "text",
|
|
137
|
+
text: JSON.stringify(finalData),
|
|
138
|
+
},
|
|
139
|
+
];
|
|
140
|
+
// Add AI instruction as separate content block if needed
|
|
141
|
+
if (aiInstruction) {
|
|
142
|
+
content.unshift({
|
|
143
|
+
type: "text",
|
|
144
|
+
text: aiInstruction.trim(),
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
return { content };
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Adaptive verbosity system - automatically downgrades verbosity based on response size
|
|
151
|
+
* Returns adjusted verbosity level and compression info for AI instructions
|
|
152
|
+
*
|
|
153
|
+
* @deprecated Use adaptiveResponse instead for more flexible compression
|
|
154
|
+
*/
|
|
155
|
+
function adaptiveVerbosity(data, requestedVerbosity) {
|
|
156
|
+
const sizeKB = calculateSizeKB(data);
|
|
157
|
+
// No adjustment needed - response is within ideal size
|
|
158
|
+
if (sizeKB <= RESPONSE_SIZE_THRESHOLDS.IDEAL_SIZE_KB) {
|
|
159
|
+
return {
|
|
160
|
+
adjustedVerbosity: requestedVerbosity,
|
|
161
|
+
sizeKB,
|
|
162
|
+
wasCompressed: false,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
// Determine appropriate verbosity based on size
|
|
166
|
+
let adjustedVerbosity = requestedVerbosity;
|
|
167
|
+
let compressionReason = "";
|
|
168
|
+
let aiInstruction = "";
|
|
169
|
+
if (sizeKB > RESPONSE_SIZE_THRESHOLDS.MAX_SIZE_KB) {
|
|
170
|
+
// Emergency: Force inventory mode
|
|
171
|
+
adjustedVerbosity = "inventory";
|
|
172
|
+
compressionReason = `Response size (${sizeKB.toFixed(0)}KB) exceeds maximum threshold (${RESPONSE_SIZE_THRESHOLDS.MAX_SIZE_KB}KB)`;
|
|
173
|
+
aiInstruction =
|
|
174
|
+
`⚠️ RESPONSE AUTO-COMPRESSED: The response was automatically reduced to 'inventory' verbosity (names/IDs only) because the full response would be ${sizeKB.toFixed(0)}KB, which would exhaust Claude Desktop's context window.\n\n` +
|
|
175
|
+
`To get more detail:\n` +
|
|
176
|
+
`• Use format='filtered' with collection/namePattern/mode filters to narrow the scope\n` +
|
|
177
|
+
`• Use pagination (page=1, pageSize=20) to retrieve data in smaller chunks\n` +
|
|
178
|
+
`• Use returnAsLinks=true to get resource_link references instead of full data\n\n` +
|
|
179
|
+
`Current response contains variable/collection names and IDs only.`;
|
|
180
|
+
}
|
|
181
|
+
else if (sizeKB > RESPONSE_SIZE_THRESHOLDS.CRITICAL_SIZE_KB) {
|
|
182
|
+
// Critical: Downgrade to summary if higher was requested
|
|
183
|
+
if (requestedVerbosity === "full" || requestedVerbosity === "standard") {
|
|
184
|
+
adjustedVerbosity = "summary";
|
|
185
|
+
compressionReason = `Response size (${sizeKB.toFixed(0)}KB) exceeds critical threshold (${RESPONSE_SIZE_THRESHOLDS.CRITICAL_SIZE_KB}KB)`;
|
|
186
|
+
aiInstruction =
|
|
187
|
+
`⚠️ RESPONSE AUTO-COMPRESSED: The response was automatically reduced to 'summary' verbosity because the ${requestedVerbosity} response would be ${sizeKB.toFixed(0)}KB, risking context window exhaustion.\n\n` +
|
|
188
|
+
`To get more detail, use filtering options:\n` +
|
|
189
|
+
`• format='filtered' with collection='CollectionName' to focus on specific collections\n` +
|
|
190
|
+
`• namePattern='color' to filter by variable name\n` +
|
|
191
|
+
`• mode='Light' to filter by mode\n` +
|
|
192
|
+
`• pagination with smaller pageSize values\n\n` +
|
|
193
|
+
`Current response includes variable names, types, and mode information.`;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
else if (sizeKB > RESPONSE_SIZE_THRESHOLDS.WARNING_SIZE_KB) {
|
|
197
|
+
// Warning: Downgrade full to standard
|
|
198
|
+
if (requestedVerbosity === "full") {
|
|
199
|
+
adjustedVerbosity = "standard";
|
|
200
|
+
compressionReason = `Response size (${sizeKB.toFixed(0)}KB) exceeds warning threshold (${RESPONSE_SIZE_THRESHOLDS.WARNING_SIZE_KB}KB)`;
|
|
201
|
+
aiInstruction =
|
|
202
|
+
`ℹ️ RESPONSE OPTIMIZED: The response was automatically reduced to 'standard' verbosity because the full response would be ${sizeKB.toFixed(0)}KB.\n\n` +
|
|
203
|
+
`This response includes essential variable properties. For specific details, use filtering:\n` +
|
|
204
|
+
`• format='filtered' with collection/namePattern/mode filters\n` +
|
|
205
|
+
`• Request verbosity='full' with specific filters to get complete data for a subset`;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
const wasCompressed = adjustedVerbosity !== requestedVerbosity;
|
|
209
|
+
if (wasCompressed) {
|
|
210
|
+
logger.info({
|
|
211
|
+
originalVerbosity: requestedVerbosity,
|
|
212
|
+
adjustedVerbosity,
|
|
213
|
+
sizeKB: sizeKB.toFixed(2),
|
|
214
|
+
threshold: compressionReason,
|
|
215
|
+
}, "Adaptive compression applied");
|
|
216
|
+
}
|
|
217
|
+
return {
|
|
218
|
+
adjustedVerbosity,
|
|
219
|
+
sizeKB,
|
|
220
|
+
wasCompressed,
|
|
221
|
+
compressionReason: wasCompressed ? compressionReason : undefined,
|
|
222
|
+
aiInstruction: wasCompressed ? aiInstruction : undefined,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Generate compact summary of variables data (~2K tokens)
|
|
227
|
+
* Returns high-level overview with counts and names
|
|
228
|
+
*/
|
|
229
|
+
function generateSummary(data) {
|
|
230
|
+
const summary = {
|
|
231
|
+
fileKey: data.fileKey,
|
|
232
|
+
timestamp: data.timestamp,
|
|
233
|
+
source: data.source || 'cache',
|
|
234
|
+
overview: {
|
|
235
|
+
total_variables: data.variables?.length || 0,
|
|
236
|
+
total_collections: data.variableCollections?.length || 0,
|
|
237
|
+
},
|
|
238
|
+
collections: data.variableCollections?.map((c) => ({
|
|
239
|
+
id: c.id,
|
|
240
|
+
name: c.name,
|
|
241
|
+
modes: c.modes?.map((m) => ({ id: m.modeId, name: m.name })),
|
|
242
|
+
variable_count: c.variableIds?.length || 0,
|
|
243
|
+
})) || [],
|
|
244
|
+
variables_by_type: {},
|
|
245
|
+
variable_names: [],
|
|
246
|
+
};
|
|
247
|
+
// Count variables by type
|
|
248
|
+
const typeCount = {};
|
|
249
|
+
const names = [];
|
|
250
|
+
data.variables?.forEach((v) => {
|
|
251
|
+
typeCount[v.resolvedType] = (typeCount[v.resolvedType] || 0) + 1;
|
|
252
|
+
names.push(v.name);
|
|
253
|
+
});
|
|
254
|
+
summary.variables_by_type = typeCount;
|
|
255
|
+
summary.variable_names = names;
|
|
256
|
+
return summary;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Apply filters to variables data
|
|
260
|
+
*/
|
|
261
|
+
function applyFilters(data, filters, verbosity = "standard") {
|
|
262
|
+
let filteredVariables = [...(data.variables || [])];
|
|
263
|
+
let filteredCollections = [...(data.variableCollections || [])];
|
|
264
|
+
// Filter by collection name or ID
|
|
265
|
+
if (filters.collection) {
|
|
266
|
+
const collectionFilter = filters.collection.toLowerCase();
|
|
267
|
+
filteredCollections = filteredCollections.filter((c) => c.name?.toLowerCase().includes(collectionFilter) ||
|
|
268
|
+
c.id === filters.collection);
|
|
269
|
+
const collectionIds = new Set(filteredCollections.map((c) => c.id));
|
|
270
|
+
filteredVariables = filteredVariables.filter((v) => collectionIds.has(v.variableCollectionId));
|
|
271
|
+
}
|
|
272
|
+
// Filter by variable name pattern (regex or substring)
|
|
273
|
+
if (filters.namePattern) {
|
|
274
|
+
try {
|
|
275
|
+
const regex = new RegExp(filters.namePattern, 'i');
|
|
276
|
+
filteredVariables = filteredVariables.filter((v) => regex.test(v.name));
|
|
277
|
+
}
|
|
278
|
+
catch (e) {
|
|
279
|
+
// If regex fails, fall back to substring match
|
|
280
|
+
const pattern = filters.namePattern.toLowerCase();
|
|
281
|
+
filteredVariables = filteredVariables.filter((v) => v.name?.toLowerCase().includes(pattern));
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
// Find target mode ID if mode filter specified (needed for both filtering and transformation)
|
|
285
|
+
let targetModeId = null;
|
|
286
|
+
let targetModeName = null;
|
|
287
|
+
if (filters.mode) {
|
|
288
|
+
const modeFilter = filters.mode.toLowerCase();
|
|
289
|
+
// Try direct mode ID match first
|
|
290
|
+
if (data.variableCollections || filteredCollections.length > 0) {
|
|
291
|
+
for (const collection of filteredCollections) {
|
|
292
|
+
if (collection.modes) {
|
|
293
|
+
const mode = collection.modes.find((m) => m.modeId === filters.mode ||
|
|
294
|
+
m.name?.toLowerCase().includes(modeFilter));
|
|
295
|
+
if (mode) {
|
|
296
|
+
targetModeId = mode.modeId;
|
|
297
|
+
targetModeName = mode.name;
|
|
298
|
+
break;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
// Filter by mode name or ID
|
|
305
|
+
if (filters.mode) {
|
|
306
|
+
filteredVariables = filteredVariables.filter((v) => {
|
|
307
|
+
// Check if variable has values for the specified mode
|
|
308
|
+
if (v.valuesByMode) {
|
|
309
|
+
// Try to match by mode ID directly
|
|
310
|
+
if (v.valuesByMode[filters.mode]) {
|
|
311
|
+
return true;
|
|
312
|
+
}
|
|
313
|
+
// Try using resolved targetModeId
|
|
314
|
+
if (targetModeId && v.valuesByMode[targetModeId]) {
|
|
315
|
+
return true;
|
|
316
|
+
}
|
|
317
|
+
// Try to match by mode name through collections
|
|
318
|
+
const collection = filteredCollections.find((c) => c.id === v.variableCollectionId);
|
|
319
|
+
if (collection?.modes) {
|
|
320
|
+
const mode = collection.modes.find((m) => m.name?.toLowerCase().includes(filters.mode.toLowerCase()) || m.modeId === filters.mode);
|
|
321
|
+
return mode && v.valuesByMode[mode.modeId];
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
return false;
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
// Transform valuesByMode based on verbosity level
|
|
328
|
+
// This is critical for reducing response size with multi-mode variables
|
|
329
|
+
if (verbosity !== "full") {
|
|
330
|
+
filteredVariables = filteredVariables.map((v) => {
|
|
331
|
+
const variable = { ...v };
|
|
332
|
+
// Use original collections array for lookup, not filtered, since we need mode metadata
|
|
333
|
+
// Handle both variableCollections and collections property names
|
|
334
|
+
const collections = data.variableCollections || data.collections || [];
|
|
335
|
+
const collection = collections.find((c) => c.id === v.variableCollectionId);
|
|
336
|
+
if (verbosity === "inventory") {
|
|
337
|
+
// Inventory: Remove valuesByMode entirely, add mode count
|
|
338
|
+
delete variable.valuesByMode;
|
|
339
|
+
if (collection?.modes) {
|
|
340
|
+
variable.modeCount = collection.modes.length;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
else if (verbosity === "summary") {
|
|
344
|
+
// Summary: Replace valuesByMode with mode names array
|
|
345
|
+
if (variable.valuesByMode && collection?.modes) {
|
|
346
|
+
variable.modeNames = collection.modes.map((m) => m.name);
|
|
347
|
+
variable.modeCount = collection.modes.length;
|
|
348
|
+
}
|
|
349
|
+
delete variable.valuesByMode;
|
|
350
|
+
}
|
|
351
|
+
else if (verbosity === "standard") {
|
|
352
|
+
// Standard: If mode parameter specified, filter to that mode only
|
|
353
|
+
if (targetModeId && variable.valuesByMode) {
|
|
354
|
+
const singleModeValue = variable.valuesByMode[targetModeId];
|
|
355
|
+
variable.valuesByMode = { [targetModeId]: singleModeValue };
|
|
356
|
+
variable.selectedMode = {
|
|
357
|
+
modeId: targetModeId,
|
|
358
|
+
modeName: targetModeName,
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
// If no mode specified, keep all valuesByMode but add metadata for context
|
|
362
|
+
else if (variable.valuesByMode && collection?.modes) {
|
|
363
|
+
variable.modeMetadata = collection.modes.map((m) => ({
|
|
364
|
+
modeId: m.modeId,
|
|
365
|
+
modeName: m.name,
|
|
366
|
+
}));
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
return variable;
|
|
370
|
+
});
|
|
371
|
+
// Apply field-level filtering based on verbosity
|
|
372
|
+
if (verbosity === "inventory") {
|
|
373
|
+
filteredVariables = filteredVariables.map((v) => ({
|
|
374
|
+
id: v.id,
|
|
375
|
+
name: v.name,
|
|
376
|
+
resolvedType: v.resolvedType,
|
|
377
|
+
variableCollectionId: v.variableCollectionId,
|
|
378
|
+
...(v.modeCount && { modeCount: v.modeCount }),
|
|
379
|
+
}));
|
|
380
|
+
}
|
|
381
|
+
else if (verbosity === "summary") {
|
|
382
|
+
filteredVariables = filteredVariables.map((v) => ({
|
|
383
|
+
id: v.id,
|
|
384
|
+
name: v.name,
|
|
385
|
+
resolvedType: v.resolvedType,
|
|
386
|
+
variableCollectionId: v.variableCollectionId,
|
|
387
|
+
...(v.modeNames && { modeNames: v.modeNames }),
|
|
388
|
+
...(v.modeCount && { modeCount: v.modeCount }),
|
|
389
|
+
}));
|
|
390
|
+
}
|
|
391
|
+
else if (verbosity === "standard") {
|
|
392
|
+
filteredVariables = filteredVariables.map((v) => ({
|
|
393
|
+
id: v.id,
|
|
394
|
+
name: v.name,
|
|
395
|
+
resolvedType: v.resolvedType,
|
|
396
|
+
valuesByMode: v.valuesByMode,
|
|
397
|
+
description: v.description,
|
|
398
|
+
variableCollectionId: v.variableCollectionId,
|
|
399
|
+
...(v.scopes && { scopes: v.scopes }),
|
|
400
|
+
...(v.selectedMode && { selectedMode: v.selectedMode }),
|
|
401
|
+
...(v.modeMetadata && { modeMetadata: v.modeMetadata }),
|
|
402
|
+
}));
|
|
403
|
+
}
|
|
404
|
+
// For "full" verbosity, return all fields (no filtering)
|
|
405
|
+
}
|
|
406
|
+
// IMPORTANT: Only return filtered data, not the entire original data object
|
|
407
|
+
// The ...data spread was including massive metadata that bloated responses
|
|
408
|
+
return {
|
|
409
|
+
variables: filteredVariables,
|
|
410
|
+
variableCollections: filteredCollections,
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Apply pagination to variables
|
|
415
|
+
*/
|
|
416
|
+
function paginateVariables(data, page = 1, pageSize = 50) {
|
|
417
|
+
const variables = data.variables || [];
|
|
418
|
+
const totalVariables = variables.length;
|
|
419
|
+
const totalPages = Math.ceil(totalVariables / pageSize);
|
|
420
|
+
// Validate page number
|
|
421
|
+
const currentPage = Math.max(1, Math.min(page, totalPages || 1));
|
|
422
|
+
// Calculate pagination
|
|
423
|
+
const startIndex = (currentPage - 1) * pageSize;
|
|
424
|
+
const endIndex = startIndex + pageSize;
|
|
425
|
+
const paginatedVariables = variables.slice(startIndex, endIndex);
|
|
426
|
+
return {
|
|
427
|
+
data: {
|
|
428
|
+
...data,
|
|
429
|
+
variables: paginatedVariables,
|
|
430
|
+
},
|
|
431
|
+
pagination: {
|
|
432
|
+
currentPage,
|
|
433
|
+
pageSize,
|
|
434
|
+
totalVariables,
|
|
435
|
+
totalPages,
|
|
436
|
+
hasNextPage: currentPage < totalPages,
|
|
437
|
+
hasPrevPage: currentPage > 1,
|
|
438
|
+
},
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Manage LRU cache eviction
|
|
443
|
+
*/
|
|
444
|
+
function evictOldestCacheEntry(cache) {
|
|
445
|
+
if (cache.size >= MAX_CACHE_ENTRIES) {
|
|
446
|
+
// Find oldest entry
|
|
447
|
+
let oldestKey = null;
|
|
448
|
+
let oldestTime = Infinity;
|
|
449
|
+
for (const [key, entry] of cache.entries()) {
|
|
450
|
+
if (entry.timestamp < oldestTime) {
|
|
451
|
+
oldestTime = entry.timestamp;
|
|
452
|
+
oldestKey = key;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
if (oldestKey) {
|
|
456
|
+
cache.delete(oldestKey);
|
|
457
|
+
logger.info({ evictedKey: oldestKey }, 'Evicted oldest cache entry (LRU)');
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* Resolve variable aliases to their final values for all modes
|
|
463
|
+
* @param variables Array of variables to resolve
|
|
464
|
+
* @param allVariablesMap Map of all variables by ID for lookup
|
|
465
|
+
* @param collectionsMap Map of collections by ID for mode info
|
|
466
|
+
* @returns Variables with added resolvedValuesByMode field
|
|
467
|
+
*/
|
|
468
|
+
function resolveVariableAliases(variables, allVariablesMap, collectionsMap) {
|
|
469
|
+
// Helper to format color value to hex
|
|
470
|
+
const formatColorToHex = (color) => {
|
|
471
|
+
if (typeof color === 'string')
|
|
472
|
+
return color;
|
|
473
|
+
if (color && typeof color.r === 'number' && typeof color.g === 'number' && typeof color.b === 'number') {
|
|
474
|
+
const r = Math.round(color.r * 255);
|
|
475
|
+
const g = Math.round(color.g * 255);
|
|
476
|
+
const b = Math.round(color.b * 255);
|
|
477
|
+
const a = typeof color.a === 'number' ? color.a : 1;
|
|
478
|
+
if (a < 1) {
|
|
479
|
+
const aHex = Math.round(a * 255).toString(16).padStart(2, '0');
|
|
480
|
+
return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}${aHex}`.toUpperCase();
|
|
481
|
+
}
|
|
482
|
+
return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`.toUpperCase();
|
|
483
|
+
}
|
|
484
|
+
return null;
|
|
485
|
+
};
|
|
486
|
+
// Helper to get mode ID from a mode object (handles both 'modeId' and 'id' properties)
|
|
487
|
+
const getModeId = (mode) => {
|
|
488
|
+
return mode?.modeId || mode?.id || null;
|
|
489
|
+
};
|
|
490
|
+
// Helper to get default mode ID from a collection
|
|
491
|
+
const getDefaultModeId = (collection, variable) => {
|
|
492
|
+
// Try explicit defaultModeId first
|
|
493
|
+
if (collection?.defaultModeId) {
|
|
494
|
+
return collection.defaultModeId;
|
|
495
|
+
}
|
|
496
|
+
// Try first mode's ID
|
|
497
|
+
if (collection?.modes?.length > 0) {
|
|
498
|
+
return getModeId(collection.modes[0]);
|
|
499
|
+
}
|
|
500
|
+
// Fallback to first key in valuesByMode
|
|
501
|
+
const modeKeys = Object.keys(variable?.valuesByMode || {});
|
|
502
|
+
return modeKeys.length > 0 ? modeKeys[0] : null;
|
|
503
|
+
};
|
|
504
|
+
// Helper to resolve a single value, following alias chains
|
|
505
|
+
const resolveValue = (value, resolvedType, visited = new Set(), depth = 0) => {
|
|
506
|
+
if (depth > 10) {
|
|
507
|
+
logger.warn({ depth }, 'Max alias resolution depth reached');
|
|
508
|
+
return { resolved: null, aliasChain: Array.from(visited) };
|
|
509
|
+
}
|
|
510
|
+
// Check if this is an alias
|
|
511
|
+
if (value && typeof value === 'object' && value.type === 'VARIABLE_ALIAS') {
|
|
512
|
+
const targetId = value.id;
|
|
513
|
+
// Prevent circular references
|
|
514
|
+
if (visited.has(targetId)) {
|
|
515
|
+
logger.warn({ targetId, visited: Array.from(visited) }, 'Circular alias reference detected');
|
|
516
|
+
return { resolved: null, aliasChain: Array.from(visited) };
|
|
517
|
+
}
|
|
518
|
+
visited.add(targetId);
|
|
519
|
+
const targetVar = allVariablesMap.get(targetId);
|
|
520
|
+
if (!targetVar) {
|
|
521
|
+
logger.debug({ targetId }, 'Target variable not found in map');
|
|
522
|
+
return { resolved: null, aliasChain: Array.from(visited) };
|
|
523
|
+
}
|
|
524
|
+
// Get the target's collection to find its default mode
|
|
525
|
+
const targetCollection = collectionsMap.get(targetVar.variableCollectionId);
|
|
526
|
+
const targetModeId = getDefaultModeId(targetCollection, targetVar);
|
|
527
|
+
if (!targetModeId) {
|
|
528
|
+
logger.debug({ targetId, collectionId: targetVar.variableCollectionId }, 'Could not determine target mode ID');
|
|
529
|
+
return { resolved: null, aliasChain: Array.from(visited) };
|
|
530
|
+
}
|
|
531
|
+
const targetValue = targetVar.valuesByMode?.[targetModeId];
|
|
532
|
+
if (targetValue === undefined) {
|
|
533
|
+
logger.debug({ targetId, targetModeId, availableModes: Object.keys(targetVar.valuesByMode || {}) }, 'Target value not found for mode');
|
|
534
|
+
return { resolved: null, aliasChain: Array.from(visited) };
|
|
535
|
+
}
|
|
536
|
+
// Recursively resolve
|
|
537
|
+
const result = resolveValue(targetValue, targetVar.resolvedType, visited, depth + 1);
|
|
538
|
+
return {
|
|
539
|
+
resolved: result.resolved,
|
|
540
|
+
aliasChain: [targetVar.name, ...(result.aliasChain || [])]
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
// Not an alias - format the value based on type
|
|
544
|
+
if (resolvedType === 'COLOR') {
|
|
545
|
+
return { resolved: formatColorToHex(value) };
|
|
546
|
+
}
|
|
547
|
+
return { resolved: value };
|
|
548
|
+
};
|
|
549
|
+
// Process each variable
|
|
550
|
+
return variables.map(variable => {
|
|
551
|
+
const collection = collectionsMap.get(variable.variableCollectionId);
|
|
552
|
+
const modes = collection?.modes || [];
|
|
553
|
+
const resolvedValuesByMode = {};
|
|
554
|
+
for (const mode of modes) {
|
|
555
|
+
const modeId = getModeId(mode);
|
|
556
|
+
if (!modeId)
|
|
557
|
+
continue;
|
|
558
|
+
const rawValue = variable.valuesByMode?.[modeId];
|
|
559
|
+
if (rawValue === undefined)
|
|
560
|
+
continue;
|
|
561
|
+
const { resolved, aliasChain } = resolveValue(rawValue, variable.resolvedType, new Set());
|
|
562
|
+
const modeName = mode.name || modeId;
|
|
563
|
+
resolvedValuesByMode[modeName] = {
|
|
564
|
+
value: resolved,
|
|
565
|
+
...(aliasChain && aliasChain.length > 0 && { aliasTo: aliasChain[0] })
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
return {
|
|
569
|
+
...variable,
|
|
570
|
+
resolvedValuesByMode
|
|
571
|
+
};
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* Register Figma API tools with the MCP server
|
|
576
|
+
*/
|
|
577
|
+
export function registerFigmaAPITools(server, getFigmaAPI, getCurrentUrl, getConsoleMonitor, getBrowserManager, ensureInitialized, variablesCache, options, getDesktopConnector) {
|
|
578
|
+
const isRemoteMode = options?.isRemoteMode ?? false;
|
|
579
|
+
// Tool 8: Get File Data (General Purpose)
|
|
580
|
+
// NOTE: For specific use cases, consider using specialized tools:
|
|
581
|
+
// - figma_get_component_for_development: For UI component implementation
|
|
582
|
+
// - figma_get_file_for_plugin: For plugin development
|
|
583
|
+
server.tool("figma_get_file_data", "Get full file structure and document tree. WARNING: Can consume large amounts of tokens. NOT recommended for component descriptions (use figma_get_component instead). Best for understanding file structure or finding component nodeIds. Start with verbosity='summary' and depth=1 for initial exploration.", {
|
|
584
|
+
fileUrl: z
|
|
585
|
+
.string()
|
|
586
|
+
.url()
|
|
587
|
+
.optional()
|
|
588
|
+
.describe("Figma file URL (e.g., https://figma.com/design/abc123). Auto-detected from WebSocket Desktop Bridge connection. Only required if not connected."),
|
|
589
|
+
depth: z
|
|
590
|
+
.number()
|
|
591
|
+
.min(0)
|
|
592
|
+
.max(3)
|
|
593
|
+
.optional()
|
|
594
|
+
.default(1)
|
|
595
|
+
.describe("How many levels of children to include (default: 1, max: 3). Start with 1 to prevent context exhaustion. Use 0 for full tree only when absolutely necessary."),
|
|
596
|
+
verbosity: z
|
|
597
|
+
.enum(["summary", "standard", "full"])
|
|
598
|
+
.optional()
|
|
599
|
+
.default("summary")
|
|
600
|
+
.describe("Controls payload size: 'summary' (IDs/names/types only, ~90% smaller - RECOMMENDED), 'standard' (essential properties, ~50% smaller), 'full' (everything). Default: summary for token efficiency."),
|
|
601
|
+
nodeIds: z
|
|
602
|
+
.array(z.string())
|
|
603
|
+
.optional()
|
|
604
|
+
.describe("Specific node IDs to retrieve (optional)"),
|
|
605
|
+
enrich: z
|
|
606
|
+
.boolean()
|
|
607
|
+
.optional()
|
|
608
|
+
.describe("Set to true when user asks for: file statistics, health metrics, design system audit, or quality analysis. Adds statistics, health scores, and audit summaries. Default: false"),
|
|
609
|
+
}, async ({ fileUrl, depth, nodeIds, enrich, verbosity }) => {
|
|
610
|
+
try {
|
|
611
|
+
// Initialize API client (required for file data - no Desktop Bridge alternative)
|
|
612
|
+
let api;
|
|
613
|
+
try {
|
|
614
|
+
api = await getFigmaAPI();
|
|
615
|
+
}
|
|
616
|
+
catch (apiError) {
|
|
617
|
+
const errorMessage = apiError instanceof Error ? apiError.message : String(apiError);
|
|
618
|
+
throw new Error(`Cannot retrieve file data. REST API authentication required.\n` +
|
|
619
|
+
`Error: ${errorMessage}\n\n` +
|
|
620
|
+
`To fix:\n` +
|
|
621
|
+
`1. Local mode: Set FIGMA_ACCESS_TOKEN environment variable\n` +
|
|
622
|
+
`2. Cloud mode: Authenticate via OAuth\n\n` +
|
|
623
|
+
`Note: figma_get_file_data requires REST API access. ` +
|
|
624
|
+
`For component-specific data, use figma_get_component which has Desktop Bridge fallback.`);
|
|
625
|
+
}
|
|
626
|
+
// Use provided URL or current URL from browser
|
|
627
|
+
const url = fileUrl || getCurrentUrl();
|
|
628
|
+
if (!url) {
|
|
629
|
+
throw new Error("No Figma file URL available. Pass the fileUrl parameter or ensure the Desktop Bridge plugin is open in Figma.");
|
|
630
|
+
}
|
|
631
|
+
const fileKey = extractFileKey(url);
|
|
632
|
+
if (!fileKey) {
|
|
633
|
+
throw new Error(`Invalid Figma URL: ${url}`);
|
|
634
|
+
}
|
|
635
|
+
logger.info({ fileKey, depth, nodeIds, enrich, verbosity }, "Fetching file data");
|
|
636
|
+
const fileData = await api.getFile(fileKey, {
|
|
637
|
+
depth,
|
|
638
|
+
ids: nodeIds,
|
|
639
|
+
});
|
|
640
|
+
// Apply verbosity filtering to reduce payload size
|
|
641
|
+
const filterNode = (node, level) => {
|
|
642
|
+
if (!node)
|
|
643
|
+
return node;
|
|
644
|
+
if (level === "summary") {
|
|
645
|
+
// Summary: Only IDs, names, types (~90% reduction)
|
|
646
|
+
return {
|
|
647
|
+
id: node.id,
|
|
648
|
+
name: node.name,
|
|
649
|
+
type: node.type,
|
|
650
|
+
...(node.children && {
|
|
651
|
+
children: node.children.map((child) => filterNode(child, level))
|
|
652
|
+
}),
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
if (level === "standard") {
|
|
656
|
+
// Standard: Essential properties for plugin development (~50% reduction)
|
|
657
|
+
const filtered = {
|
|
658
|
+
id: node.id,
|
|
659
|
+
name: node.name,
|
|
660
|
+
type: node.type,
|
|
661
|
+
visible: node.visible,
|
|
662
|
+
locked: node.locked,
|
|
663
|
+
};
|
|
664
|
+
// Include bounds for layout calculations
|
|
665
|
+
if (node.absoluteBoundingBox)
|
|
666
|
+
filtered.absoluteBoundingBox = node.absoluteBoundingBox;
|
|
667
|
+
if (node.size)
|
|
668
|
+
filtered.size = node.size;
|
|
669
|
+
// Include component/instance info for plugin work
|
|
670
|
+
if (node.componentId)
|
|
671
|
+
filtered.componentId = node.componentId;
|
|
672
|
+
if (node.componentPropertyReferences)
|
|
673
|
+
filtered.componentPropertyReferences = node.componentPropertyReferences;
|
|
674
|
+
// Include basic styling (but not full details)
|
|
675
|
+
if (node.fills && node.fills.length > 0) {
|
|
676
|
+
filtered.fills = node.fills.map((fill) => ({
|
|
677
|
+
type: fill.type,
|
|
678
|
+
visible: fill.visible,
|
|
679
|
+
...(fill.color && { color: fill.color }),
|
|
680
|
+
}));
|
|
681
|
+
}
|
|
682
|
+
// Include plugin data if present
|
|
683
|
+
if (node.pluginData)
|
|
684
|
+
filtered.pluginData = node.pluginData;
|
|
685
|
+
if (node.sharedPluginData)
|
|
686
|
+
filtered.sharedPluginData = node.sharedPluginData;
|
|
687
|
+
// Recursively filter children
|
|
688
|
+
if (node.children) {
|
|
689
|
+
filtered.children = node.children.map((child) => filterNode(child, level));
|
|
690
|
+
}
|
|
691
|
+
return filtered;
|
|
692
|
+
}
|
|
693
|
+
// Full: Return everything
|
|
694
|
+
return node;
|
|
695
|
+
};
|
|
696
|
+
const filteredDocument = verbosity !== "full"
|
|
697
|
+
? filterNode(fileData.document, verbosity || "standard")
|
|
698
|
+
: fileData.document;
|
|
699
|
+
let response = {
|
|
700
|
+
fileKey,
|
|
701
|
+
name: fileData.name,
|
|
702
|
+
lastModified: fileData.lastModified,
|
|
703
|
+
version: fileData.version,
|
|
704
|
+
document: filteredDocument,
|
|
705
|
+
components: fileData.components
|
|
706
|
+
? Object.keys(fileData.components).length
|
|
707
|
+
: 0,
|
|
708
|
+
styles: fileData.styles
|
|
709
|
+
? Object.keys(fileData.styles).length
|
|
710
|
+
: 0,
|
|
711
|
+
verbosity: verbosity || "standard",
|
|
712
|
+
...(nodeIds && {
|
|
713
|
+
requestedNodes: nodeIds,
|
|
714
|
+
nodes: fileData.nodes,
|
|
715
|
+
}),
|
|
716
|
+
};
|
|
717
|
+
// Apply enrichment if requested
|
|
718
|
+
if (enrich) {
|
|
719
|
+
const enrichmentOptions = {
|
|
720
|
+
enrich: true,
|
|
721
|
+
include_usage: true,
|
|
722
|
+
};
|
|
723
|
+
response = await enrichmentService.enrichFileData({ ...response, ...fileData }, enrichmentOptions);
|
|
724
|
+
}
|
|
725
|
+
const finalResponse = {
|
|
726
|
+
...response,
|
|
727
|
+
enriched: enrich || false,
|
|
728
|
+
};
|
|
729
|
+
// Use adaptive response to prevent context exhaustion
|
|
730
|
+
return adaptiveResponse(finalResponse, {
|
|
731
|
+
toolName: "figma_get_file_data",
|
|
732
|
+
compressionCallback: (adjustedLevel) => {
|
|
733
|
+
// Re-apply node filtering with lower verbosity
|
|
734
|
+
const level = adjustedLevel;
|
|
735
|
+
const refiltered = {
|
|
736
|
+
...finalResponse,
|
|
737
|
+
document: verbosity !== "full"
|
|
738
|
+
? filterNode(fileData.document, level)
|
|
739
|
+
: fileData.document,
|
|
740
|
+
verbosity: level,
|
|
741
|
+
};
|
|
742
|
+
return refiltered;
|
|
743
|
+
},
|
|
744
|
+
suggestedActions: [
|
|
745
|
+
"Use verbosity='summary' with depth=1 for initial exploration",
|
|
746
|
+
"Use verbosity='standard' for essential properties",
|
|
747
|
+
"Request specific nodeIds to narrow the scope",
|
|
748
|
+
"Reduce depth parameter (max 3, recommend 1-2)",
|
|
749
|
+
],
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
catch (error) {
|
|
753
|
+
logger.error({ error }, "Failed to get file data");
|
|
754
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
755
|
+
return {
|
|
756
|
+
content: [
|
|
757
|
+
{
|
|
758
|
+
type: "text",
|
|
759
|
+
text: JSON.stringify({
|
|
760
|
+
error: errorMessage,
|
|
761
|
+
message: "Failed to retrieve Figma file data",
|
|
762
|
+
hint: "Make sure FIGMA_ACCESS_TOKEN is configured and the file is accessible",
|
|
763
|
+
}),
|
|
764
|
+
},
|
|
765
|
+
],
|
|
766
|
+
isError: true,
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
});
|
|
770
|
+
/**
|
|
771
|
+
* Tool 9: Get Variables (Design Tokens)
|
|
772
|
+
*
|
|
773
|
+
* WORKFLOW:
|
|
774
|
+
* - Primary: Attempts to fetch variables via Figma REST API (requires Enterprise plan)
|
|
775
|
+
* - Fallback: On 403 error, provides console-based extraction snippet
|
|
776
|
+
*
|
|
777
|
+
* TWO-CALL PATTERN (when API unavailable):
|
|
778
|
+
* 1. First call: Returns snippet + instructions (useConsoleFallback: true, default)
|
|
779
|
+
* 2. User runs snippet in Figma plugin console
|
|
780
|
+
* 3. Second call: Parses captured data (parseFromConsole: true)
|
|
781
|
+
*
|
|
782
|
+
* IMPORTANT: Snippet requires Figma Plugin API context, not browser DevTools console.
|
|
783
|
+
*/
|
|
784
|
+
server.tool("figma_get_variables", "Extract design tokens and variables from a Figma file with code export support (CSS, Tailwind, TypeScript, Sass). Use when user asks for: design system tokens, variables, color/spacing values, theme data, or code exports. Handles multi-mode variables (Light/Dark themes). NOT for component metadata (use figma_get_component). Supports filtering by collection/mode/name and verbosity control to prevent token exhaustion. Enterprise plan required for Variables API; automatically falls back to Styles API or console-based extraction if unavailable. TIP: For full design system extraction (tokens + components + styles combined), prefer figma_get_design_system_kit instead — it returns everything in one optimized call.", {
|
|
785
|
+
fileUrl: z
|
|
786
|
+
.string()
|
|
787
|
+
.url()
|
|
788
|
+
.optional()
|
|
789
|
+
.describe("Figma file URL (e.g., https://figma.com/design/abc123). Auto-detected from WebSocket Desktop Bridge connection. Only required if not connected."),
|
|
790
|
+
includePublished: z
|
|
791
|
+
.boolean()
|
|
792
|
+
.optional()
|
|
793
|
+
.default(true)
|
|
794
|
+
.describe("Include published variables from libraries"),
|
|
795
|
+
verbosity: z
|
|
796
|
+
.enum(["inventory", "summary", "standard", "full"])
|
|
797
|
+
.optional()
|
|
798
|
+
.default("standard")
|
|
799
|
+
.describe("Controls payload size: 'inventory' (names/IDs only, ~95% smaller, use with filtered), 'summary' (names/values only, ~80% smaller), 'standard' (essential properties, ~45% smaller), 'full' (everything). Default: standard"),
|
|
800
|
+
enrich: z
|
|
801
|
+
.boolean()
|
|
802
|
+
.optional()
|
|
803
|
+
.describe("Set to true when user asks for: CSS/Sass/Tailwind exports, code examples, design tokens, usage information, dependencies, or any export format. Adds resolved values, dependency graphs, and usage analysis. Default: false"),
|
|
804
|
+
include_usage: z
|
|
805
|
+
.boolean()
|
|
806
|
+
.optional()
|
|
807
|
+
.describe("Include usage in styles and components (requires enrich=true)"),
|
|
808
|
+
include_dependencies: z
|
|
809
|
+
.boolean()
|
|
810
|
+
.optional()
|
|
811
|
+
.describe("Include variable dependency graph (requires enrich=true)"),
|
|
812
|
+
include_exports: z
|
|
813
|
+
.boolean()
|
|
814
|
+
.optional()
|
|
815
|
+
.describe("Include export format examples (requires enrich=true)"),
|
|
816
|
+
export_formats: z
|
|
817
|
+
.array(z.enum(["css", "sass", "tailwind", "typescript", "json"]))
|
|
818
|
+
.optional()
|
|
819
|
+
.describe("Which code formats to generate examples for. Use when user mentions specific formats like 'CSS', 'Tailwind', 'SCSS', 'TypeScript', etc. Automatically enables enrichment."),
|
|
820
|
+
format: z
|
|
821
|
+
.enum(["summary", "filtered", "full"])
|
|
822
|
+
.optional()
|
|
823
|
+
.default("full")
|
|
824
|
+
.describe("Response format: 'summary' (~2K tokens with overview and names only), 'filtered' (apply collection/name/mode filters), 'full' (complete dataset from cache or fetch). " +
|
|
825
|
+
"Summary is recommended for initial exploration. Full format returns all data but may be auto-summarized if >25K tokens. Default: full"),
|
|
826
|
+
collection: z
|
|
827
|
+
.string()
|
|
828
|
+
.optional()
|
|
829
|
+
.describe("Filter variables by collection name or ID. Case-insensitive substring match. Only applies when format='filtered'. Example: 'Primitives' or 'VariableCollectionId:123'"),
|
|
830
|
+
namePattern: z
|
|
831
|
+
.string()
|
|
832
|
+
.optional()
|
|
833
|
+
.describe("Filter variables by name using regex pattern or substring. Case-insensitive. Only applies when format='filtered'. Example: 'color/brand' or '^typography'"),
|
|
834
|
+
mode: z
|
|
835
|
+
.string()
|
|
836
|
+
.optional()
|
|
837
|
+
.describe("Filter variables by mode name or ID. Only returns variables that have values for this mode. Only applies when format='filtered'. Example: 'Light' or 'Dark'"),
|
|
838
|
+
returnAsLinks: z
|
|
839
|
+
.boolean()
|
|
840
|
+
.optional()
|
|
841
|
+
.default(false)
|
|
842
|
+
.describe("Return variables as resource_link references instead of full data. Drastically reduces payload size (100+ variables = ~20KB vs >1MB). Use with figma_get_variable_by_id to fetch specific variables. Recommended for large variable sets. Default: false"),
|
|
843
|
+
refreshCache: z
|
|
844
|
+
.boolean()
|
|
845
|
+
.optional()
|
|
846
|
+
.default(false)
|
|
847
|
+
.describe("Force refresh cache by fetching fresh data from Figma. Use when data may have changed since last fetch. Default: false (use cached data if available and fresh)"),
|
|
848
|
+
useConsoleFallback: z
|
|
849
|
+
.boolean()
|
|
850
|
+
.optional()
|
|
851
|
+
.default(true)
|
|
852
|
+
.describe("Enable automatic fallback to console-based extraction when REST API returns 403 (Figma Enterprise plan required). " +
|
|
853
|
+
"When enabled, provides a JavaScript snippet that users run in Figma's plugin console. " +
|
|
854
|
+
"This is STEP 1 of a two-call workflow. After receiving the snippet, instruct the user to run it, then call this tool again with parseFromConsole=true. " +
|
|
855
|
+
"Default: true. Set to false only to disable the fallback entirely."),
|
|
856
|
+
parseFromConsole: z
|
|
857
|
+
.boolean()
|
|
858
|
+
.optional()
|
|
859
|
+
.default(false)
|
|
860
|
+
.describe("Parse variables from console logs after user has executed the snippet. " +
|
|
861
|
+
"This is STEP 2 of the two-call workflow. Set to true ONLY after: " +
|
|
862
|
+
"(1) you received a console snippet from the first call, " +
|
|
863
|
+
"(2) instructed the user to run it in Figma's PLUGIN console (Plugins → Development → Open Console or existing plugin), " +
|
|
864
|
+
"(3) user confirmed they ran the snippet and saw '✅ Variables data captured!' message. " +
|
|
865
|
+
"Default: false. Never set to true on the first call."),
|
|
866
|
+
page: z
|
|
867
|
+
.number()
|
|
868
|
+
.int()
|
|
869
|
+
.min(1)
|
|
870
|
+
.optional()
|
|
871
|
+
.default(1)
|
|
872
|
+
.describe("Page number for paginated results (1-based). Use when response is too large (>1MB). Each page returns up to 50 variables."),
|
|
873
|
+
pageSize: z
|
|
874
|
+
.number()
|
|
875
|
+
.int()
|
|
876
|
+
.min(1)
|
|
877
|
+
.max(100)
|
|
878
|
+
.optional()
|
|
879
|
+
.default(50)
|
|
880
|
+
.describe("Number of variables per page (1-100). Default: 50. Smaller values reduce response size."),
|
|
881
|
+
resolveAliases: z
|
|
882
|
+
.boolean()
|
|
883
|
+
.optional()
|
|
884
|
+
.default(false)
|
|
885
|
+
.describe("Automatically resolve variable aliases to their final values (hex colors, numbers, etc.). " +
|
|
886
|
+
"When true, each variable will include a 'resolvedValuesByMode' field with the actual values " +
|
|
887
|
+
"instead of just alias references. Useful for getting color hex values without manual resolution. " +
|
|
888
|
+
"Default: false."),
|
|
889
|
+
}, async ({ fileUrl, includePublished, verbosity, enrich, include_usage, include_dependencies, include_exports, export_formats, format, collection, namePattern, mode, returnAsLinks, refreshCache, useConsoleFallback, parseFromConsole, page, pageSize, resolveAliases }) => {
|
|
890
|
+
// Extract fileKey and optional branchId outside try block so they're available in catch block
|
|
891
|
+
const url = fileUrl || getCurrentUrl();
|
|
892
|
+
if (!url) {
|
|
893
|
+
return {
|
|
894
|
+
content: [
|
|
895
|
+
{
|
|
896
|
+
type: "text",
|
|
897
|
+
text: JSON.stringify({
|
|
898
|
+
error: "No Figma file URL available",
|
|
899
|
+
message: "Pass the fileUrl parameter or ensure the Desktop Bridge plugin is open in Figma."
|
|
900
|
+
}),
|
|
901
|
+
},
|
|
902
|
+
],
|
|
903
|
+
isError: true,
|
|
904
|
+
};
|
|
905
|
+
}
|
|
906
|
+
// Use extractFigmaUrlInfo to get fileKey, branchId, and nodeId
|
|
907
|
+
const urlInfo = extractFigmaUrlInfo(url);
|
|
908
|
+
if (!urlInfo) {
|
|
909
|
+
return {
|
|
910
|
+
content: [
|
|
911
|
+
{
|
|
912
|
+
type: "text",
|
|
913
|
+
text: JSON.stringify({
|
|
914
|
+
error: `Invalid Figma URL: ${url}`,
|
|
915
|
+
message: "Could not extract file key from URL"
|
|
916
|
+
}),
|
|
917
|
+
},
|
|
918
|
+
],
|
|
919
|
+
isError: true,
|
|
920
|
+
};
|
|
921
|
+
}
|
|
922
|
+
// For branch URLs, the branchId IS the file key to use for API calls
|
|
923
|
+
// Figma branch URLs contain the branch key directly in the path
|
|
924
|
+
const fileKey = urlInfo.branchId || urlInfo.fileKey;
|
|
925
|
+
const mainFileKey = urlInfo.fileKey;
|
|
926
|
+
const branchId = urlInfo.branchId;
|
|
927
|
+
if (branchId) {
|
|
928
|
+
logger.info({ mainFileKey, branchId, effectiveFileKey: fileKey }, 'Branch URL detected, using branch key for API calls');
|
|
929
|
+
}
|
|
930
|
+
try {
|
|
931
|
+
// =====================================================================
|
|
932
|
+
// CACHE-FIRST LOGIC: Check if we have cached data before fetching
|
|
933
|
+
// =====================================================================
|
|
934
|
+
let cachedData = null;
|
|
935
|
+
let shouldFetch = true;
|
|
936
|
+
if (variablesCache && !parseFromConsole) {
|
|
937
|
+
const cacheEntry = variablesCache.get(fileKey);
|
|
938
|
+
if (cacheEntry) {
|
|
939
|
+
const isValid = isCacheValid(cacheEntry.timestamp);
|
|
940
|
+
if (isValid && !refreshCache) {
|
|
941
|
+
// Cache hit! Use cached data
|
|
942
|
+
cachedData = cacheEntry.data;
|
|
943
|
+
shouldFetch = false;
|
|
944
|
+
logger.info({
|
|
945
|
+
fileKey,
|
|
946
|
+
cacheAge: Date.now() - cacheEntry.timestamp,
|
|
947
|
+
variableCount: cachedData.variables?.length,
|
|
948
|
+
}, 'Using cached variables data');
|
|
949
|
+
}
|
|
950
|
+
else if (!isValid) {
|
|
951
|
+
logger.info({ fileKey, cacheAge: Date.now() - cacheEntry.timestamp }, 'Cache expired, will refresh');
|
|
952
|
+
}
|
|
953
|
+
else if (refreshCache) {
|
|
954
|
+
logger.info({ fileKey }, 'Refresh cache requested, will fetch fresh data');
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
else {
|
|
958
|
+
logger.info({ fileKey }, 'No cache entry found, will fetch data');
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
// If we have cached data, skip fetching and jump to formatting
|
|
962
|
+
if (cachedData && !shouldFetch) {
|
|
963
|
+
// Apply format logic based on user request
|
|
964
|
+
let responseData = cachedData;
|
|
965
|
+
let paginationInfo = null;
|
|
966
|
+
if (format === 'summary') {
|
|
967
|
+
// Return compact summary
|
|
968
|
+
responseData = generateSummary(cachedData);
|
|
969
|
+
logger.info({ fileKey, estimatedTokens: estimateTokens(responseData) }, 'Generated summary from cache');
|
|
970
|
+
}
|
|
971
|
+
else if (format === 'filtered') {
|
|
972
|
+
// Apply filters with verbosity-aware valuesByMode transformation
|
|
973
|
+
responseData = applyFilters(cachedData, {
|
|
974
|
+
collection,
|
|
975
|
+
namePattern,
|
|
976
|
+
mode,
|
|
977
|
+
}, verbosity || 'standard');
|
|
978
|
+
// ALWAYS apply pagination for filtered results to prevent 1MB limit
|
|
979
|
+
// Default to page 1, pageSize 50 if not specified
|
|
980
|
+
const paginated = paginateVariables(responseData, page || 1, pageSize || 50);
|
|
981
|
+
responseData = paginated.data;
|
|
982
|
+
paginationInfo = paginated.pagination;
|
|
983
|
+
// Apply verbosity filtering to minimize payload size
|
|
984
|
+
// For filtered results, default to "inventory" for maximum size reduction
|
|
985
|
+
const effectiveVerbosity = verbosity || "inventory";
|
|
986
|
+
// CRITICAL FIX: Only include collections referenced by paginated variables
|
|
987
|
+
const referencedCollectionIds = new Set(responseData.variables.map((v) => v.variableCollectionId));
|
|
988
|
+
responseData.variableCollections = responseData.variableCollections.filter((c) => referencedCollectionIds.has(c.id));
|
|
989
|
+
// Filter variables to minimal needed fields
|
|
990
|
+
responseData.variables = responseData.variables.map((v) => {
|
|
991
|
+
if (effectiveVerbosity === "inventory") {
|
|
992
|
+
// Ultra-minimal: just names and IDs for inventory purposes
|
|
993
|
+
// If mode filter is specified, include only that mode's value
|
|
994
|
+
const result = {
|
|
995
|
+
id: v.id,
|
|
996
|
+
name: v.name,
|
|
997
|
+
collectionId: v.variableCollectionId,
|
|
998
|
+
};
|
|
999
|
+
// If mode filter specified, include just that single mode's value
|
|
1000
|
+
if (mode && v.valuesByMode) {
|
|
1001
|
+
// Find the mode ID from the collection
|
|
1002
|
+
const collection = responseData.variableCollections.find((c) => c.id === v.variableCollectionId);
|
|
1003
|
+
if (collection?.modes) {
|
|
1004
|
+
const modeObj = collection.modes.find((m) => m.name?.toLowerCase().includes(mode.toLowerCase()) || m.modeId === mode);
|
|
1005
|
+
if (modeObj && v.valuesByMode[modeObj.modeId]) {
|
|
1006
|
+
result.value = v.valuesByMode[modeObj.modeId];
|
|
1007
|
+
result.mode = modeObj.name;
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
return result;
|
|
1012
|
+
}
|
|
1013
|
+
if (effectiveVerbosity === "summary") {
|
|
1014
|
+
return {
|
|
1015
|
+
id: v.id,
|
|
1016
|
+
name: v.name,
|
|
1017
|
+
resolvedType: v.resolvedType,
|
|
1018
|
+
valuesByMode: v.valuesByMode,
|
|
1019
|
+
variableCollectionId: v.variableCollectionId,
|
|
1020
|
+
// Include modeNames and modeCount added by applyFilters
|
|
1021
|
+
...(v.modeNames && { modeNames: v.modeNames }),
|
|
1022
|
+
...(v.modeCount && { modeCount: v.modeCount }),
|
|
1023
|
+
};
|
|
1024
|
+
}
|
|
1025
|
+
if (effectiveVerbosity === "standard") {
|
|
1026
|
+
return {
|
|
1027
|
+
id: v.id,
|
|
1028
|
+
name: v.name,
|
|
1029
|
+
resolvedType: v.resolvedType,
|
|
1030
|
+
valuesByMode: v.valuesByMode,
|
|
1031
|
+
description: v.description,
|
|
1032
|
+
variableCollectionId: v.variableCollectionId,
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
1035
|
+
return v; // full
|
|
1036
|
+
});
|
|
1037
|
+
// Filter collections to remove massive variableIds arrays
|
|
1038
|
+
responseData.variableCollections = responseData.variableCollections.map((c) => {
|
|
1039
|
+
if (effectiveVerbosity === "inventory") {
|
|
1040
|
+
// Ultra-minimal: just ID and name, mode names only (no full mode objects)
|
|
1041
|
+
return {
|
|
1042
|
+
id: c.id,
|
|
1043
|
+
name: c.name,
|
|
1044
|
+
modeNames: c.modes?.map((m) => m.name) || [],
|
|
1045
|
+
};
|
|
1046
|
+
}
|
|
1047
|
+
if (effectiveVerbosity === "summary") {
|
|
1048
|
+
return {
|
|
1049
|
+
id: c.id,
|
|
1050
|
+
name: c.name,
|
|
1051
|
+
modes: c.modes, // Keep modes for user to understand mode structure
|
|
1052
|
+
};
|
|
1053
|
+
}
|
|
1054
|
+
if (effectiveVerbosity === "standard") {
|
|
1055
|
+
return {
|
|
1056
|
+
id: c.id,
|
|
1057
|
+
name: c.name,
|
|
1058
|
+
modes: c.modes,
|
|
1059
|
+
defaultModeId: c.defaultModeId,
|
|
1060
|
+
};
|
|
1061
|
+
}
|
|
1062
|
+
// For full, remove variableIds array to reduce size
|
|
1063
|
+
const { variableIds, ...rest } = c;
|
|
1064
|
+
return rest;
|
|
1065
|
+
});
|
|
1066
|
+
logger.info({
|
|
1067
|
+
fileKey,
|
|
1068
|
+
originalCount: cachedData.variables?.length,
|
|
1069
|
+
filteredCount: paginationInfo.totalVariables,
|
|
1070
|
+
returnedCount: responseData.variables?.length,
|
|
1071
|
+
page: paginationInfo.currentPage,
|
|
1072
|
+
totalPages: paginationInfo.totalPages,
|
|
1073
|
+
verbosity: effectiveVerbosity,
|
|
1074
|
+
}, 'Applied filters, pagination, and verbosity filtering to cached data');
|
|
1075
|
+
// Apply alias resolution if requested
|
|
1076
|
+
if (resolveAliases && responseData.variables?.length > 0) {
|
|
1077
|
+
// Build maps from ALL cached variables (not just filtered) for resolution
|
|
1078
|
+
const allVariablesMap = new Map();
|
|
1079
|
+
const collectionsMap = new Map();
|
|
1080
|
+
for (const v of cachedData.variables || []) {
|
|
1081
|
+
allVariablesMap.set(v.id, v);
|
|
1082
|
+
}
|
|
1083
|
+
for (const c of cachedData.variableCollections || []) {
|
|
1084
|
+
collectionsMap.set(c.id, c);
|
|
1085
|
+
}
|
|
1086
|
+
responseData.variables = resolveVariableAliases(responseData.variables, allVariablesMap, collectionsMap);
|
|
1087
|
+
logger.info({ fileKey, resolvedCount: responseData.variables.length }, 'Applied alias resolution to filtered variables');
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
else {
|
|
1091
|
+
// format === 'full'
|
|
1092
|
+
// Check if we need to auto-summarize
|
|
1093
|
+
const estimatedTokens = estimateTokens(responseData);
|
|
1094
|
+
if (estimatedTokens > 25000) {
|
|
1095
|
+
logger.warn({ fileKey, estimatedTokens }, 'Full data exceeds MCP token limit (25K), auto-summarizing. Use format=summary or format=filtered to get specific data.');
|
|
1096
|
+
const summary = generateSummary(responseData);
|
|
1097
|
+
return {
|
|
1098
|
+
content: [
|
|
1099
|
+
{
|
|
1100
|
+
type: "text",
|
|
1101
|
+
text: JSON.stringify({
|
|
1102
|
+
fileKey,
|
|
1103
|
+
source: 'cache_auto_summarized',
|
|
1104
|
+
warning: 'Full dataset exceeds MCP token limit (25,000 tokens)',
|
|
1105
|
+
suggestion: 'Use format="summary" for overview or format="filtered" with collection/namePattern/mode filters to get specific variables',
|
|
1106
|
+
estimatedTokens,
|
|
1107
|
+
summary,
|
|
1108
|
+
}),
|
|
1109
|
+
},
|
|
1110
|
+
],
|
|
1111
|
+
};
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
// Apply alias resolution for 'full' format if not already applied (filtered format handles it above)
|
|
1115
|
+
if (resolveAliases && format !== 'filtered' && responseData.variables?.length > 0) {
|
|
1116
|
+
// Build maps from ALL cached variables for resolution
|
|
1117
|
+
const allVariablesMap = new Map();
|
|
1118
|
+
const collectionsMap = new Map();
|
|
1119
|
+
for (const v of cachedData.variables || []) {
|
|
1120
|
+
allVariablesMap.set(v.id, v);
|
|
1121
|
+
}
|
|
1122
|
+
for (const c of cachedData.variableCollections || []) {
|
|
1123
|
+
collectionsMap.set(c.id, c);
|
|
1124
|
+
}
|
|
1125
|
+
responseData.variables = resolveVariableAliases(responseData.variables, allVariablesMap, collectionsMap);
|
|
1126
|
+
logger.info({ fileKey, resolvedCount: responseData.variables.length, format }, 'Applied alias resolution to variables (full/summary format)');
|
|
1127
|
+
}
|
|
1128
|
+
// Return cached/processed data
|
|
1129
|
+
// If returnAsLinks=true, return resource_link references instead of full data
|
|
1130
|
+
if (returnAsLinks) {
|
|
1131
|
+
const summary = {
|
|
1132
|
+
fileKey,
|
|
1133
|
+
source: 'cache',
|
|
1134
|
+
totalVariables: responseData.variables?.length || 0,
|
|
1135
|
+
totalCollections: responseData.variableCollections?.length || 0,
|
|
1136
|
+
...(paginationInfo && { pagination: paginationInfo }),
|
|
1137
|
+
};
|
|
1138
|
+
// Build resource_link content for each variable
|
|
1139
|
+
const content = [
|
|
1140
|
+
{
|
|
1141
|
+
type: "text",
|
|
1142
|
+
text: JSON.stringify(summary),
|
|
1143
|
+
},
|
|
1144
|
+
];
|
|
1145
|
+
// Add resource_link for each variable (minimal overhead ~150 bytes each)
|
|
1146
|
+
responseData.variables?.forEach((v) => {
|
|
1147
|
+
content.push({
|
|
1148
|
+
type: "resource_link",
|
|
1149
|
+
uri: `figma://variable/${v.id}`,
|
|
1150
|
+
name: v.name || v.id,
|
|
1151
|
+
description: `${v.resolvedType || 'VARIABLE'} from ${fileKey}`,
|
|
1152
|
+
});
|
|
1153
|
+
});
|
|
1154
|
+
logger.info({
|
|
1155
|
+
fileKey,
|
|
1156
|
+
format: 'resource_links',
|
|
1157
|
+
variableCount: responseData.variables?.length || 0,
|
|
1158
|
+
linkCount: content.length - 1, // -1 for summary text
|
|
1159
|
+
estimatedSizeKB: (content.length * 150) / 1024,
|
|
1160
|
+
}, `Returning variables as resource_links`);
|
|
1161
|
+
return { content };
|
|
1162
|
+
}
|
|
1163
|
+
// Default: return full data
|
|
1164
|
+
const responsePayload = {
|
|
1165
|
+
fileKey,
|
|
1166
|
+
source: 'cache',
|
|
1167
|
+
format: format || 'full',
|
|
1168
|
+
timestamp: cachedData.timestamp,
|
|
1169
|
+
data: responseData,
|
|
1170
|
+
...(paginationInfo && { pagination: paginationInfo }),
|
|
1171
|
+
};
|
|
1172
|
+
// Remove pretty printing to reduce payload size by 30-40%
|
|
1173
|
+
const responseText = JSON.stringify(responsePayload);
|
|
1174
|
+
const responseSizeBytes = Buffer.byteLength(responseText, 'utf8');
|
|
1175
|
+
const responseSizeMB = (responseSizeBytes / (1024 * 1024)).toFixed(2);
|
|
1176
|
+
logger.info({
|
|
1177
|
+
fileKey,
|
|
1178
|
+
format: format || 'full',
|
|
1179
|
+
verbosity: verbosity || 'standard',
|
|
1180
|
+
variableCount: responseData.variables?.length || 0,
|
|
1181
|
+
collectionCount: responseData.variableCollections?.length || 0,
|
|
1182
|
+
responseSizeBytes,
|
|
1183
|
+
responseSizeMB: `${responseSizeMB} MB`,
|
|
1184
|
+
isUnder1MB: responseSizeBytes < 1024 * 1024,
|
|
1185
|
+
}, `Response size check: ${responseSizeMB} MB`);
|
|
1186
|
+
return {
|
|
1187
|
+
content: [
|
|
1188
|
+
{
|
|
1189
|
+
type: "text",
|
|
1190
|
+
text: responseText,
|
|
1191
|
+
},
|
|
1192
|
+
],
|
|
1193
|
+
};
|
|
1194
|
+
}
|
|
1195
|
+
// =====================================================================
|
|
1196
|
+
// FETCH LOGIC: No cache or cache invalid/refresh requested
|
|
1197
|
+
// =====================================================================
|
|
1198
|
+
// Check if REST API token is available (determines priority)
|
|
1199
|
+
const hasToken = !!process.env.FIGMA_ACCESS_TOKEN;
|
|
1200
|
+
let restApiSucceeded = false;
|
|
1201
|
+
// PRIORITY LOGIC:
|
|
1202
|
+
// 1. If token exists → Try REST API FIRST (enterprise users)
|
|
1203
|
+
// 2. If no token OR REST API fails → Try Desktop Bridge as fallback
|
|
1204
|
+
logger.info({ hasToken }, "Authentication method detection");
|
|
1205
|
+
// Try REST API first if token is available
|
|
1206
|
+
if (hasToken && !parseFromConsole) {
|
|
1207
|
+
try {
|
|
1208
|
+
logger.info({ fileKey, includePublished, verbosity, enrich }, "Fetching variables via REST API (priority: token detected)");
|
|
1209
|
+
const api = await getFigmaAPI();
|
|
1210
|
+
// Wrap API call with timeout to prevent indefinite hangs (30s timeout)
|
|
1211
|
+
const { local, published, localError, publishedError } = await withTimeout(api.getAllVariables(fileKey), 30000, 'Figma Variables API');
|
|
1212
|
+
// If local variables failed (e.g., 403 without Enterprise), fall through to Desktop Bridge
|
|
1213
|
+
if (localError) {
|
|
1214
|
+
logger.warn({ error: localError, fileKey }, "REST API failed to get local variables, falling back to Desktop Bridge");
|
|
1215
|
+
throw new Error(localError);
|
|
1216
|
+
}
|
|
1217
|
+
let localFormatted = formatVariables(local);
|
|
1218
|
+
let publishedFormatted = includePublished
|
|
1219
|
+
? formatVariables(published)
|
|
1220
|
+
: null;
|
|
1221
|
+
// DEBUG: Check if valuesByMode exists before filtering
|
|
1222
|
+
if (localFormatted.variables[0]) {
|
|
1223
|
+
logger.info({
|
|
1224
|
+
hasValuesByMode: !!localFormatted.variables[0].valuesByMode,
|
|
1225
|
+
variableKeys: Object.keys(localFormatted.variables[0]),
|
|
1226
|
+
collectionCount: localFormatted.collections?.length,
|
|
1227
|
+
}, 'Variable structure before filtering');
|
|
1228
|
+
}
|
|
1229
|
+
// Apply collection/name/mode filtering if format is 'filtered'
|
|
1230
|
+
if (format === 'filtered') {
|
|
1231
|
+
// Create properly structured data for applyFilters
|
|
1232
|
+
const dataToFilter = {
|
|
1233
|
+
variables: localFormatted.variables,
|
|
1234
|
+
variableCollections: localFormatted.collections,
|
|
1235
|
+
};
|
|
1236
|
+
const filteredLocal = applyFilters(dataToFilter, { collection, namePattern, mode }, verbosity || "standard");
|
|
1237
|
+
localFormatted = {
|
|
1238
|
+
summary: localFormatted.summary,
|
|
1239
|
+
collections: filteredLocal.variableCollections,
|
|
1240
|
+
variables: filteredLocal.variables,
|
|
1241
|
+
};
|
|
1242
|
+
// Also filter published if included
|
|
1243
|
+
if (includePublished && publishedFormatted) {
|
|
1244
|
+
const dataToFilterPublished = {
|
|
1245
|
+
variables: publishedFormatted.variables,
|
|
1246
|
+
variableCollections: publishedFormatted.collections,
|
|
1247
|
+
};
|
|
1248
|
+
const filteredPublished = applyFilters(dataToFilterPublished, { collection, namePattern, mode }, verbosity || "standard");
|
|
1249
|
+
publishedFormatted = {
|
|
1250
|
+
summary: publishedFormatted.summary,
|
|
1251
|
+
collections: filteredPublished.variableCollections,
|
|
1252
|
+
variables: filteredPublished.variables,
|
|
1253
|
+
};
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
// Apply verbosity filtering after collection/name/mode filters
|
|
1257
|
+
if (verbosity && verbosity !== 'full') {
|
|
1258
|
+
const verbosityFiltered = applyFilters({
|
|
1259
|
+
variables: localFormatted.variables,
|
|
1260
|
+
variableCollections: localFormatted.collections,
|
|
1261
|
+
}, {}, verbosity);
|
|
1262
|
+
localFormatted = {
|
|
1263
|
+
...localFormatted,
|
|
1264
|
+
collections: verbosityFiltered.variableCollections,
|
|
1265
|
+
variables: verbosityFiltered.variables,
|
|
1266
|
+
};
|
|
1267
|
+
if (includePublished && publishedFormatted) {
|
|
1268
|
+
const verbosityFilteredPublished = applyFilters({
|
|
1269
|
+
variables: publishedFormatted.variables,
|
|
1270
|
+
variableCollections: publishedFormatted.collections,
|
|
1271
|
+
}, {}, verbosity);
|
|
1272
|
+
publishedFormatted = {
|
|
1273
|
+
...publishedFormatted,
|
|
1274
|
+
collections: verbosityFilteredPublished.variableCollections,
|
|
1275
|
+
variables: verbosityFilteredPublished.variables,
|
|
1276
|
+
};
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
// Apply pagination if requested
|
|
1280
|
+
let paginationInfo;
|
|
1281
|
+
if (pageSize) {
|
|
1282
|
+
const startIdx = (page - 1) * pageSize;
|
|
1283
|
+
const endIdx = startIdx + pageSize;
|
|
1284
|
+
const totalVars = localFormatted.variables.length;
|
|
1285
|
+
paginationInfo = {
|
|
1286
|
+
page,
|
|
1287
|
+
pageSize,
|
|
1288
|
+
totalItems: totalVars,
|
|
1289
|
+
totalPages: Math.ceil(totalVars / pageSize),
|
|
1290
|
+
hasNextPage: endIdx < totalVars,
|
|
1291
|
+
hasPrevPage: page > 1,
|
|
1292
|
+
};
|
|
1293
|
+
localFormatted.variables = localFormatted.variables.slice(startIdx, endIdx);
|
|
1294
|
+
if (includePublished && publishedFormatted) {
|
|
1295
|
+
publishedFormatted.variables = publishedFormatted.variables.slice(startIdx, endIdx);
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
// Cache the successful REST API response
|
|
1299
|
+
const dataForCache = {
|
|
1300
|
+
fileKey,
|
|
1301
|
+
local: {
|
|
1302
|
+
summary: localFormatted.summary,
|
|
1303
|
+
collections: localFormatted.collections,
|
|
1304
|
+
variables: localFormatted.variables,
|
|
1305
|
+
},
|
|
1306
|
+
...(includePublished &&
|
|
1307
|
+
publishedFormatted && {
|
|
1308
|
+
published: {
|
|
1309
|
+
summary: publishedFormatted.summary,
|
|
1310
|
+
collections: publishedFormatted.collections,
|
|
1311
|
+
variables: publishedFormatted.variables,
|
|
1312
|
+
},
|
|
1313
|
+
}),
|
|
1314
|
+
verbosity: verbosity || "standard",
|
|
1315
|
+
enriched: enrich || false,
|
|
1316
|
+
timestamp: Date.now(),
|
|
1317
|
+
source: "rest_api",
|
|
1318
|
+
};
|
|
1319
|
+
if (variablesCache) {
|
|
1320
|
+
variablesCache.set(fileKey, { data: dataForCache, timestamp: Date.now() });
|
|
1321
|
+
logger.info({ fileKey }, "Cached REST API variables");
|
|
1322
|
+
}
|
|
1323
|
+
// Apply alias resolution if requested (REST API format has local.variables)
|
|
1324
|
+
if (resolveAliases && localFormatted.variables?.length > 0) {
|
|
1325
|
+
// Build maps from local variables and collections
|
|
1326
|
+
const allVariablesMap = new Map();
|
|
1327
|
+
const collectionsMap = new Map();
|
|
1328
|
+
for (const v of localFormatted.variables || []) {
|
|
1329
|
+
allVariablesMap.set(v.id, v);
|
|
1330
|
+
}
|
|
1331
|
+
for (const c of localFormatted.collections || []) {
|
|
1332
|
+
collectionsMap.set(c.id, c);
|
|
1333
|
+
}
|
|
1334
|
+
// Also include published variables if available
|
|
1335
|
+
if (publishedFormatted?.variables) {
|
|
1336
|
+
for (const v of publishedFormatted.variables) {
|
|
1337
|
+
allVariablesMap.set(v.id, v);
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
if (publishedFormatted?.collections) {
|
|
1341
|
+
for (const c of publishedFormatted.collections) {
|
|
1342
|
+
collectionsMap.set(c.id, c);
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
localFormatted.variables = resolveVariableAliases(localFormatted.variables, allVariablesMap, collectionsMap);
|
|
1346
|
+
if (publishedFormatted?.variables) {
|
|
1347
|
+
publishedFormatted.variables = resolveVariableAliases(publishedFormatted.variables, allVariablesMap, collectionsMap);
|
|
1348
|
+
}
|
|
1349
|
+
logger.info({ fileKey, resolvedCount: localFormatted.variables.length }, 'Applied alias resolution to REST API variables');
|
|
1350
|
+
}
|
|
1351
|
+
// Handle resource_links format
|
|
1352
|
+
if (returnAsLinks) {
|
|
1353
|
+
const content = [
|
|
1354
|
+
{
|
|
1355
|
+
type: "text",
|
|
1356
|
+
text: `Variables for file ${fileKey} (${localFormatted.variables.length} variables). Use figma_get_variable_by_id to fetch specific variables:\n\n`,
|
|
1357
|
+
},
|
|
1358
|
+
];
|
|
1359
|
+
for (const variable of localFormatted.variables) {
|
|
1360
|
+
content.push({
|
|
1361
|
+
type: "resource",
|
|
1362
|
+
resource: {
|
|
1363
|
+
uri: `figma://variable/${fileKey}/${variable.id}`,
|
|
1364
|
+
mimeType: "application/json",
|
|
1365
|
+
text: `${variable.name} (${variable.resolvedType})`,
|
|
1366
|
+
},
|
|
1367
|
+
});
|
|
1368
|
+
}
|
|
1369
|
+
logger.info({
|
|
1370
|
+
fileKey,
|
|
1371
|
+
format: 'resource_links',
|
|
1372
|
+
variableCount: localFormatted.variables.length,
|
|
1373
|
+
linkCount: content.length - 1,
|
|
1374
|
+
}, `Returning REST API variables as resource_links`);
|
|
1375
|
+
return { content };
|
|
1376
|
+
}
|
|
1377
|
+
// Build initial response data
|
|
1378
|
+
const responseData = {
|
|
1379
|
+
fileKey,
|
|
1380
|
+
local: {
|
|
1381
|
+
summary: localFormatted.summary,
|
|
1382
|
+
collections: localFormatted.collections,
|
|
1383
|
+
variables: localFormatted.variables,
|
|
1384
|
+
},
|
|
1385
|
+
...(includePublished &&
|
|
1386
|
+
publishedFormatted && {
|
|
1387
|
+
published: {
|
|
1388
|
+
summary: publishedFormatted.summary,
|
|
1389
|
+
collections: publishedFormatted.collections,
|
|
1390
|
+
variables: publishedFormatted.variables,
|
|
1391
|
+
},
|
|
1392
|
+
}),
|
|
1393
|
+
verbosity: verbosity || "standard",
|
|
1394
|
+
enriched: enrich || false,
|
|
1395
|
+
...(paginationInfo && { pagination: paginationInfo }),
|
|
1396
|
+
};
|
|
1397
|
+
// Mark REST API as successful
|
|
1398
|
+
restApiSucceeded = true;
|
|
1399
|
+
logger.info({ fileKey }, "REST API fetch successful, skipping Desktop Bridge");
|
|
1400
|
+
// Use adaptive response to prevent context exhaustion
|
|
1401
|
+
return adaptiveResponse(responseData, {
|
|
1402
|
+
toolName: "figma_get_variables",
|
|
1403
|
+
compressionCallback: (adjustedLevel) => {
|
|
1404
|
+
// Re-apply filters with adjusted verbosity
|
|
1405
|
+
const level = adjustedLevel;
|
|
1406
|
+
const refiltered = applyFilters({
|
|
1407
|
+
variables: localFormatted.variables,
|
|
1408
|
+
variableCollections: localFormatted.collections,
|
|
1409
|
+
}, { collection, namePattern, mode }, level);
|
|
1410
|
+
return {
|
|
1411
|
+
...responseData,
|
|
1412
|
+
local: {
|
|
1413
|
+
...responseData.local,
|
|
1414
|
+
variables: refiltered.variables,
|
|
1415
|
+
collections: refiltered.variableCollections,
|
|
1416
|
+
},
|
|
1417
|
+
verbosity: level,
|
|
1418
|
+
};
|
|
1419
|
+
},
|
|
1420
|
+
suggestedActions: [
|
|
1421
|
+
"Use verbosity='inventory' or 'summary' for large variable sets",
|
|
1422
|
+
"Apply filters: collection, namePattern, or mode parameters",
|
|
1423
|
+
"Use pagination with pageSize parameter (default 50, max 100)",
|
|
1424
|
+
"Use returnAsLinks=true to get resource_link references instead of full data",
|
|
1425
|
+
],
|
|
1426
|
+
});
|
|
1427
|
+
}
|
|
1428
|
+
catch (restError) {
|
|
1429
|
+
const errorMessage = restError instanceof Error ? restError.message : String(restError);
|
|
1430
|
+
// Detect specific error types for better logging and handling
|
|
1431
|
+
const isTimeout = errorMessage.includes('timed out');
|
|
1432
|
+
const isRateLimit = errorMessage.includes('429') || errorMessage.toLowerCase().includes('rate limit');
|
|
1433
|
+
const isAuthError = errorMessage.includes('403') || errorMessage.includes('401');
|
|
1434
|
+
if (isTimeout) {
|
|
1435
|
+
logger.warn({ error: errorMessage, fileKey }, "REST API timed out after 30s, falling back to Desktop Bridge");
|
|
1436
|
+
}
|
|
1437
|
+
else if (isRateLimit) {
|
|
1438
|
+
logger.warn({ error: errorMessage, fileKey }, "REST API rate limited (429), falling back to Desktop Bridge");
|
|
1439
|
+
}
|
|
1440
|
+
else if (isAuthError) {
|
|
1441
|
+
logger.warn({ error: errorMessage, fileKey }, "REST API auth error, check FIGMA_ACCESS_TOKEN validity");
|
|
1442
|
+
}
|
|
1443
|
+
else {
|
|
1444
|
+
logger.warn({ error: errorMessage, fileKey }, "REST API failed, will try Desktop Bridge fallback");
|
|
1445
|
+
}
|
|
1446
|
+
// Don't throw - fall through to Desktop Bridge
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
// FALLBACK: Try Desktop connection (when no token available OR as secondary fallback)
|
|
1450
|
+
// Only call ensureInitialized for legacy path — skip when transport-agnostic connector exists
|
|
1451
|
+
if (ensureInitialized && !getDesktopConnector && !parseFromConsole && (!hasToken || !restApiSucceeded)) {
|
|
1452
|
+
logger.info("Calling ensureInitialized to initialize browser manager (legacy path)");
|
|
1453
|
+
await ensureInitialized();
|
|
1454
|
+
}
|
|
1455
|
+
const browserManager = getBrowserManager?.();
|
|
1456
|
+
const hasDesktopConnection = !!getDesktopConnector || !!browserManager;
|
|
1457
|
+
logger.info({ hasBrowserManager: !!browserManager, hasDesktopConnector: !!getDesktopConnector, parseFromConsole, hasToken, restApiSucceeded }, "Desktop connection check");
|
|
1458
|
+
// Debug: Log why Desktop connection might be skipped
|
|
1459
|
+
if (!hasDesktopConnection) {
|
|
1460
|
+
logger.error("Desktop connection skipped: neither connector nor browserManager available");
|
|
1461
|
+
}
|
|
1462
|
+
else if (parseFromConsole) {
|
|
1463
|
+
logger.info("Desktop connection skipped: parseFromConsole is true");
|
|
1464
|
+
}
|
|
1465
|
+
else if (restApiSucceeded) {
|
|
1466
|
+
logger.info("Desktop connection skipped: REST API already succeeded");
|
|
1467
|
+
}
|
|
1468
|
+
if (hasDesktopConnection && !parseFromConsole && (!hasToken || !restApiSucceeded)) {
|
|
1469
|
+
try {
|
|
1470
|
+
logger.info({ fileKey }, "Attempting to get variables via Desktop connection");
|
|
1471
|
+
let connector;
|
|
1472
|
+
if (getDesktopConnector) {
|
|
1473
|
+
connector = await getDesktopConnector();
|
|
1474
|
+
}
|
|
1475
|
+
else {
|
|
1476
|
+
// Fallback: direct connector (legacy path)
|
|
1477
|
+
const { FigmaDesktopConnector } = await import('./figma-desktop-connector.js');
|
|
1478
|
+
const page = await browserManager.getPage();
|
|
1479
|
+
connector = new FigmaDesktopConnector(page);
|
|
1480
|
+
await connector.initialize();
|
|
1481
|
+
}
|
|
1482
|
+
logger.info({ transport: connector.getTransportType?.() || 'unknown' }, "Desktop connector ready");
|
|
1483
|
+
const desktopResult = await connector.getVariablesFromPluginUI(fileKey);
|
|
1484
|
+
if (desktopResult.success && desktopResult.variables) {
|
|
1485
|
+
logger.info({
|
|
1486
|
+
variableCount: desktopResult.variables.length,
|
|
1487
|
+
collectionCount: desktopResult.variableCollections?.length
|
|
1488
|
+
}, "Successfully retrieved variables via Desktop connection!");
|
|
1489
|
+
// Prepare data for caching (using the raw data, not enriched)
|
|
1490
|
+
const dataForCache = {
|
|
1491
|
+
fileKey,
|
|
1492
|
+
source: "desktop_connection",
|
|
1493
|
+
timestamp: desktopResult.timestamp || Date.now(),
|
|
1494
|
+
variables: desktopResult.variables,
|
|
1495
|
+
variableCollections: desktopResult.variableCollections,
|
|
1496
|
+
};
|
|
1497
|
+
// Store in cache with LRU eviction
|
|
1498
|
+
if (variablesCache) {
|
|
1499
|
+
evictOldestCacheEntry(variablesCache);
|
|
1500
|
+
variablesCache.set(fileKey, {
|
|
1501
|
+
data: dataForCache,
|
|
1502
|
+
timestamp: Date.now(),
|
|
1503
|
+
});
|
|
1504
|
+
logger.info({ fileKey, cacheSize: variablesCache.size }, 'Stored variables in cache');
|
|
1505
|
+
}
|
|
1506
|
+
// Apply format logic
|
|
1507
|
+
let responseData = dataForCache;
|
|
1508
|
+
if (format === 'summary') {
|
|
1509
|
+
responseData = generateSummary(dataForCache);
|
|
1510
|
+
logger.info({ fileKey, estimatedTokens: estimateTokens(responseData) }, 'Generated summary from fetched data');
|
|
1511
|
+
}
|
|
1512
|
+
else if (format === 'filtered') {
|
|
1513
|
+
// Apply filters with verbosity-aware valuesByMode transformation
|
|
1514
|
+
responseData = applyFilters(dataForCache, {
|
|
1515
|
+
collection,
|
|
1516
|
+
namePattern,
|
|
1517
|
+
mode,
|
|
1518
|
+
}, verbosity || 'standard');
|
|
1519
|
+
logger.info({
|
|
1520
|
+
fileKey,
|
|
1521
|
+
originalCount: dataForCache.variables?.length,
|
|
1522
|
+
filteredCount: responseData.variables?.length,
|
|
1523
|
+
}, 'Applied filters to fetched data');
|
|
1524
|
+
// Apply pagination (CRITICAL - was missing!)
|
|
1525
|
+
let paginationInfo = null;
|
|
1526
|
+
const paginated = paginateVariables(responseData, page || 1, pageSize || 50);
|
|
1527
|
+
responseData = paginated.data;
|
|
1528
|
+
paginationInfo = paginated.pagination;
|
|
1529
|
+
// Apply verbosity filtering (CRITICAL - was missing!)
|
|
1530
|
+
const effectiveVerbosity = verbosity || "inventory";
|
|
1531
|
+
// Only include collections referenced by paginated variables
|
|
1532
|
+
const referencedCollectionIds = new Set(responseData.variables.map((v) => v.variableCollectionId));
|
|
1533
|
+
responseData.variableCollections = responseData.variableCollections.filter((c) => referencedCollectionIds.has(c.id));
|
|
1534
|
+
// Filter variables by verbosity
|
|
1535
|
+
responseData.variables = responseData.variables.map((v) => {
|
|
1536
|
+
if (effectiveVerbosity === "inventory") {
|
|
1537
|
+
return {
|
|
1538
|
+
id: v.id,
|
|
1539
|
+
name: v.name,
|
|
1540
|
+
collectionId: v.variableCollectionId,
|
|
1541
|
+
};
|
|
1542
|
+
}
|
|
1543
|
+
if (effectiveVerbosity === "summary") {
|
|
1544
|
+
return {
|
|
1545
|
+
id: v.id,
|
|
1546
|
+
name: v.name,
|
|
1547
|
+
resolvedType: v.resolvedType,
|
|
1548
|
+
valuesByMode: v.valuesByMode,
|
|
1549
|
+
variableCollectionId: v.variableCollectionId,
|
|
1550
|
+
};
|
|
1551
|
+
}
|
|
1552
|
+
return v; // standard/full
|
|
1553
|
+
});
|
|
1554
|
+
// Filter collections by verbosity
|
|
1555
|
+
responseData.variableCollections = responseData.variableCollections.map((c) => {
|
|
1556
|
+
if (effectiveVerbosity === "inventory") {
|
|
1557
|
+
return {
|
|
1558
|
+
id: c.id,
|
|
1559
|
+
name: c.name,
|
|
1560
|
+
modeNames: c.modes?.map((m) => m.name) || [],
|
|
1561
|
+
};
|
|
1562
|
+
}
|
|
1563
|
+
if (effectiveVerbosity === "summary") {
|
|
1564
|
+
return {
|
|
1565
|
+
id: c.id,
|
|
1566
|
+
name: c.name,
|
|
1567
|
+
modes: c.modes,
|
|
1568
|
+
};
|
|
1569
|
+
}
|
|
1570
|
+
return c; // standard/full
|
|
1571
|
+
});
|
|
1572
|
+
}
|
|
1573
|
+
else {
|
|
1574
|
+
// format === 'full'
|
|
1575
|
+
// Check if we need to auto-summarize
|
|
1576
|
+
const estimatedTokens = estimateTokens(responseData);
|
|
1577
|
+
if (estimatedTokens > 25000) {
|
|
1578
|
+
logger.warn({ fileKey, estimatedTokens }, 'Full data exceeds MCP token limit (25K), auto-summarizing. Use format=summary or format=filtered to get specific data.');
|
|
1579
|
+
const summary = generateSummary(responseData);
|
|
1580
|
+
return {
|
|
1581
|
+
content: [
|
|
1582
|
+
{
|
|
1583
|
+
type: "text",
|
|
1584
|
+
text: JSON.stringify({
|
|
1585
|
+
fileKey,
|
|
1586
|
+
source: 'desktop_connection_auto_summarized',
|
|
1587
|
+
warning: 'Full dataset exceeds MCP token limit (25,000 tokens)',
|
|
1588
|
+
suggestion: 'Use format="summary" for overview or format="filtered" with collection/namePattern/mode filters to get specific variables',
|
|
1589
|
+
estimatedTokens,
|
|
1590
|
+
summary,
|
|
1591
|
+
}),
|
|
1592
|
+
},
|
|
1593
|
+
],
|
|
1594
|
+
};
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
// Apply alias resolution if requested
|
|
1598
|
+
if (resolveAliases && responseData.variables?.length > 0) {
|
|
1599
|
+
// Build maps from ALL variables for resolution
|
|
1600
|
+
const allVariablesMap = new Map();
|
|
1601
|
+
const collectionsMap = new Map();
|
|
1602
|
+
for (const v of dataForCache.variables || []) {
|
|
1603
|
+
allVariablesMap.set(v.id, v);
|
|
1604
|
+
}
|
|
1605
|
+
for (const c of dataForCache.variableCollections || []) {
|
|
1606
|
+
collectionsMap.set(c.id, c);
|
|
1607
|
+
}
|
|
1608
|
+
responseData.variables = resolveVariableAliases(responseData.variables, allVariablesMap, collectionsMap);
|
|
1609
|
+
logger.info({ fileKey, resolvedCount: responseData.variables.length }, 'Applied alias resolution to Desktop variables');
|
|
1610
|
+
}
|
|
1611
|
+
// If returnAsLinks=true, return resource_link references
|
|
1612
|
+
if (returnAsLinks) {
|
|
1613
|
+
const summary = {
|
|
1614
|
+
fileKey,
|
|
1615
|
+
source: 'desktop_connection',
|
|
1616
|
+
totalVariables: responseData.variables?.length || 0,
|
|
1617
|
+
totalCollections: responseData.variableCollections?.length || 0,
|
|
1618
|
+
};
|
|
1619
|
+
const content = [
|
|
1620
|
+
{
|
|
1621
|
+
type: "text",
|
|
1622
|
+
text: JSON.stringify(summary),
|
|
1623
|
+
},
|
|
1624
|
+
];
|
|
1625
|
+
// Add resource_link for each variable
|
|
1626
|
+
responseData.variables?.forEach((v) => {
|
|
1627
|
+
content.push({
|
|
1628
|
+
type: "resource_link",
|
|
1629
|
+
uri: `figma://variable/${v.id}`,
|
|
1630
|
+
name: v.name || v.id,
|
|
1631
|
+
description: `${v.resolvedType || 'VARIABLE'} from ${fileKey}`,
|
|
1632
|
+
});
|
|
1633
|
+
});
|
|
1634
|
+
logger.info({
|
|
1635
|
+
fileKey,
|
|
1636
|
+
format: 'resource_links',
|
|
1637
|
+
variableCount: responseData.variables?.length || 0,
|
|
1638
|
+
linkCount: content.length - 1,
|
|
1639
|
+
}, `Returning Desktop variables as resource_links`);
|
|
1640
|
+
return { content };
|
|
1641
|
+
}
|
|
1642
|
+
// Default: return full data (removed pretty printing)
|
|
1643
|
+
return {
|
|
1644
|
+
content: [
|
|
1645
|
+
{
|
|
1646
|
+
type: "text",
|
|
1647
|
+
text: JSON.stringify({
|
|
1648
|
+
fileKey,
|
|
1649
|
+
source: "desktop_connection",
|
|
1650
|
+
format: format || 'full',
|
|
1651
|
+
timestamp: dataForCache.timestamp,
|
|
1652
|
+
data: responseData,
|
|
1653
|
+
cached: true,
|
|
1654
|
+
}),
|
|
1655
|
+
},
|
|
1656
|
+
],
|
|
1657
|
+
};
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
catch (desktopError) {
|
|
1661
|
+
const errorMessage = desktopError instanceof Error ? desktopError.message : String(desktopError);
|
|
1662
|
+
const errorStack = desktopError instanceof Error ? desktopError.stack : undefined;
|
|
1663
|
+
logger.error({
|
|
1664
|
+
error: desktopError,
|
|
1665
|
+
message: errorMessage,
|
|
1666
|
+
stack: errorStack
|
|
1667
|
+
}, "Desktop connection failed, falling back to other methods");
|
|
1668
|
+
// Try to log to browser console if we have access to page
|
|
1669
|
+
try {
|
|
1670
|
+
if (browserManager) {
|
|
1671
|
+
const page = await browserManager.getPage();
|
|
1672
|
+
await page.evaluate((msg, stack) => {
|
|
1673
|
+
console.error('[FIGMA_TOOLS] ❌ Desktop connection failed:', msg);
|
|
1674
|
+
if (stack) {
|
|
1675
|
+
console.error('[FIGMA_TOOLS] Stack trace:', stack);
|
|
1676
|
+
}
|
|
1677
|
+
}, errorMessage, errorStack);
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
catch (logError) {
|
|
1681
|
+
// Ignore logging errors
|
|
1682
|
+
}
|
|
1683
|
+
// Continue to try other methods
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
// FALLBACK: Parse from console logs if requested
|
|
1687
|
+
if (parseFromConsole) {
|
|
1688
|
+
const consoleMonitor = getConsoleMonitor?.();
|
|
1689
|
+
if (!consoleMonitor) {
|
|
1690
|
+
throw new Error("Console monitoring not available. Make sure browser is connected to Figma.");
|
|
1691
|
+
}
|
|
1692
|
+
logger.info({ fileKey }, "Parsing variables from console logs");
|
|
1693
|
+
// Get recent logs
|
|
1694
|
+
const logs = consoleMonitor.getLogs({ count: 100, level: "log" });
|
|
1695
|
+
const varLog = snippetInjector.findVariablesLog(logs);
|
|
1696
|
+
if (!varLog) {
|
|
1697
|
+
throw new Error("No variables found in console logs.\n\n" +
|
|
1698
|
+
"Did you run the snippet in Figma's plugin console? Here's the correct workflow:\n\n" +
|
|
1699
|
+
"1. Call figma_get_variables() without parameters (you may have already done this)\n" +
|
|
1700
|
+
"2. Copy the provided snippet\n" +
|
|
1701
|
+
"3. Open Figma Desktop → Plugins → Development → Open Console\n" +
|
|
1702
|
+
"4. Paste and run the snippet in the PLUGIN console (not browser DevTools)\n" +
|
|
1703
|
+
"5. Wait for '✅ Variables data captured!' confirmation\n" +
|
|
1704
|
+
"6. Then call figma_get_variables({ parseFromConsole: true })\n\n" +
|
|
1705
|
+
"Note: The browser console won't work - you need a plugin console for the figma.variables API.");
|
|
1706
|
+
}
|
|
1707
|
+
// Parse variables from log
|
|
1708
|
+
const parsedData = snippetInjector.parseVariablesFromLog(varLog);
|
|
1709
|
+
if (!parsedData) {
|
|
1710
|
+
throw new Error("Failed to parse variables from console log");
|
|
1711
|
+
}
|
|
1712
|
+
return {
|
|
1713
|
+
content: [
|
|
1714
|
+
{
|
|
1715
|
+
type: "text",
|
|
1716
|
+
text: JSON.stringify({
|
|
1717
|
+
fileKey,
|
|
1718
|
+
source: "console_capture",
|
|
1719
|
+
local: {
|
|
1720
|
+
summary: {
|
|
1721
|
+
total_variables: parsedData.variables.length,
|
|
1722
|
+
total_collections: parsedData.variableCollections.length,
|
|
1723
|
+
},
|
|
1724
|
+
collections: parsedData.variableCollections,
|
|
1725
|
+
variables: parsedData.variables,
|
|
1726
|
+
},
|
|
1727
|
+
timestamp: parsedData.timestamp,
|
|
1728
|
+
enriched: false,
|
|
1729
|
+
}),
|
|
1730
|
+
},
|
|
1731
|
+
],
|
|
1732
|
+
};
|
|
1733
|
+
}
|
|
1734
|
+
// No more fallback options available
|
|
1735
|
+
throw new Error(`Cannot retrieve variables. All methods failed.\n\n` +
|
|
1736
|
+
`Tried methods:\n` +
|
|
1737
|
+
`${hasToken ? '✗ REST API (failed)\n' : ''}` +
|
|
1738
|
+
`✗ Desktop Bridge (failed or not available)\n` +
|
|
1739
|
+
`\nTo fix:\n` +
|
|
1740
|
+
`1. If you have FIGMA_ACCESS_TOKEN: Check your token permissions\n` +
|
|
1741
|
+
`2. Install and run the Figma Desktop Bridge plugin\n` +
|
|
1742
|
+
`3. Alternative: Use parseFromConsole=true with console snippet workflow`);
|
|
1743
|
+
}
|
|
1744
|
+
catch (error) {
|
|
1745
|
+
logger.error({ error }, "Failed to get variables");
|
|
1746
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
1747
|
+
// FIXED: Jump directly to Styles API (fast) instead of full file data (slow)
|
|
1748
|
+
if (errorMessage.includes("403")) {
|
|
1749
|
+
try {
|
|
1750
|
+
logger.info({ fileKey }, "Variables API requires Enterprise, falling back to Styles API");
|
|
1751
|
+
let api;
|
|
1752
|
+
try {
|
|
1753
|
+
api = await getFigmaAPI();
|
|
1754
|
+
}
|
|
1755
|
+
catch (apiError) {
|
|
1756
|
+
const errorMessage = apiError instanceof Error ? apiError.message : String(apiError);
|
|
1757
|
+
throw new Error(`Cannot retrieve variables or styles. REST API authentication required for both.\n` +
|
|
1758
|
+
`Error: ${errorMessage}\n\n` +
|
|
1759
|
+
`To fix:\n` +
|
|
1760
|
+
`1. Local mode: Set FIGMA_ACCESS_TOKEN environment variable\n` +
|
|
1761
|
+
`2. Cloud mode: Authenticate via OAuth`);
|
|
1762
|
+
}
|
|
1763
|
+
// Use the Styles API directly - much faster than getFile!
|
|
1764
|
+
const stylesData = await api.getStyles(fileKey);
|
|
1765
|
+
// Format the styles data similar to variables
|
|
1766
|
+
const formattedStyles = {
|
|
1767
|
+
summary: {
|
|
1768
|
+
total_styles: stylesData.meta?.styles?.length || 0,
|
|
1769
|
+
message: "Variables API requires Enterprise. Here are your design styles instead.",
|
|
1770
|
+
note: "These are Figma Styles (not Variables). Styles are the traditional way to store design tokens in Figma."
|
|
1771
|
+
},
|
|
1772
|
+
styles: stylesData.meta?.styles || []
|
|
1773
|
+
};
|
|
1774
|
+
logger.info({ styleCount: formattedStyles.summary.total_styles }, "Successfully retrieved styles as fallback!");
|
|
1775
|
+
return {
|
|
1776
|
+
content: [
|
|
1777
|
+
{
|
|
1778
|
+
type: "text",
|
|
1779
|
+
text: JSON.stringify({
|
|
1780
|
+
fileKey,
|
|
1781
|
+
source: "styles_api",
|
|
1782
|
+
message: "Variables API requires an Enterprise plan. Retrieved your design system styles instead.",
|
|
1783
|
+
data: formattedStyles,
|
|
1784
|
+
fallback_method: true,
|
|
1785
|
+
}),
|
|
1786
|
+
},
|
|
1787
|
+
],
|
|
1788
|
+
};
|
|
1789
|
+
}
|
|
1790
|
+
catch (styleError) {
|
|
1791
|
+
logger.warn({ error: styleError }, "Style extraction failed");
|
|
1792
|
+
// Return a simple error message without the console snippet
|
|
1793
|
+
return {
|
|
1794
|
+
content: [
|
|
1795
|
+
{
|
|
1796
|
+
type: "text",
|
|
1797
|
+
text: JSON.stringify({
|
|
1798
|
+
error: "Unable to extract variables or styles from this file",
|
|
1799
|
+
message: "The Variables API requires an Enterprise plan, and the automatic style extraction encountered an error.",
|
|
1800
|
+
possibleReasons: [
|
|
1801
|
+
"The file may be private or require additional permissions",
|
|
1802
|
+
"The file structure may not contain extractable styles",
|
|
1803
|
+
"There may be a network or authentication issue"
|
|
1804
|
+
],
|
|
1805
|
+
suggestion: "Please ensure the file is accessible and try again, or check if your token has the necessary permissions.",
|
|
1806
|
+
technical: styleError instanceof Error ? styleError.message : String(styleError)
|
|
1807
|
+
}),
|
|
1808
|
+
},
|
|
1809
|
+
],
|
|
1810
|
+
};
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
1813
|
+
// Standard error response
|
|
1814
|
+
return {
|
|
1815
|
+
content: [
|
|
1816
|
+
{
|
|
1817
|
+
type: "text",
|
|
1818
|
+
text: JSON.stringify({
|
|
1819
|
+
error: errorMessage,
|
|
1820
|
+
message: "Failed to retrieve Figma variables",
|
|
1821
|
+
hint: errorMessage.includes("403")
|
|
1822
|
+
? "Variables API requires Enterprise plan. Set useConsoleFallback=true for alternative method."
|
|
1823
|
+
: "Make sure FIGMA_ACCESS_TOKEN is configured and has appropriate permissions",
|
|
1824
|
+
}),
|
|
1825
|
+
},
|
|
1826
|
+
],
|
|
1827
|
+
isError: true,
|
|
1828
|
+
};
|
|
1829
|
+
}
|
|
1830
|
+
});
|
|
1831
|
+
// Tool 10: Get Component Data
|
|
1832
|
+
const componentDescription = isRemoteMode
|
|
1833
|
+
? "Get a SINGLE component's metadata or reconstruction specification. Two export formats: (1) 'metadata' (default) - comprehensive documentation with properties, variants, and design tokens for style guides and references, (2) 'reconstruction' - node tree specification compatible with Figma Component Reconstructor plugin for programmatic component creation. TIP: To get ALL components with visual specs in one call, prefer figma_get_design_system_kit instead."
|
|
1834
|
+
: "Get a SINGLE component's metadata or reconstruction specification. Two export formats: (1) 'metadata' (default) - comprehensive documentation with properties, variants, and design tokens for style guides and references, (2) 'reconstruction' - node tree specification compatible with Figma Component Reconstructor plugin for programmatic component creation. IMPORTANT: For local/unpublished components with metadata format, ensure the Figma Desktop Bridge plugin is running (Right-click in Figma → Plugins → Development → Figma Desktop Bridge) to get complete description data. TIP: To get ALL components with visual specs in one call, prefer figma_get_design_system_kit instead.";
|
|
1835
|
+
server.tool("figma_get_component", componentDescription, {
|
|
1836
|
+
fileUrl: z
|
|
1837
|
+
.string()
|
|
1838
|
+
.url()
|
|
1839
|
+
.optional()
|
|
1840
|
+
.describe("Figma file URL (e.g., https://figma.com/design/abc123). Auto-detected from WebSocket Desktop Bridge connection. Only required if not connected."),
|
|
1841
|
+
nodeId: z
|
|
1842
|
+
.string()
|
|
1843
|
+
.describe("Component node ID (e.g., '123:456')"),
|
|
1844
|
+
format: z
|
|
1845
|
+
.enum(["metadata", "reconstruction"])
|
|
1846
|
+
.optional()
|
|
1847
|
+
.default("metadata")
|
|
1848
|
+
.describe("Export format: 'metadata' (default) for comprehensive documentation, 'reconstruction' for node tree specification compatible with Figma Component Reconstructor plugin"),
|
|
1849
|
+
enrich: z
|
|
1850
|
+
.boolean()
|
|
1851
|
+
.optional()
|
|
1852
|
+
.describe("Set to true when user asks for: design token coverage, hardcoded value analysis, or component quality metrics. Adds token coverage analysis and hardcoded value detection. Default: false. Only applicable for metadata format."),
|
|
1853
|
+
}, async ({ fileUrl, nodeId, format = "metadata", enrich }) => {
|
|
1854
|
+
try {
|
|
1855
|
+
const url = fileUrl || getCurrentUrl();
|
|
1856
|
+
if (!url) {
|
|
1857
|
+
throw new Error("No Figma file URL available. Pass the fileUrl parameter or ensure the Desktop Bridge plugin is open in Figma.");
|
|
1858
|
+
}
|
|
1859
|
+
const fileKey = extractFileKey(url);
|
|
1860
|
+
if (!fileKey) {
|
|
1861
|
+
throw new Error(`Invalid Figma URL: ${url}`);
|
|
1862
|
+
}
|
|
1863
|
+
logger.info({ fileKey, nodeId, format, enrich }, "Fetching component data");
|
|
1864
|
+
// PRIORITY 1: Try Desktop Bridge plugin UI first (has reliable description field!)
|
|
1865
|
+
if (getDesktopConnector || (getBrowserManager && ensureInitialized)) {
|
|
1866
|
+
try {
|
|
1867
|
+
logger.info({ nodeId }, "Attempting to get component via Desktop Bridge plugin UI");
|
|
1868
|
+
let connector;
|
|
1869
|
+
if (getDesktopConnector) {
|
|
1870
|
+
connector = await getDesktopConnector();
|
|
1871
|
+
}
|
|
1872
|
+
else {
|
|
1873
|
+
// Fallback: direct connector (legacy path)
|
|
1874
|
+
if (ensureInitialized)
|
|
1875
|
+
await ensureInitialized();
|
|
1876
|
+
const browserManager = getBrowserManager?.();
|
|
1877
|
+
if (!browserManager) {
|
|
1878
|
+
throw new Error("Browser manager not available after initialization");
|
|
1879
|
+
}
|
|
1880
|
+
const { FigmaDesktopConnector } = await import('./figma-desktop-connector.js');
|
|
1881
|
+
const page = await browserManager.getPage();
|
|
1882
|
+
connector = new FigmaDesktopConnector(page);
|
|
1883
|
+
await connector.initialize();
|
|
1884
|
+
}
|
|
1885
|
+
const desktopResult = await connector.getComponentFromPluginUI(nodeId);
|
|
1886
|
+
if (desktopResult.success && desktopResult.component) {
|
|
1887
|
+
logger.info({
|
|
1888
|
+
componentName: desktopResult.component.name,
|
|
1889
|
+
hasDescription: !!desktopResult.component.description,
|
|
1890
|
+
hasDescriptionMarkdown: !!desktopResult.component.descriptionMarkdown,
|
|
1891
|
+
annotationsCount: desktopResult.component.annotations?.length || 0
|
|
1892
|
+
}, "Successfully retrieved component via Desktop Bridge plugin UI!");
|
|
1893
|
+
// Handle reconstruction format
|
|
1894
|
+
if (format === "reconstruction") {
|
|
1895
|
+
const reconstructionSpec = extractNodeSpec(desktopResult.component);
|
|
1896
|
+
const validation = validateReconstructionSpec(reconstructionSpec);
|
|
1897
|
+
if (!validation.valid) {
|
|
1898
|
+
logger.warn({ errors: validation.errors }, "Reconstruction spec validation warnings");
|
|
1899
|
+
}
|
|
1900
|
+
// Check if this is a COMPONENT_SET - plugin cannot create these
|
|
1901
|
+
if (reconstructionSpec.type === 'COMPONENT_SET') {
|
|
1902
|
+
const variants = listVariants(desktopResult.component);
|
|
1903
|
+
return {
|
|
1904
|
+
content: [
|
|
1905
|
+
{
|
|
1906
|
+
type: "text",
|
|
1907
|
+
text: JSON.stringify({
|
|
1908
|
+
error: "COMPONENT_SET_NOT_SUPPORTED",
|
|
1909
|
+
message: "The Figma Component Reconstructor plugin cannot create COMPONENT_SET nodes (variant containers). Please select a specific variant component instead.",
|
|
1910
|
+
componentName: reconstructionSpec.name,
|
|
1911
|
+
availableVariants: variants,
|
|
1912
|
+
instructions: [
|
|
1913
|
+
"1. In Figma, expand the component set to see individual variants",
|
|
1914
|
+
"2. Select the specific variant you want to reconstruct",
|
|
1915
|
+
"3. Copy the node ID of that variant",
|
|
1916
|
+
"4. Use figma_get_component with that variant's node ID"
|
|
1917
|
+
],
|
|
1918
|
+
note: "COMPONENT_SET is automatically created by Figma when you have variants. The plugin can only create individual COMPONENT nodes."
|
|
1919
|
+
}),
|
|
1920
|
+
},
|
|
1921
|
+
],
|
|
1922
|
+
};
|
|
1923
|
+
}
|
|
1924
|
+
// Return spec directly for plugin compatibility
|
|
1925
|
+
// Plugin expects name, type, etc. at root level
|
|
1926
|
+
return {
|
|
1927
|
+
content: [
|
|
1928
|
+
{
|
|
1929
|
+
type: "text",
|
|
1930
|
+
text: JSON.stringify(reconstructionSpec),
|
|
1931
|
+
},
|
|
1932
|
+
],
|
|
1933
|
+
};
|
|
1934
|
+
}
|
|
1935
|
+
// Handle metadata format (original behavior)
|
|
1936
|
+
let formatted = desktopResult.component;
|
|
1937
|
+
// Apply enrichment if requested
|
|
1938
|
+
if (enrich) {
|
|
1939
|
+
const enrichmentOptions = {
|
|
1940
|
+
enrich: true,
|
|
1941
|
+
include_usage: true,
|
|
1942
|
+
};
|
|
1943
|
+
formatted = await enrichmentService.enrichComponent(formatted, fileKey, enrichmentOptions);
|
|
1944
|
+
}
|
|
1945
|
+
return {
|
|
1946
|
+
content: [
|
|
1947
|
+
{
|
|
1948
|
+
type: "text",
|
|
1949
|
+
text: JSON.stringify({
|
|
1950
|
+
fileKey,
|
|
1951
|
+
nodeId,
|
|
1952
|
+
component: formatted,
|
|
1953
|
+
source: "desktop_bridge_plugin",
|
|
1954
|
+
enriched: enrich || false,
|
|
1955
|
+
note: "Retrieved via Desktop Bridge plugin - description fields and annotations are reliable and current"
|
|
1956
|
+
}),
|
|
1957
|
+
},
|
|
1958
|
+
],
|
|
1959
|
+
};
|
|
1960
|
+
}
|
|
1961
|
+
}
|
|
1962
|
+
catch (desktopError) {
|
|
1963
|
+
logger.warn({ error: desktopError, nodeId }, "Desktop Bridge plugin failed, falling back to REST API");
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
// FALLBACK: Use REST API (may have missing/outdated description)
|
|
1967
|
+
logger.info({ nodeId }, "Using REST API fallback");
|
|
1968
|
+
// Initialize API client (may throw if no token available)
|
|
1969
|
+
let api;
|
|
1970
|
+
try {
|
|
1971
|
+
api = await getFigmaAPI();
|
|
1972
|
+
}
|
|
1973
|
+
catch (apiError) {
|
|
1974
|
+
const errorMessage = apiError instanceof Error ? apiError.message : String(apiError);
|
|
1975
|
+
throw new Error(`Cannot retrieve component data. Both Desktop Bridge and REST API are unavailable.\n` +
|
|
1976
|
+
`Desktop Bridge: ${getDesktopConnector || (getBrowserManager && ensureInitialized) ? 'Failed (see logs above)' : 'Not available (local mode only)'}\n` +
|
|
1977
|
+
`REST API: ${errorMessage}\n\n` +
|
|
1978
|
+
`To fix:\n` +
|
|
1979
|
+
`1. Local mode: Set FIGMA_ACCESS_TOKEN environment variable, OR ensure Figma Desktop Bridge plugin is running\n` +
|
|
1980
|
+
`2. Cloud mode: Authenticate via OAuth\n` +
|
|
1981
|
+
`3. Ensure the Desktop Bridge plugin is running in Figma Desktop`);
|
|
1982
|
+
}
|
|
1983
|
+
const componentData = await api.getComponentData(fileKey, nodeId);
|
|
1984
|
+
if (!componentData) {
|
|
1985
|
+
throw new Error(`Component not found: ${nodeId}`);
|
|
1986
|
+
}
|
|
1987
|
+
// Handle reconstruction format
|
|
1988
|
+
if (format === "reconstruction") {
|
|
1989
|
+
const reconstructionSpec = extractNodeSpec(componentData.document);
|
|
1990
|
+
const validation = validateReconstructionSpec(reconstructionSpec);
|
|
1991
|
+
if (!validation.valid) {
|
|
1992
|
+
logger.warn({ errors: validation.errors }, "Reconstruction spec validation warnings");
|
|
1993
|
+
}
|
|
1994
|
+
// Check if this is a COMPONENT_SET - plugin cannot create these
|
|
1995
|
+
if (reconstructionSpec.type === 'COMPONENT_SET') {
|
|
1996
|
+
const variants = listVariants(componentData.document);
|
|
1997
|
+
return {
|
|
1998
|
+
content: [
|
|
1999
|
+
{
|
|
2000
|
+
type: "text",
|
|
2001
|
+
text: JSON.stringify({
|
|
2002
|
+
error: "COMPONENT_SET_NOT_SUPPORTED",
|
|
2003
|
+
message: "The Figma Component Reconstructor plugin cannot create COMPONENT_SET nodes (variant containers). Please select a specific variant component instead.",
|
|
2004
|
+
componentName: reconstructionSpec.name,
|
|
2005
|
+
availableVariants: variants,
|
|
2006
|
+
instructions: [
|
|
2007
|
+
"1. In Figma, expand the component set to see individual variants",
|
|
2008
|
+
"2. Select the specific variant you want to reconstruct",
|
|
2009
|
+
"3. Copy the node ID of that variant",
|
|
2010
|
+
"4. Use figma_get_component with that variant's node ID"
|
|
2011
|
+
],
|
|
2012
|
+
note: "COMPONENT_SET is automatically created by Figma when you have variants. The plugin can only create individual COMPONENT nodes."
|
|
2013
|
+
}),
|
|
2014
|
+
},
|
|
2015
|
+
],
|
|
2016
|
+
};
|
|
2017
|
+
}
|
|
2018
|
+
// Return spec directly for plugin compatibility
|
|
2019
|
+
// Plugin expects name, type, etc. at root level
|
|
2020
|
+
return {
|
|
2021
|
+
content: [
|
|
2022
|
+
{
|
|
2023
|
+
type: "text",
|
|
2024
|
+
text: JSON.stringify(reconstructionSpec),
|
|
2025
|
+
},
|
|
2026
|
+
],
|
|
2027
|
+
};
|
|
2028
|
+
}
|
|
2029
|
+
// Handle metadata format (original behavior)
|
|
2030
|
+
let formatted = formatComponentData(componentData.document);
|
|
2031
|
+
// Apply enrichment if requested
|
|
2032
|
+
if (enrich) {
|
|
2033
|
+
const enrichmentOptions = {
|
|
2034
|
+
enrich: true,
|
|
2035
|
+
include_usage: true,
|
|
2036
|
+
};
|
|
2037
|
+
formatted = await enrichmentService.enrichComponent(formatted, fileKey, enrichmentOptions);
|
|
2038
|
+
}
|
|
2039
|
+
return {
|
|
2040
|
+
content: [
|
|
2041
|
+
{
|
|
2042
|
+
type: "text",
|
|
2043
|
+
text: JSON.stringify({
|
|
2044
|
+
fileKey,
|
|
2045
|
+
nodeId,
|
|
2046
|
+
component: formatted,
|
|
2047
|
+
source: "rest_api",
|
|
2048
|
+
enriched: enrich || false,
|
|
2049
|
+
warning: "Retrieved via REST API - description field may be missing due to known Figma API bug",
|
|
2050
|
+
action_required: formatted.description || formatted.descriptionMarkdown ? null : "To get reliable component descriptions, run the Desktop Bridge plugin in Figma Desktop: Right-click → Plugins → Development → Figma Desktop Bridge, then try again."
|
|
2051
|
+
}),
|
|
2052
|
+
},
|
|
2053
|
+
],
|
|
2054
|
+
};
|
|
2055
|
+
}
|
|
2056
|
+
catch (error) {
|
|
2057
|
+
logger.error({ error }, "Failed to get component");
|
|
2058
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2059
|
+
return {
|
|
2060
|
+
content: [
|
|
2061
|
+
{
|
|
2062
|
+
type: "text",
|
|
2063
|
+
text: JSON.stringify({
|
|
2064
|
+
error: errorMessage,
|
|
2065
|
+
message: "Failed to retrieve component data",
|
|
2066
|
+
hint: "Make sure the node ID is correct and the file is accessible",
|
|
2067
|
+
}),
|
|
2068
|
+
},
|
|
2069
|
+
],
|
|
2070
|
+
isError: true,
|
|
2071
|
+
};
|
|
2072
|
+
}
|
|
2073
|
+
});
|
|
2074
|
+
// Tool 11: Get Styles
|
|
2075
|
+
server.tool("figma_get_styles", "Get all styles (color, text, effects, grids) from a Figma file with optional code exports. Use when user asks for: text styles, color palette, design system styles, typography, or style documentation. Returns organized style definitions with resolved values. NOT for design tokens/variables (use figma_get_variables). Set enrich=true for CSS/Tailwind/Sass code examples. Supports verbosity control to manage payload size. TIP: For full design system extraction (tokens + components + styles combined), prefer figma_get_design_system_kit instead — it returns everything in one optimized call.", {
|
|
2076
|
+
fileUrl: z
|
|
2077
|
+
.string()
|
|
2078
|
+
.url()
|
|
2079
|
+
.optional()
|
|
2080
|
+
.describe("Figma file URL (e.g., https://figma.com/design/abc123). Auto-detected from WebSocket Desktop Bridge connection. Only required if not connected."),
|
|
2081
|
+
verbosity: z
|
|
2082
|
+
.enum(["summary", "standard", "full"])
|
|
2083
|
+
.optional()
|
|
2084
|
+
.default("standard")
|
|
2085
|
+
.describe("Controls payload size: 'summary' (names/types only, ~85% smaller), 'standard' (essential properties, ~40% smaller), 'full' (everything). Default: standard"),
|
|
2086
|
+
enrich: z
|
|
2087
|
+
.boolean()
|
|
2088
|
+
.optional()
|
|
2089
|
+
.describe("Set to true when user asks for: CSS/Sass/Tailwind code, export formats, usage information, code examples, or design system exports. Adds resolved values, usage analysis, and export format examples. Default: false for backward compatibility"),
|
|
2090
|
+
include_usage: z
|
|
2091
|
+
.boolean()
|
|
2092
|
+
.optional()
|
|
2093
|
+
.describe("Include component usage information (requires enrich=true)"),
|
|
2094
|
+
include_exports: z
|
|
2095
|
+
.boolean()
|
|
2096
|
+
.optional()
|
|
2097
|
+
.describe("Include export format examples (requires enrich=true)"),
|
|
2098
|
+
export_formats: z
|
|
2099
|
+
.array(z.enum(["css", "sass", "tailwind", "typescript", "json"]))
|
|
2100
|
+
.optional()
|
|
2101
|
+
.describe("Which code formats to generate examples for. Use when user mentions specific formats like 'CSS', 'Tailwind', 'SCSS', 'TypeScript', etc. Automatically enables enrichment. Default: all formats"),
|
|
2102
|
+
}, async ({ fileUrl, verbosity, enrich, include_usage, include_exports, export_formats }) => {
|
|
2103
|
+
try {
|
|
2104
|
+
let api;
|
|
2105
|
+
try {
|
|
2106
|
+
api = await getFigmaAPI();
|
|
2107
|
+
}
|
|
2108
|
+
catch (apiError) {
|
|
2109
|
+
const errorMessage = apiError instanceof Error ? apiError.message : String(apiError);
|
|
2110
|
+
throw new Error(`Cannot retrieve styles. REST API authentication required.\n` +
|
|
2111
|
+
`Error: ${errorMessage}\n\n` +
|
|
2112
|
+
`To fix:\n` +
|
|
2113
|
+
`1. Local mode: Set FIGMA_ACCESS_TOKEN environment variable\n` +
|
|
2114
|
+
`2. Cloud mode: Authenticate via OAuth`);
|
|
2115
|
+
}
|
|
2116
|
+
const url = fileUrl || getCurrentUrl();
|
|
2117
|
+
if (!url) {
|
|
2118
|
+
throw new Error("No Figma file URL available. Pass the fileUrl parameter or ensure the Desktop Bridge plugin is open in Figma.");
|
|
2119
|
+
}
|
|
2120
|
+
const fileKey = extractFileKey(url);
|
|
2121
|
+
if (!fileKey) {
|
|
2122
|
+
throw new Error(`Invalid Figma URL: ${url}`);
|
|
2123
|
+
}
|
|
2124
|
+
logger.info({ fileKey, verbosity, enrich }, "Fetching styles");
|
|
2125
|
+
// Get styles via REST API
|
|
2126
|
+
const stylesData = await api.getStyles(fileKey);
|
|
2127
|
+
let styles = stylesData.meta?.styles || [];
|
|
2128
|
+
logger.info({ styleCount: styles.length }, "Successfully retrieved styles via REST API");
|
|
2129
|
+
// Apply verbosity filtering
|
|
2130
|
+
const filterStyle = (style, level) => {
|
|
2131
|
+
if (!style)
|
|
2132
|
+
return style;
|
|
2133
|
+
if (level === "summary") {
|
|
2134
|
+
// Summary: Only key, name, type (~85% reduction)
|
|
2135
|
+
return {
|
|
2136
|
+
key: style.key,
|
|
2137
|
+
name: style.name,
|
|
2138
|
+
style_type: style.style_type,
|
|
2139
|
+
};
|
|
2140
|
+
}
|
|
2141
|
+
if (level === "standard") {
|
|
2142
|
+
// Standard: Essential properties (~40% reduction)
|
|
2143
|
+
return {
|
|
2144
|
+
key: style.key,
|
|
2145
|
+
name: style.name,
|
|
2146
|
+
description: style.description,
|
|
2147
|
+
style_type: style.style_type,
|
|
2148
|
+
...(style.remote && { remote: style.remote }),
|
|
2149
|
+
};
|
|
2150
|
+
}
|
|
2151
|
+
// Full: Return everything
|
|
2152
|
+
return style;
|
|
2153
|
+
};
|
|
2154
|
+
if (verbosity !== "full") {
|
|
2155
|
+
styles = styles.map((style) => filterStyle(style, verbosity || "standard"));
|
|
2156
|
+
}
|
|
2157
|
+
// Apply enrichment if requested
|
|
2158
|
+
if (enrich) {
|
|
2159
|
+
const enrichmentOptions = {
|
|
2160
|
+
enrich: true,
|
|
2161
|
+
include_usage: include_usage !== false,
|
|
2162
|
+
include_exports: include_exports !== false,
|
|
2163
|
+
export_formats: export_formats || [
|
|
2164
|
+
"css",
|
|
2165
|
+
"sass",
|
|
2166
|
+
"tailwind",
|
|
2167
|
+
"typescript",
|
|
2168
|
+
"json",
|
|
2169
|
+
],
|
|
2170
|
+
};
|
|
2171
|
+
styles = await enrichmentService.enrichStyles(styles, fileKey, enrichmentOptions);
|
|
2172
|
+
}
|
|
2173
|
+
const finalResponse = {
|
|
2174
|
+
fileKey,
|
|
2175
|
+
styles,
|
|
2176
|
+
totalStyles: styles.length,
|
|
2177
|
+
verbosity: verbosity || "standard",
|
|
2178
|
+
enriched: enrich || false,
|
|
2179
|
+
};
|
|
2180
|
+
// Use adaptive response to prevent context exhaustion
|
|
2181
|
+
return adaptiveResponse(finalResponse, {
|
|
2182
|
+
toolName: "figma_get_styles",
|
|
2183
|
+
compressionCallback: (adjustedLevel) => {
|
|
2184
|
+
// Re-apply style filtering with lower verbosity
|
|
2185
|
+
const level = adjustedLevel;
|
|
2186
|
+
const refilteredStyles = verbosity !== "full"
|
|
2187
|
+
? styles.map((style) => filterStyle(style, level))
|
|
2188
|
+
: styles;
|
|
2189
|
+
return {
|
|
2190
|
+
...finalResponse,
|
|
2191
|
+
styles: refilteredStyles,
|
|
2192
|
+
verbosity: level,
|
|
2193
|
+
};
|
|
2194
|
+
},
|
|
2195
|
+
suggestedActions: [
|
|
2196
|
+
"Use verbosity='summary' for style names and types only",
|
|
2197
|
+
"Use verbosity='standard' for essential style properties",
|
|
2198
|
+
"Filter to specific style types if needed",
|
|
2199
|
+
],
|
|
2200
|
+
});
|
|
2201
|
+
}
|
|
2202
|
+
catch (error) {
|
|
2203
|
+
logger.error({ error }, "Failed to get styles");
|
|
2204
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2205
|
+
return {
|
|
2206
|
+
content: [
|
|
2207
|
+
{
|
|
2208
|
+
type: "text",
|
|
2209
|
+
text: JSON.stringify({
|
|
2210
|
+
error: errorMessage,
|
|
2211
|
+
message: "Failed to retrieve styles",
|
|
2212
|
+
}),
|
|
2213
|
+
},
|
|
2214
|
+
],
|
|
2215
|
+
isError: true,
|
|
2216
|
+
};
|
|
2217
|
+
}
|
|
2218
|
+
});
|
|
2219
|
+
// Tool 12: Get Component Image (Visual Reference)
|
|
2220
|
+
server.tool("figma_get_component_image", "Render a specific component or node as an image (PNG, JPG, SVG, PDF). Returns image URL valid for 30 days. Use when user asks for: component screenshot, visual preview, rendered output, or 'show me'. NOT for component metadata/properties (use figma_get_component). NOT for getting code/layout data (use figma_get_component_for_development). Best for: visual references, design review, documentation.", {
|
|
2221
|
+
fileUrl: z
|
|
2222
|
+
.string()
|
|
2223
|
+
.url()
|
|
2224
|
+
.optional()
|
|
2225
|
+
.describe("Figma file URL (e.g., https://figma.com/design/abc123). Auto-detected from WebSocket Desktop Bridge connection. Only required if not connected."),
|
|
2226
|
+
nodeId: z
|
|
2227
|
+
.string()
|
|
2228
|
+
.describe("Component node ID to render as image (e.g., '695:313')"),
|
|
2229
|
+
scale: z
|
|
2230
|
+
.number()
|
|
2231
|
+
.min(0.01)
|
|
2232
|
+
.max(4)
|
|
2233
|
+
.optional()
|
|
2234
|
+
.default(2)
|
|
2235
|
+
.describe("Image scale factor (0.01-4, default: 2 for high quality)"),
|
|
2236
|
+
format: z
|
|
2237
|
+
.enum(["png", "jpg", "svg", "pdf"])
|
|
2238
|
+
.optional()
|
|
2239
|
+
.default("png")
|
|
2240
|
+
.describe("Image format (default: png)"),
|
|
2241
|
+
}, async ({ fileUrl, nodeId, scale, format }) => {
|
|
2242
|
+
try {
|
|
2243
|
+
let api;
|
|
2244
|
+
try {
|
|
2245
|
+
api = await getFigmaAPI();
|
|
2246
|
+
}
|
|
2247
|
+
catch (apiError) {
|
|
2248
|
+
const errorMessage = apiError instanceof Error ? apiError.message : String(apiError);
|
|
2249
|
+
throw new Error(`Cannot render component image. REST API authentication required.\n` +
|
|
2250
|
+
`Error: ${errorMessage}\n\n` +
|
|
2251
|
+
`To fix:\n` +
|
|
2252
|
+
`1. Local mode: Set FIGMA_ACCESS_TOKEN environment variable\n` +
|
|
2253
|
+
`2. Cloud mode: Authenticate via OAuth\n\n` +
|
|
2254
|
+
`Note: For component screenshots, figma_capture_screenshot may work as an alternative ` +
|
|
2255
|
+
`if the Desktop Bridge plugin is connected.`);
|
|
2256
|
+
}
|
|
2257
|
+
const url = fileUrl || getCurrentUrl();
|
|
2258
|
+
if (!url) {
|
|
2259
|
+
throw new Error("No Figma file URL available. Pass the fileUrl parameter or ensure the Desktop Bridge plugin is open in Figma.");
|
|
2260
|
+
}
|
|
2261
|
+
const fileKey = extractFileKey(url);
|
|
2262
|
+
if (!fileKey) {
|
|
2263
|
+
throw new Error(`Invalid Figma URL: ${url}`);
|
|
2264
|
+
}
|
|
2265
|
+
logger.info({ fileKey, nodeId, scale, format }, "Rendering component image");
|
|
2266
|
+
// First, fetch the node to check if it's a COMPONENT_SET
|
|
2267
|
+
const fileData = await api.getNodes(fileKey, [nodeId]);
|
|
2268
|
+
const node = fileData.nodes?.[nodeId]?.document;
|
|
2269
|
+
if (!node) {
|
|
2270
|
+
throw new Error(`Node ${nodeId} not found in file ${fileKey}. Please verify the node ID is correct.`);
|
|
2271
|
+
}
|
|
2272
|
+
// Check if this is a COMPONENT_SET - cannot be rendered as image
|
|
2273
|
+
if (node.type === 'COMPONENT_SET') {
|
|
2274
|
+
const variants = listVariants(node);
|
|
2275
|
+
return {
|
|
2276
|
+
content: [
|
|
2277
|
+
{
|
|
2278
|
+
type: "text",
|
|
2279
|
+
text: JSON.stringify({
|
|
2280
|
+
error: "COMPONENT_SET_NOT_RENDERABLE",
|
|
2281
|
+
message: "Node is a COMPONENT_SET which cannot be rendered. Please use a specific variant component ID instead.",
|
|
2282
|
+
componentName: node.name,
|
|
2283
|
+
availableVariants: variants,
|
|
2284
|
+
instructions: [
|
|
2285
|
+
"1. In Figma, expand the component set to see individual variants",
|
|
2286
|
+
"2. Select the specific variant you want to render",
|
|
2287
|
+
"3. Copy the node ID of that variant",
|
|
2288
|
+
"4. Use figma_get_component_image with that variant's node ID"
|
|
2289
|
+
],
|
|
2290
|
+
note: "COMPONENT_SET is a container for variants. Only individual variant components can be rendered as images."
|
|
2291
|
+
}),
|
|
2292
|
+
},
|
|
2293
|
+
],
|
|
2294
|
+
};
|
|
2295
|
+
}
|
|
2296
|
+
// Call the new getImages method
|
|
2297
|
+
const result = await api.getImages(fileKey, nodeId, {
|
|
2298
|
+
scale,
|
|
2299
|
+
format,
|
|
2300
|
+
contents_only: true,
|
|
2301
|
+
});
|
|
2302
|
+
const imageUrl = result.images[nodeId];
|
|
2303
|
+
if (!imageUrl) {
|
|
2304
|
+
throw new Error(`Failed to render image for node ${nodeId}. The node may not exist or may not be renderable.`);
|
|
2305
|
+
}
|
|
2306
|
+
return {
|
|
2307
|
+
content: [
|
|
2308
|
+
{
|
|
2309
|
+
type: "text",
|
|
2310
|
+
text: JSON.stringify({
|
|
2311
|
+
fileKey,
|
|
2312
|
+
nodeId,
|
|
2313
|
+
imageUrl,
|
|
2314
|
+
scale,
|
|
2315
|
+
format,
|
|
2316
|
+
expiresIn: "30 days",
|
|
2317
|
+
note: "Use this image as visual reference for component development. Image URLs expire after 30 days.",
|
|
2318
|
+
}),
|
|
2319
|
+
},
|
|
2320
|
+
],
|
|
2321
|
+
};
|
|
2322
|
+
}
|
|
2323
|
+
catch (error) {
|
|
2324
|
+
logger.error({ error }, "Failed to render component image");
|
|
2325
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2326
|
+
return {
|
|
2327
|
+
content: [
|
|
2328
|
+
{
|
|
2329
|
+
type: "text",
|
|
2330
|
+
text: JSON.stringify({
|
|
2331
|
+
error: errorMessage,
|
|
2332
|
+
message: "Failed to render component image",
|
|
2333
|
+
hint: "Make sure the node ID is correct and the component is renderable",
|
|
2334
|
+
}),
|
|
2335
|
+
},
|
|
2336
|
+
],
|
|
2337
|
+
isError: true,
|
|
2338
|
+
};
|
|
2339
|
+
}
|
|
2340
|
+
});
|
|
2341
|
+
// Tool 13: Get Component for Development (UI Implementation)
|
|
2342
|
+
server.tool("figma_get_component_for_development", "Get component data optimized for UI implementation, includes rendered image + filtered implementation context (layout, typography, visual properties). Use when user asks to: 'build this component', 'implement this in React/Vue', 'generate code for', or needs both visual reference and technical specs. Automatically includes 2x scale image unless includeImage=false. Best for: UI development, code generation, design-to-code workflows. For just metadata, use figma_get_component; for just image, use figma_get_component_image.", {
|
|
2343
|
+
fileUrl: z
|
|
2344
|
+
.string()
|
|
2345
|
+
.url()
|
|
2346
|
+
.optional()
|
|
2347
|
+
.describe("Figma file URL (e.g., https://figma.com/design/abc123). REQUIRED unless figma_navigate was already called."),
|
|
2348
|
+
nodeId: z
|
|
2349
|
+
.string()
|
|
2350
|
+
.describe("Component node ID to get data for (e.g., '695:313')"),
|
|
2351
|
+
includeImage: z
|
|
2352
|
+
.boolean()
|
|
2353
|
+
.optional()
|
|
2354
|
+
.default(true)
|
|
2355
|
+
.describe("Include rendered image for visual reference (default: true)"),
|
|
2356
|
+
}, async ({ fileUrl, nodeId, includeImage }) => {
|
|
2357
|
+
try {
|
|
2358
|
+
let api;
|
|
2359
|
+
try {
|
|
2360
|
+
api = await getFigmaAPI();
|
|
2361
|
+
}
|
|
2362
|
+
catch (apiError) {
|
|
2363
|
+
const errorMessage = apiError instanceof Error ? apiError.message : String(apiError);
|
|
2364
|
+
throw new Error(`Cannot retrieve component for development. REST API authentication required.\n` +
|
|
2365
|
+
`Error: ${errorMessage}\n\n` +
|
|
2366
|
+
`To fix:\n` +
|
|
2367
|
+
`1. Local mode: Set FIGMA_ACCESS_TOKEN environment variable\n` +
|
|
2368
|
+
`2. Cloud mode: Authenticate via OAuth\n\n` +
|
|
2369
|
+
`Note: For component metadata, figma_get_component has Desktop Bridge fallback ` +
|
|
2370
|
+
`that works without token (requires the Desktop Bridge plugin to be connected).`);
|
|
2371
|
+
}
|
|
2372
|
+
const url = fileUrl || getCurrentUrl();
|
|
2373
|
+
if (!url) {
|
|
2374
|
+
throw new Error("No Figma file URL available. Pass the fileUrl parameter or ensure the Desktop Bridge plugin is open in Figma.");
|
|
2375
|
+
}
|
|
2376
|
+
const fileKey = extractFileKey(url);
|
|
2377
|
+
if (!fileKey) {
|
|
2378
|
+
throw new Error(`Invalid Figma URL: ${url}`);
|
|
2379
|
+
}
|
|
2380
|
+
logger.info({ fileKey, nodeId, includeImage }, "Fetching component for development");
|
|
2381
|
+
// Get node data with depth for children
|
|
2382
|
+
const nodeData = await api.getNodes(fileKey, [nodeId], { depth: 2 });
|
|
2383
|
+
const node = nodeData.nodes?.[nodeId]?.document;
|
|
2384
|
+
if (!node) {
|
|
2385
|
+
throw new Error(`Component not found: ${nodeId}`);
|
|
2386
|
+
}
|
|
2387
|
+
// Filter to visual/layout properties only
|
|
2388
|
+
const filterForDevelopment = (n) => {
|
|
2389
|
+
if (!n)
|
|
2390
|
+
return n;
|
|
2391
|
+
const result = {
|
|
2392
|
+
id: n.id,
|
|
2393
|
+
name: n.name,
|
|
2394
|
+
type: n.type,
|
|
2395
|
+
description: n.description,
|
|
2396
|
+
descriptionMarkdown: n.descriptionMarkdown,
|
|
2397
|
+
};
|
|
2398
|
+
// Layout & positioning
|
|
2399
|
+
if (n.absoluteBoundingBox)
|
|
2400
|
+
result.absoluteBoundingBox = n.absoluteBoundingBox;
|
|
2401
|
+
if (n.relativeTransform)
|
|
2402
|
+
result.relativeTransform = n.relativeTransform;
|
|
2403
|
+
if (n.size)
|
|
2404
|
+
result.size = n.size;
|
|
2405
|
+
if (n.constraints)
|
|
2406
|
+
result.constraints = n.constraints;
|
|
2407
|
+
if (n.layoutAlign)
|
|
2408
|
+
result.layoutAlign = n.layoutAlign;
|
|
2409
|
+
if (n.layoutGrow)
|
|
2410
|
+
result.layoutGrow = n.layoutGrow;
|
|
2411
|
+
if (n.layoutPositioning)
|
|
2412
|
+
result.layoutPositioning = n.layoutPositioning;
|
|
2413
|
+
// Auto-layout
|
|
2414
|
+
if (n.layoutMode)
|
|
2415
|
+
result.layoutMode = n.layoutMode;
|
|
2416
|
+
if (n.primaryAxisSizingMode)
|
|
2417
|
+
result.primaryAxisSizingMode = n.primaryAxisSizingMode;
|
|
2418
|
+
if (n.counterAxisSizingMode)
|
|
2419
|
+
result.counterAxisSizingMode = n.counterAxisSizingMode;
|
|
2420
|
+
if (n.primaryAxisAlignItems)
|
|
2421
|
+
result.primaryAxisAlignItems = n.primaryAxisAlignItems;
|
|
2422
|
+
if (n.counterAxisAlignItems)
|
|
2423
|
+
result.counterAxisAlignItems = n.counterAxisAlignItems;
|
|
2424
|
+
if (n.paddingLeft !== undefined)
|
|
2425
|
+
result.paddingLeft = n.paddingLeft;
|
|
2426
|
+
if (n.paddingRight !== undefined)
|
|
2427
|
+
result.paddingRight = n.paddingRight;
|
|
2428
|
+
if (n.paddingTop !== undefined)
|
|
2429
|
+
result.paddingTop = n.paddingTop;
|
|
2430
|
+
if (n.paddingBottom !== undefined)
|
|
2431
|
+
result.paddingBottom = n.paddingBottom;
|
|
2432
|
+
if (n.itemSpacing !== undefined)
|
|
2433
|
+
result.itemSpacing = n.itemSpacing;
|
|
2434
|
+
if (n.itemReverseZIndex)
|
|
2435
|
+
result.itemReverseZIndex = n.itemReverseZIndex;
|
|
2436
|
+
if (n.strokesIncludedInLayout)
|
|
2437
|
+
result.strokesIncludedInLayout = n.strokesIncludedInLayout;
|
|
2438
|
+
// Visual properties
|
|
2439
|
+
if (n.fills)
|
|
2440
|
+
result.fills = n.fills;
|
|
2441
|
+
if (n.strokes)
|
|
2442
|
+
result.strokes = n.strokes;
|
|
2443
|
+
if (n.strokeWeight !== undefined)
|
|
2444
|
+
result.strokeWeight = n.strokeWeight;
|
|
2445
|
+
if (n.strokeAlign)
|
|
2446
|
+
result.strokeAlign = n.strokeAlign;
|
|
2447
|
+
if (n.strokeCap)
|
|
2448
|
+
result.strokeCap = n.strokeCap;
|
|
2449
|
+
if (n.strokeJoin)
|
|
2450
|
+
result.strokeJoin = n.strokeJoin;
|
|
2451
|
+
if (n.dashPattern)
|
|
2452
|
+
result.dashPattern = n.dashPattern;
|
|
2453
|
+
if (n.cornerRadius !== undefined)
|
|
2454
|
+
result.cornerRadius = n.cornerRadius;
|
|
2455
|
+
if (n.rectangleCornerRadii)
|
|
2456
|
+
result.rectangleCornerRadii = n.rectangleCornerRadii;
|
|
2457
|
+
if (n.effects)
|
|
2458
|
+
result.effects = n.effects;
|
|
2459
|
+
if (n.opacity !== undefined)
|
|
2460
|
+
result.opacity = n.opacity;
|
|
2461
|
+
if (n.blendMode)
|
|
2462
|
+
result.blendMode = n.blendMode;
|
|
2463
|
+
if (n.isMask)
|
|
2464
|
+
result.isMask = n.isMask;
|
|
2465
|
+
if (n.clipsContent)
|
|
2466
|
+
result.clipsContent = n.clipsContent;
|
|
2467
|
+
// Typography
|
|
2468
|
+
if (n.characters)
|
|
2469
|
+
result.characters = n.characters;
|
|
2470
|
+
if (n.style)
|
|
2471
|
+
result.style = n.style;
|
|
2472
|
+
if (n.characterStyleOverrides)
|
|
2473
|
+
result.characterStyleOverrides = n.characterStyleOverrides;
|
|
2474
|
+
if (n.styleOverrideTable)
|
|
2475
|
+
result.styleOverrideTable = n.styleOverrideTable;
|
|
2476
|
+
// Component properties & variants
|
|
2477
|
+
if (n.componentProperties)
|
|
2478
|
+
result.componentProperties = n.componentProperties;
|
|
2479
|
+
if (n.componentPropertyDefinitions)
|
|
2480
|
+
result.componentPropertyDefinitions = n.componentPropertyDefinitions;
|
|
2481
|
+
if (n.variantProperties)
|
|
2482
|
+
result.variantProperties = n.variantProperties;
|
|
2483
|
+
if (n.componentId)
|
|
2484
|
+
result.componentId = n.componentId;
|
|
2485
|
+
// State
|
|
2486
|
+
if (n.visible !== undefined)
|
|
2487
|
+
result.visible = n.visible;
|
|
2488
|
+
if (n.locked)
|
|
2489
|
+
result.locked = n.locked;
|
|
2490
|
+
// Recursively process children
|
|
2491
|
+
if (n.children) {
|
|
2492
|
+
result.children = n.children.map((child) => filterForDevelopment(child));
|
|
2493
|
+
}
|
|
2494
|
+
return result;
|
|
2495
|
+
};
|
|
2496
|
+
const componentData = filterForDevelopment(node);
|
|
2497
|
+
// Get image if requested
|
|
2498
|
+
let imageUrl = null;
|
|
2499
|
+
if (includeImage) {
|
|
2500
|
+
try {
|
|
2501
|
+
const imageResult = await api.getImages(fileKey, nodeId, {
|
|
2502
|
+
scale: 2,
|
|
2503
|
+
format: "png",
|
|
2504
|
+
contents_only: true,
|
|
2505
|
+
});
|
|
2506
|
+
imageUrl = imageResult.images[nodeId];
|
|
2507
|
+
}
|
|
2508
|
+
catch (error) {
|
|
2509
|
+
logger.warn({ error }, "Failed to render component image, continuing without it");
|
|
2510
|
+
}
|
|
2511
|
+
}
|
|
2512
|
+
// Build response with component data and image URL
|
|
2513
|
+
return {
|
|
2514
|
+
content: [
|
|
2515
|
+
{
|
|
2516
|
+
type: "text",
|
|
2517
|
+
text: JSON.stringify({
|
|
2518
|
+
fileKey,
|
|
2519
|
+
nodeId,
|
|
2520
|
+
imageUrl,
|
|
2521
|
+
component: componentData,
|
|
2522
|
+
metadata: {
|
|
2523
|
+
purpose: "component_development",
|
|
2524
|
+
note: imageUrl
|
|
2525
|
+
? "Image URL provided above (valid for 30 days). Full component data optimized for UI implementation."
|
|
2526
|
+
: "Full component data optimized for UI implementation.",
|
|
2527
|
+
},
|
|
2528
|
+
}),
|
|
2529
|
+
},
|
|
2530
|
+
],
|
|
2531
|
+
};
|
|
2532
|
+
}
|
|
2533
|
+
catch (error) {
|
|
2534
|
+
logger.error({ error }, "Failed to get component for development");
|
|
2535
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2536
|
+
return {
|
|
2537
|
+
content: [
|
|
2538
|
+
{
|
|
2539
|
+
type: "text",
|
|
2540
|
+
text: JSON.stringify({
|
|
2541
|
+
error: errorMessage,
|
|
2542
|
+
message: "Failed to retrieve component development data",
|
|
2543
|
+
}),
|
|
2544
|
+
},
|
|
2545
|
+
],
|
|
2546
|
+
isError: true,
|
|
2547
|
+
};
|
|
2548
|
+
}
|
|
2549
|
+
});
|
|
2550
|
+
// Tool 14: Get File for Plugin Development
|
|
2551
|
+
server.tool("figma_get_file_for_plugin", "Get file data optimized for plugin development with filtered properties (IDs, structure, plugin data, component relationships). Excludes visual properties (fills, strokes, effects) to reduce payload. Use when user asks for: plugin development, file structure for manipulation, node IDs for plugin API. NOT for component descriptions (use figma_get_component). NOT for visual/styling data (use figma_get_component_for_development). Supports deeper tree traversal (max depth=5) than figma_get_file_data.", {
|
|
2552
|
+
fileUrl: z
|
|
2553
|
+
.string()
|
|
2554
|
+
.url()
|
|
2555
|
+
.optional()
|
|
2556
|
+
.describe("Figma file URL (e.g., https://figma.com/design/abc123). REQUIRED unless figma_navigate was already called."),
|
|
2557
|
+
depth: z
|
|
2558
|
+
.number()
|
|
2559
|
+
.min(0)
|
|
2560
|
+
.max(5)
|
|
2561
|
+
.optional()
|
|
2562
|
+
.default(2)
|
|
2563
|
+
.describe("How many levels of children to include (default: 2, max: 5). Higher depths are safe here due to filtering."),
|
|
2564
|
+
nodeIds: z
|
|
2565
|
+
.array(z.string())
|
|
2566
|
+
.optional()
|
|
2567
|
+
.describe("Specific node IDs to retrieve (optional)"),
|
|
2568
|
+
}, async ({ fileUrl, depth, nodeIds }) => {
|
|
2569
|
+
try {
|
|
2570
|
+
let api;
|
|
2571
|
+
try {
|
|
2572
|
+
api = await getFigmaAPI();
|
|
2573
|
+
}
|
|
2574
|
+
catch (apiError) {
|
|
2575
|
+
const errorMessage = apiError instanceof Error ? apiError.message : String(apiError);
|
|
2576
|
+
throw new Error(`Cannot retrieve file data for plugin development. REST API authentication required.\n` +
|
|
2577
|
+
`Error: ${errorMessage}\n\n` +
|
|
2578
|
+
`To fix:\n` +
|
|
2579
|
+
`1. Local mode: Set FIGMA_ACCESS_TOKEN environment variable\n` +
|
|
2580
|
+
`2. Cloud mode: Authenticate via OAuth`);
|
|
2581
|
+
}
|
|
2582
|
+
const url = fileUrl || getCurrentUrl();
|
|
2583
|
+
if (!url) {
|
|
2584
|
+
throw new Error("No Figma file URL available. Pass the fileUrl parameter or ensure the Desktop Bridge plugin is open in Figma.");
|
|
2585
|
+
}
|
|
2586
|
+
const fileKey = extractFileKey(url);
|
|
2587
|
+
if (!fileKey) {
|
|
2588
|
+
throw new Error(`Invalid Figma URL: ${url}`);
|
|
2589
|
+
}
|
|
2590
|
+
logger.info({ fileKey, depth, nodeIds }, "Fetching file data for plugin development");
|
|
2591
|
+
const fileData = await api.getFile(fileKey, {
|
|
2592
|
+
depth,
|
|
2593
|
+
ids: nodeIds,
|
|
2594
|
+
});
|
|
2595
|
+
// Filter to plugin-relevant properties only
|
|
2596
|
+
const filterForPlugin = (node) => {
|
|
2597
|
+
if (!node)
|
|
2598
|
+
return node;
|
|
2599
|
+
const result = {
|
|
2600
|
+
id: node.id,
|
|
2601
|
+
name: node.name,
|
|
2602
|
+
type: node.type,
|
|
2603
|
+
description: node.description,
|
|
2604
|
+
descriptionMarkdown: node.descriptionMarkdown,
|
|
2605
|
+
};
|
|
2606
|
+
// Navigation & structure
|
|
2607
|
+
if (node.visible !== undefined)
|
|
2608
|
+
result.visible = node.visible;
|
|
2609
|
+
if (node.locked)
|
|
2610
|
+
result.locked = node.locked;
|
|
2611
|
+
if (node.removed)
|
|
2612
|
+
result.removed = node.removed;
|
|
2613
|
+
// Lightweight bounds (just position/size)
|
|
2614
|
+
if (node.absoluteBoundingBox) {
|
|
2615
|
+
result.bounds = {
|
|
2616
|
+
x: node.absoluteBoundingBox.x,
|
|
2617
|
+
y: node.absoluteBoundingBox.y,
|
|
2618
|
+
width: node.absoluteBoundingBox.width,
|
|
2619
|
+
height: node.absoluteBoundingBox.height,
|
|
2620
|
+
};
|
|
2621
|
+
}
|
|
2622
|
+
// Plugin data (CRITICAL for plugins)
|
|
2623
|
+
if (node.pluginData)
|
|
2624
|
+
result.pluginData = node.pluginData;
|
|
2625
|
+
if (node.sharedPluginData)
|
|
2626
|
+
result.sharedPluginData = node.sharedPluginData;
|
|
2627
|
+
// Component relationships (important for plugins)
|
|
2628
|
+
if (node.componentId)
|
|
2629
|
+
result.componentId = node.componentId;
|
|
2630
|
+
if (node.mainComponent)
|
|
2631
|
+
result.mainComponent = node.mainComponent;
|
|
2632
|
+
if (node.componentPropertyReferences)
|
|
2633
|
+
result.componentPropertyReferences = node.componentPropertyReferences;
|
|
2634
|
+
if (node.instanceOf)
|
|
2635
|
+
result.instanceOf = node.instanceOf;
|
|
2636
|
+
if (node.exposedInstances)
|
|
2637
|
+
result.exposedInstances = node.exposedInstances;
|
|
2638
|
+
// Component properties (for manipulation)
|
|
2639
|
+
if (node.componentProperties)
|
|
2640
|
+
result.componentProperties = node.componentProperties;
|
|
2641
|
+
// Characters for text nodes (plugins often need this)
|
|
2642
|
+
if (node.characters !== undefined)
|
|
2643
|
+
result.characters = node.characters;
|
|
2644
|
+
// Recursively process children
|
|
2645
|
+
if (node.children) {
|
|
2646
|
+
result.children = node.children.map((child) => filterForPlugin(child));
|
|
2647
|
+
}
|
|
2648
|
+
return result;
|
|
2649
|
+
};
|
|
2650
|
+
const filteredDocument = filterForPlugin(fileData.document);
|
|
2651
|
+
const finalResponse = {
|
|
2652
|
+
fileKey,
|
|
2653
|
+
name: fileData.name,
|
|
2654
|
+
lastModified: fileData.lastModified,
|
|
2655
|
+
version: fileData.version,
|
|
2656
|
+
document: filteredDocument,
|
|
2657
|
+
components: fileData.components
|
|
2658
|
+
? Object.keys(fileData.components).length
|
|
2659
|
+
: 0,
|
|
2660
|
+
styles: fileData.styles
|
|
2661
|
+
? Object.keys(fileData.styles).length
|
|
2662
|
+
: 0,
|
|
2663
|
+
...(nodeIds && {
|
|
2664
|
+
requestedNodes: nodeIds,
|
|
2665
|
+
nodes: fileData.nodes,
|
|
2666
|
+
}),
|
|
2667
|
+
metadata: {
|
|
2668
|
+
purpose: "plugin_development",
|
|
2669
|
+
note: "Optimized for plugin development. Contains IDs, structure, plugin data, and component relationships.",
|
|
2670
|
+
},
|
|
2671
|
+
};
|
|
2672
|
+
// Use adaptive response to prevent context exhaustion
|
|
2673
|
+
return adaptiveResponse(finalResponse, {
|
|
2674
|
+
toolName: "figma_get_file_for_plugin",
|
|
2675
|
+
compressionCallback: (adjustedLevel) => {
|
|
2676
|
+
// For plugin format, we can't reduce much without breaking functionality
|
|
2677
|
+
// But we can strip some less critical metadata
|
|
2678
|
+
const compressNode = (node) => {
|
|
2679
|
+
const result = {
|
|
2680
|
+
id: node.id,
|
|
2681
|
+
name: node.name,
|
|
2682
|
+
type: node.type,
|
|
2683
|
+
};
|
|
2684
|
+
// Keep only essential properties based on compression level
|
|
2685
|
+
if (adjustedLevel !== "inventory") {
|
|
2686
|
+
if (node.visible !== undefined)
|
|
2687
|
+
result.visible = node.visible;
|
|
2688
|
+
if (node.locked !== undefined)
|
|
2689
|
+
result.locked = node.locked;
|
|
2690
|
+
if (node.absoluteBoundingBox)
|
|
2691
|
+
result.absoluteBoundingBox = node.absoluteBoundingBox;
|
|
2692
|
+
if (node.pluginData)
|
|
2693
|
+
result.pluginData = node.pluginData;
|
|
2694
|
+
if (node.sharedPluginData)
|
|
2695
|
+
result.sharedPluginData = node.sharedPluginData;
|
|
2696
|
+
if (node.componentId)
|
|
2697
|
+
result.componentId = node.componentId;
|
|
2698
|
+
}
|
|
2699
|
+
if (node.children) {
|
|
2700
|
+
result.children = node.children.map(compressNode);
|
|
2701
|
+
}
|
|
2702
|
+
return result;
|
|
2703
|
+
};
|
|
2704
|
+
return {
|
|
2705
|
+
...finalResponse,
|
|
2706
|
+
document: compressNode(filteredDocument),
|
|
2707
|
+
metadata: {
|
|
2708
|
+
...finalResponse.metadata,
|
|
2709
|
+
compressionApplied: adjustedLevel,
|
|
2710
|
+
},
|
|
2711
|
+
};
|
|
2712
|
+
},
|
|
2713
|
+
suggestedActions: [
|
|
2714
|
+
"Reduce depth parameter (recommend 1-2)",
|
|
2715
|
+
"Request specific nodeIds to narrow the scope",
|
|
2716
|
+
"Filter to specific component types if possible",
|
|
2717
|
+
],
|
|
2718
|
+
});
|
|
2719
|
+
}
|
|
2720
|
+
catch (error) {
|
|
2721
|
+
logger.error({ error }, "Failed to get file for plugin");
|
|
2722
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2723
|
+
return {
|
|
2724
|
+
content: [
|
|
2725
|
+
{
|
|
2726
|
+
type: "text",
|
|
2727
|
+
text: JSON.stringify({
|
|
2728
|
+
error: errorMessage,
|
|
2729
|
+
message: "Failed to retrieve file data for plugin development",
|
|
2730
|
+
}),
|
|
2731
|
+
},
|
|
2732
|
+
],
|
|
2733
|
+
isError: true,
|
|
2734
|
+
};
|
|
2735
|
+
}
|
|
2736
|
+
});
|
|
2737
|
+
// Tool 15: Capture Screenshot via Plugin (Desktop Bridge)
|
|
2738
|
+
// This uses exportAsync() which reads the current plugin runtime state, not the cloud state
|
|
2739
|
+
// Solves race condition where REST API screenshots show stale data after changes
|
|
2740
|
+
server.tool("figma_capture_screenshot", "Capture a screenshot of a node using the plugin's exportAsync API. IMPORTANT: This tool captures the CURRENT state from the plugin runtime (not cloud state like REST API), making it reliable for validating changes immediately after making them. Use this instead of figma_get_component_image when you need to verify that changes were applied correctly. Requires Desktop Bridge connection (Figma Desktop with plugin running).", {
|
|
2741
|
+
nodeId: z
|
|
2742
|
+
.string()
|
|
2743
|
+
.optional()
|
|
2744
|
+
.describe("ID of the node to capture (e.g., '1:234'). If not provided, captures the current page."),
|
|
2745
|
+
format: z
|
|
2746
|
+
.enum(["PNG", "JPG", "SVG"])
|
|
2747
|
+
.optional()
|
|
2748
|
+
.default("PNG")
|
|
2749
|
+
.describe("Image format (default: PNG)"),
|
|
2750
|
+
scale: z
|
|
2751
|
+
.number()
|
|
2752
|
+
.min(0.5)
|
|
2753
|
+
.max(4)
|
|
2754
|
+
.optional()
|
|
2755
|
+
.default(2)
|
|
2756
|
+
.describe("Scale factor (default: 2 for 2x resolution)"),
|
|
2757
|
+
}, async ({ nodeId, format, scale }) => {
|
|
2758
|
+
try {
|
|
2759
|
+
logger.info({ nodeId, format, scale }, "Capturing screenshot via Desktop Bridge");
|
|
2760
|
+
let result = null;
|
|
2761
|
+
// Use the connector abstraction (WebSocket transport)
|
|
2762
|
+
if (getDesktopConnector) {
|
|
2763
|
+
const connector = await getDesktopConnector();
|
|
2764
|
+
logger.info({ transport: connector.getTransportType?.() || 'unknown' }, "Screenshot via connector");
|
|
2765
|
+
result = await connector.captureScreenshot(nodeId || '', { format, scale });
|
|
2766
|
+
// Wrap in expected format only if connector returns raw data without a success flag
|
|
2767
|
+
if (result && typeof result.success === 'undefined' && result.image) {
|
|
2768
|
+
result = { success: true, image: result };
|
|
2769
|
+
}
|
|
2770
|
+
}
|
|
2771
|
+
// Legacy CDP fallback (only when no connector factory is available)
|
|
2772
|
+
if (!result && !getDesktopConnector) {
|
|
2773
|
+
const browserManager = getBrowserManager?.();
|
|
2774
|
+
if (!browserManager) {
|
|
2775
|
+
throw new Error("Desktop Bridge not available. To capture screenshots:\n" +
|
|
2776
|
+
"1. Open your Figma file in Figma Desktop\n" +
|
|
2777
|
+
"2. Install and run the 'Figma Console MCP' plugin\n" +
|
|
2778
|
+
"3. Ensure the plugin shows 'MCP ready' status");
|
|
2779
|
+
}
|
|
2780
|
+
if (ensureInitialized) {
|
|
2781
|
+
await ensureInitialized();
|
|
2782
|
+
}
|
|
2783
|
+
const page = await browserManager.getPage();
|
|
2784
|
+
const frames = page.frames();
|
|
2785
|
+
for (const frame of frames) {
|
|
2786
|
+
try {
|
|
2787
|
+
const hasFunction = await frame.evaluate('typeof window.captureScreenshot === "function"');
|
|
2788
|
+
if (hasFunction) {
|
|
2789
|
+
result = await frame.evaluate(`window.captureScreenshot(${JSON.stringify(nodeId || '')}, ${JSON.stringify({ format, scale })})`);
|
|
2790
|
+
break;
|
|
2791
|
+
}
|
|
2792
|
+
}
|
|
2793
|
+
catch {
|
|
2794
|
+
continue;
|
|
2795
|
+
}
|
|
2796
|
+
}
|
|
2797
|
+
}
|
|
2798
|
+
if (!result) {
|
|
2799
|
+
throw new Error("Desktop Bridge plugin not found. Ensure the 'Figma Console MCP' plugin is running in Figma Desktop.");
|
|
2800
|
+
}
|
|
2801
|
+
if (!result.success) {
|
|
2802
|
+
throw new Error(result.error || "Screenshot capture failed");
|
|
2803
|
+
}
|
|
2804
|
+
// Determine MIME type based on format
|
|
2805
|
+
const mimeType = format === "JPG" ? "image/jpeg" : format === "SVG" ? "image/svg+xml" : "image/png";
|
|
2806
|
+
logger.info({ byteLength: result.image.byteLength, format, mimeType }, "Screenshot captured via plugin");
|
|
2807
|
+
// Return as MCP image content type so Claude can actually see and analyze the image
|
|
2808
|
+
return {
|
|
2809
|
+
content: [
|
|
2810
|
+
{
|
|
2811
|
+
type: "text",
|
|
2812
|
+
text: JSON.stringify({
|
|
2813
|
+
success: true,
|
|
2814
|
+
image: {
|
|
2815
|
+
format: result.image.format,
|
|
2816
|
+
scale: result.image.scale,
|
|
2817
|
+
byteLength: result.image.byteLength,
|
|
2818
|
+
node: result.image.node,
|
|
2819
|
+
bounds: result.image.bounds,
|
|
2820
|
+
},
|
|
2821
|
+
metadata: {
|
|
2822
|
+
source: "plugin_export_async",
|
|
2823
|
+
note: "Screenshot captured successfully. The image is included below for visual analysis. This shows the CURRENT plugin runtime state (guaranteed to reflect recent changes).",
|
|
2824
|
+
},
|
|
2825
|
+
}),
|
|
2826
|
+
},
|
|
2827
|
+
{
|
|
2828
|
+
type: "image",
|
|
2829
|
+
data: result.image.base64,
|
|
2830
|
+
mimeType: mimeType,
|
|
2831
|
+
},
|
|
2832
|
+
],
|
|
2833
|
+
};
|
|
2834
|
+
}
|
|
2835
|
+
catch (error) {
|
|
2836
|
+
logger.error({ error }, "Failed to capture screenshot");
|
|
2837
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2838
|
+
return {
|
|
2839
|
+
content: [
|
|
2840
|
+
{
|
|
2841
|
+
type: "text",
|
|
2842
|
+
text: JSON.stringify({
|
|
2843
|
+
error: errorMessage,
|
|
2844
|
+
message: "Failed to capture screenshot via Desktop Bridge",
|
|
2845
|
+
suggestion: "Ensure Figma Desktop is open with the plugin running",
|
|
2846
|
+
}),
|
|
2847
|
+
},
|
|
2848
|
+
],
|
|
2849
|
+
isError: true,
|
|
2850
|
+
};
|
|
2851
|
+
}
|
|
2852
|
+
});
|
|
2853
|
+
// Tool 16: Set Instance Properties (Desktop Bridge)
|
|
2854
|
+
// Updates component properties on an instance using setProperties()
|
|
2855
|
+
// This is the correct way to update TEXT/BOOLEAN/VARIANT properties on component instances
|
|
2856
|
+
server.tool("figma_set_instance_properties", "Update component properties on a component instance. IMPORTANT: Use this tool instead of trying to edit text nodes directly when working with component instances. Components often expose TEXT, BOOLEAN, INSTANCE_SWAP, and VARIANT properties that control their content. Direct text node editing may fail silently if the component uses properties. This tool handles the #nodeId suffix pattern automatically. Requires Desktop Bridge connection.", {
|
|
2857
|
+
nodeId: z
|
|
2858
|
+
.string()
|
|
2859
|
+
.describe("ID of the INSTANCE node to update (e.g., '1:234'). Must be a component instance, not a regular frame."),
|
|
2860
|
+
properties: z
|
|
2861
|
+
.record(z.string(), z.union([z.string(), z.boolean()]))
|
|
2862
|
+
.describe("Properties to set. Keys are property names (e.g., 'Label', 'Show Icon', 'Size'). " +
|
|
2863
|
+
"Values are strings for TEXT/VARIANT properties, booleans for BOOLEAN properties. " +
|
|
2864
|
+
"The tool automatically handles the #nodeId suffix for TEXT/BOOLEAN/INSTANCE_SWAP properties."),
|
|
2865
|
+
}, async ({ nodeId, properties }) => {
|
|
2866
|
+
try {
|
|
2867
|
+
logger.info({ nodeId, properties: Object.keys(properties) }, "Setting instance properties via Desktop Bridge");
|
|
2868
|
+
let result = null;
|
|
2869
|
+
// Use the connector abstraction (WebSocket transport)
|
|
2870
|
+
if (getDesktopConnector) {
|
|
2871
|
+
const connector = await getDesktopConnector();
|
|
2872
|
+
logger.info({ transport: connector.getTransportType?.() || 'unknown' }, "Instance properties via connector");
|
|
2873
|
+
result = await connector.setInstanceProperties(nodeId, properties);
|
|
2874
|
+
}
|
|
2875
|
+
// Legacy CDP fallback (only when no connector factory is available)
|
|
2876
|
+
if (!result && !getDesktopConnector) {
|
|
2877
|
+
const browserManager = getBrowserManager?.();
|
|
2878
|
+
if (!browserManager) {
|
|
2879
|
+
throw new Error("Desktop Bridge not available. To set instance properties:\n" +
|
|
2880
|
+
"1. Open your Figma file in Figma Desktop\n" +
|
|
2881
|
+
"2. Install and run the 'Figma Console MCP' plugin\n" +
|
|
2882
|
+
"3. Ensure the plugin shows 'MCP ready' status");
|
|
2883
|
+
}
|
|
2884
|
+
if (ensureInitialized) {
|
|
2885
|
+
await ensureInitialized();
|
|
2886
|
+
}
|
|
2887
|
+
const page = await browserManager.getPage();
|
|
2888
|
+
const frames = page.frames();
|
|
2889
|
+
for (const frame of frames) {
|
|
2890
|
+
try {
|
|
2891
|
+
const hasFunction = await frame.evaluate('typeof window.setInstanceProperties === "function"');
|
|
2892
|
+
if (hasFunction) {
|
|
2893
|
+
result = await frame.evaluate(`window.setInstanceProperties(${JSON.stringify(nodeId)}, ${JSON.stringify(properties)})`);
|
|
2894
|
+
break;
|
|
2895
|
+
}
|
|
2896
|
+
}
|
|
2897
|
+
catch {
|
|
2898
|
+
continue;
|
|
2899
|
+
}
|
|
2900
|
+
}
|
|
2901
|
+
}
|
|
2902
|
+
if (!result) {
|
|
2903
|
+
throw new Error("Desktop Bridge plugin not found. Ensure the 'Figma Console MCP' plugin is running in Figma Desktop.");
|
|
2904
|
+
}
|
|
2905
|
+
if (!result.success) {
|
|
2906
|
+
throw new Error(result.error || "Failed to set instance properties");
|
|
2907
|
+
}
|
|
2908
|
+
return {
|
|
2909
|
+
content: [
|
|
2910
|
+
{
|
|
2911
|
+
type: "text",
|
|
2912
|
+
text: JSON.stringify({
|
|
2913
|
+
success: true,
|
|
2914
|
+
instance: result.instance,
|
|
2915
|
+
metadata: {
|
|
2916
|
+
note: "Instance properties updated successfully. Use figma_capture_screenshot to verify visual changes.",
|
|
2917
|
+
},
|
|
2918
|
+
}),
|
|
2919
|
+
},
|
|
2920
|
+
],
|
|
2921
|
+
};
|
|
2922
|
+
}
|
|
2923
|
+
catch (error) {
|
|
2924
|
+
logger.error({ error }, "Failed to set instance properties");
|
|
2925
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2926
|
+
return {
|
|
2927
|
+
content: [
|
|
2928
|
+
{
|
|
2929
|
+
type: "text",
|
|
2930
|
+
text: JSON.stringify({
|
|
2931
|
+
error: errorMessage,
|
|
2932
|
+
message: "Failed to set instance properties via Desktop Bridge",
|
|
2933
|
+
suggestions: [
|
|
2934
|
+
"Verify the node is a component INSTANCE (not a regular frame)",
|
|
2935
|
+
"Check available properties with figma_get_component first",
|
|
2936
|
+
"Ensure property names match exactly (case-sensitive)",
|
|
2937
|
+
"For TEXT properties, provide string values",
|
|
2938
|
+
"For BOOLEAN properties, provide true/false",
|
|
2939
|
+
],
|
|
2940
|
+
}),
|
|
2941
|
+
},
|
|
2942
|
+
],
|
|
2943
|
+
isError: true,
|
|
2944
|
+
};
|
|
2945
|
+
}
|
|
2946
|
+
});
|
|
2947
|
+
}
|