# MCP Phase 2/3 Implementation Plan: Translation Dictionary & Theme Configuration Tools

**Version:** 2.0.0
**Date:** December 9, 2024
**Status:** READY FOR IMPLEMENTATION
**Author:** Gemini 3 Pro Simulation (Architecture Planning)

---

## Executive Summary

This document provides a comprehensive implementation plan for MCP Phase 2/3 tools that expose the newly implemented Translation Dictionary System. The plan reflects the actual codebase architecture and renames the outdated "Skin Management" terminology to "Project Theme Configuration" to accurately reflect the DSS approach.

### Key Accomplishments

| Component | Status | Location |
|-----------|--------|----------|
| Translation Dictionary Python Core | **COMPLETE** | `dss-mvp1/dss/translations/` (8 modules) |
| Storybook MCP Integration | **COMPLETE** | `tools/dss_mcp/integrations/storybook.py` |
| MCP Handler Pattern | **COMPLETE** | `tools/dss_mcp/handler.py` |
| **Phase 2/3 MCP Tools** | **THIS PLAN** | `tools/dss_mcp/integrations/translations.py` |

### What This Plan Delivers

1. **12 New MCP Tools** organized into 3 categories
2. **Complete Workflow Support** for Workflows 2 & 3
3. **Integration Architecture** following existing patterns
4. **Clear Implementation Phases** with dependencies

---

## 1. Architecture Overview

### 1.1 System Integration Diagram

```
+====================================================================================+
|                           DSS MCP PLUGIN ARCHITECTURE                               |
+====================================================================================+
|                                                                                     |
|  MCP LAYER (tools/dss_mcp/)                                                        |
|  +---------------------------------------------------------------------------+     |
|  |  server.py                                                                 |     |
|  |    |                                                                       |     |
|  |    v                                                                       |     |
|  |  handler.py                                                                |     |
|  |    |                                                                       |     |
|  |    +-----> integrations/figma.py          (5 tools - COMPLETE)            |     |
|  |    +-----> integrations/storybook.py      (5 tools - COMPLETE)            |     |
|  |    +-----> integrations/translations.py   (12 tools - THIS PLAN)  [NEW]   |     |
|  |    +-----> tools/project_tools.py         (7 tools - COMPLETE)            |     |
|  +---------------------------------------------------------------------------+     |
|                                   |                                                 |
|                                   v                                                 |
|  PYTHON CORE (dss-mvp1/dss/)                                                       |
|  +---------------------------------------------------------------------------+     |
|  |  translations/                                                             |     |
|  |    +-- __init__.py          # Module exports                              |     |
|  |    +-- models.py            # TranslationDictionary, ResolvedTheme, etc.  |     |
|  |    +-- loader.py            # TranslationDictionaryLoader                 |     |
|  |    +-- resolver.py          # TokenResolver                               |     |
|  |    +-- merger.py            # ThemeMerger                                 |     |
|  |    +-- validator.py         # TranslationValidator                        |     |
|  |    +-- writer.py            # TranslationDictionaryWriter                 |     |
|  |    +-- canonical.py         # DSS_CANONICAL_TOKENS, DSS_CANONICAL_COMPONENTS |  |
|  +---------------------------------------------------------------------------+     |
|                                                                                     |
+====================================================================================+
```

### 1.2 Data Flow for Theme Resolution

```
+--------------------------------------------------------------------------------+
|                    THEME RESOLUTION DATA FLOW                                   |
+--------------------------------------------------------------------------------+
|                                                                                 |
|  1. LOAD DICTIONARIES                                                          |
|     +-------------------+                                                       |
|     | .dss/translations |                                                       |
|     |   figma.json      |---+                                                   |
|     |   legacy-css.json |---+---> TranslationDictionaryLoader                   |
|     |   custom.json     |---+            |                                      |
|     +-------------------+                v                                      |
|                              +-------------------+                              |
|                              | TranslationRegistry                              |
|                              | - combined_token_map                             |
|                              | - all_custom_props                               |
|                              | - conflicts                                      |
|                              +-------------------+                              |
|                                        |                                        |
|  2. RESOLVE TOKENS                     v                                        |
|     +-------------------+     +-------------------+                             |
|     | Base Theme        |---->| TokenResolver     |                             |
|     | (light/dark)      |     | - resolve_to_dss()                              |
|     +-------------------+     | - resolve_all_mappings()                        |
|                               +-------------------+                             |
|                                        |                                        |
|  3. MERGE THEME                        v                                        |
|                               +-------------------+                             |
|                               | ThemeMerger       |                             |
|                               | - merge()                                       |
|                               +-------------------+                             |
|                                        |                                        |
|  4. OUTPUT                             v                                        |
|                               +-------------------+                             |
|                               | ResolvedTheme     |-----> CSS Variables         |
|                               | - tokens          |-----> SCSS Variables        |
|                               | - custom_props    |-----> JSON Export           |
|                               | - provenance      |-----> Storybook Theme       |
|                               +-------------------+                             |
|                                                                                 |
+--------------------------------------------------------------------------------+
```

---

## 2. Tool Categories & Definitions

### 2.1 Category Overview

| Category | Tools | Purpose |
|----------|-------|---------|
| **Category 1: Translation Dictionary CRUD** | 5 tools | Create, read, update, delete translation dictionaries |
| **Category 2: Theme Configuration & Merging** | 4 tools | Configure project theme, merge base + translations + custom |
| **Category 3: Token Resolution & Code Generation** | 3 tools | Resolve tokens, generate CSS/SCSS output |

