Skip to main content
Glama

extract-components

Extract components from Figma designs and generate corresponding GraphQL queries and mutations for React Native development.

Instructions

Extract all components from Figma file and get all graphql queries and mutations

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • src/index.ts:49-102 (registration)
    Registers the 'extract-components' MCP tool, including its description and the inline handler function that fetches Figma data and calls generateComponent to perform the extraction.
    server.tool(
      'extract-components',
      'Extract all components from Figma file and get all graphql queries and mutations',
      async (extra) => {
        try {
          // Fetch Figma file data
          logger.info('Fetching Figma file data...')
          const response = await fetch(
            `https://api.figma.com/v1/files/${FIGMA_FILE}`,
            {
              headers: {
                'X-Figma-Token': FIGMA_TOKEN,
              },
            }
          )
    
          if (!response.ok) {
            const errorText = await response.text()
            throw new Error(
              `Failed to fetch Figma file: ${response.status} ${response.statusText} - ${errorText}`
            )
          }
    
          const data = await response.json()
          logger.info('Successfully fetched Figma file data')
    
          // Process the component data
          const result = await generateComponent(data)
          logger.info('Component extraction successful')
    
          // Return the result to the client
          return {
            // componentsData: result.componentSets, // Pass the structured component data
            content: [
              {
                type: 'text' as const,
                text: result.message,
              },
            ],
          }
        } catch (error: any) {
          logger.error('Error extracting components:', error)
          return {
            isError: true,
            content: [
              {
                type: 'text' as const,
                text: `Error extracting components: ${error.message}`,
              },
            ],
          }
        }
      }
    )
  • Inline handler function for the 'extract-components' tool. Fetches the Figma file using the provided token and file ID, then delegates extraction to generateComponent helper.
    async (extra) => {
      try {
        // Fetch Figma file data
        logger.info('Fetching Figma file data...')
        const response = await fetch(
          `https://api.figma.com/v1/files/${FIGMA_FILE}`,
          {
            headers: {
              'X-Figma-Token': FIGMA_TOKEN,
            },
          }
        )
    
        if (!response.ok) {
          const errorText = await response.text()
          throw new Error(
            `Failed to fetch Figma file: ${response.status} ${response.statusText} - ${errorText}`
          )
        }
    
        const data = await response.json()
        logger.info('Successfully fetched Figma file data')
    
        // Process the component data
        const result = await generateComponent(data)
        logger.info('Component extraction successful')
    
        // Return the result to the client
        return {
          // componentsData: result.componentSets, // Pass the structured component data
          content: [
            {
              type: 'text' as const,
              text: result.message,
            },
          ],
        }
      } catch (error: any) {
        logger.error('Error extracting components:', error)
        return {
          isError: true,
          content: [
            {
              type: 'text' as const,
              text: `Error extracting components: ${error.message}`,
            },
          ],
        }
      }
    }
  • Core helper function that implements the component extraction logic from Figma document data. Finds the 'Components' page, iterates over component sets, extracts props and children recursively, and returns structured data.
    export async function generateComponent(
      component: any,
      validation: boolean = false,
      componentToExtract: string = ''
    ) {
      try {
        const { document } = component
        const componentsPage = document.children.find(
          (c: any) => c.name === 'Components'
        )
    
        if (!componentsPage) {
          console.log('No Components page found in document')
          throw new Error('Components page not found in Figma file')
        }
    
        const page = componentsPage.children
        let componentSets = []
        let processedCount = 0
        const checkExisting = (componentName: string) =>
          validation ? !existsSync(`${componentDir}/${componentName}`) : true
    
        const specificComponent = (
          componentName: string,
          componentToExtract: string
        ) =>
          componentToExtract
            ? areSameComponent(componentName, componentToExtract)
            : true
    
        for (const section of page) {
          const { children } = section
          if (!children) continue
    
          for (const item of children) {
            const { type, name } = item
            const componentName = toPascalCase(name)
    
            if (
              type === 'COMPONENT_SET' &&
              checkExisting(componentName) &&
              specificComponent(componentName, componentToExtract)
            ) {
              processedCount++
    
              try {
                const props = extractComponentProps(item.children)
    
                const minified = {
                  name: componentName,
                  props,
                  children: extractComponentChildren(item.children),
                }
                componentSets.push(minified)
              } catch (processError) {
                return {
                  message: `Error processing component ${name}: ${processError}`,
                  componentSets: [],
                }
              }
            }
          }
        }
    
        // Create a formatted result for the user
        const message = `Successfully processed ${processedCount} components.\n\nComponent sets: ${componentSets.length}\nComponent paths:\n${componentSets.map((cs) => `- ${cs.name}`).join('\n')}`
    
        // Return both the result message and the component data
        return {
          message,
          componentSets,
        }
      } catch (error) {
        console.error(`Error generating component: ${error}`)
        throw error
      }
    }
  • Helper function to extract component props from children names, parsing key=value pairs and inferring types, merging duplicates with union types.
    function extractComponentProps(children: any[]) {
      return children
        .flatMap((c: any) => {
          const parts = c.name.split(', ')
          return parts.map((prop: string) => {
            const [key, value] = prop.split('=')
            return {
              name: toCamelCase(key),
              type: value === 'True' || value === 'False' ? 'boolean' : value,
            }
          })
        })
        .reduce((acc: Record<string, any>, prop) => {
          if (!acc[prop.name]) acc[prop.name] = { ...prop }
          else if (!acc[prop.name].type.includes(prop.type))
            acc[prop.name].type = `${acc[prop.name].type} | ${prop.type}`
          return acc
        }, {})
    }
  • Recursive helper to extract the hierarchical children structure of components, preserving name, type, style, fills.
    function extractComponentChildren(children: any[]): ComponentChild[] {
      if (!Array.isArray(children)) return []
    
      return children.map(({ name, children, type, style, fills }) => ({
        name,
        type,
        style,
        fills,
        children: extractComponentChildren(children || []),
      }))
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states what the tool does but lacks details on permissions, rate limits, output format, or whether it's read-only or destructive. For a tool with zero annotation coverage, this is a significant gap in transparency.

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

Conciseness5/5

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

The description is a single, efficient sentence that front-loads the core functionality ('Extract all components from Figma file') and adds secondary action ('get all graphql queries and mutations') without unnecessary elaboration. Every word earns its place.

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 the complexity implied by extracting components and GraphQL queries/mutations, no annotations, and no output schema, the description is incomplete. It lacks details on behavioral traits, output format, and usage context, making it inadequate for informed tool selection.

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

Parameters4/5

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

The tool has 0 parameters, and schema description coverage is 100%, so no parameter documentation is needed. The description doesn't add parameter details beyond the schema, but with no parameters, a baseline of 4 is appropriate as it adequately addresses the lack of parameters.

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 ('extract all components') and target resource ('from Figma file'), and specifies additional functionality ('get all graphql queries and mutations'). It doesn't explicitly differentiate from sibling tools like 'extract-latest-components' or 'extract-one-component', which would require a 5.

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?

No guidance is provided on when to use this tool versus its siblings ('extract-latest-components' and 'extract-one-component'), nor any context about prerequisites or alternatives. The description implies a comprehensive extraction but lacks explicit usage instructions.

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

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