Skip to main content
Glama
README.md
# mcp-diagram-agent

> **Describe a system in plain English, get back an editable Excalidraw architecture diagram. An MCP server for Claude.**

[![CI](https://github.com/shaikn6/mcp-diagram-agent/actions/workflows/ci.yml/badge.svg)](https://github.com/shaikn6/mcp-diagram-agent/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-3776AB?logo=python&logoColor=white)](pyproject.toml)

**An MCP server and REST API that turn a plain-text system description into an editable Excalidraw architecture diagram: Claude writes only a node/edge spec, and layout, styling and serialization are deterministic, unit-tested code.**

MCP Diagram Agent is a [Model Context Protocol](https://modelcontextprotocol.io/) server that accepts a natural language description of a software system and returns an [Excalidraw](https://excalidraw.com/)-compatible JSON diagram you can import and edit immediately. Claude only ever produces a structured **node/edge spec** — the layout, layer-aware coloring, and Excalidraw serialization are deterministic Python, so the same spec always produces the same layout, colors, and geometry (element ids mix in a timestamp, so the id strings differ between runs).

The same generator is exposed over **two transports**: an MCP `stdio` server (the `generate_diagram` tool, for Claude Desktop and other MCP clients) and a **FastAPI REST API** (`POST /generate`) for any HTTP client.

---

## Architecture

A request enters through either transport and converges on a single lazily-initialized `DiagramGenerator`. The LLM boundary is narrow by design: Claude returns a JSON spec of nodes (`id`, `label`, `layer`, `shape`) and edges (`from`, `to`, `label`, `style`), and everything visual after that is computed locally and unit-tested.

```mermaid
flowchart TD
    subgraph clients[Clients]
        MCPC[Claude Desktop / MCP client]
        HTTP[curl / HTTP client]
    end

    subgraph transports[Transports — src/server.py]
        MCP["MCP server (stdio)<br/>list_tools / call_tool"]
        REST["FastAPI :8000<br/>POST /generate · GET /health"]
    end

    MCPC -- generate_diagram --> MCP
    HTTP -- POST /generate --> REST
    MCP --> GEN
    REST --> GEN

    subgraph engine[DiagramGenerator — src/diagram_generator.py]
        GEN["agenerate() → generate()<br/>run_in_executor thread pool"]
        CLAUDE[Claude messages.create<br/>_SYSTEM_PROMPT]
        PARSE["_parse_claude_response()<br/>strip_json_fences + json.loads"]
        BUILD["_build_elements(spec)"]
        LAYOUT["_layout_nodes()<br/>layered columns by semantic layer"]
        COLOR["color_for_layer()<br/>Catppuccin Mocha palette"]
        ARROW["build_arrow_points()<br/>edge geometry"]
    end

    GEN --> CLAUDE
    CLAUDE -- JSON spec: nodes + edges --> PARSE
    PARSE --> BUILD
    BUILD --> LAYOUT
    BUILD --> COLOR
    BUILD --> ARROW

    BUILD --> DOC[ExcalidrawDocument<br/>Pydantic model]
    DOC --> RESP[DiagramResponse<br/>diagram · element_count · summary · model_used]
```

---

## How it works

The design keeps the LLM responsible only for *semantics* and the code responsible for *rendering* — this makes output deterministic, testable, and cheap.

1. **Narrow LLM contract.** `_SYSTEM_PROMPT` constrains Claude to emit a strict JSON object: a `summary`, a list of `nodes` (`id`, `label`, `layer`, `shape`, `description`) and a list of `edges` (`from`, `to`, `label`, `style`). No coordinates, colors, or Excalidraw internals are ever asked of the model.
2. **Fence-tolerant parsing.** `_parse_claude_response()` runs the raw text through `strip_json_fences()` before `json.loads()`, so ```` ```json ```` wrappers never break the pipeline.
3. **Deterministic layered layout.** `_layout_nodes()` groups nodes by semantic layer (`client → gateway → service → queue → data → external → default`), assigns each layer its own column (+280px per layer) and stacks nodes vertically within a layer (+140px each). Layout is pure arithmetic — no randomness, no LLM.
4. **Layer-aware styling.** `_build_elements()` maps each node's `shape` string to an `ElementType` enum and resolves stroke/fill via `color_for_layer()` using the [Catppuccin Mocha](https://github.com/catppuccin/catppuccin) palette; edges become Excalidraw arrows whose points are computed by `build_arrow_points()` (center-right of source → center-left of target), honoring solid/dashed/dotted styles.
5. **Connectivity-preserving trim.** If Claude's raw spec exceeds `max_elements`, the generator trims the spec *before* building elements: it reserves a small edge budget (at least 1, up to a quarter of the cap) instead of dropping every edge in favor of one more node, keeps nodes up to the remaining budget, then keeps only the edges that connect two surviving nodes. An 8-node chain (`n0 → n1 → … → n7`) trimmed to `max_elements=6`, for example, keeps nodes `n0`–`n4` plus the `n0 → n1` edge — 6 elements that are still connected, instead of 6 isolated boxes.
6. **Validated, importable output.** Elements are assembled into an `ExcalidrawDocument` (Pydantic v2) and serialized through `model_dump_excalidraw()`, which emits the key shape Excalidraw expects per element type. A validator requires every color to start with `#` (or be the literal `transparent`). The result is wrapped in a `DiagramResponse` (`element_count` clamped to `max_elements`).
7. **Non-blocking by default.** `agenerate()` runs the synchronous `generate()` in a thread pool via `loop.run_in_executor()`, so the async REST/MCP handlers never block the event loop on the Anthropic call.

---

## Quickstart

```bash
# 1. Clone
git clone https://github.com/shaikn6/mcp-diagram-agent.git && cd mcp-diagram-agent

# 2. Set your keys (a real Anthropic key is needed: every /generate call makes one paid model call)
export ANTHROPIC_API_KEY=sk-ant-... MCP_API_KEY=choose-a-long-random-secret
printf 'ANTHROPIC_API_KEY=%s\nMCP_API_KEY=%s\n' "$ANTHROPIC_API_KEY" "$MCP_API_KEY" > .env

# 3. Start with Docker
docker-compose up --build

# 4. Generate a diagram (auth required)
curl -s -X POST http://localhost:8000/generate \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $MCP_API_KEY" \
  -d '{"description": "Microservices app: API gateway, auth service, user service, PostgreSQL"}' \
  | python -m json.tool

# 5. Paste the "diagram" field contents into https://excalidraw.com/
```

---

## MCP Usage

Add this server to your MCP client (e.g. Claude Desktop `claude_desktop_config.json`):

```json
{
  "mcpServers": {
    "diagram-agent": {
      "command": "python",
      "args": ["-m", "src.server", "--mcp"],
      "cwd": "/absolute/path/to/mcp-diagram-agent",
      "env": {
        "ANTHROPIC_API_KEY": "sk-ant-..."
      }
    }
  }
}
```

`python -m src.server --mcp` imports the `src` package, so set `cwd` to the repo
root (as above). If you `pip install .` instead, use the installed console script
`mcp-diagram-agent-mcp` as the `command` and drop `cwd` and `args`. Both entry
points load a local `.env` (via `python-dotenv`) if one is present.

Then in Claude Desktop, use the `generate_diagram` tool:

```
Generate a diagram for: "Event-driven e-commerce platform with Kafka,
order service, inventory service, payment service, and Redis cache."
```

Claude will call `generate_diagram` and return Excalidraw JSON you can paste directly into [excalidraw.com](https://excalidraw.com/).

---

## REST API Usage

### `POST /generate`

```bash
curl -X POST http://localhost:8000/generate \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $MCP_API_KEY" \
  -d '{
    "description": "Three-tier web app: React SPA, Node.js REST API, MongoDB Atlas",
    "style": "technical",
    "max_elements": 20
  }'
```

**Response** (representative — labels, counts, and summary depend on the model's spec):

```json
{
  "diagram": {
    "type": "excalidraw",
    "version": 2,
    "elements": [ ... ],
    "appState": { "viewBackgroundColor": "#ffffff" },
    "files": {}
  },
  "element_count": 9,
  "description_summary": "Three-tier web architecture with React frontend, Node.js API, and MongoDB.",
  "model_used": "claude-sonnet-4-5"
}
```

### `GET /health`

```bash
curl http://localhost:8000/health
# {"status":"ok","version":"1.0.0","service":"mcp-diagram-agent"}
```

Interactive docs are available at `http://localhost:8000/docs`.

---

## Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `ANTHROPIC_API_KEY` | **Yes** | — | Your Anthropic API key |
| `MCP_API_KEY` | **Yes** (for REST) | — | Shared secret required to call `POST /generate`. If unset, `/generate` returns `503` (fail-closed) |
| `MCP_RATE_LIMIT_PER_MIN` | No | `30` | Max `POST /generate` requests per minute, per API key (falls back to client IP) |
| `CLAUDE_MODEL` | No | `claude-sonnet-4-5` | Claude model to use |
| `HOST` | No | `0.0.0.0` | Bind host for the REST server |
| `PORT` | No | `8000` | Bind port for the REST server |
| `LOG_LEVEL` | No | `info` | Logging level (`debug`, `info`, `warning`, `error`) |
| `RELOAD` | No | `false` | Enable hot-reload (development only) |
| `CORS_ORIGINS` | No | _(none)_ | Comma-separated allowed CORS origins. Defaults to no cross-origin access; set it explicitly to opt in |

Copy `.env.example` to `.env` to get started.

> **Authentication:** `POST /generate` requires an API key; `/health`, `/docs`, and `/redoc` stay open. Set `MCP_API_KEY` to a long random secret and send it on every request as either `Authorization: Bearer <key>` or `X-API-Key: <key>`. The key is compared in constant time. If `MCP_API_KEY` is unset the endpoint fails closed with `503`; a missing or wrong key returns `401`. Requests are rate limited to `MCP_RATE_LIMIT_PER_MIN` per key (default `30`), returning `429` when exceeded. `CORS_ORIGINS` no longer defaults to `*` — cross-origin access is denied unless you list origins explicitly. Keep the service behind a private network or authenticating proxy for defense in depth.

---

## Local Development

```bash
# Install with dev extras
pip install -e ".[dev]"

# Run all tests
pytest

# Lint + format
ruff check src/ tests/ && ruff format src/ tests/

# Type check
mypy src/

# Run the API server with auto-reload
RELOAD=true python -m src.server
```

---

## Supported Diagram Elements

| Shape | Excalidraw type | Semantic layer |
|-------|----------------|----------------|
| Rectangle | `rectangle` | services, gateways, data stores |
| Ellipse | `ellipse` | clients, external systems |
| Diamond | `diamond` | decision points |
| Arrow | `arrow` | data flow, API calls |

Layer colors follow the [Catppuccin Mocha](https://github.com/catppuccin/catppuccin) palette for a cohesive look:

| Layer | Color |
|-------|-------|
| `client` | Sky blue |
| `gateway` | Red |
| `service` | Green |
| `data` | Peach |
| `queue` | Yellow |
| `external` | Mauve |

---

## Limitations

This is an alpha tool. Known constraints, honestly stated:

- **Labels may not render as bound text on import.** Node labels are emitted as a `text` field on the shape, and edge labels as an arrow `label` object. Excalidraw renders container and arrow labels from *separate bound text elements* (linked via `boundElements` / `containerId`), which this version does not emit yet. Boxes, arrows, positions, and colors import cleanly; depending on your Excalidraw version the text may not appear until you re-type it. This is the top item on the roadmap.
- **Arrows are not bound to nodes.** `startBinding` and `endBinding` are `null`, so arrows are positioned by geometry but do not follow a box when you drag it in Excalidraw.
- **One LLM call, no self-repair.** The generator makes a single `messages.create` call. If the model returns a spec that fails validation, the request fails with a `422` rather than retrying or repairing — there is no multi-turn correction loop.
- **Layout is column-by-layer only.** `_layout_nodes()` places each semantic layer in its own column and stacks nodes vertically. There is no edge-crossing minimization or force-directed layout, so dense graphs can overlap arrows.
- **Rate limiting is in-process.** The fixed-window limiter lives in a single process; it does not coordinate across multiple workers or hosts. Put a shared gateway in front for multi-instance deployments.
- **Descriptions leave the machine and are partly logged.** Every request sends the full description to the Anthropic API, and the REST server logs its first 80 characters at `INFO` level (the default). Do not send secrets in descriptions; set `LOG_LEVEL=warning` to stop that log line.
- **No quality evaluation.** The tests check the deterministic code with a mocked model; there is no benchmark of how often the model's spec matches the described system.
- **Output quality depends on the model.** Node/edge *semantics* come from Claude, so ambiguous or very large descriptions can yield incomplete diagrams. `max_elements` trims oversized specs but cannot add missing structure.

---

## Tests

The deterministic core (parsing, layout, color mapping, arrow geometry, Pydantic serialization, the advertised MCP tool schema, and both transports) is covered by **184 tests** (`pytest --co -q`) across `test_server.py`, `test_diagram_generator.py`, and `test_comprehensive.py`. The Anthropic client is mocked, so the whole suite runs offline with no API key. The project enforces a **95% coverage gate** (`--cov-fail-under=95` in `pyproject.toml`); the suite currently runs at **98%**.

```bash
pytest                    # full suite with coverage
```

---

## Tech stack

Python 3.11 · `mcp` (Model Context Protocol SDK) · `anthropic` (Claude Sonnet) · `fastapi` + `uvicorn` (REST transport) · `pydantic` v2 (validation + Excalidraw serialization) · `python-dotenv`. Built with Hatchling, tested with `pytest` (+ `pytest-asyncio`, `pytest-cov`), linted with `ruff`, type-checked with `mypy --strict`.

---

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md). All contributions are welcome — bug reports, feature requests, and pull requests.

---

## Security

See [SECURITY.md](SECURITY.md) for the vulnerability disclosure policy.

---

## License

MIT — see [LICENSE](LICENSE).

---
<sub>Part of [Nagizaaz Shaik's open-source work](https://github.com/shaikn6) · [all repositories](https://github.com/shaikn6?tab=repositories)</sub>