validate_mermaid_syntax
Validate Mermaid diagram syntax by parsing and checking for errors. Ensures code accuracy before generating images or other formats.
Instructions
通过尝试简单转换来验证 Mermaid 图表语法。
参数:
mermaid_code: 要验证的 Mermaid 图表语法代码
返回:
包含验证结果的字典
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| mermaid_code | Yes |
Implementation Reference
- mermaid_mcp_server/main.py:218-218 (registration)Registers the validate_mermaid_syntax tool using the @mcp.tool() decorator from FastMCP.@mcp.tool()
- mermaid_mcp_server/main.py:218-291 (handler)The handler function for validate_mermaid_syntax. Cleans the input mermaid_code, base64 encodes it, and uses a HEAD request to https://mermaid.ink/svg/ endpoint to validate the syntax. Returns a dict with 'valid' boolean and error/message.@mcp.tool() def validate_mermaid_syntax(mermaid_code: str) -> Dict[str, Any]: """ 通过尝试简单转换来验证 Mermaid 图表语法。 参数: mermaid_code: 要验证的 Mermaid 图表语法代码 返回: 包含验证结果的字典 """ try: if not mermaid_code or not mermaid_code.strip(): return { "valid": False, "error": "Mermaid 代码是必需的,不能为空" } # 清理代码 cleaned_code = mermaid_code.replace("```mermaid", "").replace("```", "").strip() # 尝试编码 try: encoded_diagram = base64.urlsafe_b64encode(cleaned_code.encode('utf-8')).decode('ascii') except Exception as e: return { "valid": False, "error": f"编码图表失败:{str(e)}" } # 使用 SVG 格式进行快速验证 url = f"https://mermaid.ink/svg/{encoded_diagram}" try: response = requests.head(url, timeout=10) if response.status_code == 200: return { "valid": True, "message": "Mermaid 语法有效" } elif response.status_code == 400: return { "valid": False, "error": "无效的 Mermaid 语法" } else: return { "valid": False, "error": f"验证失败:HTTP {response.status_code}" } except requests.Timeout: return { "valid": False, "error": "验证超时" } except requests.ConnectionError: return { "valid": False, "error": "连接错误:无法访问验证服务" } except Exception as e: return { "valid": False, "error": f"验证错误:{str(e)}" } except Exception as e: return { "valid": False, "error": f"验证过程中发生意外错误:{str(e)}" }