UNPKG

spex-mcp

Version:

MCP server for Figma SpeX plugin and Cursor AI integration

439 lines (315 loc) 12.3 kB
# SpeX MCP Server A Model Context Protocol (MCP) server that enables seamless communication between Figma SpeX plugins and Cursor AI. This server provides a modular bridge for design tools to integrate with AI workflows. **Author**: Khoa Hoang ## ✨ Features - **🔀 Dual Interface**: Supports both Figma SpeX plugin connections (WebSocket) and Cursor AI integration (stdio MCP) - **🧩 Modular Architecture**: Separated functions for Figma SpeX plugin management and MCP tools - **🔄 Real-time Communication**: WebSocket server for live Figma SpeX plugin connections - **📡 Event-driven**: Handle multiple Figma SpeX plugin connections simultaneously ## 🏗️ Architecture ``` ┌─────────────────────────────────────────────────────────────────┐ 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 └─────────────────┘ └─────────────────┘ ``` ## 🚀 Installation ### From npm (Recommended) ```bash # Install globally (recommended for CLI usage) npm install -g spex-mcp # Verify installation spex-mcp --help # Or run without installing npx spex-mcp@latest --help # Or install locally in your project npm install spex-mcp ``` **Note**: If you encounter dependency resolution issues with npx, try installing globally first: ```bash npm install -g spex-mcp spex-mcp --port 8080 ``` ### From Source ```bash git clone https://github.com/your-org/spex-mcp.git cd spex-mcp npm install ``` ## 📖 Usage ### Starting the Server If installed globally: ```bash spex-mcp ``` If installed locally or from source: ```bash npm start ``` Or for development with auto-reload: ```bash npm run dev ``` ### Port Configuration You can configure the WebSocket server port using the `--port` parameter and force kill existing processes using `--force`: #### `--force` Option The `--force` option will automatically kill any process currently using the specified port before starting the WebSocket server. This is useful when: - A previous server instance didn't shut down cleanly - Another application is using the port you want to use - You want to ensure a clean start without manual intervention **Cross-platform support:** - **Linux/macOS**: Uses `lsof` to find processes and `kill -9` to terminate them - **Windows**: Uses `netstat` to find processes and `taskkill /F` to terminate them ```bash # Start server on custom port spex-mcp --port 3000 # Force kill any process using the port before starting spex-mcp --force # Combine port and force options spex-mcp --port 3000 --force # Or if using from source node src/index.js --port 3000 node src/index.js --force node src/index.js --port 3000 --force # Start server on default port (8080) spex-mcp # Show help spex-mcp --help ``` **MCP Configuration with Custom Port and Force:** ```json { "mcpServers": { "spex-server": { "command": "spex-mcp", "args": ["--port", "3000", "--force"] } } } ``` Or if installed locally: ```json { "mcpServers": { "spex-server": { "command": "node", "args": ["src/index.js", "--port", "3000"], "cwd": "/path/to/spex-mcp" } } } ``` ### Testing the Server #### Using MCP Inspector (Recommended) The MCP Inspector provides a web-based UI to test your server: ```bash npm run inspect ``` Or directly with npx: ```bash npx @modelcontextprotocol/inspector ``` **Steps to test in inspector:** 1. The inspector will open in your browser 2. Click "Add Server" 3. Enter server details: - **Name**: `spex-server` - **Command**: `spex-mcp` (if installed globally) or `node` - **Arguments**: `["--port", "8080"]` (if using spex-mcp) or `["src/index.js"]` (if using node) - **Working Directory**: Current directory path (if using node) 4. Click "Connect" 5. Test the available tools: - `hello-world`: Test basic connectivity - `get-specs-readme`: Fetch README documentation - `get-spec-files-manifest`: Get file manifest - `get-a-spec-file`: Fetch specific spec file (requires file_name parameter) - `get-page-thumbnail`: Fetch preview image of current page (no parameters required) #### Using the Test Script Run the automated test suite: ```bash npm test ``` ## 📦 Publishing ### Environment Setup For publishing to npm, you need to set up your npm access token. You can do this in two ways: #### Method 1: Using .env file (Recommended) 1. Copy the example environment file: ```bash cp .env.example .env ``` 2. Edit `.env` and add your npm access token: ```bash ENV_NPM_ACCESS_TOKEN=your_actual_npm_token_here ``` 3. Get your token from [npm.com/settings/tokens](https://www.npmjs.com/settings/tokens) #### Method 2: Using environment variables ```bash # Linux/macOS export ENV_NPM_ACCESS_TOKEN=your_token_here # Windows PowerShell $env:ENV_NPM_ACCESS_TOKEN="your_token_here" ``` ### Publishing Commands ```bash # Publish patch version (1.0.0 → 1.0.1) npm run release:patch # Publish minor version (1.0.0 → 1.1.0) npm run release:minor # Publish major version (1.0.0 → 2.0.0) npm run release:major # Manual publish (after version bump) npm run publish:npm ``` ## 🛠️ Available MCP Tools #### `hello-world` Returns a simple greeting message. - **Parameters**: None - **Returns**: Text message with greeting #### `get-specs-readme` Fetches the README.md file from the SpeX plugin that contains documentation about the exported design specs. - **Parameters**: None - **Returns**: README content with project overview and documentation #### `get-spec-files-manifest` Fetches the manifest.yaml file from the SpeX plugin to confirm design specs are ready and get the list of available spec files. - **Parameters**: None - **Returns**: YAML manifest with file listings and metadata #### `get-a-spec-file` Fetches a specific design specification file from the SpeX plugin by filename. - **Parameters**: - `file_name` (required): The name of the spec file to retrieve (e.g., 'screen.yaml', 'components/button.yaml') - **Returns**: File content with component specifications #### `get-page-thumbnail` Fetches a thumbnail image of the current page or screen from the Figma design. Returns the first available preview image generated during the export process. - **Parameters**: None - **Returns**: Page thumbnail as base64 PNG image with proper MIME type for display in AI tools **Note**: This tool uses preview images automatically generated when the Figma plugin exports design specifications. No additional parameters are needed. **Note**: The image tool returns images in the format required by Cursor's MCP image injection: ```javascript { type: "image", data: "base64-encoded-image-data", mimeType: "image/png" } ``` ## 🤖 Cursor AI Integration Add this server to your Cursor MCP configuration: ```json { "mcpServers": { "spex-server": { "command": "node", "args": ["src/index.js"], "cwd": "/path/to/spex-mcp" } } } ``` ## 📡 Message Types ### From Figma SpeX Plugin to Server - `hello-world`: Basic connectivity test - `plugin-ready`: Plugin initialization and readiness notification - `specs-data`: Send design specifications (JSON format) - `file-upload-start`: Initiate binary file upload - `file-upload-end`: Complete binary file upload - `spec-response`: Response to spec file requests (README, manifest, or specific files) ### From Server to Figma SpeX Plugin - `welcome`: Initial connection confirmation - `function-response`: Response to hello-world message - `file-upload-ready`: Acknowledgment to start binary transfer - `specs-data-response`: Response with processing results - `spec-request`: Request for specific files (get-readme, get-manifest, get-spec-file) ## 🏗️ Project Structure ``` spex-mcp/ ├── src/ ├── index.js # Main server orchestration ├── figma-functions.js # Figma SpeX plugin WebSocket management └── mcp-tools.js # MCP tools for Cursor AI ├── docs/ └── ARCHITECTURE.md # Detailed architecture documentation ├── examples/ └── figma-plugin-example.js ├── test/ └── test-server.js ├── package.json └── README.md ``` ## 🛠️ Development The server uses ES modules and includes: - **🔧 Modular Design**: Separated Figma SpeX and MCP functionalities - **🌐 WebSocket Server**: Handles Figma SpeX plugin connections on port 8080 - **📞 MCP Server**: Provides function calls to Cursor AI via stdio - **🔄 Event Handling**: Manages multiple concurrent connections - **⚠️ Error Handling**: Graceful error handling and connection cleanup ### Adding New Features #### New Figma SpeX Functions 1. Add message handler to `FigmaPluginManager.handleFigmaMessage()` 2. Implement specific handler method 3. Update message type documentation #### New MCP Tools 1. Add tool definition to `MCPToolsManager.getToolsList()` 2. Add case to `MCPToolsManager.handleToolCall()` 3. Implement tool handler method See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for detailed extension guidelines. ## 📦 Dependencies - `@modelcontextprotocol/sdk`: MCP protocol implementation - `ws`: WebSocket server for Figma plugin connections ## 🔧 Troubleshooting ### Common Issues #### "Cannot find package" errors with npx If you see module resolution errors when using `npx spex-mcp`, try: 1. **Install globally first**: ```bash npm install -g spex-mcp spex-mcp --port 8080 ``` 2. **Clear npm cache**: ```bash npm cache clean --force npx spex-mcp@latest --port 8080 ``` 3. **Use local installation**: ```bash mkdir my-project && cd my-project npm init -y npm install spex-mcp npx spex-mcp --port 8080 ``` #### Port already in use If you see "EADDRINUSE" errors: ```bash # Try a different port spex-mcp --port 3000 # Or find and kill the process using port 8080 netstat -ano | findstr :8080 # Windows lsof -ti:8080 | xargs kill # macOS/Linux ``` #### Missing dependencies If you see import errors, ensure all dependencies are installed: ```bash npm install -g spex-mcp --force ``` ## 📄 License MIT