### 2.2 Complete Tool List

```
Translation Dictionary Tools (12 total):

Category 1: Dictionary Management
  1. translation_list_dictionaries     - List available translation dictionaries
  2. translation_get_dictionary        - Get dictionary details and mappings
  3. translation_create_dictionary     - Create new translation dictionary
  4. translation_update_dictionary     - Update existing dictionary mappings
  5. translation_validate_dictionary   - Validate dictionary schema and mappings

Category 2: Theme Configuration
  6. theme_get_config                  - Get project theme configuration
  7. theme_resolve                     - Resolve complete project theme
  8. theme_add_custom_prop             - Add custom property to project
  9. theme_get_canonical_tokens        - Get DSS canonical token structure

Category 3: Code Generation
  10. codegen_export_css               - Generate CSS variables from resolved theme
  11. codegen_export_scss              - Generate SCSS variables from resolved theme
  12. codegen_export_json              - Export resolved theme as JSON
```

---

## 3. Detailed Tool Specifications

### 3.1 Category 1: Translation Dictionary Management

#### Tool 1: `translation_list_dictionaries`

```python
types.Tool(
    name="translation_list_dictionaries",
    description="List all available translation dictionaries for a project. Returns dictionary types (figma, css, heroui, custom, etc.), mapping counts, and validation status.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "include_stats": {
                "type": "boolean",
                "description": "Include mapping statistics (default: true)",
                "default": True
            }
        },
        "required": ["project_id"]
    }
)
```

**Implementation:**
```python
async def list_dictionaries(
    self,
    project_id: str,
    include_stats: bool = True
) -> Dict[str, Any]:
    """List all translation dictionaries for project."""
    project_path = await self._get_project_path(project_id)
    loader = TranslationDictionaryLoader(project_path)

    available = loader.list_available_dictionaries()

    result = {
        "project_id": project_id,
        "dictionaries": [],
        "has_translations": loader.has_translations(),
        "translations_dir": str(loader.get_translations_dir())
    }

    if include_stats:
        registry = await loader.load_all()
        for source in available:
            dict_info = {
                "source": source,
                "file": f"{source}.json"
            }
            if source in registry.dictionaries:
                d = registry.dictionaries[source]
                dict_info["token_count"] = len(d.mappings.tokens)
                dict_info["component_count"] = len(d.mappings.components)
                dict_info["custom_prop_count"] = len(d.custom_props)
                dict_info["unmapped_count"] = len(d.unmapped)
            result["dictionaries"].append(dict_info)

        result["conflicts"] = registry.conflicts
    else:
        result["dictionaries"] = [{"source": s} for s in available]

    return result
```

**Output Example:**
```json
{
  "project_id": "proj-123",
  "dictionaries": [
    {
      "source": "figma",
      "file": "figma.json",
      "token_count": 45,
      "component_count": 12,
      "custom_prop_count": 3,
      "unmapped_count": 2
    },
    {
      "source": "css",
      "file": "css.json",
      "token_count": 23,
      "component_count": 0,
      "custom_prop_count": 5,
      "unmapped_count": 8
    }
  ],
  "has_translations": true,
  "translations_dir": "/project/.dss/translations",
  "conflicts": []
}
```

---

#### Tool 2: `translation_get_dictionary`

```python
types.Tool(
    name="translation_get_dictionary",
    description="Get detailed information about a specific translation dictionary including all token mappings, component mappings, and custom props.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "source": {
                "type": "string",
                "description": "Dictionary source type",
                "enum": ["figma", "css", "scss", "heroui", "shadcn", "tailwind", "json", "custom"]
            },
            "include_unmapped": {
                "type": "boolean",
                "description": "Include list of unmapped source tokens (default: true)",
                "default": True
            }
        },
        "required": ["project_id", "source"]
    }
)
```

**Implementation:**
```python
async def get_dictionary(
    self,
    project_id: str,
    source: str,
    include_unmapped: bool = True
) -> Dict[str, Any]:
    """Get translation dictionary details."""
    project_path = await self._get_project_path(project_id)
    loader = TranslationDictionaryLoader(project_path)

    dictionary = await loader.load_dictionary(source)
    if not dictionary:
        return {
            "error": f"Dictionary not found: {source}",
            "project_id": project_id,
            "available": loader.list_available_dictionaries()
        }

    result = {
        "project_id": project_id,
        "source": source,
        "uuid": dictionary.uuid,
        "version": dictionary.version,
        "created_at": dictionary.created_at.isoformat(),
        "updated_at": dictionary.updated_at.isoformat(),
        "mappings": {
            "tokens": dictionary.mappings.tokens,
            "components": dictionary.mappings.components,
            "patterns": dictionary.mappings.patterns
        },
        "custom_props": dictionary.custom_props,
        "notes": dictionary.notes
    }

    if include_unmapped:
        result["unmapped"] = dictionary.unmapped

    return result
```

---

#### Tool 3: `translation_create_dictionary`

