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 BCF 2.1 issue export/import module (#79)
A. Sam Mohammadb0201947d305
diff --git a/docs/bcf-exchange.md b/docs/bcf-exchange.mdnew file mode 100644index 0000000..06324b1--- /dev/null+++ b/docs/bcf-exchange.md@@ -0,0 +1,16 @@+# BCF issue exchange++Two tools move issues in and out of the standard BCF 2.1 `.bcfzip` format:++- `bcf_exchange_export_bcf` saves a list of issues, and optionally the issues recorded by the QA/QC checker, to a `.bcfzip` file in your workspace folder.+- `bcf_exchange_import_bcf` reads a `.bcfzip` from your workspace folder and returns the issues (title, description, status, priority, assigned to, element ids).++Each issue can carry `title`, `description`, `status`, `priority`, `author`, `assigned_to`, `element_uids` (Revit UniqueIds) and `ifc_guids`. Neither tool changes the Revit model.++## Safety++Files must be inside the allowed workspace directories. When reading, the zip is never unpacked to disk. Files with paths that climb out of the archive, absolute paths, symbolic links, too many entries or oversized content (zip bombs) are refused, as is any XML that declares a DOCTYPE or entity (which blocks entity expansion and external-file tricks).++## Not verified++The BCF layout was written from general knowledge of BCF 2.1. It has **not** been validated against buildingSMART's XSD schemas, and files have **not** been opened in Revit, Solibri, BIMcollab, Navisworks or any other BCF tool. Treat interoperability as UNVERIFIED. Revit UniqueIds are not IFC GUIDs, so they are stored as the authoring-tool id of a component; only IFC GUIDs given as `ifc_guids` are written as `IfcGuid`. Viewpoints contain a component selection only (no camera).diff --git a/docs/tools-generated.md b/docs/tools-generated.mdindex 80eb70d..051dc05 100644--- a/docs/tools-generated.md+++ b/docs/tools-generated.md@@ -73,6 +73,8 @@ This catalog lists all tools exposed by the AEC Model Bridge providers.| Tool Name | Description | Mutating? | Execution Type || --- | --- | --- | --- |+| `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 || `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/bcf_exchange/__init__.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/bcf_exchange/__init__.pynew file mode 100644index 0000000..34cfd5f--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/bcf_exchange/__init__.py@@ -0,0 +1 @@+# bcf_exchangediff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/bcf_exchange/module.json b/packages/mcp-server-revit/src/revit_mcp_server/modules/bcf_exchange/module.jsonnew file mode 100644index 0000000..a96a1b3--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/bcf_exchange/module.json@@ -0,0 +1,67 @@+{+ "id": "bcf_exchange",+ "name": "BCF Issue Exchange",+ "version": "1.0.0",+ "schema_version": 1,+ "min_hub_version": "1.2.0",+ "description": "Write issues (for example QA/QC findings) to a BCF 2.1 .bcfzip file and read a .bcfzip back into a plain issue list. Never changes the Revit model. UNVERIFIED for interop with other BCF tools.",+ "author": "AEC Model Bridge",+ "license": "GPL-3.0-or-later",+ "requires_providers": [],+ "permissions": ["files.write"],+ "commands": [+ {+ "id": "export_bcf",+ "title": "Export Issues to BCF",+ "surface": ["mcp", "panel"],+ "execution_mode": "sync",+ "is_mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "output_path": {+ "type": "string",+ "description": "Where to save the .bcfzip file. Must end in .bcfzip and be inside the allowed workspace directories. A relative path is placed in the workspace folder."+ },+ "issues": {+ "type": "array",+ "description": "Issues to export. Each issue may have title, description, status, priority, element_uids (Revit UniqueIds), ifc_guids, author and assigned_to.",+ "items": {"type": "object"}+ },+ "use_qaqc_issues": {+ "type": "boolean",+ "description": "Also export the issues recorded by the QA/QC checker for this workspace.",+ "default": false+ },+ "project_name": {+ "type": "string",+ "description": "Optional project name stored in the file."+ },+ "overwrite": {+ "type": "boolean",+ "description": "Replace the file if it already exists.",+ "default": false+ }+ },+ "required": ["output_path"]+ }+ },+ {+ "id": "import_bcf",+ "title": "Import Issues from BCF",+ "surface": ["mcp", "panel"],+ "execution_mode": "sync",+ "is_mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "bcf_path": {+ "type": "string",+ "description": "The .bcfzip file to read. Must be inside the allowed workspace directories."+ }+ },+ "required": ["bcf_path"]+ }+ }+ ]+}diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/bcf_exchange/module.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/bcf_exchange/module.pynew file mode 100644index 0000000..e22f128--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/bcf_exchange/module.py@@ -0,0 +1,394 @@+"""+bcf_exchange module - BCF 2.1 issue export / import.++Commands:+ export_bcf - write a list of issues (and optionally the QA/QC issue store) to a .bcfzip.+ import_bcf - read a .bcfzip back into a plain list of issues.++UNVERIFIED: the BCF structure is written from general knowledge of BCF 2.1. It has+NOT been validated against buildingSMART's XSDs or opened in any other BCF tool.+The module never touches the Revit model; the only file it writes is the .bcfzip.++Safety: zip files are only ever read in memory (nothing is extracted to disk) and+are checked for path traversal, absolute paths, symlinks, too many entries and+decompression bombs. XML containing a DOCTYPE or ENTITY declaration is refused+before parsing, which blocks entity expansion and external entities.+"""+from __future__ import annotations++import os+import re+import sqlite3+import stat+import tempfile+import uuid+import zipfile+import xml.etree.ElementTree as ET+from datetime import datetime, timezone+from pathlib import Path, PurePosixPath+from typing import Any, Dict, List, Optional++BCF_EXTENSION = ".bcfzip"+MAX_ENTRIES = 5000+MAX_ENTRY_BYTES = 10 * 1024 * 1024+MAX_TOTAL_BYTES = 100 * 1024 * 1024+MAX_RATIO = 200 # uncompressed / compressed, for entries over 1 MiB+MAX_TOPICS = 2000+MAX_COMPONENTS_PER_TOPIC = 10000+QAQC_DB = "qaqc_issues.db"++_IFC_GUID_RE = re.compile(r"^[0-9A-Za-z_$]{22}$")+def _is_bad_xml_char(ch: str) -> bool:+ """True for characters that are not allowed in XML 1.0 text."""+ code = ord(ch)+ return (+ code < 0x20 and code not in (0x09, 0x0A, 0x0D)+ or 0xD800 <= code <= 0xDFFF+ or code in (0xFFFE, 0xFFFF)+ )+_GUID_RE = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")+++class BcfError(ValueError):+ pass+++# ---------------------------------------------------------------------------+# Path sandbox+# ---------------------------------------------------------------------------++def _resolve_in_workspace(path_str: str, workspace: Any) -> Path:+ roots = [Path(r).resolve() for r in getattr(workspace, "allowed_directories", []) or []]+ if not roots:+ raise BcfError("A workspace is required.")+ if not path_str or "\x00" in path_str:+ raise BcfError("A file path is required.")+ candidate = Path(path_str)+ if not candidate.is_absolute():+ candidate = roots[0] / candidate+ resolved = candidate.resolve()+ if not any(resolved.is_relative_to(r) for r in roots):+ raise BcfError(f"'{resolved}' is outside the allowed workspace directories.")+ return resolved+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def _clean(text: Any) -> str:+ return "".join(ch for ch in ("" if text is None else str(text)) if not _is_bad_xml_char(ch))+++def _now() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def _as_list(value: Any) -> List[str]:+ if value is None:+ return []+ if isinstance(value, str):+ return [value] if value else []+ return [str(v) for v in value if v not in (None, "")]+++def _qaqc_issues(workspace: Any) -> List[Dict[str, Any]]:+ db = Path(workspace.allowed_directories[0]) / QAQC_DB+ if not db.exists():+ return []+ conn = sqlite3.connect(f"file:{db.as_posix()}?mode=ro", uri=True)+ conn.row_factory = sqlite3.Row+ try:+ rows = conn.execute("SELECT * FROM issues").fetchall()+ finally:+ conn.close()+ sev_to_prio = {"error": "High", "warning": "Normal", "info": "Low"}+ out = []+ for row in rows:+ r = dict(row)+ out.append({+ "id": r.get("id"),+ "title": f"{r.get('rule_id')}: {r.get('label') or ''}".strip(": "),+ "description": r.get("message") or "",+ "status": "Closed" if r.get("status") == "resolved" else "Open",+ "priority": sev_to_prio.get(r.get("severity"), "Normal"),+ "element_uids": _as_list(r.get("element_uid")),+ "created": r.get("created_at"),+ })+ return out+++def _normalise_issue(raw: Any, index: int) -> Dict[str, Any]:+ if not isinstance(raw, dict):+ raise BcfError(f"Issue {index + 1} must be an object with a title and description.")+ guid = str(raw.get("id") or raw.get("guid") or "")+ if not _GUID_RE.match(guid):+ guid = str(uuid.uuid4())+ title = _clean(raw.get("title")).strip() or f"Issue {index + 1}"+ return {+ "id": guid.lower(),+ "title": title,+ "description": _clean(raw.get("description") or raw.get("message")),+ "status": _clean(raw.get("status")) or "Open",+ "priority": _clean(raw.get("priority")),+ "author": _clean(raw.get("author")) or "aec-model-bridge",+ "assigned_to": _clean(raw.get("assigned_to")),+ "created": _clean(raw.get("created")) or _now(),+ "element_uids": [_clean(x) for x in _as_list(raw.get("element_uids"))],+ "ifc_guids": [_clean(x) for x in _as_list(raw.get("ifc_guids"))],+ }+++# ---------------------------------------------------------------------------+# Writing+# ---------------------------------------------------------------------------++def _xml_bytes(root: ET.Element) -> bytes:+ return ET.tostring(root, encoding="utf-8", xml_declaration=True)+++def _build_markup(issue: Dict[str, Any], viewpoint_guid: str) -> bytes:+ root = ET.Element("Markup")+ header = ET.SubElement(root, "Header")+ ET.SubElement(header, "File", {"isExternal": "false"})+ topic = ET.SubElement(root, "Topic", {"Guid": issue["id"], "TopicType": "Issue", "TopicStatus": issue["status"]})+ ET.SubElement(topic, "Title").text = issue["title"]+ if issue["priority"]:+ ET.SubElement(topic, "Priority").text = issue["priority"]+ ET.SubElement(topic, "CreationDate").text = issue["created"]+ ET.SubElement(topic, "CreationAuthor").text = issue["author"]+ if issue["assigned_to"]:+ ET.SubElement(topic, "AssignedTo").text = issue["assigned_to"]+ if issue["description"]:+ ET.SubElement(topic, "Description").text = issue["description"]+ if issue["element_uids"] or issue["ifc_guids"]:+ vp = ET.SubElement(root, "Viewpoints", {"Guid": viewpoint_guid})+ ET.SubElement(vp, "Viewpoint").text = "viewpoint.bcfv"+ return _xml_bytes(root)+++def _build_viewpoint(issue: Dict[str, Any], viewpoint_guid: str) -> bytes:+ root = ET.Element("VisualizationInfo", {"Guid": viewpoint_guid})+ comps = ET.SubElement(root, "Components")+ sel = ET.SubElement(comps, "Selection")+ for guid in issue["ifc_guids"]:+ ET.SubElement(sel, "Component", {"IfcGuid": guid})+ for uid in issue["element_uids"]:+ if _IFC_GUID_RE.match(uid):+ ET.SubElement(sel, "Component", {"IfcGuid": uid})+ else:+ # Revit UniqueIds are not IFC GUIDs; keep them as the authoring-tool id.+ comp = ET.SubElement(sel, "Component")+ ET.SubElement(comp, "OriginatingSystem").text = "Revit"+ ET.SubElement(comp, "AuthoringToolId").text = uid+ # BCF 2.1 requires Visibility after Selection.+ ET.SubElement(comps, "Visibility", {"DefaultVisibility": "true"})+ return _xml_bytes(root)+++def _write_bcf(path: Path, issues: List[Dict[str, Any]], project_name: str) -> None:+ version = ET.Element("Version", {"VersionId": "2.1"})+ ET.SubElement(version, "DetailedVersion").text = "2.1"+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), suffix=".tmp")+ os.close(fd)+ try:+ with zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as zf:+ zf.writestr("bcf.version", _xml_bytes(version))+ if project_name:+ proj = ET.Element("ProjectExtension")+ p = ET.SubElement(proj, "Project", {"ProjectId": str(uuid.uuid4())})+ ET.SubElement(p, "Name").text = project_name+ ET.SubElement(proj, "ExtensionSchema")+ zf.writestr("project.bcfp", _xml_bytes(proj))+ for issue in issues:+ # BCF 2.1 expects an explicit directory entry per topic.+ zf.writestr(zipfile.ZipInfo(f"{issue['id']}/"), b"")+ vp_guid = str(uuid.uuid4())+ zf.writestr(f"{issue['id']}/markup.bcf", _build_markup(issue, vp_guid))+ if issue["element_uids"] or issue["ifc_guids"]:+ zf.writestr(f"{issue['id']}/viewpoint.bcfv", _build_viewpoint(issue, vp_guid))+ os.replace(tmp, path)+ finally:+ if os.path.exists(tmp):+ os.unlink(tmp)+++# ---------------------------------------------------------------------------+# Reading (hardened)+# ---------------------------------------------------------------------------++def _check_member_name(name: str) -> None:+ if not name or "\x00" in name or "\\" in name:+ raise BcfError(f"Unsafe entry name in zip: {name!r}")+ if name.startswith("/") or re.match(r"^[A-Za-z]:", name):+ raise BcfError(f"Absolute path in zip: {name!r}")+ if ".." in PurePosixPath(name).parts:+ raise BcfError(f"Path traversal in zip: {name!r}")+++def _read_member(zf: zipfile.ZipFile, info: zipfile.ZipInfo) -> bytes:+ # Do not trust the declared size: read with a hard cap.+ with zf.open(info) as fh:+ data = fh.read(MAX_ENTRY_BYTES + 1)+ if len(data) > MAX_ENTRY_BYTES:+ raise BcfError(f"Zip entry '{info.filename}' is too large (limit {MAX_ENTRY_BYTES} bytes).")+ return data+++def _safe_xml(data: bytes, name: str) -> ET.Element:+ # UTF-16/32 would hide the markers below; BCF is UTF-8.+ if data[:2] in (b"\xff\xfe", b"\xfe\xff") or b"\x00" in data[:4]:+ raise BcfError(f"'{name}' must be UTF-8 XML.")+ upper = data.upper()+ if b"<!DOCTYPE" in upper or b"<!ENTITY" in upper:+ raise BcfError(f"'{name}' contains a DOCTYPE/ENTITY declaration, which is not allowed.")+ try:+ return ET.fromstring(data)+ except ET.ParseError as exc:+ raise BcfError(f"'{name}' is not valid XML: {exc}") from exc+++def _local(tag: str) -> str:+ return tag.rsplit("}", 1)[-1]+++def _child_text(parent: ET.Element, name: str) -> str:+ for ch in parent:+ if _local(ch.tag) == name:+ return (ch.text or "").strip()+ return ""+++def _parse_topic(markup: ET.Element, viewpoints: List[ET.Element]) -> Dict[str, Any]:+ topic = next((c for c in markup if _local(c.tag) == "Topic"), None)+ if topic is None:+ raise BcfError("markup.bcf has no Topic element.")+ ifc_guids: List[str] = []+ element_uids: List[str] = []+ for vp in viewpoints:+ count = 0+ for comp in vp.iter():+ if _local(comp.tag) != "Component":+ continue+ count += 1+ if count > MAX_COMPONENTS_PER_TOPIC:+ raise BcfError("Too many components in one viewpoint.")+ guid = comp.attrib.get("IfcGuid")+ if guid and guid not in ifc_guids:+ ifc_guids.append(guid)+ for ch in comp:+ if _local(ch.tag) == "AuthoringToolId" and ch.text and ch.text.strip() not in element_uids:+ element_uids.append(ch.text.strip())+ return {+ "id": topic.attrib.get("Guid", ""),+ "title": _child_text(topic, "Title"),+ "description": _child_text(topic, "Description"),+ "status": topic.attrib.get("TopicStatus", ""),+ "priority": _child_text(topic, "Priority"),+ "author": _child_text(topic, "CreationAuthor"),+ "assigned_to": _child_text(topic, "AssignedTo"),+ "created": _child_text(topic, "CreationDate"),+ "element_uids": element_uids,+ "ifc_guids": ifc_guids,+ }+++def _read_bcf(path: Path) -> Dict[str, Any]:+ try:+ zf = zipfile.ZipFile(path)+ except zipfile.BadZipFile as exc:+ raise BcfError("The file is not a valid zip/.bcfzip archive.") from exc+ with zf:+ infos = zf.infolist()+ if len(infos) > MAX_ENTRIES:+ raise BcfError(f"Too many entries in zip ({len(infos)}; limit {MAX_ENTRIES}).")+ total = 0+ for info in infos:+ _check_member_name(info.filename)+ if stat.S_ISLNK(info.external_attr >> 16):+ raise BcfError(f"Symbolic link in zip: {info.filename!r}")+ total += info.file_size+ if info.file_size > MAX_ENTRY_BYTES:+ raise BcfError(f"Zip entry '{info.filename}' is too large.")+ if info.file_size > 1024 * 1024 and info.compress_size and info.file_size / info.compress_size > MAX_RATIO:+ raise BcfError(f"Zip entry '{info.filename}' has a suspicious compression ratio.")+ if total > MAX_TOTAL_BYTES:+ raise BcfError("Zip is too large when uncompressed.")++ by_name = {i.filename: i for i in infos if not i.is_dir()}+ version = ""+ if "bcf.version" in by_name:+ vroot = _safe_xml(_read_member(zf, by_name["bcf.version"]), "bcf.version")+ version = vroot.attrib.get("VersionId", "")++ folders = sorted({n.split("/", 1)[0] for n in by_name if n.count("/") == 1 and n.endswith("/markup.bcf")})+ if len(folders) > MAX_TOPICS:+ raise BcfError(f"Too many topics ({len(folders)}; limit {MAX_TOPICS}).")+ issues = []+ for folder in folders:+ markup = _safe_xml(_read_member(zf, by_name[f"{folder}/markup.bcf"]), f"{folder}/markup.bcf")+ vps = [+ _safe_xml(_read_member(zf, by_name[n]), n)+ for n in sorted(by_name)+ if n.startswith(folder + "/") and n.endswith(".bcfv")+ ]+ issue = _parse_topic(markup, vps)+ if not issue["id"]:+ issue["id"] = folder+ issues.append(issue)+ return {"bcf_version": version, "issues": issues}+++# ---------------------------------------------------------------------------+# Module class+# ---------------------------------------------------------------------------++class BcfExchangeModule:++ def export_bcf(+ self,+ output_path: str,+ issues: Optional[List[Dict[str, Any]]] = None,+ use_qaqc_issues: bool = False,+ project_name: str = "",+ overwrite: bool = False,+ workspace: Any = None,+ **_,+ ) -> Dict[str, Any]:+ if not output_path.lower().endswith(BCF_EXTENSION):+ raise BcfError(f"The output file name must end in {BCF_EXTENSION}.")+ path = _resolve_in_workspace(output_path, workspace)+ if path.exists() and not overwrite:+ raise BcfError(f"'{path}' already exists. Set overwrite to replace it.")+ raw = list(issues or [])+ if use_qaqc_issues:+ raw.extend(_qaqc_issues(workspace))+ normalised = [_normalise_issue(r, i) for i, r in enumerate(raw)]+ seen = set()+ for issue in normalised:+ if issue["id"] in seen:+ issue["id"] = str(uuid.uuid4())+ seen.add(issue["id"])+ path.parent.mkdir(parents=True, exist_ok=True)+ _write_bcf(path, normalised, _clean(project_name))+ return {+ "status": "written",+ "path": str(path),+ "issue_count": len(normalised),+ "bcf_version": "2.1",+ "warning": "UNVERIFIED: not validated against buildingSMART XSDs or other BCF tools.",+ }++ def import_bcf(self, bcf_path: str, workspace: Any = None, **_) -> Dict[str, Any]:+ path = _resolve_in_workspace(bcf_path, workspace)+ if not path.is_file():+ raise BcfError(f"File '{path}' not found.")+ result = _read_bcf(path)+ return {+ "status": "read",+ "path": str(path),+ "bcf_version": result["bcf_version"],+ "issue_count": len(result["issues"]),+ "issues": result["issues"],+ "warning": "UNVERIFIED: parsing is not validated against buildingSMART XSDs or other BCF tools.",+ }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 5cc5090..dd08ec6 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_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.","qaqc_checker_list_rules": "List the QA/QC rules that are available, optionally for one rule pack. 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.",+ "bcf_exchange_import_bcf": "Read a BCF .bcfzip file from the workspace and return its issues (title, description, status, priority, element ids). Read-only; unsafe zip files are refused.","recipe_runner_run_recipe": "Run a named automation recipe (a YAML-defined sequence of tool calls) with arguments; set dry_run to list the steps without executing them.","recipe_runner_list_recipes": "List the available automation recipes. Read-only.","recipe_runner_list_runs": "List past recipe runs, optionally for one recipe. Read-only.",@@ -479,6 +481,7 @@ NOT_READ_ONLY: dict[str, tuple[bool, bool]] = {"report_generator_export_sqlite_summary": (False, True),"model_inspector_save_query": (False, True),"selection_tools_save_selection": (False, True),+ "bcf_exchange_export_bcf": (False, True),"qaqc_checker_run_check": (False, False),"qaqc_checker_resolve_issue": (False, True),"recipe_runner_run_recipe": (True, False),diff --git a/packages/mcp-server-revit/tests/test_bcf_exchange.py b/packages/mcp-server-revit/tests/test_bcf_exchange.pynew file mode 100644index 0000000..35fa8c7--- /dev/null+++ b/packages/mcp-server-revit/tests/test_bcf_exchange.py@@ -0,0 +1,269 @@+"""Tests for the BCF 2.1 export/import module (UNVERIFIED against other BCF tools)."""+import importlib.util+import os+import sqlite3+import stat+import zipfile+from pathlib import Path++import pytest+++def _load():+ p = Path(__file__).parent.parent / "src/revit_mcp_server/modules/bcf_exchange/module.py"+ spec = importlib.util.spec_from_file_location("_bcf_impl", p)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++bcf = _load()+++class WS:+ def __init__(self, p):+ self.allowed_directories = [p]+++def ws(tmp_path):+ root = tmp_path / "ws"+ root.mkdir()+ return WS(root)+++def mod():+ return bcf.BcfExchangeModule()+++def _zip(path, entries):+ with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as zf:+ for name, data in entries:+ zf.writestr(name, data)+ return path+++MARKUP = b'<?xml version="1.0"?><Markup><Topic Guid="g1" TopicStatus="Open"><Title>T</Title></Topic></Markup>'+++def test_round_trip(mod, ws):+ issues = [+ {"title": "Door has no mark", "description": "Fix & <check>", "status": "Open", "priority": "High",+ "element_uids": ["abc-uid-1", "2O2Fr$t4X7Zf8NOew3FLOH"], "ifc_guids": ["0DWgwt6o1FOx7466fPk$jl"],+ "author": "sam", "assigned_to": "bob"},+ {"title": "No elements", "description": "plain"},+ ]+ out = mod.export_bcf("issues.bcfzip", issues=issues, workspace=ws)+ assert out["issue_count"] == 2+ res = mod.import_bcf(out["path"], workspace=ws)+ assert res["bcf_version"] == "2.1"+ by_title = {i["title"]: i for i in res["issues"]}+ d = by_title["Door has no mark"]+ assert d["description"] == "Fix & <check>"+ assert d["priority"] == "High" and d["status"] == "Open" and d["assigned_to"] == "bob"+ assert "abc-uid-1" in d["element_uids"]+ assert set(d["ifc_guids"]) == {"0DWgwt6o1FOx7466fPk$jl", "2O2Fr$t4X7Zf8NOew3FLOH"}+ assert by_title["No elements"]["element_uids"] == []+++def test_empty_list(mod, ws):+ out = mod.export_bcf("empty.bcfzip", issues=[], workspace=ws)+ assert out["issue_count"] == 0+ res = mod.import_bcf("empty.bcfzip", workspace=ws)+ assert res["issues"] == [] and res["bcf_version"] == "2.1"+++def test_qaqc_issues_exported(mod, ws):+ db = ws.allowed_directories[0] / "qaqc_issues.db"+ conn = sqlite3.connect(db)+ conn.execute("CREATE TABLE issues (id TEXT, doc_guid TEXT, rule_id TEXT, severity TEXT, element_uid TEXT,"+ " label TEXT, message TEXT, fix_template TEXT, status TEXT, created_at TEXT, updated_at TEXT)")+ conn.execute("INSERT INTO issues VALUES ('i1','d','door_missing_mark','error','uid-9','Door','No mark','', 'open','2026-01-01T00:00:00Z','x')")+ conn.commit()+ conn.close()+ mod.export_bcf("q.bcfzip", use_qaqc_issues=True, workspace=ws)+ res = mod.import_bcf("q.bcfzip", workspace=ws)+ assert res["issue_count"] == 1+ assert res["issues"][0]["priority"] == "High"+ assert res["issues"][0]["element_uids"] == ["uid-9"]+++def test_export_no_overwrite_and_extension(mod, ws):+ mod.export_bcf("a.bcfzip", issues=[], workspace=ws)+ with pytest.raises(bcf.BcfError):+ mod.export_bcf("a.bcfzip", issues=[], workspace=ws)+ mod.export_bcf("a.bcfzip", issues=[], overwrite=True, workspace=ws)+ with pytest.raises(bcf.BcfError):+ mod.export_bcf("a.zip", issues=[], workspace=ws)+++def test_bad_issue_shape(mod, ws):+ with pytest.raises(bcf.BcfError):+ mod.export_bcf("b.bcfzip", issues=["nope"], workspace=ws)+++# --- sandbox ---++def test_sandbox_rejects_outside_paths(mod, ws, tmp_path):+ with pytest.raises(bcf.BcfError):+ mod.export_bcf(str(tmp_path / "outside.bcfzip"), issues=[], workspace=ws)+ with pytest.raises(bcf.BcfError):+ mod.export_bcf("../escape.bcfzip", issues=[], workspace=ws)+ outside = _zip(tmp_path / "o.bcfzip", [("bcf.version", b"<Version VersionId='2.1'/>")])+ with pytest.raises(bcf.BcfError):+ mod.import_bcf(str(outside), workspace=ws)+ assert not (tmp_path / "escape.bcfzip").exists()+++def test_sandbox_rejects_symlink_escape(mod, ws, tmp_path):+ target = _zip(tmp_path / "t.bcfzip", [("bcf.version", b"<Version VersionId='2.1'/>")])+ link = ws.allowed_directories[0] / "link.bcfzip"+ link.symlink_to(target)+ with pytest.raises(bcf.BcfError):+ mod.import_bcf("link.bcfzip", workspace=ws)+++# --- malicious zips ---+[email protected]("name", ["../evil.txt", "g/../../evil.txt", "/abs/evil.txt", "C:/evil.txt", "a\\b.txt"])+def test_rejects_bad_entry_names(mod, ws, name):+ _zip(ws.allowed_directories[0] / "m.bcfzip", [("g1/markup.bcf", MARKUP), (name, b"x")])+ if name == "a\\b.txt" and os.sep == "\\":+ # On Windows zipfile itself rewrites '\\' to '/' when writing and reading, so the+ # reader only ever sees the harmless relative name 'a/b.txt': nothing to reject.+ assert mod.import_bcf("m.bcfzip", workspace=ws)["issue_count"] == 1+ return+ with pytest.raises(bcf.BcfError):+ mod.import_bcf("m.bcfzip", workspace=ws)+++def test_rejects_symlink_entry(mod, ws):+ p = ws.allowed_directories[0] / "s.bcfzip"+ with zipfile.ZipFile(p, "w") as zf:+ info = zipfile.ZipInfo("g1/link")+ info.external_attr = (stat.S_IFLNK | 0o777) << 16+ zf.writestr(info, "/etc/passwd")+ with pytest.raises(bcf.BcfError):+ mod.import_bcf("s.bcfzip", workspace=ws)+++def test_rejects_zip_bomb_entry(mod, ws):+ big = b"0" * (bcf.MAX_ENTRY_BYTES + 1024)+ _zip(ws.allowed_directories[0] / "b.bcfzip", [("g1/markup.bcf", big)])+ with pytest.raises(bcf.BcfError):+ mod.import_bcf("b.bcfzip", workspace=ws)+++def test_rejects_high_ratio(mod, ws):+ data = b"0" * (2 * 1024 * 1024)+ _zip(ws.allowed_directories[0] / "r.bcfzip", [("g1/markup.bcf", data)])+ with pytest.raises(bcf.BcfError):+ mod.import_bcf("r.bcfzip", workspace=ws)+++def test_rejects_too_many_entries(mod, ws, monkeypatch):+ monkeypatch.setattr(bcf, "MAX_ENTRIES", 5)+ _zip(ws.allowed_directories[0] / "n.bcfzip", [(f"g{i}/x.txt", b"x") for i in range(6)])+ with pytest.raises(bcf.BcfError):+ mod.import_bcf("n.bcfzip", workspace=ws)+++def test_rejects_xxe_and_entity_expansion(mod, ws):+ xxe = (b'<?xml version="1.0"?><!DOCTYPE m [<!ENTITY x SYSTEM "file:///etc/passwd">]>'+ b'<Markup><Topic Guid="g1"><Title>&x;</Title></Topic></Markup>')+ _zip(ws.allowed_directories[0] / "x.bcfzip", [("g1/markup.bcf", xxe)])+ with pytest.raises(bcf.BcfError, match="DOCTYPE"):+ mod.import_bcf("x.bcfzip", workspace=ws)+ lol = (b'<?xml version="1.0"?><!doctype l [<!ENTITY a "aaaa"><!ENTITY b "&a;&a;&a;&a;">]>'+ b'<Markup><Topic Guid="g1"><Title>&b;</Title></Topic></Markup>')+ _zip(ws.allowed_directories[0] / "l.bcfzip", [("g1/markup.bcf", lol)])+ with pytest.raises(bcf.BcfError):+ mod.import_bcf("l.bcfzip", workspace=ws)+++def test_rejects_utf16_xml(mod, ws):+ data = '<?xml version="1.0" encoding="utf-16"?><!DOCTYPE m [<!ENTITY x "y">]><Markup/>'.encode("utf-16")+ _zip(ws.allowed_directories[0] / "u.bcfzip", [("g1/markup.bcf", data)])+ with pytest.raises(bcf.BcfError):+ mod.import_bcf("u.bcfzip", workspace=ws)+++def test_not_a_zip_and_missing(mod, ws):+ (ws.allowed_directories[0] / "junk.bcfzip").write_bytes(b"not a zip")+ with pytest.raises(bcf.BcfError):+ mod.import_bcf("junk.bcfzip", workspace=ws)+ with pytest.raises(bcf.BcfError):+ mod.import_bcf("missing.bcfzip", workspace=ws)+++def test_tools_listed_via_registry(tmp_path):+ from revit_mcp_server.config import Config+ from revit_mcp_server.module_registry import ModuleRegistry++ cfg = Config(workspace_dir=tmp_path, allowed_directories=[tmp_path], audit_log=tmp_path / "a.log",+ enable_user_modules=False)+ reg = ModuleRegistry(config_obj=cfg)+ reg.discover_and_load()+ m = reg.get_module("bcf_exchange")+ assert m is not None and not any(c.is_mutating for c in m.manifest.commands)+++# --- BCF 2.1 schema-shape regressions (review findings) ---++def _exported(mod, ws, project_name=""):+ issues = [{"title": "T", "element_uids": ["abc-uid-1", "2O2Fr$t4X7Zf8NOew3FLOH"]}]+ out = mod.export_bcf("s.bcfzip", issues=issues, project_name=project_name, workspace=ws)+ return zipfile.ZipFile(out["path"])+++def test_file_attribute_is_isExternal(mod, ws):+ zf = _exported(mod, ws)+ name = next(n for n in zf.namelist() if n.endswith("markup.bcf"))+ data = zf.read(name).decode()+ assert 'isExternal="false"' in data and "IsExternal" not in data+++def test_viewpoint_guid_shared_between_markup_and_visinfo(mod, ws):+ import xml.etree.ElementTree as ET+ zf = _exported(mod, ws)+ markup = ET.fromstring(zf.read(next(n for n in zf.namelist() if n.endswith("markup.bcf"))))+ vis = ET.fromstring(zf.read(next(n for n in zf.namelist() if n.endswith(".bcfv"))))+ assert markup.find("Viewpoints").attrib["Guid"] == vis.attrib["Guid"]+++def test_components_have_visibility_and_child_originating_system(mod, ws):+ import xml.etree.ElementTree as ET+ zf = _exported(mod, ws)+ vis = ET.fromstring(zf.read(next(n for n in zf.namelist() if n.endswith(".bcfv"))))+ comps = vis.find("Components")+ assert [c.tag for c in comps] == ["Selection", "Visibility"]+ revit = [c for c in comps.find("Selection") if "IfcGuid" not in c.attrib]+ assert revit and all("OriginatingSystem" not in c.attrib for c in revit)+ assert [ch.tag for ch in revit[0]] == ["OriginatingSystem", "AuthoringToolId"]+++def test_project_file_has_extension_schema(mod, ws):+ import xml.etree.ElementTree as ET+ zf = _exported(mod, ws, project_name="P")+ proj = ET.fromstring(zf.read("project.bcfp"))+ assert [c.tag for c in proj] == ["Project", "ExtensionSchema"]+++def test_topic_directory_entries_present(mod, ws):+ zf = _exported(mod, ws)+ folder = next(n for n in zf.namelist() if n.endswith("markup.bcf")).split("/")[0]+ names = zf.namelist()+ assert f"{folder}/" in names+ assert names.index(f"{folder}/") < names.index(f"{folder}/markup.bcf")+++def test_round_trip_still_reads_revit_ids_after_schema_fix(mod, ws):+ _exported(mod, ws)+ res = mod.import_bcf("s.bcfzip", workspace=ws)+ assert res["issues"][0]["element_uids"] == ["abc-uid-1"]+++def test_clean_strips_invalid_xml_chars():+ assert bcf._clean("a\x00b\x0bcd\x1fe\ud800f") == "abcdef"+ assert bcf._clean("tab\tnl\n ok") == "tab\tnl\n ok"