Skip to main content
Glama

d2-mcp-server

An MCP (Model Context Protocol) server for the D2 diagram language. Lets LLMs render, validate, and format D2 diagrams without requiring the d2 binary — rendering is powered by the @terrastruct/d2 WASM package.

Tools

Tool

Description

Requires d2 binary?

d2_render

Compile and render D2 source to SVG

No

d2_inspect

Parse D2 and return a structured text summary of shapes/connections (fast preview, no rendering)

No

d2_validate

Check D2 syntax and return errors

No

d2_format

Canonically format D2 source code

Yes

d2_list_themes

List all available themes with IDs

No

d2_list_layouts

List available layout engines

No

Related MCP server: mcp-mermaid-validator

Install the D2 Skill

The repo ships a d2 agent skill that teaches LLMs how to write effective D2 diagrams (syntax, styling, patterns, when to use which layout engine, and how to save output).

Install it via skills.sh:

npx skills add itsjool/d2-mcp

This drops skills/d2/SKILL.md into your agent's skills directory so it's automatically available in any session.


Requirements

  • Node.js 18+

  • d2 binary only required for d2_format — install from d2lang.com or set D2_PATH env var

Install

npm install
npm run build

Usage with Claude Code

Via npx (no install required):

{
  "mcpServers": {
    "d2": {
      "command": "npx",
      "args": ["-y", "github:itsjool/d2-mcp"]
    }
  }
}

Via local build:

{
  "mcpServers": {
    "d2": {
      "command": "node",
      "args": ["/path/to/d2-mcp/dist/index.js"]
    }
  }
}

Then start Claude Code with:

claude --mcp-config /path/to/mcp.json

Development

npm run dev     # watch mode with tsx
npm run build   # compile TypeScript to dist/
npm start       # run compiled server

Notes

  • ELK layout is significantly slower than dagre in WASM; prefer dagre unless you specifically need ancestor-to-descendant connections or container sizing

License

MIT

Available Tools

6 tools
d2_formatFormat D2 CodeA
Read-onlyIdempotent

Format D2 diagram source code using the d2 binary formatter.

Normalizes whitespace, indentation, and syntax to D2's canonical style. The formatted output is semantically equivalent to the input.

NOTE: This tool requires the d2 binary to be installed (unlike d2_render and d2_validate which use WASM). Install from https://d2lang.com or set D2_PATH env var.

Args:

  • d2_code (string): D2 source code to format

Returns: Formatted D2 source code string.

Examples:

  • Clean up: format "a->b:label" to "a -> b: label"

  • Normalize after editing: run on any hand-written D2 code

Error Handling:

  • Returns error if d2 binary is not found (d2_render still works without it)

  • Returns error if code has syntax errors (format requires valid syntax)

Inputs: d2_code (required).

d2_inspectInspect D2 Diagram StructureA
Read-onlyIdempotent

Parse and summarize the structure of D2 source code without rendering.

Returns a human-readable text summary of all shapes, containers, connections, and boards (layers/steps/scenarios) in the diagram. Uses the compile step only — no rendering occurs, so this is fast (~100ms) regardless of diagram complexity.

Use this INSTEAD of d2_render(ascii=true) for structural previews. The ASCII renderer has known bugs with cross-container connections and reverse edges. This tool produces reliable output for all diagram types.

Args:

  • d2_code (string): D2 source code to inspect

Returns: Structured text summary, e.g.: Shapes (4): - cp [rectangle] "Control Plane" - cp.listener [rectangle] "API Gateway" - cp.grpc [rectangle] "gRPC Server" - agent [rectangle] "Data Plane Agent"

Connections (2):
  cp.grpc -> agent.stream : "mirror request"
  agent.stream -> cp.grpc : "response"

Works correctly for all diagram types:

  • Architecture diagrams with nested containers and cross-container connections

  • Sequence diagrams (filters out internal lifeline-end nodes)

  • ER diagrams (sql_table shapes, FK connections shown at table level)

  • UML class diagrams

  • Layered/stepped/scenario diagrams (each board summarized)

  • State machines, flowcharts, grid dashboards

Error handling:

  • Returns compile errors if D2 code is invalid (same as d2_validate)

Inputs: d2_code (required).

d2_list_layoutsList D2 Layout EnginesA
Read-onlyIdempotent

List available D2 layout engines with descriptions and feature support.

Use layout names with d2_render's layout parameter. No d2 binary required — layout list is built-in.

Args: (none)

