Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix: report skipped causal relationships instead of failing silently (#1715)

iuiuiudf8e852279a3
diff --git a/semantica/context/context_graph.py b/semantica/context/context_graph.py
index ef96d22a..00528f49 100644
--- a/semantica/context/context_graph.py
+++ b/semantica/context/context_graph.py
@@ -3890,14 +3890,24 @@ class ContextGraph:
source_decision_id: str,
target_decision_id: str,
relationship_type: str
- ) -> None:
+ ) -> bool:
"""
Add causal relationship between decisions.
-
+
Args:
source_decision_id: Source decision ID
target_decision_id: Target decision ID
relationship_type: Type of relationship (CAUSED, INFLUENCED, PRECEDENT_FOR)
+
+ Returns:
+ True when a new causal edge was inserted.
+ False when the operation was skipped without inserting an edge:
+ - source or target decision ID is not present in the graph;
+ - source or target node exists but is not a decision node;
+ - an equivalent causal relationship (same source, target, and
+ normalized relationship type) already exists.
+ Skipped operations are logged at WARNING level. Invalid
+ relationship types raise ValueError instead of returning False.
"""
# Normalize so callers may use either vocabulary's spelling
# ("causes" from CausalChainAnalyzer, or "CAUSED" from this module's
@@ -3911,17 +3921,25 @@ class ContextGraph:
# Check if decisions exist - if not, skip adding relationship
if source_decision_id not in self.nodes or target_decision_id not in self.nodes:
- return
-
+ self.logger.warning(
+ "add_causal_relationship skipped: unknown decision id(s) "
+ f"'{source_decision_id}' -> '{target_decision_id}'"
+ )
+ return False
+
# Check if nodes are decision nodes - if not, skip adding relationship
source_node = self.nodes[source_decision_id]
target_node = self.nodes[target_decision_id]
if (not hasattr(source_node, 'node_type') or not isinstance(source_node.node_type, str) or
not hasattr(target_node, 'node_type') or not isinstance(target_node.node_type, str) or
- source_node.node_type.lower() != "decision" or
+ source_node.node_type.lower() != "decision" or
target_node.node_type.lower() != "decision"):
- return
-
+ self.logger.warning(
+ "add_causal_relationship skipped: nodes are not decision nodes "
+ f"('{source_decision_id}' -> '{target_decision_id}')"
+ )
+ return False
+
edge = ContextEdge(
source_id=source_decision_id,
target_id=target_decision_id,
@@ -3929,7 +3947,22 @@ class ContextGraph:
weight=1.0,
metadata={"recorded_at": datetime.utcnow().isoformat()},
)
- self._add_internal_edge(edge)
+ # Guard against semantic duplicates: two calls with the same
+ # (source, target, relationship_type) triple represent the same causal
+ # link regardless of when they are recorded. The content-derived
+ # edge_id includes recorded_at, so _add_internal_edge cannot detect
+ # this. The duplicate check and the insertion are held under the same
+ # lock acquisition so no concurrent call can slip through between them.
+ # self._lock is an RLock, so the nested acquisition inside
+ # _add_internal_edge by the same thread is safe.
+ with self._lock:
+ existing = self._adjacency.get(source_decision_id, [])
+ if any(
+ e.target_id == target_decision_id and e.edge_type == relationship_type
+ for e in existing
+ ):
+ return False
+ return self._add_internal_edge(edge)
def get_causal_chain(
self,
diff --git a/semantica/mcp_server/__init__.py b/semantica/mcp_server/__init__.py
index 592ef66c..bf539386 100644
--- a/semantica/mcp_server/__init__.py
+++ b/semantica/mcp_server/__init__.py
@@ -285,6 +285,31 @@ def _tool_get_causal_chain(args: dict) -> dict:
return {"error": str(exc), "chain": []}
+def _tool_link_decisions(args: dict) -> dict:
+ """Create a typed causal relationship between two recorded decisions."""
+ source = str(args.get("source") or "").strip()
+ target = str(args.get("target") or "").strip()
+ relationship = str(args.get("relationship") or "").strip()
+ if not source or not target:
+ return {"error": "source and target are required"}
+ if not relationship:
+ return {"error": "relationship is required"}
+ graph = _get_graph()
+ try:
+ added = graph.add_causal_relationship(source, target, relationship)
+ except ValueError as exc:
+ return {"error": str(exc)}
+ except Exception as exc:
+ log.exception("link_decisions failed")
+ return {"error": str(exc)}
+ return {
+ "source": source,
+ "target": target,
+ "relationship": relationship,
+ "linked": added,
+ }
+
+
def _tool_add_entity(args: dict) -> dict:
"""Add a node/entity to the knowledge graph."""
node_id = args.get("id", "")
@@ -698,6 +723,20 @@ TOOLS = [
},
"_handler": _tool_get_causal_chain,
},
+ {
+ "name": "link_decisions",
+ "description": "Create a typed causal relationship between two recorded decisions (CAUSED, INFLUENCED, or PRECEDENT_FOR).",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "source": {"type": "string", "description": "Source decision ID (the cause)"},
+ "target": {"type": "string", "description": "Target decision ID (the effect)"},
+ "relationship": {"type": "string", "enum": ["CAUSED", "INFLUENCED", "PRECEDENT_FOR"], "description": "Causal relationship type"},
+ },
+ "required": ["source", "target", "relationship"],
+ },
+ "_handler": _tool_link_decisions,
+ },
{
"name": "add_entity",
"description": "Add a node/entity to the Semantica knowledge graph.",
diff --git a/semantica_mcp/mcp/README.md b/semantica_mcp/mcp/README.md
index 901b83b4..0e6e7c91 100644
--- a/semantica_mcp/mcp/README.md
+++ b/semantica_mcp/mcp/README.md
@@ -31,7 +31,7 @@ python -m mcp [--debug]
---
-## Tools (17 total)
+## Tools (18 total)
### Extraction
@@ -50,6 +50,7 @@ python -m mcp [--debug]
| `find_precedents` | Find past decisions similar to a scenario (hybrid similarity) |
| `get_causal_chain` | Trace upstream/downstream causal chain from a decision |
| `analyze_decision_impact` | Analyse downstream influence of a decision |
+| `link_decisions` | Create a causal relationship (CAUSED, INFLUENCED, PRECEDENT_FOR) between two decisions |
### Knowledge Graph
diff --git a/semantica_mcp/mcp/schemas.py b/semantica_mcp/mcp/schemas.py
index 19d7eb01..4c909cb6 100644
--- a/semantica_mcp/mcp/schemas.py
+++ b/semantica_mcp/mcp/schemas.py
@@ -151,6 +151,26 @@ ANALYZE_DECISION_IMPACT = {
"required": ["decision_id"],
}
+LINK_DECISIONS = {
+ "type": "object",
+ "properties": {
+ "source": {
+ "type": "string",
+ "description": "Source decision ID (the cause)",
+ },
+ "target": {
+ "type": "string",
+ "description": "Target decision ID (the effect)",
+ },
+ "relationship": {
+ "type": "string",
+ "enum": ["CAUSED", "INFLUENCED", "PRECEDENT_FOR"],
+ "description": "Causal relationship type",
+ },
+ },
+ "required": ["source", "target", "relationship"],
+}
+
ADD_ENTITY = {
"type": "object",
"properties": {
diff --git a/semantica_mcp/mcp/tools/decisions.py b/semantica_mcp/mcp/tools/decisions.py
index 9f51d695..28124095 100644
--- a/semantica_mcp/mcp/tools/decisions.py
+++ b/semantica_mcp/mcp/tools/decisions.py
@@ -13,6 +13,7 @@ from ..schemas import (
ANALYZE_DECISION_IMPACT,
FIND_PRECEDENTS,
GET_CAUSAL_CHAIN,
+ LINK_DECISIONS,
QUERY_DECISIONS,
RECORD_DECISION,
)
@@ -298,6 +299,31 @@ def handle_analyze_decision_impact(args: dict) -> dict:
return {"error": str(exc)}
+def handle_link_decisions(args: dict) -> dict:
+ """Create a typed causal relationship between two recorded decisions."""
+ source = str(args.get("source") or "").strip()
+ target = str(args.get("target") or "").strip()
+ relationship = str(args.get("relationship") or "").strip()
+ if not source or not target:
+ return {"error": "source and target are required"}
+ if not relationship:
+ return {"error": "relationship is required"}
+ try:
+ graph = get_graph()
+ added = graph.add_causal_relationship(source, target, relationship)
+ except ValueError as exc:
+ return {"error": str(exc)}
+ except Exception as exc:
+ log.exception("link_decisions failed")
+ return {"error": str(exc)}
+ return {
+ "source": source,
+ "target": target,
+ "relationship": relationship,
+ "linked": added,
+ }
+
+
DECISION_TOOLS = [
{
"name": "record_decision",
@@ -329,4 +355,10 @@ DECISION_TOOLS = [
"inputSchema": ANALYZE_DECISION_IMPACT,
"_handler": handle_analyze_decision_impact,
},
+ {
+ "name": "link_decisions",
+ "description": "Create a typed causal relationship between two recorded decisions (CAUSED, INFLUENCED, or PRECEDENT_FOR). Use this after record_decision to connect decisions into a causal chain that get_causal_chain can then traverse.",
+ "inputSchema": LINK_DECISIONS,
+ "_handler": handle_link_decisions,
+ },
]
diff --git a/tests/context/test_decision_causal_edge_regression.py b/tests/context/test_decision_causal_edge_regression.py
index 3bfa1591..8370407e 100644
--- a/tests/context/test_decision_causal_edge_regression.py
+++ b/tests/context/test_decision_causal_edge_regression.py
@@ -491,3 +491,93 @@ def test_heuristic_cause_reported_once_per_shared_entity_pair():
assert influence_hops.count((cause, effect)) == 1, (
"the same (cause, effect) pair must be reported once, not once per shared entity"
)
+
+
+# ── Issue #1653: add_causal_relationship() bool return contract ──────────────
+
+def _two_decision_graph():
+ """Return a fresh graph with two recorded decisions and their IDs."""
+ graph = ContextGraph(advanced_analytics=False)
+ source_id = graph.record_decision(
+ category="infra", scenario="Deploy service A", reasoning="r",
+ outcome="approved", confidence=0.9,
+ )
+ target_id = graph.record_decision(
+ category="infra", scenario="Deploy service B", reasoning="r",
+ outcome="approved", confidence=0.8,
+ )
+ return graph, source_id, target_id
+
+
+def test_add_causal_relationship_returns_true_on_first_insertion():
+ """Successful first insertion must return True (issue #1653 Part 2)."""
+ graph, src, tgt = _two_decision_graph()
+ result = graph.add_causal_relationship(src, tgt, "CAUSED")
+ assert result is True
+
+
+def test_add_causal_relationship_returns_false_for_missing_source():
+ """Unknown source ID → False + warning (issue #1653 Part 2)."""
+ graph, _, tgt = _two_decision_graph()
+ result = graph.add_causal_relationship("nonexistent_source", tgt, "CAUSED")
+ assert result is False
+
+
+def test_add_causal_relationship_returns_false_for_missing_target():
+ """Unknown target ID → False + warning (issue #1653 Part 2)."""
+ graph, src, _ = _two_decision_graph()
+ result = graph.add_causal_relationship(src, "nonexistent_target", "CAUSED")
+ assert result is False
+
+
+def test_add_causal_relationship_missing_id_emits_warning(caplog):
+ """Missing ID skip must log a WARNING containing both IDs."""
+ import logging
+ graph, src, _ = _two_decision_graph()
+ with caplog.at_level(logging.WARNING, logger="semantica.context.context_graph"):
+ graph.add_causal_relationship(src, "no_such_id", "CAUSED")
+ assert any("no_such_id" in r.message for r in caplog.records), (
+ "warning message must contain the unknown target ID"
+ )
+ assert any(src in r.message for r in caplog.records), (
+ "warning message must also contain the source ID"
+ )
+
+
+def test_add_causal_relationship_returns_false_for_non_decision_source():
+ """Non-decision source node → False + warning (issue #1653 Part 2)."""
+ graph, _, tgt = _two_decision_graph()
+ graph.add_node(node_id="entity_src", label="plain entity", node_type="Entity")
+ result = graph.add_causal_relationship("entity_src", tgt, "CAUSED")
+ assert result is False
+
+
+def test_add_causal_relationship_returns_false_for_non_decision_target():
+ """Non-decision target node → False + warning (issue #1653 Part 2)."""
+ graph, src, _ = _two_decision_graph()
+ graph.add_node(node_id="entity_tgt", label="plain entity", node_type="Entity")
+ result = graph.add_causal_relationship(src, "entity_tgt", "CAUSED")
+ assert result is False
+
+
+def test_add_causal_relationship_non_decision_node_emits_warning(caplog):
+ """Non-decision node skip must log a WARNING containing both IDs."""
+ import logging
+ graph, src, _ = _two_decision_graph()
+ graph.add_node(node_id="non_dec", label="plain entity", node_type="Entity")
+ with caplog.at_level(logging.WARNING, logger="semantica.context.context_graph"):
+ graph.add_causal_relationship(src, "non_dec", "CAUSED")
+ assert any("non_dec" in r.message for r in caplog.records)
+ assert any(src in r.message for r in caplog.records)
+
+
+def test_add_causal_relationship_returns_false_for_duplicate():
+ """Duplicate insertion of the same causal edge must return False (issue #1653 Part 2)."""
+ graph, src, tgt = _two_decision_graph()
+ first = graph.add_causal_relationship(src, tgt, "CAUSED")
+ second = graph.add_causal_relationship(src, tgt, "CAUSED")
+ assert first is True
+ assert second is False
+ # Exactly one edge stored, not two.
+ causal_edges = [e for e in graph.edges if e.source_id == src and e.target_id == tgt]
+ assert len(causal_edges) == 1
diff --git a/tests/test_mcp_decisions_link.py b/tests/test_mcp_decisions_link.py
new file mode 100644
index 00000000..7ea07ae3
--- /dev/null
+++ b/tests/test_mcp_decisions_link.py
@@ -0,0 +1,374 @@
+"""
+Tests for issue #1653 Part 1 — link_decisions MCP tool.
+
+Covers:
+- Validation (missing source, target, relationship)
+- Successful link surfacing True from add_causal_relationship
+- Skipped link (unknown IDs) surfacing False from add_causal_relationship
+- Invalid relationship type returning an error dict (ValueError path)
+- Unexpected exception returning an error dict
+- Tool exposed in the embedded server (semantica.mcp_server)
+- Tool exposed in the modular server (semantica_mcp.mcp)
+- End-to-end: record two decisions → link → get_causal_chain observes the edge
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import unittest
+from unittest.mock import MagicMock, patch
+
+sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
+
+from semantica_mcp.mcp.tools.decisions import handle_link_decisions
+
+
+# ── Modular server: handle_link_decisions unit tests ─────────────────────────
+
+class TestHandleLinkDecisions(unittest.TestCase):
+ """Unit tests for semantica_mcp.mcp.tools.decisions.handle_link_decisions."""
+
+ def test_missing_source_returns_error(self):
+ result = handle_link_decisions({"target": "tgt_1", "relationship": "CAUSED"})
+ self.assertIn("error", result)
+ self.assertNotIn("linked", result)
+
+ def test_missing_target_returns_error(self):
+ result = handle_link_decisions({"source": "src_1", "relationship": "CAUSED"})
+ self.assertIn("error", result)
+ self.assertNotIn("linked", result)
+
+ def test_missing_relationship_returns_error(self):
+ result = handle_link_decisions({"source": "src_1", "target": "tgt_1"})
+ self.assertIn("error", result)
+ self.assertNotIn("linked", result)
+
+ def test_empty_source_returns_error(self):
+ result = handle_link_decisions(
+ {"source": " ", "target": "tgt_1", "relationship": "CAUSED"}
+ )
+ self.assertIn("error", result)
+
+ @patch("semantica_mcp.mcp.tools.decisions.get_graph")
+ def test_successful_link_returns_linked_true(self, mock_get_graph):
+ """When add_causal_relationship returns True, linked must be True."""
+ mock_graph = MagicMock()
+ mock_graph.add_causal_relationship.return_value = True
+ mock_get_graph.return_value = mock_graph
+
+ result = handle_link_decisions(
+ {"source": "dec_a", "target": "dec_b", "relationship": "CAUSED"}
+ )
+
+ mock_graph.add_causal_relationship.assert_called_once_with("dec_a", "dec_b", "CAUSED")
+ self.assertEqual(
+ result,
+ {"source": "dec_a", "target": "dec_b", "relationship": "CAUSED", "linked": True},
+ )
+
+ @patch("semantica_mcp.mcp.tools.decisions.get_graph")
+ def test_skipped_link_returns_linked_false(self, mock_get_graph):
+ """When add_causal_relationship returns False (unknown ID), linked must be False."""
+ mock_graph = MagicMock()
+ mock_graph.add_causal_relationship.return_value = False
+ mock_get_graph.return_value = mock_graph
+
+ result = handle_link_decisions(
+ {"source": "dec_a", "target": "unknown_id", "relationship": "INFLUENCED"}
+ )
+
+ self.assertNotIn("error", result)
+ self.assertEqual(result["linked"], False)
+ self.assertEqual(result["source"], "dec_a")
+ self.assertEqual(result["target"], "unknown_id")
+ self.assertEqual(result["relationship"], "INFLUENCED")
+
+ @patch("semantica_mcp.mcp.tools.decisions.get_graph")
+ def test_invalid_relationship_type_returns_error(self, mock_get_graph):
+ """ValueError from add_causal_relationship (bad type) must surface as error dict."""
+ mock_graph = MagicMock()
+ mock_graph.add_causal_relationship.side_effect = ValueError(
+ "Relationship type must be one of: ('CAUSED', 'INFLUENCED', 'PRECEDENT_FOR')"
+ )
+ mock_get_graph.return_value = mock_graph
+
+ result = handle_link_decisions(
+ {"source": "dec_a", "target": "dec_b", "relationship": "ZAPS"}
+ )
+
+ self.assertIn("error", result)
+ self.assertIn("CAUSED", result["error"])
+ self.assertNotIn("linked", result)
+
+ @patch("semantica_mcp.mcp.tools.decisions.get_graph")
+ def test_unexpected_exception_returns_error(self, mock_get_graph):
+ """Any non-ValueError exception must surface as an error dict, not propagate."""
+ mock_graph = MagicMock()
+ mock_graph.add_causal_relationship.side_effect = RuntimeError("graph locked")
+ mock_get_graph.return_value = mock_graph
+
+ result = handle_link_decisions(
+ {"source": "dec_a", "target": "dec_b", "relationship": "CAUSED"}
+ )
+
+ self.assertIn("error", result)
+ self.assertEqual(result["error"], "graph locked")
+ self.assertNotIn("linked", result)
+
+ @patch("semantica_mcp.mcp.tools.decisions.get_graph")
+ def test_passes_args_exactly_to_add_causal_relationship(self, mock_get_graph):
+ """handler must forward source/target/relationship strings verbatim."""
+ mock_graph = MagicMock()
+ mock_graph.add_causal_relationship.return_value = True
+ mock_get_graph.return_value = mock_graph
+
+ handle_link_decisions(
+ {"source": " dec_x ", "target": " dec_y ", "relationship": "PRECEDENT_FOR"}
+ )
+
+ # Strings must be stripped before forwarding.
+ mock_graph.add_causal_relationship.assert_called_once_with(
+ "dec_x", "dec_y", "PRECEDENT_FOR"
+ )
+
+
+# ── Modular server: tool discovery ───────────────────────────────────────────
+
+class TestModularServerLinkDecisionsRegistration(unittest.TestCase):
+ """Verify link_decisions is discoverable through the modular MCP server."""
+
+ def test_link_decisions_in_tool_definitions(self):
+ from semantica_mcp.mcp.tools import TOOL_DEFINITIONS
+
+ names = [t["name"] for t in TOOL_DEFINITIONS]
+ self.assertIn(
+ "link_decisions",
+ names,
+ "link_decisions must be registered in TOOL_DEFINITIONS",
+ )
+
+ def test_link_decisions_handler_is_callable(self):
+ from semantica_mcp.mcp.tools import TOOL_DEFINITIONS
+
+ tool = next(t for t in TOOL_DEFINITIONS if t["name"] == "link_decisions")
+ self.assertTrue(callable(tool["_handler"]))
+
+ def test_link_decisions_schema_has_required_fields(self):
+ from semantica_mcp.mcp.tools import TOOL_DEFINITIONS
+
+ tool = next(t for t in TOOL_DEFINITIONS if t["name"] == "link_decisions")
+ schema = tool["inputSchema"]
+ self.assertEqual(set(schema["required"]), {"source", "target", "relationship"})
+
+ def test_link_decisions_callable_via_call_tool(self):
+ """call_tool must dispatch link_decisions without raising UnknownToolError."""
+ from semantica_mcp.mcp.server import UnknownToolError, call_tool
+
+ # Missing args hit our own validation before reaching the graph.
+ result = call_tool("link_decisions", {})
+ self.assertIn("error", result)
+ self.assertNotIn("linked", result)
+ # Must not raise UnknownToolError — the tool is registered.
+ with self.assertRaises(UnknownToolError):
+ call_tool("link_decisions_nonexistent", {})
+
+
+# ── Embedded server: tool discovery ──────────────────────────────────────────
+
+class TestEmbeddedServerLinkDecisionsRegistration(unittest.TestCase):
+ """Verify link_decisions is discoverable through the embedded MCP server."""
+
+ def test_link_decisions_in_tools_list(self):
+ from semantica.mcp_server import TOOLS
+
+ names = [t["name"] for t in TOOLS]
+ self.assertIn(
+ "link_decisions",
+ names,
+ "link_decisions must be registered in TOOLS",
+ )
+
+ def test_link_decisions_schema_required(self):
+ from semantica.mcp_server import TOOLS
+
+ tool = next(t for t in TOOLS if t["name"] == "link_decisions")
+ schema = tool["inputSchema"]
+ self.assertEqual(set(schema["required"]), {"source", "target", "relationship"})
+
+ def test_link_decisions_handler_missing_args(self):
+ """Embedded handler must return error dict on missing args, not raise."""
+ from semantica.mcp_server import TOOLS
+
+ handler = next(t["_handler"] for t in TOOLS if t["name"] == "link_decisions")
+ result = handler({})
+ self.assertIn("error", result)
+
+ @patch("semantica.mcp_server._get_graph")
+ def test_embedded_handler_calls_add_causal_relationship(self, mock_get_graph):
+ """Embedded handler must forward source/target/relationship to add_causal_relationship."""
+ from semantica.mcp_server import TOOLS
+
+ mock_graph = MagicMock()
+ mock_graph.add_causal_relationship.return_value = True
+ mock_get_graph.return_value = mock_graph
+
+ handler = next(t["_handler"] for t in TOOLS if t["name"] == "link_decisions")
+ result = handler({"source": "s1", "target": "t1", "relationship": "CAUSED"})
+
+ mock_graph.add_causal_relationship.assert_called_once_with("s1", "t1", "CAUSED")
+ self.assertEqual(result["linked"], True)
+ self.assertEqual(result["source"], "s1")
+ self.assertEqual(result["target"], "t1")
+ self.assertEqual(result["relationship"], "CAUSED")
+
+ @patch("semantica.mcp_server._get_graph")
+ def test_embedded_handler_surfaces_false_for_skip(self, mock_get_graph):
+ """Embedded handler must surface linked=False when add_causal_relationship returns False."""
+ from semantica.mcp_server import TOOLS
+
+ mock_graph = MagicMock()
+ mock_graph.add_causal_relationship.return_value = False
+ mock_get_graph.return_value = mock_graph
+
+ handler = next(t["_handler"] for t in TOOLS if t["name"] == "link_decisions")
+ result = handler({"source": "s1", "target": "unknown", "relationship": "CAUSED"})
+
+ self.assertNotIn("error", result)
+ self.assertFalse(result["linked"])
+
+ @patch("semantica.mcp_server._get_graph")
+ def test_embedded_handler_invalid_relationship_type_returns_error(self, mock_get_graph):
+ """Embedded handler must convert ValueError to error dict."""
+ from semantica.mcp_server import TOOLS
+
+ mock_graph = MagicMock()
+ mock_graph.add_causal_relationship.side_effect = ValueError("bad type")
+ mock_get_graph.return_value = mock_graph
+
+ handler = next(t["_handler"] for t in TOOLS if t["name"] == "link_decisions")
+ result = handler({"source": "s1", "target": "t1", "relationship": "BAD"})
+
+ self.assertIn("error", result)
+ self.assertNotIn("linked", result)
+
+
+# ── End-to-end: record → link → get_causal_chain (modular server) ────────────
+
+class TestLinkDecisionsEndToEnd(unittest.TestCase):
+ """
+ End-to-end test: two decisions are recorded, linked via link_decisions,
+ and get_causal_chain must subsequently see the causal relationship.
+ Uses the real ContextGraph with both handlers patched to share one graph.
+ """
+
+ def setUp(self):
+ from semantica.context import ContextGraph
+
+ self.graph = ContextGraph(advanced_analytics=False)
+ self.cause_id = self.graph.record_decision(
+ category="compliance",
+ scenario="Adopt encryption at rest",
+ reasoning="regulatory requirement",
+ outcome="approved",
+ confidence=0.95,
+ )
+ self.effect_id = self.graph.record_decision(
+ category="compliance",
+ scenario="Migrate database to encrypted volume",
+ reasoning="follows from encryption decision",
+ outcome="approved",
+ confidence=0.90,
+ )
+
+ def _call_modular(self, tool_name, 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": tool_name, "arguments": arguments})
+ self.assertNotIn("error", response, f"{tool_name} returned an error: {response}")
+ return json.loads(response["result"]["content"][0]["text"])
+
+ def test_link_then_causal_chain_observes_edge(self):
+ """After link_decisions, get_causal_chain must return the linked decision."""
+ # Step 1: link
+ link_result = self._call_modular(
+ "link_decisions",
+ {"source": self.cause_id, "target": self.effect_id, "relationship": "CAUSED"},
+ )
+ self.assertTrue(link_result["linked"], "link_decisions must report linked=True")
+
+ # Step 2: trace downstream from cause
+ chain_result = self._call_modular(
+ "get_causal_chain",
+ {"decision_id": self.cause_id, "direction": "downstream"},
+ )
+ chain_ids = [d["decision_id"] for d in chain_result["chain"]]
+ self.assertIn(
+ self.effect_id,
+ chain_ids,
+ "get_causal_chain must see the effect decision after link_decisions",
+ )
+
+ def test_duplicate_link_returns_false(self):
+ """Calling link_decisions twice with the same pair returns False on the second call."""
+ first = self._call_modular(
+ "link_decisions",
+ {"source": self.cause_id, "target": self.effect_id, "relationship": "CAUSED"},
+ )
+ second = self._call_modular(
+ "link_decisions",
+ {"source": self.cause_id, "target": self.effect_id, "relationship": "CAUSED"},
+ )
+ self.assertTrue(first["linked"])
+ self.assertFalse(second["linked"])
+
+ def test_link_unknown_id_returns_false_not_error(self):
+ """Linking to an unknown ID returns linked=False, not an error key."""
+ result = self._call_modular(
+ "link_decisions",
+ {"source": self.cause_id, "target": "nonexistent_id", "relationship": "INFLUENCED"},
+ )
+ self.assertFalse(result["linked"])
+ self.assertNotIn("error", result)
+
+
+if __name__ == "__main__":
+ unittest.main()
+
+
+# ── Embedded server: None-argument regression (issue #1653 HIGH finding) ─────
+
+class TestEmbeddedLinkDecisionsNoneArguments(unittest.TestCase):
+ """Verify the embedded handler does not crash when any argument is None.
+
+ JSON null becomes Python None in the args dict. The handler must return
+ a clean error dict — not raise AttributeError — for each case.
+ """
+
+ def _handler(self):
+ from semantica.mcp_server import TOOLS
+ return next(t["_handler"] for t in TOOLS if t["name"] == "link_decisions")
+
+ def test_none_source_returns_error_not_exception(self):
+ result = self._handler()({"source": None, "target": "dec_t", "relationship": "CAUSED"})
+ self.assertIn("error", result)
+ self.assertNotIn("linked", result)
+
+ def test_none_target_returns_error_not_exception(self):
+ result = self._handler()({"source": "dec_s", "target": None, "relationship": "CAUSED"})
+ self.assertIn("error", result)
+ self.assertNotIn("linked", result)
+
+ def test_none_relationship_returns_error_not_exception(self):
+ result = self._handler()({"source": "dec_s", "target": "dec_t", "relationship": None})
+ self.assertIn("error", result)
+ self.assertNotIn("linked", result)
+
+ def test_all_none_returns_error_not_exception(self):
+ result = self._handler()({"source": None, "target": None, "relationship": None})
+ self.assertIn("error", result)
+ self.assertNotIn("linked", result)