Back to skills
SkillHub ClubDesign ProductFull StackFrontendData / AI

ai-component-metadata

Generate AI-ready metadata for design system components to enable intelligent UI generation. Analyzes component structure and generates structured metadata that helps AI understand when and how to use components correctly. Useful for teams building AI-consumable design systems.

Packaged view

This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.

Stars
15
Hot score
86
Updated
March 19, 2026
Overall rating
C2.6
Composite score
2.6
Best-practice grade
C62.8

Install command

npx @skill-hub/cli install cris-achiardi-claude-skills-ai-component-metadata

Repository

cris-achiardi/claude-skills

Skill path: skills/ai-component-metadata

Generate AI-ready metadata for design system components to enable intelligent UI generation. Analyzes component structure and generates structured metadata that helps AI understand when and how to use components correctly. Useful for teams building AI-consumable design systems.

Open repository

Best for

Primary workflow: Design Product.

Technical facets: Full Stack, Frontend, Data / AI, Designer.

Target audience: everyone.

License: Unknown.

Original source

Catalog source: SkillHub Club.

Repository owner: cris-achiardi.

This is still a mirrored public skill entry. Review the repository before installing into production workflows.

What it helps with

  • Install ai-component-metadata into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
  • Review https://github.com/cris-achiardi/claude-skills before adding ai-component-metadata to shared team environments
  • Use ai-component-metadata for development workflows

Works across

Claude CodeCodex CLIGemini CLIOpenCode

Favorites: 0.

Sub-skills: 0.

Aggregator: No.

Original source / Raw SKILL.md

---
name: ai-component-metadata
version: 1.0.0
description: Generate AI-ready metadata for design system components to enable intelligent UI generation. Analyzes component structure and generates structured metadata that helps AI understand when and how to use components correctly. Useful for teams building AI-consumable design systems.
---

# AI Component Metadata Generator

Generate structured, AI-consumable metadata for design system components to enable intelligent UI generation and component usage.

## Quick Start

When analyzing a component, use the metadata schema template in `scripts/generate_metadata.py` or follow the manual process below:

```bash
# Automatic generation (reads component file)
python scripts/generate_metadata.py path/to/Component.tsx

# Or use the template directly
cp assets/metadata-template.tsx your-component-metadata.tsx
```

## Core Workflow

### 1. Analyze Component Structure
Identify:
- Component composition (slots, children)
- Available variants and states
- Props and their types
- Accessibility attributes

### 2. Generate Metadata
Create metadata following this schema:

```javascript
export const componentMetadata = {
  component: {
    name: "ComponentName",
    category: "atoms|molecules|organisms",
    description: "Brief description",
    type: "interactive|display|container|input|navigation"
  },
  
  usage: {
    useCases: ["primary-use", "secondary-use"],
    requiredProps: [],
    commonPatterns: [
      {
        name: "pattern-name",
        description: "When to use",
        composition: "JSX example"
      }
    ],
    antiPatterns: [
      {
        scenario: "what-not-to-do",
        reason: "why",
        alternative: "what-instead"
      }
    ]
  },
  
  composition: {
    slots: {},
    nestedComponents: [],
    commonPartners: [],
    parentConstraints: []
  },
  
  behavior: {
    states: [],
    interactions: {},
    responsive: {}
  },
  
  accessibility: {
    role: "ARIA role",
    keyboardSupport: "description",
    screenReader: "behavior",
    focusManagement: "strategy",
    wcag: "AA"
  },
  
  aiHints: {
    priority: "high|medium|low",
    keywords: [],
    context: "when to use"
  }
}
```

### 3. Validate Metadata
- Test with AI generation tasks
- Verify in Storybook
- Ensure examples are runnable

## Component Categories

- **atoms**: Basic building blocks (Button, Text, Input)
- **molecules**: Simple combinations (Card, Chip, FormField)
- **organisms**: Complex components (Header, Table, Form)

## Advanced Features

For complex scenarios, see:
- **Nested components**: [NESTED.md](references/NESTED.md)
- **Integration patterns**: [INTEGRATION.md](references/INTEGRATION.md)
- **Testing strategies**: [TESTING.md](references/TESTING.md)

## Working with Figma

When combining with Figma MCP:

