# SpeX MCP Server Architecture

This document describes the modular architecture of the SpeX MCP Server, which provides seamless integration between Figma SpeX plugins and Cursor AI.

## Overview

The server is divided into two main functional areas:
1. **Figma SpeX Plugin Functions** - Handle WebSocket communication with Figma SpeX plugins
2. **MCP Tools** - Provide tools for Cursor AI integration via Model Context Protocol

## Architecture Diagram

```
┌─────────────────────────────────────────────────────────────────┐
│                    SpeX MCP Server                              │
├─────────────────────────────────────────────────────────────────┤
│  src/index.js - Main orchestration server                      │
├─────────────────┬───────────────────────────────────────────────┤
│ Figma Functions │ MCP Tools                                     │
│                 │                                               │
│ figma-          │ mcp-tools.js                                  │
│ functions.js    │                                               │
│                 │                                               │
│ • WebSocket     │ • Tool Definitions                            │
│   Server        │ • Tool Handlers                               │
│ • Plugin Comm   │ • Specs Retrieval                             │
│ • Message       │ • Basic Tools                                 │
│   Handling      │                                               │
└─────────────────┴───────────────────────────────────────────────┘
        │                           │
        │                           │
        ▼                           ▼
┌─────────────────┐         ┌─────────────────┐
│ Figma SpeX      │         │ Cursor AI       │
│ Plugins         │         │                 │
│                 │         │ • Specs Query   │
│ • Design Specs  │         │ • Basic Tools   │
│ • Hello World   │         │                 │
└─────────────────┘         └─────────────────┘
```

## Module Structure

### 1. Main Server (`src/index.js`)

The main orchestration layer that:
- Initializes both Figma SpeX and MCP managers
- Sets up MCP request handlers
- Manages server lifecycle
- Handles graceful shutdown

### 2. Figma Functions (`src/figma-functions.js`)

**Purpose**: Handle all Figma SpeX plugin communication via WebSocket

**Key Components**:
- `FigmaPluginManager` class
- WebSocket server on port 8080
- Message routing and handling
- Connection management

**Functions**:
- `setupWebSocketServer()` - Initialize WebSocket server
- `handleFigmaMessage()` - Route incoming messages
- `pullSpecsFromFigma()` - Request design specifications
- `broadcastToFigmaPlugins()` - Send messages to all SpeX plugins
- `shutdown()` - Graceful shutdown

**Message Types Handled**:
- `hello-world` - Basic connectivity test
- `specs-data` - Design specifications data

### 3. MCP Tools (`src/mcp-tools.js`)

**Purpose**: Provide tools for Cursor AI via Model Context Protocol

**Key Components**:
- `MCPToolsManager` class
- Tool definitions and schemas
- Tool execution handlers

**Available Tools**:
- `hello-world` - Test connectivity
- `pull-specs` - Get design specifications from Figma SpeX

## Data Flow

### 1. Figma SpeX → Server → Cursor AI
```
Figma SpeX Plugin → WebSocket → FigmaPluginManager → MCPToolsManager → Cursor AI
```

### 2. Cursor AI → Server → Figma SpeX
```
Cursor AI → MCP Protocol → MCPToolsManager → FigmaPluginManager → WebSocket → Figma SpeX Plugin
```

## Communication Protocols

### WebSocket Messages (Figma SpeX ↔ Server)

**From Figma SpeX Plugin**:
```json
{
  "name": "specs-data",
  "data": {
    "components": [...],
    "styles": {...},
    "timestamp": "2024-01-01T00:00:00Z"
  }
}
```

**From Server**:
```json
{
  "type": "pull-specs-request",
  "timestamp": "2024-01-01T00:00:00Z"
}
```

### MCP Tools (Cursor AI ↔ Server)

**Tool Call**:
```json
{
  "name": "pull-specs",
  "arguments": {}
}
```

**Tool Response**:
```json
{
  "content": [
    {
      "type": "text",
      "text": "{\"message\": \"Specs pulled from Figma SpeX plugins\", ...}"
    }
  ]
}
```

## Extension Points

### Adding New Figma SpeX Functions

1. Add message handler to `FigmaPluginManager.handleFigmaMessage()`
2. Implement specific handler method
3. Update WebSocket message types documentation

### Adding New MCP Tools

1. Add tool definition to `MCPToolsManager.getToolsList()`
2. Add case to `MCPToolsManager.handleToolCall()`
3. Implement tool handler method
4. Update tool schema and documentation

## Error Handling

- WebSocket connection errors are logged and connections cleaned up
- MCP tool errors return error messages to Cursor AI
- Graceful shutdown handles SIGINT/SIGTERM signals
- Uncaught exceptions are logged and trigger shutdown

## Configuration

### Environment Variables
- WebSocket port: Hardcoded to 8080 (can be made configurable)
- Timeout values: 5 seconds for Figma SpeX responses

### Extensibility
- Message types are easily extensible
- Tool schemas follow JSON Schema format
- Simple and focused architecture for easy maintenance 