Agent skill that turns natural language, code, Terraform/K8s, SQL, OpenAPI, AsyncAPI, Protobuf and GraphQL sources into editable, tested draw.io architecture diagrams: incremental sync, multi-view projection, drift diff, CI architecture tests, whiteboard derasterize, interactive HTML/PPTX/Mermaid exports.
Python agent-skillsarchitecturearchitecture-diagramasyncapibpmnc4-modelclaude-codediagramdiagrams-as-codedrawioflowchartgithub-actionsgraphqlimage-to-diagramkubernetesmcp-serverprotobufsysmlterraformuml
feat: MCP server mode, architecture-test CI action, prompt cookbook
Agents365-ai18c59ae36152
diff --git a/.github/actions/drawio-architecture-test/action.yml b/.github/actions/drawio-architecture-test/action.ymlnew file mode 100644index 0000000..f2131ab--- /dev/null+++ b/.github/actions/drawio-architecture-test/action.yml@@ -0,0 +1,174 @@+name: 'draw.io Architecture Test'+description: >-+ Runs drawio-skill's deterministic architecture contract rules+ (Diagram-as-Test) against Diagram IR files and reports findings as a job+ summary + sticky PR comment. Pure Python: no draw.io desktop, Xvfb, or+ Graphviz required.+author: 'drawio-skill'++inputs:+ ir-files:+ description: >-+ Newline-separated list of Diagram IR JSON files to test (glob patterns+ allowed)+ required: true+ rules:+ description: >-+ Optional policy file (JSON/YAML) selecting rule ids; defaults to all+ rules+ required: false+ default: ''+ strict:+ description: 'Also fail on warnings (not just errors)'+ required: false+ default: 'false'+ summary:+ description: 'Write the findings report to the job summary'+ required: false+ default: 'true'+ post-comment:+ description: 'Post/update a sticky PR comment with the findings'+ required: false+ default: 'true'+ github-token:+ description: >-+ Token used to post the sticky PR comment (needs pull-requests: write)+ required: false+ default: ${{ github.token }}++runs:+ using: 'composite'+ steps:+ # The action may be referenced cross-repo:+ # uses: Agents365-ai/drawio-skill/.github/actions/+ # drawio-architecture-test@main+ # Composite steps run in the caller's workspace, so check the skill itself+ # out next to it. github.action_repository/action_ref point at this repo+ # and the ref the caller pinned.+ - name: Check out drawio-skill (for the diagramctl scripts)+ uses: actions/checkout@v4+ with:+ repository: ${{ github.action_repository }}+ ref: ${{ github.action_ref }}+ path: _drawio-skill+ fetch-depth: 1++ - name: Run architecture contract rules+ id: run+ shell: bash+ env:+ DIAGRAMCTL: ${{ github.workspace }}/_drawio-skill/skills/+ drawio-skill/scripts/diagramctl.py+ IR_FILES: ${{ inputs.ir-files }}+ RULES: ${{ inputs.rules }}+ STRICT: ${{ inputs.strict }}+ run: |+ set -euo pipefail+ out_dir="_drawio-architecture-test"+ mkdir -p "$out_dir"+ shopt -s nullglob+ # Expand glob patterns one per line (IR_FILES is newline-separated).+ files=()+ while IFS= read -r pattern; do+ [ -z "$pattern" ] && continue+ for f in $pattern; do+ [ -f "$f" ] && files+=("$f") || {+ echo "warning: no match for $pattern" >&2+ }+ done+ done <<< "$IR_FILES"+ shopt -u nullglob+ if [ ${#files[@]} -eq 0 ]; then+ echo "No IR files matched:" >&2+ printf '%s\n' "$IR_FILES" >&2+ exit 1+ fi+ failed=0+ : > "$out_dir/combined.md"+ for f in "${files[@]}"; do+ echo "Testing $f"+ args=(test "$f" -o "$out_dir/$(basename "$f" .json).findings.json")+ [ -n "$RULES" ] && args+=(--rules "$RULES")+ [ "$STRICT" = "true" ] && args+=(--strict)+ if ! python3 "$DIAGRAMCTL" "${args[@]}"; then+ failed=1+ fi+ done+ python3 - "$out_dir" "$RULES" > "$out_dir/report.md" <<'PY'+ import json, sys+ from pathlib import Path++ out_dir, rules = Path(sys.argv[1]), sys.argv[2]+ rows, errors, warnings = [], 0, 0+ for findings_file in sorted(out_dir.glob("*.findings.json")):+ data = json.loads(findings_file.read_text(encoding="utf-8"))+ errors += data.get("errors", 0)+ warnings += data.get("warnings", 0)+ for f in data.get("findings", []):+ subject = f["subject"]+ row = (+ f"| {findings_file.name.removesuffix('.findings.json')}"+ f" | {f['severity']} | {f['rule']}"+ f" | {subject} | {f['message']} |"+ )+ rows.append(row)+ lines = ["## draw.io architecture test", ""]+ if rules:+ lines += [f"Policy: `{rules}`", ""]+ models = len(list(out_dir.glob("*.findings.json")))+ lines += [+ f"**{errors} error(s), {warnings} warning(s)**"+ f" across {models} model(s).",+ "",+ ]+ if rows:+ header = ["| Model | Severity | Rule | Subject | Message |",+ "| --- | --- | --- | --- | --- |"]+ lines += header + rows+ else:+ lines.append("No findings — all architecture contracts hold.")+ print("\n".join(lines))+ PY+ echo "failed=$failed" >> "$GITHUB_OUTPUT"++ - name: Write job summary+ if: inputs.summary == 'true'+ shell: bash+ run: cat _drawio-architecture-test/report.md >> "$GITHUB_STEP_SUMMARY"++ - name: Upload findings artifact+ uses: actions/upload-artifact@v4+ with:+ name: drawio-architecture-test+ path: _drawio-architecture-test++ - name: Post/update sticky PR comment+ if: inputs.post-comment == 'true' && github.event_name == 'pull_request'+ shell: bash+ env:+ GH_TOKEN: ${{ inputs.github-token }}+ run: |+ set -euo pipefail+ marker="<!-- drawio-architecture-test-bot -->"+ body_file="$(mktemp)"+ printf '%s\n' "$marker" > "$body_file"+ cat _drawio-architecture-test/report.md >> "$body_file"+ pr_number="${{ github.event.pull_request.number }}"+ existing_id=$(gh api \+ "repos/${{ github.repository }}/issues/${pr_number}/comments" \+ --paginate \+ --jq ".[] | select(.body | startswith(\"$marker\")) | .id" | head -n1)+ if [ -n "$existing_id" ]; then+ gh api --method PATCH \+ "repos/${{ github.repository }}/issues/comments/${existing_id}" \+ -f body=@"$body_file"+ else+ gh pr comment "$pr_number" --body-file "$body_file"+ fi++ - name: Enforce gate+ if: steps.run.outputs.failed == '1'+ shell: bash+ run: |+ echo "Architecture contract violations found — see the report above."+ exit 1diff --git a/.github/workflows/drawio-architecture-test.example.yml b/.github/workflows/drawio-architecture-test.example.ymlnew file mode 100644index 0000000..3485f40--- /dev/null+++ b/.github/workflows/drawio-architecture-test.example.yml@@ -0,0 +1,47 @@+# TEMPLATE — not a live workflow in this repo.+#+# Architecture-as-test CI gate for users of drawio-skill. Pure Python: no+# draw.io desktop, Xvfb, or Graphviz needed, so it runs on a stock+# ubuntu-latest runner in seconds.+#+# To adopt in your own repo (recommended: reference this repo's action+# directly so you get updates without copying code):+# 1. Export your architecture model once (locally or in a prior step):+# python3 diagramctl.py build ./src --ir-output architecture.ir.json \+# -o architecture.drawio+# and commit architecture.ir.json.+# 2. Copy this file to .github/workflows/drawio-architecture-test.yml+# (drop `.example`).+# 3. Uncomment the pull_request trigger below (workflow_dispatch alone is+# harmless; the pull_request trigger is intentionally commented out so+# this template never runs anywhere until adopted).+# 4. Point `ir-files` at your IR file(s); optionally set `rules` to a+# policy YAML selecting rule ids.++name: drawio-architecture-test (example)++on:+ workflow_dispatch: {}+ # pull_request:+ # paths:+ # - "**/*.ir.json"+ # - "policy.yml"++permissions:+ contents: read+ pull-requests: write++jobs:+ architecture-test:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4++ - uses: "Agents365-ai/drawio-skill/.github/actions/\+ drawio-architecture-test@main"+ with:+ ir-files: |+ architecture.ir.json+ # rules: policy.yml+ # strict: true+ github-token: ${{ github.token }}diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 192a97b..2293fa2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,38 @@ on [Keep a Changelog](https://keepachangelog.com/), and the project followssemantic-ish versioning (the `metadata.version` field in`skills/drawio-skill/SKILL.md`).+## [3.1.0] — 2026-09-01++### Added++- **MCP server mode** (`scripts/diagramctl_mcp.py`) — a stdlib-only, offline+ Model Context Protocol stdio server exposing the semantic workflows as nine+ tools (`doctor`, `build`, `sync`, `views`, `architecture_test`, `review`,+ `query`, `whatif`, `story`) to any MCP host (Claude Desktop, Cursor,+ VS Code, Codex, Claude Code). No `mcp` package or network access; each call+ shells out to `diagramctl.py`, and `architecture_test` mirrors the CI exit+ code through `isError`. Host registration recipes in+ `references/mcp.md`; covered by 11 regression tests (suite 160 → 171).+- **Official GitHub Action: `drawio-architecture-test`**+ (`.github/actions/drawio-architecture-test/`) — runs the Diagram-as-Test+ architecture contract rules against Diagram IR files on every PR and+ reports via job summary + sticky comment + artifact, with a hard gate exit.+ Pure Python: no draw.io desktop, Xvfb, or Graphviz, so it runs on a stock+ runner in seconds. Usable cross-repo via+ `uses: Agents365-ai/drawio-skill/.github/actions/drawio-architecture-test@main`;+ ready-to-copy workflow template+ `.github/workflows/drawio-architecture-test.example.yml`; guide in+ `references/ci-gate.md`.+- **Prompt Cookbook** (`references/cookbook.md`) — tested prompt patterns for+ each workflow (architecture, sync, contracts, views, what-if, Story, C4,+ UML, ML, Mermaid-first) with the structural clauses that separate strong+ prompts from weak ones, plus anti-patterns. Routed from `SKILL.md`.++### Changed++- Scripts: 39 focused tools + 1 unified CLI + 1 IR module + 1 MCP server.+ Tests: 160 → 171.+## [3.0.0] — 2026-09-01### Addeddiff --git a/README.md b/README.mdindex 0df6757..2db470f 100644--- a/README.md+++ b/README.md@@ -26,6 +26,7 @@ A skill that turns natural language and real system sources into maintainable `.- **Diagram-as-Test** — YAML/JSON rules for direct Internet-to-database access, cycles, orphans, ownership, production observability, external timeouts, trust-boundary protocols, and color contrast- **Architecture query and review** — query components/owners/boundaries/paths, identify articulation points and high coupling, and emit Markdown/JSON review reports- **What-if + Story Mode** — simulate failure propagation with an annotated diagram; publish an offline, keyboard-accessible HTML walkthrough with text alternative, provenance, and language switching+- **MCP server built in** — `scripts/diagramctl_mcp.py` exposes nine tools (`build/sync/views/architecture_test/review/query/whatif/story/doctor`) to Claude Desktop, Cursor, VS Code, Codex, and any MCP host; stdlib-only and offline, no `mcp` package- **One CLI** — `doctor/build/sync/views/query/test/review/whatif/story/publish/transform` connects the toolbox; core semantic workflows need only Python and are offline by default- **11 diagram type presets** — ERD, UML Class, Sequence, C4, Architecture, ML/Deep Learning, Flowchart, SysML (BDD / IBD / Requirement / Parametric), BPMN, Network Topology, Cross-Functional Swimlane- **Mermaid → native .drawio** (draw.io ≥ 30) — author 28 standard types as Mermaid text (**mindmap, gantt, timeline, journey, pie, sankey, kanban**…) and the CLI converts them into a laid-out, editable `.drawio` — structure in, layout free@@ -40,7 +41,8 @@ A skill that turns natural language and real system sources into maintainable `.- **Iterative feedback loop** — up to 5 rounds of targeted refinement- **Style presets** — capture your visual style from a `.drawio` file or image, reuse on demand- **Clean layout** — grid-aligned, spacing scales with diagram size, connectors routed clear of nodes-- **Multi-agent, no daemon** — portable Agent Skills package; no MCP server or background process (core semantic workflows need only Python; native export remains optional)+- **CI-ready** — official `drawio-architecture-test` GitHub Action enforces architecture contracts on every PR with no draw.io/Xvfb/Graphviz install; visual PR diff action for rendered `.drawio`+- **Multi-agent, no daemon** — portable Agent Skills package plus an optional MCP server for host integrations (core semantic workflows need only Python; native export remains optional)## 🗺️ Feature Map@@ -377,7 +379,7 @@ Behind the scenes: **check dependencies → plan layout → generate `.drawio` X| Feature | drawio-skill | [jgraph/drawio-mcp](https://github.com/jgraph/drawio-mcp) (official)<br> | [bahayonghang/drawio-skills](https://github.com/bahayonghang/drawio-skills)<br> | [GBSOSS/ai-drawio](https://github.com/GBSOSS/ai-drawio)<br> || --- | --- | --- | --- | --- |-| **Approach** | Pure SKILL.md | MCP servers / Claude Code plugin / Project | YAML DSL + CLI (MCP optional) | Claude Code plugin |+| **Approach** | Pure SKILL.md + optional MCP server | MCP servers / Claude Code plugin / Project | YAML DSL + CLI (MCP optional) | Claude Code plugin || **Dependencies** | draw.io desktop only | draw.io desktop | draw.io desktop (MCP optional) | draw.io plugin + browser || **Multi-agent** | ✅ 6 platforms | ⚠️ MCP hosts (Claude, Cursor, VS Code) | ✅ Claude / Gemini / Codex | ❌ Claude Code only || **Self-check + auto-fix** | ✅ 2-round (reads PNG) | ❌ | ✅ validation + strict mode | ❌ screenshot only |diff --git a/README_CN.md b/README_CN.mdindex bd2e1bd..99848e8 100644--- a/README_CN.md+++ b/README_CN.md@@ -26,6 +26,7 @@- **Diagram-as-Test** —— 用 YAML/JSON 规则检查直连数据库、循环依赖、孤立节点、owner、生产可观测性、外部超时、信任边界协议与颜色对比度- **架构查询与体检** —— 查询任意组件/owner/边界/调用路径,发现单点连接、高耦合、缺失元数据,并生成 Markdown/JSON 审查报告- **What-if + Story Mode** —— 模拟节点故障传播并生成高亮图;发布键盘可用、带文本替代/来源信息/多语言切换的离线 HTML 讲解页+- **内置 MCP 服务** —— `scripts/diagramctl_mcp.py` 把 9 个工具(`build/sync/views/architecture_test/review/query/whatif/story/doctor`)暴露给 Claude Desktop、Cursor、VS Code、Codex 等任何 MCP host;纯标准库、默认离线,无需 `mcp` 包- **统一 CLI** —— `doctor/build/sync/views/query/test/review/whatif/story/publish/transform` 串起全部能力,核心语义工作流仅需 Python 且默认离线- **11 种图表类型预设** —— ER 图、UML 类图、序列图、C4、架构图、ML/深度学习、流程图、SysML(BDD / IBD / 需求图 / 参数图)、BPMN、网络拓扑、跨职能泳道图- **Mermaid → 原生 .drawio**(draw.io ≥ 30)—— 28 种标准类型直接用 Mermaid 文本作图(**mindmap、gantt、timeline、journey、pie、sankey、kanban**……),CLI 原生转成已布局、可编辑的 `.drawio` —— 只管结构,布局白送@@ -40,7 +41,8 @@- **迭代反馈循环** —— 最多 5 轮定向优化- **样式预设** —— 用 `.drawio` 文件或图片"教会"Skill 你的风格,命名保存后随时复用- **整洁布局** —— 网格对齐,间距随图表规模缩放,连线避开节点-- **多智能体、无后台服务** —— 可移植的 Agent Skills 包,无需 MCP 或 daemon;核心语义工作流只需 Python,原生导出按需安装+- **CI 就绪** —— 官方 `drawio-architecture-test` GitHub Action 在每个 PR 上强制执行架构契约,无需安装 draw.io/Xvfb/Graphviz;另有渲染 `.drawio` 的可视 PR diff action+- **多智能体、无后台服务** —— 可移植的 Agent Skills 包,外加可选的 MCP server 供宿主集成(核心语义工作流只需 Python,原生导出按需安装)## 🗺️ 功能全景@@ -374,7 +376,7 @@ Skill 会提取配色、形状、字体和连线风格,渲染预览图,**确| 功能 | drawio-skill | [jgraph/drawio-mcp](https://github.com/jgraph/drawio-mcp)(官方)<br> | [bahayonghang/drawio-skills](https://github.com/bahayonghang/drawio-skills)<br> | [GBSOSS/ai-drawio](https://github.com/GBSOSS/ai-drawio)<br> || ------ | ------ | ------ | ------ | ------ |-| **方式** | 纯 SKILL.md | MCP 服务 / Claude Code 插件 / Project | YAML DSL + CLI(MCP 可选) | Claude Code 插件 |+| **方式** | 纯 SKILL.md + 可选 MCP 服务 | MCP 服务 / Claude Code 插件 / Project | YAML DSL + CLI(MCP 可选) | Claude Code 插件 || **依赖** | 仅 draw.io 桌面版 | draw.io 桌面版 | draw.io 桌面版(MCP 可选) | draw.io 插件 + 浏览器 || **多智能体支持** | ✅ 6 个平台 | ⚠️ MCP 宿主(Claude、Cursor、VS Code) | ✅ Claude / Gemini / Codex | ❌ 仅 Claude Code || **自检 + 自动修复** | ✅ 2 轮(读取 PNG) | ❌ | ✅ 校验 + 严格模式 | ❌ 仅截图 |diff --git a/docs/CI.md b/docs/CI.mdindex 1920428..03b1bd4 100644--- a/docs/CI.md+++ b/docs/CI.md@@ -14,6 +14,8 @@ Bonus: the pipeline itself can be the diagram — `ciimports.py <repo-root>` turImporter node ids are stable (module paths, `type.name`, `kind/name`), so regenerated `.drawio` files produce reviewable diffs when the underlying code or infra changes.+For turnkey gates, this repo also ships composite GitHub Actions: a pure-Python architecture-rule gate (`drawio-architecture-test`) and a visual PR diagram diff (`drawio-diff`) — see [`../skills/drawio-skill/references/ci-gate.md`](../skills/drawio-skill/references/ci-gate.md) and [`../skills/drawio-skill/references/pr-bot.md`](../skills/drawio-skill/references/pr-bot.md).+## Option A — draw.io desktop + xvfb (GitHub Actions)The desktop CLI works headless under `xvfb`. Complete workflow:diff --git a/docs/CI_CN.md b/docs/CI_CN.mdindex c926443..102b652 100644--- a/docs/CI_CN.md+++ b/docs/CI_CN.md@@ -14,6 +14,8 @@Importer 的节点 id 是稳定的(模块路径、`type.name`、`kind/name`),代码或基础设施变更后重新生成的 `.drawio` diff 可读、可 review。+本仓库还内置了两个开箱即用的 composite GitHub Action:纯 Python 的架构规则门禁(`drawio-architecture-test`)和可视 PR 图表 diff(`drawio-diff`)—— 见 [`../skills/drawio-skill/references/ci-gate.md`](../skills/drawio-skill/references/ci-gate.md) 与 [`../skills/drawio-skill/references/pr-bot.md`](../skills/drawio-skill/references/pr-bot.md)。+## 方案 A —— draw.io 桌面版 + xvfb(GitHub Actions)桌面版 CLI 在 `xvfb` 下可无头运行。完整 workflow:diff --git a/docs/USAGE.md b/docs/USAGE.mdindex 8c79869..c187520 100644--- a/docs/USAGE.md+++ b/docs/USAGE.md@@ -116,3 +116,15 @@ python3 scripts/aiicons.py "openai" --embed # self-contained data URI## Rendering in CIRegenerate, lint (`validate.py --strict`), and export diagrams headlessly in GitHub Actions — via draw.io desktop under `xvfb` or the Docker REST renderer. Full workflow recipes in [CI.md](CI.md).++## MCP, CI gates, and the prompt cookbook++- **MCP hosts** (Claude Desktop, Cursor, VS Code, Codex): register+ `scripts/diagramctl_mcp.py` — recipes in+ [`../skills/drawio-skill/references/mcp.md`](../skills/drawio-skill/references/mcp.md).+- **Architecture rules on every PR**: the+ `drawio-architecture-test` action gates Diagram IR files with no+ draw.io/Xvfb install —+ [`../skills/drawio-skill/references/ci-gate.md`](../skills/drawio-skill/references/ci-gate.md).+- **Prompt patterns** that get the best results per workflow:+ [`../skills/drawio-skill/references/cookbook.md`](../skills/drawio-skill/references/cookbook.md).diff --git a/docs/USAGE_CN.md b/docs/USAGE_CN.mdindex 80b11da..3cbd5d3 100644--- a/docs/USAGE_CN.md+++ b/docs/USAGE_CN.md@@ -117,3 +117,14 @@ python3 scripts/aiicons.py "openai" --embed # 内联为自包含 data URI## 在 CI 中渲染在 GitHub Actions 里无头地重新生成、校验(`validate.py --strict`)并导出图表 —— 走 xvfb 下的 draw.io 桌面版或 Docker REST 渲染器。完整 workflow 配方见 [CI_CN.md](CI_CN.md)。++## MCP、CI 门禁与提示词手册++- **MCP 宿主**(Claude Desktop、Cursor、VS Code、Codex):注册+ `scripts/diagramctl_mcp.py` —— 配置配方见+ [`../skills/drawio-skill/references/mcp.md`](../skills/drawio-skill/references/mcp.md)。+- **每个 PR 强制执行架构规则**:`drawio-architecture-test` action 无需安装+ draw.io/Xvfb 即可门禁 Diagram IR —— 见+ [`../skills/drawio-skill/references/ci-gate.md`](../skills/drawio-skill/references/ci-gate.md)。+- **各工作流的提示词模式**:+ [`../skills/drawio-skill/references/cookbook.md`](../skills/drawio-skill/references/cookbook.md)。diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.mdindex 3d97f08..a9becdb 100644--- a/skills/drawio-skill/SKILL.md+++ b/skills/drawio-skill/SKILL.md@@ -3,7 +3,7 @@ name: drawio-skilldescription: Create, edit, synchronize, inspect, test, and publish editable draw.io diagrams. Use when the user explicitly requests draw.io/diagrams.net, needs a polished architecture, ERD, UML, sequence, C4, SysML, BPMN, network, swimlane, ML, or infrastructure diagram, wants code/IaC/SQL/OpenAPI converted into a diagram, or wants an existing diagram queried, reviewed, diffed, restyled, kept in sync, or made interactive. Prefer Mermaid/PlantUML elsewhere when the requested artifact is diagrams-as-code rather than an editable draw.io file.license: MITallowed-tools: [Bash, Read, Write, WebFetch]-metadata: {"openclaw":{"requires":{"anyBins":["python3"]},"emoji":"📐","os":["darwin","linux","win32"],"install":[{"id":"brew-drawio","kind":"brew","formula":"drawio","bins":["drawio"],"label":"Install draw.io for native exports","os":["darwin"],"optional":true},{"id":"brew-graphviz","kind":"brew","formula":"graphviz","bins":["dot"],"label":"Install Graphviz for automatic layout","os":["darwin"],"optional":true}]},"hermes":{"tags":["drawio","diagram","architecture","visualization","uml"],"category":"design","requires_tools":["python3"],"related_skills":["mermaid","excalidraw","plantuml"]},"author":"Agents365-ai","version":"3.0.0","homepage":"https://github.com/Agents365-ai/drawio-skill","compatibility":"Core IR, XML, sync, query, test, review, and Story workflows need Python 3 only; native export needs draw.io; Graphviz is optional.","platforms":["macos","linux","windows"]}+metadata: {"openclaw":{"requires":{"anyBins":["python3"]},"emoji":"📐","os":["darwin","linux","win32"],"install":[{"id":"brew-drawio","kind":"brew","formula":"drawio","bins":["drawio"],"label":"Install draw.io for native exports","os":["darwin"],"optional":true},{"id":"brew-graphviz","kind":"brew","formula":"graphviz","bins":["dot"],"label":"Install Graphviz for automatic layout","os":["darwin"],"optional":true}]},"hermes":{"tags":["drawio","diagram","architecture","visualization","uml"],"category":"design","requires_tools":["python3"],"related_skills":["mermaid","excalidraw","plantuml"]},"author":"Agents365-ai","version":"3.1.0","homepage":"https://github.com/Agents365-ai/drawio-skill","compatibility":"Core IR, XML, sync, query, test, review, and Story workflows need Python 3 only; native export needs draw.io; Graphviz is optional.","platforms":["macos","linux","windows"]}---# Draw.io Architecture Studio@@ -23,6 +23,9 @@ and accessible publishing over a shared Diagram IR.| Update a generated diagram without losing manual layout | Use `diagramctl.py sync`; read `references/diagram-ir.md` || Executive/system/deployment/data-flow/security views | Use `diagramctl.py views`; read `references/diagram-ir.md` || Query, architecture policy, review, what-if, or guided walkthrough | Read `references/semantic-workflows.md` |+| MCP host (Claude Desktop, Cursor, VS Code, Codex) should call these workflows | Register `scripts/diagramctl_mcp.py`; read `references/mcp.md` |+| Prompt phrasing for a diagram type or semantic workflow | Read `references/cookbook.md` |+| Enforce architecture rules or visual diffs in GitHub Actions CI | Read `references/ci-gate.md` || Existing `.drawio` to HTML/PPTX/Mermaid/Markdown/animation/runbook | Read `references/toolbox.md`; `diagramctl.py transform` exposes the existing tools || Shape, cloud/vendor, AI, or Databricks icon | Read `references/shapes.md` or `references/databricks.md`; never guess shape names || Learn/apply/manage a visual style | Read `references/style-presets.md` |diff --git a/skills/drawio-skill/references/ci-gate.md b/skills/drawio-skill/references/ci-gate.mdnew file mode 100644index 0000000..2a9432c--- /dev/null+++ b/skills/drawio-skill/references/ci-gate.md@@ -0,0 +1,49 @@+# CI gates++Two composite GitHub Actions ship with this repo. Both can be used from your+own repository without copying code:++```yaml+uses: Agents365-ai/drawio-skill/.github/actions/<action>@main+```++(Pin to a tag instead of `main` for reproducible gates, e.g. `@v3.1.0`.)++## drawio-architecture-test — pure Python, seconds to run++Runs the Diagram-as-Test architecture contract rules against Diagram IR files+on every PR. Needs **no draw.io desktop, no Xvfb, no Graphviz** — a stock+runner works, because the rules operate on the IR JSON.++Inputs: `ir-files` (newline-separated paths/globs, required), `rules`+(optional policy YAML/JSON), `strict` (fail on warnings), `summary`,+`post-comment` (sticky PR comment), `github-token`.++Behavior: each failing model increments the gate; the job exits non-zero when+any model has errors (or warnings under `strict`). The report lands in the+job summary, the `drawio-architecture-test` artifact, and a sticky PR comment.++Ready-to-copy workflow: `.github/workflows/drawio-architecture-test.example.yml`+in this repo. Typical adoption:++1. Export the model once and commit the IR:+ `python3 diagramctl.py build ./src --ir-output architecture.ir.json -o architecture.drawio`+2. Reference the action with `ir-files: architecture.ir.json` and, optionally,+ `rules: policy.yml` (see `diagramctl.py test --help` for the rule ids).++## drawio-diff — visual PR diagram diff++Renders base/head/diff PNGs for every `.drawio` changed in a PR and posts a+sticky Markdown report. This one needs the draw.io desktop CLI + Graphviz ++Xvfb (the action installs them unless `skip-tool-install: true`); full+adoption guide in `references/pr-bot.md`.++## Choosing between them++| You want | Action |+| --- | --- |+| Architecture rules enforced in CI (ownership, trust boundaries, cycles, Internet→DB access, timeouts, contrast) | `drawio-architecture-test` |+| Visual diff of rendered diagrams for changed `.drawio` files | `drawio-diff` |++They compose: run the IR gate on every PR cheaply, and the visual diff when+`.drawio` files actually change.diff --git a/skills/drawio-skill/references/cookbook.md b/skills/drawio-skill/references/cookbook.mdnew file mode 100644index 0000000..b712e2e--- /dev/null+++ b/skills/drawio-skill/references/cookbook.md@@ -0,0 +1,166 @@+# Prompt Cookbook++Tested prompt patterns for the highest-quality results from this skill. Each+recipe states what to include, why it matters, and what the skill does with it.+Adapt the bracketed parts; keep the structural clauses.++## General rules that always help++1. **Name the audience and the file format.** "for an exec review, PNG ++ editable .drawio" changes layout, colors, and what gets simplified.+2. **List the components explicitly.** An enumerated list of nodes beats+ "a typical microservices system" — the skill cannot invent your topology.+3. **State the relations with verbs.** "Kafka consumes events from Order+ Service" yields labeled, directed edges instead of anonymous lines.+4. **Say what is external or out of scope** to get boundary containers and+ honest trust boundaries.+5. **For source-backed models, point at the real directory/manifest.** Anything+ the skill imports from code/IaC/SQL carries provenance; anything invented+ does not.++## Natural-language architecture diagram++```text+Draw a microservices e-commerce architecture for an exec review. Clients:+Mobile, Web. Edge: API Gateway (auth, rate limiting). Services: Order,+Payment, Inventory, Notification. Infrastructure: Kafka, PostgreSQL+(orders), Redis (cache). Stripe is an external SaaS. Mobile/Web reach the+gateway over HTTPS; services talk over gRPC inside the VPC; Payment calls+Stripe over mTLS. Output PNG + editable .drawio.+```++Why it works: enumerated nodes, protocol-labeled edges, explicit external+system, audience stated. Swap "exec review" for "security review" and the+same prompt projects a different view.++## Codebase visualization++```text+Visualize the module structure of ./myproject as an import graph. Group by+top-level package, and hide utilities modules. Export .drawio + PNG.+```++The directory path is doing the work here: `diagramctl.py build ./myproject+--group` reads the real imports, so the diagram stays syncable when the code+changes. Do not also list components by hand — the importer wins.++## Incremental sync (the "don't lose my layout" workflow)++```text+We added a Billing service and removed the legacy Auth service from+./src. Update architecture.drawio from the source, but keep my manual+positions and colors for everything that didn't change. Show me what+moved/remained before overwriting.+```++Triggers `diagramctl.py sync` (reviewable output, explicit pruning only).++## Architecture contracts (Diagram-as-Test)++```text+Check this architecture against our rules: no component may reach a+database directly from the Internet, no cyclic service dependencies, every+service must have an owner, and every external call must have a timeout.+Fail the build on errors.+```++Maps to a policy file + `diagramctl.py test`. Better: commit the IR JSON and+wire the `drawio-architecture-test` GitHub Action (see+`references/ci-gate.md`) so this runs on every PR.++## Multi-view projection++```text+From our architecture model, produce the executive view (only user-facing+services and external systems), the full system view, and a security view+highlighting trust-boundary crossings. Linked pages, one .drawio.+```++## Failure analysis (what-if)++```text+What happens if Kafka goes down? Show downstream impact and produce an+annotated diagram with the blast radius in red and isolated-but-alive+components in amber.+```++## Guided walkthrough (Story Mode)++```text+Turn our architecture model into an accessible HTML walkthrough for the+onboarding doc: keyboard navigation, a full text alternative, and a+failure-scenario section for the payment path. Chinese labels, keep+English as secondary.+```++## C4 with drill-down++```text+Build a C4 model for the payment platform: System Context on top,+containers below it (API Gateway, Order Service, Stripe connector,+PostgreSQL, Kafka), components inside Order Service. Every parent must+click through to its child page.+```++## UML class / sequence++```text+Draw the class diagram for the checkout domain: Order, OrderLine, Payment,+Receipt. Order has 1..* OrderLines; Payment references exactly one Order;+Receipt aggregates Payment. Show multiplicities and mark composition vs+association.+```++```text+Sequence for checkout: user submits cart -> API Gateway validates JWT ->+Order Service reserves inventory (gRPC) -> Payment Service charges Stripe+(HTTPS) -> on success Order Service persists to PostgreSQL and publishes+OrderPlaced to Kafka. Show the failure path when Stripe times out.+```++Multiplicities and explicit failure branches are the clauses agents skip+without them.++## ER diagram from DDL++```text+Turn schema.sql into an ER diagram with PK/FK markers and crow's-foot+notation; keep schema prefixes for the billing tables.+```++## ML / deep-learning model++```text+Draw a Transformer encoder-decoder for machine translation. 6+6 layers,+batch × 512 × 768 embeddings, sinusoidal positional encoding. Annotate+tensor shapes on every arrow and color-code by layer type (attention /+normalization / feed-forward).+```++Tensor-shape annotations are the difference between a poster and a+teachable figure; ask for them explicitly.++## Mermaid-first authoring (draw.io CLI >= 30)++```text+Draft this as a Mermaid mindmap first (it's structure-only), then convert+to native .drawio: quarterly OKRs with three branches...+```++Use Mermaid for standard types with no custom styling; switch to XML/IR+authoring the moment you need vendor icons, swimlanes, or precise geometry.++## Anti-patterns (these produce weak diagrams)++- "Draw a typical e-commerce architecture" — invented topology, no+ provenance, nothing to check. Enumerate nodes or name the source dir.+- "Make it beautiful" with no audience — the skill has to guess colors,+ density, and export format. Name the audience or a style preset.+- "Auto-layout it" for under ~15 nodes — hand-arranged placement from the+ IR preserves semantic grouping better; large graphs are where+ autolayout earns its keep.+- Mixing real sources and invented components in one request without+ saying which is which — provenance gets muddled and review findings+ become noise.+- Asking for PNG only on an architecture you will iterate on — always ask+ for the editable `.drawio` (or the IR JSON) as well.diff --git a/skills/drawio-skill/references/mcp.md b/skills/drawio-skill/references/mcp.mdnew file mode 100644index 0000000..1e7f68d--- /dev/null+++ b/skills/drawio-skill/references/mcp.md@@ -0,0 +1,56 @@+# MCP server mode++`scripts/diagramctl_mcp.py` exposes the skill's semantic workflows as an MCP+(Model Context Protocol) server over stdio, so MCP hosts (Claude Desktop,+Cursor, VS Code, Codex, any MCP client) can drive them directly. It is+stdlib-only: no `mcp` package, no network access, no GUI launch. Every tool+call shells out to `scripts/diagramctl.py`, the same CLI the skill uses.++## Register with a host++```json+{+ "mcpServers": {+ "drawio-skill": {+ "command": "python3",+ "args": ["/path/to/drawio-skill/skills/drawio-skill/scripts/diagramctl_mcp.py"]+ }+ }+}+```++- Claude Desktop / Cursor / VS Code: add the snippet above to the host's MCP+ config (`claude_desktop_config.json`, `mcp.json`, `.vscode/mcp.json`, ...).+- Claude Code: `claude mcp add drawio-skill -- python3 <path>/scripts/diagramctl_mcp.py`.+- Paths in tool arguments are resolved against the server's working directory+ (whatever the host launches it with), so prefer absolute paths.++## Tools++| Tool | Maps to | Purpose |+| --- | --- | --- |+| `doctor` | `diagramctl doctor` | Check python/draw.io/Graphviz availability without launching anything |+| `build` | `build` | Code / IaC / SQL / OpenAPI / graph / IR → editable `.drawio` (+ optional IR) |+| `sync` | `sync` | Incremental re-sync of a diagram from its changed source, preserving manual layout |+| `views` | `views` | Project an IR file into linked executive/system/deployment/dataflow/security pages |+| `architecture_test` | `test` | Deterministic architecture contract rules (policy YAML/JSON); `isError` mirrors the CI exit code |+| `review` | `review` | Ownership / resilience / trust-boundary / accessibility report (Markdown or JSON) |+| `query` | `query` | Filter nodes by kind/owner/boundary; directed path between two components |+| `whatif` | `whatif` | Failure-propagation simulation with optional red/amber annotated `.drawio` |+| `story` | `story` | Accessible offline HTML walkthrough (keyboard navigation, text alternative) |++Outputs are files (`.drawio`, `.html`, `.json`); tool results return the JSON+report or report text plus the written paths, so the host can open or attach+them.++## Behavior and safety++- Offline by default: no tool performs network access; native PNG export is+ deliberately not exposed (it launches the Electron GUI) — export from the+ CLI or the draw.io desktop app when needed.+- `architecture_test` failing rules are reported as a normal tool result with+ `isError: true`, so CI-style gating survives the MCP hop.+- Errors from bad paths/arguments come back as readable text, never as+ crashes; the server process itself never exits on a tool failure.+- Protocol: newline-delimited JSON-RPC 2.0, `initialize` / `tools/list` /+ `tools/call` / `ping`; notifications produce no response.diff --git a/skills/drawio-skill/references/pr-bot.md b/skills/drawio-skill/references/pr-bot.mdindex 5ce016a..20ba346 100644--- a/skills/drawio-skill/references/pr-bot.md+++ b/skills/drawio-skill/references/pr-bot.md@@ -26,6 +26,19 @@ review for a repo.## Adopting it in your own repo+Without copying anything, reference this repo's action directly:++```yaml+- uses: Agents365-ai/drawio-skill/.github/actions/drawio-diff@main+```++(Pin to a tag for reproducibility; the action checks out its own skill+scripts via `github.action_repository`.) The pure-Python+`drawio-architecture-test` gate needs no desktop tools at all —+see `references/ci-gate.md`.++Alternatively, vendor the pieces:+1. Copy `.github/actions/drawio-diff/` and `skills/drawio-skill/` (or atleast `scripts/prdiff.py`, `scripts/drawiodiff.py`, `scripts/autolayout.py`)into your repo.diff --git a/skills/drawio-skill/references/toolbox.md b/skills/drawio-skill/references/toolbox.mdindex 3c0c89a..ca8b807 100644--- a/skills/drawio-skill/references/toolbox.md+++ b/skills/drawio-skill/references/toolbox.md@@ -1,6 +1,7 @@# Toolbox — every bundled script, by use-case-A map of the 39 focused tools, the unified `diagramctl.py` orchestrator, and its+A map of the 39 focused tools, the unified `diagramctl.py` orchestrator+(and its MCP server wrapper), and itsinternal `diagram_ir.py` model grouped by what you're trying to do. Theper-task routing table in `SKILL.md` says *when* to reach for each; this says*how they fit together*. Read it when you're not sure which script a request@@ -10,14 +11,14 @@ The recurring backbone is one pipeline — an **extractor** emits graph JSON, th`autolayout.py` places it, then `validate.py` lints it, then the draw.io CLIexports it:-```+```text<extractor> → graph.json → autolayout.py → diagram.drawio → validate.py → (export PNG/SVG/PDF)```For new workflows, prefer the semantic backbone. It retains provenance andsupports incremental updates instead of one-shot regeneration:-```+```textsource → diagramctl build → Diagram IR → views/test/review/story↕diagramctl sync ↔ existing .drawio@@ -29,7 +30,7 @@ Use focused scripts directly when you need their narrow interface; use## Quick decision guide| I have… | I want… | Use |-|---|---|---|+| --- | --- | --- || a description in words | a styled diagram | hand-write XML (`references/xml-authoring.md`) or `autolayout.py` || code/IaC/spec/IR | one command that detects, builds, and records provenance | `diagramctl build` || a source-backed `.drawio` + changed source | update it without losing manual layout/style | `diagramctl sync` |diff --git a/skills/drawio-skill/scripts/diagramctl_mcp.py b/skills/drawio-skill/scripts/diagramctl_mcp.pynew file mode 100644index 0000000..0787dfd--- /dev/null+++ b/skills/drawio-skill/scripts/diagramctl_mcp.py@@ -0,0 +1,361 @@+#!/usr/bin/env python3+"""Minimal MCP (Model Context Protocol) stdio server for diagramctl.++Stdlib-only JSON-RPC 2.0 over newline-delimited stdin/stdout, so any MCP host+(Claude Desktop, Cursor, VS Code, ...) can run the skill's semantic workflows+without installing the `mcp` package. Each tool call shells out to+`diagramctl.py`, the same stable CLI surface agents use directly. No tool in+this server performs network access.++Run: python3 scripts/diagramctl_mcp.py+"""++from __future__ import annotations++import json+import subprocess+import sys+from pathlib import Path++HERE = Path(__file__).resolve().parent+DIAGRAMCTL = HERE / "diagramctl.py"+PROTOCOL_VERSION = "2024-11-05"+SERVER_INFO = {"name": "drawio-skill", "version": "3.1.0"}+CALL_TIMEOUT_SECONDS = 180++# Every tool maps 1:1 to a diagramctl subcommand. Paths are resolved relative+# to the server process CWD (whatever the host launched it from).+++def _schema(props, required):+ return {+ "type": "object",+ "properties": props,+ "required": required,+ "additionalProperties": False,+ }+++TOOLS = [+ {+ "name": "doctor",+ "description": (+ "Check the local drawio-skill environment: python version, draw.io CLI, "+ "Graphviz, optional packages, and capability flags. Safe, nothing is "+ "launched."+ ),+ "inputSchema": _schema(+ {"probe": {"type": "boolean", "description": "Also run drawio --version"}},+ [],+ ),+ "argv": lambda a: ["doctor"] + (["--probe"] if a.get("probe") else []),+ },+ {+ "name": "build",+ "description": (+ "Build an editable .drawio diagram from code, IaC, SQL, OpenAPI, "+ "compose, a graph JSON, or an existing IR file. Auto-detects the "+ "source type. Returns a JSON report and writes the .drawio (and "+ "optionally the IR JSON)."+ ),+ "inputSchema": _schema(+ {+ "source": {"type": "string", "description": "Path to source dir/file"},+ "output": {"type": "string", "description": "Output .drawio path"},+ "source_type": {+ "type": "string",+ "description": "Override auto-detection "+ "(python|javascript|go|rust|pyclasses|terraform|kubernetes|"+ "compose|sql|openapi|ci|graph|ir|drawio)",+ },+ "group": {+ "type": "boolean",+ "description": "Group nodes by module/namespace",+ },+ "views": {+ "type": "string",+ "description": "Comma-separated views: executive,system,deployment,dataflow,security",+ },+ "title": {"type": "string"},+ },+ ["source", "output"],+ ),+ "argv": lambda a: ["build", a["source"], "-o", a["output"]]+ + (["--from", a["source_type"]] if a.get("source_type") else [])+ + (["--group"] if a.get("group") else [])+ + (["--views", a["views"]] if a.get("views") else [])+ + (["--title", a["title"]] if a.get("title") else []),+ },+ {+ "name": "sync",+ "description": (+ "Incrementally update an existing .drawio from its (changed) source "+ "while preserving manual geometry and styling. Removals are staged "+ "for review unless prune is set."+ ),+ "inputSchema": _schema(+ {+ "diagram": {"type": "string", "description": "Existing .drawio file"},+ "source": {+ "type": "string",+ "description": "Fresh source to sync from",+ },+ "output": {"type": "string", "description": "Updated .drawio path"},+ "prune": {+ "type": "boolean",+ "description": "Explicitly remove elements gone from the source",+ },+ },+ ["diagram", "source", "output"],+ ),+ "argv": lambda a: ["sync", a["diagram"], a["source"], "-o", a["output"]]+ + (["--prune"] if a.get("prune") else []),+ },+ {+ "name": "views",+ "description": (+ "Project one Diagram IR file into linked audience/concern views "+ "(executive, system, deployment, dataflow, security) as a multi-page "+ ".drawio."+ ),+ "inputSchema": _schema(+ {+ "input": {"type": "string", "description": "Diagram IR JSON path"},+ "output": {"type": "string", "description": "Output .drawio path"},+ "views": {+ "type": "string",+ "description": "Comma-separated view names (default: all five)",+ },+ "direction": {"type": "string", "enum": ["TB", "LR"]},+ },+ ["input", "output"],+ ),+ "argv": lambda a: ["views", a["input"], "-o", a["output"]]+ + (["--views", a["views"]] if a.get("views") else [])+ + (["--direction", a["direction"]] if a.get("direction") else []),+ },+ {+ "name": "architecture_test",+ "description": (+ "Run deterministic architecture contract rules (direct "+ "Internet-to-database access, cycles, orphans, ownership, production "+ "observability, external timeouts, trust-boundary protocols, contrast) "+ "against a Diagram IR file. Exit is reflected in isError."+ ),+ "inputSchema": _schema(+ {+ "input": {"type": "string", "description": "Diagram IR JSON path"},+ "rules": {+ "type": "string",+ "description": "Optional JSON/YAML policy path (default: all rules)",+ },+ "strict": {"type": "boolean", "description": "Fail on warnings too"},+ },+ ["input"],+ ),+ "argv": lambda a: ["test", a["input"]]+ + (["--rules", a["rules"]] if a.get("rules") else [])+ + (["--strict"] if a.get("strict") else []),+ },+ {+ "name": "review",+ "description": (+ "Review an architecture model for ownership, resilience, trust "+ "boundaries, and accessibility; returns a Markdown or JSON report."+ ),+ "inputSchema": _schema(+ {+ "input": {"type": "string", "description": "Diagram IR JSON path"},+ "format": {"type": "string", "enum": ["markdown", "json"]},+ },+ ["input"],+ ),+ "argv": lambda a: [+ "review",+ a["input"],+ "--format",+ a.get("format", "markdown"),+ ],+ },+ {+ "name": "query",+ "description": (+ "Query a Diagram IR: filter nodes by kind/owner/boundary, or find the "+ "directed path between two components."+ ),+ "inputSchema": _schema(+ {+ "input": {"type": "string", "description": "Diagram IR JSON path"},+ "kind": {"type": "string"},+ "owner": {"type": "string"},+ "boundary": {"type": "string"},+ "from": {"type": "string", "description": "Path query: start node id"},+ "to": {"type": "string", "description": "Path query: end node id"},+ },+ ["input"],+ ),+ "argv": lambda a: ["query", a["input"]]+ + sum(+ (+ [f"--{k.replace('_', '-')}", a[k]]+ for k in ("kind", "owner", "boundary", "from", "to")+ if a.get(k)+ ),+ [],+ ),+ },+ {+ "name": "whatif",+ "description": (+ "Simulate failure propagation from one component: downstream impact, "+ "isolation points, and an optional red/amber annotated .drawio."+ ),+ "inputSchema": _schema(+ {+ "input": {"type": "string", "description": "Diagram IR JSON path"},+ "fail": {"type": "string", "description": "Node id or label to fail"},+ "drawio": {+ "type": "string",+ "description": "Optional annotated .drawio output path",+ },+ },+ ["input", "fail"],+ ),+ "argv": lambda a: ["whatif", a["input"], "--fail", a["fail"]]+ + (["--drawio", a["drawio"]] if a.get("drawio") else []),+ },+ {+ "name": "story",+ "description": (+ "Publish an accessible, self-contained offline HTML walkthrough of "+ "the model (keyboard navigation, text alternative, multilingual "+ "labels)."+ ),+ "inputSchema": _schema(+ {+ "input": {"type": "string", "description": "Diagram IR JSON path"},+ "output": {"type": "string", "description": "Output .html path"},+ "title": {"type": "string"},+ "fail": {+ "type": "string",+ "description": "Optional failure-scenario node",+ },+ },+ ["input", "output"],+ ),+ "argv": lambda a: ["story", a["input"], "-o", a["output"]]+ + (["--title", a["title"]] if a.get("title") else [])+ + (["--fail", a["fail"]] if a.get("fail") else []),+ },+]+++def call_tool(name, arguments):+ tool = next((t for t in TOOLS if t["name"] == name), None)+ if tool is None:+ raise KeyError(f"unknown tool {name!r}")+ argv = [sys.executable, str(DIAGRAMCTL)] + tool["argv"](arguments or {})+ proc = subprocess.run(+ argv, capture_output=True, text=True, timeout=CALL_TIMEOUT_SECONDS+ )+ text = (proc.stdout or proc.stderr).strip()+ if proc.returncode == 2: # usage/argument error from diagramctl+ raise ValueError(f"diagramctl rejected the arguments: {text}")+ return proc.returncode, text+++def dispatch(method, params):+ if method == "initialize":+ return {+ "protocolVersion": PROTOCOL_VERSION,+ "capabilities": {"tools": {}},+ "serverInfo": SERVER_INFO,+ }+ if method == "ping":+ return {}+ if method == "tools/list":+ return {+ "tools": [+ {+ "name": t["name"],+ "description": t["description"],+ "inputSchema": t["inputSchema"],+ }+ for t in TOOLS+ ]+ }+ if method == "tools/call":+ name = params.get("name", "")+ try:+ code, text = call_tool(name, params.get("arguments") or {})+ except KeyError:+ raise MethodError(-32602, f"unknown tool {name!r}") from None+ except ValueError as exc:+ return {"content": [{"type": "text", "text": str(exc)}], "isError": True}+ except subprocess.TimeoutExpired:+ return {+ "content": [+ {+ "type": "text",+ "text": f"{name} timed out after {CALL_TIMEOUT_SECONDS}s",+ }+ ],+ "isError": True,+ }+ return {+ "content": [{"type": "text", "text": text}],+ "isError": code not in (0, 1),+ }+ raise MethodError(-32601, f"method not found: {method}")+++class MethodError(Exception):+ def __init__(self, code, message):+ super().__init__(message)+ self.code = code+ self.message = message+++def handle(line):+ """Handle one JSON-RPC message; returns a response dict or None (notification)."""+ try:+ msg = json.loads(line)+ except ValueError:+ return {+ "jsonrpc": "2.0",+ "id": None,+ "error": {"code": -32700, "message": "parse error"},+ }+ method = msg.get("method", "")+ is_notification = "id" not in msg+ if method.startswith("notifications/"):+ return None+ try:+ result = dispatch(method, msg.get("params") or {})+ return (+ None+ if is_notification+ else {"jsonrpc": "2.0", "id": msg["id"], "result": result}+ )+ except MethodError as exc:+ return (+ None+ if is_notification+ else {+ "jsonrpc": "2.0",+ "id": msg.get("id"),+ "error": {"code": exc.code, "message": exc.message},+ }+ )+++def main():+ for line in sys.stdin:+ response = handle(line)+ if response is not None:+ sys.stdout.write(json.dumps(response, ensure_ascii=False) + "\n")+ sys.stdout.flush()+++if __name__ == "__main__":+ main()diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.pynew file mode 100644index 0000000..9090688--- /dev/null+++ b/tests/test_mcp_server.py@@ -0,0 +1,165 @@+#!/usr/bin/env python3+"""Tests for the diagramctl MCP stdio server (scripts/diagramctl_mcp.py)."""++import importlib.util+import json+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++HERE = Path(__file__).resolve().parent+SCRIPTS = HERE.parent / "skills" / "drawio-skill" / "scripts"++_spec = importlib.util.spec_from_file_location(+ "diagramctl_mcp", SCRIPTS / "diagramctl_mcp.py"+)+assert _spec is not None and _spec.loader is not None+mcp = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(mcp)++GRAPH = {+ "nodes": [+ {"id": "web", "label": "Web", "kind": "service"},+ {"id": "db", "label": "Orders DB", "kind": "database"},+ ],+ "edges": [{"source": "web", "target": "db", "label": "SQL"}],+}+++def rpc(method, params=None, id=1):+ line = json.dumps(+ {"jsonrpc": "2.0", "id": id, "method": method, "params": params or {}}+ )+ return mcp.handle(line)+++class TestMcpProtocol(unittest.TestCase):+ def test_initialize(self):+ resp = rpc("initialize")+ self.assertEqual(resp["result"]["serverInfo"]["name"], "drawio-skill")+ self.assertIn("protocolVersion", resp["result"])++ def test_notification_returns_none(self):+ self.assertIsNone(+ mcp.handle(+ json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"})+ )+ )++ def test_ping(self):+ self.assertEqual(rpc("ping")["result"], {})++ def test_unknown_method(self):+ resp = rpc("nope/nope")+ self.assertEqual(resp["error"]["code"], -32601)++ def test_parse_error(self):+ resp = mcp.handle("{broken")+ self.assertEqual(resp["error"]["code"], -32700)++ def test_unknown_tool(self):+ resp = rpc("tools/call", {"name": "bogus"})+ self.assertEqual(resp["error"]["code"], -32602)+++class TestMcpTools(unittest.TestCase):+ def test_tools_list(self):+ tools = rpc("tools/list")["result"]["tools"]+ names = {t["name"] for t in tools}+ self.assertTrue(+ {+ "doctor",+ "build",+ "sync",+ "views",+ "architecture_test",+ "review",+ "query",+ "whatif",+ "story",+ }+ <= names+ )+ for tool in tools:+ self.assertEqual(tool["inputSchema"]["type"], "object")+ self.assertIn("description", tool)++ def test_doctor_call(self):+ resp = rpc("tools/call", {"name": "doctor"})+ result = resp["result"]+ self.assertFalse(result["isError"])+ self.assertIn("python", result["content"][0]["text"])++ def test_build_and_test_roundtrip(self):+ with tempfile.TemporaryDirectory() as td:+ graph = Path(td) / "graph.json"+ graph.write_text(json.dumps(GRAPH))+ out = Path(td) / "out.drawio"+ ir = Path(td) / "out.ir.json"+ resp = rpc(+ "tools/call",+ {+ "name": "build",+ "arguments": {+ "source": str(graph),+ "output": str(out),+ "source_type": "graph",+ },+ },+ )+ self.assertFalse(resp["result"]["isError"], resp["result"]["content"])+ self.assertTrue(out.exists())+ self.assertTrue(ir.exists() is False) # ir-output not requested+ report = json.loads(resp["result"]["content"][0]["text"])+ self.assertEqual(report["nodes"], 2)++ resp = rpc(+ "tools/call",+ {+ "name": "architecture_test",+ "arguments": {"input": str(ir if ir.exists() else graph)},+ },+ )+ # graph is not IR; the call must fail cleanly with isError, not crash+ if not resp["result"]["isError"]:+ self.assertIn("errors", resp["result"]["content"][0]["text"])++ def test_bad_arguments_is_clean_error(self):+ resp = rpc(+ "tools/call",+ {+ "name": "build",+ "arguments": {+ "source": "/nonexistent/xyz",+ "output": "/tmp/xyz.drawio",+ },+ },+ )+ self.assertTrue(resp["result"]["isError"])+++class TestMcpStdioProcess(unittest.TestCase):+ def test_end_to_end_stdio(self):+ msgs = [+ {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}},+ {"jsonrpc": "2.0", "method": "notifications/initialized"},+ {"jsonrpc": "2.0", "id": 2, "method": "tools/list"},+ ]+ payload = "\n".join(json.dumps(m) for m in msgs) + "\n"+ proc = subprocess.run(+ [sys.executable, str(SCRIPTS / "diagramctl_mcp.py")],+ input=payload,+ capture_output=True,+ text=True,+ timeout=60,+ )+ lines = [json.loads(line) for line in proc.stdout.splitlines() if line.strip()]+ self.assertEqual(len(lines), 2) # notifications produce no response+ self.assertEqual(lines[0]["result"]["serverInfo"]["name"], "drawio-skill")+ self.assertIn("tools", lines[1]["result"])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_skill_metadata.py b/tests/test_skill_metadata.pyindex a95e6c9..24c9991 100644--- a/tests/test_skill_metadata.py+++ b/tests/test_skill_metadata.py@@ -18,9 +18,10 @@ class TestSkillMetadata(unittest.TestCase):metadata_match = re.search(r"^metadata:\s*(\{.*\})\s*$", text, re.M)self.assertIsNotNone(metadata_match, "metadata JSON is missing")+ assert metadata_match is not Nonemetadata = json.loads(metadata_match.group(1))- self.assertEqual("3.0.0", metadata.get("version"))+ self.assertEqual("3.1.0", metadata.get("version"))self.assertEqual("https://github.com/Agents365-ai/drawio-skill", metadata.get("homepage"))