```python
types.Tool(
    name="translation_create_dictionary",
    description="Create a new translation dictionary for a project. Maps external tokens (Figma, CSS, etc.) to DSS canonical tokens.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "source": {
                "type": "string",
                "description": "Source type for the dictionary",
                "enum": ["figma", "css", "scss", "heroui", "shadcn", "tailwind", "json", "custom"]
            },
            "token_mappings": {
                "type": "object",
                "description": "Token mappings: source_token -> DSS canonical path",
                "additionalProperties": {
                    "type": "string"
                }
            },
            "component_mappings": {
                "type": "object",
                "description": "Component mappings: source_component -> DSS component",
                "additionalProperties": {
                    "type": "string"
                }
            },
            "custom_props": {
                "type": "object",
                "description": "Custom properties (must use DSS namespace like 'color.brand.myproject.primary')",
                "additionalProperties": {}
            },
            "notes": {
                "type": "array",
                "items": {"type": "string"},
                "description": "Human-readable notes"
            }
        },
        "required": ["project_id", "source"]
    }
)
```

**Implementation:**
```python
async def create_dictionary(
    self,
    project_id: str,
    source: str,
    token_mappings: Optional[Dict[str, str]] = None,
    component_mappings: Optional[Dict[str, str]] = None,
    custom_props: Optional[Dict[str, Any]] = None,
    notes: Optional[List[str]] = None
) -> Dict[str, Any]:
    """Create new translation dictionary."""
    project_path = await self._get_project_path(project_id)
    writer = TranslationDictionaryWriter(project_path)

    # Validate before creating
    validator = TranslationValidator()
    test_data = {
        "$schema": "dss-translation-v1",
        "project": project_id,
        "source": source,
        "mappings": {
            "tokens": token_mappings or {},
            "components": component_mappings or {}
        },
        "custom_props": custom_props or {}
    }

    validation_result = validator.validate_dictionary(test_data)
    if not validation_result.is_valid:
        return {
            "error": "Validation failed",
            "errors": [str(e) for e in validation_result.errors],
            "warnings": [str(w) for w in validation_result.warnings]
        }

    dictionary = await writer.create(
        source=source,
        project=project_id,
        token_mappings=token_mappings,
        component_mappings=component_mappings,
        custom_props=custom_props,
        notes=notes
    )

    return {
        "project_id": project_id,
        "source": source,
        "uuid": dictionary.uuid,
        "created": True,
        "file_path": str(writer.translations_dir / f"{source}.json"),
        "token_count": len(dictionary.mappings.tokens),
        "component_count": len(dictionary.mappings.components),
        "custom_prop_count": len(dictionary.custom_props),
        "warnings": [str(w) for w in validation_result.warnings]
    }
```

---

#### Tool 4: `translation_update_dictionary`

```python
types.Tool(
    name="translation_update_dictionary",
    description="Update an existing translation dictionary. Add or modify token mappings, component mappings, or custom props.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "source": {
                "type": "string",
                "description": "Dictionary source type to update",
                "enum": ["figma", "css", "scss", "heroui", "shadcn", "tailwind", "json", "custom"]
            },
            "token_mappings": {
                "type": "object",
                "description": "Token mappings to add/update",
                "additionalProperties": {"type": "string"}
            },
            "component_mappings": {
                "type": "object",
                "description": "Component mappings to add/update",
                "additionalProperties": {"type": "string"}
            },
            "custom_props": {
                "type": "object",
                "description": "Custom props to add/update",
                "additionalProperties": {}
            },
            "remove_tokens": {
                "type": "array",
                "items": {"type": "string"},
                "description": "Source tokens to remove from mappings"
            },
            "notes": {
                "type": "array",
                "items": {"type": "string"},
                "description": "Notes to append"
            }
        },
        "required": ["project_id", "source"]
    }
)
```

---

#### Tool 5: `translation_validate_dictionary`

```python
types.Tool(
    name="translation_validate_dictionary",
    description="Validate a translation dictionary. Checks schema compliance, DSS token path validity, and detects conflicts.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "source": {
                "type": "string",
                "description": "Dictionary source type to validate",
                "enum": ["figma", "css", "scss", "heroui", "shadcn", "tailwind", "json", "custom"]
            },
            "strict": {
                "type": "boolean",
                "description": "Strict mode - unknown tokens are errors (default: false)",
                "default": False
            }
        },
        "required": ["project_id", "source"]
    }
)
```

---

### 3.2 Category 2: Theme Configuration & Merging

#### Tool 6: `theme_get_config`

```python
types.Tool(
    name="theme_get_config",
    description="Get project theme configuration including base theme, loaded dictionaries, and custom props summary.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            }
        },
        "required": ["project_id"]
    }
)
```

**Implementation:**
```python
async def get_config(self, project_id: str) -> Dict[str, Any]:
    """Get project theme configuration."""
    project_path = await self._get_project_path(project_id)
    loader = TranslationDictionaryLoader(project_path)

    # Load registry to get full picture
    registry = await loader.load_all()

    return {
        "project_id": project_id,
        "base_themes_available": ["light", "dark"],
        "translation_dictionaries": list(registry.dictionaries.keys()),
        "total_token_mappings": len(registry.combined_token_map),
        "total_component_mappings": len(registry.combined_component_map),
        "total_custom_props": len(registry.all_custom_props),
        "conflicts": registry.conflicts,
        "has_config": loader.has_translations()
    }
```

---

#### Tool 7: `theme_resolve`

```python
types.Tool(
    name="theme_resolve",
    description="Resolve complete project theme by merging base theme with translation dictionaries and custom props. Returns fully resolved tokens with provenance.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "base_theme": {
                "type": "string",
                "description": "Base theme to use",
                "enum": ["light", "dark"],
                "default": "light"
            },
            "include_provenance": {
                "type": "boolean",
                "description": "Include token resolution provenance chain (default: false)",
                "default": False
            }
        },
        "required": ["project_id"]
    }
)
```

