Skip to main content
Glama

Figma-To-Code

Convert Figma designs into production-ready frontend code tailored to your tech stack. Automatically detects project configurations, integrates design standards, and ensures visual validation with generated PNG previews.

Instructions

Generate pixel-perfect frontend code from Figma designs. Automatically parses Figma DSL structure and style information, combines with PNG preview images for visual validation, and generates high-quality frontend component code that matches your project tech stack. Supports automatic detection of project configurations (UnoCSS/TailwindCSS/SCSS etc.) and uses existing style variables and design standards.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fileKeyYesThe key of the Figma file to fetch, often found in a provided URL like figma.com/(file|design)/<fileKey>/...
nodeIdNoThe ID of the node to fetch, often found as URL parameter node-id=<nodeId>, always use if provided

Implementation Reference

  • The main handler (execute function) for the Figma-To-Code tool. Fetches Figma design data as YAML DSL, retrieves PNG preview image, constructs XML prompt with embedded prompt template, DSL, and image content for LLM code generation.
    execute: async ({
      fileKey,
      nodeId,
    }, {
      session,
    }: {
      session: any
    }) => {
      try {
        const figmaService = this.figmaToolsCore.figmaService
        const yamlResult = await this.figmaToolsCore.figmaToCode({
          fileKey,
          nodeId: nodeId || '',
        })
    
        const figmaImg = await figmaService.getImageData(fileKey, nodeId as string)
    
        const figmaImgData = await imageContent({
          url: figmaImg,
        })
        console.log('figmaImgData', figmaImgData)
    
        const prompt: string = `
          <xml>
            <prompt>${figmaToCodePrompt}</prompt>
            <Figma-DSL>${yamlResult}</Figma-DSL>
          </xml>
        `
    
        return {
          content: [
            { type: 'text', text: prompt },
            figmaImgData,
          ],
        }
      } catch (error) {
        const message = error instanceof Error ? error.message : JSON.stringify(error)
        Logger.error(`Error fetching file ${fileKey}:`, message)
        return {
          isError: true,
          content: [{ type: 'text', text: `Error fetching file: ${message}` }],
        }
      }
    },
  • Registration of the Figma-To-Code tool using server.addTool, including name, description, Zod input schema, and execute handler.
    this.server.addTool({
      name: 'Figma-To-Code',
      description: 'Generate pixel-perfect frontend code from Figma designs. Automatically parses Figma DSL structure and style information, combines with PNG preview images for visual validation, and generates high-quality frontend component code that matches your project tech stack. Supports automatic detection of project configurations (UnoCSS/TailwindCSS/SCSS etc.) and uses existing style variables and design standards.',
      parameters: z.object({
        fileKey: z
          .string()
          .describe(
            'The key of the Figma file to fetch, often found in a provided URL like figma.com/(file|design)/<fileKey>/...',
          ),
        nodeId: z
          .string()
          .optional()
          .describe(
            'The ID of the node to fetch, often found as URL parameter node-id=<nodeId>, always use if provided',
          ),
      }),
      execute: async ({
        fileKey,
        nodeId,
      }, {
        session,
      }: {
        session: any
      }) => {
        try {
          const figmaService = this.figmaToolsCore.figmaService
          const yamlResult = await this.figmaToolsCore.figmaToCode({
            fileKey,
            nodeId: nodeId || '',
          })
    
          const figmaImg = await figmaService.getImageData(fileKey, nodeId as string)
    
          const figmaImgData = await imageContent({
            url: figmaImg,
          })
          console.log('figmaImgData', figmaImgData)
    
          const prompt: string = `
            <xml>
              <prompt>${figmaToCodePrompt}</prompt>
              <Figma-DSL>${yamlResult}</Figma-DSL>
            </xml>
          `
    
          return {
            content: [
              { type: 'text', text: prompt },
              figmaImgData,
            ],
          }
        } catch (error) {
          const message = error instanceof Error ? error.message : JSON.stringify(error)
          Logger.error(`Error fetching file ${fileKey}:`, message)
          return {
            isError: true,
            content: [{ type: 'text', text: `Error fetching file: ${message}` }],
          }
        }
      },
    })
  • Input schema using Zod: fileKey (string, Figma file key), nodeId (optional string, specific node ID).
    parameters: z.object({
      fileKey: z
        .string()
        .describe(
          'The key of the Figma file to fetch, often found in a provided URL like figma.com/(file|design)/<fileKey>/...',
        ),
      nodeId: z
        .string()
        .optional()
        .describe(
          'The ID of the node to fetch, often found as URL parameter node-id=<nodeId>, always use if provided',
        ),
    }),
  • Helper method in FigmaToolsCore that fetches and simplifies Figma file/node to JSON (YAML DSL) for the prompt.
    public async figmaToCode({
      fileKey,
      nodeId,
    }: {
      fileKey: string
      nodeId: string
    }) {
    
      const figmaService = this.figmaService
    
      let file: SimplifiedDesign
      if (nodeId) {
        file = await figmaService.getNode(fileKey, nodeId)
      } else {
        file = await figmaService.getFile(fileKey)
      }
    
      Logger.log(`Successfully fetched file: ${file.name}`)
      const { nodes, globalVars, ...metadata } = file
    
      const result = {
        metadata,
        nodes,
        globalVars,
      }
    
      Logger.log('Generating YAML result from file')
      const yamlResult = JSON.stringify(result, null, 2)
    
      Logger.log('Sending result to client')
      Logger.log('content', yamlResult)
    
      return yamlResult
    }
  • Core parsing function that transforms raw Figma API response into a simplified, YAML-friendly design structure (SimplifiedDesign) used as DSL in the prompt. Aggregates components, parses nodes recursively, deduplicates styles into globalVars.
    export function parseFigmaResponse(data: GetFileResponse | GetFileNodesResponse): SimplifiedDesign {
      const aggregatedComponents: Record<string, Component> = {};
      const aggregatedComponentSets: Record<string, ComponentSet> = {};
      let nodesToParse: Array<FigmaDocumentNode>;
    
      if ("nodes" in data) {
        // GetFileNodesResponse
        const nodeResponses = Object.values(data.nodes); // Compute once
        nodeResponses.forEach((nodeResponse) => {
          if (nodeResponse.components) {
            Object.assign(aggregatedComponents, nodeResponse.components);
          }
          if (nodeResponse.componentSets) {
            Object.assign(aggregatedComponentSets, nodeResponse.componentSets);
          }
        });
        nodesToParse = nodeResponses.map((n) => n.document);
      } else {
        // GetFileResponse
        Object.assign(aggregatedComponents, data.components);
        Object.assign(aggregatedComponentSets, data.componentSets);
        nodesToParse = data.document.children;
      }
    
      const sanitizedComponents = sanitizeComponents(aggregatedComponents);
      const sanitizedComponentSets = sanitizeComponentSets(aggregatedComponentSets);
    
      const { name, lastModified, thumbnailUrl } = data;
    
      let globalVars: GlobalVars = {
        styles: {},
      };
    
      const simplifiedNodes: SimplifiedNode[] = nodesToParse
        .filter(isVisible)
        .map((n) => parseNode(globalVars, n))
        .filter((child) => child !== null && child !== undefined);
    
      const simplifiedDesign: SimplifiedDesign = {
        name,
        lastModified,
        thumbnailUrl: thumbnailUrl || "",
        nodes: simplifiedNodes,
        components: sanitizedComponents,
        componentSets: sanitizedComponentSets,
        globalVars,
      };
    
      return removeEmptyKeys(simplifiedDesign);
    }
Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Panzer-Jack/feuse-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server