Mermaid Flow Repair
by Riper21
README.md
[English](README.md) | [Русский](README_RU.md)
# Mermaid Guard
Mermaid Guard is a deterministic, line-based heuristic linter, guardrail, and conservative repair tool for Mermaid diagrams. It is useful in CI/CD, pre-commit checks, AI agent workflows, and development that needs instant local validation.
It is not a complete Mermaid grammar parser, a renderer, or a promise that every accepted diagram will render in every Mermaid release. The tool reports the scope of its checks and leaves uncertain input unchanged.
## Capabilities
The heuristic scope currently covers:
- `flowchart` and `graph` headers, including basic quote and delimiter balance checks and `subgraph` blocks;
- `sequenceDiagram` headers, including nested `alt`, `opt`, `loop`, `critical`, `par`, `rect`, `box`, and `break` blocks;
- basic recognition of `stateDiagram` and `classDiagram` headers;
- Markdown files containing one or more `mermaid` fenced blocks;
- UTF-8 input, UTF-8 BOM, and CRLF or LF line endings.
Other Mermaid diagram families are reported as unsupported or unknown rather than being silently treated as flowcharts. The linter does not attempt full grammar validation, participant inference, or renderer compatibility checks.
Repair is non-destructive:
- a missing header is added only when an explicit expected type and strong diagram-like syntax make that inference reasonably safe;
- unclosed sequence blocks and simple flowchart delimiters may be completed;
- `autonumber` is not a mandatory repair and is never inserted just because it is absent;
- prose, unsupported types, orphan blocks, ambiguous delimiters, and a type mismatch retain the original source and produce a failed repair result;
- no generic skeleton is substituted for user input.
## Requirements
- Python 3.9 or newer;
- the core package has no mandatory runtime dependencies.
## Installation
```text
python -m pip install .
```
Install the development tools without optional model integrations:
```text
python -m pip install ".[dev]"
```
Install only the integration needed for the selected provider:
```text
python -m pip install ".[ai]"
python -m pip install ".[openai]"
python -m pip install ".[ollama]"
python -m pip install ".[env]"
```
`ai` installs the OpenAI-compatible LangChain integration used by the `openai`, `deepseek`, and `custom` providers. `ollama` installs the separate Ollama integration. Core linting, repair, Markdown handling, and offline synthesis do not import those extras.
## Command-line usage
The installed command is `mermaid-repair`. The module form `python -m mermaid_repair.cli` is also supported.
```text
mermaid-repair --version
mermaid-repair lint diagram.mmd
mermaid-repair lint document.md --json
mermaid-repair repair diagram.mmd --output fixed.mmd
mermaid-repair repair diagram.mmd --output fixed.mmd --force
mermaid-repair generate "Collect an order, validate payment, and send a receipt" --type flowchart
```
`lint` accepts regular `.mmd` and `.mermaid` files or Markdown files. For Markdown, every `mermaid` fenced block is checked and diagnostics use the original file line and column. A file without a Mermaid block is an error; prose is not accepted as a diagram. File inputs default to a 1 MiB byte limit; use `--max-bytes` to choose a different positive limit.
`repair` preserves Markdown prose and non-Mermaid fenced blocks. It only changes Mermaid block contents. Existing output paths are not overwritten without `--force`; output is written through a temporary file and an atomic replace. An input and output path that resolve to the same file is rejected unless `--force` is explicit.
Exit status values are stable for CI use:
- `0`: requested operation completed without heuristic errors;
- `1`: lint or repair found residual errors, or repair was intentionally not applied;
- `2`: invalid arguments, input/output error, or unsafe path;
- `3`: an explicitly requested LLM path used deterministic fallback.
A provider or model option without `--llm` is an error. A missing optional integration, credential, or LLM service is not reported as a successful LLM generation.
## Python API
The original string API remains available:
```python
from mermaid_repair import MermaidLinter
valid, messages = MermaidLinter.validate_mermaid(
"sequenceDiagram\n actor User\n participant API\n"
)
```
For diagnostics that retain codes, severity, and source positions, use the structured API:
```python
from mermaid_repair import MermaidLinter
report = MermaidLinter.validate_mermaid_report(
"sequenceDiagram\n actor User\n alt Login\n",
filename="login.mmd",
)
for diagnostic in report.diagnostics:
print(diagnostic.severity, diagnostic.code, diagnostic.line, diagnostic.column)
```
A repair result makes the outcome explicit:
```python
from mermaid_repair import MermaidLinter
result = MermaidLinter.repair_mermaid(
"sequenceDiagram\n actor User\n alt Login\n",
expected_type="sequence",
filename="login.mmd",
)
if not result.success:
print(result.text)
print(result.warnings)
else:
print(result.text)
print(result.changes)
```
`MermaidLinter.sanitize_and_repair(code)` is retained for callers that need a string. It returns the original text when a safe repair cannot be made. Use `repair_mermaid` or `repair_document` when the caller needs to inspect success, diagnostics, changes, and warnings.
For a Markdown string:
```python
from mermaid_repair import MermaidLinter
result = MermaidLinter.repair_document(
markdown_text,
file_format="markdown",
)
if result.success:
updated_markdown = result.text
```
## Offline synthesis
Without an LLM, the synthesizer extracts deterministic steps from `process_description` and uses them as labels or messages. It does not contact a network service:
```python
from mermaid_repair.synthesizer import generate_flowchart
diagram = generate_flowchart(
"Receive a support ticket. Assign an agent. Send a confirmation email."
)
```
The generated text is passed through the same heuristic repair checks. This is a deterministic transformation; it does not establish semantic completeness or correctness of the description.
## Optional LLM providers
The factory creates LangChain-compatible clients only when their optional integration and credentials are available:
```python
from mermaid_repair.llm import get_llm
llm = get_llm(
provider="deepseek",
model="deepseek-chat",
api_key="explicit-key",
timeout=30,
max_tokens=800,
max_retries=1,
)
```
Provider credentials are isolated: `openai` uses `OPENAI_API_KEY`, `deepseek` uses `DEEPSEEK_API_KEY`, and `custom` uses `CUSTOM_API_KEY`. An OpenAI key is never used as a fallback for DeepSeek or a custom endpoint. Unknown providers raise `ValueError`. Automatic provider selection uses available environment variables in a fixed order, so production callers should normally specify the provider explicitly.
Environment files are not loaded at import time. Loading is explicit:
```python
llm = get_llm(
provider="openai",
load_env=True,
env_file=".env",
)
```
The `env` extra is required for that form. The equivalent CLI form is `mermaid-repair generate ... --llm --load-env --env-file .env`.
An LLM request sends the supplied process description and title to the selected provider or endpoint. Do not put secrets, personal data, or confidential source code in a description unless that transmission is intended and approved. The tool does not log API keys. Provider availability, retention, and privacy policies remain the responsibility of the selected service.
## External Verification & Status Semantics
While the core linter operates entirely in-process using fast Python heuristics, an optional authoritative verification adapter is available:
```python
from mermaid_repair.verifier import MermaidCliVerifier
verifier = MermaidCliVerifier()
result = verifier.verify("flowchart TD\nA-->B")
print(result.status) # 'verified' (if mmdc installed) or 'unverified'
```
If `mermaid-cli` (`mmdc`) is not installed, the tool gracefully reports `status = "unverified"` instead of falsely claiming renderability. See [ARCHITECTURE.md](file:///./ARCHITECTURE.md) for details.
## Model Context Protocol (MCP)
Mermaid Flow Repair provides native tools for AI Agents and MCP runners:
- `validate_mermaid`: In-process linting with exact line and column diagnostics.
- `repair_mermaid`: Conservative, non-destructive syntax repair.
- `validate_markdown`: Multi-block documentation linting.
- `verify_external_mermaid`: Authoritative rendering check via `mmdc`.
Run as an MCP tool provider:
```bash
python -m mermaid_repair.mcp.server
```
## Development
```text
python -m pip install ".[dev]"
ruff check src tests examples
mypy
python -m pytest -p no:cacheprovider
python -m pytest -p no:cacheprovider --cov=mermaid_repair --cov-report=term-missing
```
Run tests with `PYTHONDONTWRITEBYTECODE=1` when the working tree must remain free of Python cache files. The CI workflow tests the core package in a clean environment and does not require an LLM key.
## License
MIT. See `LICENSE`.
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo issues