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(panel): click-to-select findings and working report open/refresh
sammohammad5782a3e79ce781f
diff --git a/Hermes.json b/Hermes.jsonindex 88e2aec..cbb2e17 100644--- a/Hermes.json+++ b/Hermes.json@@ -1,6 +1,6 @@{"mcpServers": {- "aec-model-bridge": {+ "aec-model-bridge-revit-2026": {"command": "C:\\path\\to\\aec-model-bridge\\.venv\\Scripts\\python.exe","args": ["-m",@@ -8,7 +8,7 @@],"env": {"MCP_REVIT_MODE": "bridge",- "MCP_REVIT_BRIDGE_URL": "http://127.0.0.1:3000",+ "MCP_REVIT_HOST_VERSION": "2026","MCP_REVIT_WORKSPACE_DIR": "C:\\RevitProjects","MCP_REVIT_ALLOWED_DIRECTORIES": "C:\\RevitProjects"},@@ -159,6 +159,7 @@"revit_replace_family_type","revit_rotate_element","revit_save_document",+ "revit_select_by_unique_ids","revit_set_element_material","revit_set_parameter_value","revit_set_selection",diff --git a/docs/tools-generated.md b/docs/tools-generated.mdindex 858cc79..5a4ad20 100644--- a/docs/tools-generated.md+++ b/docs/tools-generated.md@@ -224,6 +224,7 @@ This catalog lists all tools exposed by the AEC Model Bridge providers.| `revit_replace_family_type` | Replace all instances of one family/type combination with another, identified by name. | Yes | sync || `revit_rotate_element` | Rotate an element. | Yes | sync || `revit_save_document` | Save the current Revit document. | Yes | sync |+| `revit_select_by_unique_ids` | Select and zoom to elements in the active view by their UniqueId. | No | sync || `revit_set_element_material` | Set material for an element or specific face. | Yes | sync || `revit_set_parameter_value` | Set a parameter value for an element. | Yes | sync || `revit_set_selection` | Set selection by element IDs. | Yes | sync |diff --git a/packages/mcp-server-revit/src/revit_mcp_server/panel_server.py b/packages/mcp-server-revit/src/revit_mcp_server/panel_server.pyindex 52e224f..e191768 100644--- a/packages/mcp-server-revit/src/revit_mcp_server/panel_server.py+++ b/packages/mcp-server-revit/src/revit_mcp_server/panel_server.py@@ -31,6 +31,14 @@ logger = logging.getLogger(__name__)DEFAULT_PORT = 8787+# report_generator writes exports directly to the workspace root (see+# modules/report_generator/module.py's _ws_dir). Other modules keep their own+# state there too (qaqc_issues.db, saved_selections.json) - these are never+# something a user exported and would want to open, so they're excluded by+# name even though qaqc_issues.db shares a report extension.+REPORT_EXTENSIONS = {".xlsx", ".csv", ".db"}+NON_REPORT_FILENAMES = {"qaqc_issues.db"}+def _run_tool_sync(registry, approval_provider, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:"""Execute one tool call to completion in a fresh event loop.@@ -64,6 +72,7 @@ def _run_tool_sync(registry, approval_provider, name: str, arguments: Dict[str,class PanelRequestHandler(BaseHTTPRequestHandler):registry = Noneapproval_provider = None+ workspace = Nonedef log_message(self, format: str, *args: Any) -> None: # noqa: A002logger.debug("panel_server: " + format, *args)@@ -80,8 +89,27 @@ class PanelRequestHandler(BaseHTTPRequestHandler):if self.path == "/health":self._send_json(200, {"status": "healthy", "tools": len(self.registry.get_all_tools())})return+ if self.path == "/reports":+ self._handle_list_reports()+ returnself._send_json(404, {"ok": False, "error": f"Unknown path '{self.path}'"})+ def _handle_list_reports(self) -> None:+ workspace_dir = self.workspace.allowed_directories[0]+ reports = [+ {+ "path": str(entry),+ "name": entry.name,+ "modified": entry.stat().st_mtime,+ }+ for entry in workspace_dir.iterdir()+ if entry.is_file()+ and entry.suffix.lower() in REPORT_EXTENSIONS+ and entry.name not in NON_REPORT_FILENAMES+ ]+ reports.sort(key=lambda r: r["modified"], reverse=True)+ self._send_json(200, {"ok": True, "reports": reports})+def do_POST(self) -> None: # noqa: N802if self.path == "/agent/chat":self._handle_agent_chat()@@ -142,11 +170,12 @@ class PanelRequestHandler(BaseHTTPRequestHandler):def build_server(port: int | None = None, workspace: WorkspaceMonitor | None = None) -> ThreadingHTTPServer:- registry, approval_provider, _job_manager, _module_registry, _workspace = build_registry(workspace=workspace)+ registry, approval_provider, _job_manager, _module_registry, resolved_workspace = build_registry(workspace=workspace)handler = type("BoundPanelRequestHandler", (PanelRequestHandler,), {"registry": registry,"approval_provider": approval_provider,+ "workspace": resolved_workspace,})resolved_port = port if port is not None else int(os.getenv("MCP_PANEL_HTTP_PORT", str(DEFAULT_PORT)))diff --git a/packages/mcp-server-revit/src/revit_mcp_server/providers/revit.py b/packages/mcp-server-revit/src/revit_mcp_server/providers/revit.pyindex f18aa13..5e0a8de 100644--- a/packages/mcp-server-revit/src/revit_mcp_server/providers/revit.py+++ b/packages/mcp-server-revit/src/revit_mcp_server/providers/revit.py@@ -7,7 +7,7 @@ import httpxfrom ..bridge.client import BridgeClientfrom ..bridge.mock import MockBridgefrom ..config import BridgeMode, config-from ..errors import WorkspaceViolation+from ..errors import BridgeError, WorkspaceViolationfrom ..legacy.tools import TOOL_HANDLERSfrom ..security.workspace import WorkspaceMonitorfrom .base import AECProvider, ProviderTool, enrich_mutation_metadata@@ -15,17 +15,33 @@ from .base import AECProvider, ProviderTool, enrich_mutation_metadatalogger = logging.getLogger(__name__)+class UnavailableBridge:+ def __init__(self, message: str) -> None:+ self.message = message++ def initialize(self) -> None:+ return None++ def _get(self, path: str) -> Dict[str, Any]:+ return {"status": "unhealthy", "error": self.message}++ def send_tool(self, tool_name: str, payload: dict) -> dict:+ raise BridgeError(self.message)++class RevitProvider(AECProvider):def __init__(self,workspace: WorkspaceMonitor,mode: BridgeMode = config.mode,bridge_url: str | None = config.bridge_url,+ host_version: str | None = config.host_version,bridge_factory=None,) -> None:self.workspace = workspaceself.mode = modeself.bridge_url = bridge_url+ self.host_version = host_versionself._bridge = self._build_bridge(bridge_factory)self._init_tool_mapping()self._enrich_tool_metadata()@@ -67,18 +83,30 @@ class RevitProvider(AECProvider):def _build_bridge(self, factory=None):if self.mode == BridgeMode.bridge:- from ..bridge.discovery import discover_switches-- switches = discover_switches()+ from ..bridge.discovery import available_host_versions, select_switchurl = self.bridge_urltoken = Noneif not url:- if "revit" in switches:- url = switches["revit"].endpoint- token = switches["revit"].session_token- logger.info("Resolved Revit switch from registry: %s", url)+ switch = select_switch("revit", self.host_version)+ if switch:+ url = switch.endpoint+ token = switch.session_token+ logger.info(+ "Resolved Revit %s switch from registry: %s",+ switch.host_version,+ url,+ )+ elif self.host_version:+ versions = available_host_versions("revit")+ available = ", ".join(versions) if versions else "none"+ message = (+ f"No live Revit {self.host_version} bridge found. "+ f"Available Revit versions: {available}."+ )+ logger.warning(message)+ return UnavailableBridge(message)else:url = "http://127.0.0.1:3000"for port in (3000, 3002):@@ -402,6 +430,10 @@ class RevitProvider(AECProvider):),"revit_get_selection": ("revit.get_selection", lambda args: {}),"revit_set_selection": ("revit.set_selection", lambda args: {"element_ids": args.get("element_ids")}),+ "revit_select_by_unique_ids": (+ "revit.select_by_unique_ids",+ lambda args: {"element_uids": args.get("element_uids")},+ ),"revit_create_text_note": ("revit.create_text_note",lambda args: {@@ -1205,6 +1237,19 @@ class RevitProvider(AECProvider):"required": ["element_ids"],},),+ # Not flagged mutating: only changes what's selected/framed in the active+ # view, never the document, so the dockable panel can jump to a flagged+ # element (by its stable UniqueId, unlike revit_set_selection's+ # session-scoped ElementIds) without an approval round trip.+ ProviderTool(+ name="revit_select_by_unique_ids",+ description="Select and zoom to elements in the active view by their UniqueId",+ inputSchema={+ "type": "object",+ "properties": {"element_uids": {"type": "array", "items": {"type": "string"}}},+ "required": ["element_uids"],+ },+ ),ProviderTool(name="revit_create_text_note",description="Create a text note",diff --git a/packages/mcp-server-revit/tests/test_panel_server.py b/packages/mcp-server-revit/tests/test_panel_server.pyindex 27ffce5..1e6d030 100644--- a/packages/mcp-server-revit/tests/test_panel_server.py+++ b/packages/mcp-server-revit/tests/test_panel_server.py@@ -8,6 +8,7 @@ from __future__ import annotationsimport jsonimport threading+import timeimport urllib.errorimport urllib.request@@ -100,6 +101,38 @@ def test_mutating_tool_without_plan_is_rejected(running_server):assert "plan_id" in body["error"]+def test_reports_lists_workspace_exports_newest_first(running_server, tmp_path):+ """The Reports tab's Refresh button has no MCP tool behind it - it lists+ whatever report_generator has already written to the workspace root."""+ (tmp_path / "model_report.xlsx").write_bytes(b"x")+ time.sleep(0.05)+ (tmp_path / "model_data.db").write_bytes(b"x")++ status, body = _get(running_server, "/reports")++ assert status == 200+ assert body["ok"] is True+ assert [r["name"] for r in body["reports"]] == ["model_data.db", "model_report.xlsx"]+++def test_reports_excludes_internal_state_files(running_server, tmp_path):+ """qaqc_issues.db is the QA/QC module's own tracking database, not+ something report_generator exported - it must never appear as a report."""+ (tmp_path / "qaqc_issues.db").write_bytes(b"x")++ status, body = _get(running_server, "/reports")++ assert status == 200+ assert body["reports"] == []+++def test_reports_empty_workspace_returns_empty_list(running_server):+ status, body = _get(running_server, "/reports")+ assert status == 200+ assert body["ok"] is True+ assert body["reports"] == []++def test_plan_actions_approve_execute_round_trip_over_http(running_server):"""Proves the panel can drive the full W5 workflow end-to-end throughHTTP alone: plan -> approve -> execute -> verify, all as separatediff --git a/packages/mcp-server-revit/tests/test_providers.py b/packages/mcp-server-revit/tests/test_providers.pyindex 272c56f..4578aa4 100644--- a/packages/mcp-server-revit/tests/test_providers.py+++ b/packages/mcp-server-revit/tests/test_providers.py@@ -3,6 +3,7 @@ from pathlib import Pathimport ifcopenshellimport pytestfrom revit_mcp_server.config import BridgeMode+from revit_mcp_server.errors import BridgeErrorfrom revit_mcp_server.providers import FakeProvider, IfcProvider, ProviderRegistry, RevitProviderfrom revit_mcp_server.security.workspace import WorkspaceMonitor@@ -120,6 +121,69 @@ def test_revit_wall_placement_keeps_flat_coordinates_compatible(tmp_path):assert payload["location"] == {"x": 1.0, "y": 2.0, "z": 3.0}+def test_revit_select_by_unique_ids_is_registered_and_not_mutating(tmp_path):+ """The panel selects a flagged element by its stable UniqueId (not the+ session-scoped integer ElementId revit_set_selection expects), and must+ never require an approved plan just to change what's on screen."""+ workspace = WorkspaceMonitor([tmp_path])+ provider = RevitProvider(workspace=workspace, mode=BridgeMode.mock)++ tools = {tool.name: tool for tool in provider.get_capabilities()}+ assert "revit_select_by_unique_ids" in tools+ assert tools["revit_select_by_unique_ids"].is_mutating is False+++async def test_revit_select_by_unique_ids_passes_uids_through(tmp_path):+ workspace = WorkspaceMonitor([tmp_path])+ provider = RevitProvider(workspace=workspace, mode=BridgeMode.mock)++ result = await provider.execute_tool(+ "revit_select_by_unique_ids", {"element_uids": ["abc-123", "def-456"]}+ )++ assert result["tool"] == "revit.select_by_unique_ids"+ assert result["payload"]["element_uids"] == ["abc-123", "def-456"]+++def test_revit_provider_explicit_bridge_url_takes_precedence(tmp_path):+ workspace = WorkspaceMonitor([tmp_path])+ calls = []++ class DummyBridge:+ def initialize(self):+ calls.append(("initialize", None))++ provider = RevitProvider(+ workspace=workspace,+ mode=BridgeMode.bridge,+ bridge_url="http://bridge",+ host_version="2024",+ bridge_factory=lambda url, token=None: calls.append((url, token)) or DummyBridge(),+ )++ assert provider.bridge_url == "http://bridge"+ assert calls[0] == ("http://bridge", None)+++async def test_revit_provider_missing_requested_host_version_reports_available(tmp_path, monkeypatch):+ workspace = WorkspaceMonitor([tmp_path])++ monkeypatch.setattr("revit_mcp_server.bridge.discovery.select_switch", lambda provider_id, host_version: None)+ monkeypatch.setattr("revit_mcp_server.bridge.discovery.available_host_versions", lambda provider_id: ["2024", "2026"])++ provider = RevitProvider(workspace=workspace, mode=BridgeMode.bridge, host_version="2025")+ health = await provider.check_health()++ assert health["status"] == "unhealthy"+ assert "No live Revit 2025 bridge found" in health["error"]+ assert "2024, 2026" in health["error"]++ with pytest.raises(BridgeError, match="No live Revit 2025 bridge found"):+ await provider.execute_tool("revit_health", {})++@pytest.mark.anyioasync def test_ifc_provider_tools(tmp_path):workspace = WorkspaceMonitor([tmp_path])diff --git a/packages/revit-bridge-addin/src/Bridge/BridgeCommandFactory.cs b/packages/revit-bridge-addin/src/Bridge/BridgeCommandFactory.csindex 9039e3d..9ca9294 100644--- a/packages/revit-bridge-addin/src/Bridge/BridgeCommandFactory.cs+++ b/packages/revit-bridge-addin/src/Bridge/BridgeCommandFactory.cs@@ -2472,6 +2472,37 @@ public static class BridgeCommandFactoryreturn new { selected_count = ids.Count };}+ // UniqueId is stable across sessions (unlike ElementId, which revit.set_selection+ // takes) - the panel only has UniqueIds from QA/QC findings, which come from a+ // stored snapshot, not the live document. Not mutating: this only changes the+ // active view's selection/framing, never the document.+ [BridgeCommand("revit.select_by_unique_ids", IsMutating = false)]+ private static object ExecuteSelectByUniqueIds(UIApplication app, JsonElement payload)+ {+ var uidoc = app.ActiveUIDocument;+ if (uidoc == null) throw new InvalidOperationException("No active UIDocument");++ var doc = uidoc.Document;+ var requestedUids = payload.GetProperty("element_uids").EnumerateArray()+ .Select(x => x.GetString())+ .ToList();++ var ids = requestedUids+ .Select(uid => doc.GetElement(uid))+ .Where(element => element != null)+ .Select(element => element.Id)+ .ToList();++ if (ids.Count == 0)+ {+ return new { selected_count = 0, not_found_count = requestedUids.Count };+ }++ uidoc.Selection.SetElementIds(ids);+ uidoc.ShowElements(ids);+ return new { selected_count = ids.Count, not_found_count = requestedUids.Count - ids.Count };+ }+[BridgeCommand("revit.create_text_note", IsMutating = true)]private static object ExecuteCreateTextNote(UIApplication app, JsonElement payload){diff --git a/packages/revit-bridge-addin/src/UI/BridgePanel.xaml.cs b/packages/revit-bridge-addin/src/UI/BridgePanel.xaml.csindex f7304d6..b2d2ace 100644--- a/packages/revit-bridge-addin/src/UI/BridgePanel.xaml.cs+++ b/packages/revit-bridge-addin/src/UI/BridgePanel.xaml.cs@@ -1,5 +1,6 @@using System;using System.Collections.Generic;+using System.Diagnostics;using System.IO;using System.Text.Json;using System.Threading.Tasks;@@ -102,8 +103,11 @@ namespace RevitBridge.UI/// <summary>/// Maps a panel message type to a real hub tool call and posts the result back./// chat.message shells out to a CLI agent (see agent_bridge.py) rather than- /// calling a tool directly; settings/report-browsing remain local-only for now- /// (no corresponding hub tool).+ /// calling a tool directly; reports.refresh/open and selection.set have no MCP+ /// tool for one side of the round trip (reports.open opens a local file, and+ /// reports.refresh lists the workspace directly via the panel hub's /reports+ /// endpoint, not a tool call). settings remains local-only for now (no+ /// corresponding hub tool)./// </summary>private async Task DispatchToHubAsync(string message){@@ -150,6 +154,73 @@ namespace RevitBridge.UIawait RunToolAndPostAsync("report_generator_export_excel", new { }, "reports.updated", type);break;+ case "reports.refresh":+ {+ var reports = await HubClient.ListReportsAsync();+ if (!reports.Ok)+ {+ PostToPanel(new { type = "tool.error", action = type, message = reports.Error });+ break;+ }++ PostToPanel(new { type = "reports.list", reports = reports.Result });+ break;+ }++ case "reports.open":+ {+ var path = root.TryGetProperty("reportId", out var pathEl) ? pathEl.GetString() : null;+ if (string.IsNullOrEmpty(path))+ {+ break;+ }++ if (!File.Exists(path))+ {+ PostToPanel(new { type = "tool.error", action = type, message = $"Report file not found: {path}" });+ break;+ }++ try+ {+ Process.Start(new ProcessStartInfo(path) { UseShellExecute = true });+ }+ catch (Exception ex)+ {+ Log.Warning(ex, "Failed to open report file {Path}", path);+ PostToPanel(new { type = "tool.error", action = type, message = $"Could not open report: {ex.Message}" });+ }+ break;+ }++ case "selection.set":+ {+ var elementUids = new List<string>();+ if (root.TryGetProperty("elementUids", out var uidsEl) && uidsEl.ValueKind == JsonValueKind.Array)+ {+ foreach (var uidEl in uidsEl.EnumerateArray())+ {+ var uid = uidEl.GetString();+ if (!string.IsNullOrEmpty(uid))+ {+ elementUids.Add(uid);+ }+ }+ }++ if (elementUids.Count == 0)+ {+ break;+ }++ await RunToolAndPostAsync(+ "revit_select_by_unique_ids",+ new { element_uids = elementUids },+ "selection.result",+ type);+ break;+ }+case "chat.message":{var text = root.TryGetProperty("message", out var msgEl) ? msgEl.GetString() : null;diff --git a/packages/revit-bridge-addin/src/UI/HubClient.cs b/packages/revit-bridge-addin/src/UI/HubClient.csindex 356d5b1..d2122f6 100644--- a/packages/revit-bridge-addin/src/UI/HubClient.cs+++ b/packages/revit-bridge-addin/src/UI/HubClient.cs@@ -50,6 +50,22 @@ namespace RevitBridge.UI}}+ public static async Task<HubResult> ListReportsAsync()+ {+ try+ {+ using (var response = await Client.GetAsync($"http://127.0.0.1:{Port}/reports").ConfigureAwait(false))+ {+ var text = await response.Content.ReadAsStringAsync().ConfigureAwait(false);+ return ParseReportsResponse(text, (int)response.StatusCode);+ }+ }+ catch (Exception ex)+ {+ return HubResult.Failure($"Could not reach the AEC Model Bridge hub on 127.0.0.1:{Port}: {ex.Message}");+ }+ }+public static async Task<ChatResult> ChatAsync(string provider, string message, string sessionId){var requestBody = JsonSerializer.Serialize(new { provider, message, session_id = sessionId });@@ -69,6 +85,29 @@ namespace RevitBridge.UI}}+ private static HubResult ParseReportsResponse(string text, int statusCode)+ {+ try+ {+ using (var doc = JsonDocument.Parse(text))+ {+ var root = doc.RootElement;+ var ok = root.TryGetProperty("ok", out var okEl) && okEl.ValueKind == JsonValueKind.True;+ if (ok && root.TryGetProperty("reports", out var reportsEl))+ {+ return HubResult.Success(reportsEl.Clone());+ }++ var error = root.TryGetProperty("error", out var errEl) ? errEl.GetString() : null;+ return HubResult.Failure(error ?? $"Hub returned HTTP {statusCode}");+ }+ }+ catch (JsonException)+ {+ return HubResult.Failure($"Hub returned an unparseable response (HTTP {statusCode})");+ }+ }+private static HubResult ParseResponse(string text, int statusCode){trydiff --git a/panel/app.js b/panel/app.jsindex 14547a2..3fb2f13 100644--- a/panel/app.js+++ b/panel/app.js@@ -223,12 +223,18 @@ function renderFindings() {findings.forEach((finding) => {const item = document.createElement("article");item.className = "item";+ const selectButton = finding.elementUid+ ? `<div class="item-actions">+ <button type="button" data-select-uid="${escapeHtml(finding.elementUid)}">Select in Revit</button>+ </div>`+ : "";item.innerHTML = `<div class="item-head"><h2>${escapeHtml(finding.title)}</h2><span class="badge ${escapeHtml(finding.severity)}">${escapeHtml(finding.severity)}</span></div>- <p>${escapeHtml(finding.detail)}</p>`;+ <p>${escapeHtml(finding.detail)}</p>+ ${selectButton}`;findingList.appendChild(item);});}@@ -322,6 +328,12 @@ document.body.addEventListener("click", (event) => {postToHost("reports.open", { reportId });addLog("Report opened", reportId);}++ const selectUid = target.dataset.selectUid;+ if (selectUid) {+ postToHost("selection.set", { elementUids: [selectUid] });+ addLog("Selection requested", selectUid);+ }});chatForm.addEventListener("submit", (event) => {@@ -363,6 +375,7 @@ function mapFindings(hubResult) {const findings = (hubResult && hubResult.findings) || [];return findings.map((finding, index) => ({id: finding.element_uid ? `${finding.rule_id}:${finding.element_uid}` : `${finding.rule_id}:${index}`,+ elementUid: finding.element_uid || null,severity: finding.severity || "info",title: String(finding.rule_id || "finding").replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),detail: finding.message || ""@@ -391,6 +404,17 @@ function mapReport(hubResult) {};}+// Maps one entry from GET /reports (packages/mcp-server-revit's panel_server.py) -+// a plain workspace-directory listing, not an MCP tool result, since listing past+// exports has no tool of its own.+function mapReportEntry(entry) {+ return {+ id: entry.path,+ title: entry.name,+ detail: `Modified ${new Date(entry.modified * 1000).toLocaleString()}`+ };+}+if (window.chrome && window.chrome.webview) {window.chrome.webview.addEventListener("message", (event) => {if (event.data?.type === "host.status") {@@ -422,6 +446,19 @@ if (window.chrome && window.chrome.webview) {renderReports();addLog("Report exported", report.title);}+ if (event.data?.type === "reports.list") {+ state.reports = (event.data.reports || []).map(mapReportEntry);+ renderReports();+ addLog("Reports refreshed", `${state.reports.length} report(s)`);+ }+ if (event.data?.type === "selection.result") {+ const result = event.data.result || {};+ const notFound = result.not_found_count || 0;+ const detail = notFound > 0+ ? `${result.selected_count || 0} selected, ${notFound} not found in the active document`+ : `${result.selected_count || 0} selected`;+ addLog("Selection updated", detail);+ }if (event.data?.type === "tool.error") {addLog(`Error: ${event.data.action || "tool"}`, event.data.message || "Unknown error");}