Skip to content

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

feat: expose JSON-LD export on he-mcp

Frankie-Xu51545e8d7324
diff --git a/docs/en/mcp.md b/docs/en/mcp.md
index 133dab3..0bcd763 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_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` 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_jsonld` 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.md
index 741d4a6..5060080 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_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` 使用与 CLI 相同的导出器(见 [`he export`](cli/commands/export.md))。
+> `export_obsidian` 依赖 Obsidian 导出功能(见 [`he export obsidian`](cli/commands/export.md))。若不可用,该工具会返回说明信息而不会报错。`export_graphml` / `export_csv` / `export_jsonld` 使用与 CLI 相同的导出器(见 [`he export`](cli/commands/export.md))。
---
diff --git a/hyperextract/cli/cli.py b/hyperextract/cli/cli.py
index 950ef83..b33309b 100644
--- a/hyperextract/cli/cli.py
+++ b/hyperextract/cli/cli.py
@@ -663,22 +663,23 @@ def export_jsonld_cmd(
Binary edges are `@type: Edge` with source/target. Edges with three
or more endpoints are `@type: Hyperedge` with an endpoint list.
"""
- from hyperextract.utils.exporters import export_to_jsonld
+ from hyperextract.utils.exporters.common import resolve_export_file
+ from hyperextract.utils.exporters.ka import GraphTypeError, export_ka_jsonld
logger.info("command=export-jsonld 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}")
@@ -688,14 +689,16 @@ def export_jsonld_cmd(
with console.status("[bold blue]Exporting to JSON-LD..."):
try:
- export_to_jsonld(
- 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_jsonld(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.py
index 1fa83e0..63234fb 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_jsonld : export a KA to JSON-LD (same as `he export jsonld`)
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_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}"
+
+
# ---------------------------------------------------------------------------
# Server wiring
# ---------------------------------------------------------------------------
@@ -354,6 +378,7 @@ def build_server():
export_obsidian,
export_graphml,
export_csv,
+ export_jsonld,
):
server.tool()(fn)
return server
diff --git a/hyperextract/utils/exporters/ka.py b/hyperextract/utils/exporters/ka.py
index 7456832..0140f9c 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 JSON-LD 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/jsonld`` and MCP ``export_graphml`` /
+``export_csv`` / ``export_jsonld`` 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
@@ -13,6 +14,7 @@ from typing import Any
from .common import resolve_export_file
from .csv_export import export_to_csv
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 "
@@ -65,3 +67,17 @@ def export_ka_csv(ka: Any, dest: str | Path, *, overwrite: bool = False) -> Path
hypergraph=is_hypergraph_ka(ka),
overwrite=overwrite,
)
+
+
+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 --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py
index 308140d..35fe7b0 100644
--- a/tests/test_mcp_server.py
+++ b/tests/test_mcp_server.py
@@ -316,6 +316,42 @@ def test_export_csv_rejects_non_graph_with_same_message(monkeypatch, tmp_path):
assert "graph-type knowledge abstracts" in graphml
+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 "
+ "knowledge abstracts (graph, hypergraph, temporal/spatial graphs)."
+ )
+
+
# ---------------------------------------------------------------------------
# FastMCP wiring (needs the optional `mcp` package)
# ---------------------------------------------------------------------------
diff --git a/tests/utils/test_exporters.py b/tests/utils/test_exporters.py
index 8989ba5..34cb6f3 100644
--- a/tests/utils/test_exporters.py
+++ b/tests/utils/test_exporters.py
@@ -28,6 +28,7 @@ from hyperextract.utils.exporters.ka import (
GraphTypeError,
export_ka_csv,
export_ka_graphml,
+ export_ka_jsonld,
)
from hyperextract.utils.exporters.graphml import GRAPHML_NS
@@ -487,6 +488,48 @@ class TestCommonHelpers:
export_ka_graphml(fake, dest, overwrite=True)
assert dest.read_text(encoding="utf-8") != "KEEP"
+ 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):