mcp-design-system-bridge-windsurf

No description

GitHub Stars

0

User Rating

Not Rated

Forks

0

Issues

0

Views

1

Favorites

0

README
MCP Design System Bridge Windsurf

npm version License: MIT code style: prettier

A bidirectional bridge between your IDE and Figma for seamless Design System management. This tool allows you to keep your design system in sync between your codebase and Figma, enabling a more efficient design-to-code workflow.

✨ Features
  • Bidirectional Sync: Keep your design system in sync between Figma and your codebase
  • React Component Generation: Generate React components from Figma designs
  • Design Token Extraction: Extract design tokens (colors, typography, spacing, etc.) from Figma
  • Type Safety: Full TypeScript support for type-safe components and tokens
  • Storybook Integration: Auto-generated Storybook stories for your components
  • CLI Tools: Easy-to-use command line interface for common tasks
  • Customizable: Extend and customize the bridge to fit your workflow
🚀 Installation
# Using npm
npm install mcp-design-system-bridge --save-dev

# Or using yarn
yarn add -D mcp-design-system-bridge
🔧 Configuration

Create a configuration file at the root of your project:

// mcp.config.js
module.exports = {
  // Required: Your Figma personal access token
  figmaToken: process.env.FIGMA_ACCESS_TOKEN,
  
  // Required: Your Figma file key (found in the URL)
  fileKey: 'YOUR_FIGMA_FILE_KEY',
  
  // Optional: Output directory for generated components
  outputDir: 'src/components',
  
  // Optional: Output directory for design tokens
  tokensDir: 'src/tokens',
  
  // Optional: Custom templates for component generation
  templates: {
    component: './templates/component.tsx.hbs',
    stories: './templates/stories.tsx.hbs',
    test: './templates/test.tsx.hbs',
  },
};
🛠️ Usage
Generate a Component from Figma
# Generate a Button component from a Figma node
npx mcp-design-system-bridge generate Button --figma-node 1234:5678

# Generate with custom output directory
npx mcp-design-system-bridge generate Button --output src/components/ui
Extract Design Tokens
# Extract design tokens from Figma
npx mcp-design-system-bridge extract-tokens --file-key YOUR_FIGMA_FILE_KEY

# Extract with custom output format (json, css, scss, js, ts)
npx mcp-design-system-bridge extract-tokens --format scss --output src/styles/tokens
Sync Components
# Sync all components from Figma to your codebase
npx mcp-design-system-bridge sync

# Sync a specific component
npx mcp-design-system-bridge sync Button
📚 Documentation
Component Generation

The MCP Design System Bridge can generate React components from Figma designs. The generated components include:

  • TypeScript types
  • Storybook stories
  • Unit tests
  • Documentation
Design Tokens

Extract and manage design tokens including:

  • Colors
  • Typography
  • Spacing
  • Border radius
  • Shadows
  • Transitions
  • Z-indices
API Reference
MCPDesignSystemBridge

The main class that provides the bridge functionality.

import { MCPDesignSystemBridge } from 'mcp-design-system-bridge';

const bridge = new MCPDesignSystemBridge({
  // Configuration options
});
Methods
  • generateReactComponent(spec: ComponentSpec): Promise<GeneratedFiles> - Generate React component files
  • extractDesignTokens(options: ExtractTokensOptions): Promise<DesignTokens> - Extract design tokens from Figma
  • syncComponent(componentName: string): Promise<SyncResult> - Sync a component between Figma and code
  • syncAllComponents(): Promise<SyncResult[]> - Sync all components
🤝 Contributing

Contributions are welcome! Please read our Contributing Guide for details on our code of conduct and the process for submitting pull requests.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments
  • Inspired by various design system tools and frameworks
  • Built with ❤️ by the MCP team

Made with create-mcp-tool

Features
  • Design Token Management: Extract and sync design tokens (colors, typography, spacing, etc.) from Figma
  • Component Generation: Generate React components from Figma designs with TypeScript support
  • Bidirectional Sync: Keep your design system in sync between Figma and code
  • Type Safety: Full TypeScript support for all generated components and tokens
  • Storybook Integration: Auto-generated Storybook stories for all components
  • Testing Ready: Includes test files for generated components
  • Customizable: Extensible architecture to fit your specific needs
