Documentation
Complete reference for Synapse Layer — the reference implementation of a universal memory layer for AI agents in the MCP ecosystem. Privacy-first, MCP-native, secure-by-design.
Getting Started
First Memory in 3 Minutes →
Two curl commands. Zero dependencies. No SDK required.
Installation
Install the SDK from PyPI. Requires Python 3.10 or newer.
pip install synapse-layerFor MCP server support, also install the MCP SDK:
pip install synapse-layer "mcp[cli]"Quick Start
Initialize a memory instance and store your first memory. Every operation goes through the full 3-layer security pipeline automatically.
from synapse_memory.core import SynapseMemory
# Initialize with default security (all 3 layers active)
memory = SynapseMemory(
agent_id="my-agent",
sanitize_enabled=True, # Layer 1: PII sanitization
privacy_enabled=True, # Layer 2: Differential privacy
privacy_epsilon=0.5, # Lower = stronger privacy
)
# Store a memory (PII is auto-stripped, DP noise injected)
result = memory.store(
content="User prefers dark mode and lives in Berlin",
confidence=0.9,
)
print(result.memory_id) # SHA-256 hash
print(result.trust_quotient) # Confidence x validation score
print(result.sanitized) # True
print(result.privacy_applied) # True
# Recall memories (self-healing resolves conflicts)
memories = memory.recall("user preferences", top_k=5)
for m in memories:
print(f"{m.content} (similarity: {m.similarity:.4f})")Configuration
All configuration is done through constructor parameters and environment variables:
| Parameter | Default | Description |
|---|---|---|
| agent_id | required | Unique namespace for this agent's memories |
| sanitize_enabled | True | Enable PII sanitization (Layer 1) |
| privacy_enabled | True | Enable differential privacy (Layer 2) |
| privacy_epsilon | 0.5 | DP budget (0.01-10.0, lower = stronger) |
| aggressive_sanitize | False | Strip proper nouns (anti-inference) |
Core Concepts
Privacy-First Architecture
Synapse Layer applies a privacy-first pipeline before persistence: content passes through PII sanitization and differential-privacy noise injection on embeddings, then is encrypted at rest with AES-256-GCM using a per-operation random IV. The authentication tag is validated on every read. Only privacy-treated results (sanitized content + noisy embeddings) are persisted; original raw content is never stored.
3-Layer Cognitive Security Pipeline
Every memory operation passes through three independent, non-bypassable security layers:
Semantic Privacy Guard™
12 precompiled regex patterns detect and strip PII (emails, SSNs, CPFs, credit cards, API keys, bearer tokens, AWS keys, IPs). In aggressive mode, proper nouns are removed to prevent embedding-based inference attacks. Each operation produces an audit payload with removed items, risk score, and SHA-256 forensic hashes.
Differential Privacy
Calibrated Gaussian noise injection on embedding vectors using the analytic Gaussian mechanism: σ = Δf · √(2·ln(1.25/δ)) / ε. Provides (ε,δ)-differential privacy — mathematically provable bounds on information leakage. Vectors are L2-normalized post-noise to preserve cosine similarity compatibility. SNR metric exposed in dB.
Intelligent Intent Validation™
Every memory is classified into 8 intent categories: PREFERENCE, FACT, PROCEDURAL, BIO, EPHEMERAL, CRITICAL, UNKNOWN, INVALID. Uses keyword-consensus with saturation-based confidence scoring. Critical keyword detection provides automatic promotion. Self-Healing Protocol: conflicting memories are auto-reclassified during recall via aggregate keyword evidence.
TRUTH QUOTIENT™
Every stored memory receives a TRUTH QUOTIENT™ (TQ) score that combines agent-provided confidence with the validation layer's assessment. The TQ is computed as a function of Recency, Consistency, Confidence, and Relevance. Higher TQ scores indicate memories with stronger evidence and more recent validation. The exact weighting formula is proprietary and dynamically calibrated.
MCP Integration
Synapse Layer ships with a reference MCP server that exposes the full security pipeline as two standard MCP tools. Compatible with any MCP client: Claude Desktop, LangChain, CrewAI, MCP Inspector.
Complete MCP Server (server.py)
from __future__ import annotations
import os, json, logging
from typing import Optional
from mcp.server.fastmcp import FastMCP
from synapse_memory.core import SynapseMemory
AGENT_ID = os.getenv("SYNAPSE_AGENT_ID", "mcp-secure-memory")
PRIVACY_EPSILON = float(os.getenv("SYNAPSE_PRIVACY_EPSILON", "0.5"))
logging.basicConfig(level=logging.INFO)
memory = SynapseMemory(
agent_id=AGENT_ID,
sanitize_enabled=True,
privacy_enabled=True,
privacy_epsilon=PRIVACY_EPSILON,
)
mcp = FastMCP("Synapse Layer — Secure Memory", json_response=True)
@mcp.tool()
def store_memory(
content: str,
confidence: float = 0.9,
metadata: Optional[str] = None,
) -> dict:
"""Store a memory with automatic PII sanitization
and differential-privacy noise injection."""
meta = json.loads(metadata) if metadata else None
result = memory.store(content, confidence=confidence, metadata=meta)
return {
"memory_id": result.memory_id,
"trust_quotient": round(result.trust_quotient, 4),
"sanitized": result.sanitized,
"privacy_applied": result.privacy_applied,
"content_hash": result.content_hash,
"timestamp": result.timestamp,
}
@mcp.tool()
def recall_memory(query: str, top_k: int = 5) -> list[dict]:
"""Recall memories semantically similar to the query.
Includes self-healing metadata."""
results = memory.recall(query, top_k=top_k)
return [
{
"memory_id": r.memory_id,
"content": r.content,
"similarity": round(r.similarity, 4),
"trust_quotient": round(r.trust_quotient, 4),
"self_healed": r.self_healed,
}
for r in results
]
if __name__ == "__main__":
mcp.run(transport="stdio")Claude Desktop Configuration
Add this to your claude_desktop_config.json:
{
"mcpServers": {
"synapse-secure-memory": {
"command": "python",
"args": ["path/to/server.py"],
"env": {
"SYNAPSE_AGENT_ID": "claude-desktop",
"SYNAPSE_PRIVACY_EPSILON": "0.5"
}
}
}
}Once configured, Claude can store and recall memories using natural language. PII is sanitized and DP noise is applied transparently on every operation.
Architecture
┌──────────────────────────────────────────────┐
│ MCP Client │
│ (Claude / LangChain / CrewAI) │
└───────────────────────┬──────────────────────┘
│ JSON-RPC (stdio)
▼
┌──────────────────────────────────────────────┐
│ MCP Server (synapse-secure-memory) │
│ store_memory | recall_memory │
└───────────────────────┬──────────────────────┘
│
▼
┌──────────────────────────────────────────────┐
│ Synapse Layer SDK │
│ Sanitizer → Validator → DP → Encrypt │
└──────────────────────────────────────────────┘API Reference
TOOLstore_memory
Store a memory with automatic PII sanitization and differential-privacy noise injection.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| content | str | required | Raw text to memorize (PII auto-stripped) |
| confidence | float | 0.9 | Agent confidence (0.0\u20131.0) |
| metadata | str | null | null | Optional JSON string with key-value pairs |
Response
{
"memory_id": "a1b2c3d4...",
"trust_quotient": 0.8234,
"sanitized": true,
"privacy_applied": true,
"content_hash": "sha256:e5f6...",
"timestamp": 1712345678.123
}TOOLrecall_memory
Recall memories semantically similar to a query. Self-healing resolves conflicting categories before results are returned.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| query | str | required | Natural-language query |
| top_k | int | 5 | Maximum memories to return |
Response
[
{
"memory_id": "a1b2c3d4...",
"content": "User prefers dark mode",
"similarity": 0.9412,
"trust_quotient": 0.8234,
"self_healed": false,
"timestamp": 1712345678.123
}
]CROSS-AGENTShared Memory Recall
Any agent with a valid token for the same user_id can recall memories stored by other agents — zero configuration required.
Use the standard /api/v1/recall endpoint. Memories are ranked by the Compound Relevance Scoring (CRS) algorithm: semantic similarity, recency, and agent scope affinity.
SECUREAgent Handover (V2)
Securely transfer memory context between agents using encryption, audit trail and one-time access guarantees. Handover V1 has been deprecated and replaced by V2.
{
"action": "handover_generate",
"memoryIds": ["mem_abc123", "mem_def456"],
"fromAgentId": "claude-desktop",
"toAgentId": "cursor",
"ttlMinutes": 15
}
// Response:
{
"success": true,
"handoverId": "sess_...",
"token": "cf048e40aff806b2...", // shown ONCE
"expiresAt": "2026-05-12T04:32:18Z",
"memoryCount": 2
}{
"action": "handover_consume",
"token": "cf048e40aff806b2...",
"consumingAgent": "cursor"
}
// Response:
{
"success": true,
"fromAgent": "claude-desktop",
"memoryCount": 2,
"memories": [
{ "content": "decrypted text...", "tqScore": 0.52 }
]
}REST API (Connect)
Direct HTTP endpoints for storing and recalling memories without the Python SDK. All endpoints require authentication via x-connect-token header or Authorization: Bearer <token>.
Recall uses native pgvector cosine similarity (1536 dims, HNSW index: m=16, ef_construction=64) with full-text search fallback. Server-side embedding generation via OpenAI text-embedding-3-small on capture.
POST/api/v1/capture
Store a memory. Server generates embedding automatically from content (1536-dim, text-embedding-3-small). Optionally pass pre-computed embedding.
curl -X POST https://forge.synapselayer.org/api/v1/capture \
-H "Content-Type: application/json" \
-H "x-connect-token: sk_connect_YOUR_KEY" \
-d '{
"content": "User prefers dark mode and uses Linux",
"source": "my-app"
}'Response (201)
{
"status": "stored",
"id": "clx1abc...",
"tq": 0.4533,
"pipeline": {
"sanitized": false,
"privacyApplied": true,
"intent": "preference",
"isCritical": false,
"piiRedacted": 0
},
"source": "my-app",
"elapsed_ms": 1250
}POST/api/v1/recall
Recall memories via semantic search (pgvector 1536 dims, cosine similarity) with full-text search fallback. Supports hybrid mode with Reciprocal Rank Fusion (RRF).
curl -X POST https://forge.synapselayer.org/api/v1/recall \
-H "Content-Type: application/json" \
-H "x-connect-token: sk_connect_YOUR_KEY" \
-d '{
"query": "What are the user preferences?",
"recall_mode": "hybrid",
"limit": 5
}'Authentication
Two methods supported (both use sk_connect_* tokens):
1. x-connect-token: sk_connect_xxx (preferred)
2. Authorization: Bearer sk_connect_xxx
Generate tokens at /dashboard/connect or via POST /api/v1/token/generate.
Security & Compliance
Designed for GDPR Compliance
PII auto-stripped before storage. Right to erasure supported through memory ID deletion. Audit trail provides data processing records. (Not formally certified.)
Designed for LGPD Compliance
Full CPF/CNPJ detection. AES-256-GCM encryption at rest with PII sanitization. Architecture designed under Brazilian data protection law. (Not formally certified.)
BAA available (Enterprise)
PHI patterns detected by sanitizer. Differential privacy prevents embedding-based inference of health data. Audit payloads for compliance reporting. Compliance certifications obtained on per-customer basis.
SOC 2 Roadmap
Every operation produces cryptographic audit trails (SHA-256 hashes, timestamps, TRUTH QUOTIENT™ scores). All data encrypted in transit (TLS 1.3) and at rest (AES-256-GCM). (Not certified.)
Audit Trail Structure
Every store() call returns a complete audit payload:
result = memory.store("User data here", confidence=0.9)
# Audit fields available:
result.memory_id # SHA-256 hash of sanitized content
result.content_hash # Integrity fingerprint
result.sanitized # True (PII was processed)
result.privacy_applied # True (DP noise injected)
result.trust_quotient # Confidence x validation score
result.timestamp # Unix timestamp
result.sanitization_details # {removed_items, risk_score, pii_count}
result.privacy_details # {epsilon, delta, sigma, snr_db}
result.validation_details # {intent, confidence, source_type}PII Detection Patterns
| Pattern | Sensitivity | Examples |
|---|---|---|
| HIGH | [email protected] | |
| Credit Card | CRITICAL | 4111-1111-1111-1111 |
| SSN | CRITICAL | 123-45-6789 |
| CPF (Brazil) | CRITICAL | 000.000.000-00 |
| Phone | HIGH | +1 (555) 123-4567 |
| Date of Birth | HIGH | 01/15/1990 |
| CNPJ (Brazil) | MEDIUM | 00.000.000/0000-00 |
| API Key | CRITICAL | sk-... |
| Bearer Token | CRITICAL | Bearer eyJ... |
| URL | LOW | https://... |
| IP Address | MEDIUM | 192.168.1.1 |
| AWS Key | CRITICAL | AKIA... |
Examples
Claude Desktop
Once the MCP server is configured, Claude uses natural language to interact with memory:
"Remember that the user prefers dark mode and lives in Berlin."
Calls store_memory automatically. PII (location) is sanitized. Audit payload returned with memory_id and trust_quotient.
"What do I know about the user's preferences?"
Calls recall_memory. Returns semantically similar memories with self-healing metadata.
LangChain
from langchain_mcp_adapters.client import MultiServerMCPClient
async with MultiServerMCPClient(
{
"synapse-memory": {
"command": "python",
"args": ["path/to/server.py"],
"env": {
"SYNAPSE_AGENT_ID": "langchain-agent",
"SYNAPSE_PRIVACY_EPSILON": "0.5",
},
}
}
) as client:
tools = client.get_tools()
# tools includes store_memory and recall_memory
# Use with create_react_agent, AgentExecutor, etc.CrewAI
from crewai import Agent, Crew
from crewai_tools import MCPServerAdapter
mcp_tools = MCPServerAdapter(
server_params={
"command": "python",
"args": ["path/to/server.py"],
"env": {"SYNAPSE_AGENT_ID": "crewai-agent"},
}
)
researcher = Agent(
role="Research Analyst",
goal="Gather and securely persist research findings",
tools=mcp_tools.tools,
)
crew = Crew(agents=[researcher], tasks=[...])
crew.kickoff()MCP Inspector (Testing)
# Terminal 1: Start the server
python server.py
# Terminal 2: Launch MCP Inspector
npx -y @modelcontextprotocol/inspector
# Connect to stdio://python server.py
# Test store_memory and recall_memory interactivelyReady to integrate?
Start with the free tier or explore the Forge dashboard.