Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(kg): make calculate_pagerank and MCP graph analytics work on ContextGraph (#1744)

Kevin5f3187b58845
diff --git a/semantica/kg/centrality_calculator.py b/semantica/kg/centrality_calculator.py
index 0b3da2b2..3e4bc9f1 100644
--- a/semantica/kg/centrality_calculator.py
+++ b/semantica/kg/centrality_calculator.py
@@ -622,7 +622,11 @@ class CentralityCalculator:
try:
self.logger.info("Calculating PageRank scores")
- if not hasattr(graph, "nodes") and hasattr(self, "_to_networkx"):
+ # ContextGraph.nodes is a dict rather than a NetworkX NodeView,
+ # so an attribute presence test would skip the conversion and the
+ # node filter below would then call that dict.
+ needs_conversion = not callable(getattr(graph, "nodes", None))
+ if needs_conversion and hasattr(self, "_to_networkx"):
try:
graph = self._to_networkx(graph)
except Exception:
diff --git a/semantica_mcp/mcp/tools/graph.py b/semantica_mcp/mcp/tools/graph.py
index 917c3c45..67989e14 100644
--- a/semantica_mcp/mcp/tools/graph.py
+++ b/semantica_mcp/mcp/tools/graph.py
@@ -176,6 +176,50 @@ def handle_get_graph_summary(args: dict) -> dict: # noqa: ARG001
return {"error": str(exc), "graph_ready": False}
+def _top_rankings(payload, top_n: int) -> list:
+ """Return the first ``top_n`` entries of a centrality result.
+
+ ``CentralityCalculator`` returns ``{"centrality": {node: score},
+ "rankings": [...]}`` and the rankings list is already sorted, so the
+ handler only has to trim it. PageRank emits ``(node, score)`` pairs
+ while the other measures emit ``{"node": ..., "score": ...}`` dicts;
+ both are normalised here so the tool returns one shape.
+ """
+ if not isinstance(payload, dict):
+ return []
+ rankings = payload.get("rankings")
+ if not isinstance(rankings, list):
+ centrality = payload.get("centrality")
+ if not isinstance(centrality, dict):
+ return []
+ rankings = sorted(centrality.items(), key=lambda item: item[1], reverse=True)
+ trimmed = []
+ for entry in rankings[:top_n]:
+ if isinstance(entry, dict):
+ trimmed.append(entry)
+ elif isinstance(entry, (list, tuple)) and len(entry) == 2:
+ trimmed.append({"node": entry[0], "score": entry[1]})
+ return trimmed
+
+
+def _community_groups(payload) -> list:
+ """Return the community groups of a ``detect_communities`` result.
+
+ The detector returns ``{"communities": [set, ...], ...}``; the groups
+ are sets, which the JSON transport cannot serialise, so each one is
+ returned as a sorted list.
+ """
+ if isinstance(payload, dict):
+ groups = payload.get("communities")
+ elif isinstance(payload, list):
+ groups = payload
+ else:
+ groups = None
+ if not isinstance(groups, list):
+ return []
+ return [sorted(group) if isinstance(group, (set, frozenset)) else group for group in groups]
+
+
def handle_get_graph_analytics(args: dict) -> dict:
"""Compute centrality, community detection, and other graph metrics."""
requested = args.get("metrics", ["all"])
@@ -189,32 +233,30 @@ def handle_get_graph_analytics(args: dict) -> dict:
if compute_all or "pagerank" in requested:
try:
pr = CentralityCalculator().calculate_pagerank(graph)
- items = pr.items() if hasattr(pr, "items") else []
- result["pagerank"] = sorted(items, key=lambda x: x[1], reverse=True)[:top_n]
+ result["pagerank"] = _top_rankings(pr, top_n)
except Exception as exc:
result["pagerank_error"] = str(exc)
if compute_all or "betweenness" in requested:
try:
bc = CentralityCalculator().calculate_betweenness_centrality(graph)
- items = bc.items() if hasattr(bc, "items") else []
- result["betweenness"] = sorted(items, key=lambda x: x[1], reverse=True)[:top_n]
+ result["betweenness"] = _top_rankings(bc, top_n)
except Exception as exc:
result["betweenness_error"] = str(exc)
if compute_all or "communities" in requested:
try:
comms = CommunityDetector().detect_communities(graph)
- result["community_count"] = len(comms) if isinstance(comms, (list, dict)) else 0
- result["communities"] = comms if isinstance(comms, list) else []
+ groups = _community_groups(comms)
+ result["community_count"] = len(groups)
+ result["communities"] = groups
except Exception as exc:
result["communities_error"] = str(exc)
if compute_all or "degree" in requested:
try:
deg = CentralityCalculator().calculate_degree_centrality(graph)
- items = deg.items() if hasattr(deg, "items") else []
- result["degree"] = sorted(items, key=lambda x: x[1], reverse=True)[:top_n]
+ result["degree"] = _top_rankings(deg, top_n)
except Exception as exc:
result["degree_error"] = str(exc)
diff --git a/tests/test_mcp_package_graph_analytics.py b/tests/test_mcp_package_graph_analytics.py
new file mode 100644
index 00000000..e9abb448
--- /dev/null
+++ b/tests/test_mcp_package_graph_analytics.py
@@ -0,0 +1,163 @@
+"""Regression tests for issue #1721 - MCP get_graph_analytics on a ContextGraph.
+
+Two defects sat on the same call path:
+
+1. ``CentralityCalculator.calculate_pagerank()`` decided whether to convert
+ the graph with ``hasattr(graph, "nodes")``. ``ContextGraph.nodes`` is a
+ dict, so the attribute exists, the conversion was skipped, and
+ ``_filter_nodes_by_labels()`` then called that dict - "TypeError: 'dict'
+ object is not callable". The other four centrality measures convert
+ unconditionally and were unaffected.
+
+2. ``handle_get_graph_analytics()`` treated every centrality result as
+ ``{node: score}``. The calculators return
+ ``{"centrality": {...}, "rankings": [...]}``, so sorting the outer dict
+ raised "'<' not supported", every metric came back under a ``*_error``
+ key, and the community count came from ``len(dict)`` while the group list
+ was forced to ``[]``.
+
+These tests pin both: a ContextGraph has to survive pagerank, and the tool
+has to return values instead of errors.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import unittest
+from unittest.mock import patch
+
+sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
+
+
+def _make_context_graph():
+ """A ContextGraph with three nodes and two edges."""
+ from semantica.context.context_graph import ContextGraph
+
+ graph = ContextGraph()
+ graph.add_node("alice", "person", "Alice")
+ graph.add_node("bob", "person", "Bob")
+ graph.add_node("acme", "org", "Acme")
+ graph.add_edge("alice", "bob", "knows")
+ graph.add_edge("bob", "acme", "works_at")
+ return graph
+
+
+class TestPagerankAcceptsContextGraph(unittest.TestCase):
+ """Defect 1: the graph-kind check read a dict attribute as callable."""
+
+ @classmethod
+ def setUpClass(cls):
+ cls.graph = _make_context_graph()
+
+ def test_context_graph_nodes_is_a_dict(self):
+ # The premise of the bug: the attribute exists but is not callable.
+ self.assertTrue(hasattr(self.graph, "nodes"))
+ self.assertFalse(callable(self.graph.nodes))
+
+ def test_calculate_pagerank_returns_scores(self):
+ from semantica.kg import CentralityCalculator
+
+ result = CentralityCalculator().calculate_pagerank(self.graph)
+ self.assertIsInstance(result, dict)
+ self.assertEqual(set(result["centrality"]), {"alice", "bob", "acme"})
+
+ def test_pagerank_agrees_with_sibling_measures(self):
+ """The other measures already accepted a ContextGraph; pagerank did not."""
+ from semantica.kg import CentralityCalculator
+
+ calculator = CentralityCalculator()
+ for name in (
+ "calculate_pagerank",
+ "calculate_degree_centrality",
+ "calculate_betweenness_centrality",
+ "calculate_closeness_centrality",
+ "calculate_eigenvector_centrality",
+ ):
+ with self.subTest(measure=name):
+ result = getattr(calculator, name)(self.graph)
+ self.assertEqual(set(result["centrality"]), {"alice", "bob", "acme"})
+
+
+def _make_two_node_graph():
+ """The smallest connected graph: two nodes, one edge (issue #1761)."""
+ from semantica.context.context_graph import ContextGraph
+
+ graph = ContextGraph()
+ graph.add_node("a", "person", "A")
+ graph.add_node("b", "person", "B")
+ graph.add_edge("a", "b", "knows")
+ return graph
+
+
+class TestGraphAnalyticsTool(unittest.TestCase):
+ """Defect 2: the handler mis-unpacked the calculator results."""
+
+ @classmethod
+ def setUpClass(cls):
+ cls.graph = _make_context_graph()
+
+ def _call_handler(self, args):
+ from semantica_mcp.mcp.tools import graph as graph_tools
+
+ with patch.object(graph_tools, "get_graph", return_value=self.graph):
+ return graph_tools.handle_get_graph_analytics(args)
+
+ def test_all_metrics_return_values_not_errors(self):
+ result = self._call_handler({"metrics": ["all"], "top_n": 5})
+ for key in ("pagerank", "betweenness", "degree"):
+ with self.subTest(metric=key):
+ self.assertNotIn(f"{key}_error", result)
+ self.assertTrue(result[key])
+ self.assertIn("node", result[key][0])
+ self.assertIn("score", result[key][0])
+ self.assertNotIn("communities_error", result)
+
+ def test_communities_match_the_reported_count(self):
+ result = self._call_handler({"metrics": ["all"], "top_n": 5})
+ self.assertEqual(result["community_count"], len(result["communities"]))
+ self.assertTrue(result["communities"])
+
+ def test_result_is_json_serialisable(self):
+ # Community groups are sets; the stdio transport needs them as lists.
+ result = self._call_handler({"metrics": ["all"], "top_n": 5})
+ json.dumps(result)
+
+ def test_metric_selection_limits_the_output(self):
+ result = self._call_handler({"metrics": ["pagerank"], "top_n": 1})
+ self.assertEqual(len(result["pagerank"]), 1)
+ self.assertNotIn("degree", result)
+ self.assertNotIn("betweenness", result)
+
+ def test_top_n_is_respected(self):
+ result = self._call_handler({"metrics": ["degree"], "top_n": 1})
+ self.assertEqual(len(result["degree"]), 1)
+
+ def test_two_node_graph_reports_its_one_community(self):
+ """A connected pair is one community. #1761 saw it reported as four.
+
+ ``community_count`` came from ``len()`` of the result wrapper, whose
+ four keys have nothing to do with the grouping, and ``communities``
+ was forced to ``[]`` because the wrapper is not a list.
+ """
+ from semantica_mcp.mcp.tools import graph as graph_tools
+
+ graph = _make_two_node_graph()
+ with patch.object(graph_tools, "get_graph", return_value=graph):
+ result = graph_tools.handle_get_graph_analytics(
+ {"metrics": ["all"], "top_n": 5}
+ )
+
+ for key in ("pagerank", "betweenness", "degree"):
+ with self.subTest(metric=key):
+ self.assertNotIn(f"{key}_error", result)
+ self.assertEqual(len(result[key]), 2)
+ self.assertNotIn("communities_error", result)
+ self.assertEqual(result["community_count"], 1)
+ self.assertEqual(result["communities"], [["a", "b"]])
+ json.dumps(result)
+
+
+if __name__ == "__main__":
+ unittest.main()