Mermaid Diagrams skill for Claude Code

Diagrams as code that render on the first try. Claude picks the diagram type that answers the question, builds it from the real code or schema, and keeps each view under about twenty nodes. It avoids the parser traps that blank a diagram, like a lowercase end label or unquoted parentheses, themes with frontmatter config that survives dark mode, and renders with mmdc before handing it over, accounting for older Mermaid versions on GitHub.

  • namemermaid-diagrams
  • size219 lines · ≈1,850 tokens
  • files2
  • licenseMIT
  • updated

What Claude sees before loading it

This description is the only part of the skill that sits in context all the time. Claude reads it to decide when to load the full playbook below.

description: Writes Mermaid diagrams that render the first time and stay readable — choosing the right diagram type (flowchart, sequence, ER, state, class, gantt, timeline, mindmap), syntax that avoids parser traps, layout control with direction, subgraphs, and ELK, theming via frontmatter config, and rendering to SVG/PNG/PDF with mermaid-cli. Use when the user asks for a diagram, flowchart, sequence diagram, ERD, state machine, or gantt chart in Markdown, GitHub, GitLab, Notion, or docs sites, or when a Mermaid block fails to render.

Try asking

  • Draw a sequence diagram of our checkout flow from these route handlers
  • Make an ER diagram of the tables in our Prisma schema
  • This Mermaid block won't render on GitHub — fix it

Use it when

  • Docs, READMEs, or PRs need a flowchart, sequence, ER, or state diagram
  • A Mermaid block fails to render or looks cluttered
  • Diagrams must be exported as SVG, PNG, or PDF
  • A gantt chart or timeline should live in Markdown

Skip it when

  • You need formal C4 context and container views — use c4-diagrams instead
  • The task is a data chart with real numbers — use data-visualization instead

How to check the result

mmdc renders the file to SVG without errors, every node maps to something real in the code or schema, and the output stays readable in both light and dark themes.

The common mistake it prevents

Using syntax newer than the target platform's pinned Mermaid version, so the diagram works in the live editor but shows an error box on GitHub.

~/.claude/skills/mermaid-diagrams/SKILL.md

--- name: mermaid-diagrams description: Writes Mermaid diagrams that render the first time and stay readable — choosing the right diagram type (flowchart, sequence, ER, state,… license: MIT ---

Done well means: the diagram type matches the question being answered, it renders without errors in the target (GitHub, docs site, mmdc), it fits on one screen with at most ~15–20 nodes per view, labels are short and specific, and you actually rendered it once to catch syntax errors rather than trusting it by eye.

Pick the type

QuestionDiagramHeader
What steps/decisions happen?Flowchartflowchart TD / flowchart LR
Who calls whom, in what order?SequencesequenceDiagram
What tables exist and how do they relate?Entity relationshiperDiagram
What states can an object be in?StatestateDiagram-v2
What classes/types and relationships?ClassclassDiagram
When does work happen?Ganttgantt
What happened when?Timelinetimeline
How do ideas branch?Mindmapmindmap
System context/containersFlowchart with subgraphs, or C4 (see c4-diagrams)

More types (gitGraph, quadrantChart, xychart-beta, sankey-beta, block-beta, architecture-beta, kanban, pie) and full syntax per type are in references/syntax.md; read it when you need a type not covered below or an unusual feature.

Workflow

- [ ] 1. State the question the diagram answers and the audience
- [ ] 2. Pick the type; list nodes/participants from the real system (code, schema, spec)
- [ ] 3. Draft at most ~15–20 nodes; split into several diagrams if larger
- [ ] 4. Render with mmdc (or the target's preview) and fix errors
- [ ] 5. Check readability: direction, crossing edges, label length, contrast in dark mode

Flowchart

flowchart LR
  user([User]) --> web[Web app]
  web -->|REST, JWT| api[API service]
  api --> db[(Postgres)]
  api -.->|async| q[[Job queue]]
  q --> worker[Worker]
  worker --> s3[(S3 bucket)]
  subgraph vpc [Private VPC]
    api
    db
    q
    worker
  end
  classDef store fill:#eef,stroke:#557
  class db,s3 store

Shapes: [rect], (rounded), ([stadium]), [(cylinder)], {decision}, [[subroutine]], ((circle)), >flag]. Newer Mermaid (v11.3+) also accepts id@{ shape: cyl, label: "Postgres" } for an expanded shape set — use it only if the target renderer is current (GitHub and docs sites can lag).

Edges: -->, ---, -.-> (dotted), ==> (thick), --o, --x, labels with -->|label| or -- label -->. Chain: a --> b & c --> d.

Flowchart traps:

  • The word end in lowercase as a node label breaks parsing; write End or ["end"].
  • A node ID starting with o or x right after -- is read as an edge type (A---oB); add a space or rename.
  • Quote labels with special characters: A["Price (USD) / unit"]. Use #quot; for a literal double quote inside a quoted label; <br> for line breaks.
  • Define each node’s label once; later references use the bare ID.
  • subgraph IDs must not collide with node IDs. Set direction inside with direction TB.
  • Too many crossings: switch TD↔LR, reorder node declarations (Mermaid lays out in declaration order), or split the diagram.

Sequence diagram

sequenceDiagram
  autonumber
  actor U as User
  participant W as Web
  participant A as API
  participant S as Stripe
  U->>W: Click "Pay"
  W->>+A: POST /checkout
  A->>+S: Create PaymentIntent
  S-->>-A: client_secret
  A-->>-W: 200 {client_secret}
  alt card requires 3DS
    W->>U: Show challenge
  else success
    W->>U: Show receipt
  end
  Note over A,S: Webhook confirms payment asynchronously

Arrows: ->> sync request, -->> response, -) async, -x failure. +/- on arrows activate/deactivate lifelines. Blocks: alt/else, opt, loop, par/and, critical, break, rect rgb(...) for highlighting — each closed with end. Keep message labels under ~40 characters; put payload details in notes.

