Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(mcp): rank pagerank scores from the centrality result (#1753)

Kevina756c5a01869
diff --git a/semantica/mcp_server/__init__.py b/semantica/mcp_server/__init__.py
index d151b9fe..c336c000 100644
--- a/semantica/mcp_server/__init__.py
+++ b/semantica/mcp_server/__init__.py
@@ -410,6 +410,41 @@ def _tool_run_reasoning(args: dict) -> dict:
return {"derived_facts": derived if isinstance(derived, list) else list(derived)}
+def _pagerank_rankings(result: object) -> list:
+ """Return the ranked ``(node, score)`` pairs of a PageRank result.
+
+ ``CentralityCalculator.calculate_pagerank`` returns
+ ``{"centrality": {node: score}, "rankings": [...]}`` rather than a flat
+ ``{node: score}`` mapping, and its rankings list is already ordered.
+ """
+ if not isinstance(result, dict):
+ return []
+ rankings = result.get("rankings")
+ if isinstance(rankings, list):
+ return rankings
+ scores = result.get("centrality")
+ if not isinstance(scores, dict):
+ return []
+ return sorted(scores.items(), key=lambda item: item[1], reverse=True)
+
+
+def _community_count(result: object) -> int:
+ """Return the number of communities in a ``detect_communities`` result.
+
+ ``CommunityDetector.detect_communities`` returns a wrapper dict
+ (``communities``, ``node_assignments``, ``modularity``, ``algorithm``), so
+ taking ``len()`` of the whole result gives the key count, which is 4 for
+ every graph and every algorithm. A bare list of groups is still accepted.
+ """
+ if isinstance(result, dict):
+ groups = result.get("communities")
+ elif isinstance(result, list):
+ groups = result
+ else:
+ return 0
+ return len(groups) if isinstance(groups, list) else 0
+
+
def _tool_get_graph_analytics(args: dict) -> dict:
"""Compute graph analytics: centrality, community detection, metrics."""
graph = _get_graph()
@@ -424,11 +459,8 @@ def _tool_get_graph_analytics(args: dict) -> dict:
return {
"node_count": node_count,
"edge_count": edge_count,
- "top_nodes_by_pagerank": sorted(
- centrality.items() if hasattr(centrality, "items") else [],
- key=lambda x: x[1], reverse=True
- )[:10],
- "community_count": len(communities) if isinstance(communities, (list, dict)) else 0,
+ "top_nodes_by_pagerank": _pagerank_rankings(centrality)[:10],
+ "community_count": _community_count(communities),
}
except Exception as exc:
return {"error": str(exc)}
diff --git a/tests/test_mcp_server_community_count.py b/tests/test_mcp_server_community_count.py
new file mode 100644
index 00000000..fe3cbe6b
--- /dev/null
+++ b/tests/test_mcp_server_community_count.py
@@ -0,0 +1,110 @@
+"""Regression tests for community_count in the MCP get_graph_analytics tool (#1754).
+
+`_tool_get_graph_analytics` took `len()` of the whole `detect_communities`
+result. That result is a wrapper dict (`communities`, `node_assignments`,
+`modularity`, `algorithm`), so the tool reported the key count — 4 for every
+graph and every algorithm — instead of the number of communities.
+
+The line is unreachable through the real calculator on `main`: the sort feeding
+`top_nodes_by_pagerank` raises first on a ContextGraph (issue #1747). Before
+#1744 the failure happened one step earlier, inside `calculate_pagerank` itself
+(issue #1721). These tests stub PageRank with a flat mapping, which both the old
+sort and the #1747 ranking helper accept, so the handler reaches the community
+line however those two fixes land.
+"""
+
+import unittest
+from unittest import mock
+
+from semantica import mcp_server
+from semantica.context import ContextGraph
+from semantica.kg import CentralityCalculator, CommunityDetector
+
+PAGERANK_STUB = {"alice": 0.5, "bob": 0.3, "acme": 0.2}
+
+
+def _one_cluster() -> ContextGraph:
+ """Three nodes joined through one hub; Louvain finds a single community."""
+ graph = ContextGraph(advanced_analytics=True)
+ graph.add_node("alice", node_type="Person", content="Alice")
+ graph.add_node("bob", node_type="Person", content="Bob")
+ graph.add_node("acme", node_type="Organization", content="Acme")
+ graph.add_edge("alice", "acme", edge_type="worksFor")
+ graph.add_edge("bob", "acme", edge_type="worksFor")
+ graph.add_edge("alice", "bob", edge_type="knows")
+ return graph
+
+
+def _two_clusters() -> ContextGraph:
+ """Two pairs with no edge between them, so Louvain has to split them."""
+ graph = ContextGraph(advanced_analytics=True)
+ for name in ("alice", "bob", "carol", "dave"):
+ graph.add_node(name, node_type="Person", content=name)
+ graph.add_edge("alice", "bob", edge_type="knows")
+ graph.add_edge("carol", "dave", edge_type="knows")
+ return graph
+
+
+class _StubbedHandlerCase(unittest.TestCase):
+ """Runs the handler with PageRank stubbed, so the community line is reached."""
+
+ def _run(self, graph: ContextGraph) -> dict:
+ previous = mcp_server._graph
+ mcp_server._graph = graph
+ patcher = mock.patch.object(
+ CentralityCalculator,
+ "calculate_pagerank",
+ return_value=PAGERANK_STUB,
+ )
+ patcher.start()
+ try:
+ return mcp_server._tool_get_graph_analytics({})
+ finally:
+ patcher.stop()
+ mcp_server._graph = previous
+
+
+class TestCommunityCountFromTheHandler(_StubbedHandlerCase):
+
+ def test_reports_the_community_count_not_the_key_count(self):
+ graph = _one_cluster()
+ result = self._run(graph)
+ self.assertNotIn("error", result, result)
+ detected = CommunityDetector().detect_communities(graph)
+ self.assertEqual(result["community_count"], len(detected["communities"]))
+ self.assertEqual(result["community_count"], 1)
+
+ def test_counts_every_community_when_the_graph_splits(self):
+ """A single-community graph alone cannot tell a count from a constant."""
+ result = self._run(_two_clusters())
+ self.assertNotIn("error", result, result)
+ self.assertEqual(result["community_count"], 2)
+
+ def test_reports_zero_on_an_empty_graph(self):
+ result = self._run(ContextGraph(advanced_analytics=True))
+ self.assertNotIn("error", result, result)
+ self.assertEqual(result["community_count"], 0)
+
+
+class TestCommunityCountHelper(unittest.TestCase):
+
+ def test_reads_the_groups_out_of_the_wrapper_dict(self):
+ payload = {
+ "communities": [frozenset({"alice", "bob"}), frozenset({"acme"})],
+ "node_assignments": {"alice": 0, "bob": 0, "acme": 1},
+ "modularity": 0.0,
+ "algorithm": "louvain",
+ }
+ self.assertEqual(mcp_server._community_count(payload), 2)
+
+ def test_accepts_a_plain_list_of_groups(self):
+ self.assertEqual(mcp_server._community_count([{"alice"}, {"bob"}, {"acme"}]), 3)
+
+ def test_reports_zero_for_missing_or_misshaped_groups(self):
+ for payload in ({}, {"communities": None}, {"communities": 4}, None, 4, "4"):
+ with self.subTest(payload=payload):
+ self.assertEqual(mcp_server._community_count(payload), 0)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_mcp_server_graph_analytics.py b/tests/test_mcp_server_graph_analytics.py
new file mode 100644
index 00000000..41fc02f1
--- /dev/null
+++ b/tests/test_mcp_server_graph_analytics.py
@@ -0,0 +1,128 @@
+"""Regression tests for the MCP get_graph_analytics tool on a ContextGraph (issue #1747).
+
+The handler reads whatever `_get_graph()` returns, and the default is a
+ContextGraph. `calculate_pagerank` returns a nested result:
+
+ {"centrality": {node: score}, "rankings": [(node, score), ...]}
+
+The handler sorted that outer mapping instead, so its two entries (`centrality`,
+a dict, and `rankings`, a list) were compared with each other and the sort raised
+`'<' not supported between instances of 'dict' and 'list'`.
+
+Before #1744 the failure was masked: `calculate_pagerank` raised on a
+ContextGraph before the handler reached the sort line (that was issue #1721).
+`TestGraphAnalyticsRankings` stubs the PageRank call so the ranking path is
+pinned on its own; `TestGraphAnalyticsOnARealContextGraph` runs the whole path,
+which is reachable now that #1744 is on `main`.
+"""
+
+import json
+import unittest
+from unittest import mock
+
+from semantica import mcp_server
+from semantica.context import ContextGraph
+from semantica.kg import CentralityCalculator
+
+PAGERANK_RESULT = {
+ "centrality": {"alice": 0.5, "bob": 0.3, "acme": 0.2},
+ "rankings": [("alice", 0.5), ("bob", 0.3), ("acme", 0.2)],
+}
+
+
+def _graph() -> ContextGraph:
+ graph = ContextGraph(advanced_analytics=True)
+ graph.add_node("alice", node_type="Person", content="Alice")
+ graph.add_node("bob", node_type="Person", content="Bob")
+ graph.add_node("acme", node_type="Organization", content="Acme")
+ graph.add_edge("alice", "acme", edge_type="worksFor")
+ graph.add_edge("bob", "acme", edge_type="worksFor")
+ graph.add_edge("alice", "bob", edge_type="knows")
+ return graph
+
+
+class TestGraphAnalyticsRankings(unittest.TestCase):
+
+ def setUp(self):
+ self._old_graph = mcp_server._graph
+ mcp_server._graph = _graph()
+ patcher = mock.patch.object(
+ CentralityCalculator, "calculate_pagerank", return_value=PAGERANK_RESULT
+ )
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def tearDown(self):
+ mcp_server._graph = self._old_graph
+
+ def test_returns_nodes_ranked_by_pagerank_score(self):
+ result = mcp_server._tool_get_graph_analytics({})
+ self.assertNotIn("error", result, result)
+ self.assertEqual(
+ result["top_nodes_by_pagerank"],
+ [("alice", 0.5), ("bob", 0.3), ("acme", 0.2)],
+ )
+
+ def test_falls_back_to_the_centrality_mapping_without_rankings(self):
+ """A result that carries only `centrality` is still ranked, not dropped."""
+ with mock.patch.object(
+ CentralityCalculator,
+ "calculate_pagerank",
+ return_value={"centrality": {"alice": 0.5, "bob": 0.3, "acme": 0.2}},
+ ):
+ result = mcp_server._tool_get_graph_analytics({})
+ self.assertNotIn("error", result, result)
+ self.assertEqual(
+ result["top_nodes_by_pagerank"],
+ [("alice", 0.5), ("bob", 0.3), ("acme", 0.2)],
+ )
+
+ def test_reports_the_context_graph_counts(self):
+ """The counts in the same response come from `find_nodes()` and `stats()`."""
+ result = mcp_server._tool_get_graph_analytics({})
+ self.assertNotIn("error", result, result)
+ self.assertEqual(result["node_count"], 3)
+ self.assertEqual(result["edge_count"], 3)
+
+
+class TestGraphAnalyticsOnARealContextGraph(unittest.TestCase):
+ """The tool end to end, with no stubbed calculator."""
+
+ def setUp(self):
+ self._old_graph = mcp_server._graph
+ mcp_server._graph = _graph()
+
+ def tearDown(self):
+ mcp_server._graph = self._old_graph
+
+ def test_ranks_the_nodes_and_serialises_to_json(self):
+ result = mcp_server._tool_get_graph_analytics({})
+ self.assertNotIn("error", result, result)
+ self.assertEqual(result["node_count"], 3)
+ self.assertEqual(result["edge_count"], 3)
+ self.assertEqual(result["community_count"], 1)
+
+ ranked = result["top_nodes_by_pagerank"]
+ self.assertEqual({node for node, _ in ranked}, {"alice", "bob", "acme"})
+ scores = [score for _, score in ranked]
+ self.assertEqual(scores, sorted(scores, reverse=True))
+
+ # The response goes straight out over the MCP transport, so it has to
+ # survive a plain dump with no encoder of its own.
+ json.dumps(result)
+
+ def test_keeps_the_error_response_for_an_empty_graph(self):
+ """An empty graph still surfaces the calculator's own message.
+
+ This one holds on the base revision too. It is here to pin the
+ contract rather than to show the ranking fix, so that a later change
+ cannot quietly turn an empty graph into a zero-filled response.
+ """
+ mcp_server._graph = ContextGraph(advanced_analytics=True)
+ result = mcp_server._tool_get_graph_analytics({})
+ self.assertIn("error", result)
+ self.assertIn("No nodes found", result["error"])
+
+
+if __name__ == "__main__":
+ unittest.main()