```javascript
// Figma provides visual context
const figmaContext = await Figma.get_design_context();

// Your metadata provides behavioral context
const componentMetadata = components.Button.metadata;

// AI combines both for complete understanding
```

## Best Practices

1. **Keep examples real** - Use actual, runnable code
2. **Focus on patterns** - Document common usage patterns
3. **Include anti-patterns** - Help AI avoid mistakes
4. **Validate through usage** - Test with actual AI generation

## Success Metrics

Your metadata is effective when:
- AI uses existing components instead of recreating
- Correct variants are selected based on context
- Accessibility is maintained in generated code
- Patterns are consistent across AI outputs


---

## Referenced Files

> The following files are referenced in this skill and included for context.

### references/NESTED.md

```markdown
# Nested Component Metadata

Guide for handling metadata in component composition hierarchies.

## Traversal Strategy

When components contain other components, metadata should reference the full tree:

```javascript
// Card → CardHeader → Text (h3)
//      → CardBody → Text (body2)
//      → CardFooter → Button → Button.Text

composition: {
  nestedComponents: ["CardHeader", "CardBody", "CardFooter"],
  // Each nested component has its own metadata
}
```

## Inheritance Patterns

### Props Inheritance
Child components may inherit certain metadata from parents:

```javascript
// Parent Card metadata
accessibility: {
  role: "article",
  landmark: true
}

// Child CardHeader inherits context
accessibility: {
  role: "heading",
  level: "derived from parent" // h2 if Card is top-level, h3 if nested
}
```

### Context Propagation
Semantic meaning flows down:

```javascript
// Form provides context
behavior: {
  context: "form-submission"
}

// Button inside Form understands its purpose
aiHints: {
  contextAware: true,
  inferredPurpose: "submit-action when inside Form"
}
```

## Composition Examples

### Simple Composition (Molecule)
```javascript
// Chip contains Text and optional Icon
composition: {
  slots: {
    "Text": { required: true, description: "Label content" },
    "Icon": { required: false, description: "Visual indicator" }
  },
  nestedComponents: ["Text", "Icon"]
}
```

### Complex Composition (Organism)
```javascript
// Table contains multiple levels
composition: {
  nestedComponents: [
    "TableHeader",
    "TableBody", 
    "TableFooter"
  ],
  deepStructure: {
    "TableHeader": ["TableRow", "TableHead"],
    "TableBody": ["TableRow", "TableCell"],
    "TableRow": ["TableCell", "Chip", "Button", "Text"]
  }
}
```

## AI Traversal Hints

Help AI understand component relationships:

```javascript
aiHints: {
  traversalRules: [
    "Always include TableRow when using Table",
    "TableCell can contain any atom or molecule",
    "Nested Tables should be avoided"
  ]
}
```

```

### references/INTEGRATION.md

```markdown
# Integration Patterns

Common patterns for integrating components with AI metadata.

## With Figma MCP

Combine visual and behavioral context:

```javascript
// Step 1: Get visual specs from Figma
const figmaContext = await Figma.get_design_context();
// Returns: layout, spacing, colors, typography

// Step 2: Get behavioral specs from metadata
const behaviorContext = componentMetadata.behavior;
// Returns: states, interactions, accessibility

// Step 3: AI combines both
const fullContext = {
  visual: figmaContext,
  behavioral: behaviorContext,
  implementation: componentCode
};
```

## With Code Generation

### Direct Component Usage
AI should prefer existing components:

```javascript
// User: "Create a status indicator"

// ❌ Bad: AI creates new element
<div style={{background: 'green'}}>Active</div>

// ✅ Good: AI uses existing Chip
<Chip variant="solid_success" size="sm">
  <Chip.Text>Active</Chip.Text>
</Chip>
```

### Pattern Recognition
AI learns from commonPatterns:

```javascript
// Metadata defines pattern
commonPatterns: [{
  name: "form-actions",
  composition: `
    <Stack direction="horizontal" gap="$2">
      <Button variant="solid_primary">Submit</Button>
      <Button variant="outline_default">Cancel</Button>
    </Stack>
  `
}]