Installation
# Using npm
npm install mcp-design-system-bridge

# Using yarn
yarn add mcp-design-system-bridge

# Using pnpm
pnpm add mcp-design-system-bridge
Prerequisites
  • Node.js 18 or later
  • A Figma account with access to the design files
  • A Figma personal access token (can be created at Figma Account Settings)
  • A React project with TypeScript
Quick Start
  1. Initialize the MCP client
import { createMCP } from 'mcp-design-system-bridge';

const mcp = createMCP({
  figmaToken: 'your-figma-token',
  projectRoot: process.cwd(),
});
  1. Extract design tokens from Figma
async function extractTokens() {
  try {
    const tokens = await mcp.extractFromFigma('your-figma-file-key');
    console.log('Extracted tokens:', tokens);
  } catch (error) {
    console.error('Failed to extract tokens:', error);
  }
}
  1. Generate a React component
const buttonSpec = {
  name: 'Button',
  description: 'A customizable button component',
  props: [
    {
      name: 'children',
      type: 'ReactNode',
      description: 'Button content',
      required: true,
    },
    {
      name: 'variant',
      type: 'string',
      description: 'Button variant',
      options: ['primary', 'secondary', 'outline', 'ghost', 'link'],
      defaultValue: 'primary',
    },
    {
      name: 'size',
      type: 'string',
      description: 'Button size',
      options: ['sm', 'md', 'lg'],
      defaultValue: 'md',
    },
    {
      name: 'disabled',
      type: 'boolean',
      description: 'Disable the button',
      defaultValue: false,
    },
  ],
  variants: [
    {
      name: 'primary',
      props: {
        className: 'bg-primary text-primary-foreground hover:bg-primary/90',
      },
    },
    {
      name: 'secondary',
      props: {
        className: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
      },
    },
  ],
};

async function generateButton() {
  try {
    const output = await mcp.generateReactComponent(buttonSpec);
    // Save the generated files
    await Promise.all([
      mcp.fileSystemService.writeFile('src/components/Button/Button.tsx', output.component),
      mcp.fileSystemService.writeFile('src/components/Button/Button.types.ts', output.types),
      mcp.fileSystemService.writeFile('src/components/Button/Button.stories.tsx', output.stories),
      mcp.fileSystemService.writeFile('src/components/Button/Button.test.tsx', output.tests),
      mcp.fileSystemService.writeFile('src/components/Button/index.ts', output.index),
    ]);
    console.log('Button component generated successfully!');
  } catch (error) {
    console.error('Failed to generate button component:', error);
  }
}
CLI Usage

The MCP Design System Bridge comes with a CLI for common tasks:

# Install the CLI globally
npm install -g mcp-design-system-bridge

# See available commands
mcp --help

# Generate a component
mcp generate:component Button --figma-node=1234:5678

# Extract tokens from Figma
mcp extract:tokens --file=abc123

# Sync components from Figma to code
mcp sync:from-figma --file=abc123

# Sync components from code to Figma
mcp sync:to-figma
Configuration

Create a mcp.config.js file in your project root:

module.exports = {
  figma: {
    fileKey: 'your-figma-file-key',
    // Optional: Map Figma styles to your token names
    styleMapping: {
      'colors/primary': 'color.primary',
      'text/heading': 'typography.heading',
    },
  },
  paths: {
    // Where to output generated components
    components: 'src/components',
    // Where to output design tokens
    tokens: 'src/tokens',
    // Where to output assets (icons, images)
    assets: 'public/assets',
  },
  // Component generation options
  component: {
    // Whether to use CSS Modules (default: false)
    cssModules: false,
    // Whether to generate TypeScript types (default: true)
    typescript: true,
    // Whether to generate tests (default: true)
    tests: true,
    // Whether to generate Storybook stories (default: true)
    stories: true,
  },
};
API Reference
createMCP(config: MCPConfig): MCPDesignSystemBridge

Creates a new instance of the MCP Design System Bridge.

