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.

bash
pip install synapse-layer

For MCP server support, also install the MCP SDK:

bash
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.

python
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:

ParameterDefaultDescription
agent_idrequiredUnique namespace for this agent's memories
sanitize_enabledTrueEnable PII sanitization (Layer 1)
privacy_enabledTrueEnable differential privacy (Layer 2)
privacy_epsilon0.5DP budget (0.01-10.0, lower = stronger)
aggressive_sanitizeFalseStrip 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:

Layer 1

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.

Layer 2

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.

Layer 3

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)

python
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:

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

text
┌──────────────────────────────────────────────┐
│              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

NameTypeDefaultDescription
contentstrrequiredRaw text to memorize (PII auto-stripped)
confidencefloat0.9Agent confidence (0.0\u20131.0)
metadatastr | nullnullOptional JSON string with key-value pairs

Response

json
{
  "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

NameTypeDefaultDescription
querystrrequiredNatural-language query
top_kint5Maximum memories to return

Response

json
[
  {
    "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.

Agent AEncrypt (AES-256-GCM)Package + TokenAgent BDecrypt
AES-256-GCM encryption per package
One-time token consumption
SHA-256 token hashing (never stored plaintext)
Audit trail via ForgeEvent
Explicit revoke support
Cross-user isolation (fail-closed)
GENERATE → POST /api/forge
python
{
  "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
}
CONSUME → POST /api/forge
python
{
  "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>.

pgvector Semantic Search — Shipped v2.0

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.

bash
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)

json
{
  "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).

bash
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:

python
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

PatternSensitivityExamples
EmailHIGH[email protected]
Credit CardCRITICAL4111-1111-1111-1111
SSNCRITICAL123-45-6789
CPF (Brazil)CRITICAL000.000.000-00
PhoneHIGH+1 (555) 123-4567
Date of BirthHIGH01/15/1990
CNPJ (Brazil)MEDIUM00.000.000/0000-00
API KeyCRITICALsk-...
Bearer TokenCRITICALBearer eyJ...
URLLOWhttps://...
IP AddressMEDIUM192.168.1.1
AWS KeyCRITICALAKIA...

Examples

Claude Desktop

Once the MCP server is configured, Claude uses natural language to interact with memory:

User

"Remember that the user prefers dark mode and lives in Berlin."

Claude

Calls store_memory automatically. PII (location) is sanitized. Audit payload returned with memory_id and trust_quotient.

User

"What do I know about the user's preferences?"

Claude

Calls recall_memory. Returns semantically similar memories with self-healing metadata.

LangChain

python
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

python
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)

bash
# 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 interactively

Ready to integrate?

Start with the free tier or explore the Forge dashboard.