Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(mcp): serialize Decision objects returned by get_causal_chain (#1655)

gyroscope1110cb7cbcc66b35
diff --git a/semantica/mcp_server/__init__.py b/semantica/mcp_server/__init__.py
index 03692c1f..592ef66c 100644
--- a/semantica/mcp_server/__init__.py
+++ b/semantica/mcp_server/__init__.py
@@ -275,7 +275,12 @@ def _tool_get_causal_chain(args: dict) -> dict:
from semantica.context.causal_analyzer import CausalChainAnalyzer
analyzer = CausalChainAnalyzer(graph_store=graph)
chain = analyzer.get_causal_chain(decision_id, direction=direction, max_depth=max_depth)
- return {"chain": chain if isinstance(chain, list) else list(chain)}
+ # The analyzer returns Decision dataclasses, and tools/call json.dumps
+ # this result. serialize_decision applies the existing default=str
+ # policy, which also covers non-JSON values inside decision metadata.
+ from semantica.context.decision_models import serialize_decision
+ return {"chain": [json.loads(serialize_decision(d)) if hasattr(d, "to_dict") else d
+ for d in chain]}
except Exception as exc:
return {"error": str(exc), "chain": []}
diff --git a/semantica_mcp/mcp/tools/decisions.py b/semantica_mcp/mcp/tools/decisions.py
index 61fc0383..9f51d695 100644
--- a/semantica_mcp/mcp/tools/decisions.py
+++ b/semantica_mcp/mcp/tools/decisions.py
@@ -4,6 +4,7 @@ Decision intelligence tools — record, query, precedents, causal chain, impact.
from __future__ import annotations
+import json
import logging
import os
from typing import Any
@@ -261,7 +262,17 @@ def handle_get_causal_chain(args: dict) -> dict:
),
"chain": [],
}
- result = chain if isinstance(chain, list) else list(chain)
+ # CausalChainAnalyzer returns Decision dataclasses, which the tools/call
+ # handler cannot json.dumps. serialize_decision applies the existing
+ # default=str policy, which also covers non-JSON values inside decision
+ # metadata. The fallback backends may already return plain values, so
+ # only objects exposing to_dict() are converted.
+ from semantica.context.decision_models import serialize_decision
+
+ result = [
+ json.loads(serialize_decision(item)) if hasattr(item, "to_dict") else item
+ for item in chain
+ ]
return {"chain": result, "count": len(result), "direction": direction}
except Exception as exc:
log.exception("get_causal_chain failed")
diff --git a/tests/test_mcp_decisions_causal_chain.py b/tests/test_mcp_decisions_causal_chain.py
index 2cfdb79e..8b63c3b2 100644
--- a/tests/test_mcp_decisions_causal_chain.py
+++ b/tests/test_mcp_decisions_causal_chain.py
@@ -7,6 +7,7 @@ import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
+import json
import unittest
from unittest.mock import MagicMock, patch
from semantica_mcp.mcp.tools.decisions import handle_get_causal_chain
@@ -265,5 +266,70 @@ class TestMCPDecisionsCausalChain(unittest.TestCase):
self.assertEqual(graph_mock.call_count, 1)
+class TestCausalChainSerializationWithRealGraph(unittest.TestCase):
+ """The tests above mock the analyzer, whose fake chains are strings. The
+ real CausalChainAnalyzer returns Decision dataclasses, and the tools/call
+ handler json.dumps the tool result, so every non-empty chain failed with
+ "Object of type Decision is not JSON serializable"."""
+
+ def setUp(self):
+ from semantica.context import ContextGraph
+
+ self.graph = ContextGraph(advanced_analytics=False)
+ self.ids = [
+ self.graph.record_decision(
+ category="compliance",
+ scenario=scenario,
+ reasoning="test",
+ outcome="approved",
+ confidence=0.9,
+ )
+ for scenario in ("Adopt HIPAA program", "Require BAA from vendors", "Host on AWS")
+ ]
+ self.graph.add_causal_relationship(self.ids[0], self.ids[1], "CAUSED")
+ self.graph.add_causal_relationship(self.ids[1], self.ids[2], "CAUSED")
+
+ def _tools_call(self, arguments):
+ from semantica_mcp.mcp.server import _handle_tools_call
+
+ with patch("semantica_mcp.mcp.tools.decisions.get_graph", return_value=self.graph):
+ response = _handle_tools_call(1, {"name": "get_causal_chain", "arguments": arguments})
+ self.assertNotIn("error", response)
+ return json.loads(response["result"]["content"][0]["text"])
+
+ def test_upstream_chain_round_trips_through_tools_call(self):
+ payload = self._tools_call({"decision_id": self.ids[2], "direction": "upstream"})
+ self.assertEqual(payload["count"], 2)
+ self.assertEqual(
+ {d["scenario"]: d["metadata"]["causal_distance"] for d in payload["chain"]},
+ {"Adopt HIPAA program": 2, "Require BAA from vendors": 1},
+ )
+
+ def test_downstream_chain_round_trips_through_tools_call(self):
+ payload = self._tools_call({"decision_id": self.ids[0], "direction": "downstream"})
+ self.assertEqual(
+ {d["scenario"]: d["metadata"]["causal_distance"] for d in payload["chain"]},
+ {"Require BAA from vendors": 1, "Host on AWS": 2},
+ )
+
+ def test_non_json_metadata_is_stringified(self):
+ from datetime import datetime
+
+ cause = self.graph.record_decision(
+ category="compliance",
+ scenario="Audit finding",
+ reasoning="test",
+ outcome="approved",
+ confidence=0.9,
+ metadata={"reviewed_at": datetime(2026, 9, 1), "tags": {"hipaa"}},
+ )
+ self.graph.add_causal_relationship(cause, self.ids[0], "CAUSED")
+
+ payload = self._tools_call({"decision_id": self.ids[0], "direction": "upstream"})
+ metadata = next(d["metadata"] for d in payload["chain"] if d["scenario"] == "Audit finding")
+ self.assertEqual(metadata["reviewed_at"], "2026-09-01 00:00:00")
+ self.assertIsInstance(metadata["tags"], str)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_mcp_server_causal_chain.py b/tests/test_mcp_server_causal_chain.py
new file mode 100644
index 00000000..2186fa66
--- /dev/null
+++ b/tests/test_mcp_server_causal_chain.py
@@ -0,0 +1,120 @@
+"""Regression tests: the MCP get_causal_chain tool failed on any non-empty chain.
+
+``CausalChainAnalyzer.get_causal_chain()`` returns ``Decision`` dataclasses.
+``_tool_get_causal_chain`` returned them as-is, and the tools/call handler then
+``json.dumps`` the result, so every chain that found a decision came back as
+
+ JSON-RPC -32603: Object of type Decision is not JSON serializable
+
+An empty chain serializes as ``[]``, which is why a graph with no causal links
+never showed the problem. These tests drive a real ContextGraph through the
+same tools/call handler a client hits.
+"""
+
+import json
+import unittest
+from datetime import datetime
+
+from semantica import mcp_server
+from semantica.context import ContextGraph
+
+SCENARIOS = ("Adopt HIPAA program", "Require BAA from vendors", "Host on AWS")
+
+
+def _linked_graph():
+ """Three decisions linked A -CAUSED-> B -CAUSED-> C."""
+ graph = ContextGraph(advanced_analytics=False)
+ ids = [
+ graph.record_decision(
+ category="compliance",
+ scenario=scenario,
+ reasoning="test",
+ outcome="approved",
+ confidence=0.9,
+ )
+ for scenario in SCENARIOS
+ ]
+ graph.add_causal_relationship(ids[0], ids[1], "CAUSED")
+ graph.add_causal_relationship(ids[1], ids[2], "CAUSED")
+ return graph, ids
+
+
+class TestGetCausalChainTool(unittest.TestCase):
+
+ def setUp(self):
+ self._old_graph = mcp_server._graph
+ self.graph, self.ids = _linked_graph()
+ mcp_server._graph = self.graph
+
+ def tearDown(self):
+ mcp_server._graph = self._old_graph
+
+ def _call(self, **arguments):
+ response = mcp_server._handle({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "tools/call",
+ "params": {"name": "get_causal_chain", "arguments": arguments},
+ })
+ # Before the fix this was {"error": {"code": -32603, ...}}.
+ self.assertNotIn("error", response)
+ payload = json.loads(response["result"]["content"][0]["text"])
+ self.assertNotIn("error", payload)
+ return payload["chain"]
+
+ @staticmethod
+ def _distances(chain):
+ return {d["scenario"]: d["metadata"]["causal_distance"] for d in chain}
+
+ def test_upstream_chain_serializes(self):
+ chain = self._call(decision_id=self.ids[2], direction="upstream")
+ self.assertEqual(
+ self._distances(chain),
+ {"Adopt HIPAA program": 2, "Require BAA from vendors": 1},
+ )
+
+ def test_downstream_chain_serializes(self):
+ chain = self._call(decision_id=self.ids[0], direction="downstream")
+ self.assertEqual(
+ self._distances(chain),
+ {"Require BAA from vendors": 1, "Host on AWS": 2},
+ )
+
+ def test_entries_are_plain_decision_dicts(self):
+ chain = self._call(decision_id=self.ids[2], direction="upstream")
+ for entry in chain:
+ self.assertIsInstance(entry, dict)
+ self.assertIn(entry["decision_id"], self.ids)
+ self.assertIsInstance(entry["timestamp"], str)
+
+ def test_non_json_metadata_is_stringified(self):
+ """record_decision accepts arbitrary metadata values; a datetime or set
+ in a chained decision must not break the response either."""
+ cause = self.graph.record_decision(
+ category="compliance",
+ scenario="Audit finding",
+ reasoning="test",
+ outcome="approved",
+ confidence=0.9,
+ metadata={"reviewed_at": datetime(2026, 9, 1), "tags": {"hipaa"}},
+ )
+ self.graph.add_causal_relationship(cause, self.ids[0], "CAUSED")
+
+ chain = self._call(decision_id=self.ids[0], direction="upstream")
+ metadata = next(d["metadata"] for d in chain if d["scenario"] == "Audit finding")
+ self.assertEqual(metadata["reviewed_at"], "2026-09-01 00:00:00")
+ self.assertIsInstance(metadata["tags"], str)
+
+ def test_unlinked_decision_still_returns_empty_chain(self):
+ lone = self.graph.record_decision(
+ category="compliance",
+ scenario="Unrelated",
+ reasoning="test",
+ outcome="approved",
+ confidence=0.9,
+ )
+ self.assertEqual(self._call(decision_id=lone, direction="upstream"), [])
+
+
+if __name__ == "__main__":
+ unittest.main()