zapcode-figma-mcp 1.0.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.
Files changed (3) hide show
  1. package/LICENSE.md +21 -0
  2. package/build/index.js +238 -0
  3. package/package.json +35 -0
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Zapcode
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/build/index.js ADDED
@@ -0,0 +1,238 @@
1
+ #!/usr/bin/env node
2
+ import { createServer as createHttpServer, } from "http";
3
+ import { Server as SocketIOServer } from "socket.io";
4
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
6
+ import { URL } from "url";
7
+ import * as fs from "fs";
8
+ import * as path from "path";
9
+ // --- Default Ports ---
10
+ const DEFAULT_FIGMA_SOCKET_IO_PORT = 32896;
11
+ const DEFAULT_MCP_HTTP_PORT = 3001;
12
+ // --- Paths ---
13
+ const MCP_SSE_PATH = "/zapcode-mcp-sse";
14
+ const MCP_MESSAGE_PATH = "/mcp-messages";
15
+ // --- Global Variables ---
16
+ let figmaHttpServer = null;
17
+ let io = null;
18
+ let connectedFigmaClient = null;
19
+ const figmaContextRequests = new Map();
20
+ const figmaHttpConnections = new Set();
21
+ let mcpHttpServer = null;
22
+ let mcpServerInstance = null;
23
+ const mcpSseTransports = new Map();
24
+ // --- Argument Parsing ---
25
+ function parseArgs() {
26
+ const args = process.argv.slice(2);
27
+ let mcpPort = DEFAULT_MCP_HTTP_PORT;
28
+ const portArgIndex = args.findIndex((arg) => arg === "--port" || arg === "-p");
29
+ if (portArgIndex !== -1 && args[portArgIndex + 1]) {
30
+ const port = parseInt(args[portArgIndex + 1], 10);
31
+ if (!isNaN(port)) {
32
+ mcpPort = port;
33
+ }
34
+ }
35
+ return { mcpPort };
36
+ }
37
+ // --- Socket.IO Server Logic ---
38
+ function startSocketIOServer(port) {
39
+ return new Promise((resolve, reject) => {
40
+ console.log(`Attempting to start Socket.IO server for Figma on port ${port}...`);
41
+ try {
42
+ figmaHttpServer = createHttpServer();
43
+ io = new SocketIOServer(figmaHttpServer, {
44
+ maxHttpBufferSize: 1e8,
45
+ cors: { origin: "*" },
46
+ });
47
+ io.on("connection", (socket) => {
48
+ console.log(`Figma plugin connected: ${socket.id}`);
49
+ if (connectedFigmaClient) {
50
+ connectedFigmaClient.disconnect(true);
51
+ }
52
+ connectedFigmaClient = socket;
53
+ socket.on("context_response", (data) => {
54
+ if (!data?.requestId)
55
+ return;
56
+ const request = figmaContextRequests.get(data.requestId);
57
+ if (request) {
58
+ if (data.error)
59
+ request.reject(new Error(data.error));
60
+ else if (data.payload)
61
+ request.resolve(data.payload);
62
+ else
63
+ request.reject(new Error("Invalid context_response from Figma"));
64
+ figmaContextRequests.delete(data.requestId);
65
+ }
66
+ });
67
+ socket.on("disconnect", (reason) => {
68
+ console.log(`Figma plugin disconnected: ${socket.id}. Reason: ${reason}`);
69
+ if (connectedFigmaClient === socket) {
70
+ connectedFigmaClient = null;
71
+ }
72
+ });
73
+ socket.on("error", (err) => console.error(`Figma Socket.IO error: ${err.message}`));
74
+ });
75
+ figmaHttpServer.listen(port, () => {
76
+ console.log(`✅ Figma Socket.IO server listening on port ${port}`);
77
+ resolve();
78
+ });
79
+ }
80
+ catch (error) {
81
+ console.error(`Error creating Figma Socket.IO server: ${error}`);
82
+ reject(error);
83
+ }
84
+ });
85
+ }
86
+ // --- MCP Server Logic ---
87
+ async function startMcpServer(port) {
88
+ console.log(`Attempting to start MCP HTTP/SSE server on port ${port}...`);
89
+ const serverInfo = {
90
+ name: "zapcode-figma-mcp-server",
91
+ title: "Zapcode Figma MCP",
92
+ version: "1.0.2",
93
+ };
94
+ const serverOptions = { capabilities: { tools: {} } };
95
+ mcpServerInstance = new McpServer(serverInfo, serverOptions);
96
+ mcpServerInstance.tool("get_figma_context", "Retrieves the selected Figma frame context (HTML, CSS, prompt, image, assets). Saves any provided SVG assets to the local 'assets/svg' directory.", {}, async () => {
97
+ console.log("MCP Tool 'get_figma_context' invoked.");
98
+ if (!connectedFigmaClient?.connected) {
99
+ console.error("Error: Figma plugin not connected.");
100
+ return {
101
+ isError: true,
102
+ content: [
103
+ {
104
+ type: "text",
105
+ text: "Error: Figma plugin is not connected. Please connect the plugin in Figma.",
106
+ },
107
+ ],
108
+ };
109
+ }
110
+ const requestId = `figma-ctx-${Date.now()}`;
111
+ try {
112
+ console.log(`Emitting 'request_context' to Figma (ID: ${requestId})`);
113
+ connectedFigmaClient.emit("request_context", { requestId });
114
+ const context = await new Promise((resolve, reject) => {
115
+ figmaContextRequests.set(requestId, { resolve, reject });
116
+ setTimeout(() => {
117
+ if (figmaContextRequests.has(requestId)) {
118
+ reject(new Error("Request to Figma plugin timed out after 30 seconds."));
119
+ figmaContextRequests.delete(requestId);
120
+ }
121
+ }, 30000);
122
+ });
123
+ console.log("Successfully received context from Figma.");
124
+ // Save assets to the current working directory
125
+ const workspacePath = process.cwd();
126
+ const assetResults = await saveSvgAssets(context.assets, workspacePath);
127
+ const mcpContent = [];
128
+ if (context.image) {
129
+ mcpContent.push({
130
+ type: "image",
131
+ data: context.image,
132
+ mimeType: "image/png",
133
+ });
134
+ }
135
+ const textDetails = `Figma Context Details:\n\nPrompt Suggestion:\n${context.prompt}\n\nTechnology Configuration:\n\`\`\`json\n${JSON.stringify(context.tech_config, null, 2)}\n\`\`\`\n\nSVG Assets ${assetResults.savedFiles.length > 0
136
+ ? "(Saved to " + path.join(workspacePath, "assets", "svg") + "):"
137
+ : "(None saved)"}\n${assetResults.savedFiles
138
+ .map((p) => `- ${path.basename(p)}`)
139
+ .join("\n")}\n\nHTML:\n\`\`\`html\n${context.HTML}\n\`\`\`\n\nCSS:\n\`\`\`css\n${context.CSS}\n\`\`\``;
140
+ mcpContent.push({ type: "text", text: textDetails });
141
+ return { content: mcpContent };
142
+ }
143
+ catch (error) {
144
+ console.error(`Error during Figma context request: ${error.message}`);
145
+ return {
146
+ isError: true,
147
+ content: [
148
+ {
149
+ type: "text",
150
+ text: `Error getting Figma context: ${error.message}`,
151
+ },
152
+ ],
153
+ };
154
+ }
155
+ });
156
+ return new Promise((resolve, reject) => {
157
+ mcpHttpServer = createHttpServer(async (req, res) => {
158
+ const requestUrl = new URL(req.url || "", `http://${req.headers.host}`);
159
+ if (req.method === "GET" && requestUrl.pathname === MCP_SSE_PATH) {
160
+ const transport = new SSEServerTransport(MCP_MESSAGE_PATH, res);
161
+ mcpSseTransports.set(transport.sessionId, transport);
162
+ console.log(`New MCP client connected. SessionID: ${transport.sessionId}`);
163
+ req.socket.on("close", () => mcpSseTransports.delete(transport.sessionId));
164
+ await mcpServerInstance.connect(transport);
165
+ }
166
+ else if (req.method === "POST" &&
167
+ requestUrl.pathname === MCP_MESSAGE_PATH) {
168
+ const sessionId = requestUrl.searchParams.get("sessionId");
169
+ const transport = sessionId
170
+ ? mcpSseTransports.get(sessionId)
171
+ : undefined;
172
+ if (transport)
173
+ await transport.handlePostMessage(req, res);
174
+ else
175
+ res.writeHead(404).end("Session not found");
176
+ }
177
+ else {
178
+ res.writeHead(404).end("Not Found");
179
+ }
180
+ });
181
+ mcpHttpServer.listen(port, () => {
182
+ console.log(`✅ MCP HTTP/SSE server listening on http://localhost:${port}${MCP_SSE_PATH}`);
183
+ resolve();
184
+ });
185
+ });
186
+ }
187
+ // --- Utility Functions (modified to remove vscode dependency) ---
188
+ async function saveSvgAssets(assets, basePath) {
189
+ const savedFiles = [];
190
+ const errors = [];
191
+ if (!Array.isArray(assets))
192
+ return { savedFiles, errors: ["No assets provided"] };
193
+ const assetsDir = path.join(basePath, "assets", "svg");
194
+ try {
195
+ if (!fs.existsSync(assetsDir)) {
196
+ fs.mkdirSync(assetsDir, { recursive: true });
197
+ }
198
+ for (const asset of assets) {
199
+ if (asset.type !== "svg" || !asset.name || !asset.data)
200
+ continue;
201
+ const fileName = asset.name.replace(/[^a-z0-9]/gi, "_").toLowerCase() + ".svg";
202
+ const filePath = path.join(assetsDir, fileName);
203
+ const svgContent = asset.data.startsWith("data:image/svg+xml;base64,")
204
+ ? Buffer.from(asset.data.split(",")[1], "base64").toString()
205
+ : asset.data;
206
+ fs.writeFileSync(filePath, svgContent);
207
+ savedFiles.push(filePath);
208
+ }
209
+ }
210
+ catch (err) {
211
+ errors.push(`Failed to save assets: ${err.message}`);
212
+ }
213
+ return { savedFiles, errors };
214
+ }
215
+ // --- Main Execution Logic ---
216
+ async function main() {
217
+ const { mcpPort } = parseArgs();
218
+ console.log("Starting Figma MCP Server...");
219
+ try {
220
+ await startSocketIOServer(DEFAULT_FIGMA_SOCKET_IO_PORT);
221
+ await startMcpServer(mcpPort);
222
+ console.log("🚀 All servers are up and running!");
223
+ console.log("Connect your Figma plugin and an MCP client to begin.");
224
+ }
225
+ catch (error) {
226
+ console.error("💥 Failed to start servers:", error);
227
+ process.exit(1);
228
+ }
229
+ }
230
+ // --- Graceful Shutdown ---
231
+ async function shutdown() {
232
+ console.log("\nGracefully shutting down servers...");
233
+ // Implement stop functions if needed, or just exit for this simple case
234
+ process.exit(0);
235
+ }
236
+ process.on("SIGINT", shutdown);
237
+ process.on("SIGTERM", shutdown);
238
+ main();
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "zapcode-figma-mcp",
3
+ "version": "1.0.0",
4
+ "description": "An MCP server that exposes Figma context via a plugin and saves assets, from Zapcode.",
5
+ "type": "module",
6
+ "bin": {
7
+ "zapcode-figma-mcp": "./build/index.js"
8
+ },
9
+ "scripts": {
10
+ "build": "tsc",
11
+ "start": "node build/index.js",
12
+ "prepublishOnly": "npm run build"
13
+ },
14
+ "keywords": [
15
+ "mcp",
16
+ "model-context-protocol",
17
+ "figma",
18
+ "ai",
19
+ "zapcode"
20
+ ],
21
+ "author": "Zapcode",
22
+ "license": "SEE LICENSE IN LICENSE.md",
23
+ "files": [
24
+ "build/"
25
+ ],
26
+ "dependencies": {
27
+ "@modelcontextprotocol/sdk": "^1.9.0",
28
+ "socket.io": "^4.7.5",
29
+ "zod": "^3.23.8"
30
+ },
31
+ "devDependencies": {
32
+ "@types/node": "^20.12.12",
33
+ "typescript": "^5.4.5"
34
+ }
35
+ }