### Start Server (stdio) Source: https://github.com/glips/figma-context-mcp/blob/main/CLAUDE.md Starts the server in stdio mode for MCP clients. ```bash pnpm start:cli ``` -------------------------------- ### Install Dependencies Source: https://github.com/glips/figma-context-mcp/blob/main/CLAUDE.md Installs all project dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Server Start Function Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/EXPORTS.md Asynchronously starts the server with the provided configuration. This is a top-level function for server initialization. ```typescript async startServer(config: ServerConfig): Promise ``` -------------------------------- ### Start Server (HTTP) Source: https://github.com/glips/figma-context-mcp/blob/main/CLAUDE.md Starts the server in HTTP mode on the default port 3333. ```bash pnpm start ``` -------------------------------- ### Complete Usage Example Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-figma-service.md This example demonstrates a complete workflow using the Figma Service, including authentication, fetching file and node data, and downloading images. ```APIDOC ## Example: Complete Usage ```typescript import { FigmaService } from 'figma-developer-mcp'; async function processFigmaFile() { const service = new FigmaService({ figmaApiKey: process.env.FIGMA_API_KEY || '', figmaOAuthToken: process.env.FIGMA_OAUTH_TOKEN || '', useOAuth: !!process.env.FIGMA_OAUTH_TOKEN, }); try { // Fetch file structure const { data: fileData, rawSize } = await service.getRawFile('myFileKey'); console.log(`File: ${fileData.name}, ${rawSize} bytes`); // Fetch a specific frame const { data: nodeData } = await service.getRawNode('myFileKey', '1:100'); const frame = nodeData.nodes['1:100'].document; console.log(`Frame: ${frame.name}`); // Download images used in the file const imageUrls = await service.getImageFillUrls('myFileKey'); const downloads = await service.downloadImages( 'myFileKey', './assets', Object.entries(imageUrls).map(([ref, url]) => ({ imageRef: ref, fileName: `asset_${ref}.png`, })) ); console.log(`Downloaded ${downloads.length} images`); } catch (error) { console.error('Failed to process Figma file:', error); } } ``` ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/glips/figma-context-mcp/blob/main/CONTRIBUTING.md Clone the project repository and install its dependencies using pnpm. ```bash git clone https://github.com/GLips/Figma-Context-MCP.git cd Figma-Context-MCP pnpm install ``` -------------------------------- ### Example Downloaded File Response Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/mcp-tools.md This is an example of the text response format indicating downloaded files, their dimensions, and optional CSS variables if requested. ```text Downloaded 3 images to `/workspace/home/assets`: - logo.png: 256x256 - icon_home.svg: 24x24 | --icon-home-w: 24px; --icon-home-h: 24px; - animation.gif: 320x240 (also requested as: anim.gif) ``` -------------------------------- ### Start MCP with OAuth Token and Custom Settings Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/configuration.md Starts the HTTP server with a specified OAuth token, port, host, and output format. This is useful for custom integrations or when running on non-default network configurations. ```bash npx figma-developer-mcp \ --figma-oauth-token=xxxxxxxxxxxxx \ --port=8080 \ --host=0.0.0.0 \ --format=json ``` -------------------------------- ### Start MCP with Custom Image Directory Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/configuration.md Starts the MCP tool and specifies a custom directory for storing downloaded images. This is useful for organizing assets or when the default location is not suitable. ```bash npx figma-developer-mcp \ --figma-api-key=fdk_xxxxxxxxxxxxx \ --image-dir=./src/assets/images \ --format=json ``` -------------------------------- ### Server HTTP Server Start Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/EXPORTS.md Starts an HTTP server on a specified host and port, with given authentication and server options. ```typescript async startHttpServer(host: string, port: number, baseAuth: FigmaAuthOptions, serverOptions): Promise ``` -------------------------------- ### CLI Configuration Priority Example Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/INDEX.md Demonstrates how CLI arguments, environment variables, and defaults are prioritized for configuration settings like the port. ```bash # CLI wins npx figma-developer-mcp --port=8080 # Uses 8080 # Env wins if no CLI PORT=5000 npx figma-developer-mcp # Uses 5000 # Default if neither npx figma-developer-mcp # Uses 3333 ``` -------------------------------- ### Build and Run Project Commands Source: https://github.com/glips/figma-context-mcp/blob/main/CONTRIBUTING.md Commands for building the project, running tests, starting the development server, and other development tasks. ```bash pnpm build ``` ```bash pnpm test ``` ```bash pnpm dev ``` ```bash pnpm type-check ``` ```bash pnpm lint ``` ```bash pnpm format ``` ```bash pnpm inspect ``` -------------------------------- ### Start MCP Server with Configuration Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-mcp-server.md Use `startServer` for a high-level initialization that configures proxy, telemetry, and connects to the appropriate transport. Ensure server configuration is complete. ```typescript async function startServer(config: ServerConfig): Promise ``` ```typescript import { startServer, getServerConfig } from 'figma-developer-mcp'; const config = getServerConfig({ figmaApiKey: process.env.FIGMA_API_KEY, port: 3333, }); await startServer(config); ``` -------------------------------- ### Start MCP with Personal Access Token Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/configuration.md Starts the HTTP server on the default port and host using a Personal Access Token for authentication. Ensure the FIGMA_API_KEY environment variable is set. ```bash export FIGMA_API_KEY=fdk_xxxxxxxxxxxxx npx figma-developer-mcp # Starts HTTP server on 127.0.0.1:3333 with tree output format ``` -------------------------------- ### Start and Stop Figma Context MCP Server Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-mcp-server.md Demonstrates the complete lifecycle of the Figma Context MCP server, including loading configuration, starting the server, and handling graceful shutdown. ```typescript import { startServer, getServerConfig, stopHttpServer } from 'figma-developer-mcp'; async function main() { // Load configuration from CLI args and environment const config = getServerConfig({ figmaApiKey: process.env.FIGMA_API_KEY, port: parseInt(process.env.PORT || '3333'), format: 'json', imageDir: './public/images', }); try { // Start the server await startServer(config); console.log('Server is running. Press Ctrl+C to stop.'); } catch (error) { console.error('Failed to start server:', error); process.exit(1); } } // Handle graceful shutdown process.on('SIGINT', async () => { console.log('\nShutting down...'); await stopHttpServer(); process.exit(0); }); main(); ``` -------------------------------- ### Example .env File Configuration Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/configuration.md A sample `.env` file demonstrating how to configure various settings like API keys, port, output format, and image directory. ```dotenv FIGMA_API_KEY=fdk_xxxxxxxxxxxxx FRAMELINK_PORT=3333 OUTPUT_FORMAT=json IMAGE_DIR=./public/images ``` -------------------------------- ### Development Mode (stdio) Source: https://github.com/glips/figma-context-mcp/blob/main/CLAUDE.md Starts the server in development mode using stdio for MCP clients. ```bash pnpm dev:cli ``` -------------------------------- ### JSON Output Format Example Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/INDEX.md An example of the structured JSON format for output, containing node information, components, and global variables. ```json { "name": "File Name", "nodes": [ { "id": "...", "type": "PAGE", "children": [...] } ], "components": { "id": {...} }, "globalVars": { "styles": {...} }, "elements": {} } ``` -------------------------------- ### Figma Node Rendering Example Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-figma-service.md Demonstrates fetching PNG and SVG render URLs for Figma nodes using `getNodeRenderUrls`. Includes examples for PNG scale and SVG options. ```typescript const pngUrls = await figmaService.getNodeRenderUrls( 'abc123xyz', ['1:10', '1:20'], 'png', { pngScale: 2 } ); // Result: { '1:10': 'https://...', '1:20': 'https://...' } const svgUrls = await figmaService.getNodeRenderUrls( 'abc123xyz', ['1:30'], 'svg', { svgOptions: { outlineText: true, includeId: false } } ); ``` -------------------------------- ### Start HTTP Server Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-mcp-server.md Initiate an HTTP server on a specified host and port using `startHttpServer`. This serves MCP over StreamableHTTP and requires authentication and server options. ```typescript async function startHttpServer( host: string, port: number, baseAuth: FigmaAuthOptions, serverOptions: Omit, ): Promise ``` ```typescript const httpServer = await startHttpServer( '127.0.0.1', 3333, { figmaApiKey: 'fdk_...', figmaOAuthToken: '', useOAuth: false }, { outputFormat: 'json', imageDir: './public' } ); console.log('Server listening on http://127.0.0.1:3333'); ``` -------------------------------- ### Development Mode (HTTP) Source: https://github.com/glips/figma-context-mcp/blob/main/CLAUDE.md Starts the server in development mode with watch and auto-restart capabilities over HTTP. ```bash pnpm dev ``` -------------------------------- ### startHttpServer Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-mcp-server.md Starts the HTTP server on the specified host and port, serving MCP over StreamableHTTP. ```APIDOC ## startHttpServer(host, port, baseAuth, serverOptions) ### Description Starts the HTTP server on the specified host and port. Serves MCP over StreamableHTTP at `/mcp` and `/sse` endpoints. ### Method Signature ```typescript async function startHttpServer( host: string, port: number, baseAuth: FigmaAuthOptions, serverOptions: Omit, ): Promise ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### `host` (string) - **Type**: string - **Required**: yes - **Description**: Bind address (e.g., `127.0.0.1` or `0.0.0.0`) #### `port` (number) - **Type**: number - **Required**: yes - **Description**: Port number (e.g., 3333) #### `baseAuth` (`FigmaAuthOptions`) - **Type**: `FigmaAuthOptions` - **Required**: yes - **Description**: Server-level auth (can be overridden per-request) #### `serverOptions` (`CreateServerOptions`) - **Type**: `CreateServerOptions` (excluding `transport`) - **Required**: yes - **Description**: Output format, image directory, etc. - **`outputFormat`** (`"tree" | "json" | "yaml"`) - **Required**: no - **Default**: `"tree"` - **Description**: Response serialization format - **`skipImageDownloads`** (boolean) - **Required**: no - **Default**: `false` - **Description**: Disable the `download_figma_images` tool if true - **`imageDir`** (string) - **Required**: no - **Description**: Directory base for image downloads (defaults to cwd) ### Returns - **Type**: `Server` (Node.js Server object) - **Description**: Node.js `Server` object. ### Throws Error if port is already in use. ### Example ```typescript const httpServer = await startHttpServer( '127.0.0.1', 3333, { figmaApiKey: 'fdk_...', figmaOAuthToken: '', useOAuth: false }, { outputFormat: 'json', imageDir: './public' } ); console.log('Server listening on http://127.0.0.1:3333'); ``` ``` -------------------------------- ### Tree Output Format Example Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/INDEX.md An example of the default human-readable ASCII tree format used for output, including emoji icons. ```text 📄 File Name ┌─ 🖼️ Page │ ├─ 🔲 Frame [layout: row] │ │ ├─ 🔤 Text │ │ └─ 🔲 Button [componentId: ...] │ └─ 🔲 Section ``` -------------------------------- ### Start MCP in Stdio Mode Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/configuration.md Starts the MCP client in stdio mode, which is suitable for integration with other command-line tools. It requires a Figma API key. ```bash npx figma-developer-mcp \ --figma-api-key=fdk_xxxxxxxxxxxxx \ --stdio ``` -------------------------------- ### Server Creation and Lifecycle Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/README.md Functions for creating, starting, and stopping the MCP server and its associated HTTP server. ```APIDOC ## createServer ### Description Creates an instance of the MCP server. ### Method `createServer()` ### Parameters None ### Response - Returns the created server instance. ``` ```APIDOC ## startServer ### Description Starts the MCP server. ### Method `startServer(server)` ### Parameters - **server**: The server instance to start. ### Response None ``` ```APIDOC ## startHttpServer ### Description Starts the HTTP server for the MCP server. ### Method `startHttpServer(server, port)` ### Parameters - **server**: The server instance. - **port** (number): The port to listen on. ### Response None ``` ```APIDOC ## stopHttpServer ### Description Stops the HTTP server for the MCP server. ### Method `stopHttpServer(server)` ### Parameters - **server**: The server instance. ### Response None ``` -------------------------------- ### Complete Figma Service Usage Example Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-figma-service.md Demonstrates fetching file structure, a specific frame, and downloading images. It uses environment variables for API keys and tokens. ```typescript import { FigmaService } from 'figma-developer-mcp'; async function processFigmaFile() { const service = new FigmaService({ figmaApiKey: process.env.FIGMA_API_KEY || '', figmaOAuthToken: process.env.FIGMA_OAUTH_TOKEN || '', useOAuth: !!process.env.FIGMA_OAUTH_TOKEN, }); try { // Fetch file structure const { data: fileData, rawSize } = await service.getRawFile('myFileKey'); console.log(`File: ${fileData.name}, ${rawSize} bytes`); // Fetch a specific frame const { data: nodeData } = await service.getRawNode('myFileKey', '1:100'); const frame = nodeData.nodes['1:100'].document; console.log(`Frame: ${frame.name}`); // Download images used in the file const imageUrls = await service.getImageFillUrls('myFileKey'); const downloads = await service.downloadImages( 'myFileKey', './assets', Object.entries(imageUrls).map(([ref, url]) => ({ imageRef: ref, fileName: `asset_${ref}.png`, })) ); console.log(`Downloaded ${downloads.length} images`); } catch (error) { console.error('Failed to process Figma file:', error); } } ``` -------------------------------- ### Tree Serialization Format Example Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/internals-and-algorithms.md Illustrates the visual representation of the tree serialization format using emoji icons and indentation. This is a visual example, not executable code. ```text 📄 File ┌─ 🖼️ Page │ ├─ 🔲 Frame │ └─ 🔤 Text └─ 🖼️ Page 2 ``` -------------------------------- ### MCP Validation Capture Installation Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/EXPORTS.md Installs a capture mechanism for validation rejections. This function modifies the server's behavior to intercept validation errors. ```typescript installValidationRejectCapture(server, options): void ``` -------------------------------- ### Example of Building Simplified Grid Layout Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/transformers-and-styles.md Shows how to use `buildSimplifiedLayout` with a Figma object configured for grid layout. The output is a simplified grid layout object. ```typescript const grid = { layoutMode: 'GRID', gridColumnsSizing: '1fr 1fr 1fr', gridRowSizing: 'auto', gridColumnGap: 12, gridRowGap: 16, }; const layout = buildSimplifiedLayout(grid); // Result: // { // mode: 'grid', // gridTemplateColumns: '1fr 1fr 1fr', // gridTemplateRows: 'auto', // gap: '16px 12px' // } ``` -------------------------------- ### Set Output Format to YAML Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/configuration.md Use the `--format` flag to specify the desired output serialization format. This example sets it to YAML. ```bash npx figma-developer-mcp --format=yaml ``` -------------------------------- ### Example of Building Simplified Flex Layout Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/transformers-and-styles.md Demonstrates how to use `buildSimplifiedLayout` with a Figma frame object configured for flex layout. The output is a simplified layout object. ```typescript const frame = { layoutMode: 'FLEX', primaryAxisOrientation: 'HORIZONTAL', primaryAxisAlignItems: 'CENTER', counterAxisAlignItems: 'CENTER', itemSpacing: 16, paddingTop: 12, paddingRight: 16, paddingBottom: 12, paddingLeft: 16, }; const layout = buildSimplifiedLayout(frame); // Result: // { // mode: 'row', // justifyContent: 'center', // alignItems: 'center', // gap: '16px', // padding: '12px 16px' // } ``` -------------------------------- ### Set Output Format to JSON Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/configuration.md Use the `--format` flag to specify the desired output serialization format. This example sets it to JSON. ```bash npx figma-developer-mcp --format=json ``` -------------------------------- ### Component Extractor Example Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-extractors.md Shows how componentExtractor populates SimplifiedNode.componentId and SimplifiedNode.componentProperties from an instance node. ```typescript const instanceNode = { type: 'INSTANCE', componentId: 'abc123:xyz', overrides: [{ id: 'prop_1', value: 'Primary' }] }; // componentExtractor sets: // node.componentId = 'abc123:xyz' // node.componentProperties = { 'prop_1': 'Primary' } ``` -------------------------------- ### Fetch Entire Figma File Request Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/mcp-tools.md Example request to fetch all data from a specified Figma file using its key. ```json { "fileKey": "abc123xyz", "type": "get_figma_data" } ``` -------------------------------- ### Figma Image Download Example Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-figma-service.md Shows how to download various image types (fills and rendered nodes) using `downloadImages`. Includes logging of results and CSS variables if generated. ```typescript const results = await figmaService.downloadImages( 'abc123xyz', './public/images', [ { imageRef: 'img_1', fileName: 'logo.png' }, { gifRef: 'gif_1', fileName: 'animation.gif' }, { nodeId: '1:100', fileName: 'icon.svg' }, ] ); results.forEach(result => { console.log(`Downloaded: ${result.filePath}`); console.log(`Dimensions: ${result.finalDimensions.width}x${result.finalDimensions.height}`); if (result.cssVariables) console.log(`CSS: ${result.cssVariables}`); }); ``` -------------------------------- ### Resolved Configuration Output Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/configuration.md When starting in HTTP mode, the server prints its resolved configuration, showing the sources for each setting (default, cli, env file, etc.). ```text Configuration: - ENV_FILE: /path/to/.env (source: default) - FIGMA_API_KEY: ****abc123 (source: cli) - Authentication Method: Personal Access Token (X-Figma-Token) - FRAMELINK_PORT: 3333 (source: default) - FRAMELINK_HOST: 127.0.0.1 (source: default) - PROXY: none (source: default) - OUTPUT_FORMAT: json (source: cli) - SKIP_IMAGE_DOWNLOADS: false (source: default) - IMAGE_DIR: /workspace/home (source: default) - TELEMETRY: enabled (source: default) ``` -------------------------------- ### Server Transport Functions Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/EXPORTS.md Functions for starting and stopping the HTTP server. ```APIDOC ## startServer ### Description Starts the server with the given configuration. ### Signature ```typescript async startServer(config: ServerConfig): Promise ``` ## startHttpServer ### Description Starts an HTTP server on the specified host and port. ### Signature ```typescript async startHttpServer(host: string, port: number, baseAuth: FigmaAuthOptions, serverOptions): Promise ``` ## stopHttpServer ### Description Stops the currently running HTTP server. ### Signature ```typescript async stopHttpServer(): Promise ``` ``` -------------------------------- ### Visuals Extractor Example Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-extractors.md Illustrates how visualsExtractor populates fill, stroke, and effect properties on a SimplifiedNode. ```typescript const shapeNode = { fills: [{ type: 'SOLID', color: { r: 0.2, g: 0.4, b: 0.8 } }], strokes: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0 } }], strokeWeight: 2, effects: [{ type: 'DROP_SHADOW', offset: { x: 0, y: 4 } }] }; // visualsExtractor sets: // node.fills = ['#3366cc'] // node.strokes = { colors: ['#000000'], strokeWeight: '2px' } // node.effects = { shadows: [{ offset: [0, 4] }] } ``` -------------------------------- ### Layout Extractor Example Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-extractors.md Demonstrates how layoutExtractor processes a node's layout properties, converting them into a simplified layout object. ```typescript const node = { layoutMode: 'FLEX', primaryAxisAlignItems: 'CENTER', paddingTop: 16, paddingBottom: 16, paddingLeft: 12, paddingRight: 12, }; // layoutExtractor sets node.layout to: // { mode: 'row', justifyContent: 'center', padding: '16px 12px' } ``` -------------------------------- ### Figma Data Tree Format Example Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/mcp-tools.md Illustrates the hierarchical tree format for representing Figma design data, showing pages, frames, and components. ```text 📄 My Design File ┌─ 🖼️ Page 1 │ ├─ 🔲 Header [layout: row] │ │ ├─ 🔤 Title │ │ └─ 🔲 Button [componentId: abc123] │ └─ 🔲 Content └─ 🖼️ Page 2 ``` -------------------------------- ### Figma Flex Container Setup Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/internals-and-algorithms.md Constructs a simplified layout object for a flex container based on Figma node properties. Requires conversion functions for alignment and gap. ```typescript const layout: SimplifiedLayout = { mode: "row" | "column", justifyContent: convertJustifyContent(primaryAxisAlignItems), alignItems: convertAlignItems(counterAxisAlignItems), gap: buildFlexGap(node), wrap: node.layoutWrap === "WRAP", padding: formatPadding(top, right, bottom, left), }; ``` -------------------------------- ### Example: Custom Extractor for Modals Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-extractors.md An example of a custom extractor that identifies and marks nodes as modals if their type is 'FRAME' and their name starts with 'Modal'. This demonstrates mutating the `result` object. ```typescript const myCustomExtractor: ExtractorFn = (node, result, context) => { if (node.type === 'FRAME' && node.name.startsWith('Modal')) { result.isModal = true; // Custom property } }; await extractFromDesign(nodes, [myCustomExtractor, allExtractors]); ``` -------------------------------- ### Style Deduplication Example Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/README.md Demonstrates how styles used multiple times are hoisted to globalVars with content-addressed IDs, reducing output size and ensuring byte-stable IDs. ```typescript // Same color in two nodes nodes[0].fills = "fill_abc123de" nodes[1].fills = "fill_abc123de" globalVars.styles = { "fill_abc123de": ["#3366cc"] } ``` -------------------------------- ### Start MCP Behind HTTP Proxy Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/configuration.md Configures the MCP tool to route its HTTP requests through a specified proxy server. This is necessary when operating within a corporate network that requires proxying. ```bash npx figma-developer-mcp \ --figma-api-key=fdk_xxxxxxxxxxxxx \ --proxy=http://proxy.corp.com:3128 ``` -------------------------------- ### LLM Context Optimization with Figma Extractors Source: https://github.com/glips/figma-context-mcp/blob/main/src/extractors/README.md Provides an example function `extractForLLM` that demonstrates how to use different extractors and options to incrementally extract data from large Figma designs for various LLM phases (structure, content, styling, full). ```typescript // For large designs - extract incrementally function extractForLLM(nodes, phase) { switch (phase) { case "structure": return extractFromDesign(nodes, layoutOnly, { maxDepth: 3 }); case "content": return extractFromDesign(nodes, contentOnly); case "styling": return extractFromDesign(nodes, visualsOnly, { maxDepth: 2 }); case "full": return extractFromDesign(nodes, allExtractors); } } ``` -------------------------------- ### Get Server Configuration Function Signature Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/configuration.md This TypeScript function signature shows the main entry point for resolving server settings. It takes server flags as input and returns a ServerConfig object. ```typescript function getServerConfig(flags: ServerFlags): ServerConfig ``` -------------------------------- ### startServer Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-mcp-server.md High-level function that initializes the server, configures proxy and telemetry, and connects to the appropriate transport (stdio or HTTP). ```APIDOC ## startServer(config) ### Description High-level function that initializes the server, configures proxy and telemetry, and connects to the appropriate transport (stdio or HTTP). ### Method Signature ```typescript async function startServer(config: ServerConfig): Promise ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### `config` (`ServerConfig`) - **Type**: `ServerConfig` - **Required**: yes - **Description**: Complete server configuration (from `getServerConfig`) ### Returns - **Type**: `Promise` - **Description**: Promise that resolves when the server is listening. Server remains active until SIGINT/SIGTERM. ### Throws - `UsageError` if credentials are missing (stdio mode only) - Network errors if port binding fails (HTTP mode) ### Example ```typescript import { startServer, getServerConfig } from 'figma-developer-mcp'; const config = getServerConfig({ figmaApiKey: process.env.FIGMA_API_KEY, port: 3333, }); await startServer(config); ``` ``` -------------------------------- ### Inline Text Style References Example Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/internals-and-algorithms.md Demonstrates how to use inline text style references for unique formatting beyond bold and italic. The 'ts' namespace avoids collisions with other styles. ```typescript // Character run with unique formatting { "text": "Special {ts1}styled{/ts1} text", "textStyle": { "fontFamily": "Inter", "fontSize": 16 }, "globalVars": { "ts1": { fontStyle: "italic", fills: ["#ff0000"], fontSize: 14 } } } ``` -------------------------------- ### Fetch and Simplify Figma File Data Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/INDEX.md This snippet demonstrates fetching a raw Figma file and then simplifying its content using default extractors. It's useful for getting a structured representation of the design. ```typescript import { FigmaService } from 'figma-developer-mcp'; import { simplifyRawFigmaObject, allExtractors } from 'figma-developer-mcp'; const service = new FigmaService({ /* ... */ }); const { data } = await service.getRawFile('myFileKey'); const design = await simplifyRawFigmaObject(data, allExtractors); console.log(`Nodes: ${design.nodes.length}`); console.log(`Styles: ${Object.keys(design.globalVars.styles).length}`); ``` -------------------------------- ### Example: SVG Flattening with afterChildren Hook Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/internals-and-algorithms.md An example implementation of the `afterChildren` hook to flatten vector children into their parent node, effectively removing the parent if it's a VECTOR type. ```typescript export function collapseSvgContainers( node: FigmaDocumentNode, result: SimplifiedNode, children: SimplifiedNode[], ): SimplifiedNode[] { if (node.type === 'VECTOR') { // Flatten vector children into parent result.children = children; return []; // Remove this node from parent's children } return children; // Keep children as-is } ``` -------------------------------- ### Build Project Source: https://github.com/glips/figma-context-mcp/blob/main/CLAUDE.md Builds the project using tsup, outputting to the dist/ directory. ```bash pnpm build ``` -------------------------------- ### MCP Validation Capture Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/EXPORTS.md Installs a capture mechanism for validation rejections. ```APIDOC ## installValidationRejectCapture ### Description Installs a capture mechanism on the server to intercept and handle validation rejections. ### Signature ```typescript installValidationRejectCapture(server, options): void ``` ``` -------------------------------- ### Figma MCP Server Entry Points Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/INDEX.md Illustrates the execution flow from the command-line interface to the server's core functionalities, including tool registration and server startup. ```typescript bin.ts (executable) → server.ts (transport selection) → startServer() → stdio or HTTP mode mcp/index.ts (tool registration) ├─ get_figma_data tool └─ download_figma_images tool ``` -------------------------------- ### Run in Stdio Mode Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/configuration.md Enable stdio mode for direct MCP client integration using the `--stdio` CLI flag. This mode requires global credentials at startup. ```bash npx figma-developer-mcp --stdio ``` -------------------------------- ### Traversal Options with `collapseSvgContainers` Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-extractors.md Example demonstrating how to use the `collapseSvgContainers` function as the `afterChildren` callback within `TraversalOptions`. ```typescript const options: TraversalOptions = { afterChildren: collapseSvgContainers }; ``` -------------------------------- ### Text Extractor Example Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-extractors.md Shows how textExtractor populates SimplifiedNode.text and SimplifiedNode.textStyle from a text node's properties. ```typescript const textNode = { type: 'TEXT', characters: 'Hello World', style: { fontFamily: 'Inter', fontSize: 16, fontWeight: 500 } }; // textExtractor sets: // node.text = 'Hello World' // node.textStyle = { fontFamily: 'Inter', fontSize: 16, fontWeight: 500 } ``` -------------------------------- ### Telemetry Capture Get Figma Data Call Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/EXPORTS.md Captures the outcome and context of a `getFigmaData` operation for telemetry purposes. ```typescript captureGetFigmaDataCall(outcome: CallOutcome, context: CaptureContext): void ``` -------------------------------- ### createServer Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-mcp-server.md Creates an MCP server instance with registered Figma tools. Allows configuration of authentication, transport mode, output format, and image download behavior. ```APIDOC ## createServer(authOptions, serverOptions) ### Description Creates an MCP server instance with registered Figma tools. ### Method Signature ```typescript function createServer( authOptions: FigmaAuthOptions, { transport, outputFormat = "tree", skipImageDownloads = false, imageDir }: CreateServerOptions, ): McpServer ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### `authOptions` (`FigmaAuthOptions`) - **Type**: `FigmaAuthOptions` - **Required**: yes - **Description**: Figma authentication credentials #### `serverOptions` (`CreateServerOptions`) - **Type**: `CreateServerOptions` - **Required**: yes - **Description**: Server configuration - **`transport`** (`"stdio" | "http"`) - **Required**: yes - **Description**: Transport mode (stdio for direct integration, http for stateless servers) - **`outputFormat`** (`"tree" | "json" | "yaml"`) - **Required**: no - **Default**: `"tree"` - **Description**: Response serialization format - **`skipImageDownloads`** (boolean) - **Required**: no - **Default**: `false` - **Description**: Disable the `download_figma_images` tool if true - **`imageDir`** (string) - **Required**: no - **Description**: Directory base for image downloads (defaults to cwd) ### Returns - **Type**: `McpServer` - **Description**: An initialized MCP server ready to be connected to a transport. ### Throws None during creation; errors occur when tools are invoked. ### Example ```typescript import { createServer } from 'figma-developer-mcp'; const server = createServer( { figmaApiKey: 'fdk_...', figmaOAuthToken: '', useOAuth: false }, { transport: 'http', outputFormat: 'json' } ); // Connect to transport const transport = new StreamableHTTPServerTransport({ ... }); await server.connect(transport); ``` ``` -------------------------------- ### Get Error Meta Utility Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/EXPORTS.md Extracts metadata such as HTTP status and error code from an unknown error object. ```typescript getErrorMeta(error: unknown): { http_status?: number; error_code?: string } ``` -------------------------------- ### MCP Server Creation Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/EXPORTS.md Use `createServer` to instantiate an MCP server. Requires authentication options and server configuration. ```typescript createServer( authOptions: FigmaAuthOptions, options: CreateServerOptions ): McpServer ``` -------------------------------- ### Download with Cropping and Dimensions (JSON) Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/mcp-tools.md Configure image downloads to include cropping and dimensions. Set `needsCropping` to true and provide a `cropTransform` matrix. Set `requiresImageDimensions` to true to generate CSS variables. ```json { "fileKey": "abc123xyz", "localPath": "crops", "nodes": [ { "nodeId": "1:50", "fileName": "image_cropped.png", "needsCropping": true, "cropTransform": [[1, 0, 10], [0, 1, 20], [0, 0, 1]], "requiresImageDimensions": true } ], "type": "download_figma_images" } ``` -------------------------------- ### Create MCP Server Instance Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-mcp-server.md Use `createServer` to instantiate an MCP server with registered Figma tools. Configure authentication and server options like transport mode and output format. ```typescript function createServer( authOptions: FigmaAuthOptions, { transport, outputFormat = "tree", skipImageDownloads = false, imageDir }: CreateServerOptions, ): McpServer ``` ```typescript import { createServer } from 'figma-developer-mcp'; const server = createServer( { figmaApiKey: 'fdk_...', figmaOAuthToken: '', useOAuth: false }, { transport: 'http', outputFormat: 'json' } ); // Connect to transport const transport = new StreamableHTTPServerTransport({ ... }); await server.connect(transport); ``` -------------------------------- ### Server Lifecycle Functions in MCP Server Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/EXPORTS.md Functions to manage the lifecycle of the MCP server, including starting and stopping HTTP servers. ```typescript startServer(config): Promise ``` ```typescript startHttpServer(host, port, baseAuth, serverOptions): Promise ``` ```typescript stopHttpServer(): Promise ``` -------------------------------- ### Initialize FigmaService Client Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-figma-service.md Instantiate the FigmaService with authentication options. Requires either an API key or an OAuth token. ```typescript import { FigmaService } from 'figma-developer-mcp'; const figmaService = new FigmaService({ figmaApiKey: 'fdk_xxxxxxxxxxxxx', figmaOAuthToken: '', useOAuth: false, }); ``` -------------------------------- ### CreateServerOptions Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-mcp-server.md Options used when creating a new server instance, specifying transport and operational behaviors. ```APIDOC ## `CreateServerOptions` ### Description Options for server creation. ### Type Definition ```typescript type CreateServerOptions = { transport: ServerTransport outputFormat?: OutputFormat skipImageDownloads?: boolean imageDir?: string } ``` ### Properties - **transport** (`"stdio" | "http"`) - Required - Transport protocol - **outputFormat** (`"tree" | "json" | "yaml"`) - Optional - Response format (defaults to "tree") - **skipImageDownloads** (boolean) - Optional - Disable image download tool if true (defaults to false) - **imageDir** (string) - Optional - Directory for downloaded images ``` -------------------------------- ### Load Custom Environment File Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/configuration.md Specify a custom `.env` file for configuration using the `--env` CLI flag. This allows for externalizing settings. ```bash npx figma-developer-mcp --env=/path/to/.env.custom ``` -------------------------------- ### Disable Telemetry in MCP Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/configuration.md Starts the MCP tool with telemetry disabled by setting the DO_NOT_TRACK environment variable to 1. This respects user privacy preferences. ```bash DO_NOT_TRACK=1 npx figma-developer-mcp \ --figma-api-key=fdk_xxxxxxxxxxxxx ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/glips/figma-context-mcp/blob/main/CONTRIBUTING.md Create a .env file in the root directory to set up environment variables, including your Figma API key. ```dotenv FIGMA_API_KEY=your_figma_api_key_here ``` -------------------------------- ### Get Figma Data Request Schema Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/mcp-tools.md Defines the structure for requesting Figma data, including file key, optional node ID, and depth. ```json { "type": "object", "properties": { "fileKey": { "type": "string", "pattern": "^[a-zA-Z0-9]+$", "description": "The key of the Figma file to fetch, often found in a provided URL like figma.com/(file|design)//..." }, "nodeId": { "type": "string", "pattern": "^I?\d+[:|-]\d+(?:;\d+[:|-]\d+)*$", "description": "The ID of the node to fetch, often found as URL parameter node-id=, always use if provided. Use format '1234:5678' for a standard node, or 'I5666:180910;1:10515;1:10336' for a deeply nested instance node (the semicolon-joined path represents the instance override chain — it's still a single node ID, not multiple nodes).", "optional": true }, "depth": { "type": "number", "description": "OPTIONAL. Do NOT use unless explicitly requested by the user. Controls how many levels deep to traverse the node tree.", "optional": true } }, "required": ["fileKey"] } ``` -------------------------------- ### FigmaService Constructor Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-figma-service.md Initializes the FigmaService client with authentication options. ```APIDOC ## Constructor FigmaService ### Description Initializes the FigmaService client with authentication credentials. ### Parameters #### Path Parameters - **authOptions** (FigmaAuthOptions) - Required - Authentication credentials (API key or OAuth token) ### Request Example ```typescript import { FigmaService } from 'figma-developer-mcp'; const figmaService = new FigmaService({ figmaApiKey: 'fdk_xxxxxxxxxxxxx', figmaOAuthToken: '', useOAuth: false, }); ``` ``` -------------------------------- ### Server Creation Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/EXPORTS.md Function to create an MCP server instance. ```APIDOC ## createServer ### Description Creates a new MCP server instance with specified authentication and server options. ### Signature ```typescript createServer(authOptions, serverOptions): McpServer ``` ``` -------------------------------- ### Project File Structure Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/INDEX.md Overview of the project's directory and file organization. ```plaintext src/ ├─ bin.ts # Executable entry point ├─ index.ts # Library exports ├─ mcp-server.ts # MCP server exports ├─ config.ts # Configuration resolution ├─ server.ts # Stdio/HTTP transport selection ├─ mcp/ # MCP protocol implementation │ ├─ index.ts # Server creation │ ├─ tools/ # Tool definitions │ │ ├─ get-figma-data-tool.ts │ │ └─ download-figma-images-tool.ts │ ├─ progress.ts # Progress reporting │ └─ validation-capture.ts # Telemetry ├─ extractors/ # Extraction system │ ├─ index.ts # Exports │ ├─ design-extractor.ts # API response parsing │ ├─ node-walker.ts # Tree traversal │ ├─ built-in.ts # Layout, text, visuals, components │ ├─ finalize.ts # Style deduplication │ └─ types.ts # Type definitions ├─ transformers/ # Property converters │ ├─ layout.ts # Layout/flex/grid │ ├─ text.ts # Typography │ ├─ style.ts # Colors, strokes │ ├─ effects.ts # Shadows, blurs │ ├─ component.ts # Component metadata │ └─ style/ # Style submodules │ ├─ color.ts │ ├─ gradient.ts │ ├─ image.ts │ └─ * ├─ services/ # Business logic │ ├─ figma.ts # Figma API client │ ├─ get-figma-data.ts # Fetch+simplify pipeline │ ├─ download-figma-images.ts # Image download │ ├─ get-figma-data-metrics.ts # Metrics/telemetry │ └─ errors/ # Error messages ├─ utils/ # Helpers │ ├─ fetch-json.ts # HTTP client │ ├─ serialize.ts # Format selection │ ├─ serialize-tree.ts # Tree visualization │ ├─ yaml-dump.ts # YAML serialization │ ├─ image-processing.ts # Crop/dimensions │ ├─ local-path.ts # Path security │ ├─ figma-url.ts # URL parsing │ ├─ error-meta.ts # Error inspection │ ├─ logger.ts # Logging │ ├─ proxy-env.ts # Proxy detection │ └─ * ├─ telemetry/ # Usage tracking │ ├─ index.ts │ ├─ client.ts │ ├─ capture.ts │ └─ types.ts └─ tests/ # Test suites └─ *.test.ts ``` -------------------------------- ### Define CreateServerOptions Type Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/types.md Specifies configuration options for creating a server. Allows selection of transport protocol (stdio or http) and optional parameters for output format, skipping image downloads, and specifying an image directory. ```typescript type CreateServerOptions = { transport: "stdio" | "http"; outputFormat?: OutputFormat; skipImageDownloads?: boolean; imageDir?: string; } ``` -------------------------------- ### Format Code Source: https://github.com/glips/figma-context-mcp/blob/main/CLAUDE.md Applies Prettier formatting to the project files. ```bash pnpm format ``` -------------------------------- ### Fetch Figma Node with Depth Limit Request Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/mcp-tools.md Example request to fetch data for a specific node within a Figma file, with a limit on the traversal depth. ```json { "fileKey": "abc123xyz", "nodeId": "1:100", "depth": 3, "type": "get_figma_data" } ``` -------------------------------- ### Element Deduplication Example Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/internals-and-algorithms.md Illustrates how identical node bodies are replaced with a template reference after element deduplication. This significantly reduces context size for designs with repeated elements. ```typescript // Before finalization: nodes: [ { id: '1', type: 'RECTANGLE', fills: [...], layout: {...} }, { id: '2', type: 'RECTANGLE', fills: [...], layout: {...} }, // Identical body { id: '3', type: 'FRAME', children: ['1', '2'] }, ] // After finalization: nodes: [ { id: '1', template: 'EL-abc123def' }, { id: '2', template: 'EL-abc123def' }, { id: '3', type: 'FRAME', children: ['1', '2'] }, ], elements: { 'EL-abc123def': { type: 'RECTANGLE', fills: [...], layout: {...} } } ``` -------------------------------- ### Figma Data JSON Format Example Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/mcp-tools.md Shows the JSON representation of Figma design data, including node properties like ID, name, type, and children. ```json { "name": "My Design File", "nodes": [ { "id": "1:1", "name": "Page 1", "type": "PAGE", "children": [ { "id": "2:1", "name": "Header", "type": "FRAME", "layout": { "mode": "row" } } ] } ], "globalVars": { "styles": {} } } ``` -------------------------------- ### Initialize Figma Service with Personal Access Token Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/api-reference-figma-service.md Use this method for authentication when a Personal Access Token (API Key) is available. Ensure `useOAuth` is set to `false`. ```typescript const service = new FigmaService({ figmaApiKey: 'fdk_xxxxxxxxxxxxx', figmaOAuthToken: '', useOAuth: false, }); ``` -------------------------------- ### Fetch Specific Figma Node Request Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/mcp-tools.md Example request to fetch data for a specific node (e.g., a frame) within a Figma file, identified by its node ID. ```json { "fileKey": "abc123xyz", "nodeId": "1:100", "type": "get_figma_data" } ``` -------------------------------- ### getServerConfig Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/services-and-utilities.md Resolves complete server configuration from CLI arguments and environment variables. ```APIDOC ## getServerConfig(flags) ### Description Resolves complete server configuration from CLI arguments and environment variables. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **flags** (ServerFlags) - Required - The CLI flags. ### Returns * **ServerConfig** - The resolved server configuration. ``` -------------------------------- ### Proxy Configuration Utilities Source: https://github.com/glips/figma-context-mcp/blob/main/_autodocs/EXPORTS.md Utilities for checking proxy environment variables and setting the proxy mode. ```APIDOC ## hasProxyEnv ### Description Checks if proxy environment variables are set. ### Returns - **boolean** - True if proxy environment variables are set, false otherwise. ``` ```APIDOC ## setProxyMode ### Description Sets the proxy mode. ### Parameters - **mode** ('explicit' | 'env') - Required - The proxy mode to set. ```