**Implementation:**
```python
async def resolve_theme(
    self,
    project_id: str,
    base_theme: str = "light",
    include_provenance: bool = False
) -> Dict[str, Any]:
    """Resolve complete project theme."""
    project_path = await self._get_project_path(project_id)

    # Load translation registry
    loader = TranslationDictionaryLoader(project_path)
    registry = await loader.load_all()

    # Create merger and resolve
    merger = ThemeMerger(registry)
    resolved = await merger.merge(
        base_theme=base_theme,
        project_name=project_id
    )

    # Format tokens for output
    tokens = {}
    for dss_path, resolved_token in resolved.tokens.items():
        token_data = {
            "value": resolved_token.value,
            "source_token": resolved_token.source_token,
            "is_custom": resolved_token.is_custom
        }
        if include_provenance:
            token_data["provenance"] = resolved_token.provenance
        tokens[dss_path] = token_data

    custom_props = {}
    for dss_path, resolved_token in resolved.custom_props.items():
        prop_data = {
            "value": resolved_token.value
        }
        if include_provenance:
            prop_data["provenance"] = resolved_token.provenance
        custom_props[dss_path] = prop_data

    return {
        "project_id": project_id,
        "name": resolved.name,
        "base_theme": resolved.base_theme,
        "version": resolved.version,
        "resolved_at": resolved.resolved_at.isoformat(),
        "translations_applied": resolved.translations_applied,
        "token_count": len(tokens),
        "custom_prop_count": len(custom_props),
        "tokens": tokens,
        "custom_props": custom_props
    }
```

---

#### Tool 8: `theme_add_custom_prop`

```python
types.Tool(
    name="theme_add_custom_prop",
    description="Add a custom property to the project's custom.json translation dictionary. Custom props extend DSS with project-specific tokens.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "prop_name": {
                "type": "string",
                "description": "Property name using DSS namespace (e.g., 'color.brand.acme.primary')"
            },
            "prop_value": {
                "description": "Property value (string, number, or object)"
            },
            "description": {
                "type": "string",
                "description": "Optional description of the custom prop"
            }
        },
        "required": ["project_id", "prop_name", "prop_value"]
    }
)
```

---

#### Tool 9: `theme_get_canonical_tokens`

```python
types.Tool(
    name="theme_get_canonical_tokens",
    description="Get the DSS canonical token structure. Useful for understanding available tokens and valid mapping targets.",
    inputSchema={
        "type": "object",
        "properties": {
            "category": {
                "type": "string",
                "description": "Filter by category (optional)",
                "enum": ["color", "spacing", "typography", "border", "shadow", "motion", "zIndex", "opacity", "breakpoint"]
            },
            "include_aliases": {
                "type": "boolean",
                "description": "Include token aliases (default: true)",
                "default": True
            },
            "include_components": {
                "type": "boolean",
                "description": "Include canonical components (default: false)",
                "default": False
            }
        },
        "required": []
    }
)
```

**Implementation:**
```python
async def get_canonical_tokens(
    self,
    category: Optional[str] = None,
    include_aliases: bool = True,
    include_components: bool = False
) -> Dict[str, Any]:
    """Get DSS canonical token structure."""
    from dss.translations.canonical import (
        DSS_CANONICAL_TOKENS,
        DSS_TOKEN_ALIASES,
        DSS_CANONICAL_COMPONENTS,
        get_canonical_token_categories
    )

    result = {
        "total_tokens": len(DSS_CANONICAL_TOKENS)
    }

    if category:
        # Filter by category
        categories = get_canonical_token_categories()
        result["category"] = category
        result["tokens"] = categories.get(category, [])
    else:
        # Return all organized by category
        result["tokens_by_category"] = get_canonical_token_categories()

    if include_aliases:
        result["aliases"] = DSS_TOKEN_ALIASES

    if include_components:
        result["components"] = list(DSS_CANONICAL_COMPONENTS)

    return result
```

---

### 3.3 Category 3: Code Generation

#### Tool 10: `codegen_export_css`

```python
types.Tool(
    name="codegen_export_css",
    description="Generate CSS custom properties from resolved project theme. Outputs :root variables and optional utility classes.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "base_theme": {
                "type": "string",
                "description": "Base theme to use",
                "enum": ["light", "dark"],
                "default": "light"
            },
            "selector": {
                "type": "string",
                "description": "CSS selector for variables (default: ':root')",
                "default": ":root"
            },
            "prefix": {
                "type": "string",
                "description": "CSS variable prefix (default: 'dss')",
                "default": "dss"
            },
            "include_comments": {
                "type": "boolean",
                "description": "Include provenance comments (default: true)",
                "default": True
            },
            "output_path": {
                "type": "string",
                "description": "Optional: Write to file instead of returning content"
            }
        },
        "required": ["project_id"]
    }
)
```

