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
Add read-only clash triage module (ADR 0015 slice A) (#85)
A. Sam Mohammadb0dd7b98b7e1
diff --git a/docs/README.md b/docs/README.mdindex 572c9f2..92b74fa 100644--- a/docs/README.md+++ b/docs/README.md@@ -12,6 +12,7 @@ Start with the [installation guide](install.md). The main [README](../README.md)- [logging-and-audit.md](logging-and-audit.md): Python-side audit log and add-in logging.- [marketplaces.md](marketplaces.md): MCP Registry, bundle and client distribution.- [versioning.md](versioning.md): version numbers, release tags and release assets.+- [clash-triage.md](clash-triage.md): read-only matching of Navisworks clashes to Revit elements, with a confidence label (unverified on live projects).- [roadmap.md](roadmap.md): coordinator workflows, demo scope and the next fixes.## For contributorsdiff --git a/docs/clash-triage.md b/docs/clash-triage.mdnew file mode 100644index 0000000..59df094--- /dev/null+++ b/docs/clash-triage.md@@ -0,0 +1,39 @@+# Clash triage (read-only)++First slice of the Navisworks to Revit loop scoped in ADR 0015. It answers one question for a BIM coordinator: "for each clash in my Navisworks test, which Revit elements are involved, and how sure are we?"++It never changes the Revit model and it proposes no fixes.++## How to use it++1. Run a clash test in Navisworks and fetch the results with `navisworks_get_clash_results`.+2. Capture a Revit snapshot and note its `snapshot_id`.+3. Call `clash_triage_match_clashes` with the clash results and the `snapshot_id`.+4. Read the answer per clash. Later, `clash_triage_list_clash_issues` lists what was recorded.++In mock mode (`MCP_REVIT_MODE=mock`) the snapshot is optional and generated sample data is used. When connected to Revit a real `snapshot_id` is required; the tool refuses to guess.++## What the confidence labels mean++| Label | Meaning |+| --- | --- |+| exact | The clash item's GUID matches exactly one Revit element, by its UniqueId or by its IFC GUID parameter. |+| ambiguous | The GUID matches more than one element. None is picked for you. |+| unmatched | No GUID was supplied, or no element in the snapshot has it (the model may have changed since the test). |++A clash is only "exact" when both of its items are exact. Otherwise it takes the weaker of the two labels.++## What it will not do++- It does not use the Revit ElementId or the Navisworks InstanceGuid to find elements. Those are not reliable across tools.+- It does not match by name or category, and it does not fall back to a guess.+- It does not write to the Revit model. Results are saved as issues in the workspace file `clash_triage.db`. This is kept apart from the QA/QC issue store so a QA/QC re-run cannot close clash issues by accident.++## UNVERIFIED++Everything above was tested with fixture data only. Not yet checked on a real project with Revit and Navisworks:++- What Navisworks puts in the GUID field for items that came from Revit, IFC or NWC sources.+- Whether the Revit snapshot carries an IFC GUID parameter (the module looks for a parameter named `IfcGUID`) in your models.+- How many clashes map to the right element on both sides. A person should check a sample on one real project.+- Clashes inside linked models or groups.diff --git a/docs/tools-generated.md b/docs/tools-generated.mdindex 072d453..b184d03 100644--- a/docs/tools-generated.md+++ b/docs/tools-generated.md@@ -75,6 +75,8 @@ This catalog lists all tools exposed by the AEC Model Bridge providers.| --- | --- | --- | --- || `bcf_exchange_export_bcf` | Save issues (your own list and/or the recorded QA/QC issues) to a BCF 2. | No | sync || `bcf_exchange_import_bcf` | Read a BCF. | No | sync |+| `clash_triage_list_clash_issues` | List the clash issues recorded by clash triage, optionally filtered by status and match confidence. | No | sync |+| `clash_triage_match_clashes` | Match each clash from a Navisworks clash test to the Revit elements it involves, by UniqueId or IFC GUID, and say how sure each match is (exact, ambiguous or unmatched). | No | sync || `familytype_mapper_audit_families` | Audit the families in a saved snapshot and report problems such as unmapped or inconsistent family types. | No | sync || `familytype_mapper_list_type_mappings` | List family-type mappings found in a saved snapshot, optionally for one category. | No | sync || `hello_world_say_hello` | Example module command that returns a greeting; use it to confirm the module system works. | No | sync |diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/clash_triage/__init__.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/clash_triage/__init__.pynew file mode 100644index 0000000..e3e809c--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/clash_triage/__init__.py@@ -0,0 +1 @@+# clash_triagediff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/clash_triage/module.json b/packages/mcp-server-revit/src/revit_mcp_server/modules/clash_triage/module.jsonnew file mode 100644index 0000000..17cbf4a--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/clash_triage/module.json@@ -0,0 +1,59 @@+{+ "id": "clash_triage",+ "name": "Clash Triage",+ "version": "1.0.0",+ "schema_version": 1,+ "min_hub_version": "1.2.0",+ "description": "Read-only clash triage: match each Navisworks clash item to a Revit element by UniqueId or IFC GUID, report how sure each match is (exact, ambiguous, unmatched), and record the result as an issue. Never changes the model.",+ "author": "AEC Model Bridge",+ "license": "GPL-3.0-or-later",+ "requires_providers": ["revit", "semantic"],+ "permissions": ["model.read"],+ "commands": [+ {+ "id": "match_clashes",+ "title": "Match Clashes to Revit Elements",+ "surface": ["mcp", "panel"],+ "execution_mode": "sync",+ "is_mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "clash_results": {+ "description": "The clash results as returned by navisworks_get_clash_results (an object with a 'results' list), or just that list."+ },+ "snapshot_id": {+ "type": "string",+ "description": "Snapshot of the Revit model to match against. Required when connected to Revit."+ },+ "record_issues": {+ "type": "boolean",+ "default": true,+ "description": "Record each clash as an issue in the workspace so it can be listed later."+ }+ },+ "required": ["clash_results"]+ }+ },+ {+ "id": "list_clash_issues",+ "title": "List Clash Issues",+ "surface": ["mcp", "panel"],+ "execution_mode": "sync",+ "is_mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "doc_guid": {"type": "string", "description": "Only issues for this Revit document."},+ "status": {"type": "string", "enum": ["open", "resolved"], "description": "Only issues with this status."},+ "match": {+ "type": "string",+ "enum": ["exact", "ambiguous", "unmatched"],+ "description": "Only clashes with this overall match confidence."+ }+ },+ "required": []+ }+ }+ ]+}diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/clash_triage/module.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/clash_triage/module.pynew file mode 100644index 0000000..756749b--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/clash_triage/module.py@@ -0,0 +1,298 @@+"""+clash_triage module - read-only triage of Navisworks clash results (ADR 0015, slice A).++Commands:+ match_clashes - Match both items of every clash to Revit elements and report how sure each match is.+ list_clash_issues - List the clash issues recorded earlier.++Rules (see docs/clash-triage.md):+ - The only keys used to find a Revit element are its UniqueId and its IFC GUID+ parameter. Revit ElementId and the Navisworks InstanceGuid are never used.+ - Every item gets a confidence: exact (one element found), ambiguous (more than+ one element found, none is chosen) or unmatched (nothing found). No guessing.+ - Nothing here changes the Revit model. Results are saved in the workspace file+ ``clash_triage.db``, a separate store from the QA/QC rule issues so a QA/QC+ re-run cannot auto-resolve them.+"""+from __future__ import annotations++import json+import sqlite3+import uuid+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Dict, List, Optional++DB_FILENAME = "clash_triage.db"+RULE_ID = "clash_triage"+_RANK = {"exact": 0, "ambiguous": 1, "unmatched": 2}+++def _now() -> str:+ return datetime.now(timezone.utc).isoformat()+++def _conn(workspace: Any) -> sqlite3.Connection:+ conn = sqlite3.connect(str(workspace.allowed_directories[0] / DB_FILENAME))+ conn.row_factory = sqlite3.Row+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS clash_issues (+ id TEXT PRIMARY KEY,+ doc_guid TEXT NOT NULL,+ rule_id TEXT NOT NULL,+ severity TEXT NOT NULL,+ clash_guid TEXT NOT NULL,+ clash_name TEXT,+ status TEXT NOT NULL DEFAULT 'open',+ match TEXT NOT NULL,+ element_uid_a TEXT,+ element_uid_b TEXT,+ match_kind_a TEXT,+ match_kind_b TEXT,+ message TEXT NOT NULL,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL+ )+ """+ )+ conn.commit()+ return conn+++def _norm_param_name(name: str) -> str:+ return "".join(ch for ch in str(name).lower() if ch.isalnum())+++def _ifc_guid_of(el: Dict[str, Any]) -> Optional[str]:+ for pname, pval in (el.get("params") or {}).items():+ if _norm_param_name(pname) in ("ifcguid", "ifcglobalid"):+ v = pval.get("v") if isinstance(pval, dict) else pval+ if v not in (None, ""):+ return str(v)+ return None+++def _build_index(elements: List[Dict[str, Any]]) -> Dict[str, Any]:+ by_uid: Dict[str, List[Dict[str, Any]]] = {}+ by_ifc: Dict[str, List[Dict[str, Any]]] = {}+ for el in elements:+ uid = el.get("uid")+ if uid:+ by_uid.setdefault(str(uid).lower(), []).append(el)+ ifc = _ifc_guid_of(el)+ if ifc:+ by_ifc.setdefault(ifc, []).append(el) # IFC GUIDs are case-sensitive+ return {"uid": by_uid, "ifc": by_ifc}+++def _describe(el: Dict[str, Any]) -> Dict[str, Any]:+ return {+ "uid": el.get("uid"),+ "category": el.get("category"),+ "family": el.get("family"),+ "type_name": el.get("type_name"),+ "level_uid": el.get("level_uid"),+ }+++def _match_item(item: Any, index: Dict[str, Any]) -> Dict[str, Any]:+ """Match one Navisworks item identity to Revit elements. Never guesses."""+ if not isinstance(item, dict):+ return {"item_name": None, "ifc_guid": None, "confidence": "unmatched", "match_kind": None,+ "element": None, "candidates": [], "reason": "The clash has no item on this side."}++ guid = item.get("ifcGuid") or item.get("ifc_guid")+ base = {"item_name": item.get("displayName"), "ifc_guid": guid}+ if not guid:+ return {**base, "confidence": "unmatched", "match_kind": None, "element": None,+ "candidates": [],+ "reason": "Navisworks gave no GUID for this item, so it cannot be matched safely."}++ guid = str(guid).strip()+ found: Dict[str, Dict[str, Any]] = {}+ kinds: Dict[str, str] = {}+ for el in index["uid"].get(guid.lower(), []):+ key = str(id(el))+ found[key] = el+ kinds[key] = "unique_id"+ for el in index["ifc"].get(guid, []):+ key = str(id(el))+ if key not in found:+ found[key] = el+ kinds[key] = "ifc_guid"++ if len(found) == 1:+ key = next(iter(found))+ return {**base, "confidence": "exact", "match_kind": kinds[key],+ "element": _describe(found[key]), "candidates": [], "reason": None}+ if len(found) > 1:+ return {**base, "confidence": "ambiguous", "match_kind": None, "element": None,+ "candidates": [_describe(e) for e in found.values()],+ "reason": f"{len(found)} Revit elements share this GUID; none was chosen."}+ return {**base, "confidence": "unmatched", "match_kind": None, "element": None,+ "candidates": [],+ "reason": "No Revit element in the snapshot has this UniqueId or IFC GUID "+ "(the model may have changed since the clash test was run)."}+++def _extract_results(clash_results: Any) -> List[Dict[str, Any]]:+ if isinstance(clash_results, str):+ try:+ clash_results = json.loads(clash_results)+ except ValueError as e:+ raise ValueError(f"clash_results is not valid JSON: {e}") from e+ if isinstance(clash_results, dict):+ if isinstance(clash_results.get("results"), list):+ return clash_results["results"]+ inner = clash_results.get("result")+ if isinstance(inner, dict) and isinstance(inner.get("results"), list):+ return inner["results"]+ if clash_results.get("mock"):+ return []+ raise ValueError("clash_results has no 'results' list. Pass the output of navisworks_get_clash_results.")+ if isinstance(clash_results, list):+ return clash_results+ raise ValueError("clash_results must be the output of navisworks_get_clash_results or its list of results.")+++def _overall(a: str, b: str) -> str:+ return a if _RANK[a] >= _RANK[b] else b+++class ClashTriageModule:++ def match_clashes(+ self,+ clash_results: Any = None,+ snapshot_id: str = "",+ record_issues: bool = True,+ workspace: Any = None,+ **_,+ ) -> Dict[str, Any]:+ if clash_results is None:+ raise ValueError("clash_results is required.")+ results = _extract_results(clash_results)+ elements, doc_guid = self._get_data(snapshot_id, workspace)+ index = _build_index(elements)++ clashes = []+ for i, res in enumerate(results):+ res = res if isinstance(res, dict) else {}+ a = _match_item(res.get("item1"), index)+ b = _match_item(res.get("item2"), index)+ overall = _overall(a["confidence"], b["confidence"])+ clashes.append({+ "clash_guid": res.get("guid") or f"clash-{i}",+ "clash_name": res.get("displayName"),+ "navisworks_status": res.get("status"),+ "distance": res.get("distance"),+ "confidence": overall,+ "item1": a,+ "item2": b,+ "note": self._note(overall),+ })++ summary = {k: sum(1 for c in clashes if c["confidence"] == k) for k in _RANK}+ recorded = 0+ if record_issues and workspace is not None and clashes:+ recorded = self._record(workspace, doc_guid, clashes)++ return {+ "read_only": True,+ "doc_guid": doc_guid,+ "total_clashes": len(clashes),+ "summary": summary,+ "issues_recorded": recorded,+ "clashes": clashes,+ "unverified": "Matching was tested on fixtures only. What Navisworks puts in the GUID field "+ "for Revit, IFC or NWC sources has not been checked on a live project.",+ }++ def list_clash_issues(+ self,+ doc_guid: str = "",+ status: Optional[str] = None,+ match: Optional[str] = None,+ workspace: Any = None,+ **_,+ ) -> Dict[str, Any]:+ db_path = Path(workspace.allowed_directories[0]) / DB_FILENAME+ if not db_path.exists():+ # Listing must not create the store.+ return {"total": 0, "issues": []}+ conn = sqlite3.connect(f"file:{db_path.as_posix()}?mode=ro", uri=True)+ conn.row_factory = sqlite3.Row+ query, params = "SELECT * FROM clash_issues WHERE 1=1", []+ for col, val in (("doc_guid", doc_guid), ("status", status), ("match", match)):+ if val:+ query += f" AND {col}=?"+ params.append(val)+ try:+ rows = [dict(r) for r in conn.execute(query + " ORDER BY created_at", params)]+ except sqlite3.OperationalError: # store exists but has no table yet+ rows = []+ finally:+ conn.close()+ return {"total": len(rows), "issues": rows}++ # ------------------------------------------------------------------++ @staticmethod+ def _note(overall: str) -> str:+ return {+ "exact": "Both items matched one Revit element each. Check them in Revit before acting.",+ "ambiguous": "At least one item matched several Revit elements. Decide by hand.",+ "unmatched": "At least one item could not be found in the snapshot. No fix should be proposed.",+ }[overall]++ def _record(self, workspace: Any, doc_guid: str, clashes: List[Dict[str, Any]]) -> int:+ conn = _conn(workspace)+ now = _now()+ for c in clashes:+ a, b = c["item1"], c["item2"]+ uid_a = (a["element"] or {}).get("uid")+ uid_b = (b["element"] or {}).get("uid")+ severity = "info" if c["confidence"] == "exact" else "warning"+ message = (+ f"Clash '{c['clash_name'] or c['clash_guid']}': {c['confidence']} match. "+ f"{a['item_name']} -> {uid_a or a['confidence']}; {b['item_name']} -> {uid_b or b['confidence']}."+ )+ existing = conn.execute(+ "SELECT id FROM clash_issues WHERE doc_guid=? AND clash_guid=? AND status='open'",+ (doc_guid, c["clash_guid"]),+ ).fetchone()+ if existing:+ conn.execute(+ "UPDATE clash_issues SET match=?, severity=?, clash_name=?, element_uid_a=?, element_uid_b=?, "+ "match_kind_a=?, match_kind_b=?, message=?, updated_at=? WHERE id=?",+ (c["confidence"], severity, c["clash_name"], uid_a, uid_b,+ a["match_kind"], b["match_kind"], message, now, existing["id"]),+ )+ else:+ conn.execute(+ "INSERT INTO clash_issues (id, doc_guid, rule_id, severity, clash_guid, clash_name, status, "+ "match, element_uid_a, element_uid_b, match_kind_a, match_kind_b, message, created_at, updated_at) "+ "VALUES (?,?,?,?,?,?, 'open', ?,?,?,?,?,?,?,?)",+ (str(uuid.uuid4()), doc_guid, RULE_ID, severity, c["clash_guid"], c["clash_name"],+ c["confidence"], uid_a, uid_b, a["match_kind"], b["match_kind"], message, now, now),+ )+ conn.commit()+ conn.close()+ return len(clashes)++ def _get_data(self, snapshot_id: str, workspace: Any):+ if not snapshot_id:+ from revit_mcp_server.semantic.engine import generate_mock_snapshot, require_snapshot_or_mock+ require_snapshot_or_mock(snapshot_id, "clash_triage")+ snap = generate_mock_snapshot()+ return [el.model_dump(by_alias=True) for el in snap.elements], "mock-doc"+ snap_dir = (Path(workspace.allowed_directories[0]) / "snapshots").resolve()+ snap_path = (snap_dir / f"{snapshot_id}.json").resolve()+ if snap_path.parent != snap_dir:+ raise ValueError("snapshot_id must be a plain snapshot name inside the workspace snapshots folder.")+ if not snap_path.exists():+ raise ValueError(f"Snapshot '{snapshot_id}' not found.")+ with open(snap_path, encoding="utf-8") as f:+ data = json.load(f)+ return data.get("elements", []), data.get("source", {}).get("doc_guid", snapshot_id)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 67ec2af..2f72e2f 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@@ -42,7 +42,7 @@ DEFAULT_PORT = 8787# 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"}+NON_REPORT_FILENAMES = {"qaqc_issues.db", "clash_triage.db"}def _run_tool_sync(registry, approval_provider, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]: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 1637a42..c9bcbac 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@@ -166,6 +166,8 @@ DESCRIPTIONS: dict[str, str] = {"qaqc_checker_run_check": "Run a QA/QC rule pack against a saved snapshot and record the issues it finds.","qaqc_checker_list_issues": "List recorded QA/QC issues for a document, optionally filtered by status and severity. Read-only.","qaqc_checker_resolve_issue": "Mark one recorded QA/QC issue as resolved.",+ "clash_triage_match_clashes": "Match each clash from a Navisworks clash test to the Revit elements it involves, by UniqueId or IFC GUID, and say how sure each match is (exact, ambiguous or unmatched). Never guesses and never changes the model; records the result as issues in the workspace.",+ "clash_triage_list_clash_issues": "List the clash issues recorded by clash triage, optionally filtered by status and match confidence. Read-only.","qaqc_checker_list_rules": "List the QA/QC rules that are available, optionally for one rule pack. Read-only.","warnings_triage_review_warnings": "Group the open project's Revit warnings by type, rank them by how many elements they touch, flag duplicate marks, overlapping elements and rooms not enclosed for the coordinator, and suggest a next step for each group. Read-only.","bcf_exchange_export_bcf": "Save issues (your own list and/or the recorded QA/QC issues) to a BCF 2.1 .bcfzip file in the workspace. Writes a file; does not change the model. Not yet checked against other BCF tools.",@@ -487,6 +489,7 @@ NOT_READ_ONLY: dict[str, tuple[bool, bool]] = {"selection_tools_save_selection": (False, True),"bcf_exchange_export_bcf": (False, True),"qaqc_checker_run_check": (False, False),+ "clash_triage_match_clashes": (False, True),"qaqc_checker_resolve_issue": (False, True),"recipe_runner_run_recipe": (True, False),"aec_register_mapping": (False, True),diff --git a/packages/mcp-server-revit/tests/test_clash_triage.py b/packages/mcp-server-revit/tests/test_clash_triage.pynew file mode 100644index 0000000..c2d4b8e--- /dev/null+++ b/packages/mcp-server-revit/tests/test_clash_triage.py@@ -0,0 +1,164 @@+"""Tests for the read-only clash triage module (ADR 0015, slice A). Fixtures only; no live Revit or Navisworks."""+import importlib.util+import json+from pathlib import Path++import pytest++from revit_mcp_server.semantic.engine import generate_mock_snapshot+++def _load_mod():+ # Import under its package name so coverage (source_pkgs) measures it.+ return importlib.import_module("revit_mcp_server.modules.clash_triage.module")+++ClashTriageModule = _load_mod().ClashTriageModule++WALL = "c0326e0e-473d-4952-b8ec-f23696541f43-wall-1"+DOOR = "c0326e0e-473d-4952-b8ec-f23696541f44-door-1"+++class WS:+ def __init__(self, p):+ self.allowed_directories = [p]+++def _item(name, guid, instance="11111111-1111-1111-1111-111111111111"):+ return {"displayName": name, "className": "LcRevitNode", "instanceGuid": instance, "ifcGuid": guid}+++def _clash(guid, i1, i2, name="Clash1"):+ return {"displayName": name, "guid": guid, "status": "New", "distance": -0.05, "item1": i1, "item2": i2}+++def mod():+ return ClashTriageModule()+++def ws(tmp_path):+ return WS(tmp_path)+++def _write_snapshot(tmp_path, elements):+ snap = generate_mock_snapshot()+ data = json.loads(snap.model_dump_json(by_alias=True))+ data["elements"] = elements+ (tmp_path / "snapshots").mkdir(exist_ok=True)+ (tmp_path / "snapshots" / "snap1.json").write_text(json.dumps(data), encoding="utf-8")+ return "snap1"+++def test_exact_by_unique_id_mock_mode(mod, ws):+ res = {"results": [_clash("c1", _item("Wall", WALL), _item("Door", DOOR))]}+ out = mod.match_clashes(clash_results=res, workspace=ws)+ c = out["clashes"][0]+ assert out["read_only"] is True+ assert c["confidence"] == "exact"+ assert c["item1"]["element"]["uid"] == WALL+ assert c["item1"]["match_kind"] == "unique_id"+ assert out["summary"] == {"exact": 1, "ambiguous": 0, "unmatched": 0}+++def test_exact_by_ifc_guid_parameter(mod, ws, tmp_path):+ els = [{"uid": "u-1", "element_id": 1, "category": "OST_Walls",+ "params": {"IfcGUID": {"v": "2O2Fr$t4X7Zf8NOew3FLOH", "storage": "String"}}},+ {"uid": "u-2", "element_id": 2, "category": "OST_Doors", "params": {}}]+ sid = _write_snapshot(tmp_path, els)+ res = [_clash("c1", _item("Wall", "2O2Fr$t4X7Zf8NOew3FLOH"), _item("Door", "u-2"))]+ out = mod.match_clashes(clash_results=res, snapshot_id=sid, workspace=ws)+ c = out["clashes"][0]+ assert c["confidence"] == "exact"+ assert c["item1"]["match_kind"] == "ifc_guid"+ assert c["item2"]["match_kind"] == "unique_id"+++def test_ambiguous_when_guid_hits_two_elements(mod, ws, tmp_path):+ els = [{"uid": "u-1", "element_id": 1, "category": "OST_Walls",+ "params": {"IfcGUID": {"v": "DUPLICATE", "storage": "String"}}},+ {"uid": "u-2", "element_id": 2, "category": "OST_Walls",+ "params": {"IfcGUID": {"v": "DUPLICATE", "storage": "String"}}},+ {"uid": "u-3", "element_id": 3, "category": "OST_Doors", "params": {}}]+ sid = _write_snapshot(tmp_path, els)+ res = [_clash("c1", _item("Wall", "DUPLICATE"), _item("Door", "u-3"))]+ c = mod.match_clashes(clash_results=res, snapshot_id=sid, workspace=ws)["clashes"][0]+ assert c["confidence"] == "ambiguous"+ assert c["item1"]["element"] is None # nothing chosen silently+ assert len(c["item1"]["candidates"]) == 2+++def test_unmatched_and_never_uses_instance_guid_or_element_id(mod, ws):+ # InstanceGuid equals a real UniqueId and 200 is a real ElementId: neither may match.+ item = _item("Wall", None, instance=WALL)+ item["elementId"] = 200+ res = [_clash("c1", item, _item("Ghost", "no-such-guid"))]+ c = mod.match_clashes(clash_results=res, workspace=ws)["clashes"][0]+ assert c["confidence"] == "unmatched"+ assert c["item1"]["element"] is None and "no GUID" in c["item1"]["reason"]+ assert c["item2"]["confidence"] == "unmatched"+++def test_overall_is_worst_of_both_sides(mod, ws):+ res = [_clash("c1", _item("Wall", WALL), _item("Ghost", "nope"))]+ c = mod.match_clashes(clash_results=res, workspace=ws)["clashes"][0]+ assert c["item1"]["confidence"] == "exact"+ assert c["confidence"] == "unmatched"+++def test_issues_recorded_and_listed_without_duplicates(mod, ws):+ res = {"results": [_clash("c1", _item("Wall", WALL), _item("Door", DOOR)),+ _clash("c2", _item("Wall", WALL), _item("Ghost", "nope"), name="Clash2")]}+ assert mod.match_clashes(clash_results=res, workspace=ws)["issues_recorded"] == 2+ mod.match_clashes(clash_results=res, workspace=ws) # re-run updates, not duplicates+ assert mod.list_clash_issues(workspace=ws)["total"] == 2+ assert mod.list_clash_issues(match="unmatched", workspace=ws)["total"] == 1+ exact = mod.list_clash_issues(match="exact", workspace=ws)["issues"][0]+ assert exact["element_uid_a"] == WALL and exact["element_uid_b"] == DOOR+++def test_record_issues_false_writes_nothing(mod, ws, tmp_path):+ res = [_clash("c1", _item("Wall", WALL), _item("Door", DOOR))]+ out = mod.match_clashes(clash_results=res, record_issues=False, workspace=ws)+ assert out["issues_recorded"] == 0+ assert not (tmp_path / "clash_triage.db").exists()+++def test_bridge_mode_rejects_missing_snapshot(mod, ws, monkeypatch):+ from revit_mcp_server.config import BridgeMode, config+ monkeypatch.setattr(config, "mode", BridgeMode.bridge)+ res = [_clash("c1", _item("Wall", WALL), _item("Door", DOOR))]+ with pytest.raises(ValueError, match="requires a snapshot_id"):+ mod.match_clashes(clash_results=res, workspace=ws)+++def test_unknown_snapshot_and_bad_input(mod, ws):+ with pytest.raises(ValueError, match="not found"):+ mod.match_clashes(clash_results=[], snapshot_id="missing", workspace=ws)+ with pytest.raises(ValueError):+ mod.match_clashes(clash_results={"oops": 1}, workspace=ws)+++def test_module_declares_no_mutating_commands():+ p = Path(__file__).parent.parent / "src/revit_mcp_server/modules/clash_triage/module.json"+ manifest = json.loads(p.read_text(encoding="utf-8"))+ assert manifest["permissions"] == ["model.read"]+ assert all(c["is_mutating"] is False for c in manifest["commands"])+++def test_snapshot_id_cannot_escape_snapshots_dir(mod, ws, tmp_path):+ outside = tmp_path / "outside.json"+ outside.write_text(json.dumps({"elements": [{"uid": WALL}], "source": {"doc_guid": "x"}}), encoding="utf-8")+ (tmp_path / "snapshots").mkdir(exist_ok=True)+ res = [_clash("c1", _item("Wall", WALL), _item("Door", DOOR))]+ for bad in ("../outside", str(tmp_path / "outside")):+ with pytest.raises(ValueError):+ mod.match_clashes(clash_results=res, snapshot_id=bad, workspace=ws)+++def test_list_clash_issues_does_not_create_the_database(mod, ws, tmp_path):+ out = mod.list_clash_issues(workspace=ws)+ assert out == {"total": 0, "issues": []}+ assert not (tmp_path / "clash_triage.db").exists()+diff --git a/packages/mcp-server-revit/tests/test_panel_server.py b/packages/mcp-server-revit/tests/test_panel_server.pyindex 6a90b7e..e3ebe29 100644--- a/packages/mcp-server-revit/tests/test_panel_server.py+++ b/packages/mcp-server-revit/tests/test_panel_server.py@@ -128,6 +128,15 @@ def test_reports_excludes_internal_state_files(running_server, tmp_path):assert body["reports"] == []+def test_reports_excludes_clash_triage_state_file(running_server, tmp_path):+ (tmp_path / "clash_triage.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