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
fix(hub): fix silent rollback no-op, add execute_plan, close W5 execute-path gap
A. Sam Mohammad4b05654d0b93
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/parameter_manager/module.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/parameter_manager/module.pyindex 90e51b4..6a979e9 100644--- a/packages/mcp-server-revit/src/revit_mcp_server/modules/parameter_manager/module.py+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/parameter_manager/module.py@@ -106,9 +106,33 @@ def _make_action_plan(tool_name: str, args: Dict[str, Any], preview: Dict[str, A"arguments": args,"preview": preview,"requires_approval": True,+ "actions": _actions_from_planned(preview.get("planned", [])),}+def _actions_from_planned(planned: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ """Flatten a planned-updates list into `plan_actions`-ready tool calls.++ One `revit_set_parameter_value` action per (element, parameter) pair, so the+ caller can pass this straight to `plan_actions` — that path already captures+ before-state and supports rollback for this tool, generalizing to any batch+ size with no additional code.+ """+ actions: List[Dict[str, Any]] = []+ for entry in planned:+ element_id = entry.get("element_id")+ for pname, change in entry.get("updates", {}).items():+ actions.append({+ "tool": "revit_set_parameter_value",+ "arguments": {+ "element_id": element_id,+ "parameter_name": pname,+ "value": change.get("after"),+ },+ })+ return actions++class ParameterManagerModule:def filter_params(@@ -352,7 +376,7 @@ class ParameterManagerModule:blocked.append({"uid": uid, "param": pname, "reason": reason})if el_updates:- planned.append({"uid": uid, "updates": el_updates})+ planned.append({"uid": uid, "element_id": el.get("element_id"), "updates": el_updates})preview = {"csv_filename": csv_filename,diff --git a/packages/mcp-server-revit/src/revit_mcp_server/providers/approval_provider.py b/packages/mcp-server-revit/src/revit_mcp_server/providers/approval_provider.pyindex f9f9191..3732bb1 100644--- a/packages/mcp-server-revit/src/revit_mcp_server/providers/approval_provider.py+++ b/packages/mcp-server-revit/src/revit_mcp_server/providers/approval_provider.py@@ -74,11 +74,54 @@ class ApprovalProvider(AECProvider):raise ValueError(f"Provider not found for tool {t_name}")return await prov.execute_tool(t_name, t_args)- return self.gate.rollback_plan(plan_id, execute_helper)+ return await self.gate.rollback_plan(plan_id, execute_helper)++ elif name == "execute_plan":+ return await self._execute_plan(arguments.get("plan_id"))else:raise ValueError(f"Unknown approval tool '{name}'")+ async def _execute_plan(self, plan_id: str) -> Dict[str, Any]:+ """Run every action in an approved plan, report-and-continue on failure.++ A partially-failed plan is left in state 'approved' (not 'executed') so it is+ never mistaken for fully applied and never silently retried by rollback; failed+ and succeeded actions are both recorded so nothing is dropped from the audit trail.+ """+ plan = self.gate.load_plan(plan_id)+ if not plan:+ raise ValueError(f"Plan {plan_id} not found")+ if plan.get("state") != "approved":+ raise ValueError(+ f"Plan {plan_id} is in state '{plan.get('state')}', not 'approved'. Execution blocked."+ )++ results = []+ had_failure = False+ for action in plan["actions"]:+ tool = action["tool"]+ args = dict(action["arguments"])+ args["plan_id"] = plan_id+ provider = self.registry.lookup_tool_provider(tool)+ if not provider:+ action["state"] = "failed"+ had_failure = True+ results.append({"action_id": action["action_id"], "tool": tool, "error": f"Provider not found for tool {tool}"})+ continue+ try:+ result = await provider.execute_tool(tool, args)+ action["state"] = "executed"+ results.append({"action_id": action["action_id"], "tool": tool, "result": result})+ except Exception as e:+ action["state"] = "failed"+ had_failure = True+ results.append({"action_id": action["action_id"], "tool": tool, "error": str(e)})++ plan["state"] = "approved" if had_failure else "executed"+ self.gate.save_plan(plan)+ return {"plan_id": plan_id, "state": plan["state"], "results": results}+_capabilities = [ProviderTool(name="plan_actions",@@ -138,5 +181,18 @@ class ApprovalProvider(AECProvider):},"required": ["plan_id"]}+ ),+ ProviderTool(+ name="execute_plan",+ description="Run every action in an approved ActionPlan. Report-and-continue: a partial "+ "failure leaves the plan in state 'approved' with per-action results recorded, "+ "rather than silently skipping the rest or marking the plan fully executed.",+ inputSchema={+ "type": "object",+ "properties": {+ "plan_id": {"type": "string"}+ },+ "required": ["plan_id"]+ })]diff --git a/packages/mcp-server-revit/src/revit_mcp_server/security/approval.py b/packages/mcp-server-revit/src/revit_mcp_server/security/approval.pyindex 7407d0b..5c9cdfe 100644--- a/packages/mcp-server-revit/src/revit_mcp_server/security/approval.py+++ b/packages/mcp-server-revit/src/revit_mcp_server/security/approval.py@@ -111,7 +111,13 @@ class ApprovalGate:if plan.get("state") != "approved":raise BridgeError(f"Plan '{plan_id}' is in state '{plan.get('state')}', not 'approved'. Execution blocked.")- def rollback_plan(self, plan_id: str, execute_fn) -> Dict[str, Any]:+ async def rollback_plan(self, plan_id: str, execute_fn) -> Dict[str, Any]:+ """Roll back an executed plan.++ `execute_fn` is an async callable `(tool_name, arguments) -> dict`; it MUST be+ awaited here rather than merely invoked, otherwise the inverse tool call never+ actually runs (a bare call just constructs and discards a coroutine object).+ """plan = self.load_plan(plan_id)if not plan:raise ValueError(f"Plan {plan_id} not found")@@ -132,7 +138,7 @@ class ApprovalGate:# We temporarily set the plan state to 'approved' for the rollback callsplan["state"] = "approved"self.save_plan(plan)- execute_fn("revit_set_parameter_value", {+ await execute_fn("revit_set_parameter_value", {"element_id": elem_id,"parameter_name": param_name,"value": old_val,diff --git a/packages/mcp-server-revit/tests/test_approval_gate.py b/packages/mcp-server-revit/tests/test_approval_gate.pyindex 2895a6b..8e14f03 100644--- a/packages/mcp-server-revit/tests/test_approval_gate.py+++ b/packages/mcp-server-revit/tests/test_approval_gate.py@@ -4,15 +4,17 @@ from revit_mcp_server.config import Config, BridgeModefrom revit_mcp_server.security.approval import ApprovalGatefrom revit_mcp_server.errors import BridgeError-def test_approval_gate_lifecycle(tmp_path):++async def test_approval_gate_lifecycle(tmp_path):# 1. Setup ApprovalGate in required modegate = ApprovalGate(workspace_dir=tmp_path, approval_mode="required")-+# 2. Assert mutating tool without plan is rejectedwith pytest.raises(BridgeError) as exc_info:gate.check_tool_execution("revit_create_wall", {})assert "requires a valid 'plan_id' parameter" in str(exc_info.value)-+# 3. Create planactions = [{@@ -29,37 +31,77 @@ def test_approval_gate_lifecycle(tmp_path):plan_id = plan["plan_id"]assert plan["state"] == "pending"assert len(plan["actions"]) == 1-+# 4. Assert execution is blocked when plan is pendingwith pytest.raises(BridgeError) as exc_info:gate.check_tool_execution("revit_set_parameter_value", { "plan_id": plan_id })assert "is in state 'pending', not 'approved'" in str(exc_info.value)-+# 5. Approve plangate.update_plan_state(plan_id, "approved")-+# 6. Assert check passes when plan is approvedgate.check_tool_execution("revit_set_parameter_value", { "plan_id": plan_id })-+# 7. Execute rollback- # Mock execution function+ # Mock execution function — must be async: production passes an async+ # `execute_helper` (see providers/approval_provider.py), and rollback_plan+ # awaits it. A sync mock here would mask the exact bug this test guards+ # against (a bare, un-awaited call to an async execute_fn is a silent no-op).executed_calls = []- def mock_execute(tool_name, arguments):+ async def mock_execute(tool_name, arguments):executed_calls.append((tool_name, arguments))return { "status": "success" }# Transition state to executed firstgate.update_plan_state(plan_id, "executed")-+# Execute rollback- gate.rollback_plan(plan_id, mock_execute)-+ await gate.rollback_plan(plan_id, mock_execute)+# Verify rollback inverse callassert len(executed_calls) == 1assert executed_calls[0][0] == "revit_set_parameter_value"assert executed_calls[0][1]["value"] == "30"assert executed_calls[0][1]["element_id"] == 123-+# Verify state transitioned to rolled_backupdated_plan = gate.load_plan(plan_id)assert updated_plan["state"] == "rolled_back"+++async def test_rollback_generalizes_to_a_batch_of_actions(tmp_path):+ """A plan with N revit_set_parameter_value actions (one per element) rolls+ every one of them back — no per-tool special-casing needed for batches,+ since a "batch" is just multiple actions of an already-supported tool."""+ gate = ApprovalGate(workspace_dir=tmp_path, approval_mode="required")++ actions = [+ {"tool": "revit_set_parameter_value", "arguments": {"element_id": 1, "parameter_name": "FireRating", "value": "60"}},+ {"tool": "revit_set_parameter_value", "arguments": {"element_id": 2, "parameter_name": "FireRating", "value": "60"}},+ {"tool": "revit_set_parameter_value", "arguments": {"element_id": 3, "parameter_name": "FireRating", "value": "60"}},+ ]+ before_states = [+ {"1": {"FireRating": "30"}},+ {"2": {"FireRating": "45"}},+ {"3": {"FireRating": None}},+ ]+ plan = gate.create_plan(actions, before_states)+ plan_id = plan["plan_id"]+ gate.update_plan_state(plan_id, "approved")+ gate.update_plan_state(plan_id, "executed")++ calls = []+ async def mock_execute(tool_name, arguments):+ calls.append(arguments)+ return {"status": "success"}++ await gate.rollback_plan(plan_id, mock_execute)++ # Element 3's before-value was None (never had the param set) — skipped, not errored.+ assert len(calls) == 2+ assert {c["element_id"] for c in calls} == {1, 2}+ assert next(c["value"] for c in calls if c["element_id"] == 1) == "30"+ assert next(c["value"] for c in calls if c["element_id"] == 2) == "45"+ assert gate.load_plan(plan_id)["state"] == "rolled_back"diff --git a/packages/mcp-server-revit/tests/test_approval_provider.py b/packages/mcp-server-revit/tests/test_approval_provider.pynew file mode 100644index 0000000..a7285c5--- /dev/null+++ b/packages/mcp-server-revit/tests/test_approval_provider.py@@ -0,0 +1,150 @@+"""Integration tests for ApprovalProvider: plan_actions -> approve -> execute_plan ->+rollback_plan, wired through a real ProviderRegistry against a fake in-memory parameter+store. These exercise the full round trip that providers/approval_provider.py promises,+not just the ApprovalGate state machine in isolation (see test_approval_gate.py).+"""+from __future__ import annotations++from typing import Any, Dict, List++import pytest++from revit_mcp_server.providers.approval_provider import ApprovalProvider+from revit_mcp_server.providers.base import AECProvider, ProviderTool+from revit_mcp_server.providers.registry import ProviderRegistry+from revit_mcp_server.security.workspace import WorkspaceMonitor+++class FakeParamStore(AECProvider):+ """Minimal stand-in for RevitProvider's parameter tools, backed by a plain dict."""++ def __init__(self, values: Dict[int, Dict[str, Any]]):+ self.values = values+ self.fail_on = set() # set of element_id to force execute_tool failures for++ def get_identity(self) -> str:+ return "fake_revit"++ def get_capabilities(self) -> List[ProviderTool]:+ return [+ ProviderTool(+ name="revit_get_parameter_value",+ description="test",+ inputSchema={"type": "object", "properties": {}},+ ),+ ProviderTool(+ name="revit_set_parameter_value",+ description="test",+ inputSchema={"type": "object", "properties": {}},+ is_mutating=True,+ ),+ ]++ async def check_health(self) -> Dict[str, Any]:+ return {"status": "healthy"}++ async def shutdown(self) -> None:+ pass++ async def execute_tool(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:+ elem_id = arguments.get("element_id")+ param_name = arguments.get("parameter_name")+ if name == "revit_get_parameter_value":+ return {"value": self.values.get(elem_id, {}).get(param_name)}+ if name == "revit_set_parameter_value":+ if elem_id in self.fail_on:+ raise RuntimeError(f"simulated failure writing element {elem_id}")+ self.values.setdefault(elem_id, {})[param_name] = arguments.get("value")+ return {"status": "success"}+ raise ValueError(f"unknown tool {name}")+++def registry_and_provider(tmp_path):+ registry = ProviderRegistry()+ workspace = WorkspaceMonitor([tmp_path])+ approval = ApprovalProvider(workspace=workspace, registry=registry, approval_mode="required")+ registry.register(approval)+ store = FakeParamStore({1: {"FireRating": "30"}, 2: {"FireRating": "45"}})+ registry.register(store)+ return registry, approval, store+++async def test_plan_actions_captures_before_state_from_live_provider(registry_and_provider):+ registry, approval, store = registry_and_provider+ plan = await approval.execute_tool("plan_actions", {+ "actions": [+ {"tool": "revit_set_parameter_value", "arguments": {"element_id": 1, "parameter_name": "FireRating", "value": "60"}},+ ]+ })+ assert plan["state"] == "pending"+ assert plan["actions"][0]["diff"]["before"] == {"1": {"FireRating": "30"}}+++async def test_execute_plan_applies_all_actions_and_marks_executed(registry_and_provider):+ registry, approval, store = registry_and_provider+ plan = await approval.execute_tool("plan_actions", {+ "actions": [+ {"tool": "revit_set_parameter_value", "arguments": {"element_id": 1, "parameter_name": "FireRating", "value": "60"}},+ {"tool": "revit_set_parameter_value", "arguments": {"element_id": 2, "parameter_name": "FireRating", "value": "60"}},+ ]+ })+ plan_id = plan["plan_id"]+ await approval.execute_tool("approve_plan", {"plan_id": plan_id})++ result = await approval.execute_tool("execute_plan", {"plan_id": plan_id})+ assert result["state"] == "executed"+ assert store.values[1]["FireRating"] == "60"+ assert store.values[2]["FireRating"] == "60"+++async def test_execute_plan_rejects_unapproved(registry_and_provider):+ registry, approval, store = registry_and_provider+ plan = await approval.execute_tool("plan_actions", {+ "actions": [{"tool": "revit_set_parameter_value", "arguments": {"element_id": 1, "parameter_name": "FireRating", "value": "60"}}]+ })+ with pytest.raises(ValueError, match="not 'approved'"):+ await approval.execute_tool("execute_plan", {"plan_id": plan["plan_id"]})+++async def test_execute_plan_partial_failure_reports_and_continues(registry_and_provider):+ """One action failing must not silently swallow the rest, and must not mark+ the plan fully 'executed' — both successes and failures are recorded."""+ registry, approval, store = registry_and_provider+ store.fail_on.add(2)++ plan = await approval.execute_tool("plan_actions", {+ "actions": [+ {"tool": "revit_set_parameter_value", "arguments": {"element_id": 1, "parameter_name": "FireRating", "value": "60"}},+ {"tool": "revit_set_parameter_value", "arguments": {"element_id": 2, "parameter_name": "FireRating", "value": "60"}},+ ]+ })+ plan_id = plan["plan_id"]+ await approval.execute_tool("approve_plan", {"plan_id": plan_id})+ result = await approval.execute_tool("execute_plan", {"plan_id": plan_id})++ assert result["state"] == "approved" # not fully executed+ assert store.values[1]["FireRating"] == "60" # succeeded action applied+ assert store.values[2]["FireRating"] == "45" # failed action left untouched+ errors = [r for r in result["results"] if "error" in r]+ assert len(errors) == 1+++async def test_full_roundtrip_plan_approve_execute_rollback(registry_and_provider):+ registry, approval, store = registry_and_provider+ plan = await approval.execute_tool("plan_actions", {+ "actions": [{"tool": "revit_set_parameter_value", "arguments": {"element_id": 1, "parameter_name": "FireRating", "value": "60"}}]+ })+ plan_id = plan["plan_id"]+ await approval.execute_tool("approve_plan", {"plan_id": plan_id})+ await approval.execute_tool("execute_plan", {"plan_id": plan_id})+ assert store.values[1]["FireRating"] == "60"++ rolled_back = await approval.execute_tool("rollback_plan", {"plan_id": plan_id})+ assert rolled_back["state"] == "rolled_back"+ assert store.values[1]["FireRating"] == "30"diff --git a/packages/mcp-server-revit/tests/test_parameter_manager.py b/packages/mcp-server-revit/tests/test_parameter_manager.pyindex cb59d77..c95d656 100644--- a/packages/mcp-server-revit/tests/test_parameter_manager.py+++ b/packages/mcp-server-revit/tests/test_parameter_manager.py@@ -104,6 +104,33 @@ def test_plan_set_params_valid(pm, workspace):assert planned[0]["updates"]["Mark"]["before"] == "D-101"+def test_plan_set_params_emits_plan_actions_ready_actions(pm, workspace):+ """result['actions'] must be directly consumable by the approval gate's+ plan_actions tool — this is the bridge that lets a batch parameter change+ actually get applied, not just previewed (see providers/approval_provider.py)."""+ result = pm.plan_set_params(+ element_filter={"category": "OST_Doors"},+ param_updates={"Mark": "D-201"},+ workspace=workspace,+ )+ actions = result["actions"]+ assert len(actions) == 1+ assert actions[0] == {+ "tool": "revit_set_parameter_value",+ "arguments": {"element_id": actions[0]["arguments"]["element_id"], "parameter_name": "Mark", "value": "D-201"},+ }+ assert actions[0]["arguments"]["element_id"] is not None+++def test_plan_set_params_blocked_updates_produce_no_actions(pm, workspace):+ result = pm.plan_set_params(+ element_filter={"category": "OST_Levels"},+ param_updates={"Elevation": 10.0},+ workspace=workspace,+ )+ assert result["actions"] == []++def test_plan_set_params_blocks_readonly(pm, workspace):result = pm.plan_set_params(element_filter={"category": "OST_Levels"},