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
docs: add ADRs for approval gate, module system, snapshot schema, and panel architecture
A. Sam Mohammadef30d48a3570
diff --git a/docs/0008-approval-gate-lifecycle.md b/docs/0008-approval-gate-lifecycle.mdnew file mode 100644index 0000000..7b19f40--- /dev/null+++ b/docs/0008-approval-gate-lifecycle.md@@ -0,0 +1,74 @@+# ADR 0008: Approval Gate & ActionPlan Lifecycle++## Status+Accepted++## Context+AI agents modifying production BIM models (e.g., Revit, Navisworks) pose significant risks of silent data corruption, coordinate drift, or breaking company standards. We need a secure boundary where AI agents can propose changes (read, analyze, and plan) but can never execute modifying operations directly without explicit human review and approval.++## Decisions++### 1. ActionPlan Lifecycle+An **ActionPlan** is the unit of human approval and execution control. It transitions through the following states:++```mermaid+graph TD+ Draft[Draft] -->|plan_actions| Validated[Validated]+ Validated -->|submit| Pending[Pending Review]+ Pending -->|approve| Approved[Approved]+ Pending -->|reject| Rejected[Rejected]+ Approved -->|execute| Executed[Executed]+ Executed -->|rollback| RolledBack[Rolled Back]+```++- **Draft**: A plan containing proposed actions (tool calls and arguments) under construction.+- **Validated**: The plan has been checked against schemas, and dry-run validation checks have run (e.g., uniqueness, category support, element ownership).+- **Pending**: Submitted to the human approval queue, visible on the dockable panel.+- **Approved**: Human checked the parameter diffs and element counts, giving explicit consent.+- **Rejected**: Human rejected the plan; it is closed and archived.+- **Executed**: The changes are applied to the model inside host transactions.+- **Rolled Back**: The executed changes are reversed using Revit Undo (same session) or inverse parameters.++### 2. ActionPlan Schema+The ActionPlan represents a batch of modifications:+```json+{+ "plan_id": "plan_01J...ULID",+ "state": "pending",+ "created_at": "2026-07-08T18:07:30Z",+ "actions": [+ {+ "action_id": "act_01...",+ "tool": "revit.batch_set_parameters",+ "arguments": {+ "elements": ["revit-uniqueid-1"],+ "parameter": "FireRating",+ "value": "60"+ },+ "diff": {+ "type": "parameter_change",+ "before": {"revit-uniqueid-1": {"FireRating": null}},+ "after": {"revit-uniqueid-1": {"FireRating": "60"}},+ "element_count": 1+ }+ }+ ],+ "is_reversible": true,+ "reversible_strategy": "inverse"+}+```++### 3. The Approval Gate Middleware+- **Enforcement Location**: The unified Python MCP hub acts as the single choke point.+- **Rule**: If `approval_mode=required` (default in panel mode), any tool call containing mutating or destructive metadata (`is_mutating=True` or `destructive=True`) must supply a valid, approved `plan_id`. Unplanned mutations are immediately blocked and returned as an authorization error.+- **Auto-Approval**: For headless CI/CD pipelines, `approval_mode=auto` can be set via environment variable (`MCP_REVIT_APPROVAL_MODE=auto`).++### 4. Rollback Strategies+- **Revit Undo (`undo`)**: If executed inside the same Revit session, the add-in wraps the execution in a single named transaction (`"AMB: Plan <plan_id>"`). The add-in can tigger Revit's native Undo command.+- **Inverse Counter-Plan (`inverse`)**: For persistent history rollbacks, the hub generates an inverse counter-plan by capturing the before-state (e.g., parameter values) and executing a compensating batch of updates.+- **Irreversible (`none`)**: High-risk operations (e.g., deleting models, file outputs) cannot be rolled back and require a double-confirmation from the human operator.++## Consequences+- **Trust & Safety**: Eliminates the risk of hallucinated or malicious AI writes damaging BIM models.+- **Audit Trails**: Every write corresponds to a versioned ActionPlan, a specific approving user, and an audit ledger entry.+- **Decoupled Orchestration**: AI agents can generate plans asynchronously while running long-running processes (e.g., clash detection), leaving the execution to the user.diff --git a/docs/0009-plugin-module-system.md b/docs/0009-plugin-module-system.mdnew file mode 100644index 0000000..d6ae4d0--- /dev/null+++ b/docs/0009-plugin-module-system.md@@ -0,0 +1,76 @@+# ADR 0009: Plugin Module System++## Status+Accepted++## Context+AEC Model Bridge contains a large set of tools (over 170) spanning multiple software hosts (Revit, Rhino, Navisworks) and workflows (QA/QC, massing, parameters). Hardcoding these into a single monolithic server makes the code brittle, degrades LLM tool selection performance, and prevents firms from writing custom company-standard checking rules. We need a modular plugin system that encapsulates commands, schemas, UI files, and QA rules.++## Decisions++### 1. Module Packaging & Discovery+A **Module** is a folder containing a manifest (`module.json`), code entry points (`module.py`), validation rules, and optional HTML cards. The **ModuleRegistry** loads them from three sources:+1. **Built-in**: Packaged within the hub wheel (`revit_mcp_server/modules/<name>/`).+2. **User/Firm Folder**: Local configuration directory (`%LOCALAPPDATA%\AECModelBridge\modules\<name>\`).+3. **Python Entry Points**: Discovered dynamically via `[project.entry-points."aec_model_bridge.modules"]` in installed packages.++### 2. Module Manifest Schema (`module.json`)+Every module must ship a schema-compliant manifest:+```json+{+ "id": "qaqc_checker",+ "name": "QA/QC Checker",+ "version": "1.0.0",+ "schema_version": 1,+ "min_hub_version": "1.2.0",+ "requires_providers": ["revit", "graph"],+ "requires_tools": ["revit_get_warnings"],+ "permissions": ["model.read", "workspace.write"],+ "commands": [+ {+ "id": "run_health_check",+ "title": "Run Health Check",+ "surface": ["ribbon", "panel", "mcp"],+ "mcp_tool": "qaqc_run_health_check",+ "execution_mode": "async",+ "is_mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "ruleset": {"type": "string", "default": "core"}+ }+ }+ }+ ],+ "ui": {+ "panel_card": "ui/findings_card.html"+ },+ "hooks": {+ "validate": "module:QaqcModule.validate"+ }+}+```++### 3. Enforced Security Permissions+Permissions are declared in the manifest and enforced by the hub at dispatch time:+- `model.read`: Grants read-only access to elements/properties.+- `model.write`: Permits modifications (requires approval gate).+- `model.delete`: Permits destructive actions (requires explicit confirmation).+- `workspace.write`: Restricted file output within the sandboxed workspace.+- `net.local`: Inter-app communication on local loopback.+- `net.cloud`: External synchronization (Speckle, ACC).+- `python.host`: Raw execution access (off by default, requires expert profile).++### 4. Manifest Exposure & MCP Mapping+- **To Panel**: The dockable UI queries `module_list_commands` and renders cards or panel buttons.+- **To MCP Client**: Every command with `"mcp"` surface is registered dynamically as an MCP tool named `<module_id>_<command_id>`. Schema and metadata properties (`is_mutating`, `destructive`) are carried over.++### 5. Execution Validation & Lifecycle Hooks+- **Schema Validation**: All inputs and outputs are validated against the manifest's `input_schema` and `output_schema` before execution.+- **Validate Hook**: Custom pre-execution logic runs at planning time (e.g., checks against company naming conventions). Can return warning or blocker lists.+- **On Result Hook**: Post-execution hooks run for audit ledger updates, database syncing, or notifications.++## Consequences+- **Extensibility**: Non-programmers can configure rule sets via YAML, while developers can distribute packaged python modules.+- **Tool-Context Efficiency**: LLMs are exposed to namespace-grouped tools, preventing tool list exhaustion.+- **Safety Allowlist**: Firms can deploy customized manifests restricting network and Python execution access.diff --git a/docs/0010-snapshot-schema.md b/docs/0010-snapshot-schema.mdnew file mode 100644index 0000000..cbdf32d--- /dev/null+++ b/docs/0010-snapshot-schema.md@@ -0,0 +1,79 @@+# ADR 0010: Semantic BIM Snapshot & Delta Schema++## Status+Accepted++## Context+Exchanging heavy geometry representations (like meshes or direct shapes) between BIM tools and LLM agents is slow, expensive, and strips the model of its structural semantics (levels, parameters, relationships). To enable efficient querying (W1), compliance rules (W7), and parameter batching (W5), we need a lightweight, semantic snapshot model that captures BIM elements, parameters, and relationships in a flat JSON structure.++## Decisions++### 1. Identity Strategy+- **Primary Element Identifier**: Revit `UniqueId` (stable GUID + ID) is used as the global primary key. Revit `ElementId` is treated as a temporary session-based cache and is never persisted across sessions.+- **Cross-App Identity**: Multi-platform elements (Revit, Rhino, IFC) are mapped to a unified `amb_uid` (ULID) via the `IdentityMapper` registry.+- **Document Identifier**: Document tracking uses `Document.CreationGUID` combined with `WorksharingCentralGUID` (for workshared central files) to detect SaveAs actions.++### 2. Snapshot Schema+A **Snapshot** is a JSON document containing flat element records, relational edges, type data, and Category counts:++```json+{+ "schema": "amb.snapshot/1",+ "snapshot_id": "01J...ULID",+ "taken_at": "2026-07-08T18:07:30Z",+ "source": {+ "app": "revit",+ "app_version": "2025.2",+ "doc_guid": "...",+ "doc_title": "model.rvt",+ "units": "SI"+ },+ "elements": [+ {+ "uid": "revit-unique-id-string",+ "amb_uid": "01J...",+ "category": "OST_Doors",+ "family": "Single-Flush",+ "type_name": "0915x2134mm",+ "level_uid": "level-uid-string",+ "host_uid": "wall-uid-string",+ "location": {"kind": "point", "xyz": [10.2, 5.4, 0.0], "rotation": 1.57},+ "params": {+ "Mark": {"v": "101", "storage": "String", "instance": true, "readonly": false},+ "FireRating": {"v": "30", "storage": "String", "instance": true, "readonly": false}+ }+ }+ ],+ "relations": [+ {"kind": "hosts", "from": "wall-uid-string", "to": "revit-unique-id-string"},+ {"kind": "on_level", "from": "revit-unique-id-string", "to": "level-uid-string"}+ ]+}+```++### 3. Standards and Units+- **Internal Units**: All coordinates, rotation angles, areas, and volumes are stored internally in standard SI units (metres, radians, square metres, cubic metres), matching the Rhino bridge convention.+- **Lightweight Geometry**: Elements carry basic bounding box dimensions (`bbox`) or location markers. Meshes are only exported on-demand to separate files, not inline in the snapshot.++### 4. Incremental Change Tracking+- **Session Dirty-List**: The C# add-in hooks `DocumentChanged` events to append modified/created elements to a session dirty-list.+- **Incremental Extraction**: The hub uses the dirty-list to pull only changed elements during active sessions, resolving large-model performance risks (ADR 0007).+- **Snapshot Diffing**: `snapshot_diff(a, b)` generates parameter-level and relational differences between versioned snapshots.++### 5. Delta Roundtrip Schema+Modifications sent from external tools (Grasshopper, Excel) are structured as transactional deltas:+```json+{+ "schema": "amb.delta/1",+ "base_snapshot": "01J...ULID",+ "actions": [+ {"op": "update", "uid": "door-uid", "set": {"FireRating": "60"}},+ {"op": "create", "temp_id": "t1", "class": "FamilyInstance", "family": "GlassPanel", "type_name": "Clear", "placement": {"kind": "adaptive_points", "points_m": [[0,0,0], [1,0,0], [1,1,0], [0,1,0]]}}+ ]+}+```++## Consequences+- **High Performance**: Snapshots of 10k-element models are lightweight and can be parsed in seconds rather than minutes.+- **Offline QA Checks**: QA/QC rule engines can run rule evaluations against the local SQLite-mirrored snapshot database without blocking the live Revit API thread.+- **Conflict Prevention**: Reconciling delta files against live snapshots detects if elements were modified by other team members since the base snapshot was taken, preventing data loss.diff --git a/docs/0011-panel-architecture.md b/docs/0011-panel-architecture.mdnew file mode 100644index 0000000..2e46637--- /dev/null+++ b/docs/0011-panel-architecture.md@@ -0,0 +1,60 @@+# ADR 0011: WebView2 Dockable Panel & Hub Message Bridge++## Status+Accepted++## Context+Standard Revit add-ins built with WPF (Windows Presentation Foundation) suffer from development friction, lack of modern CSS/animation styling capabilities, and poor cross-platform portability. In addition, loading native assemblies into Revit's single-threaded app domain carries risk of thread locks and assembly load-order clashes. To deliver a modern, premium user interface (dark mode, glassmorphism, responsive chat, plan diff lists) that is portable across Revit, Rhino, and Navisworks, we need a WebView2-based panel architecture.++## Decisions++### 1. Panel Architecture Overview+The user interface is hosted inside a native C# WPF dockable pane using Revit's `IDockablePaneProvider` API. The panel hosts a Microsoft WebView2 runtime instance displaying a local web app:++```+┌────────────────────────────────────────────────────────┐+│ Revit UI Shell │+│ ┌──────────────────────────────────────────────────┐ │+│ │ WPF Dockable Pane Chrome │ │+│ │ ┌────────────────────────────────────────────┐ │ │+│ │ │ WebView2 Browser Control │ │ │+│ │ │ │ │ │+│ │ │ UI Web App (HTML/JS/Vanilla CSS) │ │ │+│ │ │ ────────────────────────────────────────── │ │ │+│ │ │ - Chat interface (conversational window) │ │ │+│ │ │ - ActionPlan Card Queue (Approve/Reject) │ │ │+│ │ │ - Live Run Ledger & Metrics │ │ │+│ │ └────────────────────────────────────────────┘ │ │+│ └──────────────────────────────────────────────────┘ │+└────────────────────────────────────────────────────────┘+```++### 2. Double-Bridge Communication System+To maintain security boundaries while enabling rapid data transfer:++1. **Host Bridge (C# WebView2 Integration)**:+ - Communication from the Web App to the Revit C# add-in goes through WebView2's built-in message interface:+ - JS to C#: `window.chrome.webview.postMessage(JSON.stringify(payload))`+ - C# to JS: `webView.CoreWebView2.PostWebMessageAsString(payload)`+ - Used for UI-triggered host actions (e.g., highlighting an element by ID, selecting instances, zooming to bounding box).++2. **Hub Bridge (REST / MCP local loopback)**:+ - The Web App communicates with the Python hub via standard HTTP/JSON REST endpoints exposed by the hub's local server (running on a dynamic port published in `%LOCALAPPDATA%\AECModelBridge\registry\`).+ - The Web App queries:+ - `/plans/pending`: Active plans in the approval queue.+ - `/plans/{id}/approve`: Approves a plan for execution.+ - `/plans/{id}/reject`: Rejects a plan.+ - `/audit/logs`: Historical ledger entries for the active document.++### 3. Safety & Thread Isolation+- **Non-blocking UI**: The Web App runs entirely inside the isolated WebView2 process. Rendering complex graphs, SVG models, or parsing large log files does not block Revit's single-threaded user interface.+- **API Threading Dispatch**: Commands requiring access to Revit API objects are passed over the WebView2 Host Bridge, enqueued on `CommandQueue.Enqueue`, and raised via `ExternalEvent.Raise()` to execute on Revit's main API thread inside a standard Transaction.++### 4. UI Design Philosophy & Frameworks+- **Styling**: Pure Vanilla CSS tailored with rich aesthetic HSL variables (sleek dark mode default, subtle micro-animations for hover states, glassmorphism card layouts).+- **No Heavy Frameworks**: Minimal javascript boilerplate; native Web Components or a lightweight view-scheduler (e.g., standard template strings) to avoid load-time lag.++## Consequences+- **Rapid Iteration**: UI changes, styling patches, and log viewer additions can be made and tested inside standard web browsers without needing to restart the Revit host application.+- **Cross-Platform Reusability**: The same WebView2 HTML code can be loaded into Rhino/Grasshopper panels or Navisworks UI containers, minimizing cross-platform code redundancy.+- **Runtime Requirement**: The client machine must have the Microsoft WebView2 Evergreen Runtime installed (shipped by default with Windows 10/11 and Microsoft 365 apps).