Установка
SKILL.md
Draw.io Diagram Skill
Generate draw.io diagrams as native .drawio files. Author each diagram either as Mermaid (concise text that the draw.io desktop CLI converts and lays out for you) or as draw.io XML directly. Optionally auto-layout XML-authored diagrams with ELK, export to PNG/SVG/PDF with the diagram XML embedded (so the exported file stays editable in draw.io), or generate a browser URL that opens the diagram directly in the draw.io editor.
Authoring: Mermaid or XML?
The desktop CLI can convert Mermaid to a native .drawio file, so prefer Mermaid for the diagram types it handles well — its parser lays the diagram out automatically, which is far more reliable than hand-positioning cells in XML.
| Author as | Best for | Needs desktop CLI? |
|---|---|---|
| Mermaid | Flowcharts, sequence, class, state, ER, gantt, mindmap, timeline, user journey, quadrant, C4, git graph, pie, and other standard types | Yes — to convert to .drawio |
| XML | Custom styling, precise/hand positioning, specific shape libraries (AWS, Azure, network, UML detail…), or when the desktop CLI is not installed | No (optional ELK --layout needs the CLI) |
- Prefer Mermaid when the desktop CLI is available and the request is one of the standard types above — write terse Mermaid and let draw.io lay it out.
- Use XML for precise control, or as the universal fallback: XML needs no CLI at all, so it's the only option when the desktop app isn't installed (output a
.drawiofile or aurl). - For XML-authored diagrams you can ask the CLI to apply an ELK auto-layout (
--layout) instead of computing coordinates yourself — the same layouts the draw.io editor's Arrange ▸ Layout menu applies, and the same engine the draw.io MCP app server uses. See ELK layout for XML.
If you're unsure whether the desktop CLI is present, detect it first (see Locating the CLI). No CLI → author as XML and deliver a .drawio file or a url.
The pipeline
Every diagram becomes a native .drawio file first, then is delivered in the requested output format. This keeps the delivery step identical whether you authored Mermaid or XML.
- Author →
.drawio- Mermaid: write the Mermaid to a
.mmdfile, then convert it with the CLI:<!-- -->
<!-- -->Delete thedrawio -x -f xml -o diagram.drawio diagram.mmd.mmdafterward — the.drawiois the artifact. draw.io's Mermaid parser has already laid the diagram out, so no--layoutis needed. - XML: write the mxGraphModel XML to
diagram.drawio(see XML format). Optionally apply an ELK layout (see ELK layout for XML).
- Mermaid: write the Mermaid to a
- Deliver (identical for both sources):<!-- -->
- (no format) → keep
diagram.drawioand open it. - png / svg / pdf → export from the
.drawiowith embedded XML, then delete the source.drawio:<!-- -->drawio -x -f png -e -b 10 -o diagram.drawio.png diagram.drawio - url → build a browser URL from the
.drawioXML, open it, and keep the.drawioas a local copy (see Browser URL output).
- (no format) → keep
- Open the result — the exported file, the URL, or the
.drawio. If the open command fails, print the absolute path (or URL) so the user can open it manually.
Always convert Mermaid to .drawio first, then export — do not export a .mmd straight to an image. Direct Mermaid → PNG export with -e is broken in current draw.io Desktop (the embedded-XML step crashes); the two-step path (convert, then export the .drawio) is reliable and produces an editable embed. See Troubleshooting.
If Mermaid was requested but no desktop CLI is available, fall back to authoring the same diagram directly as XML.
ELK layout for XML
XML-authored diagrams can be auto-positioned by the CLI's --layout pass — the same ELK layouts as the editor's Arrange ▸ Layout menu and the same engine the draw.io MCP app server uses. Generate the cells with approximate (or even 0,0) positions and let ELK place them; you only have to get the graph structure — nodes and edges — right.
Add --layout <name> to any CLI call that reads your XML. The simplest form lays out in place after you write the file (reading and overwriting the same path is supported):
drawio -x -f xml --layout verticalFlow -o diagram.drawio diagram.drawio
Or combine layout with export in a single call (works for XML input):
drawio -x -f png -e -b 10 --layout verticalFlow -o diagram.drawio.png diagram.drawio
Layout presets
| Name | Layout |
|---|---|
verticalFlow | Layered, top-to-bottom — flowcharts, pipelines |
horizontalFlow | Layered, left-to-right |
verticalTree | Tree, top-down — hierarchies, org charts |
horizontalTree | Tree, left-to-right |
radialTree | Radial tree |
organic | Force-directed — networks, mind-map-like graphs |
Custom layout JSON
For finer control, pass a JSON array (starting with [) instead of a preset name — the same format as the editor's custom-layout dialog:
drawio -x -f xml --layout '[{"layout":"elkLayered","config":{"elk.direction":"RIGHT"}}]' -o diagram.drawio diagram.drawio
Each entry is {"layout": <algorithm>, "config": { … }}:
- Algorithms:
elkLayered,elkTree,elkRadial,elkOrganic,elkStress,elkBox. config: keys starting withelk.are ELK options — e.g.elk.direction(UP/DOWN/LEFT/RIGHT),elk.spacing.nodeNode,elk.layered.spacing.nodeNodeBetweenLayers. The keysedgeStyle(e.g.orthogonal) andcorners(e.g.rounded) control connector rendering.
Orthogonal edge routing
--layout libavoid routes the edges orthogonally around the shapes (the editor's Arrange ▸ Layout ▸ Orthogonal Routing) without moving any vertex — the complement of the node layouts above. Use it as an in-place pass on hand-positioned XML whose connectors cross shapes:
drawio -x -f xml --layout libavoid -o diagram.drawio diagram.drawio
Skip it after a flow/tree preset — those already route their edges.
When to use it: author the graph structure as XML without worrying about coordinates, then apply verticalFlow / horizontalFlow for flow-style diagrams or organic for networks. Mermaid-authored diagrams are already laid out — don't add --layout.
Mermaid syntax reference
When authoring Mermaid, fetch and follow the shared Mermaid reference (all supported diagram types plus flowchart styling — style, classDef, linkStyle):
https://raw.githubusercontent.com/jgraph/drawio-mcp/main/shared/mermaid-reference.md
Match the language of the diagram labels to the user's language.
Choosing the output format
Check the user's request for a format preference. Examples:
/drawio:drawio create a flowchart→ Mermaid →flowchart.drawio/drawio:drawio png flowchart for login→ Mermaid →login-flow.drawio.png/drawio:drawio svg: ER diagram→ Mermaid →er-diagram.drawio.svg/drawio:drawio pdf AWS architecture overview→ XML (needs AWS shapes) →architecture-overview.drawio.pdf/drawio:drawio url flowchart for user login→ opens browser atapp.diagrams.netwith the diagram, keepslogin-flow.drawiolocally
If no format is mentioned, just produce the .drawio file and open it in draw.io. The user can always ask to export later.
Supported export formats
| Format | Embed XML | Notes |
|---|---|---|
png | Yes (-e) | Viewable everywhere, editable in draw.io |
svg | Yes (-e) | Scalable, editable in draw.io |
pdf | Yes (-e) | Printable, editable in draw.io |
jpg | No | Lossy, no embedded XML support |
PNG, SVG, and PDF all support --embed-diagram — the exported file contains the full diagram XML, so opening it in draw.io recovers the editable diagram.
Browser URL output
When the user requests url format, generate a draw.io URL that opens the diagram directly in the browser editor at app.diagrams.net — no draw.io Desktop required to view it. (Mermaid-authored diagrams still need the desktop CLI to convert to .drawio first; if no CLI is available, author the diagram as XML and build the URL from that.)
How it works
- The
.drawiofile is written to disk as usual (gives the user a persistent local copy they can re-edit) - The XML is compressed with Node.js's built-in
zliband base64-encoded - The result is embedded in a
https://app.diagrams.net/#create=...URL - The URL is opened in the default browser
This uses only Node.js built-in modules (zlib, child_process) — no external dependencies.
URL generation
Run this node -e one-liner to read the .drawio file and print the URL (replace DIAGRAM.drawio with the actual filename):
URL=$(node -e '
const fs = require("fs");
const zlib = require("zlib");
const xml = fs.readFileSync(process.argv[1], "utf8");
const compressed = zlib.deflateRawSync(encodeURIComponent(xml)).toString("base64");
const payload = encodeURIComponent(JSON.stringify({ type: "xml", compressed: true, data: compressed }));
console.log("https://app.diagrams.net/?grid=0&pv=0&border=10&edit=_blank#create=" + payload);
' "DIAGRAM.drawio")
The URL format matches the MCP Tool Server. Node.js's zlib.deflateRawSync and pako.deflateRaw both implement RFC 1951 and produce identical output, so URLs from either source are interchangeable.
Opening the URL
| Environment | Command |
|---|---|
| macOS | open "$URL" |
| Linux (native) | xdg-open "$URL" |
| WSL2 | Write a temp .url file, open via cmd.exe (see below) |
| Windows (native) | Write a temp .url file, open via start (see below) |
Why the .url workaround on Windows/WSL2? cmd.exe's start command treats & as a command separator and strips everything after # in URLs. The diagram payload lives in the #create=... fragment, so passing the URL directly causes it to be silently lost. A .url shortcut file preserves the URL intact.
macOS / Linux example:
open "$URL" # macOS
xdg-open "$URL" # Linux
WSL2 example:
TMPFILE=$(mktemp --suffix=.url)
printf '[InternetShortcut]\r\nURL=%s\r\n' "$URL" > "$TMPFILE"
cmd.exe /c start "" "$(wslpath -w "$TMPFILE")"
Windows (native) example:
Do not build the .url file with echo URL=%URL%. The generated URL contains & characters (?grid=0&pv=0&...) that cmd.exe treats as command separators, so the shortcut is written truncated and the diagram payload is lost — the exact failure the .url file is meant to prevent. Let Node write the file directly (it already holds the URL string) and open only the resulting path, which never contains &:
TMPFILE=$(node -e '
const fs = require("fs");
const os = require("os");
const path = require("path");
const p = path.join(os.tmpdir(), "drawio.url");
fs.writeFileSync(p, "[InternetShortcut]\r\nURL=" + process.argv[1] + "\r\n");
process.stdout.write(p);
' "$URL")
cmd.exe /c start "" "$TMPFILE"
After opening
Print the URL so the user can copy or share it, and confirm the local file path:
Opened in browser: <URL>
Local file: DIAGRAM.drawio
The .drawio file stays on disk so the user can re-edit it later, attach it elsewhere, or export it to an image format on demand.
URL length
The URL embeds the full compressed diagram in its hash fragment. Very large diagrams may hit browser URL length limits (typically ~32K–2MB depending on the browser). For complex diagrams that exceed the limit, fall back to writing the .drawio file and opening it locally.
draw.io CLI
The draw.io desktop app includes a command-line interface used for converting Mermaid to .drawio, applying ELK layouts (--layout), and exporting to PNG/SVG/PDF. All three require the desktop app to be installed.
Locating the CLI
First, detect the environment, then locate the CLI accordingly:
WSL2 (Windows Subsystem for Linux)
WSL2 is detected when /proc/version contains microsoft or WSL:
grep -qi microsoft /proc/version 2>/dev/null && echo "WSL2"
On WSL2, use the Windows draw.io Desktop executable via /mnt/c/...:
DRAWIO_CMD="/mnt/c/Program Files/draw.io/draw.io.exe"
Double-quote the path so the space in Program Files is treated as part of the path. Do not wrap it in backticks — in bash, backticks are command substitution, which would try to execute the binary at locate-time instead of storing its path.
If draw.io is installed in a non-default location, check common alternatives:
# Default install path
"/mnt/c/Program Files/draw.io/draw.io.exe"
# Per-user install (if the above does not exist)
"/mnt/c/Users/$WIN_USER/AppData/Local/Programs/draw.io/draw.io.exe"
macOS
/Applications/draw.io.app/Contents/MacOS/draw.io
Linux (native)
drawio # typically on PATH via snap/apt/flatpak
Windows (native, non-WSL2)
"C:\Program Files\draw.io\draw.io.exe"
Use which drawio (or where draw.io on Windows) to check if it's on PATH before falling back to the platform-specific path.
Convert / layout / export commands
Convert Mermaid to .drawio:
drawio -x -f xml -o diagram.drawio diagram.mmd
Apply an ELK layout to XML (see ELK layout for XML):
drawio -x -f xml --layout verticalFlow -o diagram.drawio diagram.drawio
Export to an image format:
drawio -x -f <format> -e -b 10 -o "<output>" "<input.drawio>"
WSL2 export example:
"/mnt/c/Program Files/draw.io/draw.io.exe" -x -f png -e -b 10 -o "diagram.drawio.png" "diagram.drawio"
Key flags:
-x/--export: export mode (also used for Mermaid conversion and layout passes)-f/--format: output format (xml, png, svg, pdf, jpg) — usexmlto produce a.drawiofrom Mermaid or a layout pass--layout: run a layout before writing the output — an ELK preset name, thelibavoidedge-routing pass, or a custom-layout JSON array--mermaid-image 1: convert Mermaid to a single static SVG image cell (the Mermaid source stays on the cell for re-editing) instead of an editable diagram — only when the user explicitly asks for a non-editable image cell-e/--embed-diagram: embed diagram XML in the output (PNG, SVG, PDF only)-o/--output: output file path-b/--border: border width around diagram (default: 0)-t/--transparent: transparent background (PNG only)-s/--scale: scale the diagram size--width/--height: fit into specified dimensions (preserves aspect ratio)-a/--all-pages: export all pages (PDF only)-p/--page-index: select a specific page (1-based)
Opening the result
| Environment | Command |
|---|---|
| macOS | open <file> |
| Linux (native) | xdg-open <file> |
| WSL2 | cmd.exe /c start "" "$(wslpath -w <file>)" |
| Windows | start <file> |
WSL2 notes:
wslpath -w <file>converts a WSL2 path (e.g./home/user/diagram.drawio) to a Windows path (e.g.C:\Users\...). This is required becausecmd.execannot resolve/mnt/c/...style paths.- The empty string
""afterstartis required to preventstartfrom interpreting the filename as a window title.
WSL2 example:
cmd.exe /c start "" "$(wslpath -w diagram.drawio)"
File naming
- Use a descriptive filename based on the diagram content (e.g.,
login-flow,database-schema) - Use lowercase with hyphens for multi-word names
- When authoring Mermaid, write it to a matching
.mmdfile, convert to.drawio, then delete the.mmd— the.drawiois the artifact - For export, use double extensions:
name.drawio.png,name.drawio.svg,name.drawio.pdf— this signals the file contains embedded diagram XML - After a successful export, delete the intermediate
.drawiofile — the exported file contains the full diagram - For
urlmode, keep the.drawiofile (no double extension) — the URL is a view/edit handle and the local file is the persistent copy
XML format
A .drawio file is native mxGraphModel XML. When authoring as XML, generate it directly; Mermaid is converted to this same format by the CLI (-f xml), so both authoring routes end up as a native .drawio.
Basic structure
Every diagram must have this structure:
<mxGraphModel adaptiveColors="auto">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<!-- Diagram cells go here with parent="1" -->
</root>
</mxGraphModel>
- Cell
id="0"is the root layer - Cell
id="1"is the default parent layer - All diagram elements use
parent="1"unless using multiple layers
(В примере выше XML-комментарий используется только для того, чтобы указать, где располагаются ячейки — никогда не выводите комментарии в реальном результате; см. раздел о корректности XML.)
Справочник по XML
Полный справочник по XML для draw.io, включая общие стили, маршрутизацию рёбер, контейнеры, слои, теги, метаданные, цвета тёмной темы и правила корректности XML, доступен по адресу: https://raw.githubusercontent.com/jgraph/drawio-mcp/main/shared/xml-reference.md — загрузите и следуйте инструкциям.
Устранение неполадок
| Проблема | Причина | Решение |
|---|---|---|
| draw.io CLI не найден | Настольное приложение не установлено или отсутствует в PATH | Создайте диаграмму в виде XML и передайте .drawio файл или url (преобразование Mermaid, компоновка ELK и экспорт изображений требуют настольного приложения). Сообщите пользователю, что он может установить настольное приложение draw.io, чтобы включить эти возможности |
| Экспорт Mermaid → PNG завершается сбоем | Прямой экспорт .mmd → PNG с помощью -e не работает в текущей версии draw.io Desktop (этап встраивания XML) | Используйте двухэтапный путь: сначала преобразуйте Mermaid в .drawio (-f xml), затем экспортируйте .drawio в PNG — промежуточный файл встраивается корректно |
| Пустая диаграмма из Mermaid | Опечатка в ключевом слове типа или синтаксическая ошибка (неверный ID узла, метка без кавычек) | Проверьте справочник по Mermaid; ключевое слово в первой строке, не являющейся директивой, определяет тип диаграммы |
| Компоновка ничего не делает / выдаёт ошибки | Неизвестное имя пресета, пользовательский JSON не является массивом или сборка настольного приложения слишком стара для --layout / .mmd входных данных | Используйте пресет из раздела «Пресеты компоновки» или массив JSON, начинающийся с [; на старой сборке настольного приложения создайте диаграмму в виде XML с явными позициями и сообщите пользователю, что обновление draw.io Desktop включает преобразование Mermaid и компоновку |
| Экспорт создаёт пустой или повреждённый файл | Некорректный XML (например, двойные дефисы в комментариях, неэкранированные специальные символы) | Проверьте корректность XML перед записью; см. раздел о корректности XML ниже |
| Диаграмма открывается, но выглядит пустой | Отсутствуют корневые ячейки id="0" и id="1" | Убедитесь, что базовая структура mxGraphModel полная |
| Рёбра не отображаются | mxCell ребра является самозакрывающимся (нет дочернего элемента mxGeometry) | Каждое ребро должно иметь <mxGeometry relative="1" as="geometry" /> в качестве дочернего элемента |
| Файл не открывается после экспорта | Неверный путь к файлу или отсутствует связь с файлом | Выведите абсолютный путь к файлу, чтобы пользователь мог открыть его вручную |
Браузер открывается с пустой диаграммой в url режиме | cmd.exe удалил #create=... фрагмент | Используйте .url обходной путь с временным файлом в Windows/WSL2 (см. раздел «Открытие URL») — никогда не передавайте URL напрямую в cmd.exe /c start |
| URL слишком длинный для браузера | Очень большая диаграмма превышает ограничение длины URL браузера | Вернитесь к записи .drawio файла и откройте его локально |
ВАЖНО: корректность XML
- НИКОГДА не включайте в вывод ЛЮБЫЕ XML-комментарии (
<!-- -->). XML-комментарии строго запрещены — они расходуют токены, могут вызывать ошибки разбора и не несут никакой пользы в XML диаграммы. - Экранируйте специальные символы в значениях атрибутов:
&,<,>," - Всегда используйте уникальные
idзначения для каждогоmxCell
Вставить в README
Ссылка на карточку для вашего README — без картинок и счётчиков.
[DarkPlay: drawio](https://darkplay.ru/ai/skills/drawio-mcp-drawio)
Похожие скиллы и другие разделы каталога
Та же категория — сравните, что ещё подойдёт под вашу задачу.
diagram-designcathrynlavery · Создание технических и продуктовых диаграмм: архитектура, флоучарты, ER-модели, таймлайны…
plannotator-visual-explainerbacknotprop · Генерация самодостаточных HTML-визуализаций с оформлением Plannotator. Используйте для…
fireworks-tech-graphyizhiyanhua-ai · Создание технических диаграмм: архитектура ПО, потоки данных, блок-схемы, диаграммы…
architecture-diagramcocoon-ai · Создаёт аккуратные тёмные архитектурные диаграммы в виде самодостаточных файлов HTML+SVG…
excalidraw-diagramcoleam00 · Создаёт JSON-файлы диаграмм Excalidraw для визуальной аргументации. Используется, когда…
excalidraw-diagramaxtonliu · Генерация диаграмм Excalidraw из текста: Obsidian, стандартный и анимированный форматы
mermaid-diagramssoftaworks · Диаграммы софта на Mermaid: классы, последовательности, потоки, архитектура.
excalidraw-skillyctimlin · Инструментарий Excalidraw для создания и итеративной правки диаграмм на живом холсте.
pretty-mermaidimxv · Рендер диаграмм Mermaid в SVG или ASCII через beautiful-mermaid: 15+ тем, 5 типов.
flowchart-creatormhattingpete · Создаёт HTML-блок-схемы и диаграммы процессов с деревьями решений, этапами и дорожками.Самые востребованные скиллов раздела по установкам и звёздам.
find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.Соседние разделы каталога: возможно, нужный инструмент живёт там.
drawiojgraph · Создаёт нативные диаграммы .drawio из Claude Code: авторство в Mermaid или XML с…
next-ai-drawioanthropics · Генерация диаграмм Draw.io с помощью ИИ и предпросмотром в браузере в реальном времени…
legal-visualizationcat-xierluo · Схемы для юристов: отношения, процессы, таймлайны, доказательства в .drawio, .svg и .png.
drawioagents365-ai · Диаграммы Draw.io: генерация .drawio XML, экспорт в PNG/SVG/PDF.
io.github.yohasacura/drawio-mcpyohasacura · MCP-сервер для программного создания и редактирования XML-файлов draw.io / diagrams.net.
Smart Drawioyunshenwuchuxun · Создание, проверка, исправление и оформление редактируемых диаграмм draw.io в XML.Лучшие ИИ-инструменты для генерации видео
Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,
VEED.IOVeed
MootionMootion
Sora (OpenAI)OpenAI
viralpulse.appViralpulse
Viral Maker AIViral-makerЛучшие ИИ-инструменты для генерации текста и копирайтинга
Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра
NeuroscribeNeuroscribe
GoGPTGogpt
НейроТекстерNeuro-texter
ChatGPTOpenAI
Cosmo ScribeCosmoscribe
Memo HelperCopilot33
LibraChatLibrachatЛучшие ИИ-инструменты для генерации изображений
Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты
MagviMagvi
DALL-E 3OpenAI
SupaLabSupalab
Freestyling.aiFreestyling
ArtGeneration.meArtgeneration
BigjpgBigjpg
Художник от VKVK
Avato AI12ai
Virton AIVirton