Framelink MCP for Figma

repository·main·Indexed 12 days ago

https://github.com/glips/figma-context-mcp

A Model Context Protocol (MCP) server that provides AI coding agents, such as Cursor, with direct access to Figma design data. It translates raw Figma API responses into optimized metadata for layout and styling to enable accurate, one-shot UI implementation. Includes a Figma Data Extractor system with built-in extractors for layout, text, visuals, and components, as well as support for custom ExtractorFn implementations. Version 0.13.2.

Tokens
17.2K
Snippets
56
Records
73
Agent score
96%

What's inside Framelink MCP for Figma

  1. How the Figma Data Extractor architecture works

    main

    The extraction system is organized into three distinct layers to ensure efficiency and composability:

    1. Strategy Layer: Where you define what you want to extract (e.g., choosing specific extractors).
    2. Traversal Layer: A single-pass tree walking mechanism that visits nodes and applies the configured extractors.
    3. Extraction Layer: Pure functions that perform the actual transformation of individual node data into the result object.

    This architecture ensures that no matter how many extractors you use, the system only performs a single tree walk, making it highly efficient.

  2. How Framelink MCP for Figma works with AI agents

    main

    The Framelink MCP for Figma server provides AI-powered coding tools (like Cursor) with direct access to Figma design data. Instead of relying on screenshots, the agent can fetch precise layout and styling metadata.

    Workflow:

    1. Open your IDE's chat (e.g., agent mode in Cursor).
    2. Paste a link to a Figma file, frame, or group.
    3. Ask the agent to implement the design.
    4. The agent uses the MCP server to fetch simplified, relevant metadata from the Figma API to write accurate code.

    This process reduces context noise by translating raw Figma API responses into only the most relevant styling and layout information for the LLM.

  3. Use the Figma Data Extractor system

    main

    The Figma Data Extractor system allows you to perform single-pass data extraction from Figma design files. You can compose different extractors to optimize the data returned, which is particularly useful for managing LLM context windows.

    Use extractFromDesign to process nodes with a specific set of extractors and optional configuration.

    Basic Usage Patterns

    • Extract everything: Use allExtractors to replicate standard parsing behavior.
    • Content planning: Use layoutAndText to get structure and text.
    • Copy audits: Use contentOnly combined with a nodeFilter to target TEXT nodes.

    Configuration Options

    • maxDepth: Limits how deep the traversal goes into the node tree.
    • nodeFilter: A predicate function (node) => boolean used to include or exclude specific nodes during traversal.
    import { extractFromDesign, allExtractors, layoutAndText, contentOnly } from "figma-mcp/extractors";
    
    // Extract everything
    const fullData = extractFromDesign(nodes, allExtractors);
    
    // Extract only layout + text for content planning
    const layoutData = extractFromDesign(nodes, layoutAndText, {
      maxDepth: 3,
    });
    
    // Extract only text content for copy audits
    const textData = extractFromDesign(nodes, contentOnly, {
      nodeFilter: (node) => node.type === "TEXT",
    });
  4. Configure Framelink MCP for Figma in your IDE

    main

    To use the figma-developer-mcp server, you must add it to your MCP configuration file. You will need a Figma personal access token.

    MacOS / Linux

    Add the following to your configuration file:

    {
      "mcpServers": {
        "Framelink MCP for Figma": {
          "command": "npx",
          "args": ["-y", "figma-developer-mcp", "--figma-api-key=YOUR-KEY", "--stdio"]
        }
      }
    }

    Windows

    Add the following to your configuration file:

    {
      "mcpServers": {
        "Framelink MCP for Figma": {
          "command": "cmd",
          "args": ["/c", "npx", "-y", "figma-developer-mcp", "--figma-api-key=YOUR-KEY", "--stdio"]
        }
      }
    }

    Alternative Configuration via Environment Variables

    Instead of using command-line arguments, you can provide credentials via the env field in your configuration using:

    • FIGMA_API_KEY
    • PORT
  5. How configuration resolution works

    main

    The project uses a hierarchical resolution strategy to determine configuration values. This allows users to override settings easily without changing permanent environment variables.

    Priority Order:

    1. CLI Flags: Explicit arguments passed to the command line.
    2. Environment Variables: Values found in the shell environment or loaded from a .env file.
    3. Defaults: Hardcoded fallback values defined in the source code.

    When getServerConfig is called, it also tracks the source (e.g., "cli", "env", or "default") for each setting, which is printed to the console in non-stdio mode to help with debugging.

  6. Understand the SimplifiedDesign output format

    main

    The SimplifiedDesign interface represents the final, processed output of a Figma design extraction. It is a structured representation designed to be more compact and developer-friendly than the raw Figma API response.

    Key components of SimplifiedDesign:

    • nodes: An array of top-level SimplifiedNode objects.
    • components & componentSets: Records of component definitions extracted from the design.
    • globalVars: A collection of styles (text, fills, layout, strokes, effects) that are shared across the design.
    • elements: A dictionary of deduplicated element bodies. To save space, if multiple nodes share the same visual properties, they are replaced by a template reference pointing to a key in this object (e.g., EL-xxxxxxxx).
  7. Configure Figma Authentication

    main

    The server requires Figma credentials to access data. You can provide authentication via a Personal Access Token or an OAuth Bearer Token. The system follows a priority chain: CLI flag → Environment Variable → Default.

    Authentication Methods

    1. Personal Access Token: Uses the X-Figma-Token header. Provide via --figma-api-key or FIGMA_API_KEY.
    2. OAuth Bearer Token: Uses the Authorization: Bearer header. Provide via --figma-oauth-token or FIGMA_OAUTH_TOKEN. If an OAuth token is detected, the system automatically switches to OAuth mode.

    Required Credentials

    For stdio mode or the fetch CLI, global credentials must be resolvable at startup. If neither a Personal Access Token nor an OAuth token is provided, the server will throw a UsageError.

    export interface ServerFlags {
      figmaApiKey?: string;
      figmaOauthToken?: string;
      // ...
    }
    
    // Example Environment Variables:
    // FIGMA_API_KEY=your_token_here
    // FIGMA_OAUTH_TOKEN=your_oauth_token_here
  8. Create a custom ExtractorFn

    main

    You can extend the system by creating custom extractors that implement the ExtractorFn type. An extractor is a function that receives the current node, the result object (which you can mutate to add new properties), and a context object.

    import type { ExtractorFn } from "figma-mcp/extractors";
    
    // Custom extractor that identifies design system components
    const designSystemExtractor: ExtractorFn = (node, result, context) => {
      if (node.name.startsWith("DS/")) {
        result.isDesignSystemComponent = true;
        result.dsCategory = node.name.split("/")[1];
      }
    };
    
    // Use it with other extractors
    const data = extractFromDesign(nodes, [layoutExtractor, designSystemExtractor]);
    import type { ExtractorFn } from "figma-mcp/extractors";
    
    // Custom extractor that identifies design system components
    const designSystemExtractor: ExtractorFn = (node, result, context) => {
      if (node.name.startsWith("DS/")) {
        result.isDesignSystemComponent = true;
        result.dsCategory = node.name.split("/")[1];
      };
    };
    
    // Use it with other extractors
    const data = extractFromDesign(nodes, [layoutExtractor, designSystemExtractor]);
  9. Configure design extraction with TraversalOptions

    main

    When using the design extraction tools, you can provide a TraversalOptions object to control the depth of the walk, filter specific nodes, or modify the resulting tree structure.

    Key options include:

    • maxDepth: Limits how deep the extractor traverses the Figma node tree.
    • nodeFilter: A predicate function (node: FigmaDocumentNode) => boolean used to include or exclude specific Figma nodes.
    • afterChildren: A lifecycle hook called after a node's children have been processed. It allows you to mutate the SimplifiedNode being built and control which children are included in the final output by returning a filtered array of SimplifiedNode[].
    • nodeCounter: An optional NodeCounter object. If provided, the walker will increment this object, allowing you to track live progress or final node counts.
    const options: TraversalOptions = {
      maxDepth: 5,
      nodeFilter: (node) => node.type !== 'RECTANGLE', // Example: skip rectangles
      afterChildren: (node, result, children) => {
        // Example: filter out children with specific properties
        return children.filter(child => child.type !== 'TEXT');
      },
      nodeCounter: { count: 0 }
    };
  10. Configure proxy settings in the MCP server

    main

    The server handles proxying to api.figma.com based on the config.proxy value in ServerConfig:

    ValueResult
    config.proxy = 'some-url'Uses ProxyAgent with the provided URL.
    config.proxy = 'none'Disables proxying (uses Node's default, bypassing system-level proxy env vars).
    config.proxy is undefined AND proxy env vars existUses EnvHttpProxyAgent to route through environment-defined proxies.
    OtherwiseUses Node's default dispatcher.

    Warning: If config.isStdioMode is true and imageDir is set to 'default', the server will warn via stderr that images will be saved in the server's current working directory. It is recommended to explicitly set IMAGE_DIR or pass --image-dir to avoid files being saved in unexpected locations (like an MCP client's installation directory).

  11. Configure CreateServerOptions

    main

    When calling createServer, you can pass the following options to control the server's behavior:

    OptionTypeDefaultDescription
    transport"stdio" | "http"RequiredThe communication protocol used by the MCP server.
    outputFormatOutputFormat"tree"The serialization format for the Figma data returned to the agent.
    skipImageDownloadsbooleanfalseIf true, the downloadFigmaImagesTool will not be registered with the server.
    imageDirstringundefinedThe directory where downloaded Figma images will be stored. Required if skipImageDownloads is false and you use the image download tool.
    type CreateServerOptions = {
      transport: ServerTransport; // "stdio" | "http"
      outputFormat?: OutputFormat;
      skipImageDownloads?: boolean;
      imageDir?: string;
    };
  12. Reference built-in Figma extractors and combinations

    main

    The module provides several pre-defined extractors and convenience combinations for common use cases.

    Individual Extractors

    • layoutExtractor: Extracts layout properties like positioning, sizing, and flex properties.
    • textExtractor: Extracts text content and typography styles.
    • visualsExtractor: Extracts visual appearance including fills, strokes, effects, opacity, and borders.
    • componentExtractor: Extracts component instance data.

    Convenience Combinations

    • allExtractors: Includes everything (replicates standard parseNode behavior).
    • layoutAndText: Combines layout and text extraction.
    • contentOnly: Extracts text content only.
    • visualsOnly: Extracts visual styles only.
    • layoutOnly: Extracts layout properties only.