Open-source Revit MCP server: let Claude and other AI assistants read and edit BIM models, with human approval on every change.
Python aecai-agentsautodeskautomationbimclaudeifcmcpmcp-servermodel-context-protocolnavisworksrevitrevit-addinrevit-apirhino
Add one-file Model review workbook (report_generator_build_review_pack) (#82)
A. Sam Mohammad98993365de56
diff --git a/docs/tools-generated.md b/docs/tools-generated.mdindex 46a9b3e..f4afeb0 100644--- a/docs/tools-generated.md+++ b/docs/tools-generated.md@@ -99,6 +99,7 @@ This catalog lists all tools exposed by the AEC Model Bridge providers.| `recipe_runner_list_recipes` | List the available automation recipes. | No | sync || `recipe_runner_list_runs` | List past recipe runs, optionally for one recipe. | No | sync || `recipe_runner_run_recipe` | Run a named automation recipe (a YAML-defined sequence of tool calls) with arguments; set dry_run to list the steps without executing them. | No | sync |+| `report_generator_build_review_pack` | Build one Excel 'Model review' workbook from a snapshot: cover, findings from the QA/QC rules, counts by category and what to do next. | No | sync || `report_generator_export_excel` | Export a snapshot (optionally filtered, with chosen parameters and QA/QC findings) to an Excel workbook in the workspace. | No | sync || `report_generator_export_sqlite_summary` | Export a summary of a snapshot to a SQLite database file in the workspace. | No | sync || `selection_tools_group_convert_to_detail` | Convert a model group into a detail group. | Yes | sync |diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/report_generator/module.json b/packages/mcp-server-revit/src/revit_mcp_server/modules/report_generator/module.jsonindex ecfc1db..c1c8ffb 100644--- a/packages/mcp-server-revit/src/revit_mcp_server/modules/report_generator/module.json+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/report_generator/module.json@@ -51,6 +51,22 @@},"required": []}+ },+ {+ "id": "build_review_pack",+ "title": "Build Model Review Workbook",+ "surface": ["mcp", "panel"],+ "execution_mode": "sync",+ "is_mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "snapshot_id": {"type": "string", "description": "Snapshot to review. Required when connected to Revit."},+ "rule_pack": {"type": "string", "default": "core", "description": "QA/QC rule pack to apply."},+ "output_filename": {"type": "string", "default": "model_review.xlsx"}+ },+ "required": []+ }}]}diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/report_generator/module.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/report_generator/module.pyindex 6859053..71ce418 100644--- a/packages/mcp-server-revit/src/revit_mcp_server/modules/report_generator/module.py+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/report_generator/module.py@@ -4,6 +4,8 @@ report_generator module — P14 Excel / SQLite reporting (W8, W16).Commands:export_excel — Generate a multi-sheet .xlsx: Elements, Params, QA Findings.export_sqlite_summary — Write elements + types into a fresh SQLite db.+ build_review_pack — One 'Model review' .xlsx for a coordinator: Cover, Findings,+ Counts by category, What to do next."""from __future__ import annotations@@ -124,6 +126,110 @@ def _load_qaqc_issues(workspace: Any) -> List[Dict[str, Any]]:return [dict(r) for r in rows]+# ---------------------------------------------------------------------------+# Model review pack (one-file coordinator workbook)+# ---------------------------------------------------------------------------++_SEVERITY_ORDER = {"error": 0, "warning": 1, "info": 2}+_SEVERITY_LABEL = {"error": "Must fix", "warning": "Should fix", "info": "For information"}+++def _load_review_snapshot(snapshot_id: str, workspace: Any) -> Dict[str, Any]:+ """Elements, types, identity and time for a snapshot (or generated mock data)."""+ if not snapshot_id:+ from revit_mcp_server.semantic.engine import generate_mock_snapshot, require_snapshot_or_mock+ require_snapshot_or_mock(snapshot_id, "report_generator")+ snap = generate_mock_snapshot()+ return {+ "snapshot_id": snap.snapshot_id,+ "taken_at": snap.taken_at.strftime("%Y-%m-%d %H:%M:%S UTC"),+ "source": {"doc_title": "Generated mock data (not a live model)", "doc_guid": "mock-doc"},+ "elements": [el.model_dump(by_alias=True) for el in snap.elements],+ "types": [t.model_dump() for t in snap.types],+ "is_mock": True,+ }+ snap_dir = (_ws_dir(workspace) / "snapshots").resolve()+ path = (snap_dir / f"{snapshot_id}.json").resolve()+ if path.parent != snap_dir:+ raise ValueError("snapshot_id must be a plain snapshot name inside the workspace snapshots folder.")+ if not path.exists():+ raise ValueError(f"Snapshot '{snapshot_id}' not found.")+ with open(path, encoding="utf-8") as f:+ data = json.load(f)+ return {+ "snapshot_id": data.get("snapshot_id") or snapshot_id,+ "taken_at": str(data.get("taken_at") or ""),+ "source": data.get("source", {}) or {},+ "elements": data.get("elements", []),+ "types": data.get("types", []),+ "is_mock": False,+ }+++def _qaqc_rules_module() -> Any:+ """Load the QA/QC rule engine by file path so it works however modules are loaded."""+ import importlib.util++ path = Path(__file__).resolve().parent.parent / "qaqc_checker" / "module.py"+ spec = importlib.util.spec_from_file_location("_review_pack_qaqc_rules", path)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++_MAX_CELL_CHARS = 32000 # Excel's hard limit is 32,767+++def _chunk_uids(uids: List[str], limit: int = _MAX_CELL_CHARS) -> List[str]:+ """Join UniqueIds with '; ' into strings that each fit in one Excel cell."""+ chunks: List[str] = []+ current: List[str] = []+ size = 0+ for uid in uids:+ add = len(uid) + (2 if current else 0)+ if current and size + add > limit:+ chunks.append("; ".join(current))+ current, size, add = [], 0, len(uid)+ current.append(uid)+ size += add+ if current:+ chunks.append("; ".join(current))+ return chunks+++def _review_findings(elements: List[Dict[str, Any]], types: List[Dict[str, Any]], doc_guid: str, rule_pack: str) -> List[Dict[str, Any]]:+ """Run the QA/QC rules in memory (does not touch the issue store), grouped per rule."""+ qaqc = _qaqc_rules_module()++ grouped: List[Dict[str, Any]] = []+ for rule in qaqc._load_rule_pack(rule_pack):+ try:+ hits = qaqc._run_rule(rule, elements, types, doc_guid)+ except Exception as exc: # a broken rule must not sink the whole pack+ logger.error("Rule '%s' failed: %s", rule.get("id"), exc)+ continue+ if not hits:+ continue+ uids = [h["element_uid"] for h in hits if h.get("element_uid")]+ first_label = hits[0].get("label") or ""+ template = rule.get("fix_template") or ""+ try:+ step = template.format(label=first_label) if template else ""+ except (KeyError, IndexError, ValueError):+ step = template+ grouped.append({+ "severity": rule.get("severity", "info"),+ "rule_id": rule["id"],+ "category": rule.get("category", ""),+ "message": rule.get("description", ""),+ "count": len(hits),+ "uids": uids,+ "next_step": step or "Review the listed elements in Revit and correct them.",+ })+ grouped.sort(key=lambda g: (_SEVERITY_ORDER.get(g["severity"], 9), g["rule_id"]))+ return grouped++class ReportGeneratorModule:def export_excel(@@ -223,6 +329,116 @@ class ReportGeneratorModule:"sheets": wb.sheetnames,}+ def build_review_pack(+ self,+ snapshot_id: str = "",+ rule_pack: str = "core",+ output_filename: str = "model_review.xlsx",+ workspace: Any = None,+ **_,+ ) -> Dict[str, Any]:+ """Build one 'Model review' workbook: Cover, Findings, Counts by category, What to do next."""+ from datetime import datetime, timezone+ from revit_mcp_server.security.workspace import WorkspaceMonitor++ data = _load_review_snapshot(snapshot_id, workspace)+ elements, types, source = data["elements"], data["types"], data["source"]+ doc_guid = source.get("doc_guid") or data["snapshot_id"]+ findings = _review_findings(elements, types, doc_guid, rule_pack)++ out_path = WorkspaceMonitor(workspace.allowed_directories).assert_in_workspace(+ _ws_dir(workspace) / output_filename+ )+ if out_path.suffix.lower() != ".xlsx":+ raise ValueError("output_filename must end in .xlsx")++ wb = openpyxl.Workbook()++ # --- Cover ---+ ws = wb.active+ ws.title = "Cover"+ flagged_uids = {u for f in findings for u in f["uids"]}+ total_hits = len(flagged_uids)+ label = "MOCK data - generated sample, not a live Revit model" if data["is_mock"] else "Snapshot taken from the model"+ rows = [+ ("Document", source.get("doc_title") or source.get("title") or ""),+ ("Document GUID", source.get("doc_guid", "")),+ ("Snapshot ID", data["snapshot_id"]),+ ("Snapshot time", data["taken_at"]),+ ("Data source", "mock" if data["is_mock"] else "real"),+ ("Data source note", label),+ ("Review generated (UTC)", datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")),+ ("Rule pack", rule_pack),+ ("Elements reviewed", len(elements)),+ ("Rules with findings", len(findings)),+ ("Elements flagged", total_hits),+ ]+ _write_header(ws, ["Item", "Value"])+ ws.column_dimensions["A"].width = 26+ ws.column_dimensions["B"].width = 60+ for row in rows:+ ws.append(list(row))++ # --- Findings ---+ ws_f = wb.create_sheet("Findings")+ f_headers = ["Severity", "Rule", "Category", "What is wrong", "Elements affected", "UniqueIds", "Next step"]+ _write_header(ws_f, f_headers)+ for width, col in zip((12, 24, 14, 50, 12, 60, 50), "ABCDEFG"):+ ws_f.column_dimensions[col].width = width+ r = 1+ for f in findings:+ # An Excel cell holds at most 32,767 characters; continue long UniqueId+ # lists on extra rows so no id is silently dropped.+ chunks = _chunk_uids(f["uids"]) or [""]+ for i, chunk in enumerate(chunks):+ r += 1+ if i == 0:+ ws_f.append([f["severity"], f["rule_id"], f["category"], f["message"], f["count"], chunk, f["next_step"]])+ else:+ ws_f.append([f["severity"], f["rule_id"], f["category"], f["message"] + " (UniqueIds continued)", "", chunk, ""])+ color = SEVERITY_COLORS.get(f["severity"])+ if color:+ for col in range(1, len(f_headers) + 1):+ ws_f.cell(row=r, column=col).fill = PatternFill("solid", fgColor=color)++ # --- Counts by category ---+ ws_c = wb.create_sheet("Counts by category")+ _write_header(ws_c, ["Category", "Elements", "Flagged by rules"])+ ws_c.column_dimensions["A"].width = 30+ cat_total: Dict[str, int] = {}+ cat_flagged: Dict[str, int] = {}+ for el in elements:+ cat = el.get("category") or "(none)"+ cat_total[cat] = cat_total.get(cat, 0) + 1+ if el.get("uid") in flagged_uids:+ cat_flagged[cat] = cat_flagged.get(cat, 0) + 1+ for cat in sorted(cat_total):+ ws_c.append([cat, cat_total[cat], cat_flagged.get(cat, 0)])++ # --- What to do next ---+ ws_n = wb.create_sheet("What to do next")+ _write_header(ws_n, ["Priority", "Action", "Why", "Elements"])+ for col, width in zip("ABCD", (16, 60, 50, 10)):+ ws_n.column_dimensions[col].width = width+ if data["is_mock"]:+ ws_n.append(["Note", "Capture a real snapshot of the open model and run this again.", "This pack was built from generated sample data.", ""])+ if not findings:+ ws_n.append(["Done", "No rule findings. Nothing to fix from this rule pack.", "", ""])+ for f in findings:+ ws_n.append([_SEVERITY_LABEL.get(f["severity"], f["severity"]), f["next_step"], f["message"], f["count"]])++ wb.save(str(out_path))++ return {+ "status": "exported",+ "output_file": str(out_path),+ "data_source": "mock" if data["is_mock"] else "real",+ "snapshot_id": data["snapshot_id"],+ "element_count": len(elements),+ "finding_rules": len(findings),+ "sheets": wb.sheetnames,+ }+def export_sqlite_summary(self,snapshot_id: str = "",diff --git a/packages/mcp-server-revit/src/revit_mcp_server/tool_metadata.py b/packages/mcp-server-revit/src/revit_mcp_server/tool_metadata.pyindex ab6bd23..039b81c 100644--- a/packages/mcp-server-revit/src/revit_mcp_server/tool_metadata.py+++ b/packages/mcp-server-revit/src/revit_mcp_server/tool_metadata.py@@ -174,6 +174,7 @@ DESCRIPTIONS: dict[str, str] = {"recipe_runner_list_runs": "List past recipe runs, optionally for one recipe. Read-only.","recipe_runner_get_run_status": "Return the status and results of one recipe run. Read-only.","report_generator_export_excel": "Export a snapshot (optionally filtered, with chosen parameters and QA/QC findings) to an Excel workbook in the workspace. Writes a file; does not change the model.",+ "report_generator_build_review_pack": "Build one Excel 'Model review' workbook from a snapshot: cover, findings from the QA/QC rules, counts by category and what to do next. Writes a file; does not change the model.","report_generator_export_sqlite_summary": "Export a summary of a snapshot to a SQLite database file in the workspace. Writes a file; does not change the model.","selection_tools_set_selection": "Select the given elements (by UniqueId) in the Revit UI. Does not modify the model.","selection_tools_save_selection": "Save a set of element UniqueIds under a name for later restore.",@@ -479,6 +480,7 @@ NOT_READ_ONLY: dict[str, tuple[bool, bool]] = {"exporter_graph_to_sqlite": (False, False),"parameter_manager_export_params_csv": (False, True),"report_generator_export_excel": (False, True),+ "report_generator_build_review_pack": (False, True),"report_generator_export_sqlite_summary": (False, True),"model_inspector_save_query": (False, True),"selection_tools_save_selection": (False, True),diff --git a/packages/mcp-server-revit/tests/test_report_generator.py b/packages/mcp-server-revit/tests/test_report_generator.pyindex d304176..101a68d 100644--- a/packages/mcp-server-revit/tests/test_report_generator.py+++ b/packages/mcp-server-revit/tests/test_report_generator.py@@ -116,3 +116,123 @@ def test_export_excel_has_summary_sheet_first(tmp_path):values = {row[0].value: row[1].value for row in wb["Summary"].iter_rows(min_row=2)}assert values["Snapshot ID"] == "(mock)"assert "mock" in values["Document"].lower()+++# --- build_review_pack (one-file coordinator review) ---++def test_review_pack_sheets_columns_and_mock_label(tmp_path):+ import openpyxl+ from types import SimpleNamespace++ ws = SimpleNamespace(allowed_directories=[tmp_path])+ result = ReportGeneratorModule().build_review_pack(workspace=ws)+ assert result["data_source"] == "mock"+ wb = openpyxl.load_workbook(result["output_file"])+ assert wb.sheetnames == ["Cover", "Findings", "Counts by category", "What to do next"]+ cover = {r[0].value: r[1].value for r in wb["Cover"].iter_rows(min_row=2)}+ assert cover["Data source"] == "mock"+ assert "mock" in cover["Data source note"].lower()+ assert cover["Snapshot ID"]+ headers = [c.value for c in wb["Findings"][1]]+ assert headers == ["Severity", "Rule", "Category", "What is wrong", "Elements affected", "UniqueIds", "Next step"]+ assert [c.value for c in wb["Counts by category"][1]] == ["Category", "Elements", "Flagged by rules"]+ assert [c.value for c in wb["What to do next"][1]][:2] == ["Priority", "Action"]+++def test_review_pack_real_snapshot_labelled_real(tmp_path):+ import json+ import openpyxl+ from types import SimpleNamespace++ (tmp_path / "snapshots").mkdir()+ snap = {+ "snapshot_id": "snap1", "taken_at": "2026-01-01T00:00:00Z",+ "source": {"doc_title": "Tower A", "doc_guid": "g-1"},+ "elements": [{"uid": "u1", "category": "OST_Rooms", "type_name": "Office", "params": {}}],+ "types": [],+ }+ (tmp_path / "snapshots" / "snap1.json").write_text(json.dumps(snap), encoding="utf-8")+ ws = SimpleNamespace(allowed_directories=[tmp_path])+ result = ReportGeneratorModule().build_review_pack(snapshot_id="snap1", workspace=ws)+ assert result["data_source"] == "real"+ wb = openpyxl.load_workbook(result["output_file"])+ cover = {r[0].value: r[1].value for r in wb["Cover"].iter_rows(min_row=2)}+ assert cover["Document"] == "Tower A"+ assert cover["Data source"] == "real"+ findings = list(wb["Findings"].iter_rows(min_row=2, values_only=True))+ assert any("u1" in (row[5] or "") for row in findings)+++def test_review_pack_rejects_missing_snapshot_in_bridge_mode(tmp_path, monkeypatch):+ from revit_mcp_server.config import BridgeMode, config+ from types import SimpleNamespace++ monkeypatch.setattr(config, "mode", BridgeMode.bridge)+ ws = SimpleNamespace(allowed_directories=[tmp_path])+ with pytest.raises(ValueError, match="requires a snapshot_id"):+ ReportGeneratorModule().build_review_pack(snapshot_id="", workspace=ws)+++def test_review_pack_rejects_path_outside_workspace(tmp_path):+ from types import SimpleNamespace++ ws = SimpleNamespace(allowed_directories=[tmp_path])+ with pytest.raises(Exception, match="outside the allowed workspace"):+ ReportGeneratorModule().build_review_pack(output_filename="../escape.xlsx", workspace=ws)+++def _real_snapshot(tmp_path, elements, name="snap1"):+ import json++ (tmp_path / "snapshots").mkdir(exist_ok=True)+ snap = {+ "snapshot_id": name, "taken_at": "2026-01-01T00:00:00Z",+ "source": {"doc_title": "Tower A", "doc_guid": "g-1"},+ "elements": elements, "types": [],+ }+ (tmp_path / "snapshots" / f"{name}.json").write_text(json.dumps(snap), encoding="utf-8")+++def test_review_pack_snapshot_id_cannot_escape_snapshots_dir(tmp_path):+ import json+ from types import SimpleNamespace++ (tmp_path / "snapshots").mkdir()+ (tmp_path / "outside.json").write_text(json.dumps({"snapshot_id": "x", "elements": []}), encoding="utf-8")+ ws = SimpleNamespace(allowed_directories=[tmp_path])+ for bad in ("../outside", str(tmp_path / "outside")):+ with pytest.raises(ValueError):+ ReportGeneratorModule().build_review_pack(snapshot_id=bad, workspace=ws)+++def test_review_pack_cover_counts_distinct_elements(tmp_path):+ import openpyxl+ from types import SimpleNamespace++ # One room missing both Name and Number is flagged by two rules but is one element.+ _real_snapshot(tmp_path, [{"uid": "u1", "category": "OST_Rooms", "type_name": "Office", "params": {}}])+ ws = SimpleNamespace(allowed_directories=[tmp_path])+ result = ReportGeneratorModule().build_review_pack(snapshot_id="snap1", workspace=ws)+ wb = openpyxl.load_workbook(result["output_file"])+ cover = {r[0].value: r[1].value for r in wb["Cover"].iter_rows(min_row=2)}+ assert cover["Rules with findings"] >= 2+ assert cover["Elements flagged"] == 1+ assert cover["Elements flagged"] <= cover["Elements reviewed"]+++def test_review_pack_keeps_every_uid_when_list_exceeds_cell_limit(tmp_path):+ import openpyxl+ from types import SimpleNamespace++ n = 1500+ uids = [f"{i:04d}-" + "x" * 40 for i in range(n)] # ~ 45 chars each -> > 32,767 joined+ _real_snapshot(tmp_path, [{"uid": u, "category": "OST_Rooms", "type_name": "Office", "params": {}} for u in uids])+ ws = SimpleNamespace(allowed_directories=[tmp_path])+ result = ReportGeneratorModule().build_review_pack(snapshot_id="snap1", workspace=ws)+ wb = openpyxl.load_workbook(result["output_file"])+ found = set()+ for row in wb["Findings"].iter_rows(min_row=2, values_only=True):+ cell = row[5] or ""+ assert len(cell) <= 32767+ found.update(p for p in cell.split("; ") if p)+ assert set(uids) <= found