ContextSynapse MCP Server
Provides tool wrappers that let CrewAI agents query and update the shared context graph.
Supports Google Gemini as an LLM target for context delivery and shared agent memory.
Provides a LangChain retriever, tools, and chat message history backed by the ContextSynapse graph.
Provides a LangGraph checkpoint saver, context tools, and message history for graph-based agent workflows.
Provides function definitions and adapters for OpenAI models, enabling function calling and context retrieval from the shared graph.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@ContextSynapse MCP ServerRecall everything about Project Atlas"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
ContextSynapse
The shared brain your agents are missing. Open-source context engine for AI agents — ingest knowledge, build connections, and deliver the right context to any LLM.
What is ContextSynapse?
ContextSynapse is the shared brain for your AI agents. It stores knowledge as connected graphs, lets agents remember and recall across sessions, and delivers the right context to any LLM — Claude, GPT, Llama, Gemini, or any other model.
Not a database. Not an agent framework. The context layer between them.
Your Agents (any LLM) ContextSynapse Your Data
+------------------+ +--------------------+ +----------------+
| Claude agent |----->| |<-----| Documents |
| GPT agent |----->| Shared Brain |<-----| APIs |
| Llama agent |----->| |<-----| Databases |
| Custom agent |----->| Remember, Recall |<-----| Files |
+------------------+ | Search, Reason | +----------------+
+--------------------+Core capabilities:
Shared agent memory — Agents remember, recall, and share knowledge across sessions
Graph RAG — Retrieve context via keyword, BM25, and vector fusion — relationships that vector-only RAG misses
AIQL query language — SQL-like syntax with graph patterns, traversals, and hybrid search
Context assembly — Polyglot data pull + access control + fusion output in one call
MCP server — Expose your brain as tools for Claude, Copilot, and other AI agents
Security — Field-level PII encryption, RBAC framework, audit middleware, JWT refresh, CSRF, rate limiting
Workflow engine — Approval workflows with auto-checks, delegation, expiry
App factory — Build domain-specific apps (verticals) on top of the platform
Skills framework — Markdown-defined agent capabilities with LangGraph execution
Any LLM, any framework — Works with LangChain, CrewAI, AutoGen, OpenAI, Anthropic, and 8+ more
Related MCP server: Memxus
Build Your Own Vertical
ContextSynapse is a platform — like Salesforce or Oracle. You build verticals (applications) on top of it.
# my_app.py — your vertical application
from contextsynapse.app_factory import create_app
from contextsynapse.security.rbac_framework import get_role_registry
from contextsynapse.security.field_encryption import get_field_encryptor
from contextsynapse.workflow.registry import get_workflow_registry
# 1. Register your roles
reg = get_role_registry()
reg.register_vertical("healthcare", {
"doctor": {
"permissions": ["view_patient", "write_notes", "order_tests"],
"label": "Doctor",
"global_access": False,
},
"nurse": {
"permissions": ["view_patient", "write_vitals"],
"label": "Nurse",
"global_access": False,
},
"admin": {
"permissions": ["view_patient", "manage_users", "view_audit"],
"label": "Clinic Admin",
"global_access": True,
},
})
# 2. Register PII fields
enc = get_field_encryptor()
enc.register("patients", {
"ssn": {"mask": "last4", "decrypt_roles": ["admin"]},
"phone": {"mask": "phone", "decrypt_roles": ["admin", "doctor"]},
})
# 3. Register workflows
get_workflow_registry().register("lab_order", {
"label": "Lab Order",
"approvers": ["doctor"],
"auto_approve_below": 0,
"timeout_hours": 24,
"vertical": "healthcare",
})
# 4. Create your app
from fastapi import APIRouter
my_router = APIRouter()
@my_router.get("/patients")
def list_patients():
return {"patients": []}
app = create_app(
title="HealthCare App",
verticals={
"healthcare": {
"register": lambda: None, # registration done above
"routers": [my_router],
},
},
)
# Run: uvicorn my_app:appWhat the platform gives you for free:
Authentication (JWT + refresh tokens)
RBAC (your roles, your permissions)
PII encryption (your fields, your masking rules)
Audit log (every API call logged)
Workflow approvals (your workflow types)
Context assembly (polyglot data pull with access control)
Graph database (CSR + Redis + PostgreSQL)
LLM client (10+ providers auto-detected)
MCP server (expose tools to AI agents)
Skills framework (markdown-defined agent capabilities)
Quick Start
Install
pip install contextsynapse30-Second Demo
from contextsynapse import ContextSynapse
from contextsynapse.aiql import AIQLExecutor
# Create a graph and executor
db = ContextSynapse()
ex = AIQLExecutor(contextcore=db)
# Build a knowledge graph
ex.execute("CREATE GRAPH company")
ex.execute("USE GRAPH company")
ex.execute('CREATE NODE Person {name: "Alice", role: "Engineer", age: 30}')
ex.execute('CREATE NODE Person {name: "Bob", role: "Manager", age: 42}')
ex.execute('CREATE NODE Project {name: "Atlas", status: "active"}')
ex.execute('CREATE EDGE WORKS_ON FROM Person WHERE name = "Alice" TO Project WHERE name = "Atlas"')
ex.execute('CREATE EDGE MANAGES FROM Person WHERE name = "Bob" TO Project WHERE name = "Atlas"')
# Query it
result = ex.execute("SELECT * FROM Person")
for node in result.get("nodes", []):
print(node.properties.get("name"), "—", node.properties.get("role"))
# Build LLM-ready context
from contextsynapse.context.hub import ContextHub
hub = ContextHub(system_prompt="You are a project analyst.")
hub.add_nodes(db.get_all_nodes())
messages = hub.to_messages() # Ready for OpenAI/Anthropic APIRun the full demo:
python examples/demo.pyRunning the Full Stack
ContextSynapse has a Python backend (API server) and a React frontend (dashboard). Three ways to run it:
Option 1: Docker Compose (recommended)
# Clone the repo
git clone https://github.com/contextsynapse/contextsynapse.git
cd contextsynapse
# Copy env file and set your keys
cp .env.example .env
# Edit .env — at minimum set CONTEXTSYNAPSE_ADMIN_KEY and CONTEXTSYNAPSE_JWT_SECRET
# Start everything (API + Redis + PostgreSQL)
docker compose up -d
# With the frontend dashboard
docker compose --profile ui up -d
# API: http://localhost:8000
# Dashboard: http://localhost:3000
# Redis: localhost:6379
# Postgres: localhost:5432Option 2: Manual Setup
Backend:
# Create a virtual environment
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
# Install with all extras
pip install -e ".[all]"
# Copy and configure environment
cp .env.example .env
# Edit .env — set at minimum:
# CONTEXTSYNAPSE_ADMIN_KEY=your-secure-key
# CONTEXTSYNAPSE_JWT_SECRET=your-jwt-secret
# Start the API server
uvicorn contextsynapse.api.api:app --host 0.0.0.0 --port 8000 --reloadFrontend:
cd frontend
npm install
npm start
# Opens at http://localhost:3000Optional services (Redis, PostgreSQL):
# Redis — needed for multi-agent coordination, caching, agent registry
docker run -d --name redis -p 6379:6379 redis:7-alpine
# PostgreSQL — needed for user auth, tenant management, audit logs
docker run -d --name postgres -p 5432:5432 \
-e POSTGRES_DB=contextsynapse \
-e POSTGRES_USER=contextsynapse \
-e POSTGRES_PASSWORD=contextsynapse \
postgres:16-alpineOption 3: Minimal (Python library only)
No server needed — use ContextSynapse as an in-process graph database:
pip install contextsynapsefrom contextsynapse import ContextSynapse
db = ContextSynapse()
# Use directly — no API server requiredIntegration
ContextSynapse connects to your agents via 5 integration paths — use whichever fits your stack:
+-----------+ +-------+ +-----+ +--------+ +---------+
| MCP Server| | REST | | A2A | | Python | |Framework|
| (Claude, | | API | |Proto| | SDK | |Adapters |
| Copilot) | | | | | | | | |
+-----------+ +-------+ +-----+ +--------+ +---------+
| | | | |
+--------+-------+-----+------+------+------+------+-------+
| | | |
+-------- ContextSynapse (shared brain) ---+1. MCP Server (Claude / Copilot / any MCP client)
Exposes 29 tools via Model Context Protocol. Two agents using this server share the same graph.
# Stdio transport (default — for Claude Desktop, Claude Code)
python -m contextsynapse.mcp
# SSE transport (for web clients, remote agents)
python -m contextsynapse.mcp --transport sse --port 8100
# With namespace and auth
python -m contextsynapse.mcp --namespace myproject --api-key agent1:secretClaude Desktop config (claude_desktop_config.json):
{
"mcpServers": {
"contextsynapse": {
"command": "python",
"args": ["-m", "contextsynapse.mcp"]
}
}
}Claude Code:
claude mcp add contextsynapse -- python -m contextsynapse.mcpMCP Auth: Multi-session auth middleware — each agent gets scoped access to their session's graph. Set CONTEXTSYNAPSE_API_KEY for authenticated connections.
2. REST API
Full-featured FastAPI server with 30+ route modules:
uvicorn contextsynapse.api.api:app --host 0.0.0.0 --port 8000Key endpoints:
Endpoint | Description |
| Register an agent, get API key |
| Create a shared session |
| Ingest content into session |
| Search across contexts |
| Execute AIQL query |
| Get agent briefing |
| Run agent experiment |
| Dashboard data endpoints |
Auth: JWT tokens via POST /auth/login + x-admin-key header for admin ops.
3. A2A Protocol (Agent-to-Agent)
Implements Google's A2A protocol for agent interoperability:
from contextsynapse.a2a import Task, TaskState, TextPart, Message
# Create a task for another agent
task = Task(id="task-1", state=TaskState.SUBMITTED)
task.messages.append(Message(
role="user",
parts=[TextPart(text="Analyze TSLA earnings")]
))Features: task state machine, agent card discovery, SSE streaming, artifact exchange.
4. Python SDK
pip install contextsynapse-sdkfrom contextsynapse_sdk import ContextSynapseClient
# Connect to server
client = ContextSynapseClient("http://localhost:8000", api_key="your-key")
# Register an agent
agent = client.agents.register("my-bot", role="researcher")
# Create a session and work with it
session = client.sessions.create("research-project")
session.ingest({"content": "Tesla Q3 revenue was $25.2B", "type": "Fact"})
results = session.search("Tesla revenue")5. Framework Adapters
Drop-in integration with 8 AI frameworks:
Framework | Import | What you get |
LangChain |
| Retriever, tools, chat message history |
LangGraph |
| Checkpoint saver, context tools, message history |
CrewAI |
| Tool wrappers for CrewAI agents |
AutoGen |
| Tool wrappers for AutoGen agents |
OpenAI |
| Function definitions for function calling |
LlamaIndex |
| Tool specs for LlamaIndex agents |
PydanticAI |
| Tool wrappers for PydanticAI |
Swarm |
| Tool functions for OpenAI Swarm |
# Example: LangChain retriever
from contextsynapse.adapters.langchain import AIContextDBRetriever
retriever = AIContextDBRetriever(db=my_graph, k=10)
docs = retriever.get_relevant_documents("What is TSLA outlook?")LLM Providers
ContextSynapse supports 12+ LLM providers. No LLM is required for core graph operations — LLMs are only needed for entity extraction, RAG queries, natural language search, and the agent playground.
Provider | Env Variable | Default Model | Notes |
Groq |
|
| Fastest, free tier available |
OpenAI |
|
| Most reliable |
Anthropic |
|
| Best reasoning |
Ollama |
|
| Local, no API key needed |
DeepSeek |
|
| Cost-effective |
Together |
|
| Open-source models |
Mistral |
|
| EU-hosted |
Cerebras |
|
| Fast inference |
Fireworks |
|
| Serverless |
Perplexity |
|
| Search-augmented |
Google Gemini |
|
| Multimodal |
Cohere |
|
| RAG-optimized |
Auto-detection: set any API key and ContextSynapse picks it up. Or specify explicitly:
from contextsynapse.llm import get_llm_client
llm = get_llm_client(provider="groq")Security
Enterprise-grade security — all configurable, all platform-level.
Layer | Module | What it does |
RBAC Framework |
| Verticals register their own roles + permissions. Multi-role support. |
Field Encryption |
| Fernet AES encryption per field. Role-based decryption + masking. |
Audit Middleware |
| Every POST/PUT/DELETE logged to PostgreSQL with user, IP, timing. |
JWT Refresh |
| 15-min access token + 7-day refresh token. |
CSRF Protection |
| Double-submit cookie pattern (enable via env). |
Per-User Rate Limit |
| Rate limit by JWT user_id, fallback to IP. |
Error Monitoring |
| Sentry integration (optional) + file logging. |
PII Detection |
| Auto-detect and redact PII (emails, phones, SSNs) in text. |
Context ACL |
| Path-based access control on assembled contexts. |
Row-Level Security |
| Tenant-isolated queries. |
# Field-level PII encryption (vertical configures, platform encrypts)
from contextsynapse.security.field_encryption import get_field_encryptor
enc = get_field_encryptor()
enc.register("patients", {
"ssn": {"mask": "last4", "decrypt_roles": ["admin"]},
"phone": {"mask": "phone", "decrypt_roles": ["admin", "doctor"]},
})
record = {"name": "Alice", "ssn": "123-45-6789", "phone": "+1-555-0123"}
admin_view = enc.process_record(record, "patients", user_roles=["admin"])
# → {"name": "Alice", "ssn": "123-45-6789", "phone": "+1-555-0123"}
nurse_view = enc.process_record(record, "patients", user_roles=["nurse"])
# → {"name": "Alice", "ssn": "XXXXX6789", "phone": "XXXXXXX0123"}
# Generic RBAC (verticals register their own roles)
from contextsynapse.security.rbac_framework import get_role_registry
reg = get_role_registry()
reg.register_vertical("myapp", {
"editor": {"permissions": ["read", "write"], "global_access": False},
"viewer": {"permissions": ["read"], "global_access": False},
})
perms = reg.effective_permissions(["editor", "viewer"]) # → {"read", "write"}Workflow Engine
Generic approval workflow — verticals register their own workflow types.
from contextsynapse.workflow.registry import get_workflow_registry
from contextsynapse.workflow.engine import WorkflowEngine
# Register workflow types
get_workflow_registry().register("approval", {
"label": "Document Approval",
"approvers": ["manager"],
"auto_approve_below": 0,
"timeout_hours": 48,
"vertical": "myapp",
})
# Initiate a workflow
engine = WorkflowEngine()
task = engine.initiate("approval", initiated_by="user_123", payload={"doc": "report.pdf"})
# → status: "pending_approval"
# Approve
engine.approve(task["id"], approved_by="manager_456")
# → status: "approved"Context Assembly
Assemble composite contexts from polyglot stores with role-based access control.
from contextsynapse.context.assembly import ContextAssemblyEngine
engine = ContextAssemblyEngine(graph_registry)
# Doctor sees full patient context
result = engine.assemble(
purpose="patient_review",
requester={"user_id": "dr_123", "roles": ["doctor"], "scoped_ids": ["patient_abc"]},
params={"patient_id": "patient_abc"},
)
# → contexts: {patient_record, lab_results, vitals, medications}
# → redacted: []
# Receptionist sees only non-sensitive data
result = engine.assemble(
purpose="patient_review",
requester={"user_id": "rec_456", "roles": ["receptionist"]},
params={"patient_id": "patient_abc"},
)
# → contexts: {patient_record} (name + appointment only)
# → redacted: ["lab_results", "vitals", "medications"]Architecture
contextsynapse/
├── core/ # Graph storage engine (CSR, Redis, LMDB)
├── aiql/ # AIQL query language (grammar, parser, compiler, executor)
├── api/ # FastAPI REST API
├── mcp/ # MCP server for Claude/Copilot
├── context/ # ContextHub — LLM context building + assembled contexts
├── storage/ # Storage backends + WAL + namespace store
├── vector/ # Vector DB integration (NumPy, FAISS, Qdrant, Chroma)
├── ingestion/ # Universal ingestion pipeline (URL, file, API)
├── search/ # Graph-enhanced search + RAG + full-text
├── extraction/ # Entity/fact extraction from documents
├── security/ # RBAC, RLS, encryption, PII detection, audit
├── shield/ # AgentShield — behavioral auth + trust engine
├── governance/ # Data governance layer
├── a2a/ # Agent-to-agent protocol
├── adapters/ # Framework adapters (LangChain, CrewAI, etc.)
├── llm/ # Multi-provider LLM client (12+ providers)
├── rules/ # Rule engine with temporal + aggregate evaluators
├── workspace/ # Git/GitHub workspace connectors
└── plugins/ # Plugin system for vertical applications
frontend/ # React dashboard (graph explorer, playground, sessions)
plugins/ # Domain plugins (installed separately)
verticals/ # Vertical applications (private, not included in package)
sdk/ # Python SDK for REST API accessStorage Backends
Backend | Best For | Scale |
CSR (in-memory) | Development, small graphs | ~1M nodes |
Redis | Multi-worker, shared state | ~10M nodes |
LMDB | Single-node persistence | ~50M nodes |
PostgreSQL | Production, horizontal scale | Unlimited |
# Redis backend
CONTEXTSYNAPSE_GRAPH_BACKEND=redis
CONTEXTSYNAPSE_REDIS_URL=redis://localhost:6379
# LMDB backend
CONTEXTSYNAPSE_STORAGE_BACKEND=lmdbCloud Storage
For Kubernetes and ephemeral deployments, graphs persist to cloud storage:
Provider | Backend | Auth | Install |
AWS S3 |
| IAM / env credentials |
|
Google Cloud Storage |
| Service account JSON |
|
Azure Blob |
| Connection string or DefaultAzureCredential |
|
MinIO / R2 |
| S3-compatible endpoint |
|
# AWS S3
CONTEXTSYNAPSE_STORAGE_BACKEND=s3
CONTEXTSYNAPSE_S3_BUCKET=my-context-graphs
CONTEXTSYNAPSE_S3_REGION=us-east-1
# Google Cloud Storage
CONTEXTSYNAPSE_STORAGE_BACKEND=gcs
CONTEXTSYNAPSE_GCS_BUCKET=my-context-graphs
# Azure Blob Storage
CONTEXTSYNAPSE_STORAGE_BACKEND=azure
CONTEXTSYNAPSE_AZURE_CONTAINER=context-graphs
CONTEXTSYNAPSE_AZURE_CONNECTION_STRING=DefaultEndpointsProtocol=https;AccountName=...Configuration
All configuration is via environment variables (prefix CONTEXTSYNAPSE_). Copy .env.example to .env and set what you need — everything has sensible defaults.
Note: The older
AICONTEXTDB_*prefix is still supported for backward compatibility.
Core Settings
Variable | Default | Description |
| required | Admin API key for server mode |
| required | JWT signing secret for auth |
|
|
|
|
| Allowed CORS origins |
|
| API rate limit (requests/minute) |
Graph Backend
Variable | Default | Options | When to use |
|
|
|
|
| — |
| Set to enable Redis backend |
|
|
|
|
| SQLite |
| Set for PostgreSQL (users, auth, tenants) |
LLM Providers
Not required for core graph operations. Only needed for entity extraction, RAG answers, NL queries, and the agent playground. Set any one key — auto-detected:
Provider | Env Variable | Default Model | Speed | Cost |
Groq |
|
| Fastest | Free tier |
OpenAI |
|
| Fast | Pay-per-use |
Anthropic |
|
| Fast | Pay-per-use |
Ollama |
|
| Local | Free (self-hosted) |
DeepSeek |
|
| Fast | Cheapest |
Together |
|
| Fast | Pay-per-use |
Mistral |
|
| Fast | EU-hosted |
Cerebras |
|
| Fastest | Free beta |
Fireworks |
|
| Fast | Serverless |
Perplexity |
|
| Fast | Search-augmented |
|
| Fast | Free tier | |
Cohere |
|
| Fast | RAG-optimized |
Embedding Models
Default: Ollama nomic-embed-text (768 dims, local, free). Falls back to NumPy cosine if no embedding model available.
Provider | Model | Dimensions | Notes |
Ollama |
| 768 | Default, local, free |
Ollama |
| 1024 | Higher quality |
Ollama |
| 384 | Smallest, fastest |
OpenAI |
| 1536 | Best quality/cost |
OpenAI |
| 3072 | Highest quality |
Cohere |
| 4096 | RAG-optimized |
Gemini |
| 768 | Multimodal |
Mistral |
| 1024 | EU-hosted |
Together |
| 768 | Open-source |
Local |
| 384 | sentence-transformers, no API |
Configure in config/config.yaml:
embeddings:
provider: "local" # "local" (sentence-transformers) or "ollama"
model: "all-MiniLM-L6-v2"
dimension: 384Vector Database
Backend | Env Variable | Notes |
NumPy (default) | — | Built-in, no setup, good for <100K vectors |
Qdrant |
| Production, scalable |
FAISS |
| Fast, in-process |
ChromaDB |
| Embedded, easy setup |
CONTEXTSYNAPSE_VECTOR_DB_BACKEND=qdrant # or: custom, faiss, chromaAdvanced Settings
Variable | Default | Description |
|
| Max graphs in memory (LRU eviction) |
|
| Max concurrent LLM calls |
|
| LLM rate limit per minute |
|
| Memory confidence decay half-life |
|
| Auto-prune interval (seconds) |
|
| Max concurrent MCP sessions |
| — | S3 bucket for cloud graph storage |
| — | Google Cloud Storage bucket |
| — | Azure Blob Storage container |
Zero-Config Quick Start
ContextSynapse works out of the box with zero configuration:
Graph: in-memory CSR (no Redis needed)
Search: keyword + BM25 index (no vector DB needed)
Embedding: NumPy cosine fallback (no embedding model needed)
Database: SQLite (no PostgreSQL needed)
Encryption: Base64 fallback (no cryptography package needed)
Just pip install contextsynapse and go.
Building Plugins
ContextSynapse follows an open-core model — the graph engine is open source, and domain-specific applications are built as plugins.
from contextsynapse.plugins import VerticalPlugin, Sensor, PluginSchema
class MySensor(Sensor):
name = "my_data_feed"
interval_seconds = 300
async def collect(self, db):
return [{"id": "item_1", "type": "MyType", "properties": {"value": 42}}]
class MyVertical(VerticalPlugin):
name = "my_domain"
version = "0.1.0"
def sensors(self):
return [MySensor()]
def schemas(self):
return [PluginSchema(name="my_schema", node_types={...})]Register via pyproject.toml:
[project.entry-points."contextsynapse.plugins"]
my_domain = "my_package.plugin:MyVertical"SDK
pip install contextsynapse-sdkfrom contextsynapse_sdk import ContextSynapseClient
client = ContextSynapseClient("http://localhost:8000", api_key="your-key")
client.add_node("person_1", "Person", {"name": "Alice"})
results = client.search("Alice")Examples
Example | Description |
Start here — startup knowledge graph with PII detection + LLM context | |
Graph RAG — document ingestion, keyword search, topic clustering, hybrid retrieval | |
Shared Memory — multi-agent remember/recall, cross-agent sharing, versioning | |
Memory Layer — 4-tier memory (working/hot/persistent/cold), cross-agent sharing, versioning | |
Secure Vault — PII gate, field encryption, AgentShield trust, RBAC, audit trail | |
Context Quality — node scoring, freshness detection, quality filtering, usage tracking | |
Traceability — blockchain hash chains, Merkle roots, proof tokens, tamper detection | |
Agent Security — trust scoring, adaptive permissions, anomaly detection | |
Simple walkthrough — graph, AIQL, context building | |
Minimal 30-line getting started | |
RAG pipeline with graph-enhanced retrieval | |
Multi-agent coordination and task queues | |
Session-based graph management | |
Team collaboration with shared context | |
Ingest documents from a folder | |
AIQL pipeline queries |
Performance
Graph Operations (CSR in-memory backend)
Operation | 1K nodes | 10K nodes | 50K nodes |
Node insert | ~25K ops/s | ~20K ops/s | ~15K ops/s |
Edge insert | ~20K ops/s | ~15K ops/s | ~10K ops/s |
Node lookup | ~500K ops/s | ~500K ops/s | ~500K ops/s |
Neighbor traverse | ~200K ops/s | ~180K ops/s | ~150K ops/s |
Memory per node | ~500 bytes | ~600 bytes | ~700 bytes |
Performance Optimizations
Component | Optimization | Impact |
CSR Graph | Compressed Sparse Row format, O(1) neighbor access | 10-100x vs NetworkX |
Lazy CSR Rebuild | O(1) edge adds, deferred matrix construction | Fast writes, amortized reads |
Property Index | Hash-based index on node properties | O(1) property lookups |
HNSW Vector Index | Hierarchical Navigable Small World graph | 100x vs linear scan, sub-ms queries |
LMDB Search Index | Persistent keyword + BM25 index | Microsecond reads, no rebuild cycle |
Query Cache | LRU/LFU/TTL eviction, 5000 entries, 500MB cap | Avoid re-computing AIQL queries |
RAG Cache | 2-tier (Redis + in-process LRU) | Skip redundant LLM calls |
Embedding Cache | LMDB-backed vector cache | 3-5s saved per cache hit |
Write-Ahead Log | ACID compliance with checkpoints | Crash recovery, 1000-op checkpoints |
Buffer Manager | Configurable batching (70% threshold flush) | Smooth write latency |
Connection Pool | LRU cache, 50 sessions, 30min timeout | Reuse graph connections |
Search & Retrieval Latency
Operation | Latency | Backend |
Keyword search | ~1ms | Inverted index (cached) |
BM25 full-text search | ~50ms | LMDB / Whoosh |
Agent memory recall | ~10ms | Graph traversal |
Working memory cache hit | ~5ms | Redis |
Hot memory get/set | ~0.1ms | Redis hash |
Vector search | 6-12s | Ollama embedding (local) |
Agent Memory System
ContextSynapse provides a 4-tier memory system for AI agents:
Tier | Purpose | Latency | Backend |
Working Memory | Per-agent context cache, reactive invalidation | ~5ms | Redis |
Hot Memory | Current task, active state (TTL-based) | ~0.1ms | Redis hash |
Agent Memory | Persistent facts, decisions, preferences with confidence decay | ~10ms | Graph |
Cold Memory | Time-anchored, recall-at-timestamp, auto-decay | ~50ms | DuckDB |
from contextsynapse.context.agent_memory import AgentMemory
from contextsynapse.core.registry import GraphRegistry
mem = AgentMemory(GraphRegistry(), namespace="shared_brain")
# Agent stores a fact
mem.remember("agent-1", "Revenue grew 8% YoY", tags=["fact", "revenue"], confidence=0.95)
# Another agent recalls it
memories = mem.recall("agent-2", query="revenue", limit=5)
# Build LLM context from agent's memories
hub = mem.build_context("agent-1", system_prompt="You are an analyst.")
messages = hub.to_messages() # Ready for any LLM APIGraph RAG
ContextSynapse's RAG pipeline combines vector similarity, BM25 full-text, and keyword matching via Reciprocal Rank Fusion:
from contextsynapse.search.rag import hybrid_retrieve, plain_search, topic_scan
# Fast keyword search (no LLM needed, ~1ms)
results = plain_search(db, "connection pool incident", k=10)
# Topic clustering (no LLM needed)
topics = topic_scan(db, graph_name="knowledge_base", max_topics=10)
# Hybrid retrieval (vector + BM25 + keyword fusion)
top_results, sources = hybrid_retrieve(db, "What caused the outage?", k=5)Why Graph RAG > Vector RAG: Regular RAG retrieves similar chunks. Graph RAG retrieves chunks and follows relationships — connecting incidents to root causes to runbooks. Relationships that pure vector similarity would miss.
Context Quality Scoring
ContextSynapse doesn't just store context — it measures whether context is any good.
Layer | What it does | Speed |
Ingest Gate | Scores every node 0-100 (connectivity, specificity, source, completeness) | 300K scores/s |
Freshness Detection | Extracts event dates, classifies as fresh/recent/aging/stale/historical | <1ms |
Quality Filter | Blocks low-quality nodes before delivery to agents | instant |
Usage Tracking | Measures if delivered context was actually used (relevance, waste ratio) | per-agent |
Promotion Scoring | Auto-promotes high-value agent memories to main graph | on-demand |
from contextsynapse.context.quality import score_node
from contextsynapse.intelligence.freshness import detect_event_date, score_freshness
# Score a node at ingest
score = score_node({"label": "Fact", "properties": {"statement": "Revenue grew 8%", "source_url": "..."}, "edge_count": 4})
# → 85 (high quality: sourced, connected, specific)
# Detect content freshness
result = detect_event_date("Tesla reported Q3 2026 results on August 15")
freshness = score_freshness(result.event_date)
# → freshness="recent", staleness_days=29Documentation
Document | Description |
Complete AIQL query language reference | |
System architecture and design decisions | |
Storage backend details and configuration | |
Production deployment guide | |
Development setup and contribution guidelines | |
Version history |
Contributing
See CONTRIBUTING.md for development setup and guidelines.
License
Apache 2.0 — see LICENSE.
This server cannot be deployed
Maintenance
Related MCP Connectors
shared AI-context layer for teams — persistent memory your agents search and update over MCP
Cross-tool persistent memory and context for AI assistants over MCP.
Your memory, everywhere AI goes. Build knowledge once, access it via MCP anywhere.
Personal knowledge graph as an AI memory layer over MCP - read, save, and link your memories.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceObsidian-backed knowledge graph with semantic search, entity extraction, and cross-session memory. 11 MCP tools. Works with Claude Code, Cursor, Windsurf, and any MCP-compatible editor.59 npm1MIT
- AlicenseAqualityAmaintenanceOne context engine for every AI. Persistent context from GitHub, Notion, and your decisions, delivered to Claude, ChatGPT, Cursor, VS Code, Gemini, and any MCP-compatible client.93AGPL 3.0
- AlicenseAqualityBmaintenanceProvides persistent, graph-based memory for AI agents via MCP, enabling semantic search, wikilink traversal, reminders, and injection protection.933Apache 2.0
- AlicenseAqualityAmaintenanceEnables personal AI memory management through MCP tools for adding, searching, exporting, and deleting memories, with knowledge-graph retrieval and multi-hop association for clients like Claude Desktop and Cursor.6Apache 2.0