MCP Diagram Agent
Generates editable Excalidraw architecture diagrams as Excalidraw-compatible JSON that can be imported and edited in excalidraw.com.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
mcp-diagram-agent
Describe a system in plain English, get back an editable Excalidraw architecture diagram. An MCP server for Claude.
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 server that accepts a natural language description of a software system and returns an Excalidraw-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.
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]Related MCP server: excalidash-mcp
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.
Narrow LLM contract.
_SYSTEM_PROMPTconstrains Claude to emit a strict JSON object: asummary, a list ofnodes(id,label,layer,shape,description) and a list ofedges(from,to,label,style). No coordinates, colors, or Excalidraw internals are ever asked of the model.Fence-tolerant parsing.
_parse_claude_response()runs the raw text throughstrip_json_fences()beforejson.loads(), so```jsonwrappers never break the pipeline.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.Layer-aware styling.
_build_elements()maps each node'sshapestring to anElementTypeenum and resolves stroke/fill viacolor_for_layer()using the Catppuccin Mocha palette; edges become Excalidraw arrows whose points are computed bybuild_arrow_points()(center-right of source → center-left of target), honoring solid/dashed/dotted styles.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 tomax_elements=6, for example, keeps nodesn0–n4plus then0 → n1edge — 6 elements that are still connected, instead of 6 isolated boxes.Validated, importable output. Elements are assembled into an
ExcalidrawDocument(Pydantic v2) and serialized throughmodel_dump_excalidraw(), which emits the key shape Excalidraw expects per element type. A validator requires every color to start with#(or be the literaltransparent). The result is wrapped in aDiagramResponse(element_countclamped tomax_elements).Non-blocking by default.
agenerate()runs the synchronousgenerate()in a thread pool vialoop.run_in_executor(), so the async REST/MCP handlers never block the event loop on the Anthropic call.
Quickstart
# 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):
{
"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.
REST API Usage
POST /generate
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):
{
"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
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 |
| Yes | — | Your Anthropic API key |
| Yes (for REST) | — | Shared secret required to call |
| No |
| Max |
| No |
| Claude model to use |
| No |
| Bind host for the REST server |
| No |
| Bind port for the REST server |
| No |
| Logging level ( |
| No |
| Enable hot-reload (development only) |
| 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 /generaterequires an API key;/health,/docs, and/redocstay open. SetMCP_API_KEYto a long random secret and send it on every request as eitherAuthorization: Bearer <key>orX-API-Key: <key>. The key is compared in constant time. IfMCP_API_KEYis unset the endpoint fails closed with503; a missing or wrong key returns401. Requests are rate limited toMCP_RATE_LIMIT_PER_MINper key (default30), returning429when exceeded.CORS_ORIGINSno 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
# 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.serverSupported Diagram Elements
Shape | Excalidraw type | Semantic layer |
Rectangle |
| services, gateways, data stores |
Ellipse |
| clients, external systems |
Diamond |
| decision points |
Arrow |
| data flow, API calls |
Layer colors follow the Catppuccin Mocha palette for a cohesive look:
Layer | Color |
| Sky blue |
| Red |
| Green |
| Peach |
| Yellow |
| 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
textfield on the shape, and edge labels as an arrowlabelobject. Excalidraw renders container and arrow labels from separate bound text elements (linked viaboundElements/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.
startBindingandendBindingarenull, 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.createcall. If the model returns a spec that fails validation, the request fails with a422rather 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
INFOlevel (the default). Do not send secrets in descriptions; setLOG_LEVEL=warningto 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_elementstrims 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%.
pytest # full suite with coverageTech 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. All contributions are welcome — bug reports, feature requests, and pull requests.
Security
See SECURITY.md for the vulnerability disclosure policy.
License
MIT — see LICENSE.
Part of Nagizaaz Shaik's open-source work · all repositories
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
MCP server for generating rough-draft project plans from natural-language prompts.
MCP server unifying ERPs, CRMs, APIs and knowledge base for Claude, ChatGPT and Gemini.
MCP server that lets your AI assistant build and deploy apps, hosting each one at a live URL.
Collaborative whiteboard MCP server — create objects, connectors, C4 diagrams, and manage boards
Related MCP Servers
- AlicenseBqualityCmaintenanceAn MCP server that generates beautiful Excalidraw architecture diagrams with perfect auto-layout, stateful editing, and architecture-aware component styling.26108 PyPI164MIT
- FlicenseNot gradedqualityCmaintenanceMCP server that lets Claude (and other MCP clients) create, list, read, update, and delete drawings in ExcaliDash via its REST API. It allows users to create diagrams directly from natural language commands like 'draw a flowchart'.-
- AlicenseAqualityBmaintenanceMCP server that creates, edits and exports architecture diagrams as .fluyo.json files, operating through tools like create_diagram, edit_diagram, and export_diagram directly from Claude.98MIT
- FlicenseAqualityBmaintenanceAn MCP server that generates standalone SVG architecture diagrams from text descriptions, running entirely on your machine with no dependencies or network access.8-