Skip to content

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.

feat: add Protocol Buffers importer (protoimports.py) (#120)

Tactical-Camell4664fcecb05d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 05555da..28950c3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,13 @@ semantic-ish versioning (the `metadata.version` field in
## [3.2.4] - 2026-09-11
+### Added
+
+- **Protobuf importer** (`protoimports.py`): parse Protocol Buffers (`.proto`)
+ files into service (with RPC methods), message (with typed fields), and enum
+ nodes with source provenance, request/response and field-type edges, and
+ optional package grouping.
+
### Changed
- **README / README_CN reorganized for readability**: the 26 flat Highlights
diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.md
index b550bc0..2141061 100644
--- a/skills/drawio-skill/SKILL.md
+++ b/skills/drawio-skill/SKILL.md
@@ -1,6 +1,6 @@
---
name: drawio-skill
-description: 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.
+description: 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/Protobuf 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: MIT
allowed-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.2.4","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"]}
@@ -21,6 +21,7 @@ and accessible publishing over a shared Diagram IR.
| Standard flowchart/mindmap/gantt/timeline/etc. with no special styling | If draw.io >=30, read `references/mermaid-authoring.md` and convert Mermaid to native `.drawio` |
| Large graph (~15+ nodes) that needs automatic layout | Use `autolayout.py`; read `references/autolayout.md` before passing any `--layout` value |
| Code, Terraform, K8s, compose, SQL, OpenAPI, or CI source | Use `diagramctl.py build`; read `references/diagram-ir.md` |
+| Protocol Buffers schema (.proto) | Use `protoimports.py` or `diagramctl.py build`; read `references/toolbox.md` |
| Running cluster/stack/cloud (actual state, not declared config) | Read `references/live-infra.md`, then use `tfstate.py`, `dockerimports.py`, or `k8simports.py -` |
| 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` |
diff --git a/skills/drawio-skill/references/cookbook.md b/skills/drawio-skill/references/cookbook.md
index b712e2e..f88f0d6 100644
--- a/skills/drawio-skill/references/cookbook.md
+++ b/skills/drawio-skill/references/cookbook.md
@@ -128,6 +128,14 @@ Turn schema.sql into an ER diagram with PK/FK markers and crow's-foot
notation; keep schema prefixes for the billing tables.
```
+## Protobuf / gRPC architecture diagram
+
+```text
+Turn our Protocol Buffers schemas under ./proto into a service and message diagram.
+Show RPC methods on the service nodes, group by proto package, and link request/response
+and referenced field types. Output PNG + editable .drawio.
+```
+
## ML / deep-learning model
```text
diff --git a/skills/drawio-skill/references/toolbox.md b/skills/drawio-skill/references/toolbox.md
index 7396f8b..ee5a90a 100644
--- a/skills/drawio-skill/references/toolbox.md
+++ b/skills/drawio-skill/references/toolbox.md
@@ -43,6 +43,7 @@ Use focused scripts directly when you need their narrow interface; use
| a running cluster/stack/cloud | what's **actually deployed** | `tfstate` · `dockerimports` · `k8simports -` |
| a SQL schema | an ER diagram | `sqlerd` |
| an OpenAPI / Swagger spec | an API diagram (by method) | `openapiimports` |
+| a Protocol Buffers (.proto) schema | a message/service diagram | `protoimports` |
| CI workflows (GH Actions / GitLab) | the pipeline as a DAG | `ciimports` |
| a diagram + a metrics file | it coloured by the data | `heatmap` |
| a sequence of interactions | a UML sequence diagram | `seqlayout` |
@@ -88,6 +89,7 @@ All emit graph JSON → `autolayout.py`.
- **`sqlerd.py`** — SQL DDL (`CREATE TABLE`) → ERD with crow's-foot FK edges.
- **`ciimports.py`** — GitHub Actions (`.github/workflows/*.yml`) and/or `.gitlab-ci.yml` -> pipeline DAG: job nodes (runner, `matrix xN`, reusable-workflow calls in purple), `needs:` edges, an `on:` trigger node per workflow, jobs boxed per workflow / per GitLab stage.
- **`openapiimports.py`** — OpenAPI 3 / Swagger 2 spec → API diagram: one node per operation (coloured by HTTP method) + one per component schema, with edges to the schemas each operation uses and between nested schemas. `--group` by tag.
+- **`protoimports.py`** — Protocol Buffers (`.proto`) → message/service diagram: one node per message, service (with RPC methods), or enum; edges for referenced message field types and service request/response types. `--group` by proto package.
## 4. Live infrastructure → diagram (actually running)
diff --git a/skills/drawio-skill/scripts/diagram_ir.py b/skills/drawio-skill/scripts/diagram_ir.py
index f7e5a29..384b1d6 100644
--- a/skills/drawio-skill/scripts/diagram_ir.py
+++ b/skills/drawio-skill/scripts/diagram_ir.py
@@ -425,11 +425,21 @@ def _grid_page(graph, page_id, name):
style = html.escape(node.get("style") or DEFAULT_NODE_STYLE, quote=True)
label = html.escape(str(node.get("label") or node["id"]), quote=True)
nid = html.escape(node["id"], quote=True)
- cells.append(
- f' <mxCell id="{nid}" value="{label}" style="{style}" vertex="1" parent="1">\n'
- f' <mxGeometry x="{x}" y="{y}" width="{node.get("width", 160)}" height="{node.get("height", 70)}" as="geometry"/>\n'
- f" </mxCell>"
- )
+ if "link" in node:
+ link = html.escape(str(node["link"]), quote=True)
+ cells.append(
+ f' <UserObject id="{nid}" label="{label}" link="{link}">\n'
+ f' <mxCell style="{style}" vertex="1" parent="1">\n'
+ f' <mxGeometry x="{x}" y="{y}" width="{node.get("width", 160)}" height="{node.get("height", 70)}" as="geometry"/>\n'
+ f' </mxCell>\n'
+ f' </UserObject>'
+ )
+ else:
+ cells.append(
+ f' <mxCell id="{nid}" value="{label}" style="{style}" vertex="1" parent="1">\n'
+ f' <mxGeometry x="{x}" y="{y}" width="{node.get("width", 160)}" height="{node.get("height", 70)}" as="geometry"/>\n'
+ f" </mxCell>"
+ )
for i, edge in enumerate(graph.get("edges", [])):
cells.append(
f' <mxCell id="edge-{page_id}-{i}" value="{html.escape(edge.get("label", ""), quote=True)}" '
diff --git a/skills/drawio-skill/scripts/diagramctl.py b/skills/drawio-skill/scripts/diagramctl.py
index b2d3114..963a75d 100644
--- a/skills/drawio-skill/scripts/diagramctl.py
+++ b/skills/drawio-skill/scripts/diagramctl.py
@@ -51,6 +51,7 @@ IMPORTERS = {
"compose": "composeimports.py",
"sql": "sqlerd.py",
"openapi": "openapiimports.py",
+ "proto": "protoimports.py",
"ci": "ciimports.py",
}
CODE_IMPORTERS = {"python", "javascript", "js", "go", "rust", "pyclasses"}
@@ -80,6 +81,8 @@ def emit(value, output=None):
def detect_source(path):
p = Path(path)
if p.is_dir():
+ if list(p.rglob("*.proto")):
+ return "proto"
if list(p.rglob("*.tf")):
return "terraform"
if (p / "Cargo.toml").exists():
@@ -92,6 +95,8 @@ def detect_source(path):
return "ci"
return "python"
suffix = p.suffix.lower()
+ if suffix == ".proto":
+ return "proto"
if suffix == ".sql":
return "sql"
if suffix in {".tf", ".tfvars"}:
@@ -161,6 +166,7 @@ def importer_ir(source, source_type, group=False):
"rust",
"pyclasses",
"openapi",
+ "proto",
}:
cmd.insert(-2, "--group")
proc = subprocess.run(cmd, text=True, capture_output=True)
@@ -500,7 +506,8 @@ def parser():
p.set_defaults(func=cmd_doctor)
p = sub.add_parser(
- "build", help="build a draw.io from IR, graph JSON, code, IaC, SQL or OpenAPI"
+ "build",
+ help="build a draw.io from IR, graph JSON, code, IaC, SQL, OpenAPI or Protobuf",
)
p.add_argument("source")
p.add_argument("-o", "--output", required=True)
diff --git a/skills/drawio-skill/scripts/protoimports.py b/skills/drawio-skill/scripts/protoimports.py
new file mode 100755
index 0000000..d22b339
--- /dev/null
+++ b/skills/drawio-skill/scripts/protoimports.py
@@ -0,0 +1,545 @@
+#!/usr/bin/env python3
+"""Turn Protocol Buffers (.proto) schemas into a diagram as autolayout graph JSON.
+
+Parses .proto files (file or directory) into nodes for services (with RPC methods),
+messages (with fields), and enums (with values), connected by edges for service
+request/response types and referenced message field types.
+
+Feeds autolayout.py:
+ python3 protoimports.py ./proto --group -o graph.json
+ python3 autolayout.py graph.json -o services.drawio
+
+Supports proto2 and proto3 syntax using a stdlib-only parser (no protoc required).
+Tolerates imports, options, and reserved declarations by skipping them.
+
+Usage: python3 protoimports.py <file.proto-or-dir> [-o graph.json]
+ [--direction TB|LR] [--group]
+"""
+import argparse
+import glob
+import json
+import os
+import re
+import sys
+
+SERVICE_STYLE = (
+ "rounded=1;whiteSpace=wrap;html=1;align=left;verticalAlign=top;"
+ "spacingLeft=8;spacingTop=6;fillColor=#dae8fc;strokeColor=#6c8ebf;"
+)
+MESSAGE_STYLE = (
+ "rounded=1;whiteSpace=wrap;html=1;align=left;verticalAlign=top;"
+ "spacingLeft=8;spacingTop=6;fillColor=#e1d5e7;strokeColor=#9673a6;"
+)
+ENUM_STYLE = (
+ "rounded=1;whiteSpace=wrap;html=1;align=left;verticalAlign=top;"
+ "spacingLeft=8;spacingTop=6;fillColor=#fff2cc;strokeColor=#d6b656;"
+)
+
+SERVICE_EDGE = (
+ "edgeStyle=orthogonalEdgeStyle;html=1;rounded=0;fontSize=10;"
+ "endArrow=open;strokeColor=#6c8ebf;"
+)
+REF_EDGE = (
+ "edgeStyle=orthogonalEdgeStyle;html=1;rounded=0;fontSize=10;"
+ "dashed=1;endArrow=open;strokeColor=#9673a6;"
+)
+
+SCALAR_TYPES = {
+ "double", "float", "int32", "int64", "uint32", "uint64",
+ "sint32", "sint64", "fixed32", "fixed64", "sfixed32", "sfixed64",
+ "bool", "string", "bytes",
+}
+
+TOKEN_RE = re.compile(
+ r"""
+ (?P<STRING>"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')
+ | (?P<NUM>-?[0-9]+(?:\.[0-9]+)?)
+ | (?P<IDENT>[A-Za-z_][A-Za-z0-9_.]*)
+ | (?P<SYM>[{}();=<>:,\[\]])
+ | (?P<WS>\s+)
+""",
+ re.VERBOSE,
+)
+
+
+class Token:
+ __slots__ = ("kind", "value", "line")
+
+ def __init__(self, kind, value, line):
+ self.kind = kind
+ self.value = value
+ self.line = line
+
+
+def strip_comments(text):
+ def repl_block(m):
+ return "\n" * m.group(0).count("\n")
+
+ text = re.sub(r"/\*.*?\*/", repl_block, text, flags=re.DOTALL)
+ text = re.sub(r"//[^\n]*", "", text)
+ return text
+
+
+def tokenize(text):
+ tokens = []
+ line = 1
+ pos = 0
+ text = strip_comments(text)
+ for m in TOKEN_RE.finditer(text):
+ kind = m.lastgroup
+ val = m.group()
+ line += text[pos:m.start()].count("\n")
+ pos = m.start()
+ if kind != "WS":
+ tokens.append(Token(kind, val, line))
+ line += val.count("\n")
+ pos = m.end()
+ return tokens
+
+
+def parse_proto(text, file_path=""):
+ tokens = tokenize(text)
+ idx = 0
+ n = len(tokens)
+
+ package = ""
+ enums = []
+ messages = []
+ services = []
+
+ def peek(offset=0):
+ pos = idx + offset
+ return tokens[pos] if pos < n else None
+
+ def advance():
+ nonlocal idx
+ tok = tokens[idx]
+ idx += 1
+ return tok
+
+ def match(val):
+ t = peek()
+ if t and t.value == val:
+ advance()
+ return True
+ return False
+
+ def skip_until_semi():
+ depth = 0
+ bracket_depth = 0
+ nonlocal idx
+ while idx < n:
+ t = advance()
+ if t.value == "{":
+ depth += 1
+ elif t.value == "}":
+ depth -= 1
+ if depth <= 0 and bracket_depth == 0:
+ break
+ elif t.value == "[":
+ bracket_depth += 1
+ elif t.value == "]":
+ bracket_depth -= 1
+ elif t.value == ";" and depth == 0 and bracket_depth == 0:
+ break
+
+ def parse_enum(scope=""):
+ enum_tok = advance()
+ name = enum_tok.value
+ full_name = f"{scope}.{name}" if scope else name
+ line = enum_tok.line
+ values = []
+ if not match("{"):
+ return
+ while idx < n:
+ t = peek()
+ if not t or t.value == "}":
+ advance()
+ break
+ if t.value in ("option", "reserved"):
+ skip_until_semi()
+ continue
+ val_name = advance().value
+ if match("="):
+ val_num = advance().value
+ values.append((val_name, val_num))
+ skip_until_semi()
+ else:
+ skip_until_semi()
+ enums.append({
+ "name": name,
+ "full_name": full_name,
+ "values": values,
+ "line": line,
+ "file": file_path,
+ "package": package,
+ })
+
+ def parse_service():
+ srv_tok = advance()
+ name = srv_tok.value
+ line = srv_tok.line
+ rpcs = []
+ if not match("{"):
+ return
+ while idx < n:
+ t = peek()
+ if not t or t.value == "}":
+ advance()
+ break
+ if t.value == "rpc":
+ advance()
+ rpc_tok = advance()
+ rpc_name = rpc_tok.value
+ rpc_line = rpc_tok.line
+ req_stream = False
+ resp_stream = False
+
+ match("(")
+ if match("stream"):
+ req_stream = True
+ req_type = advance().value
+ match(")")
+
+ match("returns")
+
+ match("(")
+ if match("stream"):
+ resp_stream = True
+ resp_type = advance().value
+ match(")")
+
+ t2 = peek()
+ if t2 and t2.value == "{":
+ skip_until_semi()
+ elif t2 and t2.value == ";":
+ advance()
+ rpcs.append({
+ "name": rpc_name,
+ "req_type": req_type,
+ "req_stream": req_stream,
+ "resp_type": resp_type,
+ "resp_stream": resp_stream,
+ "line": rpc_line,
+ })
+ else:
+ skip_until_semi()
+ services.append({
+ "name": name,
+ "full_name": name,
+ "rpcs": rpcs,
+ "line": line,
+ "file": file_path,
+ "package": package,
+ })
+
+ def parse_message(scope=""):
+ msg_tok = advance()
+ name = msg_tok.value
+ full_name = f"{scope}.{name}" if scope else name
+ line = msg_tok.line
+ fields = []
+ if not match("{"):
+ return
+ while idx < n:
+ t = peek()
+ if not t or t.value == "}":
+ advance()
+ break
+ if t.value == "message":
+ advance()
+ parse_message(scope=full_name)
+ elif t.value == "enum":
+ advance()
+ parse_enum(scope=full_name)
+ elif t.value == "oneof":
+ advance()
+ oneof_name = advance().value
+ if match("{"):
+ while idx < n:
+ o_tok = peek()
+ if not o_tok or o_tok.value == "}":
+ advance()
+ break
+ f_type = advance().value
+ f_name = advance().value
+ f_line = o_tok.line
+ fields.append({
+ "name": f_name,
+ "type": f_type,
+ "modifier": "oneof",
+ "oneof": oneof_name,
+ "line": f_line,
+ })
+ skip_until_semi()
+ elif t.value in ("option", "reserved", "extensions"):
+ skip_until_semi()
+ elif t.value == "map":
+ advance()
+ match("<")
+ k_type = advance().value
+ match(",")
+ v_type = advance().value
+ match(">")
+ f_tok = advance()
+ f_name = f_tok.value
+ fields.append({
+ "name": f_name,
+ "type": f"map<{k_type}, {v_type}>",
+ "val_type": v_type,
+ "modifier": "map",
+ "line": f_tok.line,
+ })
+ skip_until_semi()
+ else:
+ modifier = ""
+ if t.value in ("repeated", "optional", "required"):
+ modifier = advance().value
+ f_type_tok = advance()
+ f_type = f_type_tok.value
+ f_name_tok = advance()
+ f_name = f_name_tok.value
+ fields.append({
+ "name": f_name,
+ "type": f_type,
+ "modifier": modifier,
+ "line": f_type_tok.line,
+ })
+ skip_until_semi()
+ messages.append({
+ "name": name,
+ "full_name": full_name,
+ "fields": fields,
+ "line": line,
+ "file": file_path,
+ "package": package,
+ })
+
+ while idx < n:
+ tok = peek()
+ if not tok:
+ break
+ if tok.value == "package":
+ advance()
+ package = advance().value
+ match(";")
+ elif tok.value in ("syntax", "import", "option"):
+ skip_until_semi()
+ elif tok.value == "enum":
+ advance()
+ parse_enum()
+ elif tok.value == "message":
+ advance()
+ parse_message()
+ elif tok.value == "service":
+ advance()
+ parse_service()
+ else:
+ advance()
+
+ return {
+ "package": package,
+ "enums": enums,
+ "messages": messages,
+ "services": services,
+ }
+
+
+def compute_dimensions(lines):
+ width = max(160, -(-max(7 * len(l) + 30 for l in lines) // 10) * 10)
+ height = max(50, -(-(30 + 18 * len(lines)) // 10) * 10)
+ return width, height
+
+
+def build(proto_data_list, group=False, direction="TB"):
+ """List of parse_proto dicts -> autolayout graph JSON."""
+ nodes = []
+ edges = []
+ seen_edges = set()
+
+ # Build symbol map: qualified name & short name -> node_id
+ # Also index by package
+ all_symbols = {}
+ package_symbols = {}
+
+ # Assign IDs
+ # If package exists, prefix with package to ensure uniqueness across packages
+ for data in proto_data_list:
+ pkg = data.get("package", "")
+ for s in data["services"]:
+ nid = f"{pkg}.{s['name']}" if pkg else s["name"]
+ s["id"] = nid
+ all_symbols[nid] = nid
+ all_symbols[s["name"]] = nid
+ package_symbols.setdefault(pkg, {})[s["name"]] = nid
+
+ for m in data["messages"]:
+ nid = f"{pkg}.{m['full_name']}" if pkg else m["full_name"]
+ m["id"] = nid
+ all_symbols[nid] = nid
+ all_symbols[m["full_name"]] = nid
+ all_symbols[m["name"]] = nid
+ package_symbols.setdefault(pkg, {})[m["full_name"]] = nid
+ package_symbols.setdefault(pkg, {})[m["name"]] = nid
+
+ for e in data["enums"]:
+ nid = f"{pkg}.{e['full_name']}" if pkg else e["full_name"]
+ e["id"] = nid
+ all_symbols[nid] = nid
+ all_symbols[e["full_name"]] = nid
+ all_symbols[e["name"]] = nid
+ package_symbols.setdefault(pkg, {})[e["full_name"]] = nid
+ package_symbols.setdefault(pkg, {})[e["name"]] = nid
+
+ def resolve(type_name, current_pkg=""):
+ if type_name in SCALAR_TYPES:
+ return None
+ # Check current package first
+ pkg_map = package_symbols.get(current_pkg, {})
+ if type_name in pkg_map:
+ return pkg_map[type_name]
+ # Then global table
+ return all_symbols.get(type_name)
+
+ def add_edge(src, dst, style, label="", line=0, file_path=""):
+ key = (src, dst, label)
+ if src != dst and key not in seen_edges:
+ seen_edges.add(key)
+ edge = {
+ "source": src,
+ "target": dst,
+ "style": style,
+ "label": label,
+ }
+ if file_path or line:
+ edge["provenance"] = {"path": file_path, "line": line}
+ edges.append(edge)
+
+ for data in proto_data_list:
+ pkg = data.get("package", "")
+
+ for s in data["services"]:
+ lines = [f"«service»\n{s['name']}", "—"]
+ if s["rpcs"]:
+ for r in s["rpcs"]:
+ req = f"stream {r['req_type']}" if r["req_stream"] else r["req_type"]
+ resp = f"stream {r['resp_type']}" if r["resp_stream"] else r["resp_type"]
+ lines.append(f"{r['name']}({req}): {resp}")
+ else:
+ lines.append("(no rpcs)")
+
+ w, h = compute_dimensions(lines)
+ node = {
+ "id": s["id"],
+ "label": "\n".join(lines),
+ "style": SERVICE_STYLE,
+ "width": w,
+ "height": h,
+ "provenance": {"path": s["file"], "line": s["line"]},
+ }
+ if group and pkg:
+ node["group"] = pkg
+ nodes.append(node)
+
+ for r in s["rpcs"]:
+ target_req = resolve(r["req_type"], pkg)
+ if target_req:
+ add_edge(s["id"], target_req, SERVICE_EDGE, r["name"], r["line"], s["file"])
+ target_resp = resolve(r["resp_type"], pkg)
+ if target_resp:
+ add_edge(s["id"], target_resp, SERVICE_EDGE, r["name"], r["line"], s["file"])
+
+ for m in data["messages"]:
+ lines = [m["full_name"], "—"]
+ if m["fields"]:
+ for f in m["fields"]:
+ prefix = f"{f['modifier']} " if f["modifier"] in ("repeated", "optional") else ""
+ lines.append(f"{f['name']}: {prefix}{f['type']}")
+ else:
+ lines.append("(no fields)")
+
+ w, h = compute_dimensions(lines)
+ node = {
+ "id": m["id"],
+ "label": "\n".join(lines),
+ "style": MESSAGE_STYLE,
+ "width": w,
+ "height": h,
+ "provenance": {"path": m["file"], "line": m["line"]},
+ }
+ if group and pkg:
+ node["group"] = pkg
+ nodes.append(node)
+
+ for f in m["fields"]:
+ ref_type = f.get("val_type") or f["type"]
+ target = resolve(ref_type, pkg)
+ if target:
+ add_edge(m["id"], target, REF_EDGE, f["name"], f["line"], m["file"])
+
+ for e in data["enums"]:
+ lines = [f"«enum»\n{e['full_name']}", "—"]
+ if e["values"]:
+ for v_name, v_num in e["values"]:
+ lines.append(f"{v_name} = {v_num}")
+ else:
+ lines.append("(empty)")
+
+ w, h = compute_dimensions(lines)
+ node = {
+ "id": e["id"],
+ "label": "\n".join(lines),
+ "style": ENUM_STYLE,
+ "width": w,
+ "height": h,
+ "provenance": {"path": e["file"], "line": e["line"]},
+ }
+ if group and pkg:
+ node["group"] = pkg
+ nodes.append(node)
+
+ return {"direction": direction, "nodes": nodes, "edges": edges}
+
+
+def main():
+ ap = argparse.ArgumentParser(description="Protocol Buffers (.proto) -> message/service graph JSON.")
+ ap.add_argument("path", help=".proto file or directory containing .proto files")
+ ap.add_argument("-o", "--output", help="output JSON path (default: stdout)")
+ ap.add_argument("--direction", default="TB", choices=["TB", "LR"])
+ ap.add_argument("--group", action="store_true", help="group messages and services by package")
+ args = ap.parse_args()
+
+ if os.path.isfile(args.path):
+ files = [args.path]
+ elif os.path.isdir(args.path):
+ files = sorted(glob.glob(os.path.join(args.path, "**", "*.proto"), recursive=True))
+ else:
+ sys.exit(f"error: {args.path} not found")
+
+ if not files:
+ sys.exit(f"error: no .proto files found under {args.path}")
+
+ parsed_list = []
+ for fpath in files:
+ with open(fpath, encoding="utf-8", errors="replace") as fh:
+ parsed_list.append(parse_proto(fh.read(), file_path=fpath))
+
+ graph = build(parsed_list, group=args.group, direction=args.direction)
+ text = json.dumps(graph, indent=2, ensure_ascii=False)
+ if args.output:
+ with open(args.output, "w", encoding="utf-8") as fh:
+ fh.write(text)
+ sys.stderr.write(f"wrote {args.output}\n")
+ else:
+ sys.stdout.write(text)
+
+ srv_count = sum(len(p["services"]) for p in parsed_list)
+ msg_count = sum(len(p["messages"]) for p in parsed_list)
+ enum_count = sum(len(p["enums"]) for p in parsed_list)
+ sys.stderr.write(
+ f"{srv_count} services, {msg_count} messages, {enum_count} enums, {len(graph['edges'])} edges\n"
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/test_protoimports.py b/tests/test_protoimports.py
new file mode 100644
index 0000000..8a53a86
--- /dev/null
+++ b/tests/test_protoimports.py
@@ -0,0 +1,213 @@
+import importlib.util
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+SCRIPT = os.path.join(ROOT, "skills", "drawio-skill", "scripts", "protoimports.py")
+DIAGRAMCTL = os.path.join(ROOT, "skills", "drawio-skill", "scripts", "diagramctl.py")
+
+
+def load_importer():
+ spec = importlib.util.spec_from_file_location("protoimports", SCRIPT)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+class TestProtoImports(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.importer = load_importer()
+
+ def test_services_messages_enums_and_edges(self):
+ proto = """
+ syntax = "proto3";
+ package bookstore.v1;
+
+ import "google/protobuf/timestamp.proto";
+ option go_package = "example.com/bookstore/v1";
+
+ enum Format {
+ FORMAT_UNSPECIFIED = 0;
+ FORMAT_HARDCOVER = 1;
+ FORMAT_PAPERBACK = 2;
+ FORMAT_EBOOK = 3;
+ }
+
+ message Author {
+ string id = 1;
+ string name = 2;
+ }
+
+ message Book {
+ string isbn = 1;
+ string title = 2;
+ Author author = 3;
+ Format format = 4;
+ repeated string tags = 5;
+ }
+
+ message GetBookRequest {
+ string isbn = 1;
+ }
+
+ message GetBookResponse {
+ Book book = 1;
+ }
+
+ service BookstoreService {
+ rpc GetBook (GetBookRequest) returns (GetBookResponse);
+ rpc ListBooks (GetBookRequest) returns (stream Book);
+ }
+ """
+ parsed = self.importer.parse_proto(proto, "bookstore.proto")
+ graph = self.importer.build([parsed], group=True, direction="TB")
+ by_id = {node["id"]: node for node in graph["nodes"]}
+ pairs = {(edge["source"], edge["target"]) for edge in graph["edges"]}
+
+ self.assertEqual(graph["direction"], "TB")
+ self.assertIn("bookstore.v1.BookstoreService", by_id)
+ self.assertIn("bookstore.v1.Book", by_id)
+ self.assertIn("bookstore.v1.Author", by_id)
+ self.assertIn("bookstore.v1.Format", by_id)
+
+ # Service node has RPC methods
+ srv_node = by_id["bookstore.v1.BookstoreService"]
+ self.assertEqual(srv_node["group"], "bookstore.v1")
+ self.assertIn("GetBook(GetBookRequest): GetBookResponse", srv_node["label"])
+ self.assertIn("ListBooks(GetBookRequest): stream Book", srv_node["label"])
+
+ # Service -> request/response edges
+ self.assertIn(
+ ("bookstore.v1.BookstoreService", "bookstore.v1.GetBookRequest"), pairs
+ )
+ self.assertIn(
+ ("bookstore.v1.BookstoreService", "bookstore.v1.GetBookResponse"), pairs
+ )
+ self.assertIn(("bookstore.v1.BookstoreService", "bookstore.v1.Book"), pairs)
+
+ # Message -> field type edges
+ self.assertIn(("bookstore.v1.Book", "bookstore.v1.Author"), pairs)
+ self.assertIn(("bookstore.v1.Book", "bookstore.v1.Format"), pairs)
+ self.assertIn(("bookstore.v1.GetBookResponse", "bookstore.v1.Book"), pairs)
+
+ def test_nested_messages_enums_and_maps(self):
+ proto = """
+ syntax = "proto3";
+ package shop;
+
+ message Cart {
+ enum State {
+ STATE_ACTIVE = 0;
+ STATE_ABANDONED = 1;
+ }
+ message Item {
+ string item_id = 1;
+ int32 qty = 2;
+ }
+ string cart_id = 1;
+ State state = 2;
+ repeated Item items = 3;
+ map<string, Item> item_map = 4;
+ }
+ """
+ parsed = self.importer.parse_proto(proto, "shop.proto")
+ graph = self.importer.build([parsed], group=False)
+ by_id = {node["id"]: node for node in graph["nodes"]}
+ pairs = {(edge["source"], edge["target"]) for edge in graph["edges"]}
+
+ self.assertIn("shop.Cart", by_id)
+ self.assertIn("shop.Cart.State", by_id)
+ self.assertIn("shop.Cart.Item", by_id)
+
+ self.assertIn(("shop.Cart", "shop.Cart.State"), pairs)
+ self.assertIn(("shop.Cart", "shop.Cart.Item"), pairs)
+
+ def test_cli_reads_file_and_directory(self):
+ with tempfile.TemporaryDirectory() as td:
+ p1 = os.path.join(td, "user.proto")
+ with open(p1, "w", encoding="utf-8") as f:
+ f.write("""
+ syntax = "proto3";
+ package users;
+ message User { string id = 1; string name = 2; }
+ """)
+
+ p2 = os.path.join(td, "auth.proto")
+ with open(p2, "w", encoding="utf-8") as f:
+ f.write("""
+ syntax = "proto3";
+ package users;
+ message AuthRequest { string username = 1; }
+ service AuthService {
+ rpc Login (AuthRequest) returns (User);
+ }
+ """)
+
+ # Run CLI on directory
+ out_json = os.path.join(td, "graph.json")
+ res = subprocess.run(
+ [sys.executable, SCRIPT, td, "--group", "-o", out_json],
+ capture_output=True,
+ text=True,
+ )
+ self.assertEqual(res.returncode, 0, res.stderr)
+ self.assertTrue(os.path.isfile(out_json))
+
+ with open(out_json, encoding="utf-8") as f:
+ graph = json.load(f)
+
+ node_ids = {n["id"] for n in graph["nodes"]}
+ self.assertIn("users.User", node_ids)
+ self.assertIn("users.AuthRequest", node_ids)
+ self.assertIn("users.AuthService", node_ids)
+
+ def test_diagramctl_auto_detects_proto(self):
+ with tempfile.TemporaryDirectory() as td:
+ proto_file = os.path.join(td, "service.proto")
+ with open(proto_file, "w", encoding="utf-8") as f:
+ f.write("""
+ syntax = "proto3";
+ package test;
+ message PingRequest {}
+ message PingResponse {}
+ service PingService {
+ rpc Ping (PingRequest) returns (PingResponse);
+ }
+ """)
+ out_drawio = os.path.join(td, "service.drawio")
+ ir_json = os.path.join(td, "service.ir.json")
+
+ res = subprocess.run(
+ [
+ sys.executable,
+ DIAGRAMCTL,
+ "build",
+ td,
+ "--group",
+ "--ir-output",
+ ir_json,
+ "-o",
+ out_drawio,
+ ],
+ capture_output=True,
+ text=True,
+ )
+ self.assertEqual(res.returncode, 0, res.stderr)
+ result_meta = json.loads(res.stdout)
+ self.assertEqual(result_meta["source_type"], "proto")
+ self.assertTrue(os.path.isfile(out_drawio))
+ self.assertTrue(os.path.isfile(ir_json))
+
+ with open(ir_json, encoding="utf-8") as f:
+ ir = json.load(f)
+ self.assertEqual(ir["metadata"]["importer"], "proto")
+ self.assertTrue(any(n["id"] == "test.PingService" for n in ir["nodes"]))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index 331b44b..95f6a41 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -1525,6 +1525,25 @@ class TestImportersCli(unittest.TestCase):
self.assertTrue(graph["nodes"][0]["id"].startswith("op"))
self.assertEqual(graph["edges"], [])
+ def test_protoimports_service_and_messages(self):
+ proto = (
+ "syntax = \"proto3\";\n"
+ "package service.v1;\n"
+ "message Req { string query = 1; }\n"
+ "message Resp { int32 total = 1; }\n"
+ "service SearchService {\n"
+ " rpc Search(Req) returns (Resp);\n"
+ "}\n"
+ )
+ with tempfile.TemporaryDirectory() as d:
+ p = os.path.join(d, "search.proto")
+ self._write(p, proto)
+ graph = json.loads(run("protoimports.py", p, "--group").stdout)
+ ids = {n["id"] for n in graph["nodes"]}
+ self.assertEqual(ids, {"service.v1.SearchService", "service.v1.Req", "service.v1.Resp"})
+ self.assertEqual(len(graph["edges"]), 2)
+ self.assertEqual({n.get("group") for n in graph["nodes"]}, {"service.v1"})
+
class TestDrawioHtml(unittest.TestCase):
@classmethod