Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
refactor(mcp): harden handle_get_causal_chain inputs and signature introspection (#781)
Sameer6305a1f835c9b2ee
diff --git a/mcp/tools/decisions.py b/mcp/tools/decisions.pyindex 57de2c3a..d18117c5 100644--- a/mcp/tools/decisions.py+++ b/mcp/tools/decisions.py@@ -91,11 +91,19 @@ def handle_find_precedents(args: dict) -> dict:def handle_get_causal_chain(args: dict) -> dict:"""Trace the upstream or downstream causal chain from a decision."""- decision_id = args.get("decision_id", "").strip()+ if not isinstance(args, dict):+ return {"error": "args must be a dictionary", "chain": []}+ decision_id = str(args.get("decision_id") or "").strip()if not decision_id:return {"error": "decision_id is required", "chain": []}- direction = args.get("direction", "downstream")- max_depth = int(args.get("max_depth", 5))+ direction = str(args.get("direction") or "downstream").strip()+ try:+ max_depth = int(args.get("max_depth", 5))+ if max_depth <= 0:+ max_depth = 5+ max_depth = min(max_depth, 100)+ except (ValueError, TypeError):+ max_depth = 5try:graph = get_graph()try:@@ -106,23 +114,60 @@ def handle_get_causal_chain(args: dict) -> dict:)except (ImportError, AttributeError):if hasattr(graph, "get_causal_chain"):+ import inspecttry:- chain = graph.get_causal_chain(- decision_id,- direction=direction,- max_depth=max_depth,+ sig = inspect.signature(graph.get_causal_chain)+ params = sig.parameters+ has_var_kwargs = any(+ p.kind == inspect.Parameter.VAR_KEYWORD+ for p in params.values())- except TypeError:- try:+ if has_var_kwargs or (+ "direction" in params and "max_depth" in params+ ):+ chain = graph.get_causal_chain(+ decision_id,+ direction=direction,+ max_depth=max_depth,+ )+ elif "depth" in params:chain = graph.get_causal_chain(decision_id,depth=max_depth,)- except TypeError:+ else:chain = graph.get_causal_chain(decision_id)+ except (ValueError, TypeError):+ try:+ chain = graph.get_causal_chain(+ decision_id,+ direction=direction,+ max_depth=max_depth,+ )+ except TypeError as exc:+ if "unexpected keyword argument" in str(+ exc+ ) or "positional" in str(exc):+ try:+ chain = graph.get_causal_chain(+ decision_id,+ depth=max_depth,+ )+ except TypeError as exc2:+ if "unexpected keyword argument" in str(+ exc2+ ) or "positional" in str(exc2):+ chain = graph.get_causal_chain(decision_id)+ else:+ raise+ else:+ raiseelse:return {- "error": "Causal chain analysis is not supported on this graph backend",+ "error": (+ "Causal chain analysis is not supported on this graph"+ " backend"+ ),"chain": [],}result = chain if isinstance(chain, list) else list(chain)diff --git a/tests/test_mcp_decisions_causal_chain.py b/tests/test_mcp_decisions_causal_chain.pyindex 76e389c3..841c00e2 100644--- a/tests/test_mcp_decisions_causal_chain.py+++ b/tests/test_mcp_decisions_causal_chain.py@@ -188,6 +188,50 @@ class TestMCPDecisionsCausalChain(unittest.TestCase):{"chain": ["pos_node"], "count": 1, "direction": "downstream"},)+ @patch("mcp.tools.decisions.get_graph")+ @patch("semantica.context.causal_analyzer.CausalChainAnalyzer")+ def test_input_hardening_and_dos_prevention(+ self, mock_analyzer_cls, mock_get_graph+ ):+ """Verify non-dict args, non-string IDs, and max_depth bounds clamping."""+ self.assertEqual(+ handle_get_causal_chain(None),+ {"error": "args must be a dictionary", "chain": []},+ )+ mock_analyzer_instance = MagicMock()+ mock_analyzer_instance.get_causal_chain.return_value = ["n1"]+ mock_analyzer_cls.return_value = mock_analyzer_instance+ mock_get_graph.return_value = MagicMock()++ # Test integer decision_id and huge max_depth clamping (1000 -> 100)+ resp = handle_get_causal_chain(+ {"decision_id": 12345, "max_depth": 1000}+ )+ self.assertEqual(resp["chain"], ["n1"])+ mock_analyzer_instance.get_causal_chain.assert_called_once_with(+ "12345", direction="downstream", max_depth=100+ )++ @patch("mcp.tools.decisions.get_graph")+ @patch("semantica.context.causal_analyzer.CausalChainAnalyzer")+ def test_internal_typeerror_not_masked(self, mock_analyzer_cls, mock_get_graph):+ """Verify internal TypeError inside get_causal_chain is not masked as signature error."""+ mock_analyzer_cls.side_effect = ImportError("mocked import error")++ class BadInternalGraphMock:+ def get_causal_chain(self, node_id, direction="downstream", max_depth=5):+ raise TypeError("unsupported operand type(s) for +: 'int' and 'str'")++ mock_get_graph.return_value = BadInternalGraphMock()+ response = handle_get_causal_chain({"decision_id": "dec_err"})+ self.assertEqual(+ response,+ {+ "error": "unsupported operand type(s) for +: 'int' and 'str'",+ "chain": [],+ },+ )+if __name__ == "__main__":unittest.main()