figma-console-mcp 1.7.0 → 1.8.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/README.md +33 -5
- package/dist/cloudflare/core/design-code-tools.js +2 -2
- package/dist/cloudflare/core/figma-connector.js +8 -0
- package/dist/cloudflare/core/figma-desktop-connector.js +69 -2
- package/dist/cloudflare/core/figma-tools.js +118 -98
- package/dist/cloudflare/core/websocket-connector.js +235 -0
- package/dist/cloudflare/core/websocket-server.js +603 -0
- package/dist/cloudflare/index.js +5 -5
- package/dist/core/design-code-tools.js +2 -2
- package/dist/core/design-code-tools.js.map +1 -1
- package/dist/core/figma-connector.d.ts +47 -0
- package/dist/core/figma-connector.d.ts.map +1 -0
- package/dist/core/figma-connector.js +9 -0
- package/dist/core/figma-connector.js.map +1 -0
- package/dist/core/figma-desktop-connector.d.ts +14 -1
- package/dist/core/figma-desktop-connector.d.ts.map +1 -1
- package/dist/core/figma-desktop-connector.js +69 -2
- package/dist/core/figma-desktop-connector.js.map +1 -1
- package/dist/core/figma-tools.d.ts +1 -1
- package/dist/core/figma-tools.d.ts.map +1 -1
- package/dist/core/figma-tools.js +118 -98
- package/dist/core/figma-tools.js.map +1 -1
- package/dist/core/websocket-connector.d.ts +53 -0
- package/dist/core/websocket-connector.d.ts.map +1 -0
- package/dist/core/websocket-connector.js +236 -0
- package/dist/core/websocket-connector.js.map +1 -0
- package/dist/core/websocket-server.d.ts +183 -0
- package/dist/core/websocket-server.d.ts.map +1 -0
- package/dist/core/websocket-server.js +604 -0
- package/dist/core/websocket-server.js.map +1 -0
- package/dist/local.d.ts +10 -3
- package/dist/local.d.ts.map +1 -1
- package/dist/local.js +820 -274
- package/dist/local.js.map +1 -1
- package/figma-desktop-bridge/README.md +30 -16
- package/figma-desktop-bridge/code.js +195 -3
- package/figma-desktop-bridge/manifest.json +4 -1
- package/figma-desktop-bridge/ui.html +229 -0
- package/package.json +6 -4
|
@@ -0,0 +1,603 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WebSocket Bridge Server (Multi-Client)
|
|
3
|
+
*
|
|
4
|
+
* Creates a WebSocket server that multiple Desktop Bridge plugin instances connect to.
|
|
5
|
+
* Each instance represents a different Figma file and is identified by its fileKey
|
|
6
|
+
* (sent via FILE_INFO on connection). Per-file state (selection, document changes,
|
|
7
|
+
* console logs) is maintained independently.
|
|
8
|
+
*
|
|
9
|
+
* Active file tracking: The "active" file is automatically switched when the user
|
|
10
|
+
* interacts with a file (selection/page changes) or can be set explicitly via
|
|
11
|
+
* setActiveFile(). All backward-compatible getters return data from the active file.
|
|
12
|
+
*
|
|
13
|
+
* Data flow: MCP Server ←WebSocket→ ui.html ←postMessage→ code.js ←figma.*→ Figma
|
|
14
|
+
*/
|
|
15
|
+
import { WebSocketServer as WSServer, WebSocket } from 'ws';
|
|
16
|
+
import { EventEmitter } from 'events';
|
|
17
|
+
import { createChildLogger } from './logger.js';
|
|
18
|
+
const logger = createChildLogger({ component: 'websocket-server' });
|
|
19
|
+
export class FigmaWebSocketServer extends EventEmitter {
|
|
20
|
+
constructor(options) {
|
|
21
|
+
super();
|
|
22
|
+
this.wss = null;
|
|
23
|
+
/** Named clients indexed by fileKey — each represents a connected Figma file */
|
|
24
|
+
this.clients = new Map();
|
|
25
|
+
/** Clients awaiting FILE_INFO identification, mapped to their pending timeout */
|
|
26
|
+
this._pendingClients = new Map();
|
|
27
|
+
/** The fileKey of the currently active (targeted) file */
|
|
28
|
+
this._activeFileKey = null;
|
|
29
|
+
this.pendingRequests = new Map();
|
|
30
|
+
this.requestIdCounter = 0;
|
|
31
|
+
this._isStarted = false;
|
|
32
|
+
this.consoleBufferSize = 1000;
|
|
33
|
+
this.documentChangeBufferSize = 200;
|
|
34
|
+
this.options = options;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Start the WebSocket server
|
|
38
|
+
*/
|
|
39
|
+
async start() {
|
|
40
|
+
if (this._isStarted)
|
|
41
|
+
return;
|
|
42
|
+
return new Promise((resolve, reject) => {
|
|
43
|
+
try {
|
|
44
|
+
this.wss = new WSServer({
|
|
45
|
+
port: this.options.port,
|
|
46
|
+
host: this.options.host || 'localhost',
|
|
47
|
+
maxPayload: 100 * 1024 * 1024, // 100MB — screenshots and large component data can be big
|
|
48
|
+
verifyClient: (info, callback) => {
|
|
49
|
+
// Mitigate Cross-Site WebSocket Hijacking (CSWSH):
|
|
50
|
+
// Reject connections from unexpected browser origins.
|
|
51
|
+
const origin = info.origin;
|
|
52
|
+
const allowed = !origin || // No origin — local process (e.g. Node.js client)
|
|
53
|
+
origin === 'null' || // Sandboxed iframe / Figma Desktop plugin UI
|
|
54
|
+
origin.startsWith('https://www.figma.com') ||
|
|
55
|
+
origin.startsWith('https://figma.com');
|
|
56
|
+
if (allowed) {
|
|
57
|
+
callback(true);
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
logger.warn({ origin }, 'Rejected WebSocket connection from unauthorized origin');
|
|
61
|
+
callback(false, 403, 'Unauthorized Origin');
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
});
|
|
65
|
+
this.wss.on('listening', () => {
|
|
66
|
+
this._isStarted = true;
|
|
67
|
+
logger.info({ port: this.options.port, host: this.options.host || 'localhost' }, 'WebSocket bridge server started');
|
|
68
|
+
resolve();
|
|
69
|
+
});
|
|
70
|
+
this.wss.on('error', (error) => {
|
|
71
|
+
if (!this._isStarted) {
|
|
72
|
+
reject(error);
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
logger.error({ error }, 'WebSocket server error');
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
this.wss.on('connection', (ws) => {
|
|
79
|
+
// Add to pending until FILE_INFO identifies the file
|
|
80
|
+
const pendingTimeout = setTimeout(() => {
|
|
81
|
+
if (this._pendingClients.has(ws)) {
|
|
82
|
+
this._pendingClients.delete(ws);
|
|
83
|
+
logger.warn('Pending WebSocket client timed out without sending FILE_INFO');
|
|
84
|
+
ws.close(1000, 'File identification timeout');
|
|
85
|
+
}
|
|
86
|
+
}, 30000);
|
|
87
|
+
this._pendingClients.set(ws, pendingTimeout);
|
|
88
|
+
logger.info({ totalClients: this.clients.size, pendingClients: this._pendingClients.size }, 'New WebSocket connection (pending file identification)');
|
|
89
|
+
ws.on('message', (data) => {
|
|
90
|
+
try {
|
|
91
|
+
let text;
|
|
92
|
+
if (typeof data === 'string') {
|
|
93
|
+
text = data;
|
|
94
|
+
}
|
|
95
|
+
else if (Buffer.isBuffer(data)) {
|
|
96
|
+
text = data.toString();
|
|
97
|
+
}
|
|
98
|
+
else if (Array.isArray(data)) {
|
|
99
|
+
text = Buffer.concat(data).toString();
|
|
100
|
+
}
|
|
101
|
+
else {
|
|
102
|
+
text = Buffer.from(data).toString();
|
|
103
|
+
}
|
|
104
|
+
const message = JSON.parse(text);
|
|
105
|
+
this.handleMessage(message, ws);
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
logger.error({ error }, 'Failed to parse WebSocket message');
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
ws.on('close', (code, reason) => {
|
|
112
|
+
this.handleClientDisconnect(ws, code, reason.toString());
|
|
113
|
+
});
|
|
114
|
+
ws.on('error', (error) => {
|
|
115
|
+
logger.error({ error }, 'WebSocket client error');
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
reject(error);
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Find a named client connection by its WebSocket reference
|
|
126
|
+
*/
|
|
127
|
+
findClientByWs(ws) {
|
|
128
|
+
for (const [fileKey, client] of this.clients) {
|
|
129
|
+
if (client.ws === ws)
|
|
130
|
+
return { fileKey, client };
|
|
131
|
+
}
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Handle incoming message from a plugin UI WebSocket connection
|
|
136
|
+
*/
|
|
137
|
+
handleMessage(message, ws) {
|
|
138
|
+
// Response to a command we sent
|
|
139
|
+
if (message.id && this.pendingRequests.has(message.id)) {
|
|
140
|
+
const pending = this.pendingRequests.get(message.id);
|
|
141
|
+
clearTimeout(pending.timeoutId);
|
|
142
|
+
this.pendingRequests.delete(message.id);
|
|
143
|
+
if (message.error) {
|
|
144
|
+
pending.reject(new Error(message.error));
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
pending.resolve(message.result);
|
|
148
|
+
}
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
// Unsolicited data from plugin (FILE_INFO, events, forwarded data)
|
|
152
|
+
if (message.type) {
|
|
153
|
+
// FILE_INFO promotes pending clients to named clients
|
|
154
|
+
if (message.type === 'FILE_INFO' && message.data) {
|
|
155
|
+
this.handleFileInfo(message.data, ws);
|
|
156
|
+
}
|
|
157
|
+
// Buffer document changes for the specific file
|
|
158
|
+
if (message.type === 'DOCUMENT_CHANGE' && message.data) {
|
|
159
|
+
const found = this.findClientByWs(ws);
|
|
160
|
+
if (found) {
|
|
161
|
+
const entry = {
|
|
162
|
+
hasStyleChanges: message.data.hasStyleChanges,
|
|
163
|
+
hasNodeChanges: message.data.hasNodeChanges,
|
|
164
|
+
changedNodeIds: message.data.changedNodeIds || [],
|
|
165
|
+
changeCount: message.data.changeCount || 0,
|
|
166
|
+
timestamp: message.data.timestamp || Date.now(),
|
|
167
|
+
};
|
|
168
|
+
found.client.documentChanges.push(entry);
|
|
169
|
+
if (found.client.documentChanges.length > this.documentChangeBufferSize) {
|
|
170
|
+
found.client.documentChanges.shift();
|
|
171
|
+
}
|
|
172
|
+
found.client.lastActivity = Date.now();
|
|
173
|
+
}
|
|
174
|
+
this.emit('documentChange', { fileKey: found?.fileKey ?? null, ...message.data });
|
|
175
|
+
}
|
|
176
|
+
// Track selection changes — user interaction makes this the active file
|
|
177
|
+
if (message.type === 'SELECTION_CHANGE' && message.data) {
|
|
178
|
+
const found = this.findClientByWs(ws);
|
|
179
|
+
if (found) {
|
|
180
|
+
found.client.selection = message.data;
|
|
181
|
+
found.client.lastActivity = Date.now();
|
|
182
|
+
this._activeFileKey = found.fileKey;
|
|
183
|
+
}
|
|
184
|
+
this.emit('selectionChange', { fileKey: found?.fileKey ?? null, ...message.data });
|
|
185
|
+
}
|
|
186
|
+
// Track page changes — user interaction makes this the active file
|
|
187
|
+
if (message.type === 'PAGE_CHANGE' && message.data) {
|
|
188
|
+
const found = this.findClientByWs(ws);
|
|
189
|
+
if (found) {
|
|
190
|
+
found.client.fileInfo.currentPage = message.data.pageName;
|
|
191
|
+
found.client.lastActivity = Date.now();
|
|
192
|
+
this._activeFileKey = found.fileKey;
|
|
193
|
+
}
|
|
194
|
+
this.emit('pageChange', { fileKey: found?.fileKey ?? null, ...message.data });
|
|
195
|
+
}
|
|
196
|
+
// Capture console logs for the specific file
|
|
197
|
+
if (message.type === 'CONSOLE_CAPTURE' && message.data) {
|
|
198
|
+
const found = this.findClientByWs(ws);
|
|
199
|
+
const data = message.data;
|
|
200
|
+
const entry = {
|
|
201
|
+
timestamp: data.timestamp || Date.now(),
|
|
202
|
+
level: data.level || 'log',
|
|
203
|
+
message: typeof data.message === 'string' ? data.message.substring(0, 1000) : String(data.message),
|
|
204
|
+
args: Array.isArray(data.args) ? data.args.slice(0, 10) : [],
|
|
205
|
+
source: 'plugin',
|
|
206
|
+
};
|
|
207
|
+
if (found) {
|
|
208
|
+
found.client.consoleLogs.push(entry);
|
|
209
|
+
if (found.client.consoleLogs.length > this.consoleBufferSize) {
|
|
210
|
+
found.client.consoleLogs.shift();
|
|
211
|
+
}
|
|
212
|
+
found.client.lastActivity = Date.now();
|
|
213
|
+
}
|
|
214
|
+
this.emit('consoleLog', entry);
|
|
215
|
+
}
|
|
216
|
+
this.emit('pluginMessage', message);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
logger.debug({ message }, 'Unhandled WebSocket message');
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Handle FILE_INFO message — promotes pending clients to named clients.
|
|
223
|
+
* This is the critical multi-client identification step: each plugin reports
|
|
224
|
+
* its fileKey on connect, allowing the server to track multiple files.
|
|
225
|
+
*/
|
|
226
|
+
handleFileInfo(data, ws) {
|
|
227
|
+
const fileKey = data.fileKey || null;
|
|
228
|
+
if (!fileKey) {
|
|
229
|
+
logger.warn('FILE_INFO received without fileKey — client remains pending');
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
// Remove from pending clients (cancel identification timeout)
|
|
233
|
+
const pendingTimeout = this._pendingClients.get(ws);
|
|
234
|
+
if (pendingTimeout) {
|
|
235
|
+
clearTimeout(pendingTimeout);
|
|
236
|
+
this._pendingClients.delete(ws);
|
|
237
|
+
}
|
|
238
|
+
// Check if this ws was already registered under a different fileKey
|
|
239
|
+
// (shouldn't happen in practice — each plugin instance is per-file)
|
|
240
|
+
const previousEntry = this.findClientByWs(ws);
|
|
241
|
+
if (previousEntry && previousEntry.fileKey !== fileKey) {
|
|
242
|
+
this.clients.delete(previousEntry.fileKey);
|
|
243
|
+
if (this._activeFileKey === previousEntry.fileKey) {
|
|
244
|
+
this._activeFileKey = null;
|
|
245
|
+
}
|
|
246
|
+
logger.info({ oldFileKey: previousEntry.fileKey, newFileKey: fileKey }, 'WebSocket client switched files');
|
|
247
|
+
}
|
|
248
|
+
// If same fileKey already connected with a DIFFERENT ws, clean up old connection
|
|
249
|
+
const existing = this.clients.get(fileKey);
|
|
250
|
+
if (existing && existing.ws !== ws) {
|
|
251
|
+
logger.info({ fileKey }, 'Replacing existing connection for same file');
|
|
252
|
+
if (existing.gracePeriodTimer) {
|
|
253
|
+
clearTimeout(existing.gracePeriodTimer);
|
|
254
|
+
}
|
|
255
|
+
// Reject any in-flight commands before replacing — the old ws close event
|
|
256
|
+
// won't find this fileKey in the map after overwrite, so pending requests
|
|
257
|
+
// would hang until timeout otherwise.
|
|
258
|
+
this.rejectPendingRequestsForFile(fileKey, 'Connection replaced by same file reconnection');
|
|
259
|
+
if (existing.ws.readyState === WebSocket.OPEN || existing.ws.readyState === WebSocket.CONNECTING) {
|
|
260
|
+
existing.ws.close(1000, 'Replaced by same file reconnection');
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
// Create client connection (preserve per-file state from previous connection of same file)
|
|
264
|
+
this.clients.set(fileKey, {
|
|
265
|
+
ws,
|
|
266
|
+
fileInfo: {
|
|
267
|
+
fileName: data.fileName,
|
|
268
|
+
fileKey,
|
|
269
|
+
currentPage: data.currentPage,
|
|
270
|
+
connectedAt: Date.now(),
|
|
271
|
+
},
|
|
272
|
+
selection: existing?.selection || null,
|
|
273
|
+
documentChanges: existing?.documentChanges || [],
|
|
274
|
+
consoleLogs: existing?.consoleLogs || [],
|
|
275
|
+
lastActivity: Date.now(),
|
|
276
|
+
gracePeriodTimer: null,
|
|
277
|
+
});
|
|
278
|
+
// Set as active file if no active file or active file is disconnected
|
|
279
|
+
if (!this._activeFileKey || !this.clients.has(this._activeFileKey) ||
|
|
280
|
+
this.clients.get(this._activeFileKey)?.ws.readyState !== WebSocket.OPEN) {
|
|
281
|
+
this._activeFileKey = fileKey;
|
|
282
|
+
}
|
|
283
|
+
logger.info({
|
|
284
|
+
fileName: data.fileName,
|
|
285
|
+
fileKey,
|
|
286
|
+
totalClients: this.clients.size,
|
|
287
|
+
isActive: this._activeFileKey === fileKey,
|
|
288
|
+
}, 'File connected via WebSocket');
|
|
289
|
+
// Emit both events for backward compat and new features
|
|
290
|
+
this.emit('connected');
|
|
291
|
+
this.emit('fileConnected', { fileKey, fileName: data.fileName });
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Handle a client WebSocket disconnecting.
|
|
295
|
+
* Starts a grace period before removing the client to allow reconnection.
|
|
296
|
+
*/
|
|
297
|
+
handleClientDisconnect(ws, code, reason) {
|
|
298
|
+
// Check if it was a pending client (never identified itself)
|
|
299
|
+
const pendingTimeout = this._pendingClients.get(ws);
|
|
300
|
+
if (pendingTimeout) {
|
|
301
|
+
clearTimeout(pendingTimeout);
|
|
302
|
+
this._pendingClients.delete(ws);
|
|
303
|
+
logger.info('Pending WebSocket client disconnected before file identification');
|
|
304
|
+
this.emit('disconnected');
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
// Find which named client this belongs to
|
|
308
|
+
const found = this.findClientByWs(ws);
|
|
309
|
+
if (!found) {
|
|
310
|
+
logger.debug('Unknown WebSocket client disconnected');
|
|
311
|
+
this.emit('disconnected');
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
const { fileKey, client } = found;
|
|
315
|
+
logger.info({ fileKey, fileName: client.fileInfo.fileName, code, reason }, 'File disconnected from WebSocket');
|
|
316
|
+
// Start grace period — keep state but clean up if not reconnected
|
|
317
|
+
client.gracePeriodTimer = setTimeout(() => {
|
|
318
|
+
client.gracePeriodTimer = null;
|
|
319
|
+
// Only remove if the client in the map is still the disconnected one
|
|
320
|
+
const current = this.clients.get(fileKey);
|
|
321
|
+
if (current && current.ws === ws) {
|
|
322
|
+
this.clients.delete(fileKey);
|
|
323
|
+
this.rejectPendingRequestsForFile(fileKey, 'WebSocket client disconnected');
|
|
324
|
+
// If active file disconnected, switch to another connected file
|
|
325
|
+
if (this._activeFileKey === fileKey) {
|
|
326
|
+
this._activeFileKey = null;
|
|
327
|
+
for (const [fk, c] of this.clients) {
|
|
328
|
+
if (c.ws.readyState === WebSocket.OPEN) {
|
|
329
|
+
this._activeFileKey = fk;
|
|
330
|
+
break;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
this.emit('fileDisconnected', { fileKey, fileName: client.fileInfo.fileName });
|
|
335
|
+
}
|
|
336
|
+
}, 5000);
|
|
337
|
+
this.emit('disconnected');
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Send a command to a plugin UI and wait for the response.
|
|
341
|
+
* By default targets the active file. Pass targetFileKey to target a specific file.
|
|
342
|
+
*/
|
|
343
|
+
sendCommand(method, params = {}, timeoutMs = 15000, targetFileKey) {
|
|
344
|
+
return new Promise((resolve, reject) => {
|
|
345
|
+
const fileKey = targetFileKey || this._activeFileKey;
|
|
346
|
+
if (!fileKey) {
|
|
347
|
+
reject(new Error('No active file connected. Make sure the Desktop Bridge plugin is open in Figma.'));
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
const client = this.clients.get(fileKey);
|
|
351
|
+
if (!client || client.ws.readyState !== WebSocket.OPEN) {
|
|
352
|
+
reject(new Error('No WebSocket client connected. Make sure the Desktop Bridge plugin is open in Figma.'));
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
const id = `ws_${++this.requestIdCounter}_${Date.now()}`;
|
|
356
|
+
const timeoutId = setTimeout(() => {
|
|
357
|
+
if (this.pendingRequests.has(id)) {
|
|
358
|
+
this.pendingRequests.delete(id);
|
|
359
|
+
reject(new Error(`WebSocket command ${method} timed out after ${timeoutMs}ms`));
|
|
360
|
+
}
|
|
361
|
+
}, timeoutMs);
|
|
362
|
+
this.pendingRequests.set(id, {
|
|
363
|
+
resolve,
|
|
364
|
+
reject,
|
|
365
|
+
method,
|
|
366
|
+
timeoutId,
|
|
367
|
+
createdAt: Date.now(),
|
|
368
|
+
targetFileKey: fileKey,
|
|
369
|
+
});
|
|
370
|
+
const message = JSON.stringify({ id, method, params });
|
|
371
|
+
try {
|
|
372
|
+
client.ws.send(message);
|
|
373
|
+
}
|
|
374
|
+
catch (sendError) {
|
|
375
|
+
this.pendingRequests.delete(id);
|
|
376
|
+
clearTimeout(timeoutId);
|
|
377
|
+
reject(new Error(`Failed to send WebSocket command ${method}: ${sendError instanceof Error ? sendError.message : String(sendError)}`));
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
client.lastActivity = Date.now();
|
|
381
|
+
logger.debug({ id, method, fileKey }, 'Sent WebSocket command');
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Check if any named client is connected (transport availability check)
|
|
386
|
+
*/
|
|
387
|
+
isClientConnected() {
|
|
388
|
+
for (const [, client] of this.clients) {
|
|
389
|
+
if (client.ws.readyState === WebSocket.OPEN) {
|
|
390
|
+
return true;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return false;
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* Whether the server has been started
|
|
397
|
+
*/
|
|
398
|
+
isStarted() {
|
|
399
|
+
return this._isStarted;
|
|
400
|
+
}
|
|
401
|
+
// ============================================================================
|
|
402
|
+
// Active file getters (backward compatible — return active file's state)
|
|
403
|
+
// ============================================================================
|
|
404
|
+
/**
|
|
405
|
+
* Get info about the currently active Figma file.
|
|
406
|
+
* Returns null if no file is active or connected.
|
|
407
|
+
*/
|
|
408
|
+
getConnectedFileInfo() {
|
|
409
|
+
if (!this._activeFileKey)
|
|
410
|
+
return null;
|
|
411
|
+
const client = this.clients.get(this._activeFileKey);
|
|
412
|
+
return client?.fileInfo || null;
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Get the current user selection in the active Figma file
|
|
416
|
+
*/
|
|
417
|
+
getCurrentSelection() {
|
|
418
|
+
if (!this._activeFileKey)
|
|
419
|
+
return null;
|
|
420
|
+
const client = this.clients.get(this._activeFileKey);
|
|
421
|
+
return client?.selection || null;
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Get buffered document change events from the active file
|
|
425
|
+
*/
|
|
426
|
+
getDocumentChanges(options) {
|
|
427
|
+
if (!this._activeFileKey)
|
|
428
|
+
return [];
|
|
429
|
+
const client = this.clients.get(this._activeFileKey);
|
|
430
|
+
if (!client)
|
|
431
|
+
return [];
|
|
432
|
+
let filtered = [...client.documentChanges];
|
|
433
|
+
if (options?.since !== undefined) {
|
|
434
|
+
filtered = filtered.filter((e) => e.timestamp >= options.since);
|
|
435
|
+
}
|
|
436
|
+
if (options?.count !== undefined && options.count > 0) {
|
|
437
|
+
filtered = filtered.slice(-options.count);
|
|
438
|
+
}
|
|
439
|
+
return filtered;
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Clear document change buffer for the active file
|
|
443
|
+
*/
|
|
444
|
+
clearDocumentChanges() {
|
|
445
|
+
if (!this._activeFileKey)
|
|
446
|
+
return 0;
|
|
447
|
+
const client = this.clients.get(this._activeFileKey);
|
|
448
|
+
if (!client)
|
|
449
|
+
return 0;
|
|
450
|
+
const count = client.documentChanges.length;
|
|
451
|
+
client.documentChanges = [];
|
|
452
|
+
return count;
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Get console logs from the active file with optional filtering
|
|
456
|
+
*/
|
|
457
|
+
getConsoleLogs(options) {
|
|
458
|
+
if (!this._activeFileKey)
|
|
459
|
+
return [];
|
|
460
|
+
const client = this.clients.get(this._activeFileKey);
|
|
461
|
+
if (!client)
|
|
462
|
+
return [];
|
|
463
|
+
let filtered = [...client.consoleLogs];
|
|
464
|
+
if (options?.since !== undefined) {
|
|
465
|
+
filtered = filtered.filter((log) => log.timestamp >= options.since);
|
|
466
|
+
}
|
|
467
|
+
if (options?.level && options.level !== 'all') {
|
|
468
|
+
filtered = filtered.filter((log) => log.level === options.level);
|
|
469
|
+
}
|
|
470
|
+
if (options?.count !== undefined && options.count > 0) {
|
|
471
|
+
filtered = filtered.slice(-options.count);
|
|
472
|
+
}
|
|
473
|
+
return filtered;
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* Clear console log buffer for the active file
|
|
477
|
+
*/
|
|
478
|
+
clearConsoleLogs() {
|
|
479
|
+
if (!this._activeFileKey)
|
|
480
|
+
return 0;
|
|
481
|
+
const client = this.clients.get(this._activeFileKey);
|
|
482
|
+
if (!client)
|
|
483
|
+
return 0;
|
|
484
|
+
const count = client.consoleLogs.length;
|
|
485
|
+
client.consoleLogs = [];
|
|
486
|
+
return count;
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Get console monitoring status for the active file
|
|
490
|
+
*/
|
|
491
|
+
getConsoleStatus() {
|
|
492
|
+
const client = this._activeFileKey ? this.clients.get(this._activeFileKey) : null;
|
|
493
|
+
const logs = client?.consoleLogs || [];
|
|
494
|
+
return {
|
|
495
|
+
isMonitoring: !!(client && client.ws.readyState === WebSocket.OPEN),
|
|
496
|
+
anyClientConnected: this.isClientConnected(),
|
|
497
|
+
logCount: logs.length,
|
|
498
|
+
bufferSize: this.consoleBufferSize,
|
|
499
|
+
workerCount: 0,
|
|
500
|
+
oldestTimestamp: logs[0]?.timestamp,
|
|
501
|
+
newestTimestamp: logs[logs.length - 1]?.timestamp,
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
// ============================================================================
|
|
505
|
+
// Multi-client methods
|
|
506
|
+
// ============================================================================
|
|
507
|
+
/**
|
|
508
|
+
* Get info about all connected Figma files.
|
|
509
|
+
* Returns an array of ConnectedFileInfo for each file with an active WebSocket.
|
|
510
|
+
*/
|
|
511
|
+
getConnectedFiles() {
|
|
512
|
+
const files = [];
|
|
513
|
+
for (const [fileKey, client] of this.clients) {
|
|
514
|
+
if (client.ws.readyState === WebSocket.OPEN) {
|
|
515
|
+
files.push({
|
|
516
|
+
...client.fileInfo,
|
|
517
|
+
isActive: fileKey === this._activeFileKey,
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
return files;
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Set the active file by fileKey. Returns true if the file is connected.
|
|
525
|
+
*/
|
|
526
|
+
setActiveFile(fileKey) {
|
|
527
|
+
const client = this.clients.get(fileKey);
|
|
528
|
+
if (client && client.ws.readyState === WebSocket.OPEN) {
|
|
529
|
+
this._activeFileKey = fileKey;
|
|
530
|
+
logger.info({ fileKey, fileName: client.fileInfo.fileName }, 'Active file switched');
|
|
531
|
+
this.emit('activeFileChanged', { fileKey, fileName: client.fileInfo.fileName });
|
|
532
|
+
return true;
|
|
533
|
+
}
|
|
534
|
+
return false;
|
|
535
|
+
}
|
|
536
|
+
/**
|
|
537
|
+
* Get the currently active file's key
|
|
538
|
+
*/
|
|
539
|
+
getActiveFileKey() {
|
|
540
|
+
return this._activeFileKey;
|
|
541
|
+
}
|
|
542
|
+
// ============================================================================
|
|
543
|
+
// Cleanup
|
|
544
|
+
// ============================================================================
|
|
545
|
+
/**
|
|
546
|
+
* Reject pending requests that were sent to a specific file
|
|
547
|
+
*/
|
|
548
|
+
rejectPendingRequestsForFile(fileKey, reason) {
|
|
549
|
+
for (const [id, pending] of this.pendingRequests) {
|
|
550
|
+
if (pending.targetFileKey === fileKey) {
|
|
551
|
+
clearTimeout(pending.timeoutId);
|
|
552
|
+
pending.reject(new Error(reason));
|
|
553
|
+
this.pendingRequests.delete(id);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Reject all pending requests (used during shutdown)
|
|
559
|
+
*/
|
|
560
|
+
rejectPendingRequests(reason) {
|
|
561
|
+
for (const [, pending] of this.pendingRequests) {
|
|
562
|
+
clearTimeout(pending.timeoutId);
|
|
563
|
+
pending.reject(new Error(reason));
|
|
564
|
+
}
|
|
565
|
+
this.pendingRequests.clear();
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* Stop the server and clean up all connections
|
|
569
|
+
*/
|
|
570
|
+
async stop() {
|
|
571
|
+
// Clear all per-client grace period timers
|
|
572
|
+
for (const [, client] of this.clients) {
|
|
573
|
+
if (client.gracePeriodTimer) {
|
|
574
|
+
clearTimeout(client.gracePeriodTimer);
|
|
575
|
+
client.gracePeriodTimer = null;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
// Clear pending client identification timeouts
|
|
579
|
+
for (const [, timeout] of this._pendingClients) {
|
|
580
|
+
clearTimeout(timeout);
|
|
581
|
+
}
|
|
582
|
+
this._pendingClients.clear();
|
|
583
|
+
this.rejectPendingRequests('WebSocket server shutting down');
|
|
584
|
+
// Terminate all connected clients so wss.close() resolves promptly
|
|
585
|
+
if (this.wss) {
|
|
586
|
+
for (const ws of this.wss.clients) {
|
|
587
|
+
ws.terminate();
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
this.clients.clear();
|
|
591
|
+
this._activeFileKey = null;
|
|
592
|
+
if (this.wss) {
|
|
593
|
+
return new Promise((resolve) => {
|
|
594
|
+
this.wss.close(() => {
|
|
595
|
+
this._isStarted = false;
|
|
596
|
+
logger.info('WebSocket bridge server stopped');
|
|
597
|
+
resolve();
|
|
598
|
+
});
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
this._isStarted = false;
|
|
602
|
+
}
|
|
603
|
+
}
|
package/dist/cloudflare/index.js
CHANGED
|
@@ -30,7 +30,7 @@ export class FigmaConsoleMCPv3 extends McpAgent {
|
|
|
30
30
|
super(...arguments);
|
|
31
31
|
this.server = new McpServer({
|
|
32
32
|
name: "Figma Console MCP",
|
|
33
|
-
version: "
|
|
33
|
+
version: "1.8.0",
|
|
34
34
|
});
|
|
35
35
|
this.browserManager = null;
|
|
36
36
|
this.consoleMonitor = null;
|
|
@@ -1309,7 +1309,7 @@ export default {
|
|
|
1309
1309
|
return new Response(JSON.stringify({
|
|
1310
1310
|
status: "healthy",
|
|
1311
1311
|
service: "Figma Console MCP",
|
|
1312
|
-
version: "
|
|
1312
|
+
version: "1.8.0",
|
|
1313
1313
|
endpoints: {
|
|
1314
1314
|
mcp: ["/sse", "/mcp"],
|
|
1315
1315
|
oauth_mcp_spec: ["/.well-known/oauth-authorization-server", "/authorize", "/token", "/oauth/register"],
|
|
@@ -1355,13 +1355,13 @@ export default {
|
|
|
1355
1355
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1356
1356
|
<title>Figma Console MCP - The Most Comprehensive MCP Server for Figma</title>
|
|
1357
1357
|
<link rel="icon" type="image/svg+xml" href="https://docs.figma-console-mcp.southleft.com/favicon.svg">
|
|
1358
|
-
<meta name="description" content="Turn your Figma design system into a living API.
|
|
1358
|
+
<meta name="description" content="Turn your Figma design system into a living API. 53+ tools give AI assistants deep access to design tokens, component specs, variables, and programmatic design creation.">
|
|
1359
1359
|
|
|
1360
1360
|
<!-- Open Graph -->
|
|
1361
1361
|
<meta property="og:type" content="website">
|
|
1362
1362
|
<meta property="og:url" content="https://figma-console-mcp.southleft.com">
|
|
1363
1363
|
<meta property="og:title" content="Figma Console MCP - Turn Your Design System Into a Living API">
|
|
1364
|
-
<meta property="og:description" content="The most comprehensive MCP server for Figma.
|
|
1364
|
+
<meta property="og:description" content="The most comprehensive MCP server for Figma. 53+ tools give AI assistants deep access to design tokens, components, variables, and programmatic design creation.">
|
|
1365
1365
|
<meta property="og:image" content="https://docs.figma-console-mcp.southleft.com/images/og-image.jpg">
|
|
1366
1366
|
<meta property="og:image:width" content="1200">
|
|
1367
1367
|
<meta property="og:image:height" content="630">
|
|
@@ -1369,7 +1369,7 @@ export default {
|
|
|
1369
1369
|
<!-- Twitter -->
|
|
1370
1370
|
<meta name="twitter:card" content="summary_large_image">
|
|
1371
1371
|
<meta name="twitter:title" content="Figma Console MCP - Turn Your Design System Into a Living API">
|
|
1372
|
-
<meta name="twitter:description" content="The most comprehensive MCP server for Figma.
|
|
1372
|
+
<meta name="twitter:description" content="The most comprehensive MCP server for Figma. 53+ tools give AI assistants deep access to design tokens, components, variables, and programmatic design creation.">
|
|
1373
1373
|
<meta name="twitter:image" content="https://docs.figma-console-mcp.southleft.com/images/og-image.jpg">
|
|
1374
1374
|
|
|
1375
1375
|
<meta name="theme-color" content="#0D9488">
|
|
@@ -1287,7 +1287,7 @@ export function registerDesignCodeTools(server, getFigmaAPI, getCurrentUrl, vari
|
|
|
1287
1287
|
try {
|
|
1288
1288
|
const url = fileUrl || getCurrentUrl();
|
|
1289
1289
|
if (!url) {
|
|
1290
|
-
throw new Error("No Figma file URL
|
|
1290
|
+
throw new Error("No Figma file URL available. Pass the fileUrl parameter, call figma_navigate (CDP mode), or ensure the Desktop Bridge plugin is connected (WebSocket mode).");
|
|
1291
1291
|
}
|
|
1292
1292
|
const fileKey = extractFileKey(url);
|
|
1293
1293
|
if (!fileKey) {
|
|
@@ -1474,7 +1474,7 @@ export function registerDesignCodeTools(server, getFigmaAPI, getCurrentUrl, vari
|
|
|
1474
1474
|
try {
|
|
1475
1475
|
const url = fileUrl || getCurrentUrl();
|
|
1476
1476
|
if (!url) {
|
|
1477
|
-
throw new Error("No Figma file URL
|
|
1477
|
+
throw new Error("No Figma file URL available. Pass the fileUrl parameter, call figma_navigate (CDP mode), or ensure the Desktop Bridge plugin is connected (WebSocket mode).");
|
|
1478
1478
|
}
|
|
1479
1479
|
const fileKey = extractFileKey(url);
|
|
1480
1480
|
if (!fileKey) {
|