**Implementation:**
```python
async def export_css(
    self,
    project_id: str,
    base_theme: str = "light",
    selector: str = ":root",
    prefix: str = "dss",
    include_comments: bool = True,
    output_path: Optional[str] = None
) -> Dict[str, Any]:
    """Generate CSS variables from resolved theme."""
    # Resolve theme first
    resolved_result = await self.resolve_theme(
        project_id,
        base_theme,
        include_provenance=include_comments
    )

    if "error" in resolved_result:
        return resolved_result

    # Generate CSS
    css_lines = []
    if include_comments:
        css_lines.append(f"/* DSS Theme: {resolved_result['name']} */")
        css_lines.append(f"/* Base: {base_theme} | Generated: {resolved_result['resolved_at']} */")
        css_lines.append(f"/* Translations: {', '.join(resolved_result['translations_applied'])} */")
        css_lines.append("")

    css_lines.append(f"{selector} {{")

    # Core tokens
    for dss_path, token_data in resolved_result["tokens"].items():
        var_name = f"--{prefix}-{dss_path.replace('.', '-')}"
        value = token_data["value"]

        if include_comments and token_data.get("source_token"):
            css_lines.append(f"  /* Source: {token_data['source_token']} */")

        css_lines.append(f"  {var_name}: {value};")

    # Custom props
    if resolved_result["custom_props"]:
        css_lines.append("")
        css_lines.append("  /* Custom Properties */")
        for dss_path, prop_data in resolved_result["custom_props"].items():
            var_name = f"--{prefix}-{dss_path.replace('.', '-')}"
            css_lines.append(f"  {var_name}: {prop_data['value']};")

    css_lines.append("}")

    css_content = "\n".join(css_lines)

    if output_path:
        project_path = await self._get_project_path(project_id)
        full_path = project_path / output_path
        full_path.parent.mkdir(parents=True, exist_ok=True)
        full_path.write_text(css_content)

        return {
            "project_id": project_id,
            "output_path": str(full_path),
            "written": True,
            "token_count": resolved_result["token_count"],
            "custom_prop_count": resolved_result["custom_prop_count"]
        }

    return {
        "project_id": project_id,
        "content": css_content,
        "token_count": resolved_result["token_count"],
        "custom_prop_count": resolved_result["custom_prop_count"]
    }
```

---

#### Tool 11: `codegen_export_scss`

```python
types.Tool(
    name="codegen_export_scss",
    description="Generate SCSS variables from resolved project theme. Outputs $variables and optional mixins.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "base_theme": {
                "type": "string",
                "description": "Base theme to use",
                "enum": ["light", "dark"],
                "default": "light"
            },
            "prefix": {
                "type": "string",
                "description": "SCSS variable prefix (default: 'dss')",
                "default": "dss"
            },
            "generate_map": {
                "type": "boolean",
                "description": "Generate SCSS map in addition to variables (default: true)",
                "default": True
            },
            "output_path": {
                "type": "string",
                "description": "Optional: Write to file instead of returning content"
            }
        },
        "required": ["project_id"]
    }
)
```

---

#### Tool 12: `codegen_export_json`

```python
types.Tool(
    name="codegen_export_json",
    description="Export resolved theme as JSON. Useful for design tool integrations and token documentation.",
    inputSchema={
        "type": "object",
        "properties": {
            "project_id": {
                "type": "string",
                "description": "Project ID"
            },
            "base_theme": {
                "type": "string",
                "description": "Base theme to use",
                "enum": ["light", "dark"],
                "default": "light"
            },
            "format": {
                "type": "string",
                "description": "JSON structure format",
                "enum": ["flat", "nested", "style-dictionary"],
                "default": "flat"
            },
            "include_metadata": {
                "type": "boolean",
                "description": "Include resolution metadata (default: true)",
                "default": True
            },
            "output_path": {
                "type": "string",
                "description": "Optional: Write to file instead of returning content"
            }
        },
        "required": ["project_id"]
    }
)
```

---

## 4. File Structure & Implementation

### 4.1 New Files to Create

```
tools/dss_mcp/
+-- integrations/
|   +-- translations.py      # NEW - Translation dictionary MCP tools
|
+-- handler.py               # MODIFY - Register new tools
+-- server.py                # MODIFY - Import new tool lists
```

### 4.2 `integrations/translations.py` - Complete Structure