Parameters
  • config (required): Configuration object
    • figmaToken (string): Figma personal access token
    • projectRoot (string): Root directory of your project
    • logger (Logger, optional): Custom logger instance
    • figmaBaseUrl (string, optional): Custom Figma API base URL
    • timeout (number, optional): API request timeout in milliseconds
Returns

An instance of MCPDesignSystemBridge with the following methods:

  • extractFromFigma(nodeId: string): Promise<ExtractedAssets>: Extract design tokens and components from Figma
  • generateReactComponent(spec: ComponentSpec): Promise<ReactComponentOutput>: Generate a React component
  • generateComponentVariants(baseComponent: string, variants: VariantSpec[]): Promise<ReactComponentOutput>: Generate component variants
  • syncToFigma(reactComponents: ReactAssets): Promise<SyncResult>: Sync React components to Figma
  • syncFromFigma(comparison: DiffResult): Promise<SyncResult>: Sync components from Figma to code
  • analyzeReactComponent(filePath: string): Promise<ComponentAnalysis>: Analyze a React component
  • detectChanges(): Promise<ChangeSet>: Detect changes between local and remote
  • generateDiff(local: ReactAssets, remote: FigmaAssets): DiffResult: Generate a diff between local and remote assets
  • validateSync(changes: ChangeSet): ValidationResult: Validate sync changes
Examples
Extracting Design Tokens
import { createMCP } from 'mcp-design-system-bridge';

const mcp = createMCP({
  figmaToken: 'your-figma-token',
  projectRoot: process.cwd(),
});

async function extractAndSaveTokens() {
  try {
    // Extract tokens from a specific node in your Figma file
    const { tokens } = await mcp.extractFromFigma('1234:5678');
    
    // Save tokens to a JSON file
    await mcp.fileSystemService.writeJSON('src/tokens/design-tokens.json', tokens);
    
    console.log('Design tokens extracted and saved successfully!');
  } catch (error) {
    console.error('Failed to extract design tokens:', error);
  }
}

extractAndSaveTokens();
Syncing Components from Figma
import { createMCP } from 'mcp-design-system-bridge';

const mcp = createMCP({
  figmaToken: 'your-figma-token',
  projectRoot: process.cwd(),
});

async function syncComponents() {
  try {
    // First, extract components from Figma
    const { components } = await mcp.extractFromFigma('1234:5678');
    
    // Generate React components for each extracted component
    for (const component of components) {
      const output = await mcp.generateReactComponent(component);
      
      // Save the generated files
      const componentDir = `src/components/${component.name}`;
      await mcp.fileSystemService.ensureDirectory(componentDir);
      
      await Promise.all([
        mcp.fileSystemService.writeFile(`${componentDir}/${component.name}.tsx`, output.component),
        mcp.fileSystemService.writeFile(`${componentDir}/${component.name}.types.ts`, output.types),
        mcp.fileSystemService.writeFile(`${componentDir}/${component.name}.stories.tsx`, output.stories),
        mcp.fileSystemService.writeFile(`${componentDir}/${component.name}.test.tsx`, output.tests),
        mcp.fileSystemService.writeFile(`${componentDir}/index.ts`, output.index),
      ]);
      
      console.log(`Generated component: ${component.name}`);
    }
    
    console.log('All components synced successfully!');
  } catch (error) {
    console.error('Failed to sync components:', error);
  }
}

syncComponents();
Contributing

Contributions are welcome! Please read our contributing guidelines to get started.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Roadmap
  • Add support for more design tools (Sketch, Adobe XD)
  • Improve component variant detection
  • Add more documentation and examples
  • Create VS Code extension for better IDE integration
  • Add support for more styling solutions (styled-components, Emotion, etc.)
  • Improve error handling and validation
  • Add more test coverage
Support

If you encounter any issues or have questions, please open an issue.

Acknowledgments
Author Information
Bruno Nepomuceno

design, música eletrônica, creme de cupuaçu e memes ruins.

@tairape @magicoven-tech @co-de-sign @IxDABrasilia Brasília - DF

41

Followers

157

Repositories

5

Gists

1

Total Contributions

Top Contributors

Threads