Mermaid MCP Server
Mermaid MCP Server
Сервер преобразования диаграмм Mermaid на основе Model Context Protocol (MCP), предоставляющий мощные возможности генерации диаграмм для AI-клиентов
О проекте
Mermaid MCP Server — это профессиональный сервер преобразования диаграмм Mermaid на основе Model Context Protocol (MCP), предоставляющий мощные возможности генерации диаграмм для AI-клиентов. Проект позволяет преобразовывать код диаграмм Mermaid в файлы изображений различных форматов (PNG, JPG, SVG, PDF), что даёт пользователям возможность легко создавать высококачественные диаграммы в различных AI-клиентах, поддерживающих протокол MCP.
Ключевые возможности
Многоформатный вывод: поддержка различных форматов изображений: PNG, JPG, SVG, PDF и других
Настройка тем: встроенные четыре темы: default, dark, neutral, forest
Пользовательские параметры: поддержка настройки цвета фона, размеров изображения и других параметров
Проверка синтаксиса: функция проверки синтаксиса Mermaid в реальном времени
Примеры ресурсов: встроенные примеры кода для различных типов диаграмм
Обработка ошибок:完善的 механизм обработки ошибок и понятные сообщения об ошибках
Двойной режим STDIO/SSE: поддержка двух режимов связи: STDIO и SSE
Управление пакетами uv: использование сверхбыстрого менеджера пакетов uv
Related MCP server: mcp-mermaid-validator
Список функций
Название функции | Описание функции | Технологический стек | Статус |
Преобразование диаграмм | Код Mermaid в изображение | mermaid.ink API | ✅ Стабильно |
Многоформатный вывод | PNG/JPG/SVG/PDF | requests + base64 | ✅ Стабильно |
Настройка тем | 4 встроенные темы | mermaid.ink | ✅ Стабильно |
Проверка синтаксиса | Проверка синтаксиса в реальном времени | mermaid-cli | ✅ Стабильно |
Примеры ресурсов | Богатые примеры диаграмм | Статические ресурсы | ✅ Стабильно |
Обработка ошибок | Понятные сообщения об ошибках | Обработка исключений Python | ✅ Стабильно |
Протокол MCP | Model Context Protocol | mcp[cli] | ✅ Стабильно |
Режим SSE | Server-Sent Events | FastAPI + Uvicorn | ✅ Стабильно |
Техническая архитектура
Технология | Версия | Назначение |
Python | 3.12+ | Основной язык разработки |
MCP | 1.9+ | Model Context Protocol |
FastAPI | 0.104+ | Веб-фреймворк (режим SSE) |
Uvicorn | 0.24+ | ASGI-сервер |
requests | 2.31+ | HTTP-клиент |
uv | latest | Менеджер пакетов Python |
Архитектура связи
┌─────────────────────────────────────────────────────────────────────────────────┐
│ 通信架构图 │
├─────────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────────┐ ┌─────────────────────────┐ ┌─────────────┐ │
│ │ AI 客户端 │ ◄────► │ Mermaid MCP Server │ ◄────► │ Mermaid API │ │
│ │ (Cursor/Claude) │ │ STDIO/SSE │ │ mermaid.ink│ │
│ └──────────────────┘ └─────────────────────────┘ └─────────────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ AI 对话界面 MCP 协议通信 图表渲染转换 │
│ 生成图表请求 双向数据传输 返回图像数据 │
│ │
└─────────────────────────────────────────────────────────────────────────────────┘Инструкция по установке
Требования к окружению
Python 3.12+
Менеджер пакетов uv (рекомендуется)
Установка зависимостей
Способ 1: установка с помощью uv (рекомендуется)
# 克隆仓库
git clone https://github.com/wwwzhouhui/mermaid_mcp_server.git
cd mermaid_mcp_server
# 安装依赖
uv syncСпособ 2: установка с помощью pip
pip install -r requirements.txtИнструкция по использованию
Настройка клиента
Настройка Cursor
Добавьте следующую конфигурацию в файл ~/.cursor/mcp.json:
Режим STDIO (рекомендуется):
{
"mcpServers": {
"mermaid-mcp-server-png-pdf-jpg-svg": {
"command": "uvx",
"args": [
"mermaid-mcp-server-png-pdf-jpg-svg"
]
}
}
}Режим SSE:
{
"mcpServers": {
"mermaid-mcp-server-png-pdf-jpg-svg": {
"url": "http://127.0.0.1:8003/sse"
}
}
}Настройка Cherry Studio
Откройте Cherry Studio
Перейдите в Настройки → MCP Servers → Добавить сервер
Настройте параметры:
Название:
mermaid-mcp-server-png-pdf-jpg-svgОписание:
Сервис генерации диаграмм MermaidТип:
STDIOКоманда:
uvxПараметры:
mermaid-mcp-server-png-pdf-jpg-svg
Нажмите «Сохранить» и включите

