Skip to content

Open-source Revit MCP server: let Claude and other AI assistants read and edit BIM models, with human approval on every change.

feat(modules): implement Selection Tools module — set/save/restore/query selections, group rename/ungroup/convert plans (P8.1-P8.2)

A. Sam Mohammada76de8e0d222
diff --git a/docs/tools-generated.md b/docs/tools-generated.md
index 9e50cd0..0635adb 100644
--- a/docs/tools-generated.md
+++ b/docs/tools-generated.md
@@ -79,6 +79,14 @@ This catalog lists all tools exposed by the AEC Model Bridge providers.
| `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 |
+| `selection_tools_group_convert_to_detail` | Convert Group to Detail Group. | Yes | sync |
+| `selection_tools_group_rename` | Rename Group. | Yes | sync |
+| `selection_tools_group_ungroup` | Ungroup Group. | Yes | sync |
+| `selection_tools_list_saved_selections` | List Saved Selections. | No | sync |
+| `selection_tools_restore_selection` | Restore Selection. | Yes | sync |
+| `selection_tools_save_selection` | Save Selection. | No | sync |
+| `selection_tools_select_by_query` | Select By Query. | Yes | sync |
+| `selection_tools_set_selection` | Set Selection. | Yes | sync |
## Navisworks Provider
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/selection_tools/__init__.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/selection_tools/__init__.py
new file mode 100644
index 0000000..d44dbaf
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/selection_tools/__init__.py
@@ -0,0 +1 @@
+# selection_tools package
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/selection_tools/module.json b/packages/mcp-server-revit/src/revit_mcp_server/modules/selection_tools/module.json
new file mode 100644
index 0000000..1b2f9ed
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/selection_tools/module.json
@@ -0,0 +1,148 @@
+{
+ "id": "selection_tools",
+ "name": "Selection Tools",
+ "version": "1.0.0",
+ "schema_version": 1,
+ "min_hub_version": "1.2.0",
+ "description": "Selection management and model group workflows (W2 write side, W4): set/save/restore selections, select-by-query, rename/ungroup/convert groups with approval plan preview.",
+ "author": "AEC Model Bridge",
+ "license": "GPL-3.0-or-later",
+ "requires_providers": ["revit", "semantic"],
+ "permissions": ["model.read", "model.write"],
+ "commands": [
+ {
+ "id": "set_selection",
+ "title": "Set Selection",
+ "surface": ["mcp", "panel"],
+ "execution_mode": "sync",
+ "is_mutating": true,
+ "destructive": false,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "element_uids": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "Element UIDs to select in the active Revit view."
+ }
+ },
+ "required": ["element_uids"]
+ }
+ },
+ {
+ "id": "save_selection",
+ "title": "Save Selection",
+ "surface": ["mcp", "panel"],
+ "execution_mode": "sync",
+ "is_mutating": false,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "selection_name": {"type": "string", "description": "Name to save the current selection under."},
+ "element_uids": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "Element UIDs to persist as a named selection."
+ }
+ },
+ "required": ["selection_name", "element_uids"]
+ }
+ },
+ {
+ "id": "restore_selection",
+ "title": "Restore Selection",
+ "surface": ["mcp", "panel"],
+ "execution_mode": "sync",
+ "is_mutating": true,
+ "destructive": false,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "selection_name": {"type": "string", "description": "Name of a previously saved selection to restore."}
+ },
+ "required": ["selection_name"]
+ }
+ },
+ {
+ "id": "select_by_query",
+ "title": "Select By Query",
+ "surface": ["mcp", "panel"],
+ "execution_mode": "sync",
+ "is_mutating": true,
+ "destructive": false,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "snapshot_id": {"type": "string"},
+ "filter": {
+ "type": "object",
+ "description": "DSL filter to identify elements to select."
+ }
+ },
+ "required": ["filter"]
+ }
+ },
+ {
+ "id": "list_saved_selections",
+ "title": "List Saved Selections",
+ "surface": ["mcp", "panel"],
+ "execution_mode": "sync",
+ "is_mutating": false,
+ "input_schema": {
+ "type": "object",
+ "properties": {},
+ "required": []
+ }
+ },
+ {
+ "id": "group_rename",
+ "title": "Rename Group",
+ "surface": ["mcp"],
+ "execution_mode": "sync",
+ "is_mutating": true,
+ "destructive": false,
+ "requires_plan": true,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "group_uid": {"type": "string", "description": "UID of the group type or instance to rename."},
+ "new_name": {"type": "string", "description": "New name for the group type."}
+ },
+ "required": ["group_uid", "new_name"]
+ }
+ },
+ {
+ "id": "group_ungroup",
+ "title": "Ungroup Group",
+ "surface": ["mcp"],
+ "execution_mode": "sync",
+ "is_mutating": true,
+ "destructive": true,
+ "requires_plan": true,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "group_uid": {"type": "string", "description": "UID of the group instance to ungroup."},
+ "snapshot_id": {"type": "string", "description": "Snapshot to use for member count preview."}
+ },
+ "required": ["group_uid"]
+ }
+ },
+ {
+ "id": "group_convert_to_detail",
+ "title": "Convert Group to Detail Group",
+ "surface": ["mcp"],
+ "execution_mode": "sync",
+ "is_mutating": true,
+ "destructive": false,
+ "requires_plan": true,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "group_uid": {"type": "string", "description": "UID of the model group to convert to a detail group."}
+ },
+ "required": ["group_uid"]
+ }
+ }
+ ]
+}
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/selection_tools/module.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/selection_tools/module.py
new file mode 100644
index 0000000..aa940bd
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/selection_tools/module.py
@@ -0,0 +1,223 @@
+"""
+selection_tools module — P8.1 + P8.2 Selection & Model Group Workflows.
+
+Commands:
+ set_selection — Stage element UIDs to be selected (signals Revit plugin).
+ save_selection — Persist a named selection to workspace.
+ restore_selection — Retrieve and stage a previously saved selection.
+ select_by_query — Run DSL filter to compute element UIDs, then stage selection.
+ list_saved_selections — Enumerate all named saved selections.
+
+ group_rename — Draft ActionPlan to rename a group type.
+ group_ungroup — Draft ActionPlan to ungroup with member count in preview.
+ group_convert_to_detail — Draft ActionPlan to convert model group → detail group.
+
+All group write commands produce ActionPlan dicts (not executed here) that must be
+approved via the approval provider before forwarding to Revit.
+"""
+from __future__ import annotations
+
+import json
+import logging
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+logger = logging.getLogger(__name__)
+
+SELECTIONS_FILE = "saved_selections.json"
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _workspace_dir(workspace: Any) -> Path:
+ return workspace.allowed_directories[0]
+
+def _selections_file(workspace: Any) -> Path:
+ return _workspace_dir(workspace) / SELECTIONS_FILE
+
+def _load_selections(workspace: Any) -> Dict[str, List[str]]:
+ sf = _selections_file(workspace)
+ if sf.exists():
+ with open(sf, "r", encoding="utf-8") as f:
+ return json.load(f)
+ return {}
+
+def _save_selections(selections: Dict[str, List[str]], workspace: Any) -> None:
+ sf = _selections_file(workspace)
+ with open(sf, "w", encoding="utf-8") as f:
+ json.dump(selections, f, indent=2)
+
+def _load_snapshot(snapshot_id: str, workspace: Any) -> Dict[str, Any]:
+ path = _workspace_dir(workspace) / "snapshots" / 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 _match_element(el: Dict[str, Any], filter_dsl: Dict[str, Any]) -> bool:
+ 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 _make_action_plan(tool_name: str, args: Dict[str, Any], preview: Dict[str, Any]) -> Dict[str, Any]:
+ """Return a lightweight ActionPlan dict stub for gated writes."""
+ return {
+ "plan_type": "action_plan_draft",
+ "tool": tool_name,
+ "arguments": args,
+ "preview": preview,
+ "requires_approval": True,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Command implementations
+# ---------------------------------------------------------------------------
+
+class SelectionToolsModule:
+
+ def set_selection(self, element_uids: List[str], workspace: Any = None, **_) -> Dict[str, Any]:
+ """Stage element UIDs to be selected. The dockable panel / bridge picks this up."""
+ # Write pending selection to workspace for the plugin to pick up
+ pending_path = _workspace_dir(workspace) / "pending_selection.json"
+ with open(pending_path, "w", encoding="utf-8") as f:
+ json.dump({"element_uids": element_uids}, f, indent=2)
+ return {
+ "status": "staged",
+ "element_count": len(element_uids),
+ "pending_file": str(pending_path),
+ }
+
+ def save_selection(self, selection_name: str, element_uids: List[str], workspace: Any = None, **_) -> Dict[str, Any]:
+ selections = _load_selections(workspace)
+ selections[selection_name] = element_uids
+ _save_selections(selections, workspace)
+ return {"status": "saved", "selection_name": selection_name, "count": len(element_uids)}
+
+ def restore_selection(self, selection_name: str, workspace: Any = None, **_) -> Dict[str, Any]:
+ selections = _load_selections(workspace)
+ if selection_name not in selections:
+ raise ValueError(f"No saved selection named '{selection_name}'.")
+ element_uids = selections[selection_name]
+ # Stage it as pending
+ return self.set_selection(element_uids=element_uids, workspace=workspace)
+
+ def select_by_query(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_uids = [el["uid"] for el in elements if _match_element(el, filter)]
+ return self.set_selection(element_uids=matched_uids, workspace=workspace)
+
+ def list_saved_selections(self, workspace: Any = None, **_) -> Dict[str, Any]:
+ selections = _load_selections(workspace)
+ return {
+ "count": len(selections),
+ "selections": [{"name": k, "element_count": len(v)} for k, v in selections.items()],
+ }
+
+ def group_rename(self, group_uid: str, new_name: str, snapshot_id: str = "", workspace: Any = None, **_) -> Dict[str, Any]:
+ # Look up group info from snapshot
+ group_info = self._find_group(group_uid, snapshot_id, workspace)
+ preview = {
+ "group_uid": group_uid,
+ "current_name": group_info.get("current_name", "<unknown>"),
+ "new_name": new_name,
+ "instance_count": group_info.get("instance_count", 0),
+ "description": f"Rename group type to '{new_name}'. Affects {group_info.get('instance_count', 0)} instance(s).",
+ }
+ return _make_action_plan(
+ "group_rename",
+ {"group_uid": group_uid, "new_name": new_name},
+ preview
+ )
+
+ def group_ungroup(self, group_uid: str, snapshot_id: str = "", workspace: Any = None, **_) -> Dict[str, Any]:
+ group_info = self._find_group(group_uid, snapshot_id, workspace)
+ member_count = group_info.get("member_count", 0)
+ preview = {
+ "group_uid": group_uid,
+ "member_count": member_count,
+ "description": (
+ f"Ungroup will dissolve {member_count} member(s) into individual elements. "
+ "This is destructive and requires a rollback plan."
+ ),
+ "unsupported_cases": ["nested groups", "mirrored instances", "view-specific groups"],
+ }
+ return _make_action_plan(
+ "group_ungroup",
+ {"group_uid": group_uid},
+ preview
+ )
+
+ def group_convert_to_detail(self, group_uid: str, snapshot_id: str = "", workspace: Any = None, **_) -> Dict[str, Any]:
+ group_info = self._find_group(group_uid, snapshot_id, workspace)
+ preview = {
+ "group_uid": group_uid,
+ "current_name": group_info.get("current_name", "<unknown>"),
+ "description": "Convert model group to detail group. Members become annotation/detail elements.",
+ }
+ return _make_action_plan(
+ "group_convert_to_detail",
+ {"group_uid": group_uid},
+ preview
+ )
+
+ # -----------------------------------------------------------------------
+ # Internal helpers
+ # -----------------------------------------------------------------------
+
+ def _find_group(self, group_uid: str, snapshot_id: str, workspace: Any) -> 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", [])
+
+ # Count instances (elements that are groups OR members of this group)
+ group_el = next((el for el in elements if el.get("uid") == group_uid), None)
+ member_elements = [el for el in elements if el.get("group_uid") == group_uid]
+
+ return {
+ "current_name": group_el.get("type_name") if group_el else "<unknown>",
+ "member_count": len(member_elements),
+ "instance_count": 1, # Without a real Revit connection, assume 1 visible instance
+ }
diff --git a/packages/mcp-server-revit/tests/test_selection_tools.py b/packages/mcp-server-revit/tests/test_selection_tools.py
new file mode 100644
index 0000000..8514b42
--- /dev/null
+++ b/packages/mcp-server-revit/tests/test_selection_tools.py
@@ -0,0 +1,121 @@
+"""Tests for Phase 8 — Selection Tools module (W2 write side, W4)."""
+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 to bypass sys.modules namespace conflict
+_MODULE_PY = (
+ Path(__file__).parent.parent
+ / "src/revit_mcp_server/modules/selection_tools/module.py"
+)
+_spec = importlib.util.spec_from_file_location("_selection_tools_impl", _MODULE_PY)
+_mod = importlib.util.module_from_spec(_spec)
+_spec.loader.exec_module(_mod)
+SelectionToolsModule = _mod.SelectionToolsModule
+
+
+class MockWorkspace:
+ def __init__(self, tmp_path: Path):
+ self.allowed_directories = [tmp_path]
+
+
+def workspace(tmp_path):
+ return MockWorkspace(tmp_path)
+
+
+def module():
+ return SelectionToolsModule()
+
+
+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
+
+
+# --- Selection tests ---
+
+def test_set_selection_creates_pending_file(module, workspace, tmp_path):
+ uids = ["uid-1", "uid-2"]
+ result = module.set_selection(element_uids=uids, workspace=workspace)
+ assert result["status"] == "staged"
+ assert result["element_count"] == 2
+ pending_path = tmp_path / "pending_selection.json"
+ assert pending_path.exists()
+ data = json.loads(pending_path.read_text())
+ assert data["element_uids"] == uids
+
+
+def test_save_and_restore_selection(module, workspace):
+ uids = ["wall-uid-abc", "door-uid-xyz"]
+ module.save_selection(selection_name="test_sel", element_uids=uids, workspace=workspace)
+
+ res = module.restore_selection(selection_name="test_sel", workspace=workspace)
+ assert res["status"] == "staged"
+ assert res["element_count"] == 2
+
+
+def test_restore_nonexistent_raises(module, workspace):
+ with pytest.raises(ValueError, match="No saved selection"):
+ module.restore_selection(selection_name="does_not_exist", workspace=workspace)
+
+
+def test_list_saved_selections(module, workspace):
+ module.save_selection("sel_a", ["uid-1"], workspace=workspace)
+ module.save_selection("sel_b", ["uid-2", "uid-3"], workspace=workspace)
+ result = module.list_saved_selections(workspace=workspace)
+ assert result["count"] == 2
+ names = {s["name"] for s in result["selections"]}
+ assert "sel_a" in names
+ assert "sel_b" in names
+
+
+def test_select_by_query_doors(module, workspace):
+ result = module.select_by_query(filter={"category": "OST_Doors"}, workspace=workspace)
+ assert result["status"] == "staged"
+ assert result["element_count"] == 1
+
+
+def test_select_by_query_with_snapshot(module, snap_and_workspace):
+ snap, ws = snap_and_workspace
+ result = module.select_by_query(
+ filter={"category": "OST_Walls"},
+ snapshot_id=snap.snapshot_id,
+ workspace=ws
+ )
+ assert result["element_count"] == 1
+
+
+# --- Group write plan tests ---
+
+def test_group_rename_returns_action_plan(module, workspace):
+ result = module.group_rename(group_uid="some-group-uid", new_name="Lobby_Group_A", workspace=workspace)
+ assert result["plan_type"] == "action_plan_draft"
+ assert result["requires_approval"] is True
+ assert result["arguments"]["new_name"] == "Lobby_Group_A"
+ assert "Lobby_Group_A" in result["preview"]["description"]
+
+
+def test_group_ungroup_returns_plan_with_member_count(module, workspace):
+ result = module.group_ungroup(group_uid="some-group-uid", workspace=workspace)
+ assert result["plan_type"] == "action_plan_draft"
+ assert result["tool"] == "group_ungroup"
+ assert "member_count" in result["preview"]
+ # Unsupported cases are documented
+ assert "nested groups" in result["preview"]["unsupported_cases"]
+
+
+def test_group_convert_returns_action_plan(module, workspace):
+ result = module.group_convert_to_detail(group_uid="some-group-uid", workspace=workspace)
+ assert result["plan_type"] == "action_plan_draft"
+ assert result["tool"] == "group_convert_to_detail"