mermaid-mcp-server
Сервер MCP Mermaid
Сервер Model Context Protocol (MCP), который преобразует диаграммы Mermaid в изображения PNG. Этот сервер позволяет помощникам ИИ и другим приложениям генерировать визуальные диаграммы из текстовых описаний с использованием синтаксиса разметки Mermaid.
Функции
Преобразует код диаграммы Mermaid в изображения PNG
Поддерживает несколько тем диаграмм (по умолчанию, лесная, темная, нейтральная)
Настраиваемые цвета фона
Использует Puppeteer для высококачественного рендеринга headless-браузера
Реализует протокол MCP для бесшовной интеграции с помощниками на основе искусственного интеллекта.
Гибкие возможности вывода: возврат изображений напрямую или сохранение на диск
Обработка ошибок с подробными сообщениями об ошибках
Related MCP server: Mermaid MCP Server
Как это работает
Сервер использует Puppeteer для запуска headless-браузера, рендеринга диаграммы Mermaid в SVG и захвата скриншота рендеринговой диаграммы. Процесс включает в себя:
Запуск экземпляра headless-браузера
Создание HTML-шаблона с кодом Mermaid
Загрузка библиотеки Mermaid.js
Рендеринг диаграммы в SVG
Сделать снимок экрана с отрендеренным SVG в формате PNG
Либо вернуть изображение напрямую, либо сохранить его на диске
Строить
npx tscИспользование
Использовать с настольным компьютером Claude
"mcpServers": {
"mermaid": {
"command": "npx",
"args": [
"-y @peng-shawn/mermaid-mcp-server"
]
}
}Использовать с курсором и Cline
env CONTENT_IMAGE_SUPPORTED=false npx -y @peng-shawn/mermaid-mcp-serverСписок диаграмм русалок можно найти в ./diagrams , они создаются с помощью агента Cursor с подсказкой: «создать диаграммы русалок и сохранить их в отдельной папке диаграмм, объясняющей, как работает renderMermaidPng».
Бегите с инспектором
Запустите сервер с инспектором для тестирования и отладки:
npx @modelcontextprotocol/inspector node dist/index.jsСервер запустится и будет прослушивать stdio на предмет сообщений протокола MCP.
Подробнее об инспекторе можно узнать здесь .
Установка через Smithery
Чтобы автоматически установить Mermaid Diagram Generator для Claude Desktop через Smithery :
npx -y @smithery/cli install @peng-shawn/mermaid-mcp-server --client claudeСреды Docker и Smithery
При запуске в контейнерах Docker (в том числе через Smithery) вам может потребоваться обработка зависимостей Chrome:
Теперь сервер пытается использовать встроенный браузер Puppeteer по умолчанию.
Если вы столкнулись с ошибками, связанными с браузером, у вас есть два варианта:
Вариант 1: Во время сборки образа Docker:
Установите
PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=trueпри установке PuppeteerУстановите Chrome/Chromium в свой Docker-контейнер
Установите
PUPPETEER_EXECUTABLE_PATHво время выполнения, чтобы указать на установку Chrome
Вариант 2: использование встроенного Chrome от Puppeteer:
Убедитесь, что ваш Docker-контейнер имеет необходимые зависимости для Chrome
Не нужно устанавливать
PUPPETEER_SKIP_CHROMIUM_DOWNLOADКод будет автоматически использовать встроенный браузер.
Для пользователей Smithery последняя версия должна работать без дополнительной настройки.
API
Сервер предоставляет единственный инструмент:
generate: Преобразует код диаграммы Mermaid в изображение PNGПараметры:
code: Код диаграммы русалки для визуализацииtheme: (необязательно) Тема для диаграммы. Варианты: "default", "forest", "dark", "neutral"backgroundColor: (необязательно) Цвет фона для диаграммы, например, «белый», «прозрачный», «#F0F0F0»name: Имя сгенерированного файла (обязательно, если CONTENT_IMAGE_SUPPORTED=false)folder: абсолютный путь для сохранения изображения (обязательно, если CONTENT_IMAGE_SUPPORTED=false)
Поведение инструмента generate зависит от переменной среды CONTENT_IMAGE_SUPPORTED :
Если
CONTENT_IMAGE_SUPPORTED=true(по умолчанию): инструмент возвращает изображение непосредственно в ответе.Когда
CONTENT_IMAGE_SUPPORTED=false: инструмент сохраняет изображение в указанной папке и возвращает путь к файлу.
Переменные среды
CONTENT_IMAGE_SUPPORTED: управляет тем, будут ли изображения возвращаться непосредственно в ответе или сохраняться на диске.true(по умолчанию): изображения возвращаются непосредственно в ответе.false: Изображения сохраняются на диск, требуя параметрыnameиfolder
Примеры
Базовое использование
// Generate a flowchart with default settings
{
"code": "flowchart TD\n A[Start] --> B{Is it?}\n B -->|Yes| C[OK]\n B -->|No| D[End]"
}С темой и цветом фона
// Generate a sequence diagram with forest theme and light gray background
{
"code": "sequenceDiagram\n Alice->>John: Hello John, how are you?\n John-->>Alice: Great!",
"theme": "forest",
"backgroundColor": "#F0F0F0"
}Сохранение на диск (когда CONTENT_IMAGE_SUPPORTED=false)
// Generate a class diagram and save it to disk
{
"code": "classDiagram\n Class01 <|-- AveryLongClass\n Class03 *-- Class04\n Class05 o-- Class06",
"theme": "dark",
"name": "class_diagram",
"folder": "/path/to/diagrams"
}Часто задаваемые вопросы
Разве Claude Desktop уже не поддерживает русалку через холст?
Да, но он не поддерживает параметры theme и backgroundColor . Плюс, наличие выделенного сервера упрощает создание диаграмм русалок с помощью разных клиентов MCP.
Почему мне нужно указывать CONTENT_IMAGE_SUPPORTED=false при использовании с курсором?
Курсор пока не поддерживает встроенные изображения в ответах.
Издательский
В этом проекте используются действия GitHub для автоматизации процесса публикации в npm.
Метод 1: Использование сценария выпуска (рекомендуется)
Убедитесь, что все ваши изменения зафиксированы и отправлены.
Запустите скрипт релиза либо с определенным номером версии, либо с семантическим приращением версии:
# Using a specific version number npm run release 0.1.4 # Using semantic version increments npm run release patch # Increments the patch version (e.g., 0.1.3 → 0.1.4) npm run release minor # Increments the minor version (e.g., 0.1.3 → 0.2.0) npm run release major # Increments the major version (e.g., 0.1.3 → 1.0.0)Сценарий будет:
Проверить формат версии или семантическое приращение
Проверьте, находитесь ли вы на основной ветке
Обнаружение и предупреждение о несоответствии версий между файлами
Последовательно обновите все ссылки на версии (package.json, package-lock.json и index.ts)
Создайте единый коммит со всеми изменениями версии
Создайте и отправьте тег git
Затем рабочий процесс GitHub автоматически выполнит сборку и опубликует в npm.
Метод 2: Ручной процесс
Обновите свой код и зафиксируйте изменения.
Создайте и отправьте новый тег с номером версии:
git tag v0.1.4 # Use the appropriate version number git push origin v0.1.4Рабочий процесс GitHub автоматически:
Построить проект
Опубликовать в npm с версией из тега
Примечание: Вам необходимо настроить секрет NPM_TOKEN в настройках вашего репозитория GitHub. Для этого:
Сгенерируйте токен доступа npm с разрешениями на публикацию
Перейдите в свой репозиторий GitHub → Настройки → Секреты и переменные → Действия.
Создайте новый секрет репозитория с именем
NPM_TOKEN, используя ваш токен npm в качестве значения.
Значки
Лицензия
Массачусетский технологический институт
Available Tools
1 toolgenerateC
Generate PNG image or SVG from mermaid markdown
| Name | Required | Description | Default |
|---|---|---|---|
| backgroundColor | No | Background color for the diagram, e.g. 'white', 'transparent', '#F0F0F0' (optional) | |
| code | Yes | The mermaid markdown to generate an image from | |
| folder | No | Absolute path to save the image to (optional) | |
| name | No | Name of the diagram (optional) | |
| outputFormat | No | Output format for the diagram (optional, defaults to 'png') | |
| theme | No | Theme for the diagram (optional) |
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 of behavioral disclosure. It mentions the tool generates images from mermaid markdown but doesn't cover important behavioral aspects like file system interactions (saving to a folder), performance characteristics, error handling, or any side effects. For a tool that writes files, this is a significant gap in transparency.
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—a single sentence that directly states the tool's function without any fluff. It's front-loaded and efficiently communicates the core purpose, making it easy for an agent to parse quickly.
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, file output, no output schema) and lack of annotations, the description is insufficient. It doesn't explain what the tool returns, how errors are handled, or the implications of optional parameters like 'folder'. For a generative tool with file system operations, more context is needed for safe and effective use.
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 schema description coverage is 100%, meaning all parameters are well-documented in the schema itself. The description doesn't add any meaningful parameter semantics beyond what's already in the schema (e.g., it doesn't explain parameter interactions or provide examples). This meets the baseline for high schema coverage but doesn't enhance understanding.
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: 'Generate PNG image or SVG from mermaid markdown'. It specifies the verb ('Generate'), resource ('PNG image or SVG'), and source material ('mermaid markdown'), making the function unambiguous. However, since there are no sibling tools mentioned, it doesn't need to distinguish from alternatives, so it doesn't reach the highest 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, prerequisites, or context. It simply states what the tool does without indicating scenarios where it's appropriate or any limitations. This lack of usage context leaves the agent without operational guidance.
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.
1 tool update
v1.0.0- First observed
generate
TDQS
Scored across 1 tool
With only one tool, there is no possibility of ambiguity or overlap between tools. The tool's purpose is clearly defined and distinct by default.
A single tool inherently has perfect naming consistency, as there are no other tools to compare against. The name 'generate' is simple and follows a verb-based pattern.
One tool is too few for a server's purpose, as it severely limits functionality and suggests the server is under-scoped. A typical MCP server should offer multiple operations to handle a domain comprehensively.
The tool surface is severely incomplete for a mermaid diagramming domain. It only provides generation, missing essential operations like validation, editing, listing diagram types, or managing diagram states, which are necessary for agent workflows.
Maintenance
Related MCP Connectors
Render, verify, describe, and safely edit Mermaid diagrams through MCP.
Collaborative whiteboard MCP server — create objects, connectors, C4 diagrams, and manage boards
Create and manage Mermaid.js flowcharts and diagrams with AI agents via MCP.
MCP server for generating rough-draft project plans from natural-language prompts.
Related MCP Servers
- AlicenseBqualityCmaintenanceA Model Context Protocol server that validates and renders Mermaid diagrams.1186 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
- AlicenseAqualityBmaintenanceA Model Context Protocol server that converts Mermaid diagram code into various image formats (PNG, JPG, SVG, PDF) with theme customization options for AI clients.39MIT
- AlicenseAqualityDmaintenanceAn MCP server that generates diagrams from Mermaid code in multiple formats (PNG, PDF, SVG).21MIT