Returns: JSON object: { "layouts": [{ "name": string, "description": string, "features": string[] // Supported features }] }

Layout guidance:

  • dagre: Default. Fast, good for most flowcharts and architecture diagrams.

  • elk: Better for complex graphs, supports ancestor-to-descendant connections, width/height on containers. Slower than dagre.

Inputs: no named parameters.

d2_list_themesList D2 ThemesA
Read-onlyIdempotent

List all available D2 diagram themes with their IDs and names.

Use theme IDs with d2_render's theme_id parameter. No d2 binary required — theme list is built-in.

Args: (none)

Returns: JSON object: { "light": [{ "id": number, "name": string }], "dark": [{ "id": number, "name": string }] }

Notable themes:

  • 0: Neutral Default (clean, professional — good default)

  • 3: Flagship Terrastruct (vibrant, colorful)

  • 8: Colorblind Clear (accessible palette)

  • 200: Dark Mauve (dark mode)

  • 300: Terminal (monospace, dot-fill containers, uppercase labels)

  • 302: Origami (paper-like aesthetic)

  • 303: C4 (C4 architecture diagram style)

Inputs: no named parameters.

d2_renderRender D2 DiagramA
Read-onlyIdempotent

Render D2 diagram source code to SVG or ASCII art using the D2 WASM engine.

D2 is a diagram scripting language. This tool compiles and renders D2 code without requiring the d2 binary — it uses the @terrastruct/d2 WASM package directly.

Args:

  • d2_code (string): D2 source code to render

  • theme_id (number): Theme ID (default: 0). See d2_list_themes for options. Key themes: 0=Neutral Default, 3=Flagship Terrastruct, 300=Terminal, 200=Dark Mauve

  • dark_theme_id (number): Dark mode theme ID (optional)

  • layout ('dagre' | 'elk'): Layout engine (default: 'dagre'). WARNING: elk is extremely slow in WASM — do NOT use unless explicitly requested. Dagre handles all diagram types well.

  • sketch (boolean): Hand-drawn style (default: false)

  • pad (number): Padding pixels (default: 100)

  • center (boolean): Center in viewbox (default: false)

  • scale (number): Scale factor, e.g. 0.5 halves size. Default fits SVG to screen. Set 1 to disable.

  • animate_interval (number): Animate multi-board diagrams (layers/scenarios/steps) at this ms interval. Requires target to be set. E.g. animate_interval=1000, target='*'

  • target (string): Which board to render. '*' = all boards (needs animate_interval > 0). 'layers.x' = specific layer. Default = root board only.

  • ascii (boolean): Output ASCII art instead of SVG (default: false)

  • ascii_mode ('standard' | 'extended'): ASCII char set. 'extended' uses Unicode (default).

  • no_xml_tag (boolean): Omit declaration for direct HTML embedding (default: false)

  • skip_fonts (boolean): Strip embedded font data from SVG (DEFAULT: true). Only set false if user explicitly requests embedded fonts.

Returns: SVG markup string (or ASCII art if ascii=true). SVG output starts with (unless no_xml_tag=true)

Examples:

  • Simple: d2_code="a -> b: connects"

  • Architecture: d2_code="server -> db: query\nserver -> cache: read"

  • Styled: d2_code="x: { style.fill: '#4a90d9' }\nx -> y", theme_id=3

  • ASCII preview: d2_code="a -> b -> c", ascii=true

  • Animated steps: d2_code="steps: { s1: {a} s2: {a -> b} }", animate_interval=1000, target="*"

  • With embedded fonts: skip_fonts=false (only when user explicitly requests it)

  • HTML embed: no_xml_tag=true

Error Handling:

  • Returns error with syntax details if D2 code is invalid

  • Use d2_validate first to check syntax before rendering

Inputs: d2_code (required), pad, ascii, scale, +11 more.

d2_validateValidate D2 CodeA
Read-onlyIdempotent

Validate D2 diagram source code for syntax and semantic errors using the WASM engine.

Uses compile step to detect all errors without rendering. No d2 binary required.

Args:

  • d2_code (string): D2 source code to validate

Returns: JSON object: { "valid": boolean, // Whether the code is syntactically and semantically valid "error": string // Error message if invalid (omitted if valid) }

Examples:

  • Check before rendering: validate first, then d2_render only if valid=true

  • Debug syntax: get specific line/column error info

Error Handling:

  • Returns { valid: false, error: "..." } with specific error details

  • Never throws — always returns a structured result

Inputs: d2_code (required).

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.7/5.0

    Scored across 6 tools

    Disambiguation5/5

    Each tool targets a distinct stage of the D2 workflow: validate, inspect, format, render, list themes, and list layouts. Even though d2_validate and d2_inspect both compile, their return types and purposes are clearly separated, and the descriptions explicitly guide users to d2_inspect over render-ascii for structural previews.

    Naming Consistency5/5

    All tools share the d2_ prefix and use clear imperative verbs, with lookup tools following a consistent list_X pattern. The naming is predictable and makes it easy to infer what each tool does without reading the full description.

    Tool Count5/5

    Six tools is a well-scoped set for a D2 diagram server: rendering, validation, inspection, formatting, theme listing, and layout listing each serve a distinct need. No tool feels redundant, and nothing essential appears missing for the server's purpose.

    Completeness5/5

    The tool set covers the full authoring workflow: validate before rendering, inspect structure without rendering, format source code, and render with configurable themes and layouts. It also exposes theme and layout catalogs so agents can discover valid parameters, leaving no obvious dead ends.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers