````markdown # Mermaid MCP Server User Guide > **Complete guide to using the Mermaid MCP Server with GitHub Copilot, Claude, and other AI assistants** [![npm version](https://badge.fury.io/js/%40narasimhaponnada%2Fmermaid-mcp-server.svg)](https://www.npmjs.com/package/@narasimhaponnada/mermaid-mcp-server) [![Node.js](https://img.shields.io/badge/Node.js-18+-green.svg)](https://nodejs.org/) [![MCP](https://img.shields.io/badge/MCP-1.0.4-purple.svg)](https://modelcontextprotocol.io/) [![Mermaid](https://img.shields.io/badge/Mermaid-10.0+-blue.svg)](https://mermaid.js.org/) ## Overview The **Mermaid MCP (Model Context Protocol) Server** enables AI assistants like GitHub Copilot, Claude, and custom LLM applications to generate, validate, and render professional Mermaid diagrams directly within your development workflow. This guide covers all functionality, integration methods, and usage patterns. > **💡 Quick Install:** `npm install -g @narasimhaponnada/mermaid-mcp-server` > > This guide shows **NPM installation as the recommended method** throughout. Source installation is also documented for developers who want to modify the code. ## 📋 Table of Contents ### Getting Started 1. [Quick Start](#quick-start) 2. [Integration Methods](#-integration-methods) 3. [Using in Other Projects](#-using-mcp-in-other-projects) ### Core Features 4. [Available Tools](#available-tools) 5. [Diagram Types](#diagram-types) 6. [Usage Examples](#usage-examples) ### Advanced Topics 7. [Advanced Features](#advanced-features) 8. [Integration Patterns](#integration-patterns) 9. [Best Practices](#best-practices) 10. [Customization](#customization-options) 11. [Troubleshooting](#troubleshooting) --- ## Quick Start ### ⚡ 3-Step Quick Start #### 1️⃣ Install the MCP Server **Option A: Install from NPM (Recommended)** ```bash # Install globally - works from anywhere npm install -g @narasimhaponnada/mermaid-mcp-server # Verify installation mermaid-mcp --version # Output: mermaid-mcp 1.0.1 ``` **Option B: Install from Source (For Development)** ```bash # Clone and build from source git clone https://github.com/Narasimhaponnada/mermaid-mcp.git cd mermaid-mcp/mermaid-mcp-server npm install && npm run build # Verify build node dist/index.js --version ``` #### 2️⃣ Use with GitHub Copilot Chat Open Copilot Chat (`Cmd+Shift+I`) and type: ``` Create a flowchart showing user authentication with OAuth ``` #### 3️⃣ Get Professional Diagrams Copilot will call the MCP server and return: - ✅ Mermaid diagram code - ✅ Production-ready SVG file - ✅ Markdown-ready format --- ## 🔌 Integration Methods The Mermaid MCP Server supports multiple integration methods for different use cases: ### Method 1: GitHub Copilot in VS Code (Most Common) **Best for:** Daily development workflow, documentation writing, code reviews **Setup Option A: NPM Installation (Easiest)** ```json // Add to VS Code settings.json (Cmd+Shift+P -> "Preferences: Open User Settings (JSON)") { "github.copilot.chat.mcp.enabled": true, "github.copilot.chat.mcp.servers": { "mermaid": { "command": "mermaid-mcp" } } } ``` **Setup Option B: Source Installation** ```json // Add to VS Code settings.json { "github.copilot.chat.mcp.enabled": true, "github.copilot.chat.mcp.servers": { "mermaid": { "command": "node", "args": ["/absolute/path/to/mermaid-mcp-server/dist/index.js"] } } } ``` **Usage:** ```markdown ``` **Copilot will automatically:** - Detect your request - Call the MCP server - Generate the diagram - Return ready-to-use code --- ### Method 2: Claude Desktop App **Best for:** Standalone diagram generation, brainstorming, documentation outside IDE **Setup Option A: NPM Installation (Recommended)** ```json // Edit: ~/Library/Application Support/Claude/claude_desktop_config.json { "mcpServers": { "mermaid": { "command": "mermaid-mcp" } } } ``` **Setup Option B: Source Installation** ```json // Edit: ~/Library/Application Support/Claude/claude_desktop_config.json { "mcpServers": { "mermaid": { "command": "node", "args": ["/Users/YOUR_USERNAME/Documents/Mermaid/mermaid-mcp-server/dist/index.js"] } } } ``` **Usage in Claude:** ``` User: Create a flowchart showing the CI/CD pipeline Claude: I'll use the Mermaid MCP server to generate that... [Calls MCP tool: create_diagram] [Returns professional diagram] ``` --- ### Method 3: Cursor IDE **Best for:** AI-first development environment with built-in MCP support **Setup Option A: NPM Installation (Recommended)** ```json // Add to Cursor settings (Settings -> MCP Servers) { "mcpServers": { "mermaid": { "command": "mermaid-mcp" } } } ``` **Setup Option B: Source Installation** ```json // Add to Cursor settings (Settings -> MCP Servers) { "mcpServers": { "mermaid": { "command": "node", "args": ["/absolute/path/to/mermaid-mcp-server/dist/index.js"] } } } ``` **Usage:** Same as Copilot - natural language requests in chat or comments --- ### Method 4: Direct CLI Usage **Best for:** Automation, scripts, CI/CD pipelines, batch generation **Option A: Using NPM Package (Recommended)** ```bash # If installed globally mermaid-mcp --help mermaid-mcp --version # Run the server (for MCP protocol communication) mermaid-mcp ``` **Option B: Using Source Code** ```bash cd ~/Documents/Mermaid/mermaid-mcp-server # Generate sample architecture diagrams node generate-svg-samples.js # Output: 5 production-ready SVG files in examples/architectures/ ``` **Custom Generation Script:** ```javascript // custom-diagram-generator.js import puppeteer from 'puppeteer'; import fs from 'fs/promises'; async function generateDiagram(mermaidCode, outputPath) { const browser = await puppeteer.launch({ headless: 'new' }); const page = await browser.newPage(); const html = `
${mermaidCode}
`; await page.setContent(html); await page.waitForTimeout(3000); const svg = await page.evaluate(() => { return document.querySelector('.mermaid svg').outerHTML; }); await fs.writeFile(outputPath, svg.replace(/
/g, '
').trim()); await browser.close(); } // Usage await generateDiagram('graph TD\n A[Start] --> B[End]', 'output.svg'); ``` --- ### Method 5: MCP Inspector (Testing & Debugging) **Best for:** Testing tools, debugging, development **Install:** ```bash npm install -g @modelcontextprotocol/inspector ``` **Run with NPM Package (Recommended):** ```bash # Start inspector with globally installed MCP server mcp-inspector mermaid-mcp ``` **Run with Source:** ```bash # Start inspector with source code mcp-inspector node ~/Documents/Mermaid/mermaid-mcp-server/dist/index.js ``` **Use:** - Opens web interface at http://localhost:5173 - Test all MCP tools interactively - View request/response JSON - Debug server behavior --- ### Method 6: Custom LLM Applications **Best for:** Building your own AI apps with diagram generation **Example: Node.js Integration (NPM Package)** ```typescript import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; // Create MCP client (using globally installed NPM package) const transport = new StdioClientTransport({ command: 'mermaid-mcp' }); const client = new Client({ name: 'my-app', version: '1.0.0' }, { capabilities: {} }); await client.connect(transport); // List available tools const tools = await client.listTools(); console.log('Available tools:', tools); // Generate diagram const result = await client.callTool({ name: 'create_diagram', arguments: { type: 'flowchart', description: 'User authentication process' } }); console.log('Generated diagram:', result); ``` **Example: Python Integration** ```python import subprocess import json def call_mermaid_mcp(tool_name, arguments): """Call Mermaid MCP server from Python""" request = { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": tool_name, "arguments": arguments } } process = subprocess.Popen( ['node', '/path/to/mermaid-mcp-server/dist/index.js'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) stdout, stderr = process.communicate( input=json.dumps(request).encode() ) return json.loads(stdout.decode()) # Usage result = call_mermaid_mcp('create_diagram', { 'type': 'sequence', 'description': 'API request flow' }) print(result) ``` --- ## 🚀 Using MCP in Other Projects ### Scenario 1: Adding to Existing VS Code Project **Goal:** Enable Copilot to generate diagrams in your current project **Steps:** 1. **Verify MCP Server Setup** (one-time) ```bash cd ~/Documents/Mermaid/mermaid-mcp-server npm run build ``` 2. **Add to VS Code Workspace Settings** ```json // .vscode/settings.json in your project { "github.copilot.mcp.servers": { "mermaid": { "command": "node", "args": ["${env:HOME}/Documents/Mermaid/mermaid-mcp-server/dist/index.js"] } } } ``` 3. **Use in Your Project** ```markdown # docs/architecture.md ## System Overview ``` **Benefits:** - ✅ Team members inherit the configuration - ✅ Diagrams stay consistent - ✅ Documentation updates are AI-assisted --- ### Scenario 2: Documentation Repository **Goal:** Automated diagram generation in a docs repo **Project Structure:** ``` docs-repo/ ├── .vscode/ │ └── settings.json # MCP configuration ├── diagrams/ │ ├── generate.js # Custom generator script │ └── templates/ # Diagram templates ├── architecture/ │ └── system-design.md # Auto-generated diagrams └── package.json # Scripts for automation ``` **Setup:** 1. **Add npm script** ```json { "scripts": { "diagrams:generate": "node diagrams/generate.js", "diagrams:watch": "nodemon diagrams/generate.js" }, "devDependencies": { "nodemon": "^3.0.0" } } ``` 2. **Create generator script** ```javascript // diagrams/generate.js import { execSync } from 'child_process'; import fs from 'fs'; const diagrams = [ { name: 'auth-flow', description: 'User authentication with OAuth', output: 'architecture/auth-flow.svg' }, { name: 'data-pipeline', description: 'ETL data processing pipeline', output: 'architecture/data-pipeline.svg' } ]; for (const diagram of diagrams) { console.log(`Generating ${diagram.name}...`); // Generate using MCP or direct Puppeteer } ``` 3. **Use in GitHub Actions** ```yaml # .github/workflows/update-diagrams.yml name: Update Diagrams on: push: paths: - 'diagrams/**' jobs: generate: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Node.js uses: actions/setup-node@v3 with: node-version: '18' - name: Install dependencies run: | cd ~/Documents/Mermaid/mermaid-mcp-server npm install - name: Generate diagrams run: npm run diagrams:generate - name: Commit updated diagrams run: | git config user.name "GitHub Actions" git config user.email "actions@github.com" git add architecture/*.svg git commit -m "📊 Update architecture diagrams" git push ``` --- ### Scenario 3: Web Application Integration **Goal:** Generate diagrams on-demand in a web app **Architecture:** ``` web-app/ ├── frontend/ # React/Vue/Angular │ └── components/ │ └── DiagramViewer.tsx ├── backend/ │ └── api/ │ └── diagrams.ts # MCP client integration └── mcp-client/ # Wrapper around MCP server └── index.ts ``` **Backend API (Express + MCP):** ```typescript // backend/api/diagrams.ts import express from 'express'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; const router = express.Router(); // Initialize MCP client (reuse connection) let mcpClient: Client | null = null; async function getMCPClient() { if (!mcpClient) { const transport = new StdioClientTransport({ command: 'node', args: [process.env.MCP_SERVER_PATH] }); mcpClient = new Client({ name: 'web-app', version: '1.0.0' }, {}); await mcpClient.connect(transport); } return mcpClient; } // API endpoint router.post('/generate', async (req, res) => { try { const { type, description } = req.body; const client = await getMCPClient(); const result = await client.callTool({ name: 'create_diagram', arguments: { type, description } }); res.json(result); } catch (error) { res.status(500).json({ error: error.message }); } }); export default router; ``` **Frontend Component (React):** ```typescript // frontend/components/DiagramViewer.tsx import React, { useState } from 'react'; export function DiagramGenerator() { const [description, setDescription] = useState(''); const [diagram, setDiagram] = useState(''); const [loading, setLoading] = useState(false); const generateDiagram = async () => { setLoading(true); try { const response = await fetch('/api/diagrams/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type: 'flowchart', description }) }); const result = await response.json(); setDiagram(result.content); } catch (error) { console.error('Failed to generate diagram:', error); } setLoading(false); }; return (