Настройка Claude Desktop
Добавьте в файл claude_desktop_config.json:
{
"mcpServers": {
"mermaid-mcp-server-png-pdf-jpg-svg": {
"command": "uvx",
"args": [
"mermaid-mcp-server-png-pdf-jpg-svg"
]
}
}
}Настройка Continue.dev
Добавьте в файл config.json:
{
"mcpServers": {
"mermaid-mcp-server-png-pdf-jpg-svg": {
"command": "uvx",
"args": [
"mermaid-mcp-server-png-pdf-jpg-svg"
]
}
}
}Запуск сервиса
Режим STDIO (рекомендуется для настольных клиентов)
uv run python main.pyРежим SSE (для сетевых подключений)
uv run python main.py --sseОписание конфигурации
Настройка переменных окружения
Имя переменной | Описание | Значение по умолчанию |
| Адрес сервера |
|
| Порт сервера |
|
| Уровень журналирования |
|
| Адрес Mermaid API |
|
| Время ожидания запроса (секунды) |
|
| Режим отладки |
|
| Режим разработки |
|
Доступные инструменты
1. convert_mermaid_to_image
Преобразует код диаграммы Mermaid в файлы изображений различных форматов
Параметры:
mermaid_code(string): код диаграммы Mermaidoutput_format(string, необязательно): формат вывода, поддерживаются png, jpg, svg, pdf, по умолчанию "png"theme(string, необязательно): стиль темы, поддерживаются default, dark, neutral, forest, по умолчанию "default"background_color(string, необязательно): цвет фона, шестнадцатеричный кодwidth(number, необязательно): ширина изображения (пиксели)height(number, необязательно): высота изображения (пиксели)
Поддерживаемые форматы вывода: PNG, JPG, SVG, PDF
2. validate_mermaid_syntax
Проверяет корректность синтаксиса кода диаграммы Mermaid
Параметры:
mermaid_code(string): код диаграммы Mermaid для проверки
Результат:
valid(boolean): прошла ли проверкаerror_message(string): сообщение об ошибке (если проверка не пройдена)
3. get_supported_options
Получает поддерживаемые параметры конвертера
Результат:
themes(array): список поддерживаемых темformats(array): список поддерживаемых форматов
Поддерживаемые типы диаграмм
Блок-схема (Flowchart): для представления процессов и алгоритмов
Диаграмма последовательности (Sequence Diagram): для представления взаимодействия между объектами
Диаграмма Ганта (Gantt Chart): для управления сроками проекта
Круговая диаграмма (Pie Chart): для представления долей данных
Git-граф (Git Graph): для представления истории коммитов Git
Интеллект-карта (Mind Map): для представления структуры знаний
Диаграмма классов (Class Diagram): для представления структуры классов
Примеры использования
Пример блок-схемы
请使用 convert_mermaid_to_image 工具生成一个流程图:
flowchart TD
A[开始] --> B{判断条件}
B -->|是 | C[执行动作 1]
B -->|否 | D[执行动作 2]
C --> E[结束]
D --> EПример диаграммы последовательности
请使用 convert_mermaid_to_image 工具生成一个时序图,使用深色主题:
sequenceDiagram
participant 用户
participant 系统
participant 数据库
用户->>系统:登录请求
系统->>数据库:验证用户
数据库-->>系统:返回结果
系统-->>用户:登录成功Пример проверки синтаксиса
首先使用 validate_mermaid_syntax 验证语法,然后使用 convert_mermaid_to_image 生成图表Примеры ресурсов
Получение примеров диаграмм
Вы можете получить примеры диаграмм различных типов по следующим URI ресурсов:
mermaid://examples/flowchart— пример блок-схемыmermaid://examples/sequence— пример диаграммы последовательностиmermaid://examples/gantt— пример диаграммы Гантаmermaid://examples/pie— пример круговой диаграммыmermaid://examples/gitgraph— пример Git-графаmermaid://examples/mindmap— пример интеллект-картыmermaid://examples/class— пример диаграммы классов
Структура проекта
mermaid_mcp_server/
├── mermaid_mcp_server/ # 核心模块
│ ├── __init__.py
│ └── main.py # 主程序入口
├── requirements.txt # 依赖列表(pip)
├── pyproject.toml # 项目配置(uv)
├── .env.example # 环境变量示例
├── README.md # 项目文档
└── .vscode/ # VSCode 配置
└── settings.jsonРуководство для разработчиков
Локальная разработка
# 克隆仓库
git clone https://github.com/wwwzhouhui/mermaid_mcp_server.git
cd mermaid_mcp_server
# 安装依赖
uv sync
# 配置环境变量
cp .env.example .env
# 启动服务(STDIO 模式)
uv run python main.py
# 启动服务(SSE 模式)
uv run python main.py --sseРежим отладки
Включение подробного вывода журнала:
export LOG_LEVEL=DEBUG
uv run python main.pyЧасто задаваемые вопросы
О:
Проверьте сетевое подключение и настройки брандмауэра
Убедитесь, что mermaid.ink API доступен
Проверьте настройки прокси
О:
Используйте инструмент validate_mermaid_syntax для проверки синтаксиса
Обратитесь к официальной документации Mermaid
Используйте код из примеров ресурсов
О:
Упростите содержимое диаграммы
Разделите на несколько небольших диаграмм
Настройте параметры размера изображения
О:
Установите менеджер пакетов uv:
curl -LsSf https://astral.sh/uv/install.sh | shИли установите пакет глобально с помощью pip
Проверьте переменную окружения PATH
О:
Убедитесь, что сервис запущен в режиме SSE
Проверьте, не занят ли порт 8003
Убедитесь, что URL настроен правильно
О:
Увеличьте параметры размера изображения
Выберите подходящую тему
Оптимизируйте структуру кода Mermaid
О:
Проверьте скорость сетевого подключения
Увеличьте переменную окружения REQUEST_TIMEOUT
Упростите сложность диаграммы
О:
Убедитесь, что название темы написано правильно
Проверьте, поддерживается ли эта тема
Попробуйте использовать другое название темы
О:
Используйте параметр background_color
Формат — шестнадцатеричный код цвета (например, #FFFFFF)
Поддерживается только для некоторых форматов вывода
Техническое сообщество
Приглашаем присоединиться к техническому сообществу, делиться опытом использования и оставлять отзывы:

Контакты автора
WeChat: laohaibao2025
Эл. почта: 75271002@qq.com

Поддержка проекта
Если этот проект оказался для вас полезным, вы можете угостить меня чашечкой кофе ☕
WeChat Pay

Star History
Если проект вам понравился, поставьте звёздочку ⭐
Лицензия
Лицензия MIT
Журнал обновлений
v0.1.0 (текущая версия)
✅ Выпущена начальная версия
✅ Поддержка многоформатного вывода PNG, JPG, SVG, PDF
✅ Интегрированы четыре стиля тем (default, dark, neutral, forest)
✅ Предоставлены функции проверки синтаксиса и примеров ресурсов
✅ Поддержка двух режимов связи: STDIO и SSE
v0.0.3 (2025-07-21)
✅ Выпущена начальная версия
✅ Поддержка многоформатного преобразования диаграмм
✅ Функция проверки синтаксиса
✅ Функция примеров ресурсов
Руководство по внесению вклада
Приглашаем отправлять Issue и Pull Request для улучшения этого проекта!
Сделайте форк этого репозитория
Создайте ветку функции:
git checkout -b feature/amazing-featureЗафиксируйте изменения:
git commit -m 'Add amazing feature'Отправьте в ветку:
git push origin feature/amazing-featureОтправьте Pull Request
Примечания
Генерация диаграммы может занять несколько секунд, пожалуйста, подождите
Убедитесь, что сетевое подключение работает, сервис зависит от онлайн-API mermaid.ink
Сгенерированные данные изображения возвращаются в формате base64
Сложные диаграммы могут требовать больше времени на генерацию
Наслаждайтесь созданием красивых диаграмм с Mermaid! 🎨✨
Available Tools
3 toolsconvert_mermaid_to_imageA
将 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: 图像高度(像素,可选)
返回:
包含转换后图像数据和元数据的字典
| Name | Required | Description | Default |
|---|---|---|---|
| mermaid_code | Yes | ||
| output_format | No | png | |
| theme | No | default | |
| background_color | No | ||
| width | No | ||
| height | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
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.
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.
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.
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.
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.
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.
get_supported_optionsA
获取转换器支持的选项,如图表主题和输出格式。
返回:
一个包含支持的主题和格式列表的字典。
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden. It discloses that the tool returns a dictionary with lists of supported themes and formats, which adds behavioral context beyond the input schema (which has no parameters). However, it doesn't cover other traits like performance, error handling, or authentication needs, leaving gaps in transparency for a tool with no annotation support.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is highly concise and well-structured: two sentences that directly state the purpose and return value, with no wasted words. It's front-loaded with the core function, and every sentence adds essential information, making it efficient for an agent to parse.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's low complexity (0 parameters, no annotations, but with an output schema), the description is reasonably complete. It explains what the tool does and the return format, which complements the output schema. However, it lacks usage context and some behavioral details, preventing a perfect score despite the structured support.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The tool has 0 parameters, and the input schema description coverage is 100% (with an empty schema). The description doesn't need to add parameter semantics, so it appropriately focuses on the return value. Since there are no parameters to document, a baseline score of 4 is justified, as the description doesn't introduce confusion or redundancy.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool's purpose: '获取转换器支持的选项,如图表主题和输出格式' (Get converter-supported options, such as chart themes and output formats). It specifies both the action ('获取' - get) and the resource ('支持的选项' - supported options), with concrete examples. However, it doesn't explicitly differentiate from sibling tools like 'convert_mermaid_to_image' or 'validate_mermaid_syntax', which prevents a score of 5.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides no guidance on when to use this tool versus alternatives. It doesn't mention sibling tools or suggest scenarios where this tool is appropriate (e.g., before conversion to check available options). Without any usage context or exclusions, it relies on implicit understanding, which is insufficient for clear agent decision-making.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
validate_mermaid_syntaxB
通过尝试简单转换来验证 Mermaid 图表语法。
参数:
mermaid_code: 要验证的 Mermaid 图表语法代码
返回:
包含验证结果的字典
| Name | Required | Description | Default |
|---|---|---|---|
| mermaid_code | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions '尝试简单转换' (attempting simple conversion) as the validation method, which implies a read-only, non-destructive operation, but doesn't clarify error handling, performance implications, or what '简单转换' entails. For a tool with zero annotation coverage, this leaves significant gaps in understanding its behavior.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is extremely concise and well-structured: a purpose statement followed by clear parameter and return sections in bullet-like format. Every sentence earns its place without redundancy, and it's front-loaded with the core functionality. The bilingual presentation (Chinese purpose, English labels) is efficient for clarity.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's low complexity (single parameter, no nested objects) and the presence of an output schema (which handles return values), the description is reasonably complete. It covers purpose, parameter semantics, and return type at a high level. However, it lacks usage guidelines and detailed behavioral context, which are minor gaps in this simple validation context.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The description explicitly documents the single parameter 'mermaid_code' as '要验证的 Mermaid 图表语法代码' (Mermaid diagram syntax code to validate), adding meaning beyond the schema's basic title 'Mermaid Code'. However, with schema description coverage at 0%, it doesn't provide format details, constraints, or examples. The baseline is 3 since it compensates somewhat but not fully for the schema's lack of descriptions.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool's purpose as '验证 Mermaid 图表语法' (validate Mermaid diagram syntax) and specifies the method '通过尝试简单转换' (by attempting simple conversion). It distinguishes from sibling tools like 'convert_mermaid_to_image' by focusing on validation rather than conversion to image format. However, it doesn't explicitly differentiate from 'get_supported_options' which might relate to syntax options.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides no guidance on when to use this tool versus alternatives. It doesn't mention sibling tools 'convert_mermaid_to_image' or 'get_supported_options', nor does it specify scenarios where validation is preferred over direct conversion or option checking. There's no indication of prerequisites or exclusions for usage.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
3 tool updates
- First observed
convert_mermaid_to_image - First observed
get_supported_options - First observed
validate_mermaid_syntax
TDQS
Scored across 3 tools
Each tool has a clearly distinct purpose: convert_mermaid_to_image handles the core conversion functionality, get_supported_options provides metadata about available options, and validate_mermaid_syntax performs syntax validation. There is no overlap or ambiguity between these three functions.
All tools follow a consistent snake_case naming pattern with clear verb-action structure: convert_mermaid_to_image, get_supported_options, and validate_mermaid_syntax. The naming is predictable and follows the same convention throughout.
Three tools is a reasonable number for a Mermaid diagram conversion server, though it feels slightly minimal. The tools cover the essential operations (convert, validate, get options), but additional utilities like listing available themes or handling diagram editing might enhance completeness.
The tool set covers the core Mermaid conversion workflow well: conversion, syntax validation, and option discovery. Minor gaps include operations like batch conversion, diagram editing utilities, or theme management, but agents can work effectively with the provided tools for most use cases.
Maintenance
Related MCP Connectors
A Model Context Protocol server for Wix AI tools
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
Generate dynamic Mermaid diagrams and charts with AI assistance. Customize styles and export diagr…
Render, verify, describe, and safely edit Mermaid diagrams through MCP.
Related MCP Servers
- AlicenseBqualityCmaintenanceA Model Context Protocol (MCP) server that converts Mermaid diagrams to PNG images.1109 npm234MIT
- AlicenseBqualityCmaintenanceA Model Context Protocol server that validates and renders Mermaid diagrams.1183 npm57MIT
- AlicenseNot gradedqualityNot gradedmaintenanceA server that implements the Model Context Protocol (MCP), providing an interface for LLM applications to generate mermaid.js visualizations and diagrams.MIT
- FlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that converts SVG code to PNG images, offering two conversion methods (CairoSVG and Inkscape) with support for custom working directories.3-