ER diagram

erDiagram
  CUSTOMER ||--o{ ORDER : places
  ORDER ||--|{ ORDER_ITEM : contains
  PRODUCT ||--o{ ORDER_ITEM : "appears in"
  CUSTOMER {
    uuid id PK
    string email UK
    timestamptz created_at
  }
  ORDER {
    uuid id PK
    uuid customer_id FK
    numeric total
  }

Cardinality: || exactly one, o| zero or one, }| one or more, }o zero or more. -- identifying (solid), .. non-identifying (dashed). Generate from the real schema (migrations, \d output, Prisma schema) rather than from memory; show only the tables relevant to the question.

State diagram

stateDiagram-v2
  [*] --> Draft
  Draft --> Submitted: submit()
  Submitted --> Approved: approve()
  Submitted --> Rejected: reject(reason)
  Rejected --> Draft: edit()
  Approved --> [*]
  state Submitted {
    [*] --> AwaitingReview
    AwaitingReview --> InReview: assign()
  }

Every non-terminal state should have an exit; label transitions with the event or method that causes them.

Gantt

gantt
  title Launch plan
  dateFormat YYYY-MM-DD
  excludes weekends
  section Build
    API endpoints      :done,   api, 2026-03-02, 8d
    Web UI             :active, ui,  after api, 10d
  section Release
    Beta               :        beta, after ui, 5d
    GA                 :milestone, ga, after beta, 0d

Theming and config

Use frontmatter config (the %%{init: ...}%% directive still works but is deprecated):

---
title: Order flow
config:
  theme: neutral
  flowchart:
    curve: basis
---
flowchart LR
  a --> b
  • Themes: default, neutral (best for print and docs), dark, forest, base (the only one that honors themeVariables fully).
  • GitHub picks light/dark automatically; hard-coded fill colors can become unreadable in dark mode. Prefer classDef with both a fill and a contrasting color, or no fills.
  • ELK layout (config: layout: elk) helps large flowcharts but needs a renderer with the ELK package; GitHub may not support it. Test in the target.

Rendering

npx -p @mermaid-js/mermaid-cli mmdc -i diagram.mmd -o diagram.svg
npx -p @mermaid-js/mermaid-cli mmdc -i diagram.mmd -o diagram.png -s 2 -b transparent
npx -p @mermaid-js/mermaid-cli mmdc -i diagram.mmd -o diagram.pdf -f      # -f fits PDF to the diagram
npx -p @mermaid-js/mermaid-cli mmdc -i README.md -o README.out.md          # renders every mermaid block to SVG files

mmdc uses headless Chromium via Puppeteer; in CI/containers, pass a Puppeteer config (-p puppeteer.json with {"args": ["--no-sandbox"]}) only inside an isolated container. The live editor (mermaid.live) is fine for quick checks of non-sensitive diagrams; do not paste confidential architecture into third-party sites without the user’s agreement.

Gotchas

  • Renderers differ in Mermaid version. GitHub, GitLab, Notion, Obsidian, and docs plugins each pin their own; new syntax may fail there even if mermaid.live renders it.
  • A single syntax error blanks the whole diagram; error messages give the line — render after every major edit.
  • Long labels make giant boxes; abbreviate and explain in surrounding text.
  • Comments are %% at line start; // and # are not comments.
  • Indentation is cosmetic in most types but significant in mindmap.

Verification

  • mmdc renders without errors to SVG (or the target’s preview shows it).
  • Diagram answers the stated question; every node and edge corresponds to something real in the code, schema, or spec.
  • View the rendered output in both light and dark themes if it will live on GitHub.

Bundled files

Loaded only when a step in the skill needs them. Review them here before installing.

references/syntax.md 163 lines · 3.2 KB
# Mermaid syntax reference (types beyond the core five)

Read when you need a diagram type or feature not covered in SKILL.md. Types marked
`-beta` are newer and may not render on platforms with older Mermaid versions.

## Class diagram

```mermaid
classDiagram
  class Order {
    +UUID id
    +Money total
    +addItem(Product p, int qty) void
    -recalculate() void
  }
  class OrderItem
  Order "1" *-- "1..*" OrderItem : contains
  OrderItem --> Product
  PaymentMethod <|-- Card
  PaymentMethod <|.. Wallet
  <<interface>> PaymentMethod
```

Relations: `<|--` inheritance, `*--` composition, `o--` aggregation, `-->` association,
`..>` dependency, `..|>` realization. Visibility: `+` public, `-` private, `#` protected,
`~` package. Generics: `List~Order~`.

## Timeline

```mermaid
timeline
  title Platform history
  2023 : v1 monolith
  2024 : Split billing service : Moved to Postgres 16
  2025 : Multi-region
```

## Mindmap (indentation matters)

```mermaid
mindmap
  root((Checkout))
    Payments
      Cards
      Wallets
    Fraud
      Rules
      Model
```

## Git graph

```mermaid
gitGraph
  commit
  branch feature
  checkout feature
  commit
  checkout main
  merge feature
  commit tag: "v1.2.0"
```

## Pie

```mermaid
pie showData
  title Traffic by channel
  "Organic" : 52
  "Paid" : 28
  "Referral" : 20
```

Prefer a bar chart for more than 4–5 slices or close values.

## Quadrant chart

```mermaid
quadrantChart
  title Effort vs impact
  x-axis Low effort --> High effort
  y-axis Low impact --> High impact
  quadrant-1 Plan
  quadrant-2 Do now
  quadrant-3 Skip
  quadrant-4 Delegate
  SSO: [0.7, 0.8]
  Dark mode: [0.3, 0.4]
```

## XY chart (beta)

```mermaid
xychart-beta
  title "Monthly signups"
  x-axis [Jan, Feb, Mar, Apr]
  y-axis "Signups" 0 --> 1200
  bar [420, 610, 780, 1010]
  line [420, 610, 780, 1010]
```

## Sankey (beta)

CSV-like lines `source,target,value`:

```mermaid
sankey-beta
Visitors,Signups,1200
Visitors,Bounced,8800
Signups,Paid,180
```

## Block diagram (beta)

```mermaid
block-beta
  columns 3
  client["Client"] space api["API"]
  client --> api
  db[("DB")]:3
  api --> db
```

## Architecture (beta)

```mermaid
architecture-beta
  group cloud(cloud)[Cloud]
  service api(server)[API] in cloud
  service db(database)[Database] in cloud
  service store(disk)[Storage] in cloud
  api:R --> L:db
  api:B --> T:store
```

Built-in icons: `cloud`, `database`, `disk`, `internet`, `server`. Edge sides: `T`, `B`,
`L`, `R`.

## Kanban

```mermaid
kanban
  todo[To do]
    t1[Write migration]
  doing[In progress]
    t2[Review PR 482]
  done[Done]
    t3[Ship v1.2]
```

## Flowchart extras

- Click handlers / links (only where the renderer allows): `click api "https://example.com/api" "Open docs"`.
- Markdown strings in labels: ``A["`**Bold** and _italic_`"]``.
- Edge IDs and animation (v11+): `a e1@--> b` then `e1@{ animate: true }`.
- Link styling by index: `linkStyle 0 stroke:#d33,stroke-width:2px`.
- Comments: `%% this is a comment`.

## Sequence extras

- `box Aqua Backend ... end` groups participants.
- `create participant X` / `destroy X` show lifecycle (v10.3+).
- `links A: {"Dashboard": "https://..."}` adds participant menus (renderer dependent).

About this skill

Written and maintained by the Claude Skills editors to the same editorial standard as every skill in the directory: a selective trigger, a real workflow, known pitfalls and a verification step. First published , last updated . MIT licensed.

esc