# DSS MCP Plugin - Implementation Plan

**Version:** 1.0
**Date:** December 2024
**Status:** Planning

---

## Executive Summary

This document provides a comprehensive implementation plan for completing the DSS MCP (Model Context Protocol) plugin. The plan covers three missing tool categories: **Storybook Integration**, **Skin/Theme Management**, and **Design Application** - totaling 15 new MCP tools.

### Current State
- Figma integration: 5 tools (COMPLETE)
- Project management: 7 tools (COMPLETE)
- **Storybook integration: 5 tools (MISSING)**
- **Skin/Theme management: 5 tools (MISSING)**
- **Design application: 5 tools (MISSING)**

---

## Table of Contents

1. [Architecture Overview](#1-architecture-overview)
2. [File-by-File Breakdown](#2-file-by-file-breakdown)
3. [Tool Definitions](#3-tool-definitions)
4. [Integration Points](#4-integration-points)
5. [Implementation Order](#5-implementation-order)
6. [Testing Strategy](#6-testing-strategy)
7. [Risk Assessment](#7-risk-assessment)

---

## 1. Architecture Overview

### Existing Pattern

The MCP plugin follows a layered architecture:

```
tools/dss_mcp/
├── server.py              # FastAPI + SSE server, MCP protocol handlers
├── handler.py             # Unified tool execution, routing by category
├── integrations/
│   ├── base.py            # BaseIntegration, CircuitBreaker
│   └── figma.py           # FIGMA_TOOLS list + FigmaTools executor
├── tools/
│   └── project_tools.py   # PROJECT_TOOLS list + ProjectTools executor
└── context/
    └── project_context.py # Project context loading/caching
```

### Python Core (dss-mvp1/dss/)

```
dss/
├── storybook/
│   ├── scanner.py         # StorybookScanner - scan existing stories
│   ├── generator.py       # StoryGenerator - generate stories from components
│   ├── theme.py           # ThemeGenerator - generate Storybook themes from tokens
│   └── config.py          # Host/port configuration utilities
├── themes/
│   └── default_themes.py  # get_default_light_theme(), get_default_dark_theme()
├── models/
│   └── theme.py           # Theme, DesignToken, TokenCategory models
├── ingest/
│   ├── base.py            # DesignToken, TokenCollection, TokenSource
│   ├── css.py             # CSSTokenSource
│   ├── scss.py            # SCSSTokenSource
│   └── tailwind.py        # TailwindTokenSource
├── export_import/
│   └── service.py         # DSSProjectService - export/import operations
└── tools/
    └── style_dictionary.py # StyleDictionaryWrapper - token transformation
```

---

## 2. File-by-File Breakdown

### 2.1 New Files to Create

#### A. `/tools/dss_mcp/integrations/storybook.py`

Storybook integration module wrapping Python core functionality.

```python
# Purpose: MCP tool definitions and executor for Storybook integration
# Dependencies: dss.storybook (scanner, generator, theme, config)
# Pattern: Follows figma.py structure

STORYBOOK_TOOLS = [
    types.Tool(name="storybook_scan", ...),
    types.Tool(name="storybook_generate_stories", ...),
    types.Tool(name="storybook_generate_theme", ...),
    types.Tool(name="storybook_get_status", ...),
    types.Tool(name="storybook_configure", ...),
]

class StorybookIntegration:
    # Wraps StorybookScanner, StoryGenerator, ThemeGenerator

class StorybookTools:
    # MCP tool executor
```

#### B. `/tools/dss_mcp/integrations/themes.py`

Theme/skin management integration module.

```python
# Purpose: MCP tools for skin/theme management
# Dependencies: dss.themes, dss.models.theme, dss.tools.style_dictionary

THEME_TOOLS = [
    types.Tool(name="theme_list_skins", ...),
    types.Tool(name="theme_get_skin", ...),
    types.Tool(name="theme_create_skin", ...),
    types.Tool(name="theme_apply_skin", ...),
    types.Tool(name="theme_export_tokens", ...),
]

class ThemeIntegration:
    # Wraps Theme models and StyleDictionaryWrapper

class ThemeTools:
    # MCP tool executor
```

#### C. `/tools/dss_mcp/integrations/design_application.py`

Design application integration module for applying designs to projects.

```python
# Purpose: MCP tools for applying design system to codebases
# Dependencies: dss.ingest, dss.export_import, dss.analyze

DESIGN_APPLICATION_TOOLS = [
    types.Tool(name="design_apply_tokens", ...),
    types.Tool(name="design_generate_css", ...),
    types.Tool(name="design_update_components", ...),
    types.Tool(name="design_preview_changes", ...),
    types.Tool(name="design_validate_application", ...),
]

class DesignApplicationIntegration:
    # Wraps token transformation and export services

class DesignApplicationTools:
    # MCP tool executor
```

### 2.2 Files to Modify

#### A. `/tools/dss_mcp/handler.py`

**Changes:**
1. Import new tool modules
2. Register new tool categories in `_initialize_tools()`
3. Add execution handlers for each new category

```python
# Add imports
from .integrations.storybook import STORYBOOK_TOOLS, StorybookTools
from .integrations.themes import THEME_TOOLS, ThemeTools
from .integrations.design_application import DESIGN_APPLICATION_TOOLS, DesignApplicationTools

# In _initialize_tools():
# Register Storybook tools
for tool in STORYBOOK_TOOLS:
    self._tool_registry[tool.name] = {
        "tool": tool,
        "category": "storybook",
        "requires_integration": False
    }

# Register Theme tools
for tool in THEME_TOOLS:
    self._tool_registry[tool.name] = {
        "tool": tool,
        "category": "theme",
        "requires_integration": False
    }

# Register Design Application tools
for tool in DESIGN_APPLICATION_TOOLS:
    self._tool_registry[tool.name] = {
        "tool": tool,
        "category": "design_application",
        "requires_integration": False
    }

# Add execution handlers
async def _execute_storybook_tool(self, ...): ...
async def _execute_theme_tool(self, ...): ...
async def _execute_design_application_tool(self, ...): ...
```

#### B. `/tools/dss_mcp/server.py`

**Changes:**
1. Import new tool lists for listing
2. Update `list_tools()` to include new categories

```python
# Add imports
from .integrations.storybook import STORYBOOK_TOOLS
from .integrations.themes import THEME_TOOLS
from .integrations.design_application import DESIGN_APPLICATION_TOOLS

# In list_tools():
tools = PROJECT_TOOLS.copy()
tools.extend(WORKFLOW_TOOLS)
tools.extend(DEBUG_TOOLS)
tools.extend(STORYBOOK_TOOLS)      # New
tools.extend(THEME_TOOLS)          # New
tools.extend(DESIGN_APPLICATION_TOOLS)  # New
tools.extend(plugin_registry.get_all_tools())
```

---

## 3. Tool Definitions

### 3.1 Storybook Integration Tools (5 tools)

#### Tool 1: `storybook_scan`

```python
types.Tool(
    name="storybook_scan",
    description="Scan project for existing Storybook configuration and stories. Returns story inventory, configuration details, and coverage statistics.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "path": {
                "type": "string",
                "description": "Optional: Specific path to scan (defaults to project root)"
            }
        },
        "required": ["project_id"]
    }
)
```

**Implementation:**
```python
async def scan_storybook(self, project_id: str, path: str = None) -> Dict[str, Any]:
    """Scan for Storybook config and stories."""
    project_path = await self._get_project_path(project_id)
    scan_path = Path(path) if path else project_path

    scanner = StorybookScanner(str(scan_path))
    result = await scanner.scan()
    coverage = await scanner.get_story_coverage()

    return {
        "project_id": project_id,
        "config": result.get("config"),
        "stories_count": result.get("stories_count"),
        "components_with_stories": result.get("components_with_stories"),
        "stories": result.get("stories"),
        "coverage": coverage
    }
```

---

#### Tool 2: `storybook_generate_stories`

```python
types.Tool(
    name="storybook_generate_stories",
    description="Generate Storybook stories for React components. Supports CSF3, CSF2, and MDX formats with automatic prop detection.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "component_path": {
                "type": "string",
                "description": "Path to component file or directory"
            },
            "template": {
                "type": "string",
                "description": "Story format template",
                "enum": ["csf3", "csf2", "mdx"],
                "default": "csf3"
            },
            "include_variants": {
                "type": "boolean",
                "description": "Generate variant stories (default: true)",
                "default": True
            },
            "dry_run": {
                "type": "boolean",
                "description": "Preview without writing files (default: true)",
                "default": True
            }
        },
        "required": ["project_id", "component_path"]
    }
)
```

**Implementation:**
```python
async def generate_stories(
    self,
    project_id: str,
    component_path: str,
    template: str = "csf3",
    include_variants: bool = True,
    dry_run: bool = True
) -> Dict[str, Any]:
    """Generate stories for components."""
    project_path = await self._get_project_path(project_id)
    generator = StoryGenerator(str(project_path))

    template_enum = StoryTemplate(template)

    # Check if path is file or directory
    full_path = project_path / component_path

    if full_path.is_dir():
        results = await generator.generate_stories_for_directory(
            component_path,
            template=template_enum,
            dry_run=dry_run
        )
        return {
            "project_id": project_id,
            "generated_count": len([r for r in results if "story" in r]),
            "results": results,
            "dry_run": dry_run
        }
    else:
        story = await generator.generate_story(
            component_path,
            template=template_enum,
            include_variants=include_variants
        )
        return {
            "project_id": project_id,
            "component": component_path,
            "story": story,
            "template": template,
            "dry_run": dry_run
        }
```

---

#### Tool 3: `storybook_generate_theme`

```python
types.Tool(
    name="storybook_generate_theme",
    description="Generate Storybook theme configuration from design tokens. Creates manager.ts, preview.ts, and theme files.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "brand_title": {
                "type": "string",
                "description": "Brand title for Storybook UI",
                "default": "Design System"
            },
            "base_theme": {
                "type": "string",
                "description": "Base theme (light or dark)",
                "enum": ["light", "dark"],
                "default": "light"
            },
            "output_dir": {
                "type": "string",
                "description": "Output directory (default: .storybook)"
            },
            "write_files": {
                "type": "boolean",
                "description": "Write files to disk (default: false - preview only)",
                "default": False
            }
        },
        "required": ["project_id"]
    }
)
```

**Implementation:**
```python
async def generate_theme(
    self,
    project_id: str,
    brand_title: str = "Design System",
    base_theme: str = "light",
    output_dir: str = None,
    write_files: bool = False
) -> Dict[str, Any]:
    """Generate Storybook theme from design tokens."""
    # Get project tokens
    context = await self.context_manager.get_context(project_id)
    if not context:
        return {"error": f"Project not found: {project_id}"}

    # Convert tokens to list format for ThemeGenerator
    tokens_list = [
        {"name": name, "value": token.get("value")}
        for name, token in context.tokens.items()
    ]

    generator = ThemeGenerator()

    if write_files and output_dir:
        files = generator.generate_full_config(
            tokens=tokens_list,
            brand_title=brand_title,
            output_dir=output_dir
        )
        return {
            "project_id": project_id,
            "files_written": list(files.keys()),
            "output_dir": output_dir
        }
    else:
        # Preview mode
        theme = generator.generate_from_tokens(tokens_list, brand_title, base_theme)
        theme_file = generator.generate_theme_file(theme, "ts")
        manager_file = generator.generate_manager_file()
        preview_file = generator.generate_preview_file(tokens_list)

        return {
            "project_id": project_id,
            "preview": True,
            "files": {
                "dss-theme.ts": theme_file,
                "manager.ts": manager_file,
                "preview.ts": preview_file
            },
            "theme_config": theme.to_dict()
        }
```

---

#### Tool 4: `storybook_get_status`

```python
types.Tool(
    name="storybook_get_status",
    description="Get Storybook installation and configuration status for a project.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            }
        },
        "required": ["project_id"]
    }
)
```

**Implementation:**
```python
async def get_status(self, project_id: str) -> Dict[str, Any]:
    """Get Storybook status."""
    project_path = await self._get_project_path(project_id)
    status = get_storybook_status(project_path)

    return {
        "project_id": project_id,
        **status
    }
```

---

#### Tool 5: `storybook_configure`

```python
types.Tool(
    name="storybook_configure",
    description="Configure or update Storybook for a project with DSS integration.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "action": {
                "type": "string",
                "description": "Configuration action",
                "enum": ["init", "update", "add_theme"],
                "default": "init"
            },
            "options": {
                "type": "object",
                "description": "Configuration options",
                "properties": {
                    "framework": {"type": "string", "enum": ["react", "vue", "angular"]},
                    "builder": {"type": "string", "enum": ["vite", "webpack5"]},
                    "typescript": {"type": "boolean"}
                }
            }
        },
        "required": ["project_id"]
    }
)
```

---

### 3.2 Theme/Skin Management Tools (5 tools)

#### Tool 1: `theme_list_skins`

```python
types.Tool(
    name="theme_list_skins",
    description="List all available design system skins/themes including built-in defaults and project-specific themes.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "include_builtin": {
                "type": "boolean",
                "description": "Include built-in DSS themes (default: true)",
                "default": True
            }
        },
        "required": ["project_id"]
    }
)
```

**Implementation:**
```python
async def list_skins(
    self,
    project_id: str,
    include_builtin: bool = True
) -> Dict[str, Any]:
    """List available skins/themes."""
    skins = []

    # Add built-in themes
    if include_builtin:
        light = get_default_light_theme()
        dark = get_default_dark_theme()

        skins.append({
            "name": light.name,
            "type": "builtin",
            "version": light.version,
            "token_count": len(light.tokens),
            "mode": "light"
        })
        skins.append({
            "name": dark.name,
            "type": "builtin",
            "version": dark.version,
            "token_count": len(dark.tokens),
            "mode": "dark"
        })

    # Add project-specific themes from database
    project_themes = await self._get_project_themes(project_id)
    skins.extend(project_themes)

    return {
        "project_id": project_id,
        "total_count": len(skins),
        "skins": skins
    }
```

---

#### Tool 2: `theme_get_skin`

```python
types.Tool(
    name="theme_get_skin",
    description="Get detailed information about a specific skin/theme including all design tokens.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "skin_name": {
                "type": "string",
                "description": "Name of the skin to retrieve"
            },
            "include_tokens": {
                "type": "boolean",
                "description": "Include full token definitions (default: true)",
                "default": True
            }
        },
        "required": ["project_id", "skin_name"]
    }
)
```

---

#### Tool 3: `theme_create_skin`

```python
types.Tool(
    name="theme_create_skin",
    description="Create a new skin/theme by extending an existing base theme or from scratch.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "name": {
                "type": "string",
                "description": "Name for the new skin"
            },
            "base_skin": {
                "type": "string",
                "description": "Base skin to extend (optional)"
            },
            "tokens": {
                "type": "object",
                "description": "Token overrides or new tokens",
                "additionalProperties": {
                    "type": "object",
                    "properties": {
                        "value": {"type": "string"},
                        "type": {"type": "string"},
                        "description": {"type": "string"}
                    }
                }
            },
            "description": {
                "type": "string",
                "description": "Skin description"
            }
        },
        "required": ["project_id", "name"]
    }
)
```

---

#### Tool 4: `theme_apply_skin`

```python
types.Tool(
    name="theme_apply_skin",
    description="Apply a skin/theme to the project, updating token references and generating output files.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "skin_name": {
                "type": "string",
                "description": "Name of the skin to apply"
            },
            "output_formats": {
                "type": "array",
                "items": {
                    "type": "string",
                    "enum": ["css", "scss", "json", "js", "tailwind"]
                },
                "description": "Output formats to generate",
                "default": ["css"]
            },
            "output_dir": {
                "type": "string",
                "description": "Output directory for generated files"
            },
            "preview": {
                "type": "boolean",
                "description": "Preview changes without writing (default: true)",
                "default": True
            }
        },
        "required": ["project_id", "skin_name"]
    }
)
```

---

#### Tool 5: `theme_export_tokens`

```python
types.Tool(
    name="theme_export_tokens",
    description="Export design tokens from a skin/theme to various formats (CSS, SCSS, JSON, Tailwind, TypeScript).",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "skin_name": {
                "type": "string",
                "description": "Skin name to export (optional, uses project tokens if not specified)"
            },
            "format": {
                "type": "string",
                "description": "Export format",
                "enum": ["css", "scss", "json", "js", "tailwind", "typescript"],
                "default": "css"
            },
            "output_path": {
                "type": "string",
                "description": "Output file path (optional, returns content if not specified)"
            }
        },
        "required": ["project_id", "format"]
    }
)
```

**Implementation:**
```python
async def export_tokens(
    self,
    project_id: str,
    format: str,
    skin_name: str = None,
    output_path: str = None
) -> Dict[str, Any]:
    """Export tokens to various formats."""
    # Get tokens from skin or project
    if skin_name:
        tokens = await self._get_skin_tokens(project_id, skin_name)
    else:
        context = await self.context_manager.get_context(project_id)
        tokens = context.tokens

    # Convert to TokenCollection for export
    from dss.ingest.base import TokenCollection, DesignToken

    collection = TokenCollection()
    for name, token_data in tokens.items():
        collection.add(DesignToken(
            name=name,
            value=token_data.get("value"),
            type=token_data.get("type", "string")
        ))

    # Export based on format
    format_handlers = {
        "css": collection.to_css,
        "scss": collection.to_scss,
        "json": collection.to_json,
        "typescript": collection.to_typescript,
        "tailwind": collection.to_tailwind_config,
    }

    handler = format_handlers.get(format)
    if not handler:
        return {"error": f"Unsupported format: {format}"}

    content = handler()

    if output_path:
        Path(output_path).write_text(content)
        return {
            "project_id": project_id,
            "format": format,
            "output_path": output_path,
            "token_count": len(collection)
        }

    return {
        "project_id": project_id,
        "format": format,
        "content": content,
        "token_count": len(collection)
    }
```

---

### 3.3 Design Application Tools (5 tools)

#### Tool 1: `design_apply_tokens`

```python
types.Tool(
    name="design_apply_tokens",
    description="Apply design tokens to a project, generating token files in the specified format and location.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "token_source": {
                "type": "string",
                "description": "Source of tokens (figma, skin name, or 'project')",
                "default": "project"
            },
            "output_format": {
                "type": "string",
                "description": "Output format for tokens",
                "enum": ["css", "scss", "json", "js", "tailwind"],
                "default": "css"
            },
            "output_path": {
                "type": "string",
                "description": "Output directory or file path"
            },
            "create_index": {
                "type": "boolean",
                "description": "Create index file that imports all tokens",
                "default": True
            },
            "preview": {
                "type": "boolean",
                "description": "Preview changes without writing",
                "default": True
            }
        },
        "required": ["project_id", "output_format", "output_path"]
    }
)
```

---

#### Tool 2: `design_generate_css`

```python
types.Tool(
    name="design_generate_css",
    description="Generate CSS files from design tokens with custom property definitions and utility classes.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "include_utilities": {
                "type": "boolean",
                "description": "Generate utility classes (like Tailwind)",
                "default": False
            },
            "include_reset": {
                "type": "boolean",
                "description": "Include CSS reset/normalize",
                "default": False
            },
            "selector": {
                "type": "string",
                "description": "Root selector for variables (default: :root)",
                "default": ":root"
            },
            "prefix": {
                "type": "string",
                "description": "CSS variable prefix (default: none)",
                "default": ""
            },
            "output_path": {
                "type": "string",
                "description": "Output file path (optional)"
            }
        },
        "required": ["project_id"]
    }
)
```

---

#### Tool 3: `design_update_components`

```python
types.Tool(
    name="design_update_components",
    description="Update React components to use design system tokens instead of hardcoded values.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "component_path": {
                "type": "string",
                "description": "Path to component file or directory"
            },
            "update_type": {
                "type": "string",
                "description": "Type of update to perform",
                "enum": ["inline_styles", "hardcoded_colors", "hardcoded_spacing", "all"],
                "default": "all"
            },
            "token_format": {
                "type": "string",
                "description": "How to reference tokens in code",
                "enum": ["css_var", "scss_var", "js_import", "tailwind"],
                "default": "css_var"
            },
            "preview": {
                "type": "boolean",
                "description": "Preview changes without writing",
                "default": True
            }
        },
        "required": ["project_id", "component_path"]
    }
)
```

---

#### Tool 4: `design_preview_changes`

```python
types.Tool(
    name="design_preview_changes",
    description="Preview what changes would be made when applying a design system to a project.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "skin_name": {
                "type": "string",
                "description": "Skin to preview applying (optional)"
            },
            "scope": {
                "type": "string",
                "description": "Scope of preview",
                "enum": ["tokens", "components", "full"],
                "default": "full"
            },
            "path": {
                "type": "string",
                "description": "Specific path to preview (optional)"
            }
        },
        "required": ["project_id"]
    }
)
```

---

#### Tool 5: `design_validate_application`

```python
types.Tool(
    name="design_validate_application",
    description="Validate that design tokens are correctly applied across the project. Checks for drift, inconsistencies, and missing tokens.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "check_drift": {
                "type": "boolean",
                "description": "Check for token drift from Figma source",
                "default": True
            },
            "check_usage": {
                "type": "boolean",
                "description": "Check token usage in components",
                "default": True
            },
            "check_coverage": {
                "type": "boolean",
                "description": "Check design system coverage",
                "default": True
            }
        },
        "required": ["project_id"]
    }
)
```

---

## 4. Integration Points

### 4.1 Python Core Module Mapping

| MCP Tool | Python Core Module | Classes/Functions |
|----------|-------------------|-------------------|
| `storybook_scan` | `dss.storybook.scanner` | `StorybookScanner.scan()` |
| `storybook_generate_stories` | `dss.storybook.generator` | `StoryGenerator.generate_story()` |
| `storybook_generate_theme` | `dss.storybook.theme` | `ThemeGenerator.generate_full_config()` |
| `storybook_get_status` | `dss.storybook.config` | `get_storybook_status()` |
| `storybook_configure` | `dss.storybook.config` | `write_storybook_config_file()` |
| `theme_list_skins` | `dss.themes` | `get_default_light_theme()`, `get_default_dark_theme()` |
| `theme_get_skin` | `dss.models.theme` | `Theme` model |
| `theme_create_skin` | `dss.models.theme` | `Theme`, `DesignToken` models |
| `theme_apply_skin` | `dss.tools.style_dictionary` | `StyleDictionaryWrapper.transform_theme()` |
| `theme_export_tokens` | `dss.ingest.base` | `TokenCollection.to_css()`, etc. |
| `design_apply_tokens` | `dss.tools.style_dictionary` | `StyleDictionaryWrapper` |
| `design_generate_css` | `dss.ingest.base` | `TokenCollection.to_css()` |
| `design_update_components` | `dss.analyze.quick_wins` | `QuickWinFinder` |
| `design_preview_changes` | `dss.analyze` | Various analyzers |
| `design_validate_application` | `dss.analyze.styles` | `StyleAnalyzer` |

### 4.2 Database Integration

New tables may be needed for skin/theme persistence:

```sql
-- Project themes/skins
CREATE TABLE IF NOT EXISTS project_themes (
    id INTEGER PRIMARY KEY,
    project_id TEXT NOT NULL,
    name TEXT NOT NULL,
    version TEXT DEFAULT '1.0.0',
    base_theme TEXT,
    tokens TEXT,  -- JSON blob
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(project_id, name)
);

-- Applied theme tracking
CREATE TABLE IF NOT EXISTS applied_themes (
    id INTEGER PRIMARY KEY,
    project_id TEXT NOT NULL,
    theme_name TEXT NOT NULL,
    applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    output_format TEXT,
    output_path TEXT
);
```

---

## 5. Implementation Order

### Phase 1: Foundation (Week 1)
**Priority: Critical**

1. **Create `/tools/dss_mcp/integrations/storybook.py`**
   - Implement `StorybookIntegration` class
   - Implement all 5 Storybook tools
   - Add tests for scanner and generator integration

2. **Update `handler.py`**
   - Add Storybook tool registration
   - Add `_execute_storybook_tool()` handler

3. **Update `server.py`**
   - Import and register Storybook tools

### Phase 2: Theme Management (Week 2)
**Priority: High**

1. **Create `/tools/dss_mcp/integrations/themes.py`**
   - Implement `ThemeIntegration` class
   - Implement all 5 theme tools
   - Add database migration for theme storage

2. **Update `handler.py`**
   - Add theme tool registration
   - Add `_execute_theme_tool()` handler

3. **Integration tests**
   - Test theme creation from tokens
   - Test theme application workflow

### Phase 3: Design Application (Week 3)
**Priority: High**

1. **Create `/tools/dss_mcp/integrations/design_application.py`**
   - Implement `DesignApplicationIntegration` class
   - Implement all 5 design application tools

2. **Update `handler.py`**
   - Add design application tool registration
   - Add `_execute_design_application_tool()` handler

3. **End-to-end testing**
   - Test full workflow: Figma -> Tokens -> Storybook -> Components

### Phase 4: Integration & Polish (Week 4)
**Priority: Medium**

1. **Documentation**
   - Update API documentation
   - Add usage examples
   - Update README

2. **Error handling refinement**
   - Add detailed error messages
   - Add recovery suggestions

3. **Performance optimization**
   - Add caching where appropriate
   - Optimize database queries

---

## 6. Testing Strategy

### 6.1 Unit Tests

**Location:** `tools/dss_mcp/tests/`

```python
# tests/test_storybook_tools.py
class TestStorybookTools:
    async def test_scan_empty_project(self):
        """Test scanning project with no Storybook."""

    async def test_scan_with_stories(self):
        """Test scanning project with existing stories."""

    async def test_generate_story_csf3(self):
        """Test CSF3 story generation."""

    async def test_generate_story_mdx(self):
        """Test MDX story generation."""

    async def test_generate_theme_from_tokens(self):
        """Test theme generation from project tokens."""

# tests/test_theme_tools.py
class TestThemeTools:
    async def test_list_builtin_skins(self):
        """Test listing built-in themes."""

    async def test_create_custom_skin(self):
        """Test creating custom skin."""

    async def test_apply_skin(self):
        """Test applying skin to project."""

    async def test_export_css(self):
        """Test CSS export."""

    async def test_export_tailwind(self):
        """Test Tailwind config export."""

# tests/test_design_application_tools.py
class TestDesignApplicationTools:
    async def test_apply_tokens(self):
        """Test token application."""

    async def test_preview_changes(self):
        """Test change preview."""

    async def test_validate_application(self):
        """Test validation."""
```

### 6.2 Integration Tests

```python
# tests/integration/test_workflows.py
class TestWorkflows:
    async def test_figma_to_storybook_workflow(self):
        """
        Full workflow test:
        1. Import tokens from Figma
        2. Generate Storybook theme
        3. Apply to components
        """

    async def test_skin_creation_workflow(self):
        """
        Skin workflow test:
        1. Create skin from base
        2. Apply skin
        3. Export in multiple formats
        """

    async def test_design_system_adoption(self):
        """
        Design system adoption test:
        1. Analyze project for quick wins
        2. Extract token candidates
        3. Apply design tokens
        4. Validate application
        """
```

### 6.3 Test Fixtures

```python
# tests/fixtures/
# - sample_project/           # Mock project structure
# - sample_storybook/         # Mock Storybook config
# - sample_tokens.json        # Sample design tokens
# - sample_components/        # Sample React components
```

---

## 7. Risk Assessment

### 7.1 Technical Risks

| Risk | Probability | Impact | Mitigation |
|------|-------------|--------|------------|
| Python core API changes | Low | High | Pin dependency versions, add adapter layer |
| Style Dictionary not installed | Medium | Medium | Graceful fallback to built-in export |
| Large project performance | Medium | Medium | Add pagination, streaming responses |
| File write permission issues | Medium | Low | Preview mode default, clear error messages |
| Storybook version incompatibility | Medium | Medium | Version detection, format adapters |

### 7.2 Integration Risks

| Risk | Probability | Impact | Mitigation |
|------|-------------|--------|------------|
| Database schema conflicts | Low | High | Migration scripts, backwards compatibility |
| Handler registration conflicts | Low | Medium | Unique tool name prefixes |
| Context loading failures | Medium | Medium | Fallback to minimal context |

### 7.3 Mitigation Strategies

1. **Graceful Degradation**
   - All tools should work in "preview" mode without writing files
   - Missing optional dependencies should be detected and reported
   - Clear error messages with actionable suggestions

2. **Backwards Compatibility**
   - New tools should not break existing functionality
   - Database migrations should be non-destructive
   - API responses should maintain consistent structure

3. **Testing Coverage**
   - Minimum 80% unit test coverage for new code
   - Integration tests for all workflows
   - Manual testing checklist for each tool

---

## Appendix A: Complete Tool Registry

After implementation, the MCP handler will register these tools:

```
Project Tools (7):
- dss_get_project_summary
- dss_list_components
- dss_get_component
- dss_get_design_tokens
- dss_get_project_health
- dss_list_styles
- dss_get_discovery_data

Figma Tools (5):
- figma_get_file
- figma_get_styles
- figma_get_components
- figma_extract_tokens
- figma_get_node

Storybook Tools (5): [NEW]
- storybook_scan
- storybook_generate_stories
- storybook_generate_theme
- storybook_get_status
- storybook_configure

Theme Tools (5): [NEW]
- theme_list_skins
- theme_get_skin
- theme_create_skin
- theme_apply_skin
- theme_export_tokens

Design Application Tools (5): [NEW]
- design_apply_tokens
- design_generate_css
- design_update_components
- design_preview_changes
- design_validate_application

Total: 27 tools
```

---

## Appendix B: Example Workflow Sequences

### B.1 Import from Figma -> Load in Storybook

```
1. figma_extract_tokens(file_key="abc123")
   -> Returns tokens from Figma variables

2. theme_create_skin(name="brand-v2", tokens=extracted_tokens)
   -> Creates new skin from Figma tokens

3. storybook_generate_theme(skin_name="brand-v2")
   -> Generates Storybook theme files

4. storybook_configure(action="add_theme")
   -> Configures Storybook to use new theme

5. storybook_generate_stories(component_path="src/components")
   -> Generates stories for components
```

### B.2 Apply Design to Project

```
1. dss_get_design_tokens(project_id="proj-123")
   -> Get current project tokens

2. design_preview_changes(scope="full")
   -> Preview what would change

3. design_apply_tokens(output_format="css", output_path="src/tokens")
   -> Generate CSS token files

4. design_update_components(component_path="src/components", update_type="all")
   -> Update components to use tokens

5. design_validate_application()
   -> Validate everything is correctly applied
```

---

**Document Version:** 1.0
**Last Updated:** December 2024
**Author:** Implementation Planning Team