// AI recognizes and applies pattern
// User: "Add form buttons"
// AI generates the exact pattern from metadata
```

## With Documentation

### Sync Strategies

1. **Manual Sync**
   - Developer updates both docs and metadata
   - Good for small teams

2. **Semi-Automated**
   - Metadata generates from JSDoc comments
   - Script updates both sources

3. **Fully Automated**
   - Single source of truth (code)
   - Build process generates metadata
   - Webhooks sync documentation

### Documentation Integration

```javascript
// Component file
/**
 * @metadata
 * @category atoms
 * @type interactive
 * @useCases ["primary-actions", "form-submission"]
 */
export const Button = ...

// Build process extracts to metadata
componentMetadata = extractMetadata(Button);
```

## With Testing

### AI-Driven Test Generation

```javascript
// Metadata informs test cases
accessibility: {
  keyboardSupport: "Space/Enter activates",
  focusManagement: "Visible ring on focus"
}

// AI generates tests
describe('Button Accessibility', () => {
  test('responds to Space key', () => {
    // Test implementation
  });
  
  test('shows focus ring', () => {
    // Test implementation
  });
});
```

### Visual Regression Hints

```javascript
testingHints: {
  visualRegression: [
    "All color variants render correctly",
    "Hover states are visible",
    "Focus rings appear on keyboard nav"
  ]
}
```

## With Design Tokens

```javascript
// Tokens provide values
tokens: {
  colors: { primary: "#007AFF" },
  spacing: { md: "16px" }
}

// Metadata provides meaning
aiHints: {
  tokenUsage: {
    "primary": "Use for main CTAs",
    "spacing.md": "Default component spacing"
  }
}
```

## Framework-Specific Patterns

### React/Tamagui
```javascript
// Metadata for styled components
composition: {
  styling: "tamagui",
  styledProps: ["size", "variant", "state"],
  tokenPrefix: "$"
}
```

### Vue
```javascript
// Metadata for Vue components
composition: {
  framework: "vue",
  slots: { default: true, icon: false },
  emits: ["click", "change"]
}
```

### Web Components
```javascript
// Metadata for custom elements
composition: {
  framework: "web-components",
  tagName: "ds-button",
  attributes: ["variant", "size", "disabled"]
}
```

```

### references/TESTING.md

```markdown
# Testing Strategies

How to validate AI metadata and enable AI-driven testing.

## Metadata Validation

### Completeness Checks
Ensure all required fields are present:

```javascript
function validateMetadata(metadata) {
  const required = [
    'component.name',
    'component.category', 
    'component.description',
    'usage.useCases',
    'accessibility.role'
  ];
  
  return required.every(path => 
    getNestedValue(metadata, path) !== undefined
  );
}
```

### Pattern Validation
Verify examples are runnable:

```javascript
// Test each commonPattern
metadata.usage.commonPatterns.forEach(pattern => {
  test(`Pattern "${pattern.name}" renders`, () => {
    const component = render(pattern.composition);
    expect(component).toBeTruthy();
  });
});
```

## AI Generation Testing

### Component Selection
Test if AI chooses correct component:

```javascript
// Test prompt
const prompt = "Create a toggle for notifications";

// Expected: AI selects Switch, not Button
expect(aiResponse).toContain('Switch');
expect(aiResponse).not.toContain('Button');
```

### Variant Selection
Test if AI applies correct variants:

```javascript
// Test prompt
const prompt = "Show an error message chip";

// Expected: AI uses danger variant
expect(aiResponse).toContain('variant="solid_danger"');
```

## Accessibility Testing

### WCAG Compliance
Validate accessibility claims:

```javascript
testingHints: {
  accessibility: [
    {
      test: "color-contrast",
      expected: "4.5:1 minimum",
      tools: ["axe-core", "pa11y"]
    },
    {
      test: "keyboard-navigation", 
      expected: "Full support",
      validate: "Tab, Space, Enter, Escape"
    }
  ]
}
```

### Screen Reader Testing
Verify announcements:

```javascript
accessibility: {
  screenReader: "Announces label and state",
  testCases: [
    {
      state: "checked",
      announcement: "Notifications, switch, checked"
    },
    {
      state: "unchecked",
      announcement: "Notifications, switch, unchecked"
    }
  ]
}
```

## Visual Regression

### Component States
Test all visual states:

```javascript
const states = metadata.behavior.states;
// ["default", "hover", "active", "focus", "disabled"]

