Skip to main content
Glama
rf-santos

Draw.io MCP Server

by rf-santos
README.md
# Draw.io MCP Server

A Model Context Protocol (MCP) server that enables AI assistants to create, read, and manage Draw.io diagrams programmatically through natural language interactions.

## Overview

The Draw.io MCP Server bridges the gap between conversational AI and visual documentation, allowing users to generate professional-quality diagrams without manual drawing effort. Perfect for technical writers, software developers, and anyone who needs to create architecture diagrams, flowcharts, and network diagrams quickly.

## Features

- **Write XML**: Create or update diagrams using valid Draw.io XML for complete control over diagram structure
- **Read Diagrams**: Parse and analyze existing Draw.io files with detailed shape and connection information
- **Add Shapes**: Insert new shapes (rectangles, ellipses, diamonds, cylinders, hexagons) into diagrams
- **Add Connections**: Create edges between diagram elements
- **Export Support**: Instructions for exporting to PNG, SVG, and PDF formats

## Installation

### Prerequisites

- Python 3.12 or higher
- uv (recommended) or pip

### Setup

#### Option 1: Install from PyPI (coming soon)
```bash
pip install drawio-mcp
```

#### Option 2: Install from source
```bash
git clone <repository-url>
cd drawio-mcp
uv sync --all-extras
```

#### Option 3: Build and install locally
```bash
git clone <repository-url>
cd drawio-mcp
uv sync --all-extras
uv pip install build
python -m build
pip install dist/drawio_mcp-0.0.1-py3-none-any.whl
```

## Usage

### Running the Server

The server communicates via stdio (standard input/output):

```bash
# If installed as package
drawio-mcp

# Or run as module
python -m drawio_mcp

# Or run from source
python src/drawio_mcp/__init__.py
```

### Configuration with Claude Desktop

Add to your Claude Desktop configuration (`~/Library/Application Support/Claude/claude_desktop_config.json` on macOS):

```json
{
  "mcpServers": {
    "drawio": {
      "command": "drawio-mcp",
      "args": [],
      "env": {}
    }
  }
}
```

Or if running from source:
```json
{
  "mcpServers": {
    "drawio": {
      "command": "/absolute/path/to/drawio-mcp/.venv/bin/python",
      "args": ["-m", "drawio_mcp"],
      "env": {}
    }
  }
}
```

### Available Tools

#### 1. `write_diagram_xml` ⭐ PRIMARY TOOL
Write or update a Draw.io diagram file using valid Draw.io XML content. This provides complete control over diagram structure and is the recommended way to create diagrams.

