Mermaid

From rp1-run/rp1 · View interactive version

Mermaid is an AI agent skill from the GitHub repository rp1-run/rp1. Create, validate, and repair Mermaid.js diagrams. Use when generating flowcharts, sequence, class, ER, state, or Gantt diagrams, or any visualization.

How to use this skill

Skill file

Mermaid Diagrams Skill

Create valid, well-formed Mermaid.js diagrams with automatic validation and error repair guidance.

Requirement: rp1 CLI v0.3.0 or later (includes agent-tools mmd-validate command)

What This Skill Does

When to Use

Activate this skill when:

Trigger phrases: "create a diagram", "draw a flowchart", "visualize this process", "sequence diagram for", "ER diagram", "class diagram", "fix this mermaid", "validate diagram"

Validation Workflow

CRITICAL: Every diagram MUST be validated before being considered complete.

Step 1: Create the Diagram

  1. Consult reference.md for syntax
  2. Choose the appropriate diagram type
  3. Follow proper syntax conventions:

Step 2: Validate Using CLI Tool

# Validate markdown file (all embedded diagrams)
rp1 agent-tools mmd-validate path/to/document.md

# Validate standalone mermaid file
rp1 agent-tools mmd-validate path/to/diagram.mmd

# Validate from stdin (for inline diagrams)
echo 'flowchart TD
    A --> B' | rp1 agent-tools mmd-validate

Step 3: Handle Validation Results

The CLI tool outputs structured JSON in a ToolResult envelope:

Success (all diagrams valid):

{
  "success": true,
  "tool": "mmd-validate",
  "data": {
    "diagrams": [
      { "index": 0, "valid": true, "diagramType": "flowchart", "startLine": 5 }
    ],
    "summary": { "total": 1, "valid": 1, "invalid": 0 }
  }
}

Failure (contains invalid diagrams):

{
  "success": false,
  "tool": "mmd-validate",
  "data": {
    "diagrams": [
      {
        "index": 0,
        "valid": false,
        "diagramType": "stateDiagram-v2",
        "startLine": 10,
        "errors": [{
          "diagramIndex": 0,
          "message": "Parse error on line 2: Expecting '-->', got 'MINUS'",
          "line": 2,
          "context": "[*] -> State1"
        }]
      }
    ],
    "summary": { "total": 1, "valid": 0, "invalid": 1 }
  },
  "errors": [{
    "message": "Parse error on line 2: Expecting '-->', got 'MINUS'",
    "line": 2,
    "context": "[*] -> State1"
  }]
}

Parsing the Response:

Step 4: Iterative Repair

  1. Parse the error message to detect category (see Error Categories below)
  2. Apply targeted fix based on category
  3. Re-validate using the CLI tool
  4. Repeat until valid (max 3 attempts)
  5. If unfixable after 3 attempts, report to user

Error Categories

Detect error categories by pattern matching the message field in validation errors. See EXAMPLES.md for detailed examples of each category.

| Category | Detection Patterns | Quick Fix |

|----------|-------------------|-----------|

| ARROW_SYNTAX | got 'MINUS', got 'GT', expecting.*LINK | Replace -> with --> in state/flowchart |

| QUOTE_ERROR | unterminated string, got 'STR', lexical error.*string | Wrap label in double quotes |

| CARDINALITY | cardinality, relationship, erDiagram | Use valid notation: \|\|--o{ |

| LINE_BREAK | expecting.*(NEWLINE\|NL\|EOF) | Each statement on its own line |

| ESCAPED_NEWLINE | \n found in node label text | Replace \n with <br> or remove |

| DIAGRAM_TYPE | unknown diagram type, UnknownDiagramError | Correct spelling, add declaration |

| NODE_SYNTAX | got 'PS', got 'PE', got 'SQS', got 'SQE', unclosed | Match all opening and closing brackets |

Error Category Detection

Parse the message field from validation errors to detect category:

ARROW_SYNTAX:  message contains "got 'MINUS'" or "got 'GT'" or "expecting.*LINK"
QUOTE_ERROR:   message contains "unterminated string" or "got 'STR'" or "lexical error.*string"
CARDINALITY:   message contains "cardinality" or "relationship"
LINE_BREAK:    message contains "expecting.*NEWLINE" or "expecting.*NL" or "expecting.*EOF"
ESCAPED_NEWLINE: source contains literal \n inside node labels (pre-validation check, not from error message)
DIAGRAM_TYPE:  message contains "unknown diagram type" or "UnknownDiagramError"
NODE_SYNTAX:   message contains "got 'PS'" or "got 'SQS'" or "unclosed"
UNKNOWN:       default (no pattern matched)

Fix Strategies Summary

ARROW_SYNTAX: Check diagram type and use correct arrows:

QUOTE_ERROR: Quote labels containing:

CARDINALITY: Use proper ER notation:

LINE_BREAK: Separate statements:

sequenceDiagram
    Alice->>Bob: Hello
    Bob->>Alice: Hi

ESCAPED_NEWLINE: Replace \n with <br> or rewrite as single-line:

DIAGRAM_TYPE: Valid types:

flowchart, graph, sequenceDiagram, classDiagram, stateDiagram, stateDiagram-v2, erDiagram, gantt, pie, journey, gitGraph, mindmap, timeline, quadrantChart, xychart-beta, block-beta, sankey-beta, kanban, radar-beta

NODE_SYNTAX: Balance all brackets:

Integration with Fixer Agent

For bulk diagram repair across markdown files, use the mermaid-fixer agent via the /fix-mermaid command:

# Fix all diagrams in a markdown file
/fix-mermaid path/to/document.md

# Fix a single diagram from stdin
/fix-mermaid -

The fixer agent:

  1. Runs rp1 agent-tools mmd-validate on the file
  2. Parses JSON response to build task list of invalid diagrams
  3. For each invalid diagram:
  1. Re-validates after fixes (up to 3 iterations)
  2. Inserts placeholders for unfixable diagrams
  3. Reports summary of actions taken

JSON Response Parsing for Fixer:

1. Run: rp1 agent-tools mmd-validate /path/to/file.md
2. Parse JSON output
3. If success == true AND data.summary.invalid == 0:
   -> All diagrams valid, done
4. If success == false:
   -> For each diagram in data.diagrams where valid == false:
      -> Extract errors[].message, errors[].line, errors[].context
      -> Detect error category from message patterns
      -> Apply category-specific fix
5. Re-validate and repeat (max 3 iterations)

Placeholder format for unfixable diagrams:

<!-- MERMAID FIX NEEDED: {diagram_type}
Error: {error_message}
Line: {line_number}
Attempts: 3

Original diagram could not be auto-repaired.
Please fix manually and remove this comment block.
-->

Styling Rules

NEVER use hardcoded colors in style, classDef, or inline directives. Diagrams are rendered with a coordinated light/dark theme in the rp1 web UI. Hardcoded fills bypass the theme's text color, producing unreadable text (e.g., light text on a bright fill in dark mode).

Let the theme handle styling. Default nodes, edges, and labels already have correct contrast in both themes. Do not add fill:#, color:#, stroke:#, classDef, or style directives to diagrams.

If you must visually distinguish nodes, use mermaid's built-in class system with ::: syntax — never raw hex colors:

flowchart TD
    A[Default node]
    B[Secondary node]:::secondary
    C[Tertiary node]:::tertiary

The secondary and tertiary classes are handled by the theme and render correctly in both light and dark modes. This is sufficient for most visual grouping needs.

Node Label Rules

NEVER use \n in node labels. Mermaid does not interpret \n as a line break — it renders the literal characters \n in the output. Use <br> for line breaks within labels, or keep labels concise and single-line.

%% WRONG — renders literal \n
flowchart TD
    A["First line\nSecond line"]

%% CORRECT — use <br> for line breaks
flowchart TD
    A["First line<br>Second line"]

%% BEST — keep labels short and single-line
flowchart TD
    A["First line"]

Prefer short, single-line labels (3-5 words max). If a label needs multiple lines, use <br> sparingly. Long labels make diagrams hard to read — consider splitting into separate nodes instead.

Keep subgraph labels short (1-3 words). Mermaid renders subgraph labels at the top edge of the container. Long labels overlap with child nodes inside the subgraph. Use brief titles and put detail in the child nodes instead.

%% WRONG — long subgraph label overlaps with children
flowchart TD
    subgraph Install ["Install to all platforms (claude, opencode, codex)"]
        A["Claude Code"]
        B["OpenCode"]
    end

%% CORRECT — short label, detail in children
flowchart TD
    subgraph Install ["Install"]
        A["Claude Code"]
        B["OpenCode"]
    end

Best Practices

Creating Diagrams

  1. Reference documentation first: Check reference.md for syntax
  2. Start with diagram type: Every diagram must start with type declaration
  3. Quote special characters: Always quote labels with spaces, colons, parentheses
  4. Use consistent arrow styles: Don't mix arrow types within a diagram
  5. Build incrementally: For complex diagrams, validate after each addition
  6. No hardcoded colors: See Styling Rules above — let the theme handle all colors
  7. No \n in labels: Use <br> for line breaks, or keep labels single-line

Validation

  1. Always validate before presenting: Never show unvalidated diagrams to users
  2. Use the CLI tool: rp1 agent-tools mmd-validate provides structured JSON output
  3. Parse JSON for programmatic repair: Extract errors from data.diagrams[].errors[]
  4. Check error category first: Guides targeted fixes

Troubleshooting

  1. Start minimal: If complex diagram fails, reduce to minimal example
  2. Validate incrementally: Add complexity one step at a time
  3. Reference EXAMPLES.md: Find similar error patterns
  4. Check diagram type requirements: Different types have different syntax

Tool Not Available?

If rp1 agent-tools mmd-validate returns "command not found":

Mermaid validation requires rp1 v0.3.0 or later.

Please update rp1 using your package manager:
  macOS:   brew upgrade rp1
  Windows: scoop update rp1

Or visit https://rp1.run for installation instructions.

Output Format

When presenting diagrams to users:

## Diagram Title

Brief description of what the diagram represents.

\`\`\`mermaid
flowchart TD
    A[Start] --> B[Process]
    B --> C[End]
\`\`\`

**Validation Status**: Validated successfully

Supported Diagram Types

| Type | Use Case | Declaration |

|------|----------|-------------|

| Flowchart | Process flows, decision trees | flowchart TD/LR/RL/BT |

| Sequence | API interactions, message flows | sequenceDiagram |

| Class | Object relationships, architecture | classDiagram |

| ER | Database schemas, data models | erDiagram |

| State | State machines, workflow states | stateDiagram-v2 |

| Gantt | Project timelines, schedules | gantt |

| Git Graph | Branch strategies, commit history | gitGraph |

| Pie | Proportional data | pie |

| Journey | User experience flows | journey |

| Mindmap | Hierarchical concepts | mindmap |

| Timeline | Chronological events | timeline |

| Quadrant | 2D categorization | quadrantChart |

| XY Chart | Bar/line charts | xychart-beta |

| Block | Grid layouts | block-beta |

| Sankey | Flow quantities | sankey-beta |

| Kanban | Task boards | kanban |

| Radar | Multi-axis comparison | radar-beta |

Quick Reference

Validation Commands

# Validate markdown file (all embedded diagrams)
rp1 agent-tools mmd-validate document.md

# Validate standalone mermaid file
rp1 agent-tools mmd-validate diagram.mmd

# Validate from stdin
echo 'flowchart TD; A-->B' | rp1 agent-tools mmd-validate

Common Patterns

Simple flowchart:

flowchart TD
    A[Start] --> B{Decision}
    B -->|Yes| C[Action]
    B -->|No| D[End]

Sequence diagram:

sequenceDiagram
    Client->>Server: Request
    Server-->>Client: Response

ER diagram:

erDiagram
    CUSTOMER ||--o{ ORDER : places
    ORDER ||--|{ LINE_ITEM : contains

Resources

Success Criteria

A diagram is complete when:

  1. Syntax is correct for the diagram type
  2. Validation passes with rp1 agent-tools mmd-validate
  3. Diagram accurately represents the requested information
  4. Labels are clear and properly quoted
  5. Comments document complex sections (if needed)
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.