A Model Context Protocol (MCP) server that provides D2 diagram generation and manipulation capabilities.
D2 is a modern diagram scripting language that turns text to diagrams. This MCP server allows AI assistants like Claude to create, render, export, and save D2 diagrams programmatically.
The server provides 16 MCP tools for complete-source authoring, validation, rendering, embedded D2 guidance, and incremental Oracle editing.
Create, edit, validate, render, and export D2 diagrams with confined workspace access.
2026-11-09
ดาว
—
เครื่องมือ
—
อัปไทม์
—
With the new Oracle API integration, AI assistants can now build and modify diagrams incrementally, making it perfect for:
Converting conversations into architecture diagrams
Building flowcharts step-by-step as requirements are discussed
Creating entity relationship diagrams from database schemas
Generating system diagrams from code analysis
Refining diagrams based on user feedback without starting over
Features
Source-First Diagram Operations
d2_create - Create diagrams from complete D2 source or start empty
d2_get_source - Retrieve the canonical source, including Oracle edits
d2_update_source - Validate then atomically replace complete source
d2_format - Format valid source without storing it
d2_validate - Validate raw or stored source and suggest conservative repairs
# Clone the repository
git clone https://github.com/recursivefunctions/d2mcp.git
cd d2mcp
# Build the binary
make build
# Or build for all platforms
make build-all
Using Go Install
go install github.com/recursivefunctions/d2mcp/cmd@latest
Using Docker
docker run --rm -i \
--mount type=bind,src="$PWD",dst=/workspace \
ghcr.io/recursivefunctions/d2mcp:0.5.0
The image defaults to STDIO transport and confines local imports, assets, and exports to the mounted /workspace directory. The container runs as a non-root user, so the mounted directory must be writable by that user when saving exports.
MCP Registry
Release tags publish the server as io.github.RecursiveFunctions/d2mcp in the official MCP Registry. Registry publication and editor-gallery indexing are separate, so a newly published version might not appear immediately in an editor's search results.
Compatible clients can also use the portable .mcp.json configuration in this repository. It requires Docker and mounts the current workspace at /workspace.
Editor Integrations
Client configurations are generated from server.json, so they always use the same immutable container version.
Client
Installation
VS Code
Use the installation URL, Official MCP Registry, or companion extension
VSCodium and Positron
Install the RecursiveFunctions.d2mcp companion extension from Open VSX
Replace /path/to/d2mcp with the actual path to your built binary.
Standalone
# Run the MCP server (stdio transport)
./d2mcp -transport=stdio
# Run with SSE transport (default)
./d2mcp
# or explicitly
./d2mcp -transport=sse
# Run with Streamable HTTP transport
./d2mcp -transport=streamable
Transport Options
d2mcp now supports multiple transport protocols:
STDIO Transport
The traditional stdio transport for direct process communication:
./d2mcp -transport=stdio
SSE Transport (Server-Sent Events)
HTTP-based transport that allows network connectivity:
-workspace-root is repeatable. Local path traversal and symlink escapes are rejected. Remote assets require HTTPS and are subject to DNS/IP, redirect, timeout, MIME, and response-size checks; loopback and private-network destinations are rejected.
Tools
d2_create
Create a new diagram with optional initial content (unified approach):
Empty diagram (for Oracle API workflow):
{
"id": "my-diagram"
}
With initial D2 content and a named workspace for imports/assets:
Formats are svg, png, pdf, pptx, gif, and ascii (txt is an alias). Layouts are dagre, elk, and tala. Typed options cover engine spacing, themes and overrides, bundled fonts, padding, scale, sketch mode, animation, board selection, and resource limits.
PDF, PPTX, GIF, and optionally animated SVG compose bounded descendant boards. PNG and ASCII produce one board; use boardPath to select one from a composition.
d2_save
Save a diagram inside a configured workspace root:
If path is omitted, output is written below d2mcp_output/ in the selected root.
d2_validate
Validate raw D2 source or the current source of a stored diagram. Supply exactly one input:
{
"content": "a: {\n b"
}
{
"diagram_id": "my-diagram"
}
Invalid D2 returns a successful structured result with valid: false and compiler diagnostics. Simple, unambiguous terminator errors may also include repaired_content; validation never modifies a stored diagram.
d2_get_source and d2_update_source
Complete D2 source is canonical, so every bundled v0.9 language feature can be authored without waiting for a specialized structured tool.
Updates compile first and replace atomically. Invalid drafts return structured diagnostics and leave stored source unchanged.
d2_format
{"content": "api:{db}"}
Returns formatted source without creating or changing a diagram.
d2_help and d2_capabilities
{"query": "sequence diagrams", "limit": 5}
d2_help searches the embedded v0.9.0 reference or returns an exact topic by ID. d2_capabilities lists its categories and MCP resource URIs. Embedded resources cover the core language, connections, reusable definitions, visuals, rich text, structured/sequence/grid diagrams, composition, layouts, and exports.
Oracle API Tools
The Oracle API tools enable incremental diagram manipulation without regenerating the entire diagram. These tools are ideal for building diagrams step-by-step or making surgical edits.
d2_oracle_create
Create a new shape or connection:
{
"diagram_id": "my-diagram",
"key": "server" // Creates a shape
}
{
"diagram_id": "my-diagram",
"key": "server" // Deletes the server and its children
}
d2_oracle_move
Move elements between containers:
{
"diagram_id": "my-diagram",
"key": "server",
"new_parent": "network.internal", // Moves server into network.internal
"include_descendants": "true" // Also moves child elements
}
Starting with existing content (unified approach):
// 1. Create diagram with initial content
d2_create({
id: "architecture",
content: "web -> api -> db\ndb: {shape: cylinder}"
})
// 2. Enhance incrementally using Oracle API
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" })
// 3. Export final result
d2_export({ diagramId: "architecture", format: "svg" })
When to Use Each Tool
d2_create: Create a stored source document, optionally bound to a named workspace root
d2_update_source: Author or replace any complete D2 v0.9 document atomically
d2_oracle_*: Make convenient structured edits; each mutation is revalidated before commit
d2_get_source: Retrieve the canonical source after either editing workflow
d2_help / d2_capabilities: Discover supported syntax, composition, layouts, and exports
d2_export / d2_save: Render in memory or save within an allowed workspace root
Development
Running tests
# Run all tests
make test
# Run with coverage
go test -cover ./...
# Run specific test
go test -v ./internal/presentation/handler
Code Quality
# Format code
make fmt
# Run linter
make lint
# Clean build artifacts
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
Troubleshooting
Export Limit Errors
PNG, PDF, PPTX, and GIF exports are produced by D2's bundled Go raster pipeline. If a diagram exceeds a resource ceiling, reduce its scale or board count, select a specific boardPath, or set an allowed bounded maxWidth, maxHeight, maxPixels, maxFrames, or maxOutputBytes value.
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