states.forEach(state => {
  test(`Visual regression - ${state}`, async () => {
    const screenshot = await captureComponent(Component, { state });
    expect(screenshot).toMatchSnapshot();
  });
});
```

### Responsive Behavior
Test across breakpoints:

```javascript
const breakpoints = ["mobile", "tablet", "desktop"];

breakpoints.forEach(breakpoint => {
  test(`Responsive - ${breakpoint}`, () => {
    const behavior = metadata.behavior.responsive[breakpoint];
    // Verify behavior matches description
  });
});
```

## Integration Testing

### Component Combinations
Test common partnerships:

```javascript
metadata.composition.commonPartners.forEach(partner => {
  test(`Works with ${partner}`, () => {
    const combo = render(
      <Partner>
        <Component />
      </Partner>
    );
    expect(combo).toRenderWithoutErrors();
  });
});
```

### Anti-Pattern Detection
Ensure anti-patterns fail appropriately:

```javascript
metadata.usage.antiPatterns.forEach(antiPattern => {
  test(`Prevents: ${antiPattern.scenario}`, () => {
    // Verify linter/build warns about antiPattern
    expect(lintWarnings).toContain(antiPattern.reason);
  });
});
```

## AI Behavior Validation

### Prompt Testing Suite
Create test prompts for each use case:

```javascript
const testPrompts = {
  "status-indicators": [
    "Show user is online",
    "Display error state",
    "Mark as completed"
  ],
  "category-labels": [
    "Tag as technology",
    "Label with department"
  ]
};

// Test each prompt generates appropriate component
```

### Success Metrics

Track AI performance:

```javascript
metrics: {
  componentReuseRate: "85%", // Uses existing vs creating new
  variantAccuracy: "90%",    // Correct variant selection
  accessibilityScore: "100%", // Maintains a11y standards
  patternConsistency: "95%"   // Follows documented patterns
}
```

## Continuous Validation

### Automated Checks
Run on every commit:

```bash
npm run validate:metadata    # Structure validation
npm run test:ai-generation   # AI usage tests
npm run test:accessibility   # WCAG compliance
npm run test:visual          # Visual regression
```

### Manual Review
Periodic human validation:

1. Review Storybook examples
2. Test with real AI tools
3. Validate against design specs
4. Check documentation sync

## Test Data Examples

### Sample Test Cases

```javascript
export const testCases = [
  {
    prompt: "Create a primary action button",
    expected: {
      component: "Button",
      variant: "solid_primary",
      hasText: true
    }
  },
  {
    prompt: "Show loading state",
    expected: {
      component: "Spinner|Skeleton|Button",
      state: "loading"
    }
  },
  {
    prompt: "Display user role",
    expected: {
      component: "Chip|Badge",
      variant: "outline_default"
    }
  }
];
```

```

### scripts/generate_metadata.py

