Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
feat(python): lightweight Python bridge over pyoxigraph (pip-installable lite layer)
FABIOTESS36c0dc23a5ad
diff --git a/python/.gitignore b/python/.gitignorenew file mode 100644index 00000000..86cddf80--- /dev/null+++ b/python/.gitignore@@ -0,0 +1,7 @@+.venv/+__pycache__/+*.egg-info/+.pytest_cache/+dist/+build/+*.pycdiff --git a/python/README.md b/python/README.mdnew file mode 100644index 00000000..9cab0a5c--- /dev/null+++ b/python/README.md@@ -0,0 +1,74 @@+# Open Ontologies Lite (Python bridge)++A lightweight, pip-installable Python bridge to the same [Oxigraph](https://github.com/oxigraph/oxigraph) RDF/OWL engine that powers [Open Ontologies](https://github.com/fabio-rovai/open-ontologies). **No Rust toolchain, no compilation, no multi-gigabyte build directory** — `pyoxigraph` ships the engine as a prebuilt wheel, so everything here is pure-Python glue installed from PyPI.++It exposes the core ontology lifecycle as both a Python library and an MCP server.++## Why this exists++The full Rust engine compiles a large dependency tree from source (5+ GB of build artifacts, heavy SSD churn). This bridge is the opposite trade: install in seconds, run anywhere Python runs, keep the Oxigraph SPARQL engine underneath. It covers the core surface (validate, load, query, diff, lint, convert, stats, save), not the full 100-tool engine.++## Install++```bash+pip install open-ontologies-lite # one universal wheel, no compiler+```++## Use as a Python library++```python+from open_ontologies_lite import OntologyEngine++engine = OntologyEngine()+engine.load(open("ontology.ttl").read()) # load Turtle+print(engine.stats()) # {'triples':..,'classes':..,..}++rows = engine.query(+ "SELECT ?c WHERE { ?c a <http://www.w3.org/2002/07/owl#Class> }"+)+print([r["c"] for r in rows["rows"]])++print(engine.lint()) # missing labels/domains/ranges+print(OntologyEngine.convert(ttl, "turtle", "ntriples"))+```++See [examples/python_usage.py](examples/python_usage.py) for a runnable end-to-end script.++## Use as an MCP server++```bash+open-ontologies-lite # stdio MCP server+# or: python -m open_ontologies_lite+```++Register it with any MCP client (e.g. Claude):++```json+{+ "mcpServers": {+ "open-ontologies-lite": { "command": "open-ontologies-lite" }+ }+}+```++## Tools++| Tool | Purpose |+| --- | --- |+| `onto_validate` | Parse RDF/OWL and report syntax validity + triple count (no load) |+| `onto_load` / `onto_load_file` | Load RDF text or a file into the in-memory store |+| `onto_clear` | Reset the store |+| `onto_stats` | Triple / class / property / individual counts |+| `onto_query` | SPARQL SELECT / ASK / CONSTRUCT / DESCRIBE |+| `onto_save` | Serialize the store to a file |+| `onto_convert` | Convert between Turtle / N-Triples / N-Quads / TriG / RDF-XML / N3 / JSON-LD |+| `onto_diff` | Triple-level diff between two ontologies |+| `onto_lint` | Missing labels, domains, ranges |++## Relationship to the Rust engine++This is the **Python layer** of the project. For the full engine (three-layer Dynamics/Causal/Planner architecture, HNSW semantic search, OWL2-DL tableaux reasoning, PDDL planning, governance, 100 tools), use the [Rust build](https://github.com/fabio-rovai/open-ontologies). Same Oxigraph core; pick the weight class you need.++## License++MITdiff --git a/python/examples/python_usage.py b/python/examples/python_usage.pynew file mode 100644index 00000000..93debaba--- /dev/null+++ b/python/examples/python_usage.py@@ -0,0 +1,42 @@+"""Call the engine directly from Python, no MCP, no server, no Rust toolchain.++ python examples/python_usage.py++This is the "library" face of the bridge: import it, drive Oxigraph through a+few lines of Python. The same engine is what the MCP server exposes as tools.+"""++from open_ontologies_lite import OntologyEngine++ONT = """+@prefix ex: <http://example.org/> .+@prefix owl: <http://www.w3.org/2002/07/owl#> .+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .++ex:Animal a owl:Class ; rdfs:label "Animal" .+ex:Dog a owl:Class ; rdfs:label "Dog" ; rdfs:subClassOf ex:Animal .+ex:rex a ex:Dog .+"""++# 1. validate before loading+print("validate:", OntologyEngine.validate(ONT))++# 2. load into an in-memory store+engine = OntologyEngine()+print("loaded triples:", engine.load(ONT))++# 3. stats+print("stats:", engine.stats())++# 4. SPARQL+rows = engine.query(+ "SELECT ?label WHERE { ?c a <http://www.w3.org/2002/07/owl#Class> ; "+ "<http://www.w3.org/2000/01/rdf-schema#label> ?label }"+)+print("class labels:", [r["label"] for r in rows["rows"]])++# 5. lint+print("lint:", engine.lint())++# 6. convert to N-Triples+print("ntriples:\n" + OntologyEngine.convert(ONT, "turtle", "ntriples").strip())diff --git a/python/pyproject.toml b/python/pyproject.tomlnew file mode 100644index 00000000..8d6609da--- /dev/null+++ b/python/pyproject.toml@@ -0,0 +1,36 @@+[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[project]+name = "open-ontologies-lite"+version = "0.1.0"+description = "Lightweight Python bridge to the Oxigraph RDF/OWL engine, MCP server included. No Rust toolchain, no compilation."+readme = "README.md"+requires-python = ">=3.10"+license = "MIT"+authors = [{ name = "Fabio Rovai" }]+keywords = ["ontology", "rdf", "owl", "sparql", "oxigraph", "mcp", "knowledge-graph"]+classifiers = [+ "Programming Language :: Python :: 3",+ "License :: OSI Approved :: MIT License",+ "Topic :: Scientific/Engineering",+]+dependencies = [+ "pyoxigraph>=0.5,<0.6",+ "mcp>=1.2",+]++[project.optional-dependencies]+shacl = ["pyshacl>=0.26"]+dev = ["pytest>=8"]++[project.scripts]+open-ontologies-lite = "open_ontologies_lite.server:main"++[project.urls]+Homepage = "https://github.com/fabio-rovai/open-ontologies"+Repository = "https://github.com/fabio-rovai/open-ontologies"++[tool.hatch.build.targets.wheel]+packages = ["src/open_ontologies_lite"]diff --git a/python/src/open_ontologies_lite/__init__.py b/python/src/open_ontologies_lite/__init__.pynew file mode 100644index 00000000..0996cb17--- /dev/null+++ b/python/src/open_ontologies_lite/__init__.py@@ -0,0 +1,8 @@+"""Open Ontologies Lite: a lightweight, pip-installable Python bridge to the+Oxigraph RDF/OWL engine. No Rust toolchain, no compilation, prebuilt wheels only.+"""++from .engine import OntologyEngine, ValidationResult, resolve_format++__version__ = "0.1.0"+__all__ = ["OntologyEngine", "ValidationResult", "resolve_format", "__version__"]diff --git a/python/src/open_ontologies_lite/__main__.py b/python/src/open_ontologies_lite/__main__.pynew file mode 100644index 00000000..f5f6e402--- /dev/null+++ b/python/src/open_ontologies_lite/__main__.py@@ -0,0 +1,4 @@+from .server import main++if __name__ == "__main__":+ main()diff --git a/python/src/open_ontologies_lite/engine.py b/python/src/open_ontologies_lite/engine.pynew file mode 100644index 00000000..6cc55fc0--- /dev/null+++ b/python/src/open_ontologies_lite/engine.py@@ -0,0 +1,210 @@+"""Lightweight ontology engine over a prebuilt Oxigraph store.++No compilation, no native build step: pyoxigraph ships the Oxigraph engine as a+prebuilt wheel, so everything here is pure Python glue around it. This module is+deliberately MCP-free so it can be unit-tested in isolation; server.py wires it+to the MCP transport.+"""++from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path++import pyoxigraph as ox++# Map friendly format names to Oxigraph RdfFormat values.+_FORMATS = {+ "turtle": ox.RdfFormat.TURTLE,+ "ttl": ox.RdfFormat.TURTLE,+ "ntriples": ox.RdfFormat.N_TRIPLES,+ "nt": ox.RdfFormat.N_TRIPLES,+ "nquads": ox.RdfFormat.N_QUADS,+ "nq": ox.RdfFormat.N_QUADS,+ "trig": ox.RdfFormat.TRIG,+ "rdfxml": ox.RdfFormat.RDF_XML,+ "rdf": ox.RdfFormat.RDF_XML,+ "xml": ox.RdfFormat.RDF_XML,+ "n3": ox.RdfFormat.N3,+ "jsonld": ox.RdfFormat.JSON_LD,+}++OWL_CLASS = "http://www.w3.org/2002/07/owl#Class"+RDFS_CLASS = "http://www.w3.org/2000/01/rdf-schema#Class"+RDF_PROPERTY = "http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"+++def resolve_format(name: str) -> ox.RdfFormat:+ key = name.strip().lower().lstrip(".")+ if key not in _FORMATS:+ raise ValueError(+ f"unknown format {name!r}; supported: {', '.join(sorted(set(_FORMATS)))}"+ )+ return _FORMATS[key]+++@dataclass+class ValidationResult:+ ok: bool+ triples: int+ error: str | None = None+++class OntologyEngine:+ """A single in-memory ontology store with the core lifecycle operations."""++ def __init__(self) -> None:+ self.store = ox.Store()++ # ---- validation -------------------------------------------------------+ @staticmethod+ def validate(data: str, fmt: str = "turtle") -> ValidationResult:+ """Parse RDF without loading it; report syntax validity and triple count."""+ rdf_format = resolve_format(fmt)+ try:+ count = sum(1 for _ in ox.parse(data.encode("utf-8"), format=rdf_format))+ except (SyntaxError, ValueError) as exc:+ return ValidationResult(ok=False, triples=0, error=str(exc))+ return ValidationResult(ok=True, triples=count)++ # ---- load / clear -----------------------------------------------------+ def load(self, data: str, fmt: str = "turtle") -> int:+ """Load RDF text into the store; return total triple count afterwards."""+ self.store.load(data.encode("utf-8"), format=resolve_format(fmt))+ return len(self.store)++ def load_path(self, path: str, fmt: str | None = None) -> int:+ p = Path(path)+ rdf_format = resolve_format(fmt) if fmt else ox.RdfFormat.from_extension(p.suffix.lstrip("."))+ if rdf_format is None:+ raise ValueError(f"cannot infer format from {path!r}; pass fmt explicitly")+ self.store.load(path=str(p), format=rdf_format)+ return len(self.store)++ def clear(self) -> None:+ self.store.clear()++ # ---- stats ------------------------------------------------------------+ def stats(self) -> dict[str, int]:+ return {+ "triples": len(self.store),+ "classes": self._count(+ f"SELECT (COUNT(DISTINCT ?c) AS ?n) WHERE {{ ?c a ?t "+ f"VALUES ?t {{ <{OWL_CLASS}> <{RDFS_CLASS}> }} }}"+ ),+ "properties": self._count(+ f"SELECT (COUNT(DISTINCT ?p) AS ?n) WHERE {{ ?p a <{RDF_PROPERTY}> }}"+ ),+ "individuals": self._count(+ "SELECT (COUNT(DISTINCT ?i) AS ?n) WHERE { ?i a ?t "+ f"FILTER(?t != <{OWL_CLASS}> && ?t != <{RDFS_CLASS}> && ?t != <{RDF_PROPERTY}>) }}"+ ),+ }++ def _count(self, sparql: str) -> int:+ for sol in self.store.query(sparql):+ return int(sol["n"].value)+ return 0++ # ---- query ------------------------------------------------------------+ def query(self, sparql: str) -> dict:+ """Run SPARQL. Returns a typed dict for SELECT / ASK / CONSTRUCT/DESCRIBE."""+ result = self.store.query(sparql)+ if isinstance(result, ox.QueryBoolean):+ return {"type": "boolean", "boolean": bool(result)}+ if isinstance(result, ox.QuerySolutions):+ var_objs = list(result.variables)+ names = [str(v).lstrip("?") for v in var_objs]+ rows = []+ for sol in result:+ row = {}+ for name, var in zip(names, var_objs):+ term = sol[var]+ row[name] = term.value if term is not None else None+ rows.append(row)+ return {"type": "table", "variables": names, "rows": rows}+ # QueryTriples (CONSTRUCT / DESCRIBE)+ triples = [+ {"subject": t.subject.value, "predicate": t.predicate.value, "object": t.object.value}+ for t in result+ ]+ return {"type": "graph", "triples": triples}++ # ---- save / convert ---------------------------------------------------+ def save(self, path: str, fmt: str | None = None) -> str:+ p = Path(path)+ rdf_format = resolve_format(fmt) if fmt else ox.RdfFormat.from_extension(p.suffix.lstrip("."))+ if rdf_format is None:+ raise ValueError(f"cannot infer format from {path!r}; pass fmt explicitly")+ _dump(self.store, str(p), rdf_format)+ return str(p)++ @staticmethod+ def convert(data: str, from_fmt: str, to_fmt: str) -> str:+ tmp = ox.Store()+ tmp.load(data.encode("utf-8"), format=resolve_format(from_fmt))+ out = _dump(tmp, None, resolve_format(to_fmt))+ return out.decode("utf-8") if isinstance(out, (bytes, bytearray)) else str(out)++ # ---- diff -------------------------------------------------------------+ @staticmethod+ def diff(data_a: str, data_b: str, fmt: str = "turtle") -> dict:+ """Triple-level diff between two ontologies (added/removed vs A→B)."""+ rdf_format = resolve_format(fmt)+ a = {_triple_key(t) for t in ox.parse(data_a.encode("utf-8"), format=rdf_format)}+ b = {_triple_key(t) for t in ox.parse(data_b.encode("utf-8"), format=rdf_format)}+ return {+ "added": sorted(b - a),+ "removed": sorted(a - b),+ "added_count": len(b - a),+ "removed_count": len(a - b),+ "unchanged_count": len(a & b),+ }++ # ---- lint -------------------------------------------------------------+ def lint(self) -> dict:+ """Cheap structural hygiene checks: missing labels, domains, ranges."""+ missing_labels = self._terms(+ f"SELECT DISTINCT ?c WHERE {{ ?c a ?t VALUES ?t {{ <{OWL_CLASS}> <{RDFS_CLASS}> }} "+ "FILTER NOT EXISTS {{ ?c <http://www.w3.org/2000/01/rdf-schema#label> ?l }} }"+ )+ missing_domain = self._terms(+ f"SELECT DISTINCT ?p WHERE {{ ?p a <{RDF_PROPERTY}> "+ "FILTER NOT EXISTS {{ ?p <http://www.w3.org/2000/01/rdf-schema#domain> ?d }} }"+ )+ missing_range = self._terms(+ f"SELECT DISTINCT ?p WHERE {{ ?p a <{RDF_PROPERTY}> "+ "FILTER NOT EXISTS {{ ?p <http://www.w3.org/2000/01/rdf-schema#range> ?r }} }"+ )+ issues = (+ [{"rule": "missing-label", "term": t} for t in missing_labels]+ + [{"rule": "missing-domain", "term": t} for t in missing_domain]+ + [{"rule": "missing-range", "term": t} for t in missing_range]+ )+ return {"issue_count": len(issues), "issues": issues}++ def _terms(self, sparql: str) -> list[str]:+ result = self.store.query(sparql)+ var = result.variables[0]+ out = []+ for sol in result:+ val = sol[var]+ if val is not None:+ out.append(val.value)+ return out+++def _triple_key(t) -> str:+ tr = getattr(t, "triple", t)+ return f"{tr.subject} {tr.predicate} {tr.object}"+++def _dump(store: ox.Store, output, rdf_format: ox.RdfFormat):+ """Dump a store, selecting the default graph for triples-only formats.++ A Store holds quads, so dumping to a dataset-incapable format (N-Triples,+ Turtle, RDF/XML, N3) requires naming a single graph to flatten.+ """+ if not rdf_format.supports_datasets:+ return store.dump(output=output, format=rdf_format, from_graph=ox.DefaultGraph())+ return store.dump(output=output, format=rdf_format)diff --git a/python/src/open_ontologies_lite/server.py b/python/src/open_ontologies_lite/server.pynew file mode 100644index 00000000..9e9dbf71--- /dev/null+++ b/python/src/open_ontologies_lite/server.py@@ -0,0 +1,93 @@+"""MCP server exposing the lightweight ontology engine as `onto_*` tools.++This is a thin transport layer. All real work lives in engine.py, which is pure+Python over the prebuilt pyoxigraph (Oxigraph) wheel. Run with:++ python -m open_ontologies_lite # stdio MCP server+"""++from __future__ import annotations++from mcp.server.fastmcp import FastMCP++from .engine import OntologyEngine++mcp = FastMCP(+ "open-ontologies-lite",+ instructions=(+ "Lightweight RDF/OWL ontology engine. Validate, load, query (SPARQL), "+ "diff, lint, convert, and persist ontologies in an in-memory Oxigraph store."+ ),+)++_engine = OntologyEngine()+++def onto_validate(data: str, format: str = "turtle") -> dict:+ """Parse RDF/OWL text and report syntax validity and triple count (does not load it)."""+ r = OntologyEngine.validate(data, format)+ return {"ok": r.ok, "triples": r.triples, "error": r.error}+++def onto_load(data: str, format: str = "turtle") -> dict:+ """Load RDF/OWL text into the in-memory store. Returns the total triple count."""+ return {"triples": _engine.load(data, format)}+++def onto_load_file(path: str, format: str | None = None) -> dict:+ """Load an RDF/OWL file from disk. Format is inferred from the extension if omitted."""+ return {"triples": _engine.load_path(path, format)}+++def onto_clear() -> dict:+ """Clear the in-memory store."""+ _engine.clear()+ return {"cleared": True}+++def onto_stats() -> dict:+ """Return triple, class, property, and individual counts for the loaded ontology."""+ return _engine.stats()+++def onto_query(sparql: str) -> dict:+ """Run a SPARQL query (SELECT / ASK / CONSTRUCT / DESCRIBE) against the store."""+ return _engine.query(sparql)+++def onto_save(path: str, format: str | None = None) -> dict:+ """Serialize the store to a file. Format is inferred from the extension if omitted."""+ return {"path": _engine.save(path, format)}+++def onto_convert(data: str, from_format: str, to_format: str) -> dict:+ """Convert RDF text between formats (turtle, ntriples, nquads, trig, rdfxml, n3, jsonld)."""+ return {"output": OntologyEngine.convert(data, from_format, to_format)}+++def onto_diff(data_a: str, data_b: str, format: str = "turtle") -> dict:+ """Triple-level diff between two ontologies (added/removed going A to B)."""+ return OntologyEngine.diff(data_a, data_b, format)+++def onto_lint() -> dict:+ """Structural hygiene checks on the loaded ontology: missing labels, domains, ranges."""+ return _engine.lint()+++def main() -> None:+ mcp.run(transport="stdio")+++if __name__ == "__main__":+ main()diff --git a/python/tests/test_engine.py b/python/tests/test_engine.pynew file mode 100644index 00000000..52153ddf--- /dev/null+++ b/python/tests/test_engine.py@@ -0,0 +1,82 @@+"""Engine tests. Run: pytest -q (with the package installed in the venv)."""++from open_ontologies_lite import OntologyEngine++ONT = """+@prefix ex: <http://example.org/> .+@prefix owl: <http://www.w3.org/2002/07/owl#> .+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .++ex:Animal a owl:Class ; rdfs:label "Animal" .+ex:Dog a owl:Class ; rdfs:label "Dog" ; rdfs:subClassOf ex:Animal .+ex:Cat a owl:Class .+ex:hasOwner a rdf:Property ; rdfs:domain ex:Animal ; rdfs:range ex:Person .+ex:rex a ex:Dog .+"""+++def test_validate_good():+ r = OntologyEngine.validate(ONT)+ assert r.ok and r.triples > 0 and r.error is None+++def test_validate_bad():+ r = OntologyEngine.validate("@prefix : broken")+ assert not r.ok and r.error+++def test_load_and_stats():+ e = OntologyEngine()+ e.load(ONT)+ s = e.stats()+ assert s["classes"] == 3 # Animal, Dog, Cat+ assert s["properties"] == 1 # hasOwner+ assert s["individuals"] == 1 # rex+++def test_query_select():+ e = OntologyEngine()+ e.load(ONT)+ res = e.query(+ "SELECT ?c WHERE { ?c a <http://www.w3.org/2002/07/owl#Class> }"+ )+ assert res["type"] == "table"+ assert len(res["rows"]) == 3+++def test_query_returns_values_not_none():+ e = OntologyEngine()+ e.load(ONT)+ res = e.query(+ "SELECT ?label WHERE { ?c a <http://www.w3.org/2002/07/owl#Class> ; "+ "<http://www.w3.org/2000/01/rdf-schema#label> ?label }"+ )+ labels = sorted(r["label"] for r in res["rows"])+ assert labels == ["Animal", "Dog"] # regression: must be values, not None+++def test_query_ask():+ e = OntologyEngine()+ e.load(ONT)+ res = e.query("ASK { <http://example.org/Dog> ?p ?o }")+ assert res == {"type": "boolean", "boolean": True}+++def test_lint_finds_gaps():+ e = OntologyEngine()+ e.load(ONT)+ rules = {i["rule"] for i in e.lint()["issues"]}+ assert "missing-label" in rules # ex:Cat has no label+++def test_convert_roundtrip():+ out = OntologyEngine.convert(ONT, "turtle", "ntriples")+ assert "<http://example.org/Dog>" in out+++def test_diff():+ a = "<http://x/A> <http://x/p> <http://x/B> ."+ b = "<http://x/A> <http://x/p> <http://x/C> ."+ d = OntologyEngine.diff(a, b, "ntriples")+ assert d["added_count"] == 1 and d["removed_count"] == 1