How MCP Bridges AI Assistants and Figma: A Deep Dive into Model Context Protocol
This article explains the Model Context Protocol (MCP) architecture, demonstrates how to build an MCP service for fetching Figma design data, details the data simplification pipeline, and shows how AI assistants can use standardized, secure context to generate accurate code from design files.
MCP (Model Context Protocol) Overview
Model Context Protocol (MCP) is an open standard that defines how AI applications securely and controllably interact with external data sources and tools. Its core idea is to provide a standardized context‑acquisition mechanism so AI assistants can access real‑time, accurate information to enhance their responses.
MCP Architecture
MCP follows a client‑server model:
MCP Client : typically an AI application (e.g., Cursor, Claude code).
MCP Server : provides specific functions or data access services.
Transport Layer : supports STDIO, HTTP and other communication methods.
The protocol borrows micro‑service design principles, enabling service discovery and security controls. Server APIs are exposed as “Tools” via a unified JSON‑RPC interface, and a context field (e.g., user intent, history) is embedded in requests to allow dynamic strategy adjustment.
Creating an MCP Service – Figma Example
Using the @modelcontextprotocol/sdk library, a simple MCP server can be built to fetch Figma design data:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
// 1. Create MCP server instance
const server = new McpServer({
name: "Figma MCP Server",
version: "0.4.3"
});
// 2. Register a tool
server.tool(
"get_figma_data",
"获取Figma设计文件的节点信息",
{
type: "object",
properties: {
fileKey: { type: "string" }, // required file ID
nodeId: { type: "string" } // optional node ID
},
required: ["fileKey"]
},
async (args) => {
return await figmaService.getFile(args.fileKey);
}
);After registration, the AI assistant can discover and invoke get_figma_data, using its result as part of the assistant’s context.
Benefits of MCP
Standardized Interface : unified tool registration and invocation.
Type Safety : schema‑based parameter validation.
Security Control : strict permission and access checks.
Extensibility : supports multiple data sources and functional integrations.
Figma Context MCP
Figma Context MCP is a specialized MCP service that bridges design tools (Figma) and AI programming assistants (e.g., Cursor). It enables AI to access exact node information from Figma files, ensuring design consistency and providing only the data needed for code generation.
Bridge Design and Development : connects Figma with AI assistants.
Ensure Design Consistency : uses real design data instead of screenshots.
Data Pruning and Transformation : simplifies raw Figma data to the most useful subset for code generation.
Project Structure
src/
├── cli.ts # Command‑line entry, supports STDIO and HTTP
├── config.ts # Configuration management
├── mcp.ts # MCP server entry, tool registration
├── server.ts # HTTP server implementation
├── services/
│ ├── figma.ts # Figma API wrapper
│ └── simplify-node-response.ts # Data simplification logic
├── transformers/
│ ├── layout.ts # Auto‑layout → CSS Flexbox conversion
│ ├── style.ts # Border, fill, effect handling
│ └── effects.ts # Shadow and effect processing
└── utils/
├── common.ts # General utilities
├── logger.ts # Logging system
└── sanitization.ts # Data cleaningCore Dependencies
{
"@modelcontextprotocol/sdk": "^1.10.2",
"@figma/rest-api-spec": "^0.24.0",
"zod": "^3.24.2",
"remeda": "^2.20.1"
}Runtime Flow
How to Use
Start the server with a STDIO transport for local debugging:
// Launch server
if (import.meta.url === `file://${process.argv[1]}`) {
const server = createServer({
figmaApiKey: "figd_your_figma_token",
figmaOAuthToken: "",
useOAuth: false,
});
try {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error('📱 MCP 服务器已启动');
} catch (error) {
console.error('❌ MCP 服务器启动失败:', error);
process.exit(1);
}
}Configure Cursor (or another AI assistant) to launch the MCP server via mcp.json:
"figma-mcp": {
"command": "node",
"args": ["/Users/maoxiongyu/Code/figma-context-mcp/dist/index.js"]
}After the server starts, Cursor can retrieve selected Figma node links and paste them directly into the chat window, where the AI agent generates runnable code based on the design data.
The generated code accurately reproduces dimensions, colors, and positions, though minor visual artifacts may still appear.
Figma Data Simplification Mechanism
The core simplification logic resides in src/services/simplify-node-response.ts. It converts complex Figma responses into AI‑friendly structures.
parseFigmaResponse
Handles both GetFileResponse and GetFileNodesResponse.
Aggregates component and component‑set information.
Filters visible nodes and recursively parses them.
Builds a global style variable system for deduplication.
Returns the final simplified design object.
parseNode – Depth‑First Traversal
The parseNode function processes each node, extracts text styles, fills, strokes, effects, layout, and then recursively processes children after the node’s own data has been emitted. This ordering ensures the AI sees the element’s complete context before its children.
function parseNode(globalVars, n, parent?) {
const { id, name, type } = n;
const simplified = { id, name, type };
// Text style conversion (font size, line height → em, letter‑spacing → %)
// Style deduplication via findOrCreateVar
// Fill, stroke, effect, layout handling
if (hasValue("children", n) && n.children.length > 0) {
const children = n.children
.filter(isVisible)
.map(child => parseNode(globalVars, child, n))
.filter(child => child !== null);
if (children.length) simplified.children = children;
}
return simplified;
}Style Deduplication
The findOrCreateVar helper checks whether a style value already exists in globalVars.styles. If so, it reuses the existing identifier; otherwise it generates a new one.
function findOrCreateVar(globalVars, value, prefix) {
const [existingVarId] = Object.entries(globalVars.styles).find(
([_, existingValue]) => JSON.stringify(existingValue) === JSON.stringify(value)
) ?? [];
if (existingVarId) return existingVarId;
const varId = generateVarId(prefix);
globalVars.styles[varId] = value;
return varId;
}Transformers – Modular Style Converters
Effects Transformer ( src/transformers/effects.ts) – classifies drop‑shadow and inner‑shadow, builds CSS box‑shadow or text‑shadow strings.
Style Transformer ( src/transformers/style.ts) – handles border styles, supports independent stroke weights.
Layout Transformer ( src/transformers/layout.ts) – converts Figma Auto Layout to CSS Flexbox, mapping direction, alignment, spacing, and gaps.
Image Handling
Two image strategies are implemented:
Fill Images : retrieved via getImageFills for existing background assets.
Rendered Images : exported with getImages as PNG or SVG, supporting both raster and vector outputs.
Conclusion
As the MCP ecosystem matures, a new development paradigm emerges: designers create in Figma, AI assistants consume real design data via MCP, and developers focus on review and architecture. The design file becomes an executable data source rather than a static reference, enabling more accurate, data‑driven code generation.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
