Skip to main content
Glama

analyze_figma_file

Analyze Figma file structure to extract node hierarchies and understand component relationships for design system documentation and development handoff.

Instructions

Analyze a Figma file structure to understand its nodes and hierarchy

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
figmaUrlYesThe URL of the Figma file to analyze
depthNoOptional depth parameter to limit the node tree depth

Implementation Reference

  • The main execution function for the analyze_figma_file tool. Extracts Figma IDs from URL, fetches and generates the node tree structure using Figma API, and returns formatted text content with the tree JSON or error message.
    async function doAnalyzeFigmaFile(figmaUrl: string, depth?: number): Promise<CallToolResult> {
      try {
        // Get Figma API Key
        const figmaApiKey = process.env.FIGMA_API_KEY;
        if (!figmaApiKey) {
          throw new Error('FIGMA_API_KEY not configured');
        }
        
        // Extract file ID and node ID from URL
        const { fileId, nodeId } = extractFigmaIds(figmaUrl);
        
        if (!fileId) {
          throw new Error('Could not extract file ID from URL');
        }
        
        if (!nodeId) {
          throw new Error('No node ID specified in URL');
        }
        
        // Generate the node tree
        const treeGenerator = new FigmaTreeGenerator(figmaApiKey);
        const tree = await treeGenerator.generateNodeTree(fileId, nodeId, depth);
        
        // Return the result
        return {
          content: [
            {
              type: 'text',
              text: `Successfully analyzed Figma file: ${figmaUrl}`,
            },
            {
              type: 'text',
              text: `File ID: ${fileId}`,
            },
            {
              type: 'text',
              text: `Node ID: ${nodeId}`,
            },
            {
              type: 'text',
              text: 'Node Tree Structure:',
            },
            {
              type: 'text',
              text: JSON.stringify(tree, null, 2),
            },
          ],
        };
      } catch (error) {
        console.error('Error analyzing Figma file:', error);
        
        // Return error as text content instead of throwing
        return {
          content: [
            {
              type: 'text',
              text: `Error analyzing Figma file: ${error instanceof Error ? error.message : 'Unknown error'}`
            }
          ]
        };
      }
    }
  • src/index.ts:49-71 (registration)
    Tool definition with schema and registration in the listTools handler.
    const ANALYZE_FIGMA_FILE: Tool = {
      name: 'analyze_figma_file',
      description: 'Analyze a Figma file structure to understand its nodes and hierarchy',
      inputSchema: {
        type: 'object',
        properties: {
          figmaUrl: {
            type: 'string',
            description: 'The URL of the Figma file to analyze',
          },
          depth: {
            type: 'number',
            description: 'Optional depth parameter to limit the node tree depth',
          },
        },
        required: ['figmaUrl'],
      },
    };
    
    // Register tools handler
    server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: [ANALYZE_FIGMA_FILE],
    }));
  • src/index.ts:74-81 (registration)
    Registration of the callTool handler that dispatches to doAnalyzeFigmaFile for the analyze_figma_file tool.
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
      if (request.params.name === 'analyze_figma_file') {
        const input = request.params.arguments as { figmaUrl: string; depth?: number };
        return doAnalyzeFigmaFile(input.figmaUrl, input.depth);
      }
    
      throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${request.params.name}`);
    });
  • Supporting helper function used by the handler to extract Figma file ID and node ID from the input URL.
    export function extractFigmaIds(figmaUrl: string): { fileId: string, nodeId: string | null } {
      try {
        const url = new URL(figmaUrl);
        
        // Extract the file ID from the URL path
        const pathParts = url.pathname.split('/');
        let fileIdIndex = -1;
        
        // Look for file/design/proto in the URL path
        for (let i = 0; i < pathParts.length; i++) {
          if (pathParts[i] === 'file' || pathParts[i] === 'design' || pathParts[i] === 'proto') {
            fileIdIndex = i + 1;
            break;
          }
        }
        
        if (fileIdIndex === -1 || fileIdIndex >= pathParts.length) {
          throw new Error('Invalid Figma URL format: missing file/design/proto segment');
        }
        
        const fileId = pathParts[fileIdIndex];
        
        // Extract node ID from query parameters if present
        const nodeId = url.searchParams.get('node-id') || null;
        
        return { fileId, nodeId };
      } catch (error) {
        throw new Error('Invalid Figma URL format');
      }
    }
  • Core helper class for generating and processing the Figma node tree by calling the Figma API and recursively building the hierarchy (stops at INSTANCE nodes).
    export class FigmaTreeGenerator {
      private readonly apiKey: string;
      private readonly baseUrl = 'https://api.figma.com/v1';
    
      constructor(apiKey: string) {
        this.apiKey = apiKey;
      }
    
      async generateNodeTree(fileId: string, nodeId: string, depth?: number): Promise<FigmaNode> {
        try {
          // Construct URL with optional depth parameter
          let url = `${this.baseUrl}/files/${fileId}/nodes?ids=${nodeId}`;
          if (depth !== undefined) {
            url += `&depth=${depth}`;
          }
          
          // Make request to Figma API
          const response = await axios.get<FigmaNodesResponse>(
            url,
            {
              headers: {
                'X-Figma-Token': this.apiKey
              }
            }
          );
    
          // Check if the node exists in the response
          if (!response.data.nodes[nodeId]) {
            throw new Error(`Node ${nodeId} not found in file ${fileId}`);
          }
    
          // Extract the document from the response
          const nodeData = response.data.nodes[nodeId].document;
          
          // Process the node tree
          return this.processNode(nodeData);
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : 'Unknown error';
          throw new Error(`Failed to fetch Figma node tree: ${errorMessage}`);
        }
      }
    
      private processNode(node: FigmaNode): FigmaNode {
        // Create a new node object to avoid mutating the original
        const processedNode: FigmaNode = {
          id: node.id,
          name: node.name,
          type: node.type
        };
    
        // If this is an INSTANCE node, we stop traversal here
        // By not adding children property, we indicate this is a terminal node
        if (node.type === 'INSTANCE') {
          return processedNode;
        }
    
        // If node has children, process them recursively
        if (node.children && node.children.length > 0) {
          processedNode.children = node.children.map(child => this.processNode(child));
        } else {
          processedNode.children = [];
        }
    
        return processedNode;
      }
    }
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. It states the tool analyzes structure but doesn't mention whether it's read-only, requires authentication, has rate limits, returns specific formats, or handles errors. For a tool with no annotation coverage, this leaves significant gaps in understanding its behavior.

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 a single, efficient sentence that front-loads the purpose. It avoids redundancy and is appropriately sized for a simple tool, though it could be slightly more informative without losing conciseness.

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

Completeness2/5

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

Given no annotations and no output schema, the description is incomplete. It doesn't explain what the analysis returns, how nodes are structured, or any behavioral traits. For a tool that likely outputs complex hierarchical data, this lack of context makes it inadequate for full understanding.

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?

The schema description coverage is 100%, so parameters are well-documented in the schema. The description adds minimal value beyond implying analysis of 'nodes and hierarchy', which relates to the depth parameter. It doesn't provide additional syntax or format details, so baseline 3 is appropriate as the schema does the heavy lifting.

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

Purpose4/5

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

The description clearly states the action ('analyze') and resource ('Figma file structure'), specifying the goal is to 'understand its nodes and hierarchy'. It's specific about what the tool does, though without sibling tools, differentiation isn't needed. However, it's slightly vague on the exact output or analysis type beyond 'understand'.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives, prerequisites, or constraints. It mentions analyzing file structure but doesn't specify use cases like design review, extraction, or debugging. With no sibling tools, this is less critical, but still lacks operational context.

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

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/moonray/mcp-figma'

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