iflow-mcp_andrewginns-mermaid-mcp-server 11.4.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
__init__.py ADDED
File without changes
@@ -0,0 +1,216 @@
1
+ Metadata-Version: 2.4
2
+ Name: iflow-mcp_andrewginns-mermaid-mcp-server
3
+ Version: 11.4.2
4
+ Summary: MCP server for validating Mermaid diagrams
5
+ Requires-Python: >=3.11
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: fastapi>=0.115.12
8
+ Requires-Dist: httpx>=0.28.1
9
+ Requires-Dist: langchain-mcp>=0.2.1
10
+ Requires-Dist: langchain-openai>=0.3.19
11
+ Requires-Dist: mcp[cli]>=1.9.2
12
+ Requires-Dist: pydantic>=2.11.5
13
+ Requires-Dist: pydantic-ai-slim[mcp]>=0.2.14
14
+ Requires-Dist: python-dotenv>=1.1.0
15
+ Requires-Dist: uvicorn>=0.34.3
16
+
17
+ # Mermaid MCP Server
18
+
19
+ A Model Context Protocol (MCP) server for validating Mermaid diagrams.
20
+
21
+ Implements a minimal Python wrapper over https://github.com/mermaid-js/mermaid-cli for simpler out of the box use.
22
+
23
+ ## Overview
24
+
25
+ Python MCP server for validating Mermaid diagrams and (optionally) rendering them as PNG images. It uses the Mermaid CLI tool to perform the validation and rendering.
26
+
27
+ The server provides LLMs with structured validation results including:
28
+ - **Boolean validation status** (`is_valid: true/false`) indicating whether the Mermaid diagram syntax is correct
29
+ - **Detailed error messages** explaining exactly what went wrong if validation fails (e.g., syntax errors, unsupported diagram types, malformed nodes)
30
+ - **Optional base64-encoded PNG images** of successfully rendered diagrams for visual verification
31
+
32
+ This enables LLMs to programmatically validate Mermaid diagram syntax, understand specific errors to provide helpful corrections, and optionally receive visual confirmation of the rendered output.
33
+
34
+ Also provides a simple Pydantic-AI MCP Client to invoke the MCP server using a Gemini model for testing.
35
+
36
+ ## Prerequisites
37
+
38
+ **Important**: This MCP server requires Node.js to be installed on your system, even if you're only using the server component (not the client). The server internally calls `npx @mermaid-js/mermaid-cli` as a subprocess to perform diagram validation and rendering.
39
+
40
+ ### Required Dependencies
41
+
42
+ - **Node.js** with npm (required for all usage)
43
+ - **Mermaid CLI**: Install with `npm install -g @mermaid-js/mermaid-cli`
44
+ - **Python** with uv (for running the MCP server)
45
+
46
+ ### Quick Dependency Setup
47
+
48
+ ```bash
49
+ # Install Mermaid CLI globally
50
+ npm install -g @mermaid-js/mermaid-cli
51
+
52
+ # Verify installation
53
+ npx @mermaid-js/mermaid-cli --version
54
+ ```
55
+
56
+ ## Quickstart
57
+
58
+ To use this server with an MCP client (like Claude Desktop), add the following configuration to your MCP settings:
59
+
60
+ **Note**: Make sure you have Node.js and Mermaid CLI installed (see Prerequisites above) before configuring the MCP server.
61
+
62
+ ### Configuration Format
63
+
64
+ 1. Clone this repository
65
+
66
+ 2. Add this to your MCP client configuration file (e.g., `claude_desktop_config.json`):
67
+
68
+ ```json
69
+ {
70
+ "mcpServers": {
71
+ "mermaid-validator": {
72
+ "command": "uv",
73
+ "args": ["run", "/path/to/mermaid_mcp_server.py"],
74
+ }
75
+ }
76
+ }
77
+ ```
78
+
79
+ ### Configuration Options
80
+
81
+ - **command**: Use `uv` to run the server
82
+ - **args**: Run the server script with `uv run`
83
+ - **cwd**: Set to the absolute path of your cloned repository
84
+ - **env**: Environment variables for the server
85
+ - `MCP_TRANSPORT`: Set to `"stdio"` for standard input/output communication
86
+
87
+
88
+ #### Example Extended Configuration
89
+
90
+ ```json
91
+ {
92
+ "mcpServers": {
93
+ "mermaid-validator": {
94
+ "command": "uv",
95
+ "args": ["run", "/path/to/mermaid_mcp_server.py"],
96
+ "env": {
97
+ "MCP_TRANSPORT": "stdio",
98
+ }
99
+ }
100
+ }
101
+ }
102
+ ```
103
+
104
+ ## Abstractions Over Mermaid-CLI
105
+
106
+ The Python wrapper significantly simplifies the usage of the Mermaid CLI by abstracting away complex file handling and command-line arguments:
107
+
108
+ ### Without the wrapper (raw mermaid-cli):
109
+ ```bash
110
+ # Create input file
111
+ echo "graph TD; A-->B" > diagram.mmd
112
+
113
+ # Create puppeteer config file
114
+ echo '{"args": ["--no-sandbox", "--disable-setuid-sandbox"]}' > puppeteer-config.json
115
+
116
+ # Run mermaid-cli with multiple arguments
117
+ npx @mermaid-js/mermaid-cli -i diagram.mmd -o output.png --puppeteerConfigFile puppeteer-config.json
118
+
119
+ # Handle output file and cleanup
120
+ ```
121
+
122
+ ### With the Python wrapper:
123
+ ```python
124
+ # Simple function call with diagram text
125
+ result = await validate_mermaid_diagram("graph TD; A-->B")
126
+
127
+ # All file handling, configuration, and cleanup is automatic
128
+ # Returns structured result with validation status and base64-encoded image
129
+ ```
130
+
131
+ ### Key Abstractions:
132
+
133
+ 1. **Temporary File Management**: Automatically creates and cleans up temporary `.mmd` input files
134
+ 2. **Output File Handling**: Manages temporary `.png` output files and converts them to base64 strings
135
+ 3. **Puppeteer Configuration**: Automatically generates the required sandboxing configuration for headless browser rendering
136
+ 4. **Error Handling**: Captures and returns structured error messages instead of raw stderr output
137
+ 5. **Command Construction**: Builds the complete `npx @mermaid-js/mermaid-cli` command with all necessary flags
138
+ 6. **Resource Cleanup**: Ensures all temporary files are properly deleted after processing
139
+
140
+ This abstraction allows users to focus on diagram validation and rendering without dealing with the underlying file system operations and command-line complexities.
141
+
142
+
143
+ # Local Development
144
+
145
+ This repository can be used standalone to test the functionality of the Mermaid MCP validator programmatically.
146
+
147
+ ## Requirements
148
+
149
+ See the [Prerequisites](#prerequisites) section above for required dependencies (Node.js, Mermaid CLI, and Python with uv).
150
+
151
+ ## Quick Setup (Recommended)
152
+
153
+ Use the provided Makefile for streamlined setup:
154
+
155
+ ```bash
156
+ # Install all dependencies (Python + Node.js + Mermaid CLI)
157
+ make install
158
+
159
+ # Run validation tests
160
+ make test
161
+ ```
162
+
163
+ ## Manual Setup
164
+
165
+ If you prefer manual setup:
166
+
167
+ 1. Clone this repository
168
+ 2. Install dependencies: `uv sync`
169
+ 3. Install Mermaid CLI: `npm install -g @mermaid-js/mermaid-cli`
170
+ 4. Copy `.env.example` to `.env` and fill in your API key
171
+ 5. Run the server: `uv run mermaid_mcp_server.py`
172
+
173
+ ## Usage
174
+
175
+ The server exposes a tool for validating Mermaid diagrams:
176
+
177
+ - `validate_mermaid_diagram`: Validates a Mermaid diagram and returns validation results
178
+
179
+ ### Tool Parameters
180
+
181
+ - `diagram_text` (required): The Mermaid diagram text to validate
182
+ - `return_image` (optional, default: `false`): Whether to return the base64-encoded PNG image
183
+
184
+ ### Context Length Optimisation
185
+
186
+ **Important**: By default, the tool does not return the base64-encoded image (`return_image=false`) to preserve context length in LLM conversations. Base64-encoded images can be very long strings (often 10KB-100KB+) that significantly impact the available context for the conversation.
187
+
188
+ **When to use each setting**:
189
+ - `return_image=false` (default): Use for diagram validation only. Fast and context-efficient.
190
+ - `return_image=true`: Use only when you specifically need the rendered image data. Warning: This will consume significant context length.
191
+
192
+ ### Example Usage
193
+
194
+ ```python
195
+ # Validation only (recommended for most cases)
196
+ result = await validate_mermaid_diagram("graph TD; A-->B")
197
+ # Returns: MermaidValidationResult(is_valid=True, error_message=None, diagram_image=None)
198
+
199
+ # Validation with image (use sparingly)
200
+ result = await validate_mermaid_diagram("graph TD; A-->B", return_image=True)
201
+ # Returns: MermaidValidationResult(is_valid=True, error_message=None, diagram_image="iVBORw0KGgoAAAANSUhEUg...")
202
+ ```
203
+
204
+ ## Testing
205
+
206
+ The project includes convenient testing commands:
207
+
208
+ ```bash
209
+ # Run all tests
210
+ make test
211
+
212
+ # Or run the test script directly
213
+ uv run test_pydantic.py
214
+ ```
215
+
216
+ The test script uses Pydantic AI with Gemini models to validate the MCP server functionality.
@@ -0,0 +1,8 @@
1
+ __init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ mermaid_mcp_server.py,sha256=ZNp8w4tqO_xxU9yXdribs4FdA6U7p6souRqpjieNCg4,4125
3
+ test_pydantic.py,sha256=8CkkwDUiZh1_lmXeJ6Jyp_dUyRZWr_qOse15ACohypw,1243
4
+ iflow_mcp_andrewginns_mermaid_mcp_server-11.4.2.dist-info/METADATA,sha256=2FKzHFfMFDd1WafZkyJ91r2KiQiu55aE8a7SMqp3UP4,7492
5
+ iflow_mcp_andrewginns_mermaid_mcp_server-11.4.2.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
6
+ iflow_mcp_andrewginns_mermaid_mcp_server-11.4.2.dist-info/entry_points.txt,sha256=puY__ZIXoXNQYH0HBKeYR4ZtqSr58GnL6lkKsVfMdOM,63
7
+ iflow_mcp_andrewginns_mermaid_mcp_server-11.4.2.dist-info/top_level.txt,sha256=7upMHofPhWv6FPr_Pf4Yj3qFn6utq9ubW-fSBPdpHEA,42
8
+ iflow_mcp_andrewginns_mermaid_mcp_server-11.4.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.10.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ mermaid-mcp-server = mermaid_mcp_server:main
@@ -0,0 +1,3 @@
1
+ __init__
2
+ mermaid_mcp_server
3
+ test_pydantic
mermaid_mcp_server.py ADDED
@@ -0,0 +1,128 @@
1
+ # /// script
2
+ # dependencies = [
3
+ # "pydantic>=2.11.5",
4
+ # "mcp[cli]>=1.9.2",
5
+ # ]
6
+ # ///
7
+
8
+ import os
9
+ import tempfile
10
+ import subprocess
11
+ import base64
12
+ import json
13
+ from typing import Optional
14
+ from pydantic import BaseModel, Field
15
+ from mcp.server.fastmcp import FastMCP
16
+
17
+ mcp = FastMCP("mermaid-validator")
18
+
19
+
20
+ class MermaidValidationResult(BaseModel):
21
+ """Result of mermaid diagram validation."""
22
+
23
+ is_valid: bool = Field(description="Whether the mermaid diagram is valid")
24
+ error_message: Optional[str] = Field(
25
+ None, description="Error message if the diagram is invalid"
26
+ )
27
+ diagram_image: Optional[str] = Field(
28
+ None, description="Base64-encoded PNG image of the rendered diagram if valid"
29
+ )
30
+
31
+
32
+ @mcp.tool()
33
+ async def validate_mermaid_diagram(
34
+ diagram_text: str, return_image: bool = False
35
+ ) -> MermaidValidationResult:
36
+ """
37
+ Validate a mermaid diagram and optionally render it as a PNG image.
38
+
39
+ Uses mermaid-cli to validate and render the diagram. Requires mermaid-cli
40
+ to be installed globally via npm: npm install -g @mermaid-js/mermaid-cli
41
+
42
+ Args:
43
+ diagram_text: The mermaid diagram text to validate
44
+ return_image: Whether to return the base64-encoded PNG image (default: False)
45
+ Set to True only when you specifically need the image data.
46
+ Warning: Images can be very long strings that impact context length.
47
+
48
+ Returns:
49
+ A MermaidValidationResult object containing validation results
50
+ """
51
+ temp_file_path = None
52
+ output_file_name = None
53
+ puppeteer_config_path = None
54
+
55
+ try:
56
+ with tempfile.NamedTemporaryFile(
57
+ suffix=".mmd", mode="w", delete=False
58
+ ) as temp_file:
59
+ temp_file.write(diagram_text)
60
+ temp_file_path = temp_file.name
61
+
62
+ # Always create output file for validation, but only read it if return_image=True
63
+ output_file = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
64
+ output_file.close()
65
+ output_file_name = output_file.name
66
+
67
+ puppeteer_config = {"args": ["--no-sandbox", "--disable-setuid-sandbox"]}
68
+ with tempfile.NamedTemporaryFile(
69
+ suffix=".json", mode="w", delete=False
70
+ ) as config_file:
71
+ json.dump(puppeteer_config, config_file)
72
+ puppeteer_config_path = config_file.name
73
+
74
+ result = subprocess.run(
75
+ [
76
+ "npx",
77
+ "-y",
78
+ "@mermaid-js/mermaid-cli@11.4.2",
79
+ "-i",
80
+ temp_file_path,
81
+ "-o",
82
+ output_file_name,
83
+ "--puppeteerConfigFile",
84
+ puppeteer_config_path,
85
+ ],
86
+ capture_output=True,
87
+ text=True,
88
+ )
89
+
90
+ if result.returncode == 0:
91
+ diagram_image = None
92
+ if return_image and output_file_name:
93
+ with open(output_file_name, "rb") as f:
94
+ diagram_image = base64.b64encode(f.read()).decode("utf-8")
95
+
96
+ return MermaidValidationResult(
97
+ is_valid=True, error_message=None, diagram_image=diagram_image
98
+ )
99
+ else:
100
+ return MermaidValidationResult(
101
+ is_valid=False,
102
+ error_message=f"Mermaid diagram is invalid: {result.stderr}",
103
+ diagram_image=None,
104
+ )
105
+ except Exception as e:
106
+ return MermaidValidationResult(
107
+ is_valid=False,
108
+ error_message=f"Error validating mermaid diagram: {str(e)}",
109
+ diagram_image=None,
110
+ )
111
+ finally:
112
+ for file_path in [temp_file_path, output_file_name, puppeteer_config_path]:
113
+ if file_path and os.path.exists(file_path):
114
+ try:
115
+ os.unlink(file_path)
116
+ except OSError as e:
117
+ print(f"Error deleting file {file_path}: {e}")
118
+ pass
119
+
120
+
121
+ def main():
122
+ """Main entry point for the MCP server."""
123
+ transport = os.getenv("MCP_TRANSPORT", "stdio")
124
+ mcp.run(transport=transport)
125
+
126
+
127
+ if __name__ == "__main__":
128
+ main()
test_pydantic.py ADDED
@@ -0,0 +1,47 @@
1
+ import asyncio
2
+ from dotenv import load_dotenv
3
+ from pydantic_ai import Agent
4
+ from pydantic_ai.mcp import MCPServerStdio
5
+
6
+ load_dotenv()
7
+
8
+
9
+ async def main():
10
+ """Test the mermaid validator MCP server using Pydantic AI."""
11
+ example_diagram = """
12
+ graph TD
13
+ A[Start] --> B{Is it valid?}
14
+ B -->|Yes| C[Output valid result]
15
+ B -->|No| D[Output error message]
16
+ C --> E[End]
17
+ D --> E
18
+ """
19
+
20
+ mermaid_server = MCPServerStdio(
21
+ command="uv",
22
+ args=[
23
+ "run",
24
+ "mermaid_mcp_server.py",
25
+ ],
26
+ )
27
+
28
+ agent = Agent(
29
+ "gemini-2.5-pro-preview-05-06",
30
+ system_prompt="""
31
+ You are a helpful assistant that validates mermaid diagrams.
32
+ You will be given a mermaid diagram and you need to validate it using the MCP mermaid validator tool.
33
+ Return whether the diagram is valid, and if not, provide the error message.
34
+ """,
35
+ mcp_servers=[mermaid_server],
36
+ )
37
+ Agent.instrument_all()
38
+
39
+ async with agent.run_mcp_servers():
40
+ result = await agent.run(
41
+ "Validate the following mermaid diagram: " + example_diagram
42
+ )
43
+ print(result.output)
44
+
45
+
46
+ if __name__ == "__main__":
47
+ asyncio.run(main())