Skip to main content
Glama
wwwzhouhui

Mermaid MCP Server

by wwwzhouhui

convert_mermaid_to_image

Convert Mermaid diagram code into PNG, JPG, SVG, or PDF images with customizable themes, dimensions, and background colors.

Instructions

将 Mermaid 图表代码转换为多种格式的图像(PNG、JPG、PDF、SVG)。

参数:
    mermaid_code: 要转换的 Mermaid 图表语法代码
    output_format: 输出格式 - png、jpg、svg 或 pdf(默认:png)
    theme: 视觉主题 - default、dark、neutral 或 forest(默认:default)
    background_color: 背景颜色,十六进制代码(如 FF0000)或带 ! 前缀的命名颜色(如 !white)
    width: 图像宽度(像素,可选)
    height: 图像高度(像素,可选)

返回:
    包含转换后图像数据和元数据的字典

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
mermaid_codeYes
output_formatNopng
themeNodefault
background_colorNo
widthNo
heightNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The main handler function for 'convert_mermaid_to_image' tool. Converts Mermaid diagram code to image formats (PNG, JPG, SVG, PDF) using the mermaid.ink API. Includes input validation, URL construction, HTTP request, and base64 encoding of the result.
    @mcp.tool()
    def convert_mermaid_to_image(
        mermaid_code: str,
        output_format: str = "png",
        theme: str = "default",
        background_color: str = "",
        width: Optional[int] = None,
        height: Optional[int] = None
    ) -> Dict[str, Any]:
        """
        将 Mermaid 图表代码转换为多种格式的图像(PNG、JPG、PDF、SVG)。
        
        参数:
            mermaid_code: 要转换的 Mermaid 图表语法代码
            output_format: 输出格式 - png、jpg、svg 或 pdf(默认:png)
            theme: 视觉主题 - default、dark、neutral 或 forest(默认:default)
            background_color: 背景颜色,十六进制代码(如 FF0000)或带 ! 前缀的命名颜色(如 !white)
            width: 图像宽度(像素,可选)
            height: 图像高度(像素,可选)
        
        返回:
            包含转换后图像数据和元数据的字典
        """
        try:
            # 验证输入参数
            if not mermaid_code or not mermaid_code.strip():
                return {
                    "success": False,
                    "error": "Mermaid 代码是必需的,不能为空"
                }
            
            # 清理 Mermaid 代码(移除 markdown 代码块标记)
            cleaned_code = mermaid_code.replace("```mermaid", "").replace("```", "").strip()
            
            # 验证输出格式
            valid_formats = ["png", "jpg", "jpeg", "svg", "pdf"]
            output_format = output_format.lower()
            if output_format not in valid_formats:
                return {
                    "success": False,
                    "error": f"无效的输出格式 '{output_format}'。支持的格式:{', '.join(valid_formats)}"
                }
            
            # 验证主题
            valid_themes = ["default", "dark", "neutral", "forest"]
            if theme not in valid_themes:
                return {
                    "success": False,
                    "error": f"无效的主题 '{theme}'。支持的主题:{', '.join(valid_themes)}"
                }
            
            logger.info(f"Converting Mermaid diagram to {output_format} format with theme {theme}")
            
            # Base64 编码 Mermaid 代码
            try:
                encoded_diagram = base64.urlsafe_b64encode(cleaned_code.encode('utf-8')).decode('ascii')
            except Exception as e:
                return {
                    "success": False,
                    "error": f"编码图表失败:{str(e)}"
                }
            
            # 构建 API URL
            url = _build_api_url(encoded_diagram, output_format, theme, background_color, width, height)
            
            logger.info(f"Making request to {url}")
            
            # 发送 HTTP 请求
            try:
                response = requests.get(url, timeout=30)
                
                if response.status_code != 200:
                    if response.status_code == 400:
                        error_msg = f"无效的 Mermaid 语法:{response.text}"
                    elif response.status_code == 413:
                        error_msg = "图表对于 API 来说太大了"
                    else:
                        error_msg = f"转换失败:HTTP {response.status_code}"
                    
                    logger.error(error_msg)
                    return {
                        "success": False,
                        "error": error_msg
                    }
                
                # 确定 MIME 类型
                mime_types = {
                    "png": "image/png",
                    "jpg": "image/jpeg", 
                    "jpeg": "image/jpeg",
                    "svg": "image/svg+xml",
                    "pdf": "application/pdf"
                }
                
                mime_type = mime_types.get(output_format, "image/png")
                filename = f"mermaid_diagram.{output_format}"
                
                # 将图像数据编码为 base64 以便传输
                image_base64 = base64.b64encode(response.content).decode('ascii')
                
                logger.info(f"Successfully converted diagram to {output_format} ({len(response.content)} bytes)")
                
                return {
                    "success": True,
                    "data": {
                        "image_base64": image_base64,
                        "mime_type": mime_type,
                        "filename": filename,
                        "size_bytes": len(response.content),
                        "format": output_format,
                        "theme": theme
                    },
                    "message": f"成功将 Mermaid 图表转换为 {output_format.upper()} 格式"
                }
                
            except requests.Timeout:
                error_msg = "转换超时 - mermaid.ink 响应时间过长"
                logger.error(error_msg)
                return {
                    "success": False,
                    "error": error_msg
                }
                
            except requests.ConnectionError:
                error_msg = "连接错误:无法访问 mermaid.ink 服务"
                logger.error(error_msg)
                return {
                    "success": False,
                    "error": error_msg
                }
                
            except Exception as e:
                error_msg = f"请求错误:{str(e)}"
                logger.error(error_msg)
                return {
                    "success": False,
                    "error": error_msg
                }
                
        except Exception as e:
            error_msg = f"转换过程中发生意外错误:{str(e)}"
            logger.error(error_msg)
            return {
                "success": False,
                "error": error_msg
            }
  • Helper function to build the mermaid.ink API endpoint URL with appropriate format, theme, background color, and dimensions.
    def _build_api_url(
        encoded_diagram: str, 
        output_format: str, 
        theme: str, 
        background_color: str, 
        width: Optional[int] = None, 
        height: Optional[int] = None
    ) -> str:
        """构建 mermaid.ink API URL"""
        # 根据格式选择不同的端点
        if output_format == "svg":
            base_url = f"https://mermaid.ink/svg/{encoded_diagram}"
        elif output_format == "pdf":
            base_url = f"https://mermaid.ink/pdf/{encoded_diagram}"
        else:  # png, jpg, jpeg
            base_url = f"https://mermaid.ink/img/{encoded_diagram}"
        
        # 构建查询参数
        params = {}
        
        # 格式特定参数
        if output_format in ["png", "jpg", "jpeg"]:
            params["type"] = output_format
            
        # 主题参数(仅适用于图像格式,不适用于 SVG/PDF)
        if theme and theme != "default" and output_format in ["png", "jpg", "jpeg"]:
            params["theme"] = theme
        
        # 背景颜色参数
        if background_color:
            if background_color.startswith("!"):
                params["bgColor"] = background_color
            else:
                color = background_color.lstrip("#")
                if len(color) == 6 and all(c in "0123456789ABCDEFabcdef" for c in color):
                    params["bgColor"] = color
        
        # 尺寸参数
        if width:
            params["width"] = str(width)
        if height:
            params["height"] = str(height)
        
        # 组合 URL 和参数
        if params:
            return f"{base_url}?{urlencode(params)}"
        else:
            return base_url
  • The @mcp.tool() decorator registers the convert_mermaid_to_image function as an MCP tool.
    @mcp.tool()
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden. It mentions the tool converts code to images and returns a dictionary with data and metadata, but lacks details on error handling, performance (e.g., rate limits), authentication needs, or side effects. This is inadequate for a mutation tool with zero annotation coverage.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and front-loaded: the first sentence states the core purpose, followed by a structured list of parameters and return value. Every sentence earns its place with no redundant information, making it efficient and well-organized.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (6 parameters, mutation operation) and no annotations, the description does well by detailing all parameters and noting the return structure. However, it lacks behavioral context like error cases or limitations. The presence of an output schema mitigates some gaps, but more completeness is needed for a mutation tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It provides detailed semantics for all 6 parameters beyond the schema, including explanations of mermaid_code, output_format options, theme options, background_color syntax, and optional width/height. This adds significant value over the bare schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('将 Mermaid 图表代码转换为多种格式的图像') with the resource (Mermaid chart code) and distinguishes from siblings by focusing on conversion rather than validation or option retrieval. It explicitly lists the output formats, making the purpose unambiguous.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage by specifying what the tool does, but does not explicitly state when to use it versus alternatives like validate_mermaid_syntax or get_supported_options. No guidance on prerequisites or exclusions is provided, leaving usage context partially inferred.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/wwwzhouhui/mermaid_mcp_server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server