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);
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. While it mentions the tool 'generates high-quality frontend component code' and uses 'PNG preview images for visual validation', it doesn't clarify critical behaviors like whether this is a read-only operation, potential rate limits, authentication requirements, or what happens if the Figma file is inaccessible. The description adds some context but leaves significant gaps for a tool that interacts with external resources.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is front-loaded with the core purpose ('Generate pixel-perfect frontend code from Figma designs') and efficiently details key features in two sentences. Each sentence adds value, such as mentioning parsing, validation, and tech stack support, with no redundant information. It could be slightly more concise by combining some clauses, but overall it's well-structured.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of generating code from designs, the description covers the what and how but lacks completeness. No annotations or output schema are provided, so it doesn't address behavioral traits like error handling, output format, or dependencies. It mentions 'visual validation' and 'project configurations', but for a tool with no structured safety or output info, more context on limitations or results would be beneficial.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, with clear documentation for both parameters (fileKey and nodeId). The description doesn't add any parameter-specific information beyond what's in the schema, such as examples or constraints on format. With high schema coverage, the baseline score of 3 is appropriate, as the description doesn't compensate but also doesn't need to.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with specific verbs ('generate', 'parse', 'combine') and resources ('pixel-perfect frontend code', 'Figma designs'). It distinguishes itself from sibling tools like 'Download-Figma-Images' or 'extract-color-vars' by focusing on code generation rather than asset extraction or project setup.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context through phrases like 'automatically parses Figma DSL structure' and 'supports automatic detection of project configurations', suggesting it's for converting designs to code. However, it lacks explicit guidance on when to use this versus alternatives like 'api-automation' or 'similarity-figma', and doesn't mention prerequisites or exclusions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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