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 || []), })) }

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