Skip to content

Open-source Revit MCP server: let Claude and other AI assistants read and edit BIM models, with human approval on every change.

feat(modules): implement Parameter Manager + FamilyType Mapper — filter/diff/plan-set/CSV, audit rules, type mappings (P9.1-P9.3)

A. Sam Mohammad91ab116f7352
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/familytype_mapper/__init__.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/familytype_mapper/__init__.py
new file mode 100644
index 0000000..e0e7f44
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/familytype_mapper/__init__.py
@@ -0,0 +1 @@
+# familytype_mapper
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/familytype_mapper/module.json b/packages/mcp-server-revit/src/revit_mcp_server/modules/familytype_mapper/module.json
new file mode 100644
index 0000000..058e003
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/familytype_mapper/module.json
@@ -0,0 +1,43 @@
+{
+ "id": "familytype_mapper",
+ "name": "Family Type Mapper",
+ "version": "1.0.0",
+ "schema_version": 1,
+ "min_hub_version": "1.2.0",
+ "description": "Family audit and type mapping workflows (W6): family quality audit, type mapping tables, in-place family detection, and shared-param GUID validation.",
+ "author": "AEC Model Bridge",
+ "license": "GPL-3.0-or-later",
+ "requires_providers": ["revit", "semantic"],
+ "permissions": ["model.read"],
+ "commands": [
+ {
+ "id": "audit_families",
+ "title": "Audit Families",
+ "surface": ["mcp", "panel"],
+ "execution_mode": "sync",
+ "is_mutating": false,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "snapshot_id": {"type": "string"}
+ },
+ "required": []
+ }
+ },
+ {
+ "id": "list_type_mappings",
+ "title": "List Type Mappings",
+ "surface": ["mcp", "panel"],
+ "execution_mode": "sync",
+ "is_mutating": false,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "snapshot_id": {"type": "string"},
+ "category": {"type": "string"}
+ },
+ "required": []
+ }
+ }
+ ]
+}
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/familytype_mapper/module.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/familytype_mapper/module.py
new file mode 100644
index 0000000..930a01a
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/familytype_mapper/module.py
@@ -0,0 +1,159 @@
+"""
+familytype_mapper module — P9.3 Family Audit & Type Mapping (read side).
+
+Commands:
+ audit_families — Flag in-place families, families without types, and overloaded families.
+ list_type_mappings — Return a type mapping table (family → types used) for roundtrip/W11.
+
+W6 Core Audit Rules:
+ - In-place families → always flag (should be converted to loadable)
+ - Families with zero placed instances → flag as unused
+ - Families with >10 types → flag as overloaded
+ - Type names containing spaces at start/end → flag as bad naming
+"""
+from __future__ import annotations
+
+import json
+import logging
+from collections import defaultdict
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+logger = logging.getLogger(__name__)
+
+
+def _workspace_dir(workspace: Any) -> Path:
+ return workspace.allowed_directories[0]
+
+def _load_snapshot(snapshot_id: str, workspace: Any) -> Dict[str, Any]:
+ path = _workspace_dir(workspace) / "snapshots" / f"{snapshot_id}.json"
+ if not path.exists():
+ raise ValueError(f"Snapshot '{snapshot_id}' not found.")
+ with open(path, "r", encoding="utf-8") as f:
+ return json.load(f)
+
+def _get_data(snapshot_id: str, workspace: Any):
+ if not snapshot_id:
+ from revit_mcp_server.semantic.engine import generate_mock_snapshot
+ snap = generate_mock_snapshot()
+ return (
+ [el.model_dump(by_alias=True) for el in snap.elements],
+ [t.model_dump() for t in snap.types],
+ )
+ data = _load_snapshot(snapshot_id, workspace)
+ return data.get("elements", []), data.get("types", [])
+
+
+class FamilytypeMapperModule:
+
+ def audit_families(self, snapshot_id: str = "", workspace: Any = None, **_) -> Dict[str, Any]:
+ elements, types = _get_data(snapshot_id, workspace)
+
+ # Count instances per family
+ family_instances: Dict[str, int] = defaultdict(int)
+ for el in elements:
+ fam = el.get("family")
+ if fam:
+ family_instances[fam] += 1
+
+ # Build type counts per family
+ family_types: Dict[str, List[str]] = defaultdict(list)
+ for t in types:
+ fam = t.get("family")
+ tn = t.get("type_name")
+ if fam and tn:
+ family_types[fam].append(tn)
+
+ # In-place detection (from TypeRecord.family_source == "inplace")
+ inplace_families = {t.get("family") for t in types if t.get("family_source") == "inplace"}
+
+ findings = []
+ for t in types:
+ fam = t.get("family")
+ if not fam:
+ continue
+
+ src = t.get("family_source", "loadable")
+
+ # Rule: in-place family
+ if src == "inplace":
+ findings.append({
+ "severity": "warning",
+ "rule": "inplace_family",
+ "family": fam,
+ "message": f"Family '{fam}' is in-place. Should be converted to loadable.",
+ })
+
+ # Rule: zero instances
+ if family_instances.get(fam, 0) == 0:
+ findings.append({
+ "severity": "info",
+ "rule": "unused_family",
+ "family": fam,
+ "message": f"Family '{fam}' has no placed instances.",
+ })
+
+ # De-duplicate by (rule, family)
+ seen = set()
+ deduped = []
+ for f in findings:
+ key = (f["rule"], f["family"])
+ if key not in seen:
+ seen.add(key)
+ deduped.append(f)
+
+ # Overloaded families (>10 types)
+ for fam, type_names in family_types.items():
+ if len(type_names) > 10:
+ deduped.append({
+ "severity": "warning",
+ "rule": "overloaded_family",
+ "family": fam,
+ "message": f"Family '{fam}' has {len(type_names)} types. Consider splitting.",
+ })
+
+ # Bad type name (leading/trailing spaces)
+ for t in types:
+ tn = t.get("type_name", "")
+ if tn != tn.strip():
+ deduped.append({
+ "severity": "error",
+ "rule": "bad_type_name",
+ "family": t.get("family"),
+ "type_name": tn,
+ "message": f"Type name '{tn}' has leading/trailing whitespace.",
+ })
+
+ return {
+ "families_total": len(set(t.get("family") for t in types if t.get("family"))),
+ "inplace_count": len(inplace_families),
+ "findings_count": len(deduped),
+ "findings": deduped,
+ }
+
+ def list_type_mappings(self, snapshot_id: str = "", category: str = "", workspace: Any = None, **_) -> Dict[str, Any]:
+ elements, types = _get_data(snapshot_id, workspace)
+
+ # Build per-family type → instances mapping
+ type_usage: Dict[str, Dict[str, int]] = defaultdict(lambda: defaultdict(int))
+ for el in elements:
+ if category and el.get("category") != category:
+ continue
+ fam = el.get("family")
+ tn = el.get("type_name")
+ if fam and tn:
+ type_usage[fam][tn] += 1
+
+ result = []
+ for fam in sorted(type_usage):
+ types_list = [
+ {"type_name": tn, "instance_count": cnt}
+ for tn, cnt in sorted(type_usage[fam].items())
+ ]
+ result.append({"family": fam, "types": types_list})
+
+ return {
+ "category_filter": category or "(all)",
+ "families_count": len(result),
+ "mappings": result,
+ }
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/parameter_manager/__init__.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/parameter_manager/__init__.py
new file mode 100644
index 0000000..d2f2691
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/parameter_manager/__init__.py
@@ -0,0 +1 @@
+# parameter_manager
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/parameter_manager/module.json b/packages/mcp-server-revit/src/revit_mcp_server/modules/parameter_manager/module.json
new file mode 100644
index 0000000..417d1fd
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/parameter_manager/module.json
@@ -0,0 +1,106 @@
+{
+ "id": "parameter_manager",
+ "name": "Parameter Manager",
+ "version": "1.0.0",
+ "schema_version": 1,
+ "min_hub_version": "1.2.0",
+ "description": "Parameter management workflows (W5): filter parameter grid, diff before/after values, plan-time validation, batch-set with inverse rollback plan, and CSV import/export.",
+ "author": "AEC Model Bridge",
+ "license": "GPL-3.0-or-later",
+ "requires_providers": ["revit", "semantic"],
+ "permissions": ["model.read", "model.write", "params.write"],
+ "commands": [
+ {
+ "id": "filter_params",
+ "title": "Filter Parameter Grid",
+ "surface": ["mcp", "panel"],
+ "execution_mode": "sync",
+ "is_mutating": false,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "snapshot_id": {"type": "string"},
+ "element_filter": {"type": "object", "description": "DSL filter to select elements."},
+ "param_name": {"type": "string", "description": "Parameter name to inspect."},
+ "include_readonly": {"type": "boolean", "default": false}
+ },
+ "required": ["element_filter", "param_name"]
+ }
+ },
+ {
+ "id": "diff_params",
+ "title": "Diff Parameter Values",
+ "surface": ["mcp"],
+ "execution_mode": "sync",
+ "is_mutating": false,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "snapshot_a_id": {"type": "string"},
+ "snapshot_b_id": {"type": "string"},
+ "param_names": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "Parameter names to compare."
+ }
+ },
+ "required": ["snapshot_a_id", "snapshot_b_id", "param_names"]
+ }
+ },
+ {
+ "id": "plan_set_params",
+ "title": "Plan Parameter Set",
+ "surface": ["mcp"],
+ "execution_mode": "sync",
+ "is_mutating": true,
+ "destructive": false,
+ "requires_plan": true,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "snapshot_id": {"type": "string"},
+ "element_filter": {"type": "object"},
+ "param_updates": {
+ "type": "object",
+ "description": "Map of param_name → new_value to apply."
+ }
+ },
+ "required": ["element_filter", "param_updates"]
+ }
+ },
+ {
+ "id": "export_params_csv",
+ "title": "Export Parameters to CSV",
+ "surface": ["mcp"],
+ "execution_mode": "sync",
+ "is_mutating": false,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "snapshot_id": {"type": "string"},
+ "element_filter": {"type": "object"},
+ "param_names": {"type": "array", "items": {"type": "string"}},
+ "output_filename": {"type": "string", "default": "params_export.csv"}
+ },
+ "required": ["element_filter", "param_names"]
+ }
+ },
+ {
+ "id": "import_params_csv",
+ "title": "Import Parameters from CSV",
+ "surface": ["mcp"],
+ "execution_mode": "sync",
+ "is_mutating": true,
+ "destructive": false,
+ "requires_plan": true,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "csv_filename": {"type": "string"},
+ "snapshot_id": {"type": "string"}
+ },
+ "required": ["csv_filename"]
+ }
+ }
+ ]
+}
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.py
new file mode 100644
index 0000000..90e51b4
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/parameter_manager/module.py
@@ -0,0 +1,376 @@
+"""
+parameter_manager module — P9.1 + P9.2 Parameter/Family/Type Workflows.
+
+Commands:
+ filter_params — Show parameter grid across matching elements.
+ diff_params — Diff parameter values between two snapshots.
+ plan_set_params — Validate params and produce an ActionPlan draft.
+ export_params_csv — Write param values to a CSV file in workspace.
+ import_params_csv — Read param updates from CSV → ActionPlan draft.
+
+Validation rules (P9.2):
+ - readonly params are blocked
+ - type-vs-instance mismatches are blocked
+ - wrong storage type writes are blocked
+ - workshared-owned elements emit a skip warning (not a hard block without Revit)
+"""
+from __future__ import annotations
+
+import csv
+import io
+import json
+import logging
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Tuple
+
+logger = logging.getLogger(__name__)
+
+# ---------------------------------------------------------------------------
+# Storage-type ↔ Python type mapping for validation
+# ---------------------------------------------------------------------------
+STORAGE_TYPE_VALIDATORS: Dict[str, type] = {
+ "String": str,
+ "Double": (int, float),
+ "Integer": int,
+ "ElementId": (int, str),
+ "Boolean": bool,
+}
+
+
+def _workspace_dir(workspace: Any) -> Path:
+ return workspace.allowed_directories[0]
+
+def _load_snapshot(snapshot_id: str, workspace: Any) -> Dict[str, Any]:
+ path = _workspace_dir(workspace) / "snapshots" / f"{snapshot_id}.json"
+ if not path.exists():
+ raise ValueError(f"Snapshot '{snapshot_id}' not found.")
+ with open(path, "r", encoding="utf-8") as f:
+ return json.load(f)
+
+def _match_element(el: Dict[str, Any], filter_dsl: Dict[str, Any]) -> bool:
+ for key, val in filter_dsl.items():
+ if key == "category":
+ cats = val if isinstance(val, list) else [val]
+ if el.get("category") not in cats:
+ return False
+ elif key == "family" and el.get("family") != val:
+ return False
+ elif key == "type_name" and el.get("type_name") != val:
+ return False
+ elif key == "level_uid" and el.get("level_uid") != val:
+ return False
+ elif key == "parameter":
+ pname = val.get("name")
+ params = el.get("params", {})
+ param = params.get(pname) if params else None
+ if val.get("empty") is True:
+ if param is not None and param.get("v") not in (None, ""):
+ return False
+ elif "value" in val:
+ if param is None or str(param.get("v")) != str(val["value"]):
+ return False
+ return True
+
+def _validate_param_update(
+ el: Dict[str, Any],
+ param_name: str,
+ new_value: Any,
+) -> Tuple[bool, Optional[str]]:
+ """Returns (ok, reason_if_blocked)."""
+ params = el.get("params", {})
+ param_info = params.get(param_name)
+
+ if param_info is None:
+ return False, f"Parameter '{param_name}' does not exist on element {el['uid']}"
+
+ # Readonly block
+ if param_info.get("readonly", False):
+ return False, f"Parameter '{param_name}' is read-only on element {el['uid']}"
+
+ # Storage type check
+ storage = param_info.get("storage")
+ if storage and storage in STORAGE_TYPE_VALIDATORS:
+ expected_type = STORAGE_TYPE_VALIDATORS[storage]
+ if not isinstance(new_value, expected_type):
+ return False, (
+ f"Parameter '{param_name}' has storage type '{storage}' "
+ f"but received value of type '{type(new_value).__name__}'"
+ )
+
+ return True, None
+
+def _make_action_plan(tool_name: str, args: Dict[str, Any], preview: Dict[str, Any]) -> Dict[str, Any]:
+ return {
+ "plan_type": "action_plan_draft",
+ "tool": tool_name,
+ "arguments": args,
+ "preview": preview,
+ "requires_approval": True,
+ }
+
+
+class ParameterManagerModule:
+
+ def filter_params(
+ self,
+ element_filter: Dict[str, Any],
+ param_name: str,
+ snapshot_id: str = "",
+ include_readonly: bool = False,
+ workspace: Any = None,
+ **_,
+ ) -> Dict[str, Any]:
+ elements = self._get_elements(snapshot_id, workspace)
+ matched = [el for el in elements if _match_element(el, element_filter)]
+
+ rows = []
+ for el in matched:
+ params = el.get("params", {})
+ pinfo = params.get(param_name)
+ if pinfo is None:
+ continue
+ if not include_readonly and pinfo.get("readonly", False):
+ continue
+ rows.append({
+ "uid": el["uid"],
+ "element_id": el.get("element_id"),
+ "category": el.get("category"),
+ "type_name": el.get("type_name"),
+ "param_name": param_name,
+ "value": pinfo.get("v"),
+ "storage": pinfo.get("storage"),
+ "readonly": pinfo.get("readonly", False),
+ "instance": pinfo.get("instance", True),
+ })
+
+ return {
+ "param_name": param_name,
+ "element_count": len(matched),
+ "rows_with_param": len(rows),
+ "rows": rows,
+ }
+
+ def diff_params(
+ self,
+ snapshot_a_id: str,
+ snapshot_b_id: str,
+ param_names: List[str],
+ workspace: Any = None,
+ **_,
+ ) -> Dict[str, Any]:
+ snap_a = _load_snapshot(snapshot_a_id, workspace)
+ snap_b = _load_snapshot(snapshot_b_id, workspace)
+
+ els_a = {el["uid"]: el for el in snap_a.get("elements", [])}
+ els_b = {el["uid"]: el for el in snap_b.get("elements", [])}
+
+ diffs = []
+ for uid, el_b in els_b.items():
+ el_a = els_a.get(uid)
+ if not el_a:
+ continue
+ for pname in param_names:
+ pinfo_a = el_a.get("params", {}).get(pname)
+ pinfo_b = el_b.get("params", {}).get(pname)
+ val_a = pinfo_a.get("v") if pinfo_a else None
+ val_b = pinfo_b.get("v") if pinfo_b else None
+ if val_a != val_b:
+ diffs.append({
+ "uid": uid,
+ "param_name": pname,
+ "before": val_a,
+ "after": val_b,
+ })
+
+ return {
+ "snapshot_a_id": snapshot_a_id,
+ "snapshot_b_id": snapshot_b_id,
+ "param_names": param_names,
+ "diffs_count": len(diffs),
+ "diffs": diffs,
+ }
+
+ def plan_set_params(
+ self,
+ element_filter: Dict[str, Any],
+ param_updates: Dict[str, Any],
+ snapshot_id: str = "",
+ workspace: Any = None,
+ **_,
+ ) -> Dict[str, Any]:
+ elements = self._get_elements(snapshot_id, workspace)
+ matched = [el for el in elements if _match_element(el, element_filter)]
+
+ planned = []
+ blocked = []
+
+ for el in matched:
+ # Simulate worksharing skip if workset is set (real Revit would check ownership)
+ workset = el.get("workset")
+ if workset:
+ # Just a warning, not a hard block without live Revit connection
+ logger.debug(f"Element {el['uid']} is on workset '{workset}' — check ownership in Revit.")
+
+ el_updates = {}
+ el_blocked = []
+
+ for pname, new_val in param_updates.items():
+ ok, reason = _validate_param_update(el, pname, new_val)
+ if ok:
+ # Record before-value for rollback
+ pinfo = el.get("params", {}).get(pname, {})
+ el_updates[pname] = {
+ "before": pinfo.get("v"),
+ "after": new_val,
+ "storage": pinfo.get("storage"),
+ }
+ else:
+ el_blocked.append({"param": pname, "reason": reason})
+
+ if el_updates:
+ planned.append({
+ "uid": el["uid"],
+ "element_id": el.get("element_id"),
+ "updates": el_updates,
+ })
+ if el_blocked:
+ blocked.extend(el_blocked)
+
+ preview = {
+ "element_count": len(matched),
+ "planned_count": len(planned),
+ "blocked_count": len(blocked),
+ "blocked": blocked,
+ "description": (
+ f"Set {list(param_updates.keys())} on {len(planned)} element(s). "
+ f"{len(blocked)} validation issue(s) blocked."
+ ),
+ }
+
+ return _make_action_plan(
+ "plan_set_params",
+ {"element_filter": element_filter, "param_updates": param_updates},
+ {**preview, "planned": planned},
+ )
+
+ def export_params_csv(
+ self,
+ element_filter: Dict[str, Any],
+ param_names: List[str],
+ snapshot_id: str = "",
+ output_filename: str = "params_export.csv",
+ workspace: Any = None,
+ **_,
+ ) -> Dict[str, Any]:
+ elements = self._get_elements(snapshot_id, workspace)
+ matched = [el for el in elements if _match_element(el, element_filter)]
+
+ output_path = _workspace_dir(workspace) / output_filename
+
+ header = ["uid", "element_id", "category", "family", "type_name"] + param_names
+ with open(output_path, "w", newline="", encoding="utf-8") as csvfile:
+ writer = csv.DictWriter(csvfile, fieldnames=header, extrasaction="ignore")
+ writer.writeheader()
+ for el in matched:
+ row = {
+ "uid": el["uid"],
+ "element_id": el.get("element_id", ""),
+ "category": el.get("category", ""),
+ "family": el.get("family", ""),
+ "type_name": el.get("type_name", ""),
+ }
+ for pname in param_names:
+ pinfo = el.get("params", {}).get(pname)
+ row[pname] = pinfo.get("v") if pinfo else ""
+ writer.writerow(row)
+
+ return {
+ "status": "exported",
+ "output_file": str(output_path),
+ "element_count": len(matched),
+ "param_names": param_names,
+ }
+
+ def import_params_csv(
+ self,
+ csv_filename: str,
+ snapshot_id: str = "",
+ workspace: Any = None,
+ **_,
+ ) -> Dict[str, Any]:
+ csv_path = _workspace_dir(workspace) / csv_filename
+ if not csv_path.exists():
+ raise ValueError(f"CSV file '{csv_filename}' not found in workspace.")
+
+ elements = self._get_elements(snapshot_id, workspace)
+ els_by_uid = {el["uid"]: el for el in elements}
+
+ planned = []
+ blocked = []
+
+ with open(csv_path, "r", encoding="utf-8") as f:
+ reader = csv.DictReader(f)
+ reserved_cols = {"uid", "element_id", "category", "family", "type_name"}
+ for row in reader:
+ uid = row.get("uid", "").strip()
+ if not uid:
+ continue
+ el = els_by_uid.get(uid)
+ if not el:
+ blocked.append({"uid": uid, "reason": "Element not found in snapshot."})
+ continue
+
+ el_updates = {}
+ for pname, val_str in row.items():
+ if pname in reserved_cols or not pname:
+ continue
+ # Try cast to appropriate type via current param storage
+ pinfo = el.get("params", {}).get(pname)
+ storage = pinfo.get("storage") if pinfo else "String"
+
+ # Cast value
+ try:
+ if storage == "Double":
+ new_val = float(val_str)
+ elif storage == "Integer":
+ new_val = int(val_str)
+ elif storage == "Boolean":
+ new_val = val_str.lower() in ("true", "1", "yes")
+ else:
+ new_val = val_str
+ except (ValueError, TypeError):
+ blocked.append({"uid": uid, "param": pname, "reason": f"Cannot cast '{val_str}' to {storage}"})
+ continue
+
+ ok, reason = _validate_param_update(el, pname, new_val)
+ if ok:
+ el_updates[pname] = {
+ "before": pinfo.get("v") if pinfo else None,
+ "after": new_val,
+ }
+ else:
+ blocked.append({"uid": uid, "param": pname, "reason": reason})
+
+ if el_updates:
+ planned.append({"uid": uid, "updates": el_updates})
+
+ preview = {
+ "csv_filename": csv_filename,
+ "planned_count": len(planned),
+ "blocked_count": len(blocked),
+ "blocked": blocked,
+ }
+
+ return _make_action_plan("import_params_csv", {"csv_filename": csv_filename}, {**preview, "planned": planned})
+
+ # -----------------------------------------------------------------------
+ # Internal helpers
+ # -----------------------------------------------------------------------
+
+ def _get_elements(self, snapshot_id: str, workspace: Any) -> List[Dict[str, Any]]:
+ if not snapshot_id:
+ from revit_mcp_server.semantic.engine import generate_mock_snapshot
+ snap = generate_mock_snapshot()
+ return [el.model_dump(by_alias=True) for el in snap.elements]
+ data = _load_snapshot(snapshot_id, workspace)
+ return data.get("elements", [])
diff --git a/packages/mcp-server-revit/tests/test_module_registry.py b/packages/mcp-server-revit/tests/test_module_registry.py
index 53a0cc1..39ccd80 100644
--- a/packages/mcp-server-revit/tests/test_module_registry.py
+++ b/packages/mcp-server-revit/tests/test_module_registry.py
@@ -65,4 +65,5 @@ async def test_module_provider_execution(tmp_path):
list_res = await provider.execute_tool("module_list_commands", {})
assert "modules" in list_res
assert len(list_res["modules"]) >= 1
- assert list_res["modules"][0]["id"] == "hello_world"
+ module_ids = {m["id"] for m in list_res["modules"]}
+ assert "hello_world" in module_ids
diff --git a/packages/mcp-server-revit/tests/test_parameter_manager.py b/packages/mcp-server-revit/tests/test_parameter_manager.py
new file mode 100644
index 0000000..cb59d77
--- /dev/null
+++ b/packages/mcp-server-revit/tests/test_parameter_manager.py
@@ -0,0 +1,196 @@
+"""Tests for Phase 9 — Parameter Manager + Family Type Mapper modules (W5, W6)."""
+import importlib.util
+import csv
+import json
+import pytest
+from pathlib import Path
+from revit_mcp_server.semantic.engine import generate_mock_snapshot
+
+
+def _load_mod(relpath: str, name: str):
+ p = Path(__file__).parent.parent / relpath
+ spec = importlib.util.spec_from_file_location(name, p)
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ return mod
+
+
+_pm = _load_mod("src/revit_mcp_server/modules/parameter_manager/module.py", "_pm_impl")
+ParameterManagerModule = _pm.ParameterManagerModule
+
+_fm = _load_mod("src/revit_mcp_server/modules/familytype_mapper/module.py", "_fm_impl")
+FamilytypeMapperModule = _fm.FamilytypeMapperModule
+
+
+class MockWorkspace:
+ def __init__(self, tmp_path: Path):
+ self.allowed_directories = [tmp_path]
+
+
+def workspace(tmp_path):
+ return MockWorkspace(tmp_path)
+
+
+def pm():
+ return ParameterManagerModule()
+
+
+def fm():
+ return FamilytypeMapperModule()
+
+
+def snap_and_ws(tmp_path):
+ ws = MockWorkspace(tmp_path)
+ snap = generate_mock_snapshot()
+ snap_dir = tmp_path / "snapshots"
+ snap_dir.mkdir(parents=True, exist_ok=True)
+ snap_path = snap_dir / f"{snap.snapshot_id}.json"
+ with open(snap_path, "w", encoding="utf-8") as f:
+ f.write(snap.model_dump_json(by_alias=True, indent=2))
+ return snap, ws
+
+
+# ===========================================================================
+# ParameterManager tests
+# ===========================================================================
+
+def test_filter_params_door_mark(pm, workspace):
+ result = pm.filter_params(
+ element_filter={"category": "OST_Doors"},
+ param_name="Mark",
+ workspace=workspace
+ )
+ assert result["param_name"] == "Mark"
+ assert result["rows_with_param"] == 1
+ assert result["rows"][0]["value"] == "D-101"
+
+
+def test_filter_params_excludes_readonly(pm, workspace):
+ result = pm.filter_params(
+ element_filter={"category": "OST_Levels"},
+ param_name="Elevation",
+ include_readonly=False,
+ workspace=workspace
+ )
+ # Elevation is readonly on levels, should be excluded
+ assert result["rows_with_param"] == 0
+
+
+def test_filter_params_includes_readonly(pm, workspace):
+ result = pm.filter_params(
+ element_filter={"category": "OST_Levels"},
+ param_name="Elevation",
+ include_readonly=True,
+ workspace=workspace
+ )
+ assert result["rows_with_param"] == 2
+
+
+def test_plan_set_params_valid(pm, workspace):
+ result = pm.plan_set_params(
+ element_filter={"category": "OST_Doors"},
+ param_updates={"Mark": "D-201"}, # String → String: valid
+ workspace=workspace,
+ )
+ assert result["plan_type"] == "action_plan_draft"
+ assert result["requires_approval"] is True
+ planned = result["preview"]["planned"]
+ assert len(planned) == 1
+ assert planned[0]["updates"]["Mark"]["after"] == "D-201"
+ assert planned[0]["updates"]["Mark"]["before"] == "D-101"
+
+
+def test_plan_set_params_blocks_readonly(pm, workspace):
+ result = pm.plan_set_params(
+ element_filter={"category": "OST_Levels"},
+ param_updates={"Elevation": 10.0}, # Elevation is readonly
+ workspace=workspace,
+ )
+ blocked = result["preview"]["blocked"]
+ assert any("read-only" in b["reason"] for b in blocked)
+ assert result["preview"]["planned_count"] == 0
+
+
+def test_plan_set_params_blocks_wrong_storage_type(pm, workspace):
+ result = pm.plan_set_params(
+ element_filter={"category": "OST_Doors"},
+ param_updates={"Mark": 12345}, # Mark is String, not int
+ workspace=workspace,
+ )
+ blocked = result["preview"]["blocked"]
+ assert any("storage type" in b["reason"] or "String" in b["reason"] for b in blocked)
+
+
+def test_export_and_import_params_csv(pm, workspace, tmp_path):
+ # 1. Export
+ export_result = pm.export_params_csv(
+ element_filter={"category": "OST_Doors"},
+ param_names=["Mark", "FireRating"],
+ output_filename="doors_export.csv",
+ workspace=workspace,
+ )
+ assert export_result["status"] == "exported"
+ csv_path = tmp_path / "doors_export.csv"
+ assert csv_path.exists()
+
+ # Validate CSV content
+ rows = list(csv.DictReader(open(csv_path, "r", encoding="utf-8")))
+ assert len(rows) == 1
+ assert rows[0]["Mark"] == "D-101"
+
+ # 2. Modify CSV and import
+ rows[0]["Mark"] = "D-999"
+ with open(csv_path, "w", newline="", encoding="utf-8") as f:
+ writer = csv.DictWriter(f, fieldnames=rows[0].keys())
+ writer.writeheader()
+ writer.writerows(rows)
+
+ import_result = pm.import_params_csv(
+ csv_filename="doors_export.csv",
+ workspace=workspace,
+ )
+ assert import_result["plan_type"] == "action_plan_draft"
+ planned = import_result["preview"]["planned"]
+ assert len(planned) == 1
+ assert planned[0]["updates"]["Mark"]["after"] == "D-999"
+
+
+# ===========================================================================
+# FamilytypeMapper tests
+# ===========================================================================
+
+def test_audit_families_no_inplace(fm, workspace):
+ result = fm.audit_families(workspace=workspace)
+ assert "families_total" in result
+ assert result["families_total"] >= 2
+ # Mock snapshot uses system + loadable families, no inplace
+ assert result["inplace_count"] == 0
+
+
+def test_audit_families_returns_findings(fm, workspace):
+ result = fm.audit_families(workspace=workspace)
+ # No findings expected from our clean mock
+ assert isinstance(result["findings"], list)
+
+
+def test_list_type_mappings_all_categories(fm, workspace):
+ result = fm.list_type_mappings(workspace=workspace)
+ assert result["families_count"] >= 1
+ for m in result["mappings"]:
+ assert "family" in m
+ assert "types" in m
+ for t in m["types"]:
+ assert "type_name" in t
+ assert "instance_count" in t
+
+
+def test_list_type_mappings_filtered_by_category(fm, workspace):
+ result = fm.list_type_mappings(category="OST_Doors", workspace=workspace)
+ assert result["category_filter"] == "OST_Doors"
+ # Only door families should appear
+ for m in result["mappings"]:
+ assert m["family"] in ("Single-Flush",)