**Parameters:**
- `file_path` (string): Path where the .drawio file should be saved or updated (creates file and directories if they don't exist)
- `xml_content` (string): Valid Draw.io XML content (must include complete mxfile structure)
- `validate` (boolean, optional): Whether to validate the XML before writing (default: true)

**Example:**
```
Write this XML to a new diagram file at ~/diagrams/custom.drawio:
<mxfile host="AI Agent" version="21.6.5" type="device">
  <diagram name="My Diagram" id="d1">
    <mxGraphModel dx="2037" dy="830" grid="1" gridSize="10">
      <root>
        <mxCell id="0" />
        <mxCell id="1" parent="0" />
        <mxCell id="shape1" value="Hello" style="whiteSpace=wrap;rounded=1;" vertex="1" parent="1">
          <mxGeometry x="100" y="100" width="120" height="60" as="geometry" />
        </mxCell>
      </root>
    </mxGraphModel>
  </diagram>
</mxfile>
```

**Use Cases:**
- Generate complex diagrams programmatically from code analysis
- Convert other diagram formats (Mermaid, PlantUML, etc.) to Draw.io
- Batch process diagram creation from data sources
- Create custom diagram templates with precise styling
- Build flowcharts, architecture diagrams, network topologies, ER diagrams, and more

**Key Features:**
- ✅ Creates files and directories automatically if they don't exist
- ✅ XML validation with detailed error messages
- ✅ Pretty-printed output for version control
- ✅ Returns statistics (shapes, connections, file size)

**Documentation:** See [WRITE_XML_TOOL.md](WRITE_XML_TOOL.md) for comprehensive documentation, examples, and XML structure reference. See [EXAMPLES_XML_TOOL.md](EXAMPLES_XML_TOOL.md) for practical use cases and [QUICK_REFERENCE_XML.md](QUICK_REFERENCE_XML.md) for quick XML templates.

#### 2. `read_diagram`
Read and parse an existing Draw.io diagram file.

**Parameters:**
- `file_path` (string): Path to the .drawio or .xml file

**Example:**
```
Read the diagram at ~/diagrams/architecture.drawio and tell me what's in it
```

#### 3. `add_shape`
Add a new shape to an existing diagram.

**Parameters:**
- `file_path` (string): Path to the diagram file
- `shape_type` (string): Type of shape - `rectangle`, `ellipse`, `diamond`, `cylinder`, `hexagon`, `rounded_rectangle`
- `text` (string): Text content for the shape
- `x` (number): X coordinate position
- `y` (number): Y coordinate position
- `width` (number, optional): Width of the shape (default: 120)
- `height` (number, optional): Height of the shape (default: 60)

**Example:**
```
Add a database cylinder shape labeled "User DB" at position (300, 200) to ~/diagrams/architecture.drawio
```

#### 4. `add_connection`
Add a connection between two shapes.

**Parameters:**
- `file_path` (string): Path to the diagram file
- `from_shape` (string): ID or text label of the source shape
- `to_shape` (string): ID or text label of the target shape
- `label` (string, optional): Optional label for the connection

**Example:**
```
Connect the "API Server" shape to the "Database" shape in ~/diagrams/architecture.drawio
```

#### 5. `export_diagram`
Get instructions for exporting a diagram to various formats.

**Parameters:**
- `file_path` (string): Path to the .drawio file
- `output_path` (string): Path for the exported file
- `format` (string): Export format - `png`, `svg`, or `pdf`

**Example:**
```
Export ~/diagrams/architecture.drawio to PNG format at ~/diagrams/architecture.png
```

## Creating Diagrams

The primary way to create diagrams is using the `write_diagram_xml` tool. This gives you complete control over the diagram structure using Draw.io's XML format.

### Quick Examples

**Simple Flowchart:**
```xml
<mxfile host="AI Agent" version="21.6.5" type="device">
  <diagram name="Process Flow" id="flow1">
    <mxGraphModel dx="2037" dy="830" grid="1" gridSize="10">
      <root>
        <mxCell id="0" />
        <mxCell id="1" parent="0" />
        <mxCell id="start" value="Start" style="whiteSpace=wrap;rounded=1;fillColor=#d5e8d4;strokeColor=#82b366;" vertex="1" parent="1">
          <mxGeometry x="100" y="50" width="120" height="60" as="geometry" />
        </mxCell>
        <mxCell id="end" value="End" style="whiteSpace=wrap;rounded=1;fillColor=#d5e8d4;strokeColor=#82b366;" vertex="1" parent="1">
          <mxGeometry x="100" y="150" width="120" height="60" as="geometry" />
        </mxCell>
        <mxCell id="e1" style="edgeStyle=orthogonalEdgeStyle;rounded=0;" edge="1" parent="1" source="start" target="end">
          <mxGeometry relative="1" as="geometry" />
        </mxCell>
      </root>
    </mxGraphModel>
  </diagram>
</mxfile>
```

**Architecture Diagram:**
See [WRITE_XML_TOOL.md](WRITE_XML_TOOL.md) and [EXAMPLES_XML_TOOL.md](EXAMPLES_XML_TOOL.md) for comprehensive examples of flowcharts, architecture diagrams, network topologies, and more.

## Diagram Types

All diagram types can be created using the `write_diagram_xml` tool with appropriate XML structure:

### Flowcharts
Process flows with start/end nodes, process steps, and decision diamonds.

### Architecture Diagrams
System architecture with servers, databases, APIs, and connections showing data flow.

### Network Topologies
Network topology diagrams with routers, switches, firewalls, and devices.

### ER Diagrams
Entity-relationship diagrams for database schemas showing tables and relationships.

### Sequence Diagrams
Interaction diagrams showing message flows between components over time.

### Custom Diagrams
Any diagram type supported by Draw.io can be created with the appropriate XML structure.

**Resources:**
- [WRITE_XML_TOOL.md](WRITE_XML_TOOL.md) - Complete XML reference and shape styles
- [EXAMPLES_XML_TOOL.md](EXAMPLES_XML_TOOL.md) - Real-world examples and use cases
- [QUICK_REFERENCE_XML.md](QUICK_REFERENCE_XML.md) - Quick templates and snippets

## Technical Details

### Architecture

- **MCP Protocol**: Uses the Model Context Protocol for AI-tool communication
- **XML-Based**: Direct XML manipulation for maximum flexibility and control
- **Transport**: stdio-based communication for integration with MCP clients

### File Format

Generated files use the standard Draw.io XML format (.drawio), which is:
- Human-readable XML text format
- Editable in Draw.io desktop and web applications
- Version control friendly
- Compatible with all Draw.io features and libraries
- Industry-standard format

## Capabilities and Limitations

### What You Can Do

✅ **Create any diagram type** - Full control via XML  
✅ **Read and analyze diagrams** - Parse shapes, connections, and metadata  
✅ **Precise positioning** - Control exact coordinates and sizes  
✅ **Custom styling** - Full access to colors, shapes, and styles  
✅ **Batch operations** - Generate multiple diagrams programmatically  
✅ **Template-based creation** - Reusable diagram patterns  

### Current Limitations

⚠️ **Export functionality** - Requires external Draw.io CLI or desktop app for PNG/SVG/PDF export  
⚠️ **Shape/Connection addition** - The `add_shape` and `add_connection` tools are limited due to drawpyo constraints; use `write_diagram_xml` for full control  

### Current Limitations

⚠️ **Export functionality** - Requires external Draw.io CLI or desktop app for PNG/SVG/PDF export  
⚠️ **Shape/Connection addition** - The `add_shape` and `add_connection` tools are limited due to drawpyo constraints; use `write_diagram_xml` for full control  

## Development

### Project Structure

```
drawio-mcp/
├── src/
│   └── drawio_mcp/
│       ├── __init__.py      # MCP server implementation
│       └── __main__.py      # Module entry point
├── dist/                    # Build artifacts
├── examples/                # Example diagrams
├── pyproject.toml          # Project configuration and dependencies
├── README.md               # This file
├── SETUP.md                # Setup guide
└── BUILD_SUMMARY.md        # Build documentation
```

### Dependencies

- `mcp>=1.0.0`: Model Context Protocol SDK
- `drawpyo>=0.2.0`: Draw.io diagram creation library
- `pytest>=7.0.0`: Testing framework (dev)
- `pytest-asyncio>=0.21.0`: Async testing support (dev)

### Building

To build the package for distribution:

```bash
uv sync --all-extras
python -m build
```

This creates:
- `dist/drawio_mcp-0.0.1-py3-none-any.whl` (wheel package)
- `dist/drawio_mcp-0.0.1.tar.gz` (source distribution)

## Roadmap

**Current (v0.0.1)**
- ✅ XML-based diagram creation with full control
- ✅ Diagram reading and parsing
- ✅ Shape and connection tools (limited functionality)
- ✅ Comprehensive documentation and examples

**Next Release (v0.1.0)**
- [ ] Enhanced XML templates library
- [ ] Merge functionality for selective updates
- [ ] Style preset system
- [ ] Auto-layout algorithms
- [ ] XML-to-JSON conversion helpers

**Future**
- [ ] Direct export integration (PNG/SVG/PDF)
- [ ] Code-to-diagram generators (Python, JavaScript, Java)
- [ ] Interactive diagram editor integration
- [ ] Multi-page diagram support
- [ ] Diagram diffing for version control

## Contributing

Contributions are welcome! Please feel free to submit issues or pull requests.

## License

[Add your license here]

## Acknowledgments

- Built with [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk)
- Diagram generation powered by [drawpyo](https://github.com/MerrimanInd/drawpyo)
- Based on [Draw.io](https://www.drawio.com/)

## Support

For issues, questions, or feature requests, please open an issue on GitHub.