How to Integrate Semantica as an MCP Server for AI Agents
Semantica provides a built-in MCP server that exposes knowledge-graph operations through JSON-RPC 2.0 over stdio, allowing any AI agent to discover and invoke graph tools as remote functions.
The semantica-agi/semantica repository ships with a complete Model Context Protocol (MCP) implementation. This lets Claude Code, Cursor, VS Code Copilot, and other MCP-compatible agents treat Semantica's knowledge-graph engine as a first-class tool provider without HTTP APIs or complex configuration.
What Is the Semantica MCP Server?
Semantica's MCP server follows the Model Context Protocol specification, using JSON-RPC 2.0 messages over stdio. The server runs as a long-lived subprocess: your AI agent writes requests to its stdin and reads responses from stdout.
Key architectural components:
- Event loop (
mcp/server.py): Parses incoming JSON-RPC lines, dispatches to handlers, and serializes responses - Dispatch table (
_DISPATCH): Maps MCP methods (initialize,tools/list,tools/call) to handler functions - Tool registry (
TOOL_DEFINITIONSinmcp/tools/__init__.py): Aggregates discoverable tools with JSON schemas - Graph tools (
mcp/tools/graph.py): Implementsadd_entity,add_relationship,search_graph,get_graph_summary,get_graph_analytics - Session store (
mcp/session.py): Providesget_graph()singleton for in-memory or persistent graph instances
Each request flows through: parse → dispatch → execute → wrap → write. All responses include the standard jsonrpc: "2.0" envelope with either a result or error field.
Starting the MCP Server
Launch Semantica's MCP server using Python's module execution:
# Standard start
python -m mcp
# With debug logging for troubleshooting
python -m mcp.server --debug
The server immediately enters a read loop on stdin, blocking until it receives valid JSON-RPC requests. Because it uses stdio, it runs anywhere you can spawn a subprocess with piped streams—Docker containers, VS Code extensions, Jupyter kernels, or CI pipelines.
Discovering Available Tools
After initialization, an MCP client should call tools/list to discover capabilities. This returns all graph operations with their descriptions and input schemas.
Example request:
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list"
}
The server responds with tool definitions from mcp/tools/__init__.py, including:
add_entity: Create nodes with id, label, and typeadd_relationship: Connect entities with typed edgessearch_graph: Full-text or structured queriesget_graph_summary: High-level statisticsget_graph_analytics: Computed metrics and traversal results
Each tool includes a JSON Schema describing required and optional parameters, defined in mcp/schemas.py.
Invoking Graph Operations
Use tools/call with the target tool name and arguments. The server validates inputs against schemas, executes the handler from mcp/tools/graph.py, and returns structured content.
Example: adding an entity to the knowledge graph:
{
"jsonrpc": "2.0",
"id": 42,
"method": "tools/call",
"params": {
"name": "add_entity",
"arguments": {
"id": "alice",
"label": "Alice",
"type": "Person"
}
}
}
Server response:
{
"jsonrpc": "2.0",
"id": 42,
"result": {
"content": [
{
"type": "text",
"text": "{\"id\":\"alice\",\"label\":\"Alice\",\"type\":\"Person\",\"created\":true}"
}
],
"isError": false
}
}
Note that results are JSON-encoded strings inside the text field, following MCP's content array format.
Minimal Python Client Example
This complete example demonstrates stdio-based communication with the Semantica MCP server:
import json
import subprocess
import sys
# Start the MCP server subprocess
proc = subprocess.Popen(
[sys.executable, "-m", "mcp.server"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True,
)
def rpc_call(method, params=None, req_id=1):
"""Send JSON-RPC request and return parsed response."""
request = {
"jsonrpc": "2.0",
"id": req_id,
"method": method,
"params": params or {}
}
proc.stdin.write(json.dumps(request) + "\n")
proc.stdin.flush()
return json.loads(proc.stdout.readline())
# Discover available tools
print(rpc_call("tools/list"))
# Add a person entity
print(rpc_call("tools/call", {
"name": "add_entity",
"arguments": {"id": "bob", "label": "Bob", "type": "Person"}
}))
# Create a relationship
print(rpc_call("tools/call", {
"name": "add_relationship",
"arguments": {
"source": "alice",
"target": "bob",
"type": "KNOWS"
}
}))
# Search the graph
print(rpc_call("tools/call", {
"name": "search_graph",
"arguments": {"query": "Person", "limit": 10}
}))
The rpc_call helper implements the complete request-response cycle required by the MCP protocol.
Integrating with VS Code Extensions
For TypeScript-based agent environments, spawn the server and communicate over stdio:
import * as cp from 'child_process';
const proc = cp.spawn('python', ['-m', 'mcp.server']);
// Send a tool invocation
const request = {
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: {
name: 'get_graph_summary',
arguments: {}
}
};
proc.stdin.write(JSON.stringify(request) + '\n');
proc.stdout.on('data', (data) => {
const response = JSON.parse(data.toString());
if (response.result && !response.result.isError) {
const summary = JSON.parse(response.result.content[0].text);
// Use summary.vertex_count, summary.edge_count, etc.
}
});
This pattern works identically in Cursor extensions, Claude Code plugins, or custom agent frameworks.
Configuring Persistent Storage
By default, mcp/session.py maintains the graph in memory for the process lifetime. To persist across restarts, implement a custom storage adapter:
- Subclass or replace the session's graph provider in
mcp/session.py - Add SQLite, Neo4j, or file-based persistence
- Set the custom backend before launching the server
The tool handlers in mcp/tools/graph.py call get_graph() without knowing the underlying storage, so swapping implementations is transparent to MCP clients.
Key Source Files for MCP Integration
| File | Purpose |
|---|---|
mcp/server.py |
Core event loop, dispatch table, request handling |
mcp/tools/__init__.py |
Tool registration and TOOL_DEFINITIONS aggregation |
mcp/tools/graph.py |
Implementation of all graph manipulation tools |
mcp/session.py |
Graph instance lifecycle and storage abstraction |
mcp/schemas.py |
JSON Schema definitions for tool parameters |
mcp/__main__.py |
Entry point for python -m mcp |
Summary
Integrating Semantica as an MCP server enables any JSON-RPC-capable AI agent to manipulate knowledge graphs through standardized tool calls:
- Launch via
python -m mcpfor stdio-based operation - Discover tools with
tools/list, invoke withtools/call - Core graph operations live in
mcp/tools/graph.py - Session management in
mcp/session.pycontrols persistence - Works in Docker, VS Code, Jupyter, or any subprocess-friendly environment
Frequently Asked Questions
What AI agents support Semantica's MCP server?
Any agent implementing the Model Context Protocol can connect. This includes Claude Code, Cursor, VS Code Copilot Chat, and custom agents built with MCP SDKs. The stdio transport is the most widely supported.
How do I debug communication issues with the MCP server?
Start the server with --debug to enable verbose logging of all JSON-RPC messages. Verify your client sends newline-terminated JSON and properly flushes stdin. Check that responses are parsed as single lines—mcp/server.py uses line-buffered output.
Can I extend Semantica with custom MCP tools?
Yes. Add new tool definitions to mcp/tools/__init__.py and implement handlers in mcp/tools/ submodules. Register them in TOOL_DEFINITIONS with proper JSON schemas from mcp/schemas.py. The server automatically exposes new tools via tools/list.
Is the graph data persisted between MCP server restarts?
Not by default—the graph lives in memory via mcp/session.py. To persist data, modify session.py to use a database backend (SQLite, Neo4j, etc.) before launching the server. The tool implementations remain unchanged.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →