MCP wrapper for ifcquery and ifcedit

Model Context Protocol server implementation for AI agent access to IFC
projects
This commit is contained in:
Bruno Postle
2026-02-10 22:12:44 +00:00
parent b1f1de954d
commit 060afb94b5
11 changed files with 762 additions and 0 deletions
View File
+64
View File
@@ -0,0 +1,64 @@
import pytest
import ifcopenshell
import ifcopenshell.api.aggregate
import ifcopenshell.api.owner.settings
import ifcopenshell.api.project
import ifcopenshell.api.root
import ifcopenshell.api.spatial
import ifcopenshell.api.unit
import ifcmcp.server as server_mod
@pytest.fixture
def model():
"""Create an IFC4 model with a spatial hierarchy, a wall, and a slab."""
f = ifcopenshell.api.project.create_file()
ifcopenshell.api.owner.settings.get_user = lambda ifc: (ifc.by_type("IfcPersonAndOrganization") or [None])[0]
ifcopenshell.api.owner.settings.get_application = lambda ifc: (ifc.by_type("IfcApplication") or [None])[0]
project = ifcopenshell.api.root.create_entity(f, ifc_class="IfcProject", name="TestProject")
ifcopenshell.api.unit.assign_unit(f)
site = ifcopenshell.api.root.create_entity(f, ifc_class="IfcSite", name="TestSite")
building = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuilding", name="TestBuilding")
storey = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuildingStorey", name="Ground Floor")
ifcopenshell.api.aggregate.assign_object(f, products=[site], relating_object=project)
ifcopenshell.api.aggregate.assign_object(f, products=[building], relating_object=site)
ifcopenshell.api.aggregate.assign_object(f, products=[storey], relating_object=building)
wall = ifcopenshell.api.root.create_entity(f, ifc_class="IfcWall", name="Wall001")
ifcopenshell.api.spatial.assign_container(f, products=[wall], relating_structure=storey)
slab = ifcopenshell.api.root.create_entity(f, ifc_class="IfcSlab", name="Slab001")
ifcopenshell.api.spatial.assign_container(f, products=[slab], relating_structure=storey)
return f
@pytest.fixture
def model_file(model, tmp_path):
"""Write the model fixture to a temp file and return the path."""
path = tmp_path / "test.ifc"
model.write(str(path))
return str(path)
@pytest.fixture(autouse=True)
def reset_server_state():
"""Reset module-level state before each test."""
server_mod._model = None
server_mod._model_path = None
yield
server_mod._model = None
server_mod._model_path = None
@pytest.fixture
def loaded_model(model):
"""Set the server module state to an in-memory model (no file path)."""
server_mod._model = model
server_mod._model_path = None
return model
+99
View File
@@ -0,0 +1,99 @@
import json
import pytest
from ifcmcp.server import ifc_docs, ifc_edit, ifc_list
class TestNoModel:
def test_edit_no_model(self):
with pytest.raises(ValueError, match="No model loaded"):
ifc_edit("root.create_entity")
class TestList:
def test_list_all_modules(self, loaded_model):
result = ifc_list()
assert isinstance(result, list)
assert len(result) > 0
modules = [m["module"] for m in result]
assert "root" in modules
assert "spatial" in modules
def test_list_module_functions(self, loaded_model):
result = ifc_list(module="root")
assert isinstance(result, list)
names = [f["name"] for f in result]
assert "create_entity" in names
def test_list_empty_string_returns_modules(self, loaded_model):
result = ifc_list(module="")
assert isinstance(result, list)
assert any(m["module"] == "root" for m in result)
class TestDocs:
def test_docs_create_entity(self, loaded_model):
result = ifc_docs("root.create_entity")
assert result["module"] == "root"
assert result["function"] == "create_entity"
assert "params" in result
def test_docs_bad_format(self, loaded_model):
with pytest.raises(ValueError):
ifc_docs("no_dot_here")
class TestEdit:
def test_create_entity(self, loaded_model):
result = ifc_edit("root.create_entity", json.dumps({"ifc_class": "IfcWall", "name": "NewWall"}))
assert result["ok"] is True
assert result["result"]["type"] == "IfcWall"
assert result["result"]["name"] == "NewWall"
def test_create_entity_default_params(self, loaded_model):
result = ifc_edit("root.create_entity", "{}")
assert result["ok"] is True
def test_unknown_function(self, loaded_model):
result = ifc_edit("root.nonexistent", "{}")
assert result["ok"] is False
assert "Cannot find" in result["error"]
def test_unknown_parameter(self, loaded_model):
result = ifc_edit("root.create_entity", json.dumps({"bogus": "value"}))
assert result["ok"] is False
assert "Unknown parameter" in result["error"]
def test_bad_json(self, loaded_model):
with pytest.raises(json.JSONDecodeError):
ifc_edit("root.create_entity", "not json")
def test_edit_does_not_save(self, loaded_model, tmp_path):
"""Verify that ifc_edit mutates the in-memory model but does not write to disk."""
import ifcmcp.server as server_mod
path = str(tmp_path / "test.ifc")
loaded_model.write(path)
server_mod._model_path = path
before_count = sum(1 for _ in loaded_model)
ifc_edit("root.create_entity", json.dumps({"ifc_class": "IfcWall", "name": "Unsaved"}))
after_count = sum(1 for _ in loaded_model)
assert after_count == before_count + 1
# Re-read the file — it should not have the new entity
import ifcopenshell
on_disk = ifcopenshell.open(path)
disk_count = sum(1 for _ in on_disk)
assert disk_count == before_count
def test_assign_container(self, loaded_model):
wall = loaded_model.by_type("IfcWall")[0]
storey = loaded_model.by_type("IfcBuildingStorey")[0]
result = ifc_edit(
"spatial.assign_container",
json.dumps({"products": str(wall.id()), "relating_structure": str(storey.id())}),
)
assert result["ok"] is True
+112
View File
@@ -0,0 +1,112 @@
import pytest
from ifcmcp.server import ifc_info, ifc_relations, ifc_select, ifc_summary, ifc_tree
class TestNoModel:
"""All query tools should fail when no model is loaded."""
def test_summary_no_model(self):
with pytest.raises(ValueError, match="No model loaded"):
ifc_summary()
def test_tree_no_model(self):
with pytest.raises(ValueError, match="No model loaded"):
ifc_tree()
def test_info_no_model(self):
with pytest.raises(ValueError, match="No model loaded"):
ifc_info(1)
def test_select_no_model(self):
with pytest.raises(ValueError, match="No model loaded"):
ifc_select("IfcWall")
def test_relations_no_model(self):
with pytest.raises(ValueError, match="No model loaded"):
ifc_relations(1)
class TestSummary:
def test_schema(self, loaded_model):
result = ifc_summary()
assert result["schema"] == "IFC4"
def test_total_entities(self, loaded_model):
result = ifc_summary()
assert result["total_entities"] > 0
def test_project_name(self, loaded_model):
result = ifc_summary()
assert result["project"]["name"] == "TestProject"
def test_type_counts(self, loaded_model):
result = ifc_summary()
assert result["types"]["IfcWall"] == 1
assert result["types"]["IfcSlab"] == 1
class TestTree:
def test_root_is_project(self, loaded_model):
result = ifc_tree()
assert result["type"] == "IfcProject"
assert result["name"] == "TestProject"
def test_hierarchy_depth(self, loaded_model):
result = ifc_tree()
site = result["children"][0]
assert site["type"] == "IfcSite"
building = site["children"][0]
assert building["type"] == "IfcBuilding"
storey = building["children"][0]
assert storey["type"] == "IfcBuildingStorey"
class TestInfo:
def test_wall_info(self, loaded_model):
wall = loaded_model.by_type("IfcWall")[0]
result = ifc_info(wall.id())
assert result["id"] == wall.id()
assert result["type"] == "IfcWall"
def test_invalid_id(self, loaded_model):
with pytest.raises(Exception):
ifc_info(999999)
class TestSelect:
def test_select_walls(self, loaded_model):
result = ifc_select("IfcWall")
assert len(result) == 1
assert result[0]["type"] == "IfcWall"
assert result[0]["name"] == "Wall001"
def test_select_slabs(self, loaded_model):
result = ifc_select("IfcSlab")
assert len(result) == 1
assert result[0]["name"] == "Slab001"
def test_select_no_match(self, loaded_model):
result = ifc_select("IfcWindow")
assert result == []
class TestRelations:
def test_wall_relations(self, loaded_model):
wall = loaded_model.by_type("IfcWall")[0]
result = ifc_relations(wall.id())
assert result["id"] == wall.id()
assert result["type"] == "IfcWall"
assert "hierarchy" in result
def test_traverse_up(self, loaded_model):
wall = loaded_model.by_type("IfcWall")[0]
result = ifc_relations(wall.id(), traverse="up")
assert isinstance(result, list)
assert result[0]["type"] == "IfcWall"
assert result[-1]["type"] == "IfcProject"
def test_traverse_empty_string_means_no_traverse(self, loaded_model):
wall = loaded_model.by_type("IfcWall")[0]
result = ifc_relations(wall.id(), traverse="")
assert isinstance(result, dict)
+28
View File
@@ -0,0 +1,28 @@
from ifcmcp.server import server
class TestServerRegistration:
def test_server_name(self):
assert server.name == "ifc-mcp"
def test_all_tools_registered(self):
tools = [t.name for t in server._tool_manager.list_tools()]
expected = [
"ifc_load",
"ifc_save",
"ifc_summary",
"ifc_tree",
"ifc_info",
"ifc_select",
"ifc_relations",
"ifc_clash",
"ifc_list",
"ifc_docs",
"ifc_edit",
]
for name in expected:
assert name in tools, f"Tool {name} not registered"
def test_tool_count(self):
tools = server._tool_manager.list_tools()
assert len(tools) == 11
+45
View File
@@ -0,0 +1,45 @@
import pytest
import ifcmcp.server as server_mod
from ifcmcp.server import ifc_load, ifc_save
class TestLoad:
def test_load_file(self, model_file):
result = ifc_load(model_file)
assert "IFC4" in result
assert server_mod._model is not None
assert server_mod._model_path == model_file
def test_load_sets_entity_count(self, model_file):
result = ifc_load(model_file)
assert "entities" in result
def test_load_nonexistent_file(self):
with pytest.raises(Exception):
ifc_load("/nonexistent/path/model.ifc")
class TestSave:
def test_save_no_model(self):
with pytest.raises(ValueError, match="No model loaded"):
ifc_save()
def test_save_overwrites_original(self, model_file):
ifc_load(model_file)
result = ifc_save()
assert model_file in result
def test_save_to_new_path(self, model_file, tmp_path):
ifc_load(model_file)
new_path = str(tmp_path / "output.ifc")
result = ifc_save(new_path)
assert new_path in result
import ifcopenshell
reloaded = ifcopenshell.open(new_path)
assert reloaded.schema == "IFC4"
def test_save_no_path_no_original(self, loaded_model):
with pytest.raises(ValueError, match="No path specified"):
ifc_save()