Skip to main content
Glama

extract-latest-components

Extract newly added components from Figma designs to generate React Native components with proper typing and styling.

Instructions

Extract newly added components from Figma file

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Handler function for the 'extract-latest-components' tool. It fetches Figma data and calls generateComponent with the 'validation' flag set to true to extract only newly added (non-existing) components.
    server.tool(
      'extract-latest-components',
      'Extract newly added components from Figma file',
      async (extra) => {
        try {
          // Fetch Figma file data
          logger.info('Fetching Figma file data...')
    
          // const data = await response.json()
          const data = await fetchFigmaData()
          logger.info('Successfully fetched Figma file data')
    
          // Process the component data
          const result = await generateComponent(data, true)
          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}`,
              },
            ],
          }
        }
      }
    )
  • Main helper function that implements the component extraction logic from Figma data. The 'validation' parameter (true for latest components) filters to only process components that do not yet exist on disk.
    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 fetch the Figma file data using the provided token and file ID.
    export async function fetchFigmaData() {
      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()
        return {
          isError: true,
          content: [
            {
              type: 'text' as const,
              text: `Failed to fetch Figma file: ${response.status} ${response.statusText} - ${errorText}`,
            },
          ],
        }
      }
    
      return await response.json()
    }
  • src/index.ts:104-143 (registration)
    Registration of the 'extract-latest-components' tool using server.tool.
    server.tool(
      'extract-latest-components',
      'Extract newly added components from Figma file',
      async (extra) => {
        try {
          // Fetch Figma file data
          logger.info('Fetching Figma file data...')
    
          // const data = await response.json()
          const data = await fetchFigmaData()
          logger.info('Successfully fetched Figma file data')
    
          // Process the component data
          const result = await generateComponent(data, true)
          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}`,
              },
            ],
          }
        }
      }
    )
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 mentions 'extract' but doesn't clarify if this is a read-only operation, what permissions are needed, how 'newly added' is determined (e.g., based on timestamps or user input), or what the output format might be. This leaves significant gaps for a tool with zero annotation coverage.

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 states the tool's purpose without any wasted words. It's appropriately sized and front-loaded, making it easy for an agent to parse quickly.

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 lack of annotations and output schema, the description is incomplete. It doesn't explain what 'newly added' means, how the extraction works, or what the result looks like (e.g., a list of components or metadata). For a tool with zero structured data, this leaves too much ambiguity for reliable agent use.

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 any parameter information, which is acceptable here, but it could hint at implicit inputs (e.g., file identification), so it doesn't reach a perfect score.

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') and resource ('newly added components from Figma file'), making the purpose understandable. However, it doesn't explicitly differentiate from sibling tools like 'extract-components' or 'extract-one-component', which likely handle different scopes of component extraction.

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 its siblings ('extract-components' and 'extract-one-component'). It implies usage for 'newly added components' but doesn't specify what qualifies as 'newly added' or any prerequisites, leaving the agent to guess when this is appropriate.

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