npm package: @presetdev/mcp
Description: The design system layer for AI agents — 60+ MCP tools for Claude Code, Cursor, Windsurf, and more
Latest version: 1.0.9

# @presetdev/mcp

The design system layer for AI agents. 60+ bidirectional tools for reading, writing, and enforcing your design system from Claude Code, Cursor, Windsurf, and Claude Desktop.

This is the primary way teams consume Preset — everything defined in the dashboard (tokens, presets, patterns, rules) is delivered to AI coding tools through this MCP server.

## Quick Start

### 1. Get an API Key

Go to your [Preset dashboard](https://app.preset.dev/connect) and generate an API key.

### 2. Configure Your AI Tool

**Claude Code** (recommended — authenticates via browser)

```bash
claude mcp add --transport http preset https://mcp.presetai.dev/mcp
```

Then run `/mcp` in Claude Code to authenticate.

**Claude Code** (alternative — with API key)

```bash
claude mcp add -e PRESET_API_KEY=pk_live_... preset -- npx -y @presetdev/mcp@latest
```

**Cursor** (`.cursor/mcp.json`)

```json
{
  "mcpServers": {
    "preset": {
      "command": "npx",
      "args": ["-y", "@presetdev/mcp@latest"],
      "env": {
        "PRESET_API_KEY": "pk_live_..."
      }
    }
  }
}
```

**Windsurf** (`~/.codeium/windsurf/mcp_config.json`)

Same JSON format as Cursor above.

**Claude Desktop** (`claude_desktop_config.json`)

Same JSON format as Cursor above. Config location:
- macOS: `~/Library/Application Support/Claude/`
- Windows: `%APPDATA%\Claude\`

### 3. Start Using It

Your AI tool now has access to your design system. Try:

- "What presets are available for buttons?"
- "Validate this component against our design tokens"
- "Create a pattern for our card layout"
- "What colors should I use for a success state?"

## How Authentication Works

Your `PRESET_API_KEY` is exchanged for a short-lived Supabase JWT at startup via the `mcp-session` edge function. The JWT carries the identity of the user who created the key, so all existing database permissions (RLS) apply — including write policies. The key creator must have `admin` or `editor` role in the organization.

## Troubleshooting

| Error | Solution |
|-------|----------|
| Missing PRESET_API_KEY | Set the env var. Get a key at https://app.preset.dev/connect |
| Invalid API key format | Keys start with `pk_live_` or `pk_test_` |
| API key not found | The key may have been deleted. Generate a new one. |
| API key revoked | Generate a new key at the dashboard. |
| Cannot reach Preset servers | Check your internet connection. |
| User no longer has access | The key creator was removed from the org. Create a new key. |

## Advanced

**Verbose mode**: Add `--verbose` to the args for debug logging:

```json
"args": ["-y", "@presetdev/mcp@latest", "--verbose"]
```

**Local development** (within the monorepo):

```json
{
  "mcpServers": {
    "preset": {
      "command": "node",
      "args": ["/path/to/preset/packages/mcp/dist/server.js", "--verbose"]
    }
  }
}
```

**Programmatic usage**:

```typescript
import { createServer } from '@presetdev/mcp';

const server = createServer({
  verbose: true,
  supabaseUrl: '...',
  supabaseKey: '...',
  organizationId: '...',
  designSystemId: '...',
});

await server.start();
```

## Available Tools

### get_forbidden_primitives

Returns elements and patterns that MUST NOT be generated.

**Use Case**: Call before generating UI code to understand what's forbidden.

**Returns**:
- Forbidden HTML elements (e.g., `<select>`, `<button>` without preset)
- Forbidden patterns (e.g., hardcoded Tailwind colors, `window.alert`)
- Replacement components and code
- Severity levels

### get_active_constraints

Returns context-aware constraints based on file path or component type.

**Parameters**:
- `filePath` (optional): Current file being edited
- `intent` (optional): Natural language description of what's being built

**Returns**:
- Which components MUST be used
- Which presets are recommended
- File-specific rules

### get_intent_route

Maps user intent to the correct design system component.

**Parameters**:
- `intent`: Natural language description (e.g., "dropdown for selecting time period")

**Returns**:
- `targetComponent`: The design system component to use
- `targetPreset`: Recommended preset
- `antiPatterns`: What NOT to use
- `confidence`: How confident the routing is (0-1)

### validate_before_generation

Pre-generation validation check. Call BEFORE writing code.

**Parameters**:
- `intent`: What you're trying to build
- `filePath` (optional): Current file being edited

**Returns**:
- `proceed`: Whether the approach is valid
- `constraints`: Array of constraints to follow
- `suggestedApproach`: The design-system-compliant way to build this

### validate_generated_code

Post-generation validation. Call AFTER writing code to check for violations.

**Parameters**:
- `code`: The generated code to validate
- `autoCorrect` (optional): Whether to return auto-corrected code
- `intent` (optional): What the code was meant to do

**Returns**:
- `valid`: Whether the code passes validation
- `violations`: Array of issues with line/column info
- `suggestions`: How to fix each violation
- `correctedCode`: Auto-fixed code (if autoCorrect=true)

### quick_check_violations

Fast check for violations without detailed analysis.

**Parameters**:
- `code`: The code to check

**Returns**:
- `hasViolations`: boolean

### check_drift

Measures how far code deviates from canonical design system presets. Unlike violation detection (what's forbidden), drift analysis measures deviation from the ideal (how far from perfect).

**Parameters**:
- `code`: The code to analyze
- `filePath` (optional): File path for context

**Returns**:
- `hasDrift`: Whether any drift was detected
- `driftScore`: Number 0-100 (0 = perfect alignment, 100 = complete drift)
- `instances`: Array of drift instances with location, component, expected vs actual, severity
- `summary`: Statistics including totalIssues, byCategory, bySeverity, presetCoverage

**Use Case**: Audit code quality and measure design system adoption.

### get_design_tokens

Returns design tokens from the design system for code generation.

**Parameters**:
- `category` (optional): 'colors' | 'spacing' | 'typography' | 'shadows' | 'borders' | 'radius' | 'all' (default: 'all')
- `theme` (optional): 'light' | 'dark' | 'both' (default: 'both')
- `format` (optional): 'tailwind' | 'css' | 'json' (default: 'tailwind')
- `detail_level` (optional): 'summary' | 'full' (default: 'full') — Summary returns token names, values, CSS variables, descriptions, and AI guidance without usage recommendations or typography health data. Use summary when browsing tokens; full when generating code.

**Returns**:
- `tokens`: Design tokens organized by category
  - `colors`: semantic (surface, text, border), status, brand tokens
  - `spacing`: scale from 0 to 24 (Tailwind spacing)
  - `typography`: fontSizes, fontWeights, lineHeights, fontFamilies
  - `shadows`: elevation scale
  - `borders`: widths and styles
  - `radius`: rounding scale
- `usage`: Guidelines for using tokens correctly (full mode only)
  - `doUse`: Best practices to follow
  - `dontUse`: Anti-patterns to avoid
  - `bestPractices`: Additional guidance

**Use Case**: Understand what tokens are available when generating UI code.

### suggest_fixes

Returns actionable fix suggestions for design system violations. Completes the validation → correction loop.

**Parameters**:
- `code` (required): The code containing violations
- `violations` (optional): Array of specific violation IDs to fix (if not provided, fixes all)
- `autoApply` (optional): Whether to return code with fixes applied (default: false)

**Returns**:
- `fixes`: Array of suggested fixes with:
  - `violationId`: Which violation this fixes
  - `description`: What's wrong
  - `original`: The problematic code
  - `suggested`: The corrected code
  - `confidence`: 0-1 (higher = more reliable fix)
  - `breaking`: Whether this fix could change behavior
  - `diff`: Unified diff format showing the change
  - `line`/`column`: Location in code
- `fixedCode`: Code with all auto-fixes applied (if autoApply=true)
- `unfixable`: Violations requiring manual intervention with:
  - `violationId`: Which violation
  - `reason`: Why it can't be auto-fixed
  - `manualSteps`: Array of steps to fix manually
- `stats`: Statistics about the fixes
  - `totalViolations`: Count of violations found
  - `autoFixable`: Number that can be auto-fixed
  - `requiresManual`: Number requiring manual intervention
  - `appliedFixes`: Number of fixes applied (if autoApply=true)

**Use Case**: Get specific fixes with diffs after validate_generated_code finds violations.

### get_component_api

Returns the full props API for a design system component. Essential for generating type-safe component code.

**Parameters**:
- `component` (required): Component name (e.g., "Button", "Select", "Input")
- `includeExamples` (optional): Include usage examples (default: false)
- `format` (optional): Output format - 'typescript' | 'json-schema' | 'markdown' (default: 'typescript')

**Returns**:
- `component`: Component name
- `description`: What the component does
- `props`: Array of prop definitions with:
  - `name`: Prop name
  - `type`: TypeScript type
  - `required`: Whether the prop is required
  - `default`: Default value (if any)
  - `description`: What the prop does
  - `allowedValues`: Valid values for enum types
- `presets`: Available presets with name, description, and props configuration
- `examples`: Usage examples (if includeExamples=true)
- `relatedComponents`: Components often used together
- `importStatement`: How to import the component

**Use Case**: Call BEFORE generating component code to ensure correct prop usage and type safety.

### list_components

Lists all available design system components.

**Returns**:
- Array of component names that can be used with `get_component_api`

**Use Case**: Discover what components are available in the design system.

### export_context

Generate a context file for AI coding assistants (CLAUDE.md, .cursorrules, copilot-instructions.md).

**Parameters**:
- `format` (required): Export format (`claude`, `cursor`, `copilot`)
- `design_system_id` (optional): Design system UUID
- `project_name` (optional): Project name for the header
- `project_description` (optional): Project description
- `include_presets` (optional): Include presets section (default: true)
- `include_tokens` (optional): Include tokens section (default: true)
- `include_rules` (optional): Include forbidden primitives and context rules (default: true)
- `custom_instructions` (optional): Additional instructions to append

**Returns**:
- `content`: The generated markdown content
- `filename`: Suggested filename
- `stats`: Statistics (presetCount, tokenCount, ruleCount, characterCount, estimatedTokens)
- `usage`: Instructions for how to use the file

**Use Case**: Export your design system as a portable context file that AI coding tools read automatically.

### export_rules

Export all design system enforcement rules as a portable, versioned artifact.

**Parameters**:
- `format` (required): `json` | `markdown` | `sarif`
- `design_system_id` (optional): Design system UUID (falls back to configured DS)
- `layer_id` (optional): Layer UUID for layer-specific resolved rules
- `include_defaults` (optional): Merge @preset/core defaults when DB is empty (default: false)

**Formats**:
- **json**: Full `DesignSystemRuleset` object with `$schema`, version, content hash, stats
- **markdown**: Human-readable sections grouped by type and severity
- **sarif**: SARIF v2.1.0 with rules in `tool.driver.rules[]` for CI/CD integration

**Returns**:
- `content`: The formatted export content
- `contentHash`: SHA-256 hash for cache invalidation
- `stats`: Rule counts by type and severity
- `filename`: Suggested filename (`preset-rules.json`, `preset-rules.md`, or `preset-rules.sarif.json`)

**Use Case**: Export once, enforce everywhere — CI/CD pipelines, IDE extensions, AI context files, cross-MCP sharing.

## Available Resources

MCP Resources provide read-only reference data that AI agents can pre-load for context. Unlike tools (which are action-oriented), resources are application-controlled data sources.

### anti-patterns://design-system

Comprehensive catalog of design system anti-patterns and mistakes to avoid. Pre-load this resource to prevent common violations before they happen.

**URI**: `anti-patterns://design-system`

**Returns** (JSON):
```json
{
  "title": "Design System Anti-Patterns",
  "categories": [
    {
      "name": "Color Anti-Patterns",
      "patterns": [
        {
          "id": "hardcoded-hex-values",
          "mistake": "Using hardcoded hex values instead of tokens",
          "instead": "Use semantic tokens like bg-surface-primary",
          "why": "Breaks theming, dark mode, and consistency",
          "severity": "critical",
          "examples": {
            "bad": "bg-[#f5f5f5]",
            "good": "bg-surface-secondary"
          }
        }
      ]
    }
  ],
  "quickReference": {
    "criticalMistakes": ["hardcoded-hex-values", "raw-html-button", ...],
    "aiSlopWarnings": ["unnecessary-wrapper-divs", "overcomplicated-state", ...]
  },
  "metadata": { "version": "1.0.0", "lastUpdated": "..." }
}
```

**Categories**:
| Category | Focus |
|----------|-------|
| Color Anti-Patterns | Hardcoded colors, wrong tokens, opacity misuse |
| Button Anti-Patterns | Raw HTML buttons, wrong presets, missing states |
| Form Anti-Patterns | Custom inputs, inline validation, accessibility |
| Layout Anti-Patterns | Hardcoded spacing, z-index abuse, breakpoints |
| Component Usage Anti-Patterns | Wrong components, over-engineering, prop misuse |
| AI Slop Anti-Patterns | Wrapper div soup, over-complicated state, premature abstraction |

**Use Case**: Load at session start so AI agents know what to avoid before generating code.

### examples://components

Library of correct component usage examples, organized by component and use case.

**URI**: `examples://components`

**Returns** (JSON):
```json
{
  "title": "Component Usage Examples",
  "components": {
    "Button": {
      "description": "Action triggers with semantic presets",
      "examples": [
        {
          "name": "Primary Action",
          "description": "Main call-to-action button",
          "code": "<Button preset=\"primary-action\">Save Changes</Button>",
          "when": "Use for the primary action in a form or dialog",
          "props": { "preset": "primary-action" }
        }
      ]
    }
  },
  "metadata": { "version": "1.0.0" }
}
```

**Use Case**: Reference correct usage patterns when generating component code.

### icons://library

Valid icon names from the project's icon library. Prevents AI from hallucinating icon names that cause build failures.

**URI**: `icons://library`

**Returns** (JSON):
```json
{
  "title": "Icon Library Context",
  "description": "Valid icon names for AI code generation. NEVER invent icon names.",
  "libraries": {
    "@phosphor-icons/react": {
      "name": "Phosphor Icons",
      "totalIcons": 1248,
      "icons": ["Activity", "AddressBook", "Airplane", ...],
      "weights": ["thin", "light", "regular", "bold", "fill", "duotone"],
      "usage": {
        "import": "import { IconName } from '@phosphor-icons/react'",
        "component": "<IconName size={24} weight=\"regular\" />"
      },
      "brandPreferences": {
        "messaging": { "preferred": "ChatCircle", "avoid": ["Chat"] },
        "send": { "preferred": "PaperPlaneRight", "avoid": ["PaperPlane", "Send"] }
      }
    }
  },
  "guidelines": {
    "critical": ["NEVER invent icon names", "ALWAYS verify icon exists"],
    "commonMistakes": [
      { "wrong": "IconSend", "right": "PaperPlaneRight" },
      { "wrong": "SettingsIcon", "right": "Gear" }
    ]
  }
}
```

**Use Case**: Load at session start to prevent hallucinated icon names and enforce brand consistency.

### styleguide://voice

Voice profile for UX writing. Defines tone spectrum, traits with do/don't examples, and principles for consistent product voice.

**URI**: `styleguide://voice`

**Returns** (JSON):
```json
{
  "profile": {
    "name": "Professional Friendly",
    "description": "A balanced voice that is professional yet approachable...",
    "toneSpectrum": {
      "formality": 6,
      "playfulness": 4,
      "enthusiasm": 6,
      "technicality": 5
    },
    "traits": [
      {
        "name": "Clear over clever",
        "description": "Prioritize understanding over wit...",
        "doExamples": ["Your changes have been saved.", "Enter your email address..."],
        "dontExamples": ["Your data is now immortalized!", "Drop your digits here."]
      }
    ],
    "principles": ["Write for scanning, not reading", "Front-load important information"]
  },
  "usage": {
    "keyTraits": ["Clear over clever", "Helpful not condescending", "Concise but complete"],
    "toneDescription": "Formality: 6/10, Playfulness: 4/10, Enthusiasm: 6/10, Technicality: 5/10"
  },
  "aiGuidance": ["Refer to do/don't examples", "Match tone to context"]
}
```

**Use Case**: Load at session start to ensure consistent voice across all generated UI copy.

### styleguide://terminology

Terminology glossary with preferred terms and forbidden alternatives.

**URI**: `styleguide://terminology`

**Returns** (JSON):
```json
{
  "glossary": {
    "entries": [
      {
        "id": "sign-in",
        "preferred": "Sign in",
        "forbidden": ["Log in", "Login", "Sign on"],
        "context": "User authentication",
        "reason": "Consistent with modern product conventions",
        "category": "product"
      }
    ],
    "guidance": ["Use terminology consistently", "Prefer the simpler term"]
  },
  "quickLookup": {
    "log in": "Sign in",
    "login": "Sign in",
    "register": "Sign up"
  },
  "byCategory": {
    "product": [...],
    "action": [...],
    "status": [...],
    "technical": [...]
  },
  "aiGuidance": ["Always use preferred terms", "Check quickLookup for fast replacement"]
}
```

**Use Case**: Ensure consistent terminology when generating UI text.

### styleguide://patterns

Content patterns for common UI copy scenarios with templates and examples.

**URI**: `styleguide://patterns`

**Returns** (JSON):
```json
{
  "library": {
    "patterns": [
      {
        "id": "error-generic",
        "type": "error-message",
        "name": "Generic Error",
        "whenToUse": "When something goes wrong but you can't be specific",
        "template": "Something went wrong. {action}",
        "constraints": {
          "maxLength": 100,
          "tone": "empathetic",
          "mustInclude": ["what to do next"],
          "mustAvoid": ["technical jargon", "blame language"]
        },
        "goodExamples": ["Something went wrong. Please try again."],
        "badExamples": ["Error 500: Internal Server Exception"]
      }
    ]
  },
  "byType": {
    "errorMessage": [...],
    "successMessage": [...],
    "emptyState": [...],
    "confirmationDialog": [...],
    "buttonLabel": [...],
    "tooltip": [...],
    "placeholder": [...]
  },
  "aiGuidance": ["Match patterns to context", "Adapt templates, don't use verbatim"]
}
```

**Use Case**: Reference appropriate patterns when generating error messages, success messages, empty states, etc.

### styleguide://grammar

Grammar and mechanical rules for UI writing.

**URI**: `styleguide://grammar`

**Returns** (JSON):
```json
{
  "rules": {
    "rules": [
      {
        "id": "sentence-case",
        "type": "capitalization",
        "name": "Use sentence case for UI text",
        "description": "Capitalize only the first word and proper nouns...",
        "correct": ["Create new project", "API settings"],
        "incorrect": ["Create New Project", "API Settings"],
        "priority": "high"
      }
    ],
    "guidance": ["Consistency is more important than any single rule"]
  },
  "byType": {
    "capitalization": [...],
    "punctuation": [...],
    "numbers": [...],
    "contractions": [...],
    "formatting": [...]
  },
  "byPriority": {
    "high": [...],
    "medium": [...],
    "low": [...]
  },
  "quickRules": [
    "Use sentence case for UI text (not Title Case)",
    "No periods in buttons or labels",
    "Use digits (1, 2, 3) not words (one, two, three)"
  ],
  "aiGuidance": ["High priority rules should always be followed"]
}
```

**Use Case**: Apply consistent grammar and mechanical rules to generated UI copy.

## Style Guide Tools

### check_copy

Validates UI copy against the style guide.

**Parameters**:
- `text` (required): The copy text to check
- `context` (optional): Where this copy appears ('button', 'error', 'tooltip', etc.)

**Returns**:
```json
{
  "isValid": true,
  "score": 85,
  "issues": [
    {
      "type": "terminology",
      "severity": "warning",
      "message": "Use \"Sign in\" instead of \"Log in\"",
      "suggestion": "Sign in",
      "location": { "start": 0, "end": 6 }
    }
  ],
  "recommendations": [
    "Review terminology guidelines and use preferred terms consistently"
  ],
  "contextGuidance": [
    "Buttons should use action verbs (Save, Delete, Create)",
    "Keep under 20 characters",
    "No periods at the end"
  ]
}
```

**Use Case**: Validate copy before shipping. Catches terminology violations, grammar issues, and voice misalignment.

## AI Contribution Tools

These tools enable bidirectional communication - AI tools can contribute back to the design system by reporting discoveries.

### report_antipattern

Report a new anti-pattern discovered during code review. Creates a suggestion queued for human review.

**Parameters**:
- `design_system_id` (required): UUID of the design system
- `category` (required): Category ('element', 'pattern', 'attribute', 'import', 'color', 'spacing', 'typography')
- `element` (required): The problematic element or pattern
- `pattern` (optional): Regex pattern for detection
- `replacement` (required): What to use instead
- `reason` (required): Why this is problematic (min 20 chars)
- `severity` (required): 'error' or 'warning'
- `context` (optional): Where this was discovered (file, line, component)
- `confidence` (optional): Confidence level (0.0-1.0)

**Returns**:
```json
{
  "success": true,
  "suggestion_id": "uuid",
  "message": "Anti-pattern suggestion created and queued for review",
  "status": "pending"
}
```

**Use Case**: When reviewing code, report patterns that violate design system principles so they can be added to the anti-patterns list.

### report_violation

Report a violation of an existing design system rule found in code.

**Parameters**:
- `design_system_id` (required): UUID of the design system
- `rule_id` (required): ID of the rule that was violated
- `code_snippet` (required): The violating code
- `file_path` (required): Path to the file
- `line_number` (optional): Line number
- `suggestion` (required): How to fix the violation
- `confidence` (optional): Confidence level (0.0-1.0)

**Returns**:
```json
{
  "success": true,
  "suggestion_id": "uuid",
  "message": "Violation recorded for review",
  "status": "pending"
}
```

**Use Case**: Track where violations occur to improve detection and understand common issues.

### suggest_terminology

Suggest a new terminology entry for the style guide.

**Parameters**:
- `design_system_id` (required): UUID of the design system
- `preferred` (required): The preferred term
- `forbidden` (required): Array of terms to avoid
- `context` (required): When/where this applies
- `reason` (required): Why this is preferred
- `category` (required): Category ('product', 'technical', 'action', 'status', 'general')
- `confidence` (optional): Confidence level (0.0-1.0)

**Returns**:
```json
{
  "success": true,
  "suggestion_id": "uuid",
  "message": "Terminology suggestion created and queued for review",
  "status": "pending"
}
```

**Use Case**: When encountering inconsistent language, suggest standardization.

### suggest_pattern

Suggest a new content pattern for the style guide.

**Parameters**:
- `design_system_id` (required): UUID of the design system
- `type` (required): Pattern type ('error-message', 'success-message', 'empty-state', etc.)
- `name` (required): Human-readable name
- `template` (required): Template with {placeholders}
- `when_to_use` (required): When this pattern should be used
- `good_examples` (required): Array of good examples
- `bad_examples` (optional): Array of bad examples
- `constraints` (optional): Constraints like maxLength, tone, etc.
- `confidence` (optional): Confidence level (0.0-1.0)

**Returns**:
```json
{
  "success": true,
  "suggestion_id": "uuid",
  "message": "Pattern suggestion created and queued for review",
  "status": "pending"
}
```

**Use Case**: When identifying recurring content patterns, codify them for consistency.

## Icon Tools

### validate_icon

Validates an icon name against the project's icon library.

**Parameters**:
- `iconName` (required): The icon name to validate
- `library` (optional): Icon library package name (default: '@phosphor-icons/react')

**Returns**:
- `valid`: Whether the icon exists
- `suggestions`: Similar valid icons if invalid
- `brandPreference`: Preferred icon for this use case
- `usage`: Import and component code

**Use Case**: Call BEFORE generating code with icons to prevent build failures.

### suggest_icon

Suggests icons based on a description or use case.

**Parameters**:
- `description` (required): What the icon should represent (e.g., "send message", "settings")
- `library` (optional): Icon library (default: '@phosphor-icons/react')
- `limit` (optional): Max suggestions (default: 5)

**Returns**:
- `suggestions`: Array of matching icon names
- `usage`: Import and component code for top suggestion

**Use Case**: Find the right icon for a specific purpose.

## Figma Integration Tools

These tools help bridge Figma design files with Preset's semantic token system. They provide **enrichment** on top of Figma's API by mapping Figma variables and styles to Preset's semantic schema with philosophy validation and drift detection.

**Note**: Figma's Variables API requires an Enterprise plan. These tools gracefully fall back to the Styles API (available on all plans) when Variables API access is denied.

### figma_map_tokens_to_preset

Maps Figma design file tokens (variables or styles) to Preset's semantic token schema with AI-powered enrichment.

**Parameters**:
- `file_url` (required): Figma file URL (e.g., `https://www.figma.com/design/FILEKEY/...`)
- `access_token` (required): Figma Personal Access Token
- `use_styles_fallback` (optional): Force use of Styles API even if Variables API is available (default: false)

**Returns**:
- `tokens`: Array of mapped tokens with:
  - `figmaName`: Original Figma variable/style name
  - `value`: Hex color value
  - `darkValue`: Dark mode value (if available)
  - `semantic`: Mapped Preset semantic token (e.g., 'primary', 'background')
  - `confidence`: Mapping confidence score (0-100)
  - `source`: 'variables' or 'styles'
- `unmapped`: Tokens that couldn't be mapped with reason
- `stats`: Summary statistics (total, mapped, unmapped, highConfidence, lowConfidence)
- `apiUsed`: Which Figma API was used ('variables' or 'styles')
- `fallbackUsed`: Whether fallback to Styles API occurred
- `enrichment`: Preset-specific enhancements
  - `colorGuidance`: Recommendations for token usage
  - `philosophyWarnings`: Design philosophy concerns

**Use Case**: Import Figma design tokens into Preset with semantic mapping.

### figma_compare_tokens

Compares Figma tokens against Preset's current design tokens to detect drift.

**Parameters**:
- `file_url` (required): Figma file URL
- `access_token` (required): Figma Personal Access Token
- `preset_tokens` (required): Current Preset tokens to compare against (object with semantic token keys and hex values)

**Returns**:
- `hasDrift`: Whether drift was detected between Figma and Preset
- `driftScore`: 0-100 (0 = perfect sync, 100 = complete divergence)
- `onlyInFigma`: Tokens that exist only in Figma
- `onlyInPreset`: Tokens that exist only in Preset
- `valueDifferences`: Tokens with different values between Figma and Preset
- `recommendations`: Actionable suggestions to resolve drift

**Use Case**: Audit design token consistency between Figma source-of-truth and codebase.

### figma_get_components

Fetches all published components from a Figma file with intelligent description fallbacks.

**Parameters**:
- `file_url` (required): Figma file URL
- `access_token` (required): Figma Personal Access Token

**Returns**:
- `components`: Array of components with:
  - `key`: Figma component key
  - `name`: Component name (e.g., "Button/Primary/Large")
  - `description`: API description or inferred from name
  - `inferredDescription`: Present if description was inferred
  - `componentSetName`: Parent variant set name (if applicable)
- `componentSets`: Array of component sets (variant parents)
- `stats`: Summary statistics (totalComponents, withDescription, withoutDescription)
- `guidance`: Recommendations for next steps

**Description Fallback Hierarchy**:
1. REST API description (if available)
2. Parent ComponentSet description (for variants)
3. Inferred from component name (e.g., "Button/Primary" → "Primary button")

**Use Case**: Discover components in a Figma file before mapping to Presets.

### figma_suggest_preset_mapping

Suggests Preset presets that match a Figma component based on name and description.

**Parameters**:
- `component_name` (required): Figma component name (e.g., "Button/Primary/Large")
- `component_description` (optional): Component description from Figma API

**Returns**:
- `figmaComponent`: The component being mapped
- `suggestions`: Array of suggested presets (ranked by confidence) with:
  - `presetName`: Preset name (e.g., "primary-action")
  - `componentType`: Component type (button, input, badge, etc.)
  - `confidence`: Match confidence (0-100)
  - `reasoning`: Why this preset was suggested
  - `inferredFromName`: Whether description was inferred
- `descriptionSource`: 'api', 'componentSet', or 'inferred'
- `warning`: Present if confidence is low or description was inferred

**Use Case**: Map Figma components to Preset presets with intelligent matching.

### Figma Integration Pattern

```
1. EXTRACT tokens from Figma:
   - Call figma_map_tokens_to_preset(file_url, access_token)
   - Review confidence scores and unmapped tokens
   - Use enrichment guidance to refine mappings

2. DETECT drift from source-of-truth:
   - Call figma_compare_tokens(file_url, access_token, preset_tokens)
   - Review valueDifferences for unintended changes
   - Follow recommendations to sync tokens

3. MAP components to presets:
   - Call figma_get_components(file_url, access_token) to discover components
   - For each component, call figma_suggest_preset_mapping(name, description)
   - Review suggestions and confirm mappings
   - Works even for components without descriptions

4. HANDLE Enterprise limitation:
   - If Variables API returns ENTERPRISE_REQUIRED error
   - Tools automatically fall back to Styles API
   - Fewer tokens may be available (styles vs variables)
```

### plan_feature

Generate a structured implementation plan for a multi-component UI feature from natural language intent. Composes data from recipes, intent routes, context rules, and presets — no LLM calls.

**Parameters**:
- `intent` (required): Natural language description (e.g., "settings page with profile editing and notifications")
- `context` (optional): Object with `filePath`, `location`, `existingComponents`
- `options` (optional): Object with `maxSteps`, `includeCode`, `includeFileStructure`, `layerId`

**Returns**:
- `planName`: Generated name for the plan
- `complexity`: `simple` | `moderate` | `complex`
- `sources`: Which data sources contributed (recipes, intentRoutes, contextRules)
- `steps`: Ordered array with component, preset, code, importStatement, phase, dependsOn
- `checkpoints`: Validation tool calls at phase boundaries
- `constraints`: Forbidden primitives and context rules that apply
- `antiPatterns`: Things to avoid
- `fileStructure`: Suggested file organization
- `guidance`: Overview, key decisions, and tips
- `confidence`: 0-1 score (0.9 recipe, 0.7 DB routes, 0.3 core fallback)

**Use Case**: When building multi-component features, call this first to get an ordered plan instead of manually calling get_intent_route for each component.

## Agent Integration Pattern

For optimal results, AI agents should follow this pattern:

```
0. AT SESSION START (one-time):
   - Load anti-patterns://design-system resource to know what to avoid
   - Load examples://components resource for correct usage patterns
   - Load icons://library resource for valid icon names
   - Load styleguide://voice resource for product voice and tone
   - Load styleguide://terminology resource for preferred terms
   - Load styleguide://patterns resource for UI copy templates
   - Load styleguide://grammar resource for mechanical rules

1. BEFORE generating code:
   - Call get_forbidden_primitives() to understand what's not allowed
   - Call get_active_constraints(filePath, intent) for context-specific rules
   - Call get_design_tokens(category) to understand available tokens
   - Call list_components() to discover available components
   - Call get_component_api(component) to get props, presets, and types
   - Call validate_before_generation(intent) to get recommended approach
   - Call suggest_icon(description) to find correct icon names
   - Call validate_icon(iconName) to verify icon exists

2. DURING generation:
   - Follow the constraints and suggested approach
   - Use recommended components and presets
   - Use design system tokens instead of hardcoded values
   - Use correct prop types from get_component_api results
   - Avoid patterns listed in anti-patterns resource
   - Only use icons from the icons://library resource

3. AFTER generating code:
   - Call validate_generated_code(code, autoCorrect) to check for violations
   - Call check_copy(text, context) to validate any UI text against style guide
   - If violations found:
     - Call suggest_fixes(code, autoApply=true) to get corrected code
     - Or use the fix suggestions to manually update the code

4. FOR AUDITING (optional):
   - Call check_drift(code) to measure deviation from canonical presets
   - Use drift score to track design system adoption over time
```

## Development

```bash
# Build
npm run build

# Test
npm run test

# Type check
npm run typecheck

# Watch mode
npm run dev
```

## Architecture

This package depends on:
- `@preset/core` - Provides intent routing, context analysis, and validation services
- `@modelcontextprotocol/sdk` - MCP server implementation
- `zod` - Schema validation for tool parameters

## License

MIT