```python
#!/usr/bin/env python3
"""
AI Component Metadata Generator
Analyzes React/TypeScript components and generates AI-ready metadata
"""

import re
import json
import sys
from pathlib import Path
from typing import Dict, List, Any

def extract_component_info(content: str) -> Dict[str, Any]:
    """Extract component information from TypeScript/JSX content"""
    
    # Extract component name
    name_match = re.search(r'export (?:const|function) (\w+)', content)
    component_name = name_match.group(1) if name_match else 'Unknown'
    
    # Extract props
    props_match = re.search(r'type \w+Props = \{([^}]+)\}', content, re.DOTALL)
    props = []
    if props_match:
        prop_lines = props_match.group(1).strip().split('\n')
        for line in prop_lines:
            prop_match = re.match(r'\s*(\w+)(\?)?: (.+);?', line.strip())
            if prop_match:
                props.append({
                    'name': prop_match.group(1),
                    'required': prop_match.group(2) != '?',
                    'type': prop_match.group(3).strip()
                })
    
    # Extract variants
    variant_matches = re.findall(r'variant[s]?: \{([^}]+)\}', content, re.DOTALL)
    variants = []
    for match in variant_matches:
        variant_names = re.findall(r'(\w+):', match)
        variants.extend(variant_names)
    
    # Extract states
    state_matches = re.findall(r'state[s]?: \{([^}]+)\}', content, re.DOTALL)
    states = []
    for match in state_matches:
        state_names = re.findall(r'(\w+):', match)
        states.extend(state_names)
    
    # Detect component type
    component_type = 'display'
    if 'onClick' in content or 'onPress' in content:
        component_type = 'interactive'
    elif 'onChange' in content or 'onInput' in content:
        component_type = 'input'
    elif 'Container' in content or 'Layout' in content:
        component_type = 'container'
    
    # Detect category
    category = 'atoms'
    if 'withStaticProperties' in content or '.Text' in content or '.Icon' in content:
        category = 'molecules'
    elif 'Header' in component_name or 'Footer' in component_name or 'Form' in component_name:
        category = 'organisms'
    
    # Extract nested components
    nested_match = re.findall(r'(\w+): \w+(?:Text|Icon|Thumb|Header|Body|Footer)', content)
    nested_components = list(set(nested_match))
    
    return {
        'name': component_name,
        'type': component_type,
        'category': category,
        'props': props,
        'variants': list(set(variants)),
        'states': list(set(states)),
        'nested_components': nested_components
    }

def generate_metadata(component_info: Dict[str, Any]) -> Dict[str, Any]:
    """Generate AI-ready metadata from component information"""
    
    name = component_info['name']
    
    # Generate use cases based on component name and type
    use_cases = []
    name_lower = name.lower()
    
    if 'button' in name_lower:
        use_cases = ['primary-actions', 'form-submission', 'navigation-triggers']
    elif 'switch' in name_lower or 'toggle' in name_lower:
        use_cases = ['feature-toggles', 'settings-preferences', 'notification-controls']
    elif 'chip' in name_lower or 'tag' in name_lower:
        use_cases = ['status-indicators', 'category-labels', 'filter-tags']
    elif 'text' in name_lower:
        use_cases = ['body-text', 'headings', 'labels', 'captions']
    elif 'card' in name_lower:
        use_cases = ['content-containers', 'information-display', 'interactive-tiles']
    else:
        use_cases = ['general-purpose-component']
    
    # Generate keywords
    keywords = [name_lower]
    keywords.extend(name_lower.split('_'))
    keywords.extend(name_lower.split('-'))
    
    # Build metadata structure
    metadata = {
        'component': {
            'name': name,
            'category': component_info['category'],
            'description': f'{name} component for design system',
            'type': component_info['type']
        },
        'usage': {
            'useCases': use_cases,
            'requiredProps': [p['name'] for p in component_info['props'] if p.get('required')],
            'commonPatterns': [
                {
                    'name': 'basic-usage',
                    'description': f'Basic {name} usage',
                    'composition': f'<{name}></{name}>'
                }
            ],
            'antiPatterns': []
        },
        'composition': {
            'slots': {},
            'nestedComponents': component_info.get('nested_components', []),
            'commonPartners': [],
            'parentConstraints': []
        },
        'behavior': {
            'states': component_info.get('states', ['default']),
            'interactions': {},
            'responsive': {
                'mobile': 'Adapts to mobile viewport',
                'desktop': 'Standard desktop layout'
            }
        },
        'accessibility': {
            'role': 'generic',
            'keyboardSupport': 'Standard keyboard navigation',
            'screenReader': 'Properly announced',
            'focusManagement': 'Focus ring on interaction',
            'wcag': 'AA'
        },
        'aiHints': {
            'priority': 'medium',
            'keywords': list(set(keywords)),
            'context': f'Use for {", ".join(use_cases[:2])}'
        }
    }
    
    # Add variant-specific info
    if component_info.get('variants'):
        metadata['variants'] = {
            v: {'useCase': f'Use for {v} variant'} 
            for v in component_info['variants'][:5]  # Limit to first 5
        }
    
    # Adjust for specific component types
    if component_info['type'] == 'interactive':
        metadata['behavior']['interactions'] = {
            'click': 'Triggers action',
            'hover': 'Shows hover state'
        }
        metadata['accessibility']['role'] = 'button'
        metadata['accessibility']['keyboardSupport'] = 'Space/Enter to activate'
    
    elif component_info['type'] == 'input':
        metadata['accessibility']['role'] = 'textbox'
        metadata['behavior']['interactions'] = {
            'change': 'Updates value',
            'focus': 'Shows focus state'
        }
    
    return metadata

def format_metadata_for_tsx(metadata: Dict[str, Any]) -> str:
    """Format metadata as TypeScript export"""
    
    # Convert to JSON with proper indentation
    json_str = json.dumps(metadata, indent=2)
    
    # Format as TypeScript const export
    tsx_output = f"""// AI-ready component metadata
export const componentMetadata = {json_str} as const;
"""
    
    return tsx_output

def main():
    """Main entry point"""
    
    if len(sys.argv) < 2:
        print("Usage: python generate_metadata.py <component-file.tsx>")
        print("\nThis script analyzes React/TypeScript components and generates AI-ready metadata.")
        sys.exit(1)
    
    file_path = Path(sys.argv[1])
    
    if not file_path.exists():
        print(f"Error: File '{file_path}' not found")
        sys.exit(1)
    
    # Read component file
    content = file_path.read_text()
    
    # Extract component information
    print(f"Analyzing {file_path.name}...")
    component_info = extract_component_info(content)
    
    # Generate metadata
    print(f"Generating metadata for {component_info['name']}...")
    metadata = generate_metadata(component_info)
    
    # Format as TypeScript
    tsx_output = format_metadata_for_tsx(metadata)
    
    # Save to file
    output_path = file_path.parent / f"{file_path.stem}-metadata.tsx"
    output_path.write_text(tsx_output)
    
    print(f"✅ Metadata generated: {output_path}")
    print(f"\nComponent: {component_info['name']}")
    print(f"Category: {component_info['category']}")
    print(f"Type: {component_info['type']}")
    print(f"Variants: {', '.join(component_info.get('variants', ['none']))}")
    print(f"States: {', '.join(component_info.get('states', ['default']))}")
    print(f"\nYou can now add this metadata to your component file.")

if __name__ == '__main__':
    main()

```

