🚀 D2 MCP Server
A Model Context Protocol (MCP) server enabling D2 diagram generation and manipulation, empowering AI assistants to interact with D2 diagrams programmatically.
The D2 MCP Server is a powerful tool that provides seamless integration between AI assistants and D2, a modern diagram scripting language. It allows AI assistants such as Claude to create, render, export, and save D2 diagrams in a programmatic way. With enhanced descriptions and a rich set of tools, this server is designed to optimize AI assistant integration, enabling both simple diagram rendering and sophisticated incremental diagram building.
🚀 Quick Start
The D2 MCP Server offers a range of tools for creating, editing, and exporting D2 diagrams. To get started, you need to install the server and configure it according to your requirements. You can then use the provided tools to interact with the server and generate diagrams.
✨ Features
Basic Diagram Operations
- d2_create: Create new diagrams with optional initial content (unified approach).
- d2_export: Export diagrams to various formats (SVG, PNG, PDF).
- d2_save: Save existing diagrams to files.
Oracle API for Incremental Editing
- d2_oracle_create: Create shapes and connections incrementally.
- d2_oracle_set: Set attributes on existing elements.
- d2_oracle_delete: Delete specific elements from diagrams.
- d2_oracle_move: Move shapes between containers.
- d2_oracle_rename: Rename diagram elements.
- d2_oracle_get_info: Get information about shapes, connections, or containers.
- d2_oracle_serialize: Get the current D2 text representation of the diagram.
Additional Features
- 20 themes: Support for all D2 themes (18 light + 2 dark).
📦 Installation
From Source
git clone https://github.com/i2y/d2mcp.git
cd d2mcp
make build
make build-all
Using Go Install
go install github.com/i2y/d2mcp/cmd@latest
💻 Usage Examples
With Claude Desktop
Add the following configuration to your Claude Desktop configuration file:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
Windows: %APPDATA%\Claude\claude_desktop_config.json
Linux: ~/.config/Claude/claude_desktop_config.json
For STDIO transport (recommended for Claude Desktop):
{
"mcpServers": {
"d2mcp": {
"command": "/path/to/d2mcp",
"args": ["-transport=stdio"]
}
}
}
For SSE transport:
{
"mcpServers": {
"d2mcp": {
"command": "/path/to/d2mcp",
"args": ["-transport=sse", "-addr=:3000"]
}
}
}
Replace /path/to/d2mcp with the actual path to your built binary.
Standalone
./d2mcp -transport=stdio
./d2mcp
./d2mcp -transport=sse
./d2mcp -transport=streamable
Transport Options
STDIO Transport
./d2mcp -transport=stdio
SSE Transport (Server-Sent Events)
./d2mcp -transport=sse
./d2mcp -transport=sse \
-addr=:8080 \
-base-url=http://localhost:8080 \
-base-path=/mcp \
-keep-alive=30
SSE Configuration Options:
-addr: Address to listen on (default: ":3000")
-base-url: Base URL for SSE endpoints (auto-generated if not specified)
-base-path: Base path for SSE endpoints (default: "/mcp")
-keep-alive: Keep-alive interval in seconds (default: 30)
SSE Endpoints:
- SSE stream:
http://localhost:3000/mcp/sse
- Message endpoint:
http://localhost:3000/mcp/message
Streamable HTTP Transport
./d2mcp -transport=streamable
./d2mcp -transport=streamable \
-addr=:8080 \
-endpoint-path=/mcp \
-heartbeat-interval=30 \
-stateless
Streamable HTTP Configuration Options:
-addr: Address to listen on (default: ":3000")
-endpoint-path: Endpoint path for Streamable HTTP (default: "/mcp")
-heartbeat-interval: Heartbeat interval in seconds (default: 30)
-stateless: Enable stateless mode (default: false)
Streamable HTTP Endpoint:
- Endpoint:
http://localhost:3000/mcp
Tools
d2_create
Empty diagram (for Oracle API workflow):
{
"id": "my-diagram"
}
With initial D2 content:
{
"id": "my-diagram",
"content": "a -> b: Hello\nserver: {shape: cylinder}"
}
d2_export
{
"diagramId": "my-diagram",
"format": "png"
}
d2_save
{
"diagramId": "my-diagram",
"format": "pdf",
"path": "/path/to/output.pdf"
}
Oracle API Tools
d2_oracle_create
{
"diagram_id": "my-diagram",
"key": "server"
}
{
"diagram_id": "my-diagram",
"key": "server -> database"
}
d2_oracle_set
{
"diagram_id": "my-diagram",
"key": "server.shape",
"value": "cylinder"
}
{
"diagram_id": "my-diagram",
"key": "server.style.fill",
"value": "#f0f0f0"
}
d2_oracle_delete
{
"diagram_id": "my-diagram",
"key": "server"
}
d2_oracle_move
{
"diagram_id": "my-diagram",
"key": "server",
"new_parent": "network.internal",
"include_descendants": "true"
}
d2_oracle_rename
{
"diagram_id": "my-diagram",
"key": "server",
"new_name": "web_server"
}
d2_oracle_get_info
{
"diagram_id": "my-diagram",
"key": "server",
"info_type": "object"
}
d2_oracle_serialize
{
"diagram_id": "my-diagram"
}
Creating Sequence Diagrams
{
"id": "api-flow",
"content": "shape: sequence_diagram\n\nClient -> Server: HTTP Request\nServer -> Database: Query\nDatabase -> Server: Results\nServer -> Client: HTTP Response\n\n# Add styling\nClient -> Server.\"HTTP Request\": {style.stroke-dash: 3}\nDatabase -> Server.\"Results\": {style.stroke-dash: 3}"
}
Example with actors and grouping:
{
"id": "auth-flow",
"content": "shape: sequence_diagram\n\ntitle: Authentication Flow {near: top-center}\n\n# Define actors\nClient: {shape: person}\nAuth Server: {shape: cloud}\nDatabase: {shape: cylinder}\n\n# Interactions\nClient -> Auth Server: Login Request\nAuth Server -> Database: Validate Credentials\nDatabase -> Auth Server: User Data\n\ngroup: Success Case {\n Auth Server -> Client: Access Token\n Client -> Auth Server: API Request + Token\n Auth Server -> Client: API Response\n}\n\ngroup: Failure Case {\n Auth Server -> Client: 401 Unauthorized\n}"
}
Example Oracle API Workflow
Starting from scratch:
d2_create({ id: "architecture" })
d2_oracle_create({ diagram_id: "architecture", key: "web" })
d2_oracle_create({ diagram_id: "architecture", key: "api" })
d2_oracle_create({ diagram_id: "architecture", key: "db" })
d2_oracle_set({ diagram_id: "architecture", key: "db.shape", value: "cylinder" })
d2_oracle_set({ diagram_id: "architecture", key: "web.label", value: "Web Server" })
d2_oracle_create({ diagram_id: "architecture", key: "web -> api" })
d2_oracle_create({ diagram_id: "architecture", key: "api -> db" })
d2_export({ diagramId: "architecture", format: "svg" })
Starting with existing content (unified approach):
d2_create({
id: "architecture",
content: "web -> api -> db\ndb: {shape: cylinder}"
})
d2_oracle_set({ diagram_id: "architecture", key: "web.label", value: "Web Server" })
d2_oracle_create({ diagram_id: "architecture", key: "cache" })
d2_oracle_create({ diagram_id: "architecture", key: "api -> cache" })
d2_export({ diagramId: "architecture", format: "svg" })
When to Use Each Tool
- d2_create: Always use for new diagrams - both empty (for incremental building) and with initial D2 content.
- d2_oracle_*: Use for incremental modifications to any diagram created with d2_create.
- d2_export: Use to render the final diagram in your desired format.
📚 Documentation
Project Structure
d2mcp/
├── cmd/ # Application entry point
├── internal/
│ ├── domain/ # Business entities and interfaces
│ │ ├── entity/ # Domain entities
│ │ └── repository/ # Repository interfaces
│ ├── usecase/ # Business logic
│ ├── infrastructure/ # External implementations
│ │ ├── d2/ # D2 library integration
│ │ └── mcp/ # MCP server implementation
│ └── presentation/ # MCP handlers
│ └── handler/ # Tool handlers
└── pkg/ # Public packages
Development
Running tests
make test
go test -cover ./...
go test -v ./internal/presentation/handler
Code Quality
make fmt
make lint
make clean
Adding new features
- Define entities in
internal/domain/entity.
- Add repository interfaces in
internal/domain/repository.
- Implement business logic in
internal/usecase.
- Add infrastructure implementations.
- Create MCP handlers in
internal/presentation/handler.
- Wire dependencies in
cmd/main.go.
Project Structure
- cmd/: Application entry point
- internal/domain/: Core business logic and entities
- internal/infrastructure/: External service integrations
- internal/presentation/: MCP protocol handlers
- internal/usecase/: Application business logic
🔧 Technical Details
The D2 MCP Server is built using Go and integrates with the D2 library to provide diagram generation and manipulation capabilities. It uses the MCP protocol to communicate with AI assistants, allowing them to create, edit, and export D2 diagrams programmatically. The server provides a set of tools through the MCP protocol, which are designed to optimize AI assistant integration and enable both simple diagram rendering and sophisticated incremental diagram building.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
Troubleshooting
PNG/PDF Export Not Working
If you get errors when exporting to PNG or PDF formats, install one of these tools:
macOS:
brew install librsvg
brew install imagemagick
Ubuntu/Debian:
sudo apt-get install librsvg2-bin
sudo apt-get install imagemagick
Windows:
Download and install ImageMagick from the official website.
MCP Connection Issues
- Ensure the binary has execute permissions:
chmod +x d2mcp.
- Check Claude Desktop logs for error messages.
- Verify the path in your configuration is absolute.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Changelog
v0.5.0 (Latest)
- Added SSE (Server-Sent Events) transport support for network connectivity.
- Added Streamable HTTP transport support for modern bidirectional communication.
- New command-line flags for transport configuration.
- Support for stateful and stateless modes in Streamable HTTP.
- Maintained backward compatibility with stdio transport.
- Improved error handling and logging for different transport modes.
v0.4.0
- Simplified API to unified
d2_create for all diagram creation needs.
- Enhanced tool descriptions for better AI assistant integration.
- Improved Oracle API error handling and validation.
- Reduced API surface from 14 to 10 tools.
- Breaking Change: Removed d2_render, d2_render_to_file, d2_import, d2_from_text - use d2_create instead.
v0.3.0
- Added
d2_oracle_serialize tool to get current D2 text representation.
v0.2.0
- Added D2 Oracle API integration for incremental diagram manipulation.
- 6 new MCP tools for creating, modifying, and querying diagram elements.
- Support for stateful diagram editing sessions.
v0.1.0
- Initial release with basic D2 diagram operations.
- Support for rendering, creating, exporting, and saving diagrams.
- 20 built-in themes.
- MCP protocol integration.