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
feat: warnings triage module (read-only) (#80)
A. Sam Mohammad1b586e42e982
diff --git a/docs/tools-generated.md b/docs/tools-generated.mdindex 051dc05..46a9b3e 100644--- a/docs/tools-generated.md+++ b/docs/tools-generated.md@@ -109,6 +109,7 @@ This catalog lists all tools exposed by the AEC Model Bridge providers.| `selection_tools_save_selection` | Save a set of element UniqueIds under a name for later restore. | No | sync || `selection_tools_select_by_query` | Select in Revit the elements of a snapshot that match a filter query. | Yes | sync || `selection_tools_set_selection` | Select the given elements (by UniqueId) in the Revit UI. | Yes | sync |+| `warnings_triage_review_warnings` | Group the open project's Revit warnings by type, rank them by how many elements they touch, flag duplicate marks, overlapping elements and rooms not enclosed for the coordinator, and suggest a next step for each group. | No | sync |## Navisworks Providerdiff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/warnings_triage/__init__.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/warnings_triage/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/warnings_triage/module.json b/packages/mcp-server-revit/src/revit_mcp_server/modules/warnings_triage/module.jsonnew file mode 100644index 0000000..2763922--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/warnings_triage/module.json@@ -0,0 +1,46 @@+{+ "id": "warnings_triage",+ "name": "Warnings Triage",+ "version": "1.0.0",+ "schema_version": 1,+ "min_hub_version": "1.2.0",+ "description": "Read-only triage of the warnings Revit shows for the open project: groups them by type, ranks them by how many elements they touch, flags the ones a BIM coordinator should chase, and suggests a plain next step for each group.",+ "author": "AEC Model Bridge",+ "license": "GPL-3.0-or-later",+ "requires_providers": ["revit"],+ "permissions": ["model.read"],+ "commands": [+ {+ "id": "review_warnings",+ "title": "Review Revit Warnings (grouped, ranked, with next steps)",+ "surface": ["mcp", "panel"],+ "execution_mode": "sync",+ "is_mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "snapshot_id": {+ "type": "string",+ "description": "Optional snapshot ID. Used only to turn Revit element ids into element UniqueIds."+ },+ "coordinator_only": {+ "type": "boolean",+ "description": "If true, only return the warning groups a BIM coordinator should chase (duplicate marks, overlapping elements, rooms not enclosed).",+ "default": false+ },+ "top": {+ "type": "integer",+ "description": "Maximum number of groups to return, biggest first.",+ "default": 25+ },+ "max_elements_per_group": {+ "type": "integer",+ "description": "Maximum number of element ids listed per group (the full count is always reported).",+ "default": 50+ }+ },+ "required": []+ }+ }+ ]+}diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/warnings_triage/module.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/warnings_triage/module.pynew file mode 100644index 0000000..082c749--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/warnings_triage/module.py@@ -0,0 +1,238 @@+"""+warnings_triage module — read-only triage of Revit warnings.++Command:+ review_warnings — Group warnings by type, rank by elements touched, flag the+ coordinator-relevant families, suggest a next step per group.++Data path (nothing new is needed on the Revit side):+ The Revit add-in already exposes ``revit.get_warnings`` (tool+ ``revit_get_warnings``), returning ``{"warnings": [{"description", "severity",+ "failing_elements": [<Revit element id>, ...]}], "count": N}``. The model+ snapshot does NOT carry warnings. Revit returns numeric element ids, so they+ are mapped to UniqueIds through the snapshot (if a ``snapshot_id`` is given).+ Without a snapshot the numeric ids are returned and ``unique_ids_available``+ is false.++Fetching live warnings needs a running Revit with the add-in: UNVERIFIED here.+"""+from __future__ import annotations++import json+import re+from collections import OrderedDict+from pathlib import Path+from typing import Any, Dict, List, Optional, Tuple++# (family key, label, regex on lowercase description, plain next step)+_FAMILIES: List[Tuple[str, str, str, str]] = [+ (+ "duplicate_mark",+ "Duplicate Mark values",+ r"duplicate.*(mark|number)|(mark|number).*duplicate|same (mark|number)",+ "Give each listed element its own Mark (or Number). Ask the model owner to renumber, "+ "then run Review Revit Warnings again.",+ ),+ (+ "overlapping_elements",+ "Overlapping or identical elements",+ r"overlap|identical instances|same place|duplicate (instance|element)",+ "Open the listed elements in Revit and delete or move the extra copy. "+ "Overlaps are often a double-placed or copied element, so tell the model owner.",+ ),+ (+ "room_not_enclosed",+ "Room not enclosed",+ r"room.*(not (in a )?(properly )?enclosed|redundant|not placed)|not in a properly enclosed|enclosed region",+ "Close the gap in the walls or add a Room Separation line around each listed room. "+ "Until then, room areas and numbers in schedules are wrong.",+ ),+]++_GENERIC_STEPS = [+ (r"off axis|slightly off", "Straighten the listed elements in Revit (they are a hair off the grid or axis) so they stop causing small clashes."),+ (r"join|joined|cut", "Check the listed elements' joins in Revit and unjoin or re-join them."),+ (r"tag|outside of its room|not (visible|placed)", "Move or delete the listed tags and annotations so they match the model."),+ (r"line|sketch", "Fix or delete the stray line in the listed elements' sketch."),+]+_DEFAULT_STEP = (+ "Open one listed element in Revit to read the full message, then fix it or hand it to the model owner."+)+++def _normalise(text: str) -> str:+ return re.sub(r"\s+", " ", (text or "").strip())+++def _classify(description: str) -> Tuple[str, str, str, bool]:+ low = _normalise(description).lower()+ for key, label, pattern, step in _FAMILIES:+ if re.search(pattern, low):+ return key, label, step, True+ for pattern, step in _GENERIC_STEPS:+ if re.search(pattern, low):+ return "other", "", step, False+ return "other", "", _DEFAULT_STEP, False+++def _load_snapshot(snapshot_id: str, workspace: Any) -> Dict[str, Any]:+ snap_dir = (Path(workspace.allowed_directories[0]) / "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, "r", encoding="utf-8") as f:+ return json.load(f)+++def _snapshot_id_map(data: Dict[str, Any]) -> Dict[int, str]:+ return {+ int(el["element_id"]): el["uid"]+ for el in data.get("elements", [])+ if el.get("uid") is not None and el.get("element_id") is not None+ }+++def _active_title(tool_executor: Any) -> str:+ """Title of the open Revit document, or '' when it cannot be read."""+ if tool_executor is None:+ return ""+ try:+ raw = tool_executor("revit_get_document_info", {})+ except Exception:+ return ""+ if isinstance(raw, dict) and isinstance(raw.get("data"), dict) and "title" not in raw:+ raw = raw["data"]+ title = (raw or {}).get("title") if isinstance(raw, dict) else ""+ return str(title or "").strip()+++def group_warnings(+ warnings: List[Dict[str, Any]],+ id_to_uid: Optional[Dict[int, str]] = None,+ max_elements_per_group: int = 50,+) -> List[Dict[str, Any]]:+ """Pure grouping/ranking logic (no Revit needed)."""+ id_to_uid = id_to_uid or {}+ groups: "OrderedDict[str, Dict[str, Any]]" = OrderedDict()+ for w in warnings:+ desc = _normalise(w.get("description", "")) or "(no description)"+ g = groups.setdefault(+ desc.lower(),+ {"description": desc, "severities": set(), "warning_count": 0, "ids": []},+ )+ g["warning_count"] += 1+ if w.get("severity"):+ g["severities"].add(str(w["severity"]))+ for raw in w.get("failing_elements") or []:+ if raw not in g["ids"]:+ g["ids"].append(raw)++ out: List[Dict[str, Any]] = []+ for g in groups.values():+ key, label, step, coord = _classify(g["description"])+ uids: List[str] = []+ unmapped: List[Any] = []+ for raw in g["ids"]:+ if isinstance(raw, str) and not raw.lstrip("-").isdigit():+ uids.append(raw) # already a UniqueId+ continue+ try:+ uid = id_to_uid.get(int(raw))+ except (TypeError, ValueError):+ uid = None+ if uid:+ uids.append(uid)+ else:+ unmapped.append(raw)+ out.append({+ "description": g["description"],+ "family": key,+ "family_label": label or None,+ "coordinator_relevant": coord,+ "severity": sorted(g["severities"]),+ "warning_count": g["warning_count"],+ "elements_affected": len(g["ids"]),+ "element_unique_ids": uids[:max_elements_per_group],+ "element_ids_without_unique_id": unmapped[: max(0, max_elements_per_group - len(uids[:max_elements_per_group]))],+ "element_list_truncated": len(g["ids"]) > max_elements_per_group,+ "next_step": step,+ })+ out.sort(key=lambda r: (-r["elements_affected"], -r["warning_count"], r["description"]))+ for rank, row in enumerate(out, 1):+ row["rank"] = rank+ return out+++class WarningsTriageModule:++ def review_warnings(+ self,+ snapshot_id: str = "",+ coordinator_only: bool = False,+ top: int = 25,+ max_elements_per_group: int = 50,+ workspace: Any = None,+ tool_executor: Any = None,+ warnings: Optional[List[Dict[str, Any]]] = None,+ **_,+ ) -> Dict[str, Any]:+ notes: List[str] = []+ if warnings is None:+ if tool_executor is None:+ return {+ "ok": False,+ "error": "Could not read warnings: no connection to Revit tools in this session.",+ "missing_data": (+ "Revit warnings. The model snapshot does not include them; they come "+ "live from Revit via the revit_get_warnings tool (needs Revit open "+ "with the add-in running)."+ ),+ }+ raw = tool_executor("revit_get_warnings", {})+ if isinstance(raw, dict) and isinstance(raw.get("data"), dict) and "warnings" not in raw:+ raw = raw["data"]+ warnings = (raw or {}).get("warnings") or []+ id_to_uid: Dict[int, str] = {}+ if snapshot_id and workspace is not None:+ data = _load_snapshot(snapshot_id, workspace)+ snap_title = str((data.get("source") or {}).get("doc_title") or "").strip()+ active = _active_title(tool_executor)+ if snap_title and active and snap_title.lower() == active.lower():+ id_to_uid = _snapshot_id_map(data)+ else:+ notes.append(+ "The snapshot could not be confirmed as the open Revit document "+ f"(snapshot: '{snap_title or 'unknown'}', open document: '{active or 'unknown'}'), "+ "or it is from a different document, so elements are listed by Revit id. "+ "Take a snapshot of the open document."+ )+ if not snapshot_id:+ notes.append(+ "No snapshot_id given, so elements are listed by Revit element id. "+ "Pass a snapshot_id to get UniqueIds."+ )+ elif warnings and not id_to_uid and not notes:+ notes.append("The snapshot has no elements to match against.")++ all_groups = group_warnings(warnings, id_to_uid, max(1, int(max_elements_per_group)))+ groups = [g for g in all_groups if g["coordinator_relevant"]] if coordinator_only else all_groups+ groups = groups[: max(1, int(top))]+ for rank, g in enumerate(groups, 1):+ g["rank"] = rank+ if snapshot_id and any(g["element_ids_without_unique_id"] for g in groups):+ notes.append(+ "Some element ids are not in the snapshot (take a fresh snapshot) and are listed by Revit id."+ )++ return {+ "ok": True,+ "read_only": True,+ "total_warnings": len(warnings),+ "total_groups": len(all_groups),+ "coordinator_groups": sum(1 for g in all_groups if g["coordinator_relevant"]),+ "unique_ids_available": bool(id_to_uid),+ "groups": groups,+ "notes": notes,+ }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 dd08ec6..ab6bd23 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@@ -166,6 +166,7 @@ DESCRIPTIONS: dict[str, str] = {"qaqc_checker_list_issues": "List recorded QA/QC issues for a document, optionally filtered by status and severity. Read-only.","qaqc_checker_resolve_issue": "Mark one recorded QA/QC issue as resolved.","qaqc_checker_list_rules": "List the QA/QC rules that are available, optionally for one rule pack. Read-only.",+ "warnings_triage_review_warnings": "Group the open project's Revit warnings by type, rank them by how many elements they touch, flag duplicate marks, overlapping elements and rooms not enclosed for the coordinator, and suggest a next step for each group. Read-only.","bcf_exchange_export_bcf": "Save issues (your own list and/or the recorded QA/QC issues) to a BCF 2.1 .bcfzip file in the workspace. Writes a file; does not change the model. Not yet checked against other BCF tools.","bcf_exchange_import_bcf": "Read a BCF .bcfzip file from the workspace and return its issues (title, description, status, priority, element ids). Read-only; unsafe zip files are refused.","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.",diff --git a/packages/mcp-server-revit/tests/test_warnings_triage.py b/packages/mcp-server-revit/tests/test_warnings_triage.pynew file mode 100644index 0000000..9dbe904--- /dev/null+++ b/packages/mcp-server-revit/tests/test_warnings_triage.py@@ -0,0 +1,179 @@+"""Tests for the warnings_triage module (read-only Revit warnings triage)."""+import importlib.util+from pathlib import Path++import pytest++from revit_mcp_server.config import Config+from revit_mcp_server.module_registry import ModuleRegistry+from revit_mcp_server.providers.module_provider import ModuleProvider+from revit_mcp_server.security.workspace import WorkspaceMonitor+from revit_mcp_server.semantic.engine import generate_mock_snapshot+++def _load(relpath, name):+ p = Path(__file__).parent.parent / relpath+ spec = importlib.util.spec_from_file_location(name, p)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++_wt = _load("src/revit_mcp_server/modules/warnings_triage/module.py", "_wt_impl")+WarningsTriageModule = _wt.WarningsTriageModule+++class WS:+ def __init__(self, p):+ self.allowed_directories = [p]+++# Mixed fixture shaped like the add-in's revit.get_warnings output.+FIXTURE = {+ "count": 7,+ "warnings": [+ {"description": "Elements have duplicate 'Mark' values.", "severity": "Warning", "failing_elements": [100, 101]},+ {"description": "Elements have duplicate 'Mark' values.", "severity": "Warning", "failing_elements": [101, 200]},+ {"description": "Highlighted walls overlap.", "severity": "Warning", "failing_elements": [300, 400, 401, 9999]},+ {"description": "Room is not in a properly enclosed region.", "severity": "Warning", "failing_elements": [200]},+ {"description": "Highlighted walls are slightly off axis.", "severity": "Warning", "failing_elements": [300]},+ {"description": "Something unexpected happened", "severity": "Error", "failing_elements": []},+ {"description": "There are identical instances in the same place.", "severity": "Warning", "failing_elements": [100, 101, 200, 300, 400]},+ ],+}+++def _default_executor(name, args):+ if name == "revit_get_document_info":+ return {"title": "Mock_Project.rvt"}+ return FIXTURE+++def run(**kw):+ ex = kw.pop("tool_executor", _default_executor)+ return WarningsTriageModule().review_warnings(tool_executor=ex, **kw)+++def test_groups_and_ranking():+ r = run()+ assert r["ok"] and r["read_only"]+ assert r["total_warnings"] == 7+ assert r["total_groups"] == 6+ counts = [g["elements_affected"] for g in r["groups"]]+ assert counts == sorted(counts, reverse=True)+ assert r["groups"][0]["elements_affected"] == 5 and r["groups"][0]["rank"] == 1+ dup = next(g for g in r["groups"] if g["family"] == "duplicate_mark")+ assert dup["warning_count"] == 2 and dup["elements_affected"] == 3 # 101 deduped+++def test_coordinator_flags_and_next_steps():+ r = run()+ fam = {g["family"] for g in r["groups"]}+ assert {"duplicate_mark", "overlapping_elements", "room_not_enclosed"} <= fam+ flagged = {g["family"] for g in r["groups"] if g["coordinator_relevant"]}+ assert flagged == {"duplicate_mark", "overlapping_elements", "room_not_enclosed"}+ others = [g for g in r["groups"] if g["family"] == "other"]+ assert len(others) == 2 and not any(g["coordinator_relevant"] for g in others)+ assert all(g["next_step"] for g in r["groups"])+ assert r["coordinator_groups"] == 4 # identical instances + overlap + mark + room+++def test_coordinator_only_and_top():+ r = run(coordinator_only=True)+ assert r["groups"] and all(g["coordinator_relevant"] for g in r["groups"])+ assert len(run(top=2)["groups"]) == 2+++def test_unique_ids_from_snapshot(tmp_path):+ snap = generate_mock_snapshot()+ d = tmp_path / "snapshots"+ d.mkdir()+ (d / f"{snap.snapshot_id}.json").write_text(snap.model_dump_json(by_alias=True), encoding="utf-8")+ uid = {e.element_id: e.uid for e in snap.elements}+ r = run(snapshot_id=snap.snapshot_id, workspace=WS(tmp_path))+ assert r["unique_ids_available"]+ ov = next(g for g in r["groups"] if g["description"] == "Highlighted walls overlap.")+ assert set(ov["element_unique_ids"]) == {uid[300], uid[400], uid[401]}+ assert ov["element_ids_without_unique_id"] == [9999]+++def _write_snapshot(tmp_path):+ snap = generate_mock_snapshot()+ d = tmp_path / "snapshots"+ d.mkdir(exist_ok=True)+ (d / f"{snap.snapshot_id}.json").write_text(snap.model_dump_json(by_alias=True), encoding="utf-8")+ return snap+++def test_snapshot_id_cannot_escape_snapshots_dir(tmp_path):+ outside = tmp_path / "outside.json"+ outside.write_text('{"elements": [{"element_id": 100, "uid": "LEAK"}]}', encoding="utf-8")+ (tmp_path / "snapshots").mkdir()+ for bad in ("../outside", str(tmp_path / "outside"), "..\\outside"):+ with pytest.raises(ValueError):+ run(snapshot_id=bad, workspace=WS(tmp_path))+++def test_snapshot_from_other_document_is_not_mapped(tmp_path):+ snap = _write_snapshot(tmp_path)+ other = lambda n, a: {"title": "Other_Project.rvt"} if n == "revit_get_document_info" else FIXTURE # noqa: E731+ r = run(snapshot_id=snap.snapshot_id, workspace=WS(tmp_path), tool_executor=other)+ assert not r["unique_ids_available"]+ assert all(g["element_unique_ids"] == [] for g in r["groups"])+ assert any("different" in n.lower() for n in r["notes"])+++def test_unverifiable_document_identity_is_not_mapped(tmp_path):+ snap = _write_snapshot(tmp_path)+ nodoc = lambda n, a: FIXTURE # noqa: E731+ r = run(snapshot_id=snap.snapshot_id, workspace=WS(tmp_path), tool_executor=nodoc)+ assert not r["unique_ids_available"]+++def test_element_cap_is_shared_across_both_lists(tmp_path):+ snap = _write_snapshot(tmp_path)+ r = run(snapshot_id=snap.snapshot_id, workspace=WS(tmp_path), max_elements_per_group=2)+ for g in r["groups"]:+ assert len(g["element_unique_ids"]) + len(g["element_ids_without_unique_id"]) <= 2+ ov = next(g for g in r["groups"] if g["description"] == "Highlighted walls overlap.")+ assert ov["element_list_truncated"]+++def test_without_snapshot_lists_revit_ids():+ r = run()+ assert not r["unique_ids_available"] and r["notes"]+ g = r["groups"][0]+ assert g["element_unique_ids"] == [] and g["element_ids_without_unique_id"]+++def test_truncation_and_wrapped_response():+ r = run(max_elements_per_group=2, tool_executor=lambda n, a: {"data": FIXTURE})+ g = r["groups"][0]+ assert g["element_list_truncated"] and len(g["element_ids_without_unique_id"]) == 2+ assert g["elements_affected"] == 5+++def test_no_revit_connection_says_what_is_missing():+ r = WarningsTriageModule().review_warnings()+ assert r["ok"] is False and "revit_get_warnings" in r["missing_data"]+++def test_empty_warnings():+ r = run(tool_executor=lambda n, a: {"warnings": [], "count": 0})+ assert r["ok"] and r["groups"] == [] and r["total_warnings"] == 0+++async def test_registered_as_read_only_tool(tmp_path):+ cfg = Config(+ workspace_dir=tmp_path,+ allowed_directories=[tmp_path],+ audit_log=tmp_path / "audit.log",+ enable_user_modules=False,+ )+ registry = ModuleRegistry(config_obj=cfg)+ registry.discover_and_load()+ provider = ModuleProvider(module_registry=registry, workspace=WorkspaceMonitor([tmp_path]))+ caps = {c.name: c for c in provider.get_capabilities()}+ assert "warnings_triage_review_warnings" in caps+ assert not caps["warnings_triage_review_warnings"].is_mutating