Mermaid Diagramming
Create professional software diagrams using Mermaid's text-based syntax.
Core Syntax Structure
All Mermaid diagrams follow this pattern:
diagramType
definition content
Key principles:
- First line declares diagram type (e.g.,
classDiagram, sequenceDiagram, flowchart)
- Use
%% for comments
- Whitespace aids readability; not required
- Typos break diagrams silently -- validate in Mermaid Live
Diagram Type Selection Guide
| Type |
When to use |
Reference |
| Class Diagram |
Domain modelling, OOP design, entity relationships |
references/class-diagrams.md |
| Sequence Diagram |
API flows, authentication, component interactions |
references/sequence-diagrams.md |
| Flowchart |
Processes, algorithms, decision trees, user journeys |
references/flowcharts-basic.md, references/flowcharts-advanced.md |
| ERD |
Database schemas, table relationships, data modelling |
references/erd-basic.md, references/erd-patterns.md |
| C4 Diagram |
Software architecture at Context, Container, Component levels |
references/c4-diagrams.md |
| State Diagram |
State machines, lifecycle states, workflow status |
references/other-diagrams.md |
| Git Graph |
Branching strategies, commit history |
references/other-diagrams.md |
| Gantt Chart |
Project timelines, scheduling, sprint planning |
references/other-diagrams.md |
| Pie/Quadrant |
Data distribution, prioritisation matrices |
references/other-diagrams.md |
Default to flowchart when the user's intent is unclear. Flowcharts cover the widest range of use cases.
Class Diagram
classDiagram
Title -- Genre
Title *-- Season
Title *-- Review
User --> Review : creates
class Title {
+string name
+int releaseYear
+play()
}
class Genre {
+string name
+getTopTitles()
}
Sequence Diagram
sequenceDiagram
participant User
participant API
participant Database
User->>API: POST /login
API->>Database: Query credentials
Database-->>API: Return user data
alt Valid credentials
API-->>User: 200 OK + JWT token
else Invalid credentials
API-->>User: 401 Unauthorized
end
Flowchart
flowchart TD
Start([User visits site]) --> Auth{Authenticated?}
Auth -->|No| Login[Show login page]
Auth -->|Yes| Dashboard[Show dashboard]
Login --> Creds[Enter credentials]
Creds --> Validate{Valid?}
Validate -->|Yes| Dashboard
Validate -->|No| Error[Show error]
Error --> Login
ERD
erDiagram
USER ||--o{ ORDER : places
ORDER ||--|{ LINE_ITEM : contains
PRODUCT ||--o{ LINE_ITEM : includes
USER {
int id PK
string email UK
string name
datetime created_at
}
ORDER {
int id PK
int user_id FK
decimal total
datetime created_at
}
State Diagram
stateDiagram-v2
[*] --> Draft
Draft --> Submitted : submit
Draft --> Cancelled : cancel
Submitted --> Processing : approve
Processing --> Shipped : ship
Shipped --> Delivered : confirm
Delivered --> [*]
Cancelled --> [*]
Detailed References
- references/class-diagrams.md - Domain modelling, relationships (association, composition, aggregation, inheritance), multiplicity, methods/properties
- references/sequence-diagrams.md - Actors, participants, messages (sync/async), activations, loops, alt/opt/par blocks, notes
- references/flowcharts-basic.md - Node shapes, connections, subgraphs
- references/flowcharts-advanced.md - Styling, comprehensive examples, patterns
- references/erd-basic.md - Entities, relationships, cardinality, attributes
- references/erd-patterns.md - Schema examples, design patterns
- references/c4-diagrams.md - System context, container, component diagrams, boundaries
- references/advanced-features.md - Configuration, layout, export options
- references/theming.md - Themes, colours, visual styling
- references/other-diagrams.md - State diagrams, git graphs, gantt charts, pie/quadrant
Best Practices
- Draft core entities first - Add 3-5 main nodes, then connect. Add attributes and detail in a second pass.
- Label every node and edge - Unlabelled arrows force readers to guess the relationship.
- Add
%% comments above complex sections - Explain why, not what. Future editors read comments before syntax.
- Split at 15 nodes - Diagrams with more than 15 nodes lose clarity. Break into focused views linked by a parent diagram.
- Store
.mmd files next to the code they describe - Keep diagrams and source in the same PR so they stay in sync.
- Set a title on every diagram - Use the
title keyword or a Markdown heading directly above the code block.
- Test in Mermaid Live before committing - Paste the diagram into mermaid.live to catch silent failures.
- Check colour contrast - Verify foreground/background pairs meet WCAG AA (4.5:1 ratio). Do not rely on colour alone to convey meaning.
Validation Loop (Required)
Every diagram passes through this generate-validate-repair cycle before output.
Step 1: Generate
Write the diagram using strict Mermaid syntax. Apply these rules during generation:
| Rule |
Wrong |
Correct |
Why |
| Escape parentheses in labels |
node[Node (example)] |
node["Node (example)"] |
Bare parentheses crash the parser |
| Quote text with special characters |
A[Price: $100] |
A["Price: $100"] |
$, %, &, <, > break parsing |
Quote the reserved word end |
A --> end |
A --> End["end"] |
Unquoted end silently breaks diagrams |
| Use HTML entities when quotes fail |
A["alert()"] |
A["alert()"] |
Nested parens inside quotes still fail |
Avoid {} in comments |
%% config: {dark} |
%% config dark theme |
Curly braces in comments break parsing |
| Use unique node IDs |
Reusing A across subgraphs |
A1, A2 for distinct nodes |
Duplicate IDs cause silent overwrites |
Step 2: Validate
Self-check the generated diagram against these failure patterns:
- Scan all node labels for unescaped special characters:
( ) { } $ % & < > #
- Check for bare
end used as a node name or label (not as a block closer)
- Verify arrow syntax matches the diagram type (e.g.,
--> for flowchart, ->> for sequence)
- Confirm diagram type keyword is spelled correctly on line 1
- Check participant/actor names for spaces (wrap in quotes if present)
If any issue is found, fix it before output. Do not ask the user to fix syntax.
Step 3: Render verification
After outputting the diagram, recommend the user verify rendering:
- Quick check: paste into Mermaid Live
- CLI validation:
npx @mermaid-js/mermaid-cli -i diagram.mmd -o test.png
- MCP tools: if a Mermaid MCP server is available, use it for in-session validation
Step 4: Repair (if rendering fails)
If the user reports a rendering failure:
- Read the error message (if available) and identify the failing line
- Check the syntax rules table above for the matching pattern
- Fix and re-output the corrected diagram
- Never output the same broken syntax twice
Configuration and Theming
Configure diagrams using frontmatter:
---
config:
theme: base
themeVariables:
primaryColor: "#ff6b6b"
---
flowchart LR
A --> B
Themes (default to default; use base for full colour control):
| Theme |
When to use |
default |
General-purpose diagrams (recommended) |
forest |
Green earth tones for environmental or organic topics |
dark |
Dark-mode pages or presentations |
neutral |
Grayscale professional documentation |
base |
Full colour customisation via themeVariables |
Layout: Default to dagre. Switch to elk when dagre produces crossed lines on 20+ node diagrams.
Look: Default to classic. Use handDrawn for informal docs or whiteboard-style presentations.
Exporting and Rendering
Platform support:
| Platform |
Status |
Notes |
| GitHub README/Issues |
Works |
Wiki rendering broken. C4 diagrams often fail. |
| GitLab |
Works |
May need cache refresh after adding new diagrams. |
| VS Code |
Works |
Requires Markdown Mermaid extension. |
| Obsidian |
Partial |
Desktop works. iOS fails entirely. Pie charts render as empty boxes. |
| Azure DevOps |
Works |
Requires ::: mermaid syntax, not backtick fences. |
| PDF export |
Fails |
Export as PNG/SVG from mermaid.live first. |
Export commands:
- Online: Mermaid Live Editor with PNG/SVG export
- CLI:
mmdc -i input.mmd -o output.png (install via npm install -g @mermaid-js/mermaid-cli)
- Docker:
docker run --rm -v $(pwd):/data minlag/mermaid-cli -i /data/input.mmd -o /data/output.png
Common Pitfalls
Syntax failures (most frequent):
- Unescaped special characters - Parentheses, brackets,
$, % in node labels crash the parser. Always quote labels containing these characters.
- Reserved word
end - Using end as a node name breaks diagrams silently. Wrap in quotes or rename.
- Misspelled diagram types -
classDiagram not classdiagram. Case matters for the type keyword.
- Wrong arrow syntax - Each diagram type uses different arrows. Flowcharts use
-->, sequence uses ->>, class uses ..>.
Platform-specific failures:
- GitHub Wiki - Mermaid rendering is broken despite documentation claiming support. Use README or Pages instead.
- Azure DevOps - Requires
::: mermaid syntax, not standard backtick fences.
- Obsidian iOS - Mermaid fails to render entirely on iOS. Desktop works.
- C4 diagrams on GitHub - C4 is experimental in Mermaid. Renders in mermaid.live but often fails on GitHub.
Structural issues:
- Overcomplexity - Split diagrams with more than 15 nodes into multiple focused views.
- Nested subgraphs - Deep nesting fails on some platforms. Keep to 2 levels maximum.
1---2name: mermaid-diagrams3description: Creates professional software diagrams using Mermaid's text-based syntax. Use when users request diagrams, visualizations, or documentation of software architecture including class diagrams, sequence diagrams, flowcharts, ERDs, C4 architecture diagrams, state machines, git graphs, or gantt charts. Triggers: 'diagram', 'visualize', 'model', 'map out', 'show the flow', database design, code structure.4license: MIT5---67# Mermaid Diagramming89Create professional software diagrams using Mermaid's text-based syntax.1011<instructions>1213## Core Syntax Structure1415All Mermaid diagrams follow this pattern:1617```mermaid18diagramType19 definition content20```2122**Key principles:**23- First line declares diagram type (e.g., `classDiagram`, `sequenceDiagram`, `flowchart`)24- Use `%%` for comments25- Whitespace aids readability; not required26- Typos break diagrams silently -- validate in Mermaid Live2728## Diagram Type Selection Guide2930| Type | When to use | Reference |31|------|-------------|-----------|32| Class Diagram | Domain modelling, OOP design, entity relationships | `references/class-diagrams.md` |33| Sequence Diagram | API flows, authentication, component interactions | `references/sequence-diagrams.md` |34| Flowchart | Processes, algorithms, decision trees, user journeys | `references/flowcharts-basic.md`, `references/flowcharts-advanced.md` |35| ERD | Database schemas, table relationships, data modelling | `references/erd-basic.md`, `references/erd-patterns.md` |36| C4 Diagram | Software architecture at Context, Container, Component levels | `references/c4-diagrams.md` |37| State Diagram | State machines, lifecycle states, workflow status | `references/other-diagrams.md` |38| Git Graph | Branching strategies, commit history | `references/other-diagrams.md` |39| Gantt Chart | Project timelines, scheduling, sprint planning | `references/other-diagrams.md` |40| Pie/Quadrant | Data distribution, prioritisation matrices | `references/other-diagrams.md` |4142Default to **flowchart** when the user's intent is unclear. Flowcharts cover the widest range of use cases.4344</instructions>4546<example name="Class Diagram (Domain Model)">4748### Class Diagram49```mermaid50classDiagram51 Title -- Genre52 Title *-- Season53 Title *-- Review54 User --> Review : creates5556 class Title {57 +string name58 +int releaseYear59 +play()60 }6162 class Genre {63 +string name64 +getTopTitles()65 }66```6768</example>6970<example name="Sequence Diagram (API Flow)">7172### Sequence Diagram73```mermaid74sequenceDiagram75 participant User76 participant API77 participant Database7879 User->>API: POST /login80 API->>Database: Query credentials81 Database-->>API: Return user data82 alt Valid credentials83 API-->>User: 200 OK + JWT token84 else Invalid credentials85 API-->>User: 401 Unauthorized86 end87```8889</example>9091<example name="Flowchart (User Journey)">9293### Flowchart94```mermaid95flowchart TD96 Start([User visits site]) --> Auth{Authenticated?}97 Auth -->|No| Login[Show login page]98 Auth -->|Yes| Dashboard[Show dashboard]99 Login --> Creds[Enter credentials]100 Creds --> Validate{Valid?}101 Validate -->|Yes| Dashboard102 Validate -->|No| Error[Show error]103 Error --> Login104```105106</example>107108<example name="ERD (Database Schema)">109110### ERD111```mermaid112erDiagram113 USER ||--o{ ORDER : places114 ORDER ||--|{ LINE_ITEM : contains115 PRODUCT ||--o{ LINE_ITEM : includes116117 USER {118 int id PK119 string email UK120 string name121 datetime created_at122 }123124 ORDER {125 int id PK126 int user_id FK127 decimal total128 datetime created_at129 }130```131132</example>133134<example name="State Diagram (Order Lifecycle)">135136### State Diagram137```mermaid138stateDiagram-v2139 [*] --> Draft140 Draft --> Submitted : submit141 Draft --> Cancelled : cancel142 Submitted --> Processing : approve143 Processing --> Shipped : ship144 Shipped --> Delivered : confirm145 Delivered --> [*]146 Cancelled --> [*]147```148149</example>150151<references>152153## Detailed References154155- **[references/class-diagrams.md](references/class-diagrams.md)** - Domain modelling, relationships (association, composition, aggregation, inheritance), multiplicity, methods/properties156- **[references/sequence-diagrams.md](references/sequence-diagrams.md)** - Actors, participants, messages (sync/async), activations, loops, alt/opt/par blocks, notes157- **[references/flowcharts-basic.md](references/flowcharts-basic.md)** - Node shapes, connections, subgraphs158- **[references/flowcharts-advanced.md](references/flowcharts-advanced.md)** - Styling, comprehensive examples, patterns159- **[references/erd-basic.md](references/erd-basic.md)** - Entities, relationships, cardinality, attributes160- **[references/erd-patterns.md](references/erd-patterns.md)** - Schema examples, design patterns161- **[references/c4-diagrams.md](references/c4-diagrams.md)** - System context, container, component diagrams, boundaries162- **[references/advanced-features.md](references/advanced-features.md)** - Configuration, layout, export options163- **[references/theming.md](references/theming.md)** - Themes, colours, visual styling164- **[references/other-diagrams.md](references/other-diagrams.md)** - State diagrams, git graphs, gantt charts, pie/quadrant165166</references>167168<best-practices>169170## Best Practices1711721. **Draft core entities first** - Add 3-5 main nodes, then connect. Add attributes and detail in a second pass.1732. **Label every node and edge** - Unlabelled arrows force readers to guess the relationship.1743. **Add `%%` comments above complex sections** - Explain why, not what. Future editors read comments before syntax.1754. **Split at 15 nodes** - Diagrams with more than 15 nodes lose clarity. Break into focused views linked by a parent diagram.1765. **Store `.mmd` files next to the code they describe** - Keep diagrams and source in the same PR so they stay in sync.1776. **Set a title on every diagram** - Use the `title` keyword or a Markdown heading directly above the code block.1787. **Test in Mermaid Live before committing** - Paste the diagram into [mermaid.live](https://mermaid.live) to catch silent failures.1798. **Check colour contrast** - Verify foreground/background pairs meet WCAG AA (4.5:1 ratio). Do not rely on colour alone to convey meaning.180181</best-practices>182183<validation>184185## Validation Loop (Required)186187Every diagram passes through this generate-validate-repair cycle before output.188189### Step 1: Generate190Write the diagram using strict Mermaid syntax. Apply these rules during generation:191192| Rule | Wrong | Correct | Why |193|------|-------|---------|-----|194| Escape parentheses in labels | `node[Node (example)]` | `node["Node (example)"]` | Bare parentheses crash the parser |195| Quote text with special characters | `A[Price: $100]` | `A["Price: $100"]` | `$`, `%`, `&`, `<`, `>` break parsing |196| Quote the reserved word `end` | `A --> end` | `A --> End["end"]` | Unquoted `end` silently breaks diagrams |197| Use HTML entities when quotes fail | `A["alert()"]` | `A["alert()"]` | Nested parens inside quotes still fail |198| Avoid `{}` in comments | `%% config: {dark}` | `%% config dark theme` | Curly braces in comments break parsing |199| Use unique node IDs | Reusing `A` across subgraphs | `A1`, `A2` for distinct nodes | Duplicate IDs cause silent overwrites |200201### Step 2: Validate202Self-check the generated diagram against these failure patterns:2032041. **Scan all node labels** for unescaped special characters: `( ) { } $ % & < > #`2052. **Check for bare `end`** used as a node name or label (not as a block closer)2063. **Verify arrow syntax** matches the diagram type (e.g., `-->` for flowchart, `->>` for sequence)2074. **Confirm diagram type keyword** is spelled correctly on line 12085. **Check participant/actor names** for spaces (wrap in quotes if present)209210If any issue is found, fix it before output. Do not ask the user to fix syntax.211212### Step 3: Render verification213After outputting the diagram, recommend the user verify rendering:214- **Quick check**: paste into [Mermaid Live](https://mermaid.live)215- **CLI validation**: `npx @mermaid-js/mermaid-cli -i diagram.mmd -o test.png`216- **MCP tools**: if a Mermaid MCP server is available, use it for in-session validation217218### Step 4: Repair (if rendering fails)219If the user reports a rendering failure:2201. Read the error message (if available) and identify the failing line2212. Check the syntax rules table above for the matching pattern2223. Fix and re-output the corrected diagram2234. Never output the same broken syntax twice224225</validation>226227<configuration>228229## Configuration and Theming230231Configure diagrams using frontmatter:232233```mermaid234---235config:236 theme: base237 themeVariables:238 primaryColor: "#ff6b6b"239---240flowchart LR241 A --> B242```243244**Themes (default to `default`; use `base` for full colour control):**245246| Theme | When to use |247|-------|-------------|248| `default` | General-purpose diagrams (recommended) |249| `forest` | Green earth tones for environmental or organic topics |250| `dark` | Dark-mode pages or presentations |251| `neutral` | Grayscale professional documentation |252| `base` | Full colour customisation via `themeVariables` |253254**Layout:** Default to `dagre`. Switch to `elk` when dagre produces crossed lines on 20+ node diagrams.255256**Look:** Default to `classic`. Use `handDrawn` for informal docs or whiteboard-style presentations.257258## Exporting and Rendering259260**Platform support:**261262| Platform | Status | Notes |263|----------|--------|-------|264| GitHub README/Issues | Works | Wiki rendering broken. C4 diagrams often fail. |265| GitLab | Works | May need cache refresh after adding new diagrams. |266| VS Code | Works | Requires Markdown Mermaid extension. |267| Obsidian | Partial | Desktop works. iOS fails entirely. Pie charts render as empty boxes. |268| Azure DevOps | Works | Requires `::: mermaid` syntax, not backtick fences. |269| PDF export | Fails | Export as PNG/SVG from mermaid.live first. |270271**Export commands:**272- **Online**: [Mermaid Live Editor](https://mermaid.live) with PNG/SVG export273- **CLI**: `mmdc -i input.mmd -o output.png` (install via `npm install -g @mermaid-js/mermaid-cli`)274- **Docker**: `docker run --rm -v $(pwd):/data minlag/mermaid-cli -i /data/input.mmd -o /data/output.png`275276</configuration>277278<pitfalls>279280## Common Pitfalls281282**Syntax failures (most frequent):**283- **Unescaped special characters** - Parentheses, brackets, `$`, `%` in node labels crash the parser. Always quote labels containing these characters.284- **Reserved word `end`** - Using `end` as a node name breaks diagrams silently. Wrap in quotes or rename.285- **Misspelled diagram types** - `classDiagram` not `classdiagram`. Case matters for the type keyword.286- **Wrong arrow syntax** - Each diagram type uses different arrows. Flowcharts use `-->`, sequence uses `->>`, class uses `..>`.287288**Platform-specific failures:**289- **GitHub Wiki** - Mermaid rendering is broken despite documentation claiming support. Use README or Pages instead.290- **Azure DevOps** - Requires `::: mermaid` syntax, not standard backtick fences.291- **Obsidian iOS** - Mermaid fails to render entirely on iOS. Desktop works.292- **C4 diagrams on GitHub** - C4 is experimental in Mermaid. Renders in mermaid.live but often fails on GitHub.293294**Structural issues:**295- **Overcomplexity** - Split diagrams with more than 15 nodes into multiple focused views.296- **Nested subgraphs** - Deep nesting fails on some platforms. Keep to 2 levels maximum.297298</pitfalls>