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
Proof bundles and plan_revert for executed parameter plans (#62)
A. Sam Mohammad1cfde2dcab0f
diff --git a/docs/proof-and-revert.md b/docs/proof-and-revert.mdnew file mode 100644index 0000000..e76ea70--- /dev/null+++ b/docs/proof-and-revert.md@@ -0,0 +1,43 @@+# Proof bundles and revert plans++Every plan that finishes executing leaves a proof file, and an executed parameter fix can be undone through the same approval gate.++## Proof bundle++When `execute_plan` finishes (or a mutating tool marks a plan executed), the server writes `proofs/<plan_id>.json` in the workspace. Read it with the read-only tool `get_proof_bundle(plan_id)`.++| Field | Meaning |+| --- | --- |+| `plan_id`, `tool`, `tools` | The plan and the tool(s) it called. |+| `created_at`, `approved_at`, `executed_at` | Lifecycle timestamps (UTC). |+| `approved_by` | Name passed as `approver` to `approve_plan`. Self-reported and not authenticated; `null` if none was given. |+| `document` | `snapshot_id`, `doc_guid`, `doc_title` of the snapshot the plan was drafted from. `null` if the plan has no `snapshot_id`. |+| `plan_hash` | SHA-256 of the plan content (actions, arguments, before values, skipped list). |+| `elements` | Applied changes: `element_id`, `uid` (when a snapshot is known), `parameter`, `before`, `before_storage_type` (Revit storage type reported when `before` was captured; `null` if unknown), `new`. |+| `skipped` | Elements left out, each with a `reason` (blocked at planning time, or failed at execution). Entries from `parameter_manager_plan_set_params` carry `uid`, `element_id` and `param`. |+| `outcome` | `success`, `partial` or `failed`. Only `success` means every action ran. |++To get the document identity and the skipped list, pass `snapshot_id` (and `skipped`, which `parameter_manager_plan_set_params` returns as its blocked list) to `plan_actions`.++## Reverting++`plan_revert(plan_id)` reads the proof bundle and drafts a new pending plan that sets each parameter back to its recorded `before` value. It never executes anything: the draft still needs `approve_plan` and `execute_plan`, and its own execution gets its own proof (`reverts_plan_id` links them).++It refuses, with a message, when:++- the plan has no proof bundle, or its outcome is not `success` (partial and failed runs are not reverted);+- the plan state is not `executed`;+- an element has no recorded `before` value (an empty value counts as not recorded);+- the current model value differs from the value the plan wrote. With `allow_conflicts=true` the draft is created anyway and lists those elements under `conflicts` for explicit review.++Values are compared and drafted by type. The live read returns every value as text, so the staleness check compares numerically when both sides are numbers (`"60"` equals `60`, `"61"` does not) and as text otherwise. The drafted `value` is rebuilt from `before_storage_type`: integer for Integer and ElementId, float for Double, text for String. When the storage type was not recorded (proofs written before this field existed), a numeric-looking `before` becomes a number only if the value the plan wrote was numeric; the draft's `notes` list each such guess.++Like `plan_actions`, drafting a revert is not itself gated; changing the model is.++## Limitations++- UNVERIFIED: write-back to Revit. The tests use an in-memory fake parameter store. The `outcome` reflects what the provider reported; the server does not re-read values after writing. Confirm against a live Revit session before relying on it.+- UNVERIFIED: revert's staleness check and the `before` capture read values through `revit_get_parameter_value`, so their correctness in a real model (units, type vs instance parameters, worksharing ownership) depends on that live tool.+- When a mutating tool is called directly with a `plan_id` (not through `execute_plan`), no per-action results exist. The proof is still written, but its outcome is never `success`, so such plans cannot be reverted. Direct calls that raise before the plan is marked executed leave no proof.+- Only `revit_set_parameter_value` actions are recorded per element and reverted. Other actions in the same plan appear under `other_actions` and are not reverted.+- `approved_by` is whatever the approving client passed; it is not an authenticated identity.diff --git a/docs/tools-generated.md b/docs/tools-generated.mdindex 8915127..80eb70d 100644--- a/docs/tools-generated.md+++ b/docs/tools-generated.md@@ -22,8 +22,10 @@ This catalog lists all tools exposed by the AEC Model Bridge providers.| --- | --- | --- | --- || `approve_plan` | Approve a pending ActionPlan so that its actions may be executed. | No | sync || `execute_plan` | Run every action in an approved ActionPlan. | No | sync |+| `get_proof_bundle` | Return the proof bundle (plan hash, approver, document, per-element before and new values, skipped elements and execution outcome) of a finished ActionPlan. | No | sync || `list_pending_plans` | List all ActionPlans that are waiting for review. | No | sync || `plan_actions` | Create a draft ActionPlan describing the model changes you want to make, capturing the before-state of each. | No | sync |+| `plan_revert` | Draft a new ActionPlan that sets each parameter back to the before value recorded in an executed plan's proof bundle. | No | sync || `reject_plan` | Reject and archive a pending ActionPlan so that it can never be executed. | No | sync || `rollback_plan` | Undo an already executed ActionPlan by applying the inverse of each recorded change, in reverse order. | No | sync |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 bb91892..7d8a842 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@@ -122,6 +122,10 @@ def _make_action_plan(tool_name: str, args: Dict[str, Any], preview: Dict[str, A"preview": preview,"requires_approval": True,"actions": _actions_from_planned(preview.get("planned", [])),+ # Hand these to plan_actions (snapshot_id, skipped) so the proof bundle names the+ # source document and lists what was left out and why.+ "skipped": preview.get("blocked", []),+ "snapshot_id": args.get("snapshot_id", ""),}@@ -264,7 +268,12 @@ class ParameterManagerModule:"storage": pinfo.get("storage"),}else:- el_blocked.append({"param": pname, "reason": reason})+ el_blocked.append({+ "uid": el.get("uid"),+ "element_id": el.get("element_id"),+ "param": pname,+ "reason": reason,+ })if el_updates:planned.append({@@ -288,7 +297,7 @@ class ParameterManagerModule:return _make_action_plan("plan_set_params",- {"element_filter": element_filter, "param_updates": param_updates},+ {"element_filter": element_filter, "param_updates": param_updates, "snapshot_id": snapshot_id},{**preview, "planned": planned},)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 94033fb..0a7ca65 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@@ -1,5 +1,7 @@import logging-from typing import Any, Dict, List+import math+from datetime import datetime, timezone+from typing import Any, Dict, List, Optional, Tuplefrom ..security.workspace import WorkspaceMonitorfrom ..security.approval import ApprovalGatefrom .base import AECProvider, ProviderTool@@ -7,6 +9,76 @@ from ..config import configlogger = logging.getLogger(__name__)+_TRUE = {"true", "yes"}+_FALSE = {"false", "no"}+++def _as_number(v: Any) -> Optional[float]:+ """Return a float for numbers, bools (1/0), numeric strings and yes/no strings; else None."""+ if isinstance(v, bool):+ return 1.0 if v else 0.0+ if isinstance(v, (int, float)):+ return float(v)+ if isinstance(v, str):+ t = v.strip()+ if t.lower() in _TRUE:+ return 1.0+ if t.lower() in _FALSE:+ return 0.0+ try:+ f = float(t)+ except ValueError:+ return None+ return f if math.isfinite(f) else None+ return None+++def _values_equal(current: Any, expected: Any) -> bool:+ """Compare a live parameter value (a string) with a recorded one (any JSON type)."""+ if current is None or expected is None:+ return current is None and expected is None+ a, b = _as_number(current), _as_number(expected)+ if a is not None and b is not None:+ return math.isclose(a, b, rel_tol=1e-9, abs_tol=1e-9)+ return str(current).strip() == str(expected).strip()+++def _typed_revert_value(before: Any, storage_type: Any, new: Any) -> Tuple[Any, Optional[str]]:+ """Rebuild the JSON value for a revert from the recorded before value.++ The live read returns every value as text, but the add-in's set command needs a JSON+ number for Integer/Double/ElementId parameters. Returns (value, note); note is set when+ the type had to be guessed or the value could not be converted.+ """+ if not isinstance(before, str):+ return before, None # already a typed JSON value+ st = storage_type.lower() if isinstance(storage_type, str) else None+ text = before.strip()+ if st == "string":+ return before, None+ if st in ("integer", "elementid"):+ f = _as_number(text)+ if f is not None and f == int(f):+ return int(f), None+ return before, f"before value {before!r} is not an integer for {storage_type} storage; drafted as text"+ if st == "double":+ f = _as_number(text)+ if f is not None:+ return f, None+ return before, f"before value {before!r} is not a number for Double storage; drafted as text"+ if st == "boolean":+ f = _as_number(text)+ if f is not None:+ return bool(f), None+ # Unknown storage type (older proof, or a reader that does not report it): only turn+ # numeric text into a number when the value the plan wrote was numeric.+ if isinstance(new, (int, float)) and not isinstance(new, bool):+ f = _as_number(text)+ if f is not None:+ value = int(f) if f == int(f) and isinstance(new, int) else f+ return value, "storage type not recorded; before value converted to a number because the plan wrote a number"+ return before, "storage type not recorded; before value kept as text"+class ApprovalProvider(AECProvider):def __init__(self, workspace: WorkspaceMonitor, registry: Any, approval_mode: str = config.approval_mode) -> None:self.workspace = workspace@@ -31,10 +103,12 @@ class ApprovalProvider(AECProvider):if name == "plan_actions":actions = arguments.get("actions", [])before_states = []+ before_types: List[Optional[str]] = []for action in actions:tool = action.get("tool")args = action.get("arguments", {})before_val = {}+ storage_type = Noneif tool == "revit_set_parameter_value":elem_id = args.get("element_id")param_name = args.get("parameter_name")@@ -48,11 +122,20 @@ class ApprovalProvider(AECProvider):})val = res.get("value")before_val = {str(elem_id): {param_name: val}}+ st = res.get("storage_type")+ storage_type = st if isinstance(st, str) else Noneexcept Exception as e:logger.warning("Failed to get before-state for plan: %s", e)before_states.append(before_val)+ before_types.append(storage_type)- plan = self.gate.create_plan(actions, before_states)+ plan = self.gate.create_plan(+ actions,+ before_states,+ snapshot_id=arguments.get("snapshot_id") or None,+ skipped=arguments.get("skipped") or None,+ before_storage_types=before_types,+ )return planelif name == "list_pending_plans":@@ -60,7 +143,7 @@ class ApprovalProvider(AECProvider):elif name == "approve_plan":plan_id = arguments.get("plan_id")- return self.gate.update_plan_state(plan_id, "approved")+ return self.gate.update_plan_state(plan_id, "approved", approver=arguments.get("approver"))elif name == "reject_plan":plan_id = arguments.get("plan_id")@@ -79,6 +162,16 @@ class ApprovalProvider(AECProvider):elif name == "execute_plan":return await self._execute_plan(arguments.get("plan_id"))+ elif name == "get_proof_bundle":+ plan_id = arguments.get("plan_id")+ bundle = self.gate.load_proof(plan_id)+ if bundle is None:+ raise ValueError(f"No proof bundle for plan {plan_id}: the plan has not finished executing.")+ return bundle++ elif name == "plan_revert":+ return await self._plan_revert(arguments.get("plan_id"), bool(arguments.get("allow_conflicts", False)))+else:raise ValueError(f"Unknown approval tool '{name}'")@@ -118,10 +211,101 @@ class ApprovalProvider(AECProvider):had_failure = Trueresults.append({"action_id": action["action_id"], "tool": tool, "error": str(e)})+ n_failed = sum(1 for r in results if "error" in r)plan["state"] = "partial" if had_failure else "executed"+ plan["executed_at"] = datetime.now(timezone.utc).isoformat()self.gate.save_plan(plan)+ # Proof outcome: "failed" when nothing was applied; "success" only if every action ran.+ if not had_failure:+ outcome = "success"+ elif n_failed == len(results):+ outcome = "failed"+ else:+ outcome = "partial"+ try:+ self.gate.record_proof(plan, results=results, outcome=outcome)+ except Exception:+ logger.exception("Failed to write proof bundle for plan %s", plan_id)return {"plan_id": plan_id, "state": plan["state"], "results": results}+ async def _plan_revert(self, plan_id: str, allow_conflicts: bool) -> Dict[str, Any]:+ """Draft (never execute) a plan that restores the recorded before values.++ Refuses unless the original plan fully executed, every reverted element has a+ recorded before value, and the model still holds the value the plan wrote.+ Elements whose current value differs are conflicts: refused unless+ allow_conflicts=True, in which case they are listed on the plan for review.+ """+ bundle = self.gate.load_proof(plan_id)+ if bundle is None:+ raise ValueError(f"Cannot revert plan {plan_id}: no proof bundle (plan has not been executed).")+ if bundle.get("outcome") != "success":+ raise ValueError(+ f"Cannot revert plan {plan_id}: its execution outcome is '{bundle.get('outcome')}', "+ "not a fully executed 'success'."+ )+ plan = self.gate.load_plan(plan_id)+ if not plan or plan.get("state") != "executed":+ raise ValueError(+ f"Cannot revert plan {plan_id}: plan state is '{plan.get('state') if plan else 'missing'}', not 'executed'."+ )+ elements = bundle.get("elements", [])+ if not elements:+ raise ValueError(f"Cannot revert plan {plan_id}: the proof bundle records no parameter changes.")+ missing = [e for e in elements if not e.get("before_recorded")]+ if missing:+ ids = ", ".join(f"{e.get('element_id')}/{e.get('parameter')}" for e in missing)+ raise ValueError(f"Cannot revert plan {plan_id}: no before value was recorded for: {ids}.")++ read_tool = "revit_get_parameter_value"+ provider = self.registry.lookup_tool_provider(read_tool)+ if not provider:+ raise ValueError(f"Cannot revert plan {plan_id}: cannot verify current values ({read_tool} unavailable).")++ actions, before_states, conflicts, notes = [], [], [], []+ for e in elements:+ eid, pname = e["element_id"], e["parameter"]+ try:+ res = await provider.execute_tool(read_tool, {"element_id": eid, "parameter_name": pname})+ except Exception as exc:+ raise ValueError(f"Cannot revert plan {plan_id}: failed to read current value of {eid}/{pname}: {exc}")+ current = res.get("value")+ if not _values_equal(current, e.get("new")):+ conflicts.append({"element_id": eid, "parameter": pname,+ "expected_current": e.get("new"), "actual_current": current,+ "revert_to": e.get("before")})+ if not allow_conflicts:+ continue+ value, note = _typed_revert_value(e.get("before"), e.get("before_storage_type"), e.get("new"))+ if note:+ notes.append(f"{eid}/{pname}: {note}")+ actions.append({"tool": "revit_set_parameter_value",+ "arguments": {"element_id": eid, "parameter_name": pname, "value": value}})+ before_states.append({str(eid): {pname: current}})++ if conflicts and not allow_conflicts:+ detail = "; ".join(+ f"{c['element_id']}/{c['parameter']}: expected {c['expected_current']!r}, now {c['actual_current']!r}"+ for c in conflicts+ )+ raise ValueError(+ f"Cannot revert plan {plan_id}: the model changed since it ran ({detail}). "+ "Re-run with allow_conflicts=true to draft a plan that lists these elements for explicit review."+ )++ extra: Dict[str, Any] = {"reverts_plan_id": plan_id}+ if conflicts:+ extra["conflicts"] = conflicts+ if notes:+ extra["notes"] = notes+ unreverted = [a for a in bundle.get("other_actions", []) if a.get("status") == "executed"]+ if unreverted:+ extra["warnings"] = [+ f"Action {a.get('action_id')} ({a.get('tool')}) is not a parameter change and is not reverted."+ for a in unreverted+ ]+ return self.gate.create_plan(actions, before_states, snapshot_id=plan.get("snapshot_id"), extra=extra)+_capabilities = [ProviderTool(name="plan_actions",@@ -129,6 +313,8 @@ class ApprovalProvider(AECProvider):inputSchema={"type": "object","properties": {+ "snapshot_id": {"type": "string"},+ "skipped": {"type": "array", "items": {"type": "object"}},"actions": {"type": "array","items": {@@ -155,7 +341,8 @@ class ApprovalProvider(AECProvider):inputSchema={"type": "object","properties": {- "plan_id": {"type": "string"}+ "plan_id": {"type": "string"},+ "approver": {"type": "string"}},"required": ["plan_id"]}@@ -194,5 +381,27 @@ class ApprovalProvider(AECProvider):},"required": ["plan_id"]}+ ),+ ProviderTool(+ name="get_proof_bundle",+ description="Return the proof bundle of a finished ActionPlan (success, partial or failed). Read-only.",+ inputSchema={+ "type": "object",+ "properties": {"plan_id": {"type": "string"}},+ "required": ["plan_id"]+ }+ ),+ ProviderTool(+ name="plan_revert",+ description="Draft a new ActionPlan restoring the before values recorded in an executed plan's "+ "proof bundle. Never executes; the draft still needs human approval.",+ inputSchema={+ "type": "object",+ "properties": {+ "plan_id": {"type": "string"},+ "allow_conflicts": {"type": "boolean"}+ },+ "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 ea2bab3..18c4856 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@@ -6,6 +6,7 @@ from pathlib import Pathfrom typing import Dict, Any, List, Optionalfrom ..config import configfrom ..errors import BridgeError+from . import proof as proof_modlogger = logging.getLogger(__name__)@@ -39,7 +40,15 @@ class ApprovalGate:except Exception as e:logger.error("Failed to save plan %s: %s", plan_id, e)- def create_plan(self, actions: List[Dict[str, Any]], before_states: List[Dict[str, Any]]) -> Dict[str, Any]:+ def create_plan(+ self,+ actions: List[Dict[str, Any]],+ before_states: List[Dict[str, Any]],+ snapshot_id: Optional[str] = None,+ skipped: Optional[List[Dict[str, Any]]] = None,+ extra: Optional[Dict[str, Any]] = None,+ before_storage_types: Optional[List[Optional[str]]] = None,+ ) -> Dict[str, Any]:plan_id = f"plan_{uuid.uuid4().hex[:12]}"plan_actions = []for i, action in enumerate(actions):@@ -53,6 +62,10 @@ class ApprovalGate:"after": arguments,"element_count": 1}+ if before_storage_types and i < len(before_storage_types) and before_storage_types[i]:+ # Revit StorageType of the parameter when the before value was captured, so a+ # revert can rebuild a correctly typed value (the live read returns strings).+ diff["before_storage_type"] = before_storage_types[i]plan_actions.append({"action_id": act_id,"tool": action.get("tool"),@@ -69,6 +82,12 @@ class ApprovalGate:"is_reversible": True,"reversible_strategy": "inverse"}+ if snapshot_id:+ plan["snapshot_id"] = snapshot_id+ if skipped:+ plan["skipped"] = skipped+ if extra:+ plan.update(extra)self.save_plan(plan)return plan@@ -84,14 +103,42 @@ class ApprovalGate:continuereturn plans- def update_plan_state(self, plan_id: str, state: str) -> Dict[str, Any]:+ def update_plan_state(self, plan_id: str, state: str, approver: Optional[str] = None) -> Dict[str, Any]:plan = self.load_plan(plan_id)if not plan:raise ValueError(f"Plan {plan_id} not found")plan["state"] = state+ now = datetime.now(timezone.utc).isoformat()+ if state == "approved":+ plan["approved_at"] = now+ if approver:+ plan["approved_by"] = str(approver)+ fill_proof = False+ if state == "executed":+ plan["executed_at"] = now+ # execute_plan writes a richer proof itself; only fill in for direct tool calls.+ try:+ fill_proof = proof_mod.read_proof(self.workspace_dir, plan_id) is None+ except ValueError:+ fill_proof = Falseself.save_plan(plan)+ if fill_proof:+ try:+ self.record_proof(plan)+ except Exception:+ logger.exception("Failed to write proof bundle for plan %s", plan_id)return plan+ def record_proof(self, plan: Dict[str, Any], results: Optional[List[Dict[str, Any]]] = None,+ outcome: Optional[str] = None) -> Dict[str, Any]:+ """Write proofs/<plan_id>.json for a finished (success / partial / failed) plan."""+ bundle = proof_mod.build_proof(plan, self.workspace_dir, results=results, outcome=outcome)+ proof_mod.write_proof(self.workspace_dir, bundle)+ return bundle++ def load_proof(self, plan_id: str) -> Optional[Dict[str, Any]]:+ return proof_mod.read_proof(self.workspace_dir, plan_id)+def check_tool_execution(self, tool_name: str, arguments: Dict[str, Any]) -> None:"""Interceptors check before execution.diff --git a/packages/mcp-server-revit/src/revit_mcp_server/security/proof.py b/packages/mcp-server-revit/src/revit_mcp_server/security/proof.pynew file mode 100644index 0000000..a81c854--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/security/proof.py@@ -0,0 +1,178 @@+"""Proof bundles: a verifiable per-plan record of what an executed ActionPlan did.++A bundle is written to ``<workspace>/proofs/<plan_id>.json`` when a plan finishes+executing (fully, partially or not at all). It is the single input to ``plan_revert``.++What a bundle proves, and what it does not: it records the plan content (hashed),+the before values captured when the plan was drafted, the values the plan asked to+write, and the per-action outcome *reported by the provider*. It does not re-read the+model after writing, so write-back to Revit is only as verified as the live provider+call that reported success.+"""+from __future__ import annotations++import hashlib+import json+import os+import re+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Dict, List, Optional, Tuple++SCHEMA = "amb.proof/1"+PARAM_TOOL = "revit_set_parameter_value"+_ID_RE = re.compile(r"^[A-Za-z0-9_\-]{1,128}$")+++def validate_plan_id(plan_id: Any) -> str:+ if not isinstance(plan_id, str) or not _ID_RE.match(plan_id):+ raise ValueError("Invalid plan_id.")+ return plan_id+++def proof_path(workspace_dir: Path, plan_id: str) -> Path:+ return Path(workspace_dir) / "proofs" / f"{validate_plan_id(plan_id)}.json"+++def plan_content_hash(plan: Dict[str, Any]) -> str:+ """SHA-256 over the immutable content of a plan (not its mutable state/results)."""+ content = {+ "plan_id": plan.get("plan_id"),+ "created_at": plan.get("created_at"),+ "snapshot_id": plan.get("snapshot_id"),+ "skipped": plan.get("skipped", []),+ "actions": [+ {+ "action_id": a.get("action_id"),+ "tool": a.get("tool"),+ "arguments": {k: v for k, v in (a.get("arguments") or {}).items() if k != "plan_id"},+ "before": (a.get("diff") or {}).get("before"),+ }+ for a in plan.get("actions", [])+ ],+ }+ blob = json.dumps(content, sort_keys=True, separators=(",", ":"), default=str)+ return "sha256:" + hashlib.sha256(blob.encode("utf-8")).hexdigest()+++def _load_snapshot_doc(workspace_dir: Path, snapshot_id: Optional[str]) -> Tuple[Optional[Dict[str, Any]], Dict[str, str]]:+ """Return (document identity or None, element_id -> uid map)."""+ if not snapshot_id:+ return None, {}+ doc: Dict[str, Any] = {"snapshot_id": snapshot_id, "doc_guid": None, "doc_title": None}+ uids: Dict[str, str] = {}+ try:+ if not _ID_RE.match(snapshot_id):+ raise ValueError("bad snapshot id")+ with open(Path(workspace_dir) / "snapshots" / f"{snapshot_id}.json", "r", encoding="utf-8") as f:+ snap = json.load(f)+ src = snap.get("source") or {}+ doc["doc_guid"] = src.get("doc_guid")+ doc["doc_title"] = src.get("doc_title")+ for el in snap.get("elements", []):+ if el.get("element_id") is not None and el.get("uid"):+ uids[str(el["element_id"])] = el["uid"]+ except Exception:+ doc["note"] = "snapshot file could not be read; document identity unavailable"+ return doc, uids+++def build_proof(+ plan: Dict[str, Any],+ workspace_dir: Path,+ results: Optional[List[Dict[str, Any]]] = None,+ outcome: Optional[str] = None,+) -> Dict[str, Any]:+ """Build the bundle. ``results`` is the per-action list from execute_plan; without+ it the outcome is derived from recorded action states only."""+ document, uids = _load_snapshot_doc(workspace_dir, plan.get("snapshot_id"))+ by_action = {r.get("action_id"): r for r in (results or [])}++ elements: List[Dict[str, Any]] = []+ other_actions: List[Dict[str, Any]] = []+ skipped: List[Dict[str, Any]] = list(plan.get("skipped", []))+ n_ok = n_bad = 0++ for action in plan.get("actions", []):+ res = by_action.get(action.get("action_id"))+ if res is not None:+ ok = "error" not in res+ error = res.get("error")+ else:+ ok = action.get("state") == "executed"+ error = None if ok else "no per-action result recorded"+ n_ok += ok+ n_bad += not ok+ args = action.get("arguments") or {}+ if action.get("tool") == PARAM_TOOL:+ eid = args.get("element_id")+ pname = args.get("parameter_name")+ before_map = ((action.get("diff") or {}).get("before") or {}).get(str(eid), {})+ if not isinstance(before_map, dict):+ before_map = {}+ entry = {+ "action_id": action.get("action_id"),+ "element_id": eid,+ "uid": args.get("element_uid") or uids.get(str(eid)),+ "parameter": pname,+ "before": before_map.get(pname),+ "before_recorded": before_map.get(pname) is not None,+ "before_storage_type": (action.get("diff") or {}).get("before_storage_type"),+ "new": args.get("value"),+ "status": "executed" if ok else "failed",+ }+ if ok:+ elements.append(entry)+ else:+ skipped.append({**entry, "reason": error})+ else:+ other_actions.append({+ "action_id": action.get("action_id"),+ "tool": action.get("tool"),+ "status": "executed" if ok else "failed",+ **({"error": error} if error else {}),+ })++ if outcome is None:+ outcome = "success" if n_bad == 0 and n_ok > 0 else ("failed" if n_ok == 0 else "partial")++ tools = sorted({a.get("tool") for a in plan.get("actions", []) if a.get("tool")})+ return {+ "schema": SCHEMA,+ "plan_id": plan["plan_id"],+ "tool": tools[0] if len(tools) == 1 else "mixed",+ "tools": tools,+ "created_at": plan.get("created_at"),+ "approved_at": plan.get("approved_at"),+ "executed_at": plan.get("executed_at") or datetime.now(timezone.utc).isoformat(),+ "approved_by": plan.get("approved_by"),+ "approver_note": "self-reported by the approving client; not authenticated"+ if plan.get("approved_by") else "approver identity was not recorded",+ "document": document,+ "plan_hash": plan_content_hash(plan),+ "outcome": outcome,+ "reverts_plan_id": plan.get("reverts_plan_id"),+ "elements": elements,+ "skipped": skipped,+ "other_actions": other_actions,+ "verification": "UNVERIFIED against the live model: outcome is what the provider reported; "+ "values were not re-read after writing.",+ }+++def write_proof(workspace_dir: Path, bundle: Dict[str, Any]) -> Path:+ path = proof_path(workspace_dir, bundle["plan_id"])+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp = path.with_suffix(".json.tmp")+ with open(tmp, "w", encoding="utf-8") as f:+ json.dump(bundle, f, indent=2, default=str)+ os.replace(tmp, path)+ return path+++def read_proof(workspace_dir: Path, plan_id: str) -> Optional[Dict[str, Any]]:+ path = proof_path(workspace_dir, plan_id)+ if not path.exists():+ return None+ with open(path, "r", encoding="utf-8") as f:+ return json.load(f)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 f53972b..5cc5090 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@@ -142,6 +142,8 @@ DESCRIPTIONS: dict[str, str] = {"list_pending_plans": "List all ActionPlans that are waiting for review. Read-only.","approve_plan": "Approve a pending ActionPlan so that its actions may be executed. This is the human approval step.","reject_plan": "Reject and archive a pending ActionPlan so that it can never be executed.",+ "get_proof_bundle": "Return the proof bundle (plan hash, approver, document, per-element before and new values, skipped elements and execution outcome) of a finished ActionPlan. Read-only.",+ "plan_revert": "Draft a new ActionPlan that sets each parameter back to the before value recorded in an executed plan's proof bundle. Refuses if the plan was not fully executed, a before value is missing, or the model changed since. Never executes; the draft needs approval.","rollback_plan": "Undo an already executed ActionPlan by applying the inverse of each recorded change, in reverse order. Actions without a rollback handler are reported as warnings.",# --- Modules (panel commands) -----------------------------------------"module_list_commands": "List all registered modules and the commands they expose to the dockable Revit panel. Read-only.",@@ -282,6 +284,9 @@ PARAM_DESCRIPTIONS: dict[str, str] = {"offset": "Number of items to skip (for paging).","idempotency_key": "Optional unique key; repeating a call with the same key does not repeat the write.","plan_id": "ID of an ActionPlan (from plan_actions).",+ "skipped": "Elements or parameters excluded when drafting (for example the blocked list of a parameter plan), each with a reason.",+ "approver": "Name of the person approving the plan; recorded in the proof bundle but not authenticated.",+ "allow_conflicts": "If true, draft the revert even where the model's current value differs from the value the plan wrote, listing those elements as conflicts for explicit review.","actions": "List of proposed tool calls, each with a tool name and its arguments.","parameter_name": "Name of the Revit parameter.","param_name": "Name of the parameter.",@@ -454,6 +459,7 @@ NOT_READ_ONLY: dict[str, tuple[bool, bool]] = {"approve_plan": (False, True),"reject_plan": (False, True),"rollback_plan": (True, False),+ "plan_revert": (False, False),"execute_plan": (True, False),"revit_extract_snapshot": (False, False),"snapshot_take": (False, False),diff --git a/packages/mcp-server-revit/tests/test_parameter_manager.py b/packages/mcp-server-revit/tests/test_parameter_manager.pyindex 0667818..80abedf 100644--- a/packages/mcp-server-revit/tests/test_parameter_manager.py+++ b/packages/mcp-server-revit/tests/test_parameter_manager.py@@ -141,6 +141,18 @@ def test_plan_set_params_blocks_readonly(pm, workspace):assert result["preview"]["planned_count"] == 0+def test_plan_set_params_skipped_entries_identify_element(pm, workspace):+ result = pm.plan_set_params(+ element_filter={"category": "OST_Levels"},+ param_updates={"Elevation": 10.0},+ workspace=workspace,+ )+ skipped = result["skipped"]+ assert skipped+ assert all(b.get("uid") and b.get("element_id") is not None for b in skipped)+ assert all(b["param"] == "Elevation" for b in skipped)++def test_plan_set_params_blocks_wrong_storage_type(pm, workspace):result = pm.plan_set_params(element_filter={"category": "OST_Doors"},diff --git a/packages/mcp-server-revit/tests/test_proof_and_revert.py b/packages/mcp-server-revit/tests/test_proof_and_revert.pynew file mode 100644index 0000000..761c331--- /dev/null+++ b/packages/mcp-server-revit/tests/test_proof_and_revert.py@@ -0,0 +1,299 @@+"""Proof bundles and revert plans for approved parameter fixes."""+from __future__ import annotations++import json++import pytest++from revit_mcp_server.providers.approval_provider import ApprovalProvider+from revit_mcp_server.providers.registry import ProviderRegistry+from revit_mcp_server.security.workspace import WorkspaceMonitor++from test_approval_provider import FakeParamStore+++def env(tmp_path):+ registry = ProviderRegistry()+ approval = ApprovalProvider(WorkspaceMonitor([tmp_path]), registry, approval_mode="required")+ registry.register(approval)+ store = FakeParamStore({1: {"FireRating": "30"}, 2: {"FireRating": "45"}})+ registry.register(store)+ return tmp_path, approval, store+++def _acts(*ids, value="60"):+ return [+ {"tool": "revit_set_parameter_value",+ "arguments": {"element_id": i, "parameter_name": "FireRating", "value": value}}+ for i in ids+ ]+++async def _run(approval, actions, **plan_kwargs):+ plan = await approval.execute_tool("plan_actions", {"actions": actions, **plan_kwargs})+ pid = plan["plan_id"]+ await approval.execute_tool("approve_plan", {"plan_id": pid, "approver": "[email protected]"})+ result = await approval.execute_tool("execute_plan", {"plan_id": pid})+ return pid, result+++def _proof_file(tmp_path, pid):+ return json.loads((tmp_path / "proofs" / f"{pid}.json").read_text(encoding="utf-8"))+++async def test_proof_written_on_success(env):+ tmp_path, approval, store = env+ snap_dir = tmp_path / "snapshots"+ snap_dir.mkdir()+ (snap_dir / "snap1.json").write_text(json.dumps({+ "source": {"doc_guid": "guid-1", "doc_title": "Tower.rvt"},+ "elements": [{"uid": "uid-1", "element_id": 1}],+ }), encoding="utf-8")++ pid, result = await _run(+ approval, _acts(1, 2), snapshot_id="snap1",+ skipped=[{"uid": "uid-9", "param": "FireRating", "reason": "read-only"}],+ )+ assert result["state"] == "executed"+ proof = _proof_file(tmp_path, pid)+ assert proof["outcome"] == "success"+ assert proof["plan_id"] == pid+ assert proof["tool"] == "revit_set_parameter_value"+ assert proof["approved_by"] == "[email protected]"+ assert proof["created_at"] and proof["approved_at"] and proof["executed_at"]+ assert proof["document"] == {"snapshot_id": "snap1", "doc_guid": "guid-1", "doc_title": "Tower.rvt"}+ assert proof["plan_hash"].startswith("sha256:")+ assert proof["skipped"][0]["reason"] == "read-only"+ e1 = next(e for e in proof["elements"] if e["element_id"] == 1)+ assert (e1["before"], e1["new"], e1["uid"], e1["parameter"]) == ("30", "60", "uid-1", "FireRating")++ # Hash is reproducible from the stored plan content.+ from revit_mcp_server.security.proof import plan_content_hash+ assert plan_content_hash(approval.gate.load_plan(pid)) == proof["plan_hash"]+++async def test_proof_without_approver_says_so(env):+ tmp_path, approval, _ = env+ plan = await approval.execute_tool("plan_actions", {"actions": _acts(1)})+ await approval.execute_tool("approve_plan", {"plan_id": plan["plan_id"]})+ await approval.execute_tool("execute_plan", {"plan_id": plan["plan_id"]})+ proof = _proof_file(tmp_path, plan["plan_id"])+ assert proof["approved_by"] is None+ assert "not recorded" in proof["approver_note"]+ assert proof["document"] is None+++async def test_proof_partial_never_marked_success(env):+ tmp_path, approval, store = env+ store.fail_on.add(2)+ pid, result = await _run(approval, _acts(1, 2))+ assert result["state"] == "partial"+ proof = _proof_file(tmp_path, pid)+ assert proof["outcome"] == "partial"+ assert [e["element_id"] for e in proof["elements"]] == [1]+ assert proof["skipped"][0]["element_id"] == 2+ assert "simulated failure" in proof["skipped"][0]["reason"]+++async def test_proof_failed_when_nothing_applied(env):+ tmp_path, approval, store = env+ store.fail_on.update({1, 2})+ pid, _ = await _run(approval, _acts(1, 2))+ proof = _proof_file(tmp_path, pid)+ assert proof["outcome"] == "failed"+ assert proof["elements"] == []+ assert len(proof["skipped"]) == 2+++async def test_direct_tool_path_writes_proof(env):+ tmp_path, approval, _ = env+ plan = await approval.execute_tool("plan_actions", {"actions": _acts(1)})+ pid = plan["plan_id"]+ approval.gate.update_plan_state(pid, "approved", approver="someone")+ approval.gate.update_plan_state(pid, "executed") # what mcp_server/panel do after a direct call+ proof = _proof_file(tmp_path, pid)+ assert proof["approved_by"] == "someone"+ # No per-action result was recorded on this path, so it must not claim success.+ assert proof["outcome"] != "success"+++async def test_get_proof_bundle_and_read_only(env):+ tmp_path, approval, _ = env+ pid, _ = await _run(approval, _acts(1))+ before = (tmp_path / "proofs" / f"{pid}.json").read_bytes()+ plan_before = (tmp_path / "plans" / f"{pid}.json").read_bytes()+ bundle = await approval.execute_tool("get_proof_bundle", {"plan_id": pid})+ assert bundle["plan_id"] == pid and bundle["outcome"] == "success"+ assert (tmp_path / "proofs" / f"{pid}.json").read_bytes() == before+ assert (tmp_path / "plans" / f"{pid}.json").read_bytes() == plan_before+ tool = next(t for t in approval.get_capabilities() if t.name == "get_proof_bundle")+ assert tool.is_mutating is False+ with pytest.raises(ValueError, match="No proof bundle"):+ await approval.execute_tool("get_proof_bundle", {"plan_id": "plan_nope"})+ with pytest.raises(ValueError, match="Invalid plan_id"):+ await approval.execute_tool("get_proof_bundle", {"plan_id": "../../etc/passwd"})+++async def test_plan_revert_content_and_never_auto_executes(env):+ tmp_path, approval, store = env+ pid, _ = await _run(approval, _acts(1, 2))+ revert = await approval.execute_tool("plan_revert", {"plan_id": pid})+ assert revert["state"] == "pending"+ assert revert["reverts_plan_id"] == pid+ got = {(a["arguments"]["element_id"], a["arguments"]["value"]) for a in revert["actions"]}+ assert got == {(1, "30"), (2, "45")}+ assert all(a["tool"] == "revit_set_parameter_value" for a in revert["actions"])+ assert "conflicts" not in revert+ # Not executed: model still holds the fixed values, and execution is gated.+ assert store.values[1]["FireRating"] == "60"+ with pytest.raises(ValueError, match="not 'approved'"):+ await approval.execute_tool("execute_plan", {"plan_id": revert["plan_id"]})+ # After approval + execution the originals are restored and the revert has its own proof.+ await approval.execute_tool("approve_plan", {"plan_id": revert["plan_id"]})+ await approval.execute_tool("execute_plan", {"plan_id": revert["plan_id"]})+ assert store.values[1]["FireRating"] == "30" and store.values[2]["FireRating"] == "45"+ assert _proof_file(tmp_path, revert["plan_id"])["reverts_plan_id"] == pid+++async def test_plan_revert_refused_when_not_executed(env):+ _, approval, store = env+ plan = await approval.execute_tool("plan_actions", {"actions": _acts(1)})+ with pytest.raises(ValueError, match="no proof bundle"):+ await approval.execute_tool("plan_revert", {"plan_id": plan["plan_id"]})++ store.fail_on.add(2)+ pid, _ = await _run(approval, _acts(1, 2))+ with pytest.raises(ValueError, match="'partial'"):+ await approval.execute_tool("plan_revert", {"plan_id": pid})+++async def test_plan_revert_refused_when_before_missing(env):+ _, approval, store = env+ store.values[3] = {} # parameter has no value, so no before value is captured+ pid, _ = await _run(approval, _acts(3))+ with pytest.raises(ValueError, match="no before value was recorded"):+ await approval.execute_tool("plan_revert", {"plan_id": pid})+++async def test_plan_revert_refused_when_stale_unless_conflicts_allowed(env):+ _, approval, store = env+ pid, _ = await _run(approval, _acts(1, 2))+ store.values[2]["FireRating"] = "90" # someone changed it after the fix++ with pytest.raises(ValueError, match="changed since"):+ await approval.execute_tool("plan_revert", {"plan_id": pid})++ revert = await approval.execute_tool("plan_revert", {"plan_id": pid, "allow_conflicts": True})+ assert revert["state"] == "pending"+ assert len(revert["conflicts"]) == 1+ c = revert["conflicts"][0]+ assert (c["element_id"], c["expected_current"], c["actual_current"], c["revert_to"]) == (2, "60", "90", "45")+++async def test_plan_revert_tool_metadata(env):+ _, approval, _ = env+ caps = {t.name: t for t in approval.get_capabilities()}+ # Like plan_actions, drafting is not itself gated; execution of the draft is.+ assert caps["plan_revert"].is_mutating is False+ assert "plan_revert" in caps and "get_proof_bundle" in caps+++class TypedStore(FakeParamStore):+ """Like the live add-in: values are read back as text, with the Revit storage type."""++ def __init__(self, values, types):+ super().__init__(values)+ self.types = types++ async def execute_tool(self, name, arguments):+ res = await super().execute_tool(name, arguments)+ if name == "revit_get_parameter_value":+ v = res["value"]+ res = {"value": None if v is None else str(v),+ "storage_type": self.types.get(arguments.get("parameter_name"))}+ return res+++def _typed_env(tmp_path, values, types):+ registry = ProviderRegistry()+ approval = ApprovalProvider(WorkspaceMonitor([tmp_path]), registry, approval_mode="required")+ registry.register(approval)+ store = TypedStore(values, types)+ registry.register(store)+ return approval, store+++def _set(eid, pname, value):+ return {"tool": "revit_set_parameter_value",+ "arguments": {"element_id": eid, "parameter_name": pname, "value": value}}+++async def test_revert_numeric_string_vs_number_is_not_a_conflict(tmp_path):+ approval, store = _typed_env(tmp_path, {1: {"Rating": 30}}, {"Rating": "Integer"})+ pid, _ = await _run(approval, [_set(1, "Rating", 60)])+ assert store.values[1]["Rating"] == 60 # live read returns "60", the proof holds 60+ revert = await approval.execute_tool("plan_revert", {"plan_id": pid})+ assert "conflicts" not in revert+++async def test_revert_numeric_real_conflict_still_refused(tmp_path):+ approval, store = _typed_env(tmp_path, {1: {"Rating": 30}}, {"Rating": "Integer"})+ pid, _ = await _run(approval, [_set(1, "Rating", 60)])+ store.values[1]["Rating"] = 61+ with pytest.raises(ValueError, match="changed since"):+ await approval.execute_tool("plan_revert", {"plan_id": pid})+ revert = await approval.execute_tool("plan_revert", {"plan_id": pid, "allow_conflicts": True})+ assert revert["conflicts"][0]["actual_current"] == "61"+++async def test_revert_drafts_typed_values(tmp_path):+ approval, _ = _typed_env(+ tmp_path,+ {1: {"Rating": 30, "Width": 0.5, "Mark": "A-1", "Fixed": 1, "Host": 12},+ },+ {"Rating": "Integer", "Width": "Double", "Mark": "String", "Fixed": "Integer", "Host": "ElementId"},+ )+ pid, _ = await _run(approval, [_set(1, "Rating", 60), _set(1, "Width", 1.25), _set(1, "Mark", "B-2"),+ _set(1, "Fixed", 0), _set(1, "Host", 99)])+ revert = await approval.execute_tool("plan_revert", {"plan_id": pid})+ got = {a["arguments"]["parameter_name"]: a["arguments"]["value"] for a in revert["actions"]}+ assert got == {"Rating": 30, "Width": 0.5, "Mark": "A-1", "Fixed": 1, "Host": 12}+ assert type(got["Rating"]) is int and type(got["Width"]) is float and type(got["Mark"]) is str+ assert type(got["Fixed"]) is int and type(got["Host"]) is int+ assert "notes" not in revert+ assert _proof_file(tmp_path, pid)["elements"][0]["before_storage_type"] == "Integer"+++async def test_revert_string_that_looks_numeric_stays_string(tmp_path):+ approval, _ = _typed_env(tmp_path, {1: {"Mark": "007"}}, {"Mark": "String"})+ pid, _ = await _run(approval, [_set(1, "Mark", "008")])+ revert = await approval.execute_tool("plan_revert", {"plan_id": pid})+ assert revert["actions"][0]["arguments"]["value"] == "007"+++async def test_revert_unknown_storage_type_coerces_conservatively_with_note(tmp_path):+ # No storage_type reported (older reader / older plan): numeric new value -> number, noted.+ approval, _ = _typed_env(tmp_path, {1: {"Rating": 30, "Mark": "12"}}, {})+ pid, _ = await _run(approval, [_set(1, "Rating", 60), _set(1, "Mark", "13")])+ revert = await approval.execute_tool("plan_revert", {"plan_id": pid})+ got = {a["arguments"]["parameter_name"]: a["arguments"]["value"] for a in revert["actions"]}+ assert got["Rating"] == 30 and type(got["Rating"]) is int+ assert got["Mark"] == "12" # new value was text, so stays text+ assert len(revert["notes"]) == 2 and all("storage type not recorded" in n for n in revert["notes"])