### assets/metadata-template.tsx

```tsx
import React from 'react';

/**
 * AI Component Metadata Template
 * 
 * Instructions:
 * 1. Replace COMPONENT_NAME with your actual component name
 * 2. Fill in all metadata fields based on your component
 * 3. Remove any sections that don't apply
 * 4. Add to your component file as an export
 */

// ============================================
// AI-READY METADATA
// ============================================

export const componentMetadata = {
  component: {
    name: "COMPONENT_NAME",
    category: "atoms", // atoms | molecules | organisms
    description: "One-line description of component purpose",
    type: "interactive" // interactive | display | container | input | navigation
  },
  
  usage: {
    useCases: [
      // List specific, semantic use cases
      "primary-use-case",
      "secondary-use-case"
    ],
    
    requiredProps: [
      // Props that must always be provided
    ],
    
    commonPatterns: [
      {
        name: "basic-usage",
        description: "Most common usage pattern",
        composition: `
          <COMPONENT_NAME>
            Content
          </COMPONENT_NAME>
        `
      }
    ],
    
    antiPatterns: [
      {
        scenario: "what-not-to-do",
        reason: "Why this is problematic",
        alternative: "What to do instead"
      }
    ]
  },
  
  composition: {
    slots: {
      // Define slots/subcomponents
      "SlotName": {
        required: false,
        description: "Purpose of this slot"
      }
    },
    
    nestedComponents: [
      // Child components used
    ],
    
    commonPartners: [
      // Components often used together
    ],
    
    parentConstraints: [
      // Placement restrictions
    ]
  },
  
  behavior: {
    states: ["default", "hover", "active", "disabled"],
    
    interactions: {
      "click": "Action triggered",
      "focus": "Focus behavior"
    },
    
    responsive: {
      "mobile": "Mobile behavior",
      "desktop": "Desktop behavior"
    }
  },
  
  accessibility: {
    role: "button", // ARIA role
    keyboardSupport: "Space/Enter to activate",
    screenReader: "Announces label and state",
    focusManagement: "Visible focus ring",
    wcag: "AA"
  },
  
  aiHints: {
    priority: "medium", // high | medium | low
    keywords: ["trigger", "words"],
    context: "When AI should use this component"
  }
} as const;

```

ai-component-metadata | SkillHub