```python
"""
Translation Dictionary Integration for MCP

Provides tools for managing translation dictionaries, theme configuration,
and code generation for design system tokens.
"""

from typing import Dict, Any, Optional, List
from pathlib import Path
from mcp import types

from .base import BaseIntegration
from ..context.project_context import get_context_manager


# =============================================================================
# MCP Tool Definitions
# =============================================================================

TRANSLATION_TOOLS = [
    # Category 1: Dictionary Management
    types.Tool(name="translation_list_dictionaries", ...),
    types.Tool(name="translation_get_dictionary", ...),
    types.Tool(name="translation_create_dictionary", ...),
    types.Tool(name="translation_update_dictionary", ...),
    types.Tool(name="translation_validate_dictionary", ...),

    # Category 2: Theme Configuration
    types.Tool(name="theme_get_config", ...),
    types.Tool(name="theme_resolve", ...),
    types.Tool(name="theme_add_custom_prop", ...),
    types.Tool(name="theme_get_canonical_tokens", ...),

    # Category 3: Code Generation
    types.Tool(name="codegen_export_css", ...),
    types.Tool(name="codegen_export_scss", ...),
    types.Tool(name="codegen_export_json", ...),
]


# =============================================================================
# Integration Class
# =============================================================================

class TranslationIntegration(BaseIntegration):
    """Translation dictionary integration wrapper for DSS tools"""

    def __init__(self, config: Optional[Dict[str, Any]] = None):
        super().__init__("translations", config or {})
        self.context_manager = get_context_manager()

    async def _get_project_path(self, project_id: str) -> Path:
        """Get project path from context manager."""
        context = await self.context_manager.get_context(project_id)
        if not context or not context.path:
            raise ValueError(f"Project not found: {project_id}")
        return Path(context.path)

    # Category 1: Dictionary Management
    async def list_dictionaries(self, ...) -> Dict[str, Any]: ...
    async def get_dictionary(self, ...) -> Dict[str, Any]: ...
    async def create_dictionary(self, ...) -> Dict[str, Any]: ...
    async def update_dictionary(self, ...) -> Dict[str, Any]: ...
    async def validate_dictionary(self, ...) -> Dict[str, Any]: ...

    # Category 2: Theme Configuration
    async def get_config(self, ...) -> Dict[str, Any]: ...
    async def resolve_theme(self, ...) -> Dict[str, Any]: ...
    async def add_custom_prop(self, ...) -> Dict[str, Any]: ...
    async def get_canonical_tokens(self, ...) -> Dict[str, Any]: ...

    # Category 3: Code Generation
    async def export_css(self, ...) -> Dict[str, Any]: ...
    async def export_scss(self, ...) -> Dict[str, Any]: ...
    async def export_json(self, ...) -> Dict[str, Any]: ...


# =============================================================================
# MCP Tool Executor
# =============================================================================

class TranslationTools:
    """MCP tool executor for translation integration"""

    def __init__(self, config: Optional[Dict[str, Any]] = None):
        self.translations = TranslationIntegration(config)

    async def execute_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
        """Execute translation tool."""
        handlers = {
            # Category 1
            "translation_list_dictionaries": self.translations.list_dictionaries,
            "translation_get_dictionary": self.translations.get_dictionary,
            "translation_create_dictionary": self.translations.create_dictionary,
            "translation_update_dictionary": self.translations.update_dictionary,
            "translation_validate_dictionary": self.translations.validate_dictionary,
            # Category 2
            "theme_get_config": self.translations.get_config,
            "theme_resolve": self.translations.resolve_theme,
            "theme_add_custom_prop": self.translations.add_custom_prop,
            "theme_get_canonical_tokens": self.translations.get_canonical_tokens,
            # Category 3
            "codegen_export_css": self.translations.export_css,
            "codegen_export_scss": self.translations.export_scss,
            "codegen_export_json": self.translations.export_json,
        }

        handler = handlers.get(tool_name)
        if not handler:
            return {"error": f"Unknown translation tool: {tool_name}"}

        try:
            clean_args = {k: v for k, v in arguments.items() if not k.startswith("_")}
            return await handler(**clean_args)
        except Exception as e:
            return {"error": f"Tool execution failed: {str(e)}", "tool": tool_name}
```

### 4.3 Handler Registration Update

```python
# In handler.py - add to _initialize_tools()

from .integrations.translations import TRANSLATION_TOOLS, TranslationTools

# Register Translation tools
for tool in TRANSLATION_TOOLS:
    self._tool_registry[tool.name] = {
        "tool": tool,
        "category": "translations",
        "requires_integration": False
    }

# Add to execute_tool() method
if category == "translations":
    tools = TranslationTools()
    result = await tools.execute_tool(tool_name, arguments)
```

---

## 5. Workflow Integration

### 5.1 Workflow 2: Load Project Theme into Storybook

```
+--------------------------------------------------------------------------------+
|                    WORKFLOW 2: Load Project Theme into Storybook               |
+--------------------------------------------------------------------------------+
|                                                                                 |
|  Step 1: Check translations                                                    |
|  +-----------------------+                                                      |
|  | translation_list_     |                                                      |
|  | dictionaries          |---> List available dictionaries                      |
|  +-----------------------+                                                      |
|            |                                                                    |
|            v                                                                    |
|  Step 2: Resolve theme                                                         |
|  +-----------------------+                                                      |
|  | theme_resolve         |---> Merge base + translations + custom props        |
|  | (base_theme="light")  |                                                      |
|  +-----------------------+                                                      |
|            |                                                                    |
|            v                                                                    |
|  Step 3: Generate Storybook theme                                              |
|  +-----------------------+                                                      |
|  | storybook_generate_   |---> Generate theme files with resolved tokens       |
|  | theme                 |                                                      |
|  +-----------------------+                                                      |
|            |                                                                    |
|            v                                                                    |
|  Step 4: Configure Storybook                                                   |
|  +-----------------------+                                                      |
|  | storybook_configure   |---> Update Storybook config to use theme            |
|  | (action="add_theme")  |                                                      |
|  +-----------------------+                                                      |
|                                                                                 |
+--------------------------------------------------------------------------------+

Example Tool Sequence:
1. translation_list_dictionaries(project_id="proj-123")
   -> Returns: ["figma", "css", "custom"]

2. theme_resolve(project_id="proj-123", base_theme="light", include_provenance=true)
   -> Returns: Complete resolved theme with 150 tokens

3. storybook_generate_theme(project_id="proj-123", base_theme="light", write_files=true)
   -> Writes: .storybook/dss-theme.ts, manager.ts, preview.ts

4. storybook_configure(project_id="proj-123", action="add_theme")
   -> Updates Storybook configuration
```

### 5.2 Workflow 3: Apply Design to Project

```
+--------------------------------------------------------------------------------+
|                    WORKFLOW 3: Apply Design to Project                         |
+--------------------------------------------------------------------------------+
|                                                                                 |
|  Step 1: View canonical structure                                              |
|  +-----------------------+                                                      |
|  | theme_get_canonical_  |---> Understand available DSS tokens                 |
|  | tokens                |                                                      |
|  +-----------------------+                                                      |
|            |                                                                    |
|            v                                                                    |
|  Step 2: Create/update translations                                            |
|  +-----------------------+                                                      |
|  | translation_create_   |---> Map legacy tokens to DSS                        |
|  | dictionary            |                                                      |
|  | (source="css")        |                                                      |
|  +-----------------------+                                                      |
|            |                                                                    |
|            v                                                                    |
|  Step 3: Add custom props                                                      |
|  +-----------------------+                                                      |
|  | theme_add_custom_prop |---> Add project-specific tokens                     |
|  +-----------------------+                                                      |
|            |                                                                    |
|            v                                                                    |
|  Step 4: Validate                                                              |
|  +-----------------------+                                                      |
|  | translation_validate_ |---> Ensure all mappings are valid                   |
|  | dictionary            |                                                      |
|  +-----------------------+                                                      |
|            |                                                                    |
|            v                                                                    |
|  Step 5: Resolve and export                                                    |
|  +-----------------------+                                                      |
|  | theme_resolve         |---> Generate complete theme                         |
|  |         +             |                                                      |
|  | codegen_export_css    |---> Generate CSS variables file                     |
|  +-----------------------+                                                      |
|                                                                                 |
+--------------------------------------------------------------------------------+

Example Tool Sequence:
1. theme_get_canonical_tokens(category="color", include_aliases=true)
   -> Returns: All color tokens and aliases

2. translation_create_dictionary(
     project_id="proj-123",
     source="css",
     token_mappings={
       "--brand-primary": "color.primary.500",
       "--brand-secondary": "color.secondary.500"
     }
   )
   -> Creates: .dss/translations/css.json

3. theme_add_custom_prop(
     project_id="proj-123",
     prop_name="color.brand.acme.highlight",
     prop_value="#ff6b00"
   )
   -> Updates: .dss/translations/custom.json

4. translation_validate_dictionary(project_id="proj-123", source="css")
   -> Returns: Validation result with warnings

5. codegen_export_css(
     project_id="proj-123",
     base_theme="light",
     output_path="src/styles/tokens.css"
   )
   -> Writes: src/styles/tokens.css
```

---

## 6. Implementation Phases

### Phase 1: Core Infrastructure (Day 1)

**Priority: Critical**

1. Create `integrations/translations.py` with basic structure
2. Implement Category 1 tools (Dictionary CRUD):
   - `translation_list_dictionaries`
   - `translation_get_dictionary`
   - `translation_create_dictionary`
3. Register in `handler.py`
4. Basic unit tests

**Deliverables:**
- [ ] New translations.py file
- [ ] 3 working MCP tools
- [ ] Handler registration
- [ ] Test fixtures

### Phase 2: Theme Resolution (Day 2)

**Priority: High**

1. Implement remaining Category 1 tools:
   - `translation_update_dictionary`
   - `translation_validate_dictionary`
2. Implement Category 2 tools:
   - `theme_get_config`
   - `theme_resolve`
   - `theme_add_custom_prop`
   - `theme_get_canonical_tokens`
3. Integration tests for Workflow 2

**Deliverables:**
- [ ] 6 additional MCP tools
- [ ] Workflow 2 tested end-to-end
- [ ] Integration with storybook tools verified

### Phase 3: Code Generation (Day 3)

**Priority: High**

1. Implement Category 3 tools:
   - `codegen_export_css`
   - `codegen_export_scss`
   - `codegen_export_json`
2. Integration tests for Workflow 3
3. End-to-end testing

**Deliverables:**
- [ ] 3 code generation tools
- [ ] Workflow 3 tested end-to-end
- [ ] All 12 tools complete

### Phase 4: Polish & Documentation (Day 4)

**Priority: Medium**

1. Error handling improvements
2. Edge case testing
3. Performance optimization
4. Update API documentation
5. Example workflows

**Deliverables:**
- [ ] Comprehensive error messages
- [ ] Test coverage > 80%
- [ ] Documentation updated

---

## 7. Testing Strategy

### 7.1 Unit Tests

```python
# tests/test_translation_tools.py

class TestTranslationDictionaryTools:
    """Test Category 1: Dictionary Management"""

    async def test_list_dictionaries_empty_project(self):
        """Test listing on project with no translations."""
        pass

    async def test_list_dictionaries_with_stats(self):
        """Test listing with statistics."""
        pass

    async def test_create_dictionary_valid(self):
        """Test creating valid dictionary."""
        pass

    async def test_create_dictionary_invalid_tokens(self):
        """Test creating dictionary with invalid DSS tokens."""
        pass

    async def test_validate_dictionary_warnings(self):
        """Test validation with warnings."""
        pass


class TestThemeConfigurationTools:
    """Test Category 2: Theme Configuration"""

    async def test_resolve_theme_light(self):
        """Test resolving light theme."""
        pass

    async def test_resolve_theme_with_custom_props(self):
        """Test resolution with custom props."""
        pass

    async def test_get_canonical_tokens_by_category(self):
        """Test getting tokens by category."""
        pass


class TestCodeGenerationTools:
    """Test Category 3: Code Generation"""

    async def test_export_css_basic(self):
        """Test basic CSS export."""
        pass

    async def test_export_css_to_file(self):
        """Test CSS export to file."""
        pass

    async def test_export_scss_with_map(self):
        """Test SCSS export with map."""
        pass

    async def test_export_json_nested(self):
        """Test nested JSON export."""
        pass
```

### 7.2 Integration Tests

```python
# tests/integration/test_translation_workflows.py

class TestWorkflow2:
    """Test: Load Project Theme into Storybook"""

    async def test_complete_workflow(self):
        """Test full workflow from translations to Storybook."""
        # 1. Create translation dictionary
        # 2. Resolve theme
        # 3. Generate Storybook theme
        # 4. Verify output files
        pass


class TestWorkflow3:
    """Test: Apply Design to Project"""

    async def test_complete_workflow(self):
        """Test full workflow from analysis to CSS generation."""
        # 1. Get canonical structure
        # 2. Create translations
        # 3. Add custom props
        # 4. Export CSS
        pass
```

### 7.3 Test Fixtures

```
tests/fixtures/
+-- translation_dictionaries/
|   +-- figma.json           # Sample Figma translation
|   +-- css.json             # Sample CSS translation
|   +-- custom.json          # Sample custom props
|
+-- projects/
|   +-- empty_project/       # Project with no .dss
|   +-- configured_project/  # Project with full .dss setup
```

---

## 8. 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):
- storybook_scan
- storybook_generate_stories
- storybook_generate_theme
- storybook_get_status
- storybook_configure

Translation Tools (12): [NEW - THIS PLAN]
- translation_list_dictionaries
- translation_get_dictionary
- translation_create_dictionary
- translation_update_dictionary
- translation_validate_dictionary
- theme_get_config
- theme_resolve
- theme_add_custom_prop
- theme_get_canonical_tokens
- codegen_export_css
- codegen_export_scss
- codegen_export_json

Jira Tools (5):
- jira_list_projects
- jira_get_issue
- jira_search_issues
- jira_create_issue
- jira_update_issue

Confluence Tools (5):
- confluence_list_spaces
- confluence_get_page
- confluence_search_content
- confluence_create_page
- confluence_update_page

Total: 39 tools
```

---

## 9. Risk Assessment & Mitigation

| Risk | Probability | Impact | Mitigation |
|------|-------------|--------|------------|
| Translation system async issues | Low | Medium | All Python core functions support async, use run_in_executor if needed |
| Path traversal vulnerabilities | Low | High | All path operations validated against project root (already implemented) |
| Large dictionary files | Medium | Low | Lazy loading, pagination for list operations |
| Conflicting translations | Medium | Medium | Conflict detection and reporting in registry |
| Invalid DSS paths | Medium | Low | Strict validation with helpful error messages |

---

## 10. Success Criteria

### Minimum Viable Delivery

- [ ] All 12 MCP tools implemented and registered
- [ ] Workflow 2 (Load into Storybook) works end-to-end
- [ ] Workflow 3 (Apply Design) works end-to-end
- [ ] Unit test coverage > 70%
- [ ] Documentation complete

### Full Delivery

- [ ] Integration tests for all workflows
- [ ] Error handling with actionable messages
- [ ] Performance optimized (< 1s for typical operations)
- [ ] Example workflows documented
- [ ] Test coverage > 80%

---

## Appendix A: JSON Examples

### A.1 Translation Dictionary Example

```json
{
  "$schema": "dss-translation-v1",
  "uuid": "dict-001",
  "project": "acme-web",
  "source": "css",
  "version": "1.0.0",
  "created_at": "2024-12-09T10:00:00Z",
  "updated_at": "2024-12-09T10:00:00Z",
  "mappings": {
    "tokens": {
      "--brand-primary": "color.primary.500",
      "--brand-secondary": "color.secondary.500",
      "--text-base": "typography.size.base",
      "--spacing-sm": "spacing.sm"
    },
    "components": {
      ".btn-primary": "Button[variant=primary]",
      ".btn-outline": "Button[variant=outline]"
    },
    "patterns": {}
  },
  "custom_props": {
    "color.brand.acme.highlight": "#ff6b00",
    "color.brand.acme.accent": "#00b4d8"
  },
  "unmapped": [
    "--legacy-gradient-1",
    "--deprecated-shadow"
  ],
  "notes": [
    "Mapped from legacy CSS variables",
    "Some gradient variables need manual review"
  ]
}
```

### A.2 Resolved Theme Example

```json
{
  "project_id": "acme-web",
  "name": "resolved-light",
  "base_theme": "light",
  "version": "1.0.0",
  "resolved_at": "2024-12-09T12:00:00Z",
  "translations_applied": ["css", "custom"],
  "token_count": 89,
  "custom_prop_count": 2,
  "tokens": {
    "color.primary.500": {
      "value": "#3b82f6",
      "source_token": "--brand-primary",
      "is_custom": false
    },
    "color.secondary.500": {
      "value": "#8b5cf6",
      "source_token": "--brand-secondary",
      "is_custom": false
    }
  },
  "custom_props": {
    "color.brand.acme.highlight": {
      "value": "#ff6b00"
    }
  }
}
```

### A.3 Generated CSS Example

```css
/* DSS Theme: resolved-light */
/* Base: light | Generated: 2024-12-09T12:00:00Z */
/* Translations: css, custom */

:root {
  /* Source: --brand-primary */
  --dss-color-primary-500: #3b82f6;
  /* Source: --brand-secondary */
  --dss-color-secondary-500: #8b5cf6;
  --dss-typography-size-base: 1rem;
  --dss-spacing-sm: 0.5rem;

  /* Custom Properties */
  --dss-color-brand-acme-highlight: #ff6b00;
  --dss-color-brand-acme-accent: #00b4d8;
}
```

---

**Document Version:** 2.0.0
**Last Updated:** December 9, 2024
**Author:** Gemini 3 Pro Simulation (Architecture Planning)
