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(modules): implement Model Inspector module — summarize_model, ask/DSL, list_groups, inspect_selection, saved queries (P7.1-P7.3)
A. Sam Mohammadb76a6578688e
diff --git a/docs/tools-generated.md b/docs/tools-generated.mdindex 302d4c8..9e50cd0 100644--- a/docs/tools-generated.md+++ b/docs/tools-generated.md@@ -71,6 +71,13 @@ This catalog lists all tools exposed by the AEC Model Bridge providers.| Tool Name | Description | Mutating? | Execution Type || --- | --- | --- | --- || `hello_world_say_hello` | Say Hello. | No | sync |+| `model_inspector_ask` | Ask About Model. | No | sync |+| `model_inspector_inspect_selection` | Inspect Selection. | No | sync |+| `model_inspector_list_groups` | List Model Groups. | No | sync |+| `model_inspector_list_saved_queries` | List Saved Queries. | No | sync |+| `model_inspector_run_saved_query` | Run Saved Query. | No | sync |+| `model_inspector_save_query` | Save Query. | No | sync |+| `model_inspector_summarize_model` | Summarize Model. | No | sync || `module_list_commands` | List all registered modules and their commands for dockable panels. | No | sync |## Navisworks Providerdiff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/__init__.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/__init__.pynew file mode 100644index 0000000..bffc683--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/__init__.py@@ -0,0 +1 @@+# modules packagediff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/model_inspector/__init__.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/model_inspector/__init__.pynew file mode 100644index 0000000..33cc472--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/model_inspector/__init__.py@@ -0,0 +1 @@+# model_inspector packagediff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/model_inspector/module.json b/packages/mcp-server-revit/src/revit_mcp_server/modules/model_inspector/module.jsonnew file mode 100644index 0000000..6dbd9e3--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/model_inspector/module.json@@ -0,0 +1,133 @@+{+ "id": "model_inspector",+ "name": "Model Inspector",+ "version": "1.0.0",+ "schema_version": 1,+ "min_hub_version": "1.2.0",+ "description": "Model inspection workflows: summarize model, query elements, inspect selection, list groups, and run saved queries.",+ "author": "AEC Model Bridge",+ "license": "GPL-3.0-or-later",+ "requires_providers": ["revit", "semantic"],+ "permissions": ["model.read"],+ "commands": [+ {+ "id": "summarize_model",+ "title": "Summarize Model",+ "surface": ["mcp", "panel"],+ "execution_mode": "sync",+ "is_mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "snapshot_id": {+ "type": "string",+ "description": "Snapshot ID to summarize. Omit to auto-take a fresh snapshot."+ }+ },+ "required": []+ }+ },+ {+ "id": "ask",+ "title": "Ask About Model",+ "surface": ["mcp"],+ "execution_mode": "sync",+ "is_mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "snapshot_id": {+ "type": "string",+ "description": "Snapshot ID to query. Omit to auto-take a fresh snapshot."+ },+ "filter": {+ "type": "object",+ "description": "DSL filter object to apply to snapshot query (category, family, type_name, level_uid, placed, parameter)."+ }+ },+ "required": ["filter"]+ }+ },+ {+ "id": "list_groups",+ "title": "List Model Groups",+ "surface": ["mcp", "panel"],+ "execution_mode": "sync",+ "is_mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "snapshot_id": {+ "type": "string",+ "description": "Snapshot ID to query."+ }+ },+ "required": []+ }+ },+ {+ "id": "inspect_selection",+ "title": "Inspect Selection",+ "surface": ["mcp", "panel"],+ "execution_mode": "sync",+ "is_mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "snapshot_id": {+ "type": "string",+ "description": "Snapshot ID to inspect."+ },+ "element_uids": {+ "type": "array",+ "items": {"type": "string"},+ "description": "List of element UIDs to inspect from selection."+ }+ },+ "required": ["element_uids"]+ }+ },+ {+ "id": "save_query",+ "title": "Save Query",+ "surface": ["mcp"],+ "execution_mode": "sync",+ "is_mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "query_name": {"type": "string", "description": "Unique name for this saved query."},+ "filter": {"type": "object", "description": "DSL filter object to save."}+ },+ "required": ["query_name", "filter"]+ }+ },+ {+ "id": "run_saved_query",+ "title": "Run Saved Query",+ "surface": ["mcp", "panel"],+ "execution_mode": "sync",+ "is_mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "snapshot_id": {"type": "string"},+ "query_name": {"type": "string", "description": "Name of a previously saved query."}+ },+ "required": ["query_name"]+ }+ },+ {+ "id": "list_saved_queries",+ "title": "List Saved Queries",+ "surface": ["mcp", "panel"],+ "execution_mode": "sync",+ "is_mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {},+ "required": []+ }+ }+ ]+}diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/model_inspector/module.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/model_inspector/module.pynew file mode 100644index 0000000..5847c29--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/model_inspector/module.py@@ -0,0 +1,264 @@+"""+model_inspector module — P7.1/P7.2/P7.3 Model Inspection Workflows.++Commands:+ summarize_model — Category counts + element type summary.+ ask — NL-style DSL query against snapshot.+ list_groups — List all model groups (members + instance count).+ inspect_selection — Element card: type/host/level/params/warnings.+ save_query — Persist a named DSL filter to workspace.+ run_saved_query — Re-run a named saved query against snapshot.+ list_saved_queries — Enumerate saved queries.+"""+from __future__ import annotations++import json+import logging+from collections import Counter, defaultdict+from pathlib import Path+from typing import Any, Dict, List, Optional++logger = logging.getLogger(__name__)++SAVED_QUERIES_FILE = "saved_queries.json"+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def _snapshots_dir(workspace: Any) -> Path:+ return workspace.allowed_directories[0] / "snapshots"++def _queries_file(workspace: Any) -> Path:+ return workspace.allowed_directories[0] / SAVED_QUERIES_FILE++def _load_snapshot(snapshot_id: str, workspace: Any) -> Dict[str, Any]:+ path = _snapshots_dir(workspace) / f"{snapshot_id}.json"+ 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 _load_queries(workspace: Any) -> Dict[str, Any]:+ qfile = _queries_file(workspace)+ if qfile.exists():+ with open(qfile, "r", encoding="utf-8") as f:+ return json.load(f)+ return {}++def _save_queries(queries: Dict[str, Any], workspace: Any) -> None:+ qfile = _queries_file(workspace)+ with open(qfile, "w", encoding="utf-8") as f:+ json.dump(queries, f, indent=2)++def _match_element(el: Dict[str, Any], filter_dsl: Dict[str, Any]) -> bool:+ """Apply DSL filter to a raw element dict (mirrors engine.snapshot_query logic)."""+ for key, val in filter_dsl.items():+ if key == "category":+ cats = val if isinstance(val, list) else [val]+ if el.get("category") not in cats:+ return False+ elif key == "family" and el.get("family") != val:+ return False+ elif key == "type_name" and el.get("type_name") != val:+ return False+ elif key == "level_uid" and el.get("level_uid") != val:+ return False+ elif key == "workset" and el.get("workset") != val:+ return False+ elif key == "group_uid" and el.get("group_uid") != val:+ return False+ elif key == "placed":+ is_placed = el.get("level_uid") is not None or el.get("location") is not None+ if val and not is_placed:+ return False+ elif not val and is_placed:+ return False+ elif key == "parameter":+ pname = val.get("name")+ params = el.get("params", {})+ param = params.get(pname) if params else None+ if val.get("empty") is True:+ if param is not None and param.get("v") not in (None, ""):+ return False+ elif "value" in val:+ if param is None or str(param.get("v")) != str(val["value"]):+ return False+ return True++def _element_chip(el: Dict[str, Any]) -> Dict[str, Any]:+ """Lightweight element chip for panel display."""+ return {+ "uid": el["uid"],+ "element_id": el.get("element_id"),+ "label": el.get("type_name") or el.get("category", ""),+ "category": el.get("category"),+ "family": el.get("family"),+ "type_name": el.get("type_name"),+ "level_uid": el.get("level_uid"),+ }+++# ---------------------------------------------------------------------------+# Command implementations+# ---------------------------------------------------------------------------++class ModelInspectorModule:++ def summarize_model(self, snapshot_id: str = "", workspace: Any = None, **_) -> Dict[str, Any]:+ if not snapshot_id:+ # Auto-take snapshot — call out to semantic module+ from revit_mcp_server.semantic.engine import generate_mock_snapshot+ snap = generate_mock_snapshot()+ elements = [el.model_dump(by_alias=True) for el in snap.elements]+ types = [t.model_dump() for t in snap.types]+ source = snap.source.model_dump()+ counts = snap.counts+ else:+ data = _load_snapshot(snapshot_id, workspace)+ elements = data.get("elements", [])+ types = data.get("types", [])+ source = data.get("source", {})+ counts = data.get("counts", {})++ by_cat: Counter = Counter(el.get("category") for el in elements)+ family_set = set(+ el.get("family") for el in elements if el.get("family")+ )+ type_count = len(types)++ # Count placed/unplaced rooms+ rooms = [el for el in elements if el.get("category") == "OST_Rooms"]+ placed_rooms = sum(+ 1 for r in rooms if r.get("level_uid") or r.get("location")+ )++ return {+ "doc_title": source.get("doc_title", ""),+ "doc_guid": source.get("doc_guid", ""),+ "elements_total": len(elements),+ "types_total": type_count,+ "family_count": len(family_set),+ "by_category": dict(by_cat.most_common()),+ "rooms": {"total": len(rooms), "placed": placed_rooms, "unplaced": len(rooms) - placed_rooms},+ }++ def ask(self, filter: Dict[str, Any], snapshot_id: str = "", workspace: Any = None, **_) -> Dict[str, Any]:+ if not snapshot_id:+ from revit_mcp_server.semantic.engine import generate_mock_snapshot+ snap = generate_mock_snapshot()+ elements = [el.model_dump(by_alias=True) for el in snap.elements]+ else:+ data = _load_snapshot(snapshot_id, workspace)+ elements = data.get("elements", [])++ matched = [el for el in elements if _match_element(el, filter)]+ chips = [_element_chip(el) for el in matched]++ return {+ "filter": filter,+ "matches_count": len(chips),+ "elements": chips,+ }++ def list_groups(self, snapshot_id: str = "", workspace: Any = None, **_) -> Dict[str, Any]:+ if not snapshot_id:+ from revit_mcp_server.semantic.engine import generate_mock_snapshot+ snap = generate_mock_snapshot()+ elements = [el.model_dump(by_alias=True) for el in snap.elements]+ else:+ data = _load_snapshot(snapshot_id, workspace)+ elements = data.get("elements", [])++ # Collect group members+ groups: Dict[str, List[Dict[str, Any]]] = defaultdict(list)+ for el in elements:+ gid = el.get("group_uid")+ if gid:+ groups[gid].append(_element_chip(el))++ group_list = [+ {"group_uid": gid, "member_count": len(members), "members": members}+ for gid, members in groups.items()+ ]++ return {+ "groups_count": len(group_list),+ "groups": group_list,+ }++ def inspect_selection(self, element_uids: List[str], snapshot_id: str = "", workspace: Any = None, **_) -> Dict[str, Any]:+ if not snapshot_id:+ from revit_mcp_server.semantic.engine import generate_mock_snapshot+ snap = generate_mock_snapshot()+ elements = {el.uid: el.model_dump(by_alias=True) for el in snap.elements}+ else:+ data = _load_snapshot(snapshot_id, workspace)+ elements = {el["uid"]: el for el in data.get("elements", [])}++ cards = []+ missing = []+ for uid in element_uids:+ el = elements.get(uid)+ if not el:+ missing.append(uid)+ continue++ warnings = []+ # Basic BIM quality warnings+ if el.get("category") == "OST_Rooms":+ area = (el.get("params", {}).get("Area") or {}).get("v", 0)+ if not (el.get("level_uid") or el.get("location")):+ warnings.append("Room is not placed")+ elif area == 0:+ warnings.append("Room has zero area (not enclosed)")+ mark = (el.get("params", {}).get("Number") or {}).get("v")+ if not mark:+ warnings.append("Room has no Number parameter set")++ if el.get("category") in ("OST_Doors", "OST_Windows"):+ mark = (el.get("params", {}).get("Mark") or {}).get("v")+ if not mark:+ warnings.append("Element has no Mark parameter")++ cards.append({+ "uid": el["uid"],+ "element_id": el.get("element_id"),+ "category": el.get("category"),+ "family": el.get("family"),+ "type_name": el.get("type_name"),+ "host_uid": el.get("host_uid"),+ "level_uid": el.get("level_uid"),+ "workset": el.get("workset"),+ "group_uid": el.get("group_uid"),+ "location": el.get("location"),+ "params": el.get("params", {}),+ "warnings": warnings,+ })++ return {+ "inspected_count": len(cards),+ "missing_uids": missing,+ "elements": cards,+ }++ def save_query(self, query_name: str, filter: Dict[str, Any], workspace: Any = None, **_) -> Dict[str, Any]:+ queries = _load_queries(workspace)+ queries[query_name] = filter+ _save_queries(queries, workspace)+ return {"status": "saved", "query_name": query_name, "filter": filter}++ def run_saved_query(self, query_name: str, snapshot_id: str = "", workspace: Any = None, **_) -> Dict[str, Any]:+ queries = _load_queries(workspace)+ if query_name not in queries:+ raise ValueError(f"No saved query named '{query_name}'.")+ filter_dsl = queries[query_name]+ return self.ask(filter=filter_dsl, snapshot_id=snapshot_id, workspace=workspace)++ def list_saved_queries(self, workspace: Any = None, **_) -> Dict[str, Any]:+ queries = _load_queries(workspace)+ return {+ "count": len(queries),+ "queries": [{"name": k, "filter": v} for k, v in queries.items()],+ }diff --git a/packages/mcp-server-revit/src/revit_mcp_server/providers/semantic_provider.py b/packages/mcp-server-revit/src/revit_mcp_server/providers/semantic_provider.pyindex 34f2c1b..9d7025a 100644--- a/packages/mcp-server-revit/src/revit_mcp_server/providers/semantic_provider.py+++ b/packages/mcp-server-revit/src/revit_mcp_server/providers/semantic_provider.py@@ -162,7 +162,7 @@ class SemanticProvider(AECProvider):}def _load_snapshot(self, snapshot_id: str) -> Snapshot:- snapshots_dir = self.workspace.workspace_dir / "snapshots"+ snapshots_dir = self.workspace.allowed_directories[0] / "snapshots"snapshot_path = snapshots_dir / f"{snapshot_id}.json"if not snapshot_path.exists():diff --git a/packages/mcp-server-revit/tests/test_model_inspector.py b/packages/mcp-server-revit/tests/test_model_inspector.pynew file mode 100644index 0000000..537c701--- /dev/null+++ b/packages/mcp-server-revit/tests/test_model_inspector.py@@ -0,0 +1,134 @@+"""Tests for Phase 7 — Model Inspector module (W1–W3)."""+import importlib.util+import json+import pytest+from pathlib import Path+from revit_mcp_server.semantic.engine import generate_mock_snapshot++# Load the module file directly so we bypass the sys.modules conflict+# caused by the module_registry registering the same name as a flat module.+_MODULE_PY = (+ Path(__file__).parent.parent+ / "src/revit_mcp_server/modules/model_inspector/module.py"+)+_spec = importlib.util.spec_from_file_location("_model_inspector_impl", _MODULE_PY)+_mod = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(_mod)+ModelInspectorModule = _mod.ModelInspectorModule+++class MockWorkspace:+ """Minimal workspace stub pointing to tmp_path."""+ def __init__(self, tmp_path: Path):+ self.allowed_directories = [tmp_path]+++def workspace(tmp_path):+ return MockWorkspace(tmp_path)+++def module():+ return ModelInspectorModule()+++def snap_and_workspace(tmp_path):+ ws = MockWorkspace(tmp_path)+ snap = generate_mock_snapshot()+ snap_dir = tmp_path / "snapshots"+ snap_dir.mkdir(parents=True, exist_ok=True)+ snap_path = snap_dir / f"{snap.snapshot_id}.json"+ with open(snap_path, "w", encoding="utf-8") as f:+ f.write(snap.model_dump_json(by_alias=True, indent=2))+ return snap, ws+++def test_summarize_model_no_snapshot(module, workspace):+ """summarize_model without snapshot_id generates mock."""+ result = module.summarize_model(workspace=workspace)+ assert result["elements_total"] == 6+ assert "OST_Doors" in result["by_category"]+ assert result["rooms"]["total"] == 2+ assert result["rooms"]["placed"] == 1+ assert result["rooms"]["unplaced"] == 1+++def test_summarize_model_with_snapshot(module, snap_and_workspace):+ snap, ws = snap_and_workspace+ result = module.summarize_model(snapshot_id=snap.snapshot_id, workspace=ws)+ assert result["elements_total"] == 6+ assert result["rooms"]["total"] == 2+++def test_ask_filter_by_category(module, workspace):+ result = module.ask(filter={"category": "OST_Walls"}, workspace=workspace)+ assert result["matches_count"] == 1+ assert result["elements"][0]["category"] == "OST_Walls"+++def test_ask_filter_by_parameter_value(module, workspace):+ result = module.ask(filter={"category": "OST_Rooms", "parameter": {"name": "Number", "value": "102"}}, workspace=workspace)+ assert result["matches_count"] == 1+ assert "placed" in result["elements"][0]["uid"] or result["elements"][0]["category"] == "OST_Rooms"+++def test_ask_filter_unplaced_rooms(module, workspace):+ result = module.ask(filter={"category": "OST_Rooms", "placed": False}, workspace=workspace)+ assert result["matches_count"] == 1+ assert "unplaced" in result["elements"][0]["uid"]+++def test_list_groups_no_groups(module, workspace):+ """Mock snapshot has no groups, result should be empty."""+ result = module.list_groups(workspace=workspace)+ assert result["groups_count"] == 0+++def test_inspect_selection_with_door(module, workspace):+ door_uid = "c0326e0e-473d-4952-b8ec-f23696541f44-door-1"+ result = module.inspect_selection(element_uids=[door_uid], workspace=workspace)+ assert result["inspected_count"] == 1+ card = result["elements"][0]+ assert card["uid"] == door_uid+ assert card["category"] == "OST_Doors"+ assert "params" in card+++def test_inspect_selection_missing_uid(module, workspace):+ result = module.inspect_selection(element_uids=["nonexistent-uid"], workspace=workspace)+ assert result["inspected_count"] == 0+ assert "nonexistent-uid" in result["missing_uids"]+++def test_inspect_selection_room_warnings(module, workspace):+ unplaced_uid = "c0326e0e-473d-4952-b8ec-f23696541f45-room-unplaced"+ result = module.inspect_selection(element_uids=[unplaced_uid], workspace=workspace)+ card = result["elements"][0]+ # Unplaced room should warn+ assert any("not placed" in w or "unplaced" in w.lower() for w in card["warnings"])+++def test_save_and_run_saved_query(module, workspace):+ query_name = "all_doors"+ filter_dsl = {"category": "OST_Doors"}++ # Save+ save_res = module.save_query(query_name=query_name, filter=filter_dsl, workspace=workspace)+ assert save_res["status"] == "saved"++ # List+ list_res = module.list_saved_queries(workspace=workspace)+ assert list_res["count"] == 1+ assert list_res["queries"][0]["name"] == query_name++ # Run+ run_res = module.run_saved_query(query_name=query_name, workspace=workspace)+ assert run_res["matches_count"] == 1+ assert run_res["elements"][0]["category"] == "OST_Doors"+++def test_run_nonexistent_query_raises(module, workspace):+ with pytest.raises(ValueError, match="No saved query"):+ module.run_saved_query(query_name="does_not_exist", workspace=workspace)