Skip to content

Hypergraph is more powerful. Transform unstructured text into structured knowledge with LLMs. Graphs, hypergraphs, and spatio-temporal extractions — with one command.

Merge PR #147 with #146: keep both JSON-LD and Cypher MCP export tools

yifanfeng9755ff878e7fb5
diff --cc docs/en/mcp.md
index cdde2e1,0bcd763..c4274d9
--- a/docs/en/mcp.md
+++ b/docs/en/mcp.md
@@@ -48,11 -48,11 +48,19 @@@ Point your MCP client at the `he-mcp` c
| `export_obsidian` | Export a KA to an Obsidian vault | — | embedder |
| `export_graphml` | Export a KA to GraphML (same as `he export graphml`) | — | embedder |
| `export_csv` | Export a KA to CSV tables (same as `he export csv`) | — | embedder |
++<<<<<<< HEAD
+| `export_cypher` | Export a KA to Cypher (same as `he export cypher`) | — | embedder |
+
+All tools take a `ka_path` (a directory created by `he parse`). `search`/`ask` require an index — build it with [`he build-index`](cli/commands/build-index.md).
+
+> `export_obsidian` requires the Obsidian export feature (see [`he export obsidian`](cli/commands/export.md)). If it is unavailable, the tool returns an explanatory message instead of failing. `export_graphml` / `export_csv` / `export_cypher` use the same exporters as the CLI (see [`he export`](cli/commands/export.md)).
++=======
+ | `export_jsonld` | Export a KA to JSON-LD (same as `he export jsonld`) | — | embedder |
+
+ All tools take a `ka_path` (a directory created by `he parse`). `search`/`ask` require an index — build it with [`he build-index`](cli/commands/build-index.md).
+
+ > `export_obsidian` requires the Obsidian export feature (see [`he export obsidian`](cli/commands/export.md)). If it is unavailable, the tool returns an explanatory message instead of failing. `export_graphml` / `export_csv` / `export_jsonld` use the same exporters as the CLI (see [`he export`](cli/commands/export.md)).
++>>>>>>> origin/main
---
diff --cc docs/zh/mcp.md
index 49444a2,5060080..6589e06
--- a/docs/zh/mcp.md
+++ b/docs/zh/mcp.md
@@@ -48,11 -48,11 +48,19 @@@ python -m hyperextract.mcp_serve
| `export_obsidian` | 将 KA 导出为 Obsidian 知识库 | — | 嵌入器 |
| `export_graphml` | 将 KA 导出为 GraphML(同 `he export graphml`) | — | 嵌入器 |
| `export_csv` | 将 KA 导出为 CSV 表(同 `he export csv`) | — | 嵌入器 |
++<<<<<<< HEAD
+| `export_cypher` | 将 KA 导出为 Cypher(同 `he export cypher`) | — | 嵌入器 |
+
+所有工具都接受一个 `ka_path`(由 `he parse` 创建的目录)。`search`/`ask` 需要索引——用 [`he build-index`](cli/commands/build-index.md) 构建。
+
+> `export_obsidian` 依赖 Obsidian 导出功能(见 [`he export obsidian`](cli/commands/export.md))。若不可用,该工具会返回说明信息而不会报错。`export_graphml` / `export_csv` / `export_cypher` 使用与 CLI 相同的导出器(见 [`he export`](cli/commands/export.md))。
++=======
+ | `export_jsonld` | 将 KA 导出为 JSON-LD(同 `he export jsonld`) | — | 嵌入器 |
+
+ 所有工具都接受一个 `ka_path`(由 `he parse` 创建的目录)。`search`/`ask` 需要索引——用 [`he build-index`](cli/commands/build-index.md) 构建。
+
+ > `export_obsidian` 依赖 Obsidian 导出功能(见 [`he export obsidian`](cli/commands/export.md))。若不可用,该工具会返回说明信息而不会报错。`export_graphml` / `export_csv` / `export_jsonld` 使用与 CLI 相同的导出器(见 [`he export`](cli/commands/export.md))。
++>>>>>>> origin/main
---
diff --cc hyperextract/mcp_server.py
index 7522254,63234fb..94ad0c2
--- a/hyperextract/mcp_server.py
+++ b/hyperextract/mcp_server.py
@@@ -13,7 -13,7 +13,8 @@@ Tools
- export_obsidian : export a KA to an Obsidian vault
- export_graphml : export a KA to GraphML (same as `he export graphml`)
- export_csv : export a KA to CSV tables (same as `he export csv`)
+ - export_jsonld : export a KA to JSON-LD (same as `he export jsonld`)
+ - export_cypher : export a KA to Cypher (same as `he export cypher`)
Run it (stdio transport):
@@@ -332,29 -332,29 +333,52 @@@ def export_csv(ka_path: str, output: st
return f"Wrote {written} to {dest}"
+ def export_jsonld(ka_path: str, output: str, overwrite: bool = False) -> str:
+ """Export a knowledge abstract to JSON-LD.
+
+ Args:
+ ka_path: Path to the knowledge abstract directory.
+ output: Destination ``.jsonld`` file.
+ overwrite: Overwrite an existing, non-empty JSON-LD file.
+
+ Uses the same ``export_ka_jsonld`` adapter as ``he export jsonld``.
+ Does not create, mutate, or delete the KA.
+ """
+ from hyperextract.utils.exporters.ka import GraphTypeError, export_ka_jsonld
+
+ ka = _load_ka(ka_path)
+ try:
+ dest = export_ka_jsonld(ka, output, overwrite=overwrite)
+ except GraphTypeError as e:
+ return str(e)
+ except FileExistsError as e:
+ return f"{e} Pass overwrite=true to overwrite it."
+ return f"Wrote JSON-LD to {dest}"
+
+
+def export_cypher(ka_path: str, output: str, overwrite: bool = False) -> str:
+ """Export a knowledge abstract to a Cypher MERGE script.
+
+ Args:
+ ka_path: Path to the knowledge abstract directory.
+ output: Destination ``.cypher`` file.
+ overwrite: Overwrite an existing, non-empty Cypher file.
+
+ Uses the same ``export_ka_cypher`` adapter as ``he export cypher``.
+ Does not create, mutate, or delete the KA.
+ """
+ from hyperextract.utils.exporters.ka import GraphTypeError, export_ka_cypher
+
+ ka = _load_ka(ka_path)
+ try:
+ dest = export_ka_cypher(ka, output, overwrite=overwrite)
+ except GraphTypeError as e:
+ return str(e)
+ except FileExistsError as e:
+ return f"{e} Pass overwrite=true to overwrite it."
+ return f"Wrote Cypher to {dest}"
+
+
# ---------------------------------------------------------------------------
# Server wiring
# ---------------------------------------------------------------------------
@@@ -378,7 -378,7 +402,8 @@@ def build_server()
export_obsidian,
export_graphml,
export_csv,
+ export_jsonld,
+ export_cypher,
):
server.tool()(fn)
return server
diff --cc hyperextract/utils/exporters/ka.py
index 9ba3c9d,0140f9c..7ae7527
--- a/hyperextract/utils/exporters/ka.py
+++ b/hyperextract/utils/exporters/ka.py
@@@ -1,7 -1,7 +1,8 @@@
- """KA-level adapters for GraphML, CSV, and Cypher export.
-"""KA-level adapters for GraphML, CSV, and JSON-LD export.
++"""KA-level adapters for GraphML, CSV, JSON-LD, and Cypher export.
- CLI ``he export graphml/csv/cypher`` and MCP ``export_graphml`` /
- ``export_csv`` / ``export_cypher`` call these functions so extractor
-CLI ``he export graphml/csv/jsonld`` and MCP ``export_graphml`` /
-``export_csv`` / ``export_jsonld`` call these functions so extractor
++CLI ``he export graphml/csv/jsonld/cypher`` and MCP ``export_graphml`` /
++``export_csv`` / ``export_jsonld`` / ``export_cypher`` call these functions
++so extractor
wiring and the graph-type check live in one place. Encoders stay pure
functions over node/edge models.
"""
@@@ -13,11 -13,11 +14,12 @@@ from typing import An
from .common import resolve_export_file
from .csv_export import export_to_csv
+from .cypher import export_to_cypher
from .graphml import export_to_graphml
+ from .jsonld import export_to_jsonld
GRAPH_TYPE_ERROR = (
- "Graph export (GraphML/CSV/JSON-LD) is only supported for graph-type "
+ "Graph export (GraphML/CSV/JSON-LD/Cypher) is only supported for graph-type "
"knowledge abstracts (graph, hypergraph, temporal/spatial graphs)."
)
@@@ -69,15 -69,15 +71,29 @@@ def export_ka_csv(ka: Any, dest: str |
)
+def export_ka_cypher(ka: Any, dest: str | Path, *, overwrite: bool = False) -> Path:
+ """Export a loaded graph-family KA to a Cypher MERGE script."""
+ require_graph_ka(ka)
+ dest = resolve_export_file(dest, overwrite=overwrite)
+ return export_to_cypher(
+ ka.nodes,
+ ka.edges,
+ node_id_extractor=ka.node_key_extractor,
+ incident_nodes_extractor=ka.nodes_in_edge_extractor,
+ file_path=dest,
+ edge_id_extractor=getattr(ka, "edge_key_extractor", None),
+ )
++
++
+ def export_ka_jsonld(ka: Any, dest: str | Path, *, overwrite: bool = False) -> Path:
+ """Export a loaded graph-family KA to JSON-LD."""
+ require_graph_ka(ka)
+ dest = resolve_export_file(dest, overwrite=overwrite)
+ return export_to_jsonld(
+ ka.nodes,
+ ka.edges,
+ node_id_extractor=ka.node_key_extractor,
+ incident_nodes_extractor=ka.nodes_in_edge_extractor,
+ file_path=dest,
+ edge_id_extractor=getattr(ka, "edge_key_extractor", None),
+ )
diff --cc tests/test_mcp_server.py
index 9f7bdbc,35fe7b0..064bca0
--- a/tests/test_mcp_server.py
+++ b/tests/test_mcp_server.py
@@@ -316,72 -316,40 +316,107 @@@ def test_export_csv_rejects_non_graph_w
assert "graph-type knowledge abstracts" in graphml
+def test_export_cypher(monkeypatch, tmp_path):
+ g = _graph_with_index()
+ monkeypatch.setattr(mcp_server, "_load_ka", lambda p: g)
+ dest = tmp_path / "out.cypher"
+ out = mcp_server.export_cypher("x", str(dest))
+ assert dest.exists()
+ text = dest.read_text(encoding="utf-8")
+ assert "MERGE" in text
+ assert str(dest) in out
+
+
+class _HyperedgeEvent(BaseModel):
+ label: str
+ participants: list[str]
+
+
+def test_export_cypher_nary_is_hyperedge_not_clique(monkeypatch, tmp_path):
+ class _HyperKA:
+ nodes = [
+ Entity(name="A"),
+ Entity(name="B"),
+ Entity(name="C"),
+ ]
+ edges = [_HyperedgeEvent(label="meeting", participants=["C", "A", "B"])]
+ node_key_extractor = staticmethod(lambda n: n.name)
+ edge_key_extractor = staticmethod(lambda e: e.label)
+ nodes_in_edge_extractor = staticmethod(lambda e: tuple(e.participants))
+
+ def export_obsidian(self, *args, **kwargs):
+ return None
+
+ monkeypatch.setattr(mcp_server, "_load_ka", lambda p: _HyperKA())
+ dest = tmp_path / "out.cypher"
+ out = mcp_server.export_cypher("x", str(dest))
+ text = dest.read_text(encoding="utf-8")
+ assert ":Hyperedge" in text
+ assert "[:IN]" in text
+ assert text.count("[:IN]") == 3
+ assert "-[:REL]" not in text
+ assert str(dest) in out
+
+
+def test_export_cypher_requires_overwrite(monkeypatch, tmp_path):
+ g = _graph_with_index()
+ monkeypatch.setattr(mcp_server, "_load_ka", lambda p: g)
+ dest = tmp_path / "out.cypher"
+ dest.write_text("KEEP-ME", encoding="utf-8")
+ out = mcp_server.export_cypher("x", str(dest))
+ assert "overwrite" in out.lower()
+ assert dest.read_text(encoding="utf-8") == "KEEP-ME"
+ out = mcp_server.export_cypher("x", str(dest), overwrite=True)
++
++
+ def test_export_jsonld(monkeypatch, tmp_path):
+ g = _graph_with_index()
+ monkeypatch.setattr(mcp_server, "_load_ka", lambda p: g)
+ dest = tmp_path / "out.jsonld"
+ out = mcp_server.export_jsonld("x", str(dest))
+ assert dest.exists()
+ doc = json.loads(dest.read_text(encoding="utf-8"))
+ assert any(item.get("@type") == "Edge" for item in doc["@graph"])
+ assert str(dest) in out
+
+
+ def test_export_jsonld_requires_overwrite(monkeypatch, tmp_path):
+ g = _graph_with_index()
+ monkeypatch.setattr(mcp_server, "_load_ka", lambda p: g)
+ dest = tmp_path / "out.jsonld"
+ dest.write_text("KEEP-ME", encoding="utf-8")
+ out = mcp_server.export_jsonld("x", str(dest))
+ assert "overwrite" in out.lower()
+ assert dest.read_text(encoding="utf-8") == "KEEP-ME"
+ out = mcp_server.export_jsonld("x", str(dest), overwrite=True)
assert dest.read_text(encoding="utf-8") != "KEEP-ME"
assert str(dest) in out
+ def test_export_jsonld_rejects_non_graph(monkeypatch, tmp_path):
+ class _ListKA:
+ pass
+
+ monkeypatch.setattr(mcp_server, "_load_ka", lambda p: _ListKA())
+ out = mcp_server.export_jsonld("x", str(tmp_path / "out.jsonld"))
+ assert out == (
- "Graph export (GraphML/CSV/JSON-LD) is only supported for graph-type "
++ "Graph export (GraphML/CSV/JSON-LD/Cypher) is only supported for graph-type "
++ "knowledge abstracts (graph, hypergraph, temporal/spatial graphs)."
++ )
++ assert "JSON-LD" in out
++
++
+def test_export_cypher_rejects_non_graph(monkeypatch, tmp_path):
+ class _ListKA:
+ pass
+
+ monkeypatch.setattr(mcp_server, "_load_ka", lambda p: _ListKA())
+ out = mcp_server.export_cypher("x", str(tmp_path / "out.cypher"))
+ assert out == (
+ "Graph export (GraphML/CSV/JSON-LD/Cypher) is only supported for graph-type "
"knowledge abstracts (graph, hypergraph, temporal/spatial graphs)."
)
+ assert "Cypher" in out
# ---------------------------------------------------------------------------
diff --cc tests/utils/test_exporters.py
index 4e7f90b,34cb6f3..50127ca
--- a/tests/utils/test_exporters.py
+++ b/tests/utils/test_exporters.py
@@@ -27,8 -27,8 +27,9 @@@ from hyperextract.utils.exporters.ka im
GRAPH_TYPE_ERROR,
GraphTypeError,
export_ka_csv,
+ export_ka_cypher,
export_ka_graphml,
+ export_ka_jsonld,
)
from hyperextract.utils.exporters.graphml import GRAPHML_NS
@@@ -488,34 -488,48 +489,76 @@@ class TestCommonHelpers
export_ka_graphml(fake, dest, overwrite=True)
assert dest.read_text(encoding="utf-8") != "KEEP"
+ def test_export_ka_cypher_keeps_nary_hyperedge(self, tmp_path):
+ fake = FakeGraphKA(
+ [Entity(name="A"), Entity(name="B"), Entity(name="C")],
+ [Event(label="meeting", participants=["C", "A", "B"])],
+ hypergraph=True,
+ )
+ via_adapter = export_ka_cypher(fake, tmp_path / "via_ka.cypher")
+ via_encoder = export_to_cypher(
+ fake.nodes,
+ fake.edges,
+ node_id_extractor=fake.node_key_extractor,
+ incident_nodes_extractor=fake.nodes_in_edge_extractor,
+ file_path=tmp_path / "via_enc.cypher",
+ edge_id_extractor=fake.edge_key_extractor,
+ )
+ adapter_text = via_adapter.read_text(encoding="utf-8")
+ assert adapter_text == via_encoder.read_text(encoding="utf-8")
+ assert ":Hyperedge" in adapter_text
+ assert "[:IN]" in adapter_text
+ assert adapter_text.count("[:IN]") == 3
+ assert "-[:REL]" not in adapter_text
+
+ def test_export_ka_cypher_rejects_non_graph(self, tmp_path):
+ with pytest.raises(GraphTypeError) as exc:
+ export_ka_cypher(FakeListKA(), tmp_path / "g.cypher")
+ assert str(exc.value) == GRAPH_TYPE_ERROR
+ assert "Cypher" in GRAPH_TYPE_ERROR
+
+ def test_export_ka_jsonld_matches_encoder(self, tmp_path):
+ fake = FakeGraphKA(
+ [Entity(name="A"), Entity(name="B")],
+ [Relation(source="B", target="A", relation_type="leads_to")],
+ )
+ via_adapter = export_ka_jsonld(fake, tmp_path / "via_ka.jsonld")
+ via_encoder = export_to_jsonld(
+ fake.nodes,
+ fake.edges,
+ node_id_extractor=fake.node_key_extractor,
+ incident_nodes_extractor=fake.nodes_in_edge_extractor,
+ file_path=tmp_path / "via_enc.jsonld",
+ edge_id_extractor=fake.edge_key_extractor,
+ )
+ assert _load_jsonld(via_adapter) == _load_jsonld(via_encoder)
+ edges_out = [
+ item
+ for item in _load_jsonld(via_adapter)["@graph"]
+ if item.get("@type") == "Edge"
+ ]
+ assert edges_out[0]["source"] == "B"
+ assert edges_out[0]["target"] == "A"
+
+ hyper = FakeGraphKA(
+ [Entity(name="A"), Entity(name="B"), Entity(name="C")],
+ [Event(label="meeting", participants=["C", "A", "B"])],
+ hypergraph=True,
+ )
+ hyper_path = export_ka_jsonld(hyper, tmp_path / "hyper.jsonld")
+ hypers = [
+ item
+ for item in _load_jsonld(hyper_path)["@graph"]
+ if item.get("@type") == "Hyperedge"
+ ]
+ assert len(hypers) == 1
+ assert hypers[0]["endpoint"] == ["C", "A", "B"]
+
+ def test_export_ka_jsonld_rejects_non_graph(self, tmp_path):
+ with pytest.raises(GraphTypeError) as exc:
+ export_ka_jsonld(FakeListKA(), tmp_path / "g.jsonld")
+ assert str(exc.value) == GRAPH_TYPE_ERROR
+
class TestCLIExport:
def test_graphml_writes_directed_edge(self, tmp_path):