Exposing Context Graph and Decision Tools via the Semantica MCP Server

The Semantica MCP server exposes the knowledge graph and decision-intelligence layer through a JSON-RPC 2.0 interface, allowing external AI tools to manipulate entities, relationships, and decision records via standardized tool handlers.

The Model Context Protocol (MCP) server in the semantica-agi/semantica repository transforms Semantica’s core Python library into a language-agnostic gateway. By exposing context graph and decision tools via the MCP server, Claude Code, Cursor, VS Code Copilot, and other compatible clients can read, write, and analyze the knowledge base without direct library access.

MCP Server Architecture and Request Flow

The server operates as a stdio-based JSON-RPC gateway that maps incoming requests to specific Python handlers through a centralized tool index.

JSON-RPC 2.0 Dispatch Pipeline

When a client sends a request, SemanticaMCPServer.dispatch in semantica_mcp/mcp/server.py routes it through a strict validation chain. The server expects requests on stdin shaped like:

{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "add_entity", "arguments": {...}}}

The dispatch table _DISPATCH forwards tools/call to _handle_tools_call, which extracts the tool name and arguments before invoking call_tool(name, args). This function retrieves the appropriate handler from _TOOL_INDEX and executes it, returning a plain dictionary or error object wrapped in a JSON-RPC response with type: "text" content.

Tool Index Registration

At startup, the server builds _TOOL_INDEX from definitions aggregated in semantica_mcp/mcp/tools/__init__.py. This module combines GRAPH_TOOLS and DECISION_TOOLS into a single TOOL_DEFINITIONS list, mapping each tool name to its corresponding handler function. All schemas validating input payloads live in semantica_mcp/mcp/schemas.py, ensuring type safety before execution reaches the graph or decision logic.

Graph Tools for Knowledge Management

Graph tools provide full CRUD operations and analytics on the knowledge graph, operating against a singleton instance returned by semantica_mcp.mcp.session.get_graph().

Adding Entities and Relationships

The handle_add_entity and handle_add_relationship functions in semantica_mcp/mcp/tools/graph.py enable node and edge creation. Clients can populate the graph with typed entities and define semantic connections between them.

import json, subprocess, sys

def mcp_call(name, args):
    request = {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/call",
        "params": {"name": name, "arguments": args},
    }
    proc = subprocess.Popen(
        [sys.executable, "-m", "semantica_mcp.mcp.server"],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        text=True,
    )
    stdout, _ = proc.communicate(json.dumps(request) + "\n")
    return json.loads(stdout)

# Add a new entity

entity_resp = mcp_call(
    "add_entity",
    {"id": "customer_123", "label": "Acme Corp", "type": "Organization"},
)
print(entity_resp)

# Create a relationship

rel_resp = mcp_call(
    "add_relationship",
    {"source": "customer_123", "target": "product_X", "type": "PURCHASED"},
)
print(rel_resp)

Graph Analytics and Summarization

For intelligence gathering, handle_get_graph_summary and handle_get_graph_analytics in the same file compute network metrics including PageRank, betweenness centrality, and community detection. These functions allow clients to identify influential nodes and structural clusters without implementing graph algorithms locally.


# Retrieve high-level statistics

summary = mcp_call("get_graph_summary", {})
print(summary["result"])

# Compute advanced metrics

analytics = mcp_call(
    "get_graph_analytics",
    {"metrics": ["pagerank", "communities"], "top_n": 3},
)
print(json.dumps(analytics["result"], indent=2))

The handle_search_graph function supports structured querying of nodes and edges, returning filtered subgraphs based on property matches.

Decision Tools for Intelligence Tracking

The decision-intelligence layer in semantica_mcp/mcp/tools/decisions.py captures organizational knowledge about choices, their justifications, and downstream effects.

Recording and Querying Decisions

handle_record_decision persists decisions with full contextual metadata including category, scenario, reasoning, confidence scores, and linked entities. handle_query_decisions retrieves historical records with filtering capabilities.


# Record a strategic decision

record_resp = mcp_call(
    "record_decision",
    {
        "category": "pricing",
        "scenario": "Launch discount for Q4",
        "reasoning": "Competitive pressure, forecasted demand spike",
        "outcome": "approved",
        "confidence": 0.92,
        "entities": ["product_X", "customer_123"],
    },
)
decision_id = record_resp["result"]["decision_id"]

# Query recent pricing decisions

query_resp = mcp_call(
    "query_decisions",
    {"limit": 5, "category": "pricing"},
)
print(json.dumps(query_resp, indent=2))

Causal Chains and Impact Analysis

For forensic and planning workflows, three specialized handlers provide deep inspection capabilities:

  • handle_find_precedents: Locates historically similar decisions based on entity overlap and categorical similarity.
  • handle_get_causal_chain: Traces the sequence of decisions leading to a specific outcome, reconstructing the reasoning path.
  • handle_analyze_decision_impact: Evaluates downstream effects by analyzing relationships between the decision node and subsequent graph modifications.

These functions treat decisions as first-class graph citizens, enabling longitudinal analysis of how specific choices propagated through the knowledge base.

Persistence and Session Management

The server maintains graph state through a singleton pattern implemented in semantica_mcp/mcp/session.py. The get_graph() function returns a shared instance accessible across all tool invocations, while is_persistence_safe() validates that the graph was successfully loaded from disk at startup.

Persistence is controlled by the SEMANTICA_KG_PATH environment variable. When set and the graph passes safety checks, every mutation triggers an immediate save to the filesystem. If persistence fails, the server rolls back the in-memory state to maintain consistency between RAM and disk. Static documentation resources are served via resources/read endpoints defined in semantica_mcp/mcp/resources.py.

Summary

  • The Semantica MCP server exposes graph manipulation and decision tracking through a JSON-RPC 2.0 interface compatible with any MCP client.
  • Graph tools in semantica_mcp/mcp/tools/graph.py handle entity creation, relationship mapping, and network analytics including PageRank and community detection.
  • Decision tools in semantica_mcp/mcp/tools/decisions.py record decisions with full context and support precedent finding, causal tracing, and impact analysis.
  • The _TOOL_INDEX built from semantica_mcp/mcp/tools/__init__.py maps tool names to handlers, with input validation enforced by schemas.py.
  • Optional persistence via SEMANTICA_KG_PATH ensures knowledge survives server restarts, with automatic rollback on write failures.

Frequently Asked Questions

How do I start the Semantica MCP server for local development?

Run the module directly using Python’s subprocess or execute python -m semantica_mcp.mcp.server in your terminal. The server reads JSON-RPC requests from stdin and writes responses to stdout, making it compatible with Claude Desktop, Cursor, and other MCP hosts without additional networking configuration.

What is the difference between graph tools and decision tools?

Graph tools manage the knowledge graph structure—creating entities, defining relationships between them, and computing network analytics like centrality metrics. Decision tools capture metadata about organizational choices, including the reasoning behind decisions, their confidence scores, and their causal relationships to other decisions and entities.

Can I disable graph persistence when testing the MCP server?

Yes. If the SEMANTICA_KG_PATH environment variable is unset or the graph fails to load at startup (is_persistence_safe() returns False), the server operates in memory-only mode. Mutations will not survive server restarts, but the tool API remains fully functional for testing and ephemeral workflows.

How does the server handle errors during tool execution?

The call_tool function in semantica_mcp/mcp/server.py catches exceptions and returns structured error dictionaries to the dispatcher. For persistence failures specifically, the server triggers a rollback to ensure the in-memory get_graph() instance remains consistent with the on-disk state, preventing data desynchronization.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →