Hypergraph is more powerful. Transform unstructured text into structured knowledge with LLMs. Graphs, hypergraphs, and spatio-temporal extractions — with one command.
feat: expose Cypher export on he-mcp
Frankie-Xu32568844f809
diff --git a/docs/en/mcp.md b/docs/en/mcp.mdindex 133dab3..cdde2e1 100644--- a/docs/en/mcp.md+++ b/docs/en/mcp.md@@ -48,10 +48,11 @@ Point your MCP client at the `he-mcp` command. For a Claude Desktop–style conf| `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 |+| `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` use the same exporters as the CLI (see [`he export`](cli/commands/export.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)).---diff --git a/docs/zh/mcp.md b/docs/zh/mcp.mdindex 741d4a6..49444a2 100644--- a/docs/zh/mcp.md+++ b/docs/zh/mcp.md@@ -48,10 +48,11 @@ python -m hyperextract.mcp_server| `export_obsidian` | 将 KA 导出为 Obsidian 知识库 | — | 嵌入器 || `export_graphml` | 将 KA 导出为 GraphML(同 `he export graphml`) | — | 嵌入器 || `export_csv` | 将 KA 导出为 CSV 表(同 `he export csv`) | — | 嵌入器 |+| `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` 使用与 CLI 相同的导出器(见 [`he export`](cli/commands/export.md))。+> `export_obsidian` 依赖 Obsidian 导出功能(见 [`he export obsidian`](cli/commands/export.md))。若不可用,该工具会返回说明信息而不会报错。`export_graphml` / `export_csv` / `export_cypher` 使用与 CLI 相同的导出器(见 [`he export`](cli/commands/export.md))。---diff --git a/hyperextract/cli/cli.py b/hyperextract/cli/cli.pyindex 950ef83..745bbec 100644--- a/hyperextract/cli/cli.py+++ b/hyperextract/cli/cli.py@@ -717,22 +717,23 @@ def export_cypher_cmd(Binary edges become relationships. N-ary edges become Hyperedge nodeswith IN membership (not a pairwise clique)."""- from hyperextract.utils.exporters import export_to_cypher+ from hyperextract.utils.exporters.common import resolve_export_file+ from hyperextract.utils.exporters.ka import GraphTypeError, export_ka_cypherlogger.info("command=export-cypher ka_path=%s output=%s", ka_path, output)output_path = Path(output)- existing_nonempty = (- output_path.exists()- and output_path.is_file()- and output_path.stat().st_size > 0- )- if existing_nonempty and not force:+ try:+ resolve_export_file(output_path, overwrite=force)+ except FileExistsError:console.print("[red]Error:[/red] Output file already exists. ""Use --force / -f to overwrite it.")raise typer.Exit(1)+ except IsADirectoryError as e:+ console.print(f"[red]Error:[/red] {e}")+ raise typer.Exit(1)ka, _path, template = _load_graph_ka_for_export(ka_path)console.print(f"[blue]Knowledge Abstract:[/blue] {ka_path}")@@ -742,14 +743,16 @@ def export_cypher_cmd(with console.status("[bold blue]Exporting to Cypher..."):try:- export_to_cypher(- ka.nodes,- ka.edges,- node_id_extractor=ka.node_key_extractor,- incident_nodes_extractor=ka.nodes_in_edge_extractor,- file_path=output_path,- edge_id_extractor=getattr(ka, "edge_key_extractor", None),+ export_ka_cypher(ka, output_path, overwrite=force)+ except GraphTypeError as e:+ console.print(f"[red]Error:[/red] {e}")+ raise typer.Exit(1)+ except FileExistsError:+ console.print(+ "[red]Error:[/red] Output file already exists. "+ "Use --force / -f to overwrite it.")+ raise typer.Exit(1)except Exception as e:console.print(f"[red]Error during export:[/red] {e}")raise typer.Exit(1)diff --git a/hyperextract/mcp_server.py b/hyperextract/mcp_server.pyindex 1fa83e0..7522254 100644--- a/hyperextract/mcp_server.py+++ b/hyperextract/mcp_server.py@@ -13,6 +13,7 @@ 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_cypher : export a KA to Cypher (same as `he export cypher`)Run it (stdio transport):@@ -331,6 +332,29 @@ def export_csv(ka_path: str, output: str, overwrite: bool = False) -> str:return f"Wrote {written} 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# ---------------------------------------------------------------------------@@ -354,6 +378,7 @@ def build_server():export_obsidian,export_graphml,export_csv,+ export_cypher,):server.tool()(fn)return serverdiff --git a/hyperextract/utils/exporters/ka.py b/hyperextract/utils/exporters/ka.pyindex 7456832..9ba3c9d 100644--- a/hyperextract/utils/exporters/ka.py+++ b/hyperextract/utils/exporters/ka.py@@ -1,8 +1,9 @@-"""KA-level adapters for GraphML and CSV export.+"""KA-level adapters for GraphML, CSV, and Cypher export.-CLI ``he export graphml/csv`` and MCP ``export_graphml`` / ``export_csv``-call these functions so extractor wiring and the graph-type check live in-one place. Encoders stay pure functions over node/edge models.+CLI ``he export graphml/csv/cypher`` and MCP ``export_graphml`` /+``export_csv`` / ``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."""from __future__ import annotations@@ -12,10 +13,11 @@ from typing import Anyfrom .common import resolve_export_filefrom .csv_export import export_to_csv+from .cypher import export_to_cypherfrom .graphml import export_to_graphmlGRAPH_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).")@@ -65,3 +67,17 @@ def export_ka_csv(ka: Any, dest: str | Path, *, overwrite: bool = False) -> Pathhypergraph=is_hypergraph_ka(ka),overwrite=overwrite,)+++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),+ )diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.pyindex 308140d..9f7bdbc 100644--- a/tests/test_mcp_server.py+++ b/tests/test_mcp_server.py@@ -300,7 +300,7 @@ def test_export_graphml_rejects_non_graph(monkeypatch, tmp_path):monkeypatch.setattr(mcp_server, "_load_ka", lambda p: _ListKA())out = mcp_server.export_graphml("x", str(tmp_path / "out.graphml"))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).")@@ -316,6 +316,74 @@ def test_export_csv_rejects_non_graph_with_same_message(monkeypatch, tmp_path):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)+ assert dest.read_text(encoding="utf-8") != "KEEP-ME"+ assert str(dest) 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++# ---------------------------------------------------------------------------# FastMCP wiring (needs the optional `mcp` package)# ---------------------------------------------------------------------------diff --git a/tests/utils/test_exporters.py b/tests/utils/test_exporters.pyindex 8989ba5..4e7f90b 100644--- a/tests/utils/test_exporters.py+++ b/tests/utils/test_exporters.py@@ -27,6 +27,7 @@ from hyperextract.utils.exporters.ka import (GRAPH_TYPE_ERROR,GraphTypeError,export_ka_csv,+ export_ka_cypher,export_ka_graphml,)from hyperextract.utils.exporters.graphml import GRAPHML_NS@@ -487,6 +488,34 @@ 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+class TestCLIExport:def test_graphml_writes_directed_edge(self, tmp_path):