-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmermaid_chart.py
More file actions
489 lines (427 loc) · 14.7 KB
/
mermaid_chart.py
File metadata and controls
489 lines (427 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#!/usr/bin/env python3
"""
Mermaid Chart MCP Server — 流程图绘制工具。
使用 Mermaid 语法生成流程图,输出为 HTML 文件并可在浏览器中打开。
支持:流程图、时序图、甘特图、类图、状态图、ER图 等所有 Mermaid 图表类型。
"""
import os
import time
import subprocess
import webbrowser
from pathlib import Path
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("mermaid-chart")
# ─── HTML 模板 ─────────────────────────────────────────────────────────────
HTML_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{title}</title>
<style>
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
body {{
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #0d1117;
color: #c9d1d9;
min-height: 100vh;
display: flex;
flex-direction: column;
}}
header {{
background: #161b22;
border-bottom: 1px solid #30363d;
padding: 16px 24px;
display: flex;
align-items: center;
justify-content: space-between;
}}
header h1 {{
font-size: 18px;
font-weight: 600;
color: #f0f6fc;
}}
.toolbar {{
display: flex;
gap: 8px;
}}
.toolbar button {{
background: #21262d;
color: #c9d1d9;
border: 1px solid #30363d;
border-radius: 6px;
padding: 6px 16px;
cursor: pointer;
font-size: 13px;
transition: background 0.15s;
}}
.toolbar button:hover {{
background: #30363d;
border-color: #8b949e;
}}
.container {{
flex: 1;
display: flex;
flex-direction: column;
padding: 24px;
gap: 16px;
max-width: 1400px;
width: 100%;
margin: 0 auto;
}}
.chart-wrapper {{
background: #ffffff;
border-radius: 8px;
padding: 32px;
flex: 1;
display: flex;
align-items: center;
justify-content: center;
overflow: auto;
min-height: 400px;
}}
.chart-wrapper .mermaid {{
width: 100%;
}}
.chart-wrapper .mermaid svg {{
max-width: 100%;
height: auto;
}}
.source-code {{
background: #161b22;
border: 1px solid #30363d;
border-radius: 8px;
overflow: hidden;
}}
.source-code summary {{
padding: 12px 16px;
cursor: pointer;
font-size: 13px;
color: #8b949e;
user-select: none;
}}
.source-code summary:hover {{
color: #c9d1d9;
}}
.source-code pre {{
padding: 16px;
overflow-x: auto;
font-family: 'SF Mono', 'Fira Code', monospace;
font-size: 13px;
line-height: 1.6;
color: #79c0ff;
border-top: 1px solid #30363d;
}}
footer {{
text-align: center;
padding: 12px;
font-size: 12px;
color: #484f58;
border-top: 1px solid #21262d;
}}
@media print {{
body {{ background: #fff; }}
header, footer, .toolbar, .source-code {{ display: none; }}
.chart-wrapper {{ box-shadow: none; border: none; padding: 0; }}
}}
</style>
</head>
<body>
<header>
<h1>{title}</h1>
<div class="toolbar">
<button onclick="downloadSVG()">Export SVG</button>
<button onclick="downloadPNG()">Export PNG</button>
<button onclick="window.print()">Print</button>
</div>
</header>
<div class="container">
<div class="chart-wrapper">
<pre class="mermaid">
{mermaid_code}
</pre>
</div>
<details class="source-code">
<summary>View Mermaid Source</summary>
<pre>{mermaid_source}</pre>
</details>
</div>
<footer>Generated by Mermaid Chart MCP — Code Hacker</footer>
<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
<script>
mermaid.initialize({{
startOnLoad: true,
theme: 'default',
flowchart: {{ useMaxWidth: true, htmlLabels: true, curve: 'basis' }},
securityLevel: 'loose',
}});
function downloadSVG() {{
const svg = document.querySelector('.chart-wrapper svg');
if (!svg) {{ alert('Chart not rendered yet'); return; }}
const data = new XMLSerializer().serializeToString(svg);
const blob = new Blob([data], {{ type: 'image/svg+xml' }});
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = '{filename}.svg';
a.click();
}}
function downloadPNG() {{
const svg = document.querySelector('.chart-wrapper svg');
if (!svg) {{ alert('Chart not rendered yet'); return; }}
const data = new XMLSerializer().serializeToString(svg);
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = function() {{
canvas.width = img.width * 2;
canvas.height = img.height * 2;
ctx.scale(2, 2);
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
const a = document.createElement('a');
a.href = canvas.toDataURL('image/png');
a.download = '{filename}.png';
a.click();
}};
img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(data)));
}}
</script>
</body>
</html>"""
# ─── 工具函数 ──────────────────────────────────────────────────────────────
def _get_output_dir() -> Path:
"""获取输出目录,默认 ~/.mermaid-charts/"""
out_dir = Path.home() / ".mermaid-charts"
out_dir.mkdir(parents=True, exist_ok=True)
return out_dir
def _open_in_browser(file_path: str) -> str:
"""尝试在浏览器中打开文件"""
try:
# Termux: try termux-open first
result = subprocess.run(
["termux-open", file_path],
capture_output=True, text=True, timeout=5,
)
if result.returncode == 0:
return "已在浏览器中打开"
except (FileNotFoundError, subprocess.TimeoutExpired):
pass
try:
# 常规系统
webbrowser.open(f"file://{file_path}")
return "已在浏览器中打开"
except Exception:
pass
return "请手动在浏览器中打开文件"
def _escape_html(text: str) -> str:
"""转义 HTML 特殊字符"""
return text.replace("&", "&").replace("<", "<").replace(">", ">")
# ═══════════════════════════════════════════════════════════════════════════
# MCP Tools
# ═══════════════════════════════════════════════════════════════════════════
@mcp.tool()
async def render_mermaid(
code: str,
title: str = "Mermaid Chart",
output_path: str = "",
open_browser: bool = True,
) -> str:
"""Render Mermaid diagram code to an interactive HTML file and open in browser.
Supports all Mermaid diagram types: flowchart, sequence, gantt, class, state, ER, pie, etc.
Args:
code: Mermaid diagram code (e.g., 'graph TD\\n A-->B')
title: Chart title displayed in the HTML page
output_path: Custom output HTML file path (default: auto-generated in ~/.mermaid-charts/)
open_browser: Whether to open the HTML file in browser (default: True)
Example code:
graph TD
A[Start] --> B{Decision}
B -->|Yes| C[Do Something]
B -->|No| D[Do Something Else]
C --> E[End]
D --> E
"""
if not code.strip():
return "Error: Mermaid code cannot be empty"
# 确定输出路径
if output_path:
out_file = Path(output_path)
out_file.parent.mkdir(parents=True, exist_ok=True)
else:
out_dir = _get_output_dir()
timestamp = time.strftime("%Y%m%d_%H%M%S")
safe_title = "".join(c if c.isalnum() or c in "-_" else "_" for c in title)[:40]
out_file = out_dir / f"{safe_title}_{timestamp}.html"
filename = out_file.stem
# 生成 HTML
html = HTML_TEMPLATE.format(
title=_escape_html(title),
mermaid_code=code,
mermaid_source=_escape_html(code),
filename=filename,
)
out_file.write_text(html, encoding="utf-8")
abs_path = str(out_file.resolve())
# 打开浏览器
browser_msg = ""
if open_browser:
browser_msg = _open_in_browser(abs_path)
return (
f"Mermaid 图表已生成: {abs_path}\n"
f"标题: {title}\n"
f"{browser_msg}\n"
f"功能:\n"
f" - Export SVG / PNG 按钮\n"
f" - 打印支持\n"
f" - 展开查看 Mermaid 源码"
)
@mcp.tool()
async def flowchart(
nodes: list[dict],
title: str = "Flowchart",
direction: str = "TD",
output_path: str = "",
open_browser: bool = True,
) -> str:
"""Generate a flowchart from structured node data. Easier than writing raw Mermaid syntax.
Args:
nodes: List of node definitions. Each node is a dict with:
- id: Node ID (e.g., "A", "B")
- label: Display text (e.g., "Start", "Process Data")
- shape: Optional shape - "rect" (default), "round", "diamond", "circle", "stadium"
- next: List of target node IDs or dicts with "to" and optional "label"
e.g., ["B", "C"] or [{"to": "B", "label": "Yes"}, {"to": "C", "label": "No"}]
title: Chart title
direction: Flow direction - "TD" (top-down), "LR" (left-right), "BT" (bottom-top), "RL" (right-left)
output_path: Custom output path
open_browser: Open in browser (default: True)
Example:
nodes = [
{"id": "A", "label": "Start", "shape": "stadium", "next": ["B"]},
{"id": "B", "label": "Is Valid?", "shape": "diamond", "next": [{"to": "C", "label": "Yes"}, {"to": "D", "label": "No"}]},
{"id": "C", "label": "Process", "next": ["E"]},
{"id": "D", "label": "Error", "shape": "round", "next": ["E"]},
{"id": "E", "label": "End", "shape": "stadium"},
]
"""
if not nodes:
return "Error: nodes list cannot be empty"
shape_map = {
"rect": ("[", "]"),
"round": ("(", ")"),
"diamond": ("{", "}"),
"circle": ("((", "))"),
"stadium": ("([", "])"),
}
lines = [f"graph {direction}"]
for node in nodes:
nid = node.get("id", "")
label = node.get("label", nid)
shape = node.get("shape", "rect")
left, right = shape_map.get(shape, ("[", "]"))
lines.append(f" {nid}{left}\"{label}\"{right}")
for node in nodes:
nid = node.get("id", "")
nexts = node.get("next", [])
for nxt in nexts:
if isinstance(nxt, dict):
target = nxt.get("to", "")
label = nxt.get("label", "")
if label:
lines.append(f" {nid} -->|\"{label}\"| {target}")
else:
lines.append(f" {nid} --> {target}")
else:
lines.append(f" {nid} --> {nxt}")
mermaid_code = "\n".join(lines)
return await render_mermaid(
code=mermaid_code,
title=title,
output_path=output_path,
open_browser=open_browser,
)
@mcp.tool()
async def sequence_diagram(
interactions: list[dict],
title: str = "Sequence Diagram",
output_path: str = "",
open_browser: bool = True,
) -> str:
"""Generate a sequence diagram from structured interaction data.
Args:
interactions: List of interactions. Each is a dict with:
- from: Source participant
- to: Target participant
- message: Message text
- type: Optional arrow type - "solid" (default), "dashed", "async"
- note: Optional note text (renders as a note over the 'from' participant)
title: Chart title
output_path: Custom output path
open_browser: Open in browser (default: True)
Example:
interactions = [
{"from": "Client", "to": "Server", "message": "HTTP Request"},
{"from": "Server", "to": "Database", "message": "Query", "type": "solid"},
{"from": "Database", "to": "Server", "message": "Results", "type": "dashed"},
{"from": "Server", "to": "Client", "message": "HTTP Response", "type": "dashed"},
]
"""
if not interactions:
return "Error: interactions list cannot be empty"
arrow_map = {
"solid": "->>",
"dashed": "-->>",
"async": "-)",
}
lines = ["sequenceDiagram"]
for item in interactions:
if "note" in item:
lines.append(f" Note over {item['from']}: {item['note']}")
frm = item.get("from", "")
to = item.get("to", "")
msg = item.get("message", "")
arrow = arrow_map.get(item.get("type", "solid"), "->>")
lines.append(f" {frm}{arrow}{to}: {msg}")
mermaid_code = "\n".join(lines)
return await render_mermaid(
code=mermaid_code,
title=title,
output_path=output_path,
open_browser=open_browser,
)
@mcp.tool()
async def list_charts(directory: str = "") -> str:
"""List all generated Mermaid chart HTML files.
Args:
directory: Directory to scan (default: ~/.mermaid-charts/)
"""
scan_dir = Path(directory) if directory else _get_output_dir()
if not scan_dir.is_dir():
return f"Directory does not exist: {scan_dir}"
files = sorted(scan_dir.glob("*.html"), key=lambda f: f.stat().st_mtime, reverse=True)
if not files:
return f"No chart files found in {scan_dir}"
lines = [f"=== Mermaid Charts ({len(files)} files) ===", f"目录: {scan_dir}", ""]
for f in files[:20]:
size_kb = f.stat().st_size / 1024
mtime = time.strftime("%Y-%m-%d %H:%M", time.localtime(f.stat().st_mtime))
lines.append(f" {f.name} ({size_kb:.1f}KB, {mtime})")
if len(files) > 20:
lines.append(f" ... and {len(files) - 20} more")
return "\n".join(lines)
@mcp.tool()
async def open_chart(file_path: str) -> str:
"""Open an existing Mermaid chart HTML file in the browser.
Args:
file_path: Path to the HTML file to open
"""
path = Path(file_path)
if not path.is_file():
return f"Error: File not found: {file_path}"
abs_path = str(path.resolve())
msg = _open_in_browser(abs_path)
return f"{msg}: {abs_path}"
# ─── 入口 ──────────────────────────────────────────────────────────────────
if __name__ == "__main__":
mcp.run(transport="sse", host="0.0.0.0", port=8008)