How to Use Mermaid Diagrams in Claude Code Skills to Compress Context
Mermaid diagrams convey complex processes in hundreds of tokens instead of thousands. Learn how to use them in skill.md files for better AI performance.

The Context Window Problem Every Claude Developer Faces
Describing a complex conditional workflow in plain English is expensive. A five-step code review process with branching logic might cost 700 tokens. An error handling tree with multiple recovery paths? Closer to 1,500. And thatâs before you include any actual code, conversation history, or retrieved documentation.
Context windows arenât unlimitedâand in Claude Code, every token spent explaining process logic is a token unavailable for actual work. Mermaid diagrams offer a practical fix. Claude understands Mermaid syntax natively, and a well-constructed diagram can carry the same semantic load as several paragraphs of prose at roughly 3â6x better token efficiency.
This guide covers how to embed Mermaid diagrams into Claude Code skill files for meaningful context compressionâwithout sacrificing the precision that makes skills effective for prompt engineering and workflow automation.
What Claude Code Skills Actually Are
Claude Code is Anthropicâs terminal-based AI coding agent. It operates by reading contextâproject files, conversation history, and custom instruction filesâto perform agentic tasks with genuine autonomy.
The CLAUDE.md File
The primary configuration mechanism is a CLAUDE.md file at your project root. Claude reads this automatically at startup and uses it for project-specific conventions, tooling rules, and persistent instructions. You can also place CLAUDE.md files in subdirectories; Claude reads them recursively, with parent directories loading first.
Custom Slash Commands as Skills
Claude Code supports custom slash commands, stored as markdown files in .claude/commands/. Each file defines a reusable skillâa named behavior Claude invokes when you type the command. A file named code-review.md becomes /code-review. These files can accept arguments via $ARGUMENTS, reference other files, and contain complex logic.
A simple skill file looks like this:
# Code Review
Review the provided code for correctness, security, and performance.
## Process
1. Check for obvious bugs and logic errors
2. Assess error handling coverage
3. Look for security vulnerabilities
4. Evaluate test coverage
## Output
Return a numbered list of issues. Each issue must include severity (high/medium/low) and a suggested fix.
This works fine for simple processes. But as soon as the logic branchesââif the file has tests, check coverage; if not, flag it; if itâs a security-critical path, escalate to high severityââprose becomes unwieldy and token-heavy. Thatâs where Mermaid earns its place.
Why Mermaid Is Effective at Compressing Context
Mermaid is a text-based diagramming language embedded in markdown code blocks. It uses simple declarative syntax to define flowcharts, sequence diagrams, state machines, and more. Most markdown renderers display these as visual diagrams, but Claude reads the raw syntax directly and extracts semantic meaning from it.
Claude Understands Mermaid at a Semantic Level
This is the core reason the technique works. Claude was trained on vast quantities of GitHub repositories, technical documentation, and markdown-heavy contentâmuch of which includes Mermaid diagrams. It doesnât just recognize the syntax; it understands what the diagrams mean.
When Claude reads A --> B{Is it a bug?} -->|Yes| C -->|No| D, it comprehends the conditional structure. No additional explanation needed.
The Token Comparison
Consider this workflow description in prose:
âWhen a pull request is received, first check whether it includes tests. If it doesnât, request tests from the author and stop. If it does have tests, check whether they pass. If tests fail, block the merge. If tests pass, review the logic. If there are breaking changes, verify the changelog is updated before approving. If there are no breaking changes, approve directly.â
Thatâs roughly 80 wordsâapproximately 110 tokens. It covers the main path reasonably, but itâs easy to miss edge cases and misread dependencies between steps.
The equivalent Mermaid flowchart:
flowchart TD
A[Receive PR] --> B{Has tests?}
B -->|No| C[Request tests]
B -->|Yes| D{Tests pass?}
D -->|No| E[Block merge]
D -->|Yes| F[Review logic]
F --> G{Breaking changes?}
G -->|Yes| H{Changelog updated?}
G -->|No| I[Approve]
H -->|Yes| I
H -->|No| J[Request changelog update]
This uses approximately 140 tokensâslightly more than the proseâbut itâs structurally complete. Every path is explicit. Every condition is named. No ambiguity about whether changelog checking happens before or after logic review.
For a 15-step process with multiple branches, the gap widens significantly. Prose that takes 2,000 tokens to describe might require only 400â500 tokens as Mermaid. Thatâs a meaningful amount of recovered context budget.
The Five Mermaid Diagram Types Most Useful in Skill Files
Not every Mermaid diagram type is equally useful for defining skill behavior. These five cover most real-world scenarios.
Flowcharts for Decision Logic
Flowcharts are the workhorse. Use them whenever your skill has conditional branches, multiple decision gates, or any non-linear process.
Syntax basics:
- Rectangles for steps:
A[Step label] - Diamonds for decisions:
B{Decision?} - Arrows with condition labels:
-->|Yes|and-->|No|
âșBuild a purchase approval app for 2,000 store managers
One prompt. Role-based access, audit trail and SSO come built in.
These compose cleanly into any complexity you need, and Claude interprets them reliably.
Sequence Diagrams for Multi-Actor Interactions
When a skill involves coordination between multiple systemsâa user, an API, a database, an external serviceâsequence diagrams capture the interaction order precisely.
sequenceDiagram
participant Dev
participant Claude
participant TestSuite
Dev->>Claude: Request refactor
Claude->>Claude: Analyze dependencies
Claude->>TestSuite: Run affected tests
TestSuite-->>Claude: Pass/fail results
Claude-->>Dev: Show refactored code + test results
This is particularly valuable for skills that orchestrate tool calls or external integrations. The sequence diagram makes the interaction order unambiguous in a way that prose rarely achieves.
State Diagrams for Error Handling Workflows
State diagrams work well when a skill needs to manage status transitionsâespecially retry logic, failure recovery, or multi-stage processes.
stateDiagram-v2
[*] --> Idle
Idle --> Processing: request_received
Processing --> Validating: parsed_ok
Processing --> Error: parse_failed
Validating --> Complete: valid
Validating --> Error: invalid
Error --> Retrying: attempts < 3
Error --> Failed: attempts >= 3
Retrying --> Processing
Complete --> [*]
Failed --> [*]
For skills that involve API calls or file operations where failures are expected, this communicates error handling far more clearly than prose typically does.
Class Diagrams for Data Structure Context
When your skill creates, transforms, or validates data objects, a class diagram conveys the expected structure without lengthy prose descriptions.
classDiagram
class ReviewResult {
+string file_path
+string[] issues
+string severity
+string suggested_fix
+bool blocking
}
class ReviewReport {
+ReviewResult[] results
+int total_issues
+bool approve
+string summary()
}
ReviewReport "1" --> "*" ReviewResult
This replaces a paragraph or two describing the output object with about 80 tokens of precise, unambiguous information.
ER Diagrams for Schema-Aware Tasks
For skills that involve database operations, schema-aware code generation, or data migrations, ER diagrams compress schema context efficiently.
erDiagram
USERS ||--o{ ORDERS : places
ORDERS ||--|{ ORDER_ITEMS : contains
PRODUCTS }|--|{ ORDER_ITEMS : appears_in
USERS {
int id
string email
datetime created_at
}
ORDERS {
int id
int user_id
string status
decimal total
}
Including this in a skill file for a database query task gives Claude precise schema context at a fraction of the token cost of an equivalent SQL dump.
Building a Mermaid-Enhanced Skill File: Step by Step
Step 1: Map the Process Before Writing Any Syntax
Sketch the logic first. Answer these questions before touching a keyboard:
- What triggers this skill?
- What decisions does Claude need to make, and what are the possible outcomes?
- Are there error states or retry paths?
- What does the output look like?
Get the logic clear before encoding it. Vague diagrams produce vague behavior.
Step 2: Pick the Right Diagram Type
| Process type | Best diagram |
|---|---|
| Conditional branches, decision gates | Flowchart |
| Multi-system interactions, API calls | Sequence diagram |
| State transitions, retry/error handling | State diagram |
| Output data structure | Class diagram |
| Database schema context | ER diagram |
Step 3: Keep Node Labels Short
Long labels inside diagram nodes increase token count without improving Claudeâs comprehension. Write Validate headers, not Check whether the CSV file headers match the expected schema. If a node needs more context, add a brief prose note below the diagram blockâdonât cram it inside the diagram itself.
Step 4: Structure the Skill File Clearly
A clean skill file layout:
# [Skill Name]
## Purpose
One sentence: what this skill does and when to invoke it.
## Process
[Mermaid diagram]
## Rules
- Critical constraints (3â7 bullets maximum)
- Non-obvious behavior the diagram can't capture
## Output Format
Brief description or example of expected output structure.
The diagram owns the process logic. Prose is reserved for nuance, constraints, and formatting requirements that a diagram genuinely canât express.
Step 5: Test With Real Tasks
Run the skill on a few real examples. Check:
- Does Claude follow all branches correctly?
- Are any decision points handled inconsistently?
- Does the output match the expected format?
If Claude misses a branch, check the diagram for missing arrows or ambiguous condition labels. If Claude ignores certain rules, those rules may need to be in the diagram rather than listed as prose bullets.
When Diagrams Help vs. When Prose Is Better
Mermaid isnât the right tool for everything.
Use Mermaid when:
- The logic branches conditionally
- Step order is non-obvious or critical
- Multiple actors or systems are involved
- Youâre defining error handling or retry behavior
- A data structure has relationships to communicate
Stick to prose when:
- Youâre explaining why a rule exists (motivation, context)
- The instruction is a policy rather than a process (âAlways be conservative with delete operationsâ)
- The logic is simple enough that a diagram would add visual noise without adding clarity
- You need to convey tone, emphasis, or intent
The best skill files combine both: diagram for process, prose for constraints.
Common Mistakes to Avoid
Making Diagrams Too Complex
A 35-node flowchart is harder to parse than two 15-node flowcharts. If a diagram grows unwieldy, split it into sub-processes. Claude can handle multiple diagrams in a single skill file without issue.
Syntax Errors
Mermaid syntax is fairly forgiving, but malformed diagrams can cause Claude to misread the structure. Common issues include:
- Using
:or()inside node labels without quoting them - Missing arrows between connected nodes
- Unclosed brackets in label text
Test diagrams in the Mermaid Live Editor before embedding them in skill files. It validates syntax and shows exactly what Claude encounters in the raw markdown.
Duplicating Information
If the diagram covers the process, the prose section shouldnât re-explain it. Pick one medium per piece of information and trust it. Duplication wastes tokens and creates inconsistency risks.
Hand-Waving Edge Cases
One of Mermaidâs less obvious benefits is that diagrams force you to make edge cases explicit. Every branch has to go somewhere. If you canât draw the error path, you probably havenât thought it through. That pressure is usefulâit makes your gaps visible before Claude encounters them in production.
Frequently Asked Questions
Does Claude actually understand Mermaid semantically, or just as raw text?
âș Build a credit limit review app for 800 relationship managers
Live URL today. Role-based access, audit trail and SSO come built in.
Claude understands Mermaid semantically. It was trained on large quantities of GitHub repositories and technical documentation that include Mermaid diagrams, so it learned the relationship between syntax patterns and their structural meaning. When Claude reads a flowchart block, it processes the conditional flowâit doesnât just see arrows and labels as disconnected characters.
Whatâs the realistic token savings from using Mermaid instead of prose?
It depends on complexity, but in practice, a Mermaid diagram representing a 10â15 step workflow with conditional branches uses roughly 150â350 tokens. The equivalent prose description typically runs 800â1,500 tokens. For complex processes, the improvement is roughly 3â6x. Over a full skill file with multiple processes described, that adds up to substantial recovered context budget.
Can I use Mermaid in CLAUDE.md files, not just slash command files?
Yes. Mermaid works in any markdown context Claude readsâCLAUDE.md files, custom slash command files in .claude/commands/, and any other markdown-based instruction file in the project. The approach is identical regardless of which file type youâre using.
What if Claude misinterprets a diagram?
Start by checking the diagram for ambiguityâmissing arrows, decision labels that could be read multiple ways, or branches that donât fully specify outcomes. A common fix is to add a single clarifying prose line directly below the diagram block (not replacing the diagram, just addressing the specific ambiguous point). Avoid re-describing the whole process in proseâthat defeats the purpose.
Does using Mermaid affect Claudeâs output quality beyond just saving tokens?
Often yes. Diagrams are structurally unambiguous in a way prose rarely is, so Claude tends to follow process steps more reliably and handle edge cases more consistently. The explicit structure functions like a checklist Claude can verify against as it worksâitâs harder to skip a branch when itâs drawn on the diagram.
Are there Mermaid diagram types that Claude interprets less reliably?
Gantt charts and Gitgraph diagrams appear less frequently in typical training data than flowcharts, sequence diagrams, and state diagrams, so Claudeâs interpretation is less reliable for those types. For skill files, stick to the five types covered in this articleâtheyâre the ones Claude handles most accurately and consistently.
Key Takeaways
- Mermaid diagrams reduce token usage by 3â6x for complex conditional workflows compared to equivalent proseâoften the difference between a skill file that fits comfortably in context and one that doesnât.
- Claude reads Mermaid semantically, not just as raw characters. Diagrams are interpreted with the same fidelity as well-written natural language instructions, but far more efficiently.
- Flowcharts handle most skill definitions. Use sequence diagrams for multi-system coordination, state diagrams for error handling and retry logic, and class or ER diagrams for data structure context.
- The best skill files combine both formats: let diagrams own process logic, and use prose for constraints, intent, and output formatting requirements the diagram canât express.
- Test diagrams in the Mermaid Live Editor before embedding themâsyntax errors caught early save debugging time in the middle of a live task.
- If youâre ready to move from skill files to full agent workflows, MindStudio brings the same structured-logic principle to a visual builder where the diagram is the agent.



