# https://github.com/pquattro/memoraeu-mcp 项目说明书

生成时间：2026-05-15 22:45:24 UTC

## 目录

- [Home](#page-home)
- [Installation Guide](#page-installation)
- [System Architecture](#page-architecture)
- [Security and Encryption](#page-security-encryption)
- [Auto-Memory System](#page-auto-memory)
- [Deduplication and Compression](#page-deduplication)
- [Structured Facts System](#page-structured-facts)
- [MCP Tools Reference](#page-mcp-tools)
- [Configuration Reference](#page-configuration)
- [Deployment Guide](#page-deployment)

<a id='page-home'></a>

## Home

### 相关页面

相关主题：[Installation Guide](#page-installation), [System Architecture](#page-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)
- [memoraeu_mcp/main.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)
- [server.py](https://github.com/pquattro/memoraeu-mcp/blob/main/server.py)
- [requirements.txt](https://github.com/pquattro/memoraeu-mcp/blob/main/requirements.txt)
- [CHANGELOG.md](https://github.com/pquattro/memoraeu-mcp/blob/main/CHANGELOG.md)
</details>

# Home

MemoraEU MCP is a Model Context Protocol (MCP) server that provides zero-knowledge memory and fact storage capabilities for AI assistants. The server enables AI models to automatically remember user preferences, biographical facts, technical configurations, and structured knowledge across conversations while maintaining end-to-end encryption.

## Overview

MemoraEU MCP bridges the gap between ephemeral AI conversations and persistent memory. When integrated with Claude Desktop or other MCP-compatible clients, it allows the AI to:

- **Automatically recall** relevant memories at the start of each conversation
- **Persistently remember** user preferences, decisions, and facts without explicit requests
- **Search semantically** across encrypted memory stores
- **Manage structured facts** with temporal validity (subject/predicate/object triplets)

The architecture is designed around the principle of zero-knowledge: embeddings are computed locally before encryption, ensuring the server never sees plaintext content. 资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Architecture

```mermaid
graph TD
    subgraph "Client Side (Local)"
        A[Claude Desktop / MCP Client] --> B[MemoraEU MCP Server]
        B --> C[Mistral API<br/>Embedding Generation]
        B --> D[PBKDF2 Key Derivation]
        B --> E[AES-256-GCM Encryption]
    end
    
    subgraph "MemoraEU Cloud"
        F[API Endpoint<br/>api.memoraeu.com] --> G[Encrypted Storage]
        F --> H[Vector Search Index]
    end
    
    C -->|Plaintext| E
    D -->|Derived Key| E
    E -->|Encrypted Blob| F
    C -->|Embedding Vector| F
    
    style C fill:#ff9999
    style D fill:#ff9999
    style E fill:#ff9999
    style F fill:#99ccff
    style G fill:#99ff99
    style H fill:#99ff99
```

### Security Model

The zero-knowledge architecture ensures that all sensitive processing occurs client-side:

| Component | Location | Data Handled |
|-----------|----------|---------------|
| Embedding Generation | Local (MCP server) | Plaintext content |
| Compression | Local | Plaintext content |
| Categorization | Local | Plaintext content |
| Encryption | Local (AES-256-GCM) | Plaintext → Ciphertext |
| Storage | Remote (MemoraEU Cloud) | Encrypted blobs + vectors |
| Search | Hybrid | Vector similarity on encrypted index |

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Installation Modes

MemoraEU MCP supports two deployment modes with different security guarantees:

### STDIO Mode (Zero-Knowledge)

Full zero-knowledge encryption with all processing happening locally.

```json
{
  "mcpServers": {
    "memoraeu": {
      "command": "uvx",
      "args": ["memoraeu-mcp"],
      "env": {
        "MEMORAEU_API_URL": "https://api.memoraeu.com",
        "MEMORAEU_API_KEY": "meu-sk-...",
        "MEMORAEU_SECRET": "your-memoraeu-password",
        "MEMORAEU_SALT": "your-kdf-salt",
        "MISTRAL_API_KEY": "your-mistral-key"
      }
    }
  }
}
```

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

### SSE Mode (Remote)

Direct connection without local installation, suitable for web clients.

```json
{
  "mcpServers": {
    "memoraeu": {
      "type": "sse",
      "url": "https://api.memoraeu.com/mcp/sse",
      "headers": {
        "Authorization": "Bearer meu-sk-..."
      }
    }
  }
}
```

**Note:** In SSE remote mode, content is not zero-knowledge encrypted since the server processes plaintext. 资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Available Tools

The MCP server exposes 9 tools for memory and fact management:

### Memory Tools

| Tool | Description | Required Parameters |
|------|-------------|---------------------|
| `remember` | Automatically memorizes important information when user expresses preferences, decisions, biographical facts, or technical configs | `content` |
| `recall` | Semantic search across stored memories using vector similarity | `query` |
| `forget` | Deletes a memory by its ID | `memory_id` |
| `list_memories` | Lists recent memories with optional category filter | - |
| `list_categories` | Returns existing categories sorted by usage | - |

资料来源：[memoraeu_mcp/main.py:48-110](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

### Fact Tools

| Tool | Description | Required Parameters |
|------|-------------|---------------------|
| `remember_fact` | Stores a structured fact with temporal validity (subject/predicate/object) | `subject`, `predicate`, `object` |
| `recall_facts` | Retrieves active facts for a given subject | `subject` |
| `invalidate_fact` | Marks a fact as expired by its ID | `fact_id` |

资料来源：[server.py:48-80](https://github.com/pquattro/memoraeu-mcp/blob/main/server.py)

## Auto-Memory Behavior

The MCP server is designed to operate autonomously without manual intervention.

```mermaid
sequenceDiagram
    participant U as User
    participant C as Claude
    participant M as MemoraEU MCP
    
    U->>C: First message
    C->>M: recall(topic)
    M-->>C: Relevant memories
    C->>M: load_session_context()
    M-->>C: Recent memories via memoraeu://context
    
    Note over C: System prompt auto-injected
    
    U->>C: Expresses preference
    C->>M: remember(content, category)
    M-->>C: ✅ Memorized (ID: xxx)
```

### Automatic Recall

On the first user message of each session, `recall` is called automatically with the detected topic as the query. Recent memories are also loaded via the `memoraeu://context` resource and injected as session context. 资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

### Automatic Remember

When the AI detects a memorable piece of information (preference, decision, biographical fact, technical constraint), it calls `remember` autonomously without waiting to be asked. It confirms with a single discreet line. 资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

### System Prompt Injection

On the first `recall` call, the full behavior system prompt is injected into Claude's context, reinforcing the auto-memory rules for the rest of the session. 资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Deduplication & Compression

Before storing a memory, the MCP performs several preprocessing steps:

```mermaid
graph LR
    A[Raw Content] --> B[Local Compression]
    B --> C[Vector Similarity Check]
    C -->|≥ 94%| D[Duplicate - Skip]
    C -->|&#60; 94%| E[Local Categorization]
    E --> F[AES-256-GCM Encrypt]
    F --> G[Send to API]
```

### Similarity Thresholds

| Similarity Score | Action |
|-----------------|--------|
| ≥ 94% | Memory ignored (exact duplicate) |
| < 94% | Proceed with storage |

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Environment Variables

Five distinct variables serve different purposes—they are not interchangeable:

| Variable | Purpose | Source |
|----------|---------|--------|
| `MEMORAEU_API_KEY` | HTTP Bearer token for authentication | Dashboard → Settings → API Keys |
| `MEMORAEU_SECRET` | User's login password, used as PBKDF2 input to derive the encryption key | User account password |
| `MEMORAEU_SALT` | KDF salt unique to the account, combined with SECRET to produce the encryption key | Dashboard → Settings → Encryption Keys |
| `MEMORAEU_API_URL` | API endpoint (use `https://api.memoraeu.com` for hosted service) | - |
| `MISTRAL_API_KEY` | Generates embeddings locally before encryption (required for zero-knowledge semantic search) | Mistral Console |

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

### Without MISTRAL_API_KEY

The MCP continues to function—`remember` and `recall` remain operational—but semantic search falls back to server-side keyword search. Zero-knowledge encryption is not affected. 资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Encryption Details

The encryption scheme uses industry-standard practices:

| Parameter | Value | Source |
|-----------|-------|--------|
| Algorithm | AES-256-GCM | Symmetric encryption |
| Key Derivation | PBKDF2-HMAC-SHA256 | Password-based key derivation |
| Iterations | 210,000 | OWASP 2024 recommendation |
| Ciphertext Prefix | `ENCv1:` | Version identifier |

资料来源：[CHANGELOG.md](https://github.com/pquattro/memoraeu-mcp/blob/main/CHANGELOG.md)

## Dependencies

| Package | Version | Purpose |
|---------|---------|---------|
| `mcp` | ≥1.1.0, <1.2.0 | Model Context Protocol framework |
| `httpx` | 0.28.1 | HTTP client |
| `python-dotenv` | 1.0.1 | Environment variable loading |
| `starlette` | ≥0.40.0, <0.42.0 | ASGI framework |
| `cryptography` | ≥42.0.0 | Encryption primitives |

资料来源：[requirements.txt](https://github.com/pquattro/memoraeu-mcp/blob/main/requirements.txt)

## Resources

The MCP server exposes the following resource:

| URI | Name | Description |
|-----|------|-------------|
| `memoraeu://context` | Contexte mémoire MemoraEU | Recent memories automatically injected at session start |

资料来源：[memoraeu_mcp/main.py:115-120](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

## Prompts

| Name | Description |
|------|-------------|
| `memoraeu_system` | MemoraEU automatic memory behavior system prompt—injectable into Claude's context |

资料来源：[memoraeu_mcp/main.py:137-145](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

## Quick Start Guide

### 1. Create Account and Obtain Keys

1. Create an account at [app.memoraeu.com](https://app.memoraeu.com)
2. Navigate to **Settings → Encryption Keys** → copy `MEMORAEU_SALT`
3. `MEMORAEU_SECRET` is your MemoraEU login password
4. Navigate to **Settings → API Keys** → create a key → copy `MEMORAEU_API_KEY`
5. Obtain a Mistral API key from [console.mistral.ai](https://console.mistral.ai)

### 2. Configure Claude Desktop

Add the following to your `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "memoraeu": {
      "command": "uvx",
      "args": ["memoraeu-mcp"],
      "env": {
        "MEMORAEU_API_URL": "https://api.memoraeu.com",
        "MEMORAEU_API_KEY": "meu-sk-...",
        "MEMORAEU_SECRET": "your-memoraeu-password",
        "MEMORAEU_SALT": "your-kdf-salt",
        "MISTRAL_API_KEY": "your-mistral-key"
      }
    }
  }
}
```

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Supported Clients

| Client | Support Type |
|--------|--------------|
| Claude Desktop | Full STDIO support |
| Claude.ai Web | SSE remote mode |
| Cursor | SSE configuration |
| Windsurf | SSE configuration |
| Other MCP Clients | STDIO or SSE depending on client capability |

## Changelog Summary

| Version | Date | Key Changes |
|---------|------|-------------|
| 0.1.9 | 2026-05-12 | Added `remember_fact`, `recall_facts`, `invalidate_fact`; PBKDF2 updated to 210k iterations |
| 0.1.5 | 2026-04-28 | PBKDF2 210k iterations + `ENCv1:` prefix |

资料来源：[CHANGELOG.md](https://github.com/pquattro/memoraeu-mcp/blob/main/CHANGELOG.md)

---

<a id='page-installation'></a>

## Installation Guide

### 相关页面

相关主题：[Configuration Reference](#page-configuration), [Deployment Guide](#page-deployment)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)
- [server.py](https://github.com/pquattro/memoraeu-mcp/blob/main/server.py)
- [memoraeu_mcp/server.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/server.py)
- [requirements.txt](https://github.com/pquattro/memoraeu-mcp/blob/main/requirements.txt)
- [CHANGELOG.md](https://github.com/pquattro/memoraeu-mcp/blob/main/CHANGELOG.md)
</details>

# Installation Guide

This guide covers all supported installation methods for the **memoraeu-mcp** server, a Model Context Protocol server that provides zero-knowledge encrypted memory capabilities for AI assistants.

## Overview

memoraeu-mcp can be installed in two modes:

| Mode | Transport | Zero-Knowledge | Use Case |
|------|-----------|----------------|----------|
| **Local (stdio)** | `stdio` | ✅ Full | Desktop applications (Claude Desktop, Cursor, Windsurf) |
| **Remote (SSE)** | `SSE` | ⚠️ Partial | Web clients, shared environments |

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Prerequisites

Before installation, ensure you have:

- **Python 3.11+** — Required for the MCP server
- **uvx** or **pip** — For package installation
- **MemoraEU Account** — Required for API access
- **Mistral API Key** — For local embedding generation (required for zero-knowledge semantic search)

### Required Accounts and Keys

| Service | Purpose | Signup Location |
|---------|---------|-----------------|
| MemoraEU | Memory storage and sync | [app.memoraeu.com](https://app.memoraeu.com) |
| Mistral AI | Local embedding generation | [console.mistral.ai](https://console.mistral.ai) |

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Installation Methods

### Method 1: Local Installation (stdio) — Recommended

This method provides **full zero-knowledge encryption** where embeddings are generated locally before any data leaves your machine.

#### Step 1: Install the Package

```bash
uvx memoraeu-mcp
```

Or using pip:

```bash
pip install memoraeu-mcp
```

#### Step 2: Obtain MemoraEU Credentials

1. Create an account at [app.memoraeu.com](https://app.memoraeu.com)
2. Navigate to **Settings → Encryption Keys** → copy `MEMORAEU_SALT`
3. `MEMORAEU_SECRET` is your MemoraEU login password
4. Navigate to **Settings → API Keys** → create a key → copy `MEMORAEU_API_KEY`

#### Step 3: Configure Claude Desktop

Add the following to your `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "memoraeu": {
      "command": "uvx",
      "args": ["memoraeu-mcp"],
      "env": {
        "MEMORAEU_API_URL": "https://api.memoraeu.com",
        "MEMORAEU_API_KEY": "meu-sk-...",
        "MEMORAEU_SECRET": "your-memoraeu-password",
        "MEMORAEU_SALT": "your-kdf-salt",
        "MISTRAL_API_KEY": "your-mistral-key"
      }
    }
  }
}
```

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

### Method 2: Remote Installation (SSE) — Zero-Knowledge NOT Guaranteed

Use this method when you cannot install locally or need quick access from web clients.

> ⚠️ **Security Notice**: In remote SSE mode, content is **not zero-knowledge encrypted**. The server processes plaintext. Use local `stdio` installation for full zero-knowledge guarantees.

#### Configuration for Remote Clients

Configure your MCP client (Cursor, Windsurf, or any SSE-compatible client):

```json
{
  "mcpServers": {
    "memoraeu": {
      "type": "sse",
      "url": "https://api.memoraeu.com/mcp/sse",
      "headers": {
        "Authorization": "Bearer meu-sk-..."
      }
    }
  }
}
```

**SSE Endpoint Details:**

| Property | Value |
|----------|-------|
| Endpoint URL | `https://api.memoraeu.com/mcp/sse` |
| Authentication | Bearer token in `Authorization` header |
| API Key Format | `meu-sk-xxx` |

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Environment Variables Reference

All configuration is done via environment variables. These five variables serve **three distinct purposes** — they are **not interchangeable**.

| Variable | Purpose | Required | Where to Get |
|----------|---------|----------|--------------|
| `MEMORAEU_API_KEY` | HTTP authentication (Bearer token sent with every request) | Yes | Dashboard → Settings → API Keys |
| `MEMORAEU_SECRET` | Your MemoraEU login password — used as PBKDF2 input to derive the encryption key locally | Yes (local) | Your account password |
| `MEMORAEU_SALT` | KDF salt generated by the server, unique to your account | Yes (local) | Dashboard → Settings → Encryption Keys |
| `MEMORAEU_API_URL` | API endpoint for the hosted service | Yes | Use `https://api.memoraeu.com` |
| `MISTRAL_API_KEY` | Used to generate embeddings locally before encryption | Yes (local) | [console.mistral.ai](https://console.mistral.ai) |

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

### Variable Dependency Matrix

```mermaid
graph TD
    A[Local Installation] --> B{MISTRAL_API_KEY set?}
    B -->|Yes| C[Full Zero-Knowledge Mode]
    B -->|No| D[Keyword Search Fallback]
    C --> E[Embeddings generated locally<br/>before encryption]
    D --> F[Server-side keyword search<br/>Zero-knowledge encryption preserved]
    
    G[Remote SSE Mode] --> H[No Local Processing<br/>Server sees plaintext]
    
    style C fill:#90EE90
    style D fill:#FFE4B5
    style H fill:#FFB6C1
```

### Why is MISTRAL_API_KEY Required Locally?

The zero-knowledge architecture requires that:
1. Embeddings must be calculated **before** encryption
2. This happens on your local machine
3. The MCP calls Mistral directly with plaintext
4. The server receives an opaque blob + vector it cannot decrypt

Without `MISTRAL_API_KEY`, semantic search falls back to keyword search on the server side, but **zero-knowledge encryption remains intact**.

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Configuration Examples by Client

### Claude Desktop

```json
{
  "mcpServers": {
    "memoraeu": {
      "command": "uvx",
      "args": ["memoraeu-mcp"],
      "env": {
        "MEMORAEU_API_URL": "https://api.memoraeu.com",
        "MEMORAEU_API_KEY": "meu-sk-...",
        "MEMORAEU_SECRET": "your-memoraeu-password",
        "MEMORAEU_SALT": "your-kdf-salt",
        "MISTRAL_API_KEY": "your-mistral-key"
      }
    }
  }
}
```

### Cursor / Windsurf (Local)

```json
{
  "mcpServers": {
    "memoraeu": {
      "command": "uvx",
      "args": ["memoraeu-mcp"],
      "env": {
        "MEMORAEU_API_URL": "https://api.memoraeu.com",
        "MEMORAEU_API_KEY": "meu-sk-...",
        "MEMORAEU_SECRET": "your-memoraeu-password",
        "MEMORAEU_SALT": "your-kdf-salt",
        "MISTRAL_API_KEY": "your-mistral-key"
      }
    }
  }
}
```

### Cursor / Windsurf (Remote SSE)

```json
{
  "mcpServers": {
    "memoraeu": {
      "type": "sse",
      "url": "https://api.memoraeu.com/mcp/sse",
      "headers": {
        "Authorization": "Bearer meu-sk-..."
      }
    }
  }
}
```

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Supported Transport Protocols

| Protocol | Use Case | Zero-Knowledge | Setup Complexity |
|----------|----------|----------------|------------------|
| `stdio` | Local desktop apps | ✅ Full | Requires uvx/pip |
| `sse` | Remote/web clients | ⚠️ Server sees plaintext | Quick setup |

The MCP server implements both protocols via the MCP SDK:

资料来源：[memoraeu_mcp/main.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

## Package Dependencies

The following dependencies are required and specified in `requirements.txt`:

| Package | Version | Purpose |
|---------|---------|---------|
| `mcp` | ≥1.1.0, <1.2.0 | Model Context Protocol SDK |
| `httpx` | 0.28.1 | HTTP client for API calls |
| `python-dotenv` | 1.0.1 | Environment variable loading |
| `starlette` | ≥0.40.0, <0.42.0 | ASGI framework |
| `cryptography` | ≥42.0.0 | AES-256-GCM encryption |

资料来源：[requirements.txt](https://github.com/pquattro/memoraeu-mcp/blob/main/requirements.txt)

## Installation Flow Diagram

```mermaid
flowchart TD
    A[Start Installation] --> B{Choose Mode}
    
    B -->|Local stdio| C[Install via uvx or pip]
    B -->|Remote SSE| D[Configure client directly]
    
    C --> E[Create MemoraEU Account]
    E --> F[Get API Key & Salt]
    F --> G[Get Mistral API Key]
    G --> H[Configure claude_desktop_config.json]
    H --> I[Verify Installation]
    
    D --> J[Get Bearer Token]
    J --> K[Configure SSE in client]
    K --> L[Verify Connection]
    
    I --> M[✅ Zero-Knowledge Ready]
    L --> N[⚠️ Remote Mode Active]
```

## Verifying Installation

After installation, verify the MCP server is working by:

1. **Check MCP server status** in your client
2. **Run a test command** using any available tool:
   - `list_categories` — Should return an empty list or existing categories
   - `list_memories` — Should confirm connection

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Troubleshooting

| Issue | Solution |
|-------|----------|
| "Module not found" errors | Ensure `uvx` or `pip` installation completed successfully |
| SSE connection failures | Verify API key format is `meu-sk-xxx` and endpoint URL is correct |
| Semantic search not working | Check `MISTRAL_API_KEY` is set; falls back to keyword search if missing |
| Encryption errors | Verify `MEMORAEU_SALT` and `MEMORAEU_SECRET` are correct |

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Security Architecture Summary

| Component | Location | Description |
|-----------|----------|-------------|
| Encryption | Client-side | AES-256-GCM with PBKDF2-HMAC-SHA256 (100k iterations) |
| Embedding generation | Client-side | Mistral embeddings computed before encryption |
| Storage | Server-side | Opaque encrypted blobs + vectors |
| Key derivation | Client-side | Password + salt → encryption key |

资料来源：[CHANGELOG.md](https://github.com/pquattro/memoraeu-mcp/blob/main/CHANGELOG.md)

---

<a id='page-architecture'></a>

## System Architecture

### 相关页面

相关主题：[Security and Encryption](#page-security-encryption), [MCP Tools Reference](#page-mcp-tools)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [memoraeu_mcp/main.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)
- [memoraeu_mcp/server.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/server.py)
- [server.py](https://github.com/pquattro/memoraeu-mcp/blob/main/server.py)
</details>

# System Architecture

## Overview

The **memoraeu-mcp** is a Model Context Protocol (MCP) server that provides zero-knowledge memory capabilities for AI assistants. It enables automatic memorization and semantic recall of user information while maintaining end-to-end encryption where the server never sees plaintext data.

The architecture follows a client-side encryption model where all sensitive operations (compression, embedding generation, categorization, and encryption) occur locally before any data is transmitted to the remote API.

## High-Level Architecture

```mermaid
graph TD
    subgraph Client["Client Side (Local)"]
        MCP["MCP Client<br/>(Claude Desktop, Cursor, etc.)"]
        Tools["Tool Handlers<br/>remember, recall, forget, etc."]
        Crypto["Encryption Module<br/>AES-256-GCM + PBKDF2"]
        Embed["Embedding Generator<br/>(Mistral API)"]
        Compress["Local Compression"]
        Categorize["Local Categorization"]
    end

    subgraph External["External Services"]
        Mistral["Mistral API<br/>(Embeddings)"]
    end

    subgraph Server["MemoraEU Remote API"]
        API["API Endpoint<br/>api.memoraeu.com"]
        Storage["Encrypted Storage"]
    end

    MCP --> Tools
    Tools --> Crypto
    Tools --> Embed
    Tools --> Compress
    Tools --> Categorize
    Embed --> Mistral
    Tools --> API
    API --> Storage

    style Client fill:#e1f5fe
    style Server fill:#fff3e0
    style External fill:#f3e5f5
```

## Component Architecture

### Entry Points

The project provides multiple entry points for different deployment scenarios:

| Entry Point | Purpose | Use Case |
|-------------|---------|----------|
| `memoraeu_mcp/server.py` | Pip/uvx installation entry | Installed via package manager |
| `server.py` | Development/main server | Direct execution with `python server.py` |
| SSE Remote | Remote MCP via Server-Sent Events | Web clients without local install |

资料来源：[memoraeu_mcp/server.py:1-9]()

```python
"""Entry point pour memoraeu-mcp installé via pip/uvx."""
import asyncio

def run():
    from memoraeu_mcp.main import main
    asyncio.run(main())
```

### Core Server Module

The `memoraeu_mcp/main.py` file contains the complete MCP server implementation with all tool handlers, resource providers, and prompt managers.

资料来源：[memoraeu_mcp/main.py:1-200]()

## MCP Protocol Implementation

### Tool Registration

```mermaid
graph LR
    A[list_tools] --> B[Tool Definitions]
    B --> C[remember]
    B --> D[recall]
    B --> E[forget]
    B --> F[list_memories]
    B --> G[list_categories]
    B --> H[remember_fact]
    B --> I[recall_facts]
    B --> J[invalidate_fact]
```

All tools are defined using the MCP SDK `Tool` class with JSON schemas:

```python
Tool(
    name="remember",
    description="Mémorise automatiquement une information importante...",
    inputSchema={
        "type": "object",
        "properties": {
            "content": {"type": "string"},
            "category": {"type": "string"},
            "tags": {"type": "array", "items": {"type": "string"}}
        },
        "required": ["content"]
    }
)
```

资料来源：[memoraeu_mcp/main.py:73-106]()

### Available Tools

| Tool | Function | Input Parameters |
|------|----------|-------------------|
| `remember` | Stores important information | `content` (required), `category`, `tags` |
| `recall` | Semantic search across memories | `query` (required), `limit`, `category` |
| `forget` | Deletes a memory by ID | `memory_id` (required) |
| `list_memories` | Lists recent memories | `category`, `limit` |
| `list_categories` | Returns categories sorted by usage | None |
| `remember_fact` | Stores structured fact | `subject`, `predicate`, `object`, `scope`, `valid_from` |
| `recall_facts` | Retrieves active facts | `subject`, `predicate`, `scope`, `history` |
| `invalidate_fact` | Marks fact as expired | `fact_id`, `valid_to` |

### Resources

The server provides a single resource URI for memory context injection:

| Resource URI | Name | Purpose |
|--------------|------|---------|
| `memoraeu://context` | Contexte mémoire MemoraEU | Recent memories injected automatically at session start |

资料来源：[memoraeu_mcp/main.py:148-165]()

```python
@app.list_resources()
async def list_resources() -> list[Resource]:
    return [
        Resource(
            uri="memoraeu://context",
            name="Contexte mémoire MemoraEU",
            description="Mémoires récentes injectées automatiquement en début de session",
            mimeType="text/plain"
        )
    ]
```

### Prompts

A single system prompt is available for memory behavior injection:

| Prompt Name | Description |
|-------------|-------------|
| `memoraeu_system` | Injects automatic memory behavior rules into Claude's context |

资料来源：[memoraeu_mcp/main.py:132-147]()

## Data Flow Architecture

### Memory Storage Flow

```mermaid
graph TD
    A[User Input] --> B[remember tool]
    B --> C{API Key Available?}
    C -->|Yes| D[Generate Embedding via Mistral]
    C -->|No| E[Skip Embedding]
    D --> F[Compress Content Locally]
    E --> F
    F --> G[Categorize Locally]
    G --> H[Check Duplicate Similarity]
    H --> I{Similarity >= 94%?}
    I -->|Yes| J[Ignore - Duplicate]
    I -->|No| K[Encrypt Content AES-256-GCM]
    K --> L[API POST /memories]
    L --> M[Server Stores Encrypted Blob]
```

### Memory Retrieval Flow

```mermaid
graph TD
    A[recall tool] --> B[First recall of session?]
    B -->|Yes| C[Load Session Context]
    B -->|No| D[Skip Context]
    C --> E[Inject System Prompt]
    D --> F[API POST /memories/search]
    E --> F
    F --> G[Receive Encrypted Results]
    G --> H[Decrypt Content Locally]
    H --> I[Return Plaintext to Client]
```

## Security Architecture

### Zero-Knowledge Model

```mermaid
graph LR
    subgraph Client["Client"]
        P[Plaintext Content]
        E[Encryption]
        K[Key Derivation]
    end

    subgraph Server["Server"]
        C[Encrypted Blob]
        V[Vector Embedding]
    end

    P --> E
    E --> C
    P --> K
    K --> E
    C --> Server
    V --> Server
```

The security model ensures:

1. **Encryption before transmission** - Content is encrypted locally using AES-256-GCM
2. **Client-side embedding** - Semantic vectors are generated from plaintext before encryption
3. **Key derivation** - PBKDF2-HMAC-SHA256 with 100,000 iterations derives encryption keys

### Key Derivation Parameters

| Parameter | Variable | Source |
|-----------|----------|--------|
| Secret | `MEMORAEU_SECRET` | User's account password |
| Salt | `MEMORAEU_SALT` | Server-generated, unique per account |
| Iterations | 100,000 | Hardcoded in implementation |

资料来源：[memoraeu_mcp/main.py:1-50]()

### API Authentication

Two authentication modes are supported:

| Mode | Configuration | Transport |
|------|--------------|-----------|
| Local stdio | Environment variables | Standard I/O |
| Remote SSE | Bearer token header | Server-Sent Events |

```json
{
  "mcpServers": {
    "memoraeu": {
      "type": "sse",
      "url": "https://api.memoraeu.com/mcp/sse",
      "headers": {
        "Authorization": "Bearer meu-sk-..."
      }
    }
  }
}
```

## Configuration Architecture

### Environment Variables

| Variable | Purpose | Required | Source |
|----------|---------|----------|--------|
| `MEMORAEU_API_URL` | API endpoint | Yes | Fixed for hosted service |
| `MEMORAEU_API_KEY` | HTTP Bearer authentication | Yes | Dashboard → Settings → API Keys |
| `MEMORAEU_SECRET` | Password for key derivation | Yes (local) | User account password |
| `MEMORAEU_SALT` | KDF salt | Yes (local) | Dashboard → Settings → Encryption Keys |
| `MISTRAL_API_KEY` | Local embedding generation | Yes (zero-knowledge) | Mistral Console |

资料来源：[README.md:1-50]()

### Configuration File Structure

```json
{
  "mcpServers": {
    "memoraeu": {
      "command": "uvx",
      "args": ["memoraeu-mcp"],
      "env": {
        "MEMORAEU_API_URL": "https://api.memoraeu.com",
        "MEMORAEU_API_KEY": "meu-sk-...",
        "MEMORAEU_SECRET": "your-memoraeu-password",
        "MEMORAEU_SALT": "your-kdf-salt",
        "MISTRAL_API_KEY": "your-mistral-key"
      }
    }
  }
}
```

## Dependencies

The project depends on the following packages:

| Package | Version | Purpose |
|---------|---------|---------|
| `mcp` | >=1.1.0, <1.2.0 | MCP SDK framework |
| `httpx` | 0.28.1 | HTTP client for API calls |
| `python-dotenv` | 1.0.1 | Environment variable loading |
| `starlette` | >=0.40.0, <0.42.0 | ASGI framework for SSE |
| `cryptography` | >=42.0.0 | AES-256-GCM encryption |

资料来源：[requirements.txt:1-5]()

## Auto-Memory Behavior System

The MCP server implements automatic memory management without manual intervention:

### Automatic Recall

On the first user message of each session:
1. `recall` is called automatically with detected topic as query
2. Recent memories are loaded via `memoraeu://context` resource
3. Context is injected into the session

### Automatic Remember

When Claude detects memorable information:
- Preferences
- Decisions
- Biographical facts
- Technical configurations
- Durable constraints

It calls `remember` autonomously with a single discreet confirmation.

### System Prompt Injection

On the first `recall` call, the full behavior system prompt is injected:

```
SYSTEM_PROMPT_TEXT contains:
- Memory objectives (preferences, decisions, biographical facts)
- Automatic recall rules
- Token optimization guidelines
```

## Deduplication System

Before storing a memory, the system checks for near-duplicates:

| Similarity Threshold | Action |
|---------------------|--------|
| ≥ 94% | Memory ignored (exact duplicate) |
| < 94% | Memory stored normally |

This prevents storage of redundant information while allowing similar but distinct memories.

## Error Handling Architecture

All tool handlers follow a consistent error handling pattern:

```python
@app.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
    if name == "remember":
        try:
            # Tool implementation
            return [TextContent(type="text", text="✅ Success message")]
        except Exception as e:
            return [TextContent(type="text", text=f"❌ Error : {e}")]
```

This ensures all errors return user-friendly messages rather than raw exceptions.

## Module Structure Summary

```
memoraeu_mcp/
├── main.py          # Core MCP server implementation
│   ├── @app decorators (tools, resources, prompts)
│   ├── Tool handlers (remember, recall, forget, etc.)
│   ├── Encryption functions
│   ├── API communication
│   └── Local processing (compression, categorization)
└── server.py        # Entry point for pip/uvx installation

---

<a id='page-security-encryption'></a>

## Security and Encryption

### 相关页面

相关主题：[System Architecture](#page-architecture), [Configuration Reference](#page-configuration)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [memoraeu_mcp/crypto.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/crypto.py)
- [server.py](https://github.com/pquattro/memoraeu-mcp/blob/main/server.py)
- [memoraeu_mcp/main.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)
- [requirements.txt](https://github.com/pquattro/memoraeu-mcp/blob/main/requirements.txt)
- [README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)
</details>

# Security and Encryption

## Overview

MemoraEU implements a **zero-knowledge encryption architecture** where all memory content is encrypted client-side before transmission to the server. The server never receives plaintext data or encryption keys, ensuring complete privacy of stored memories.

The system uses industry-standard cryptographic primitives:
- **AES-256-GCM** for authenticated encryption
- **PBKDF2-HMAC-SHA256** with 210,000 iterations for key derivation

资料来源：[memoraeu_mcp/crypto.py:1-15]()

---

## Architecture

### Zero-Knowledge Flow

```mermaid
graph TD
    A[User Data] -->|Plaintext| B[Client-Side MCP Server]
    B --> C[Mistral Embeddings<br/>Generated from plaintext]
    C --> D[encrypt_content]
    D --> E[AES-256-GCM<br/>Encryption]
    E --> F[ENCv1:... ciphertext]
    F --> G[MemoraEU API]
    F --> H[Stored in DB]
    
    I[API Request] -->|encrypted data only| G
    G -->|cannot decrypt| H
    
    J[MEMORAEU_SECRET<br/>+ MEMORAEU_SALT] -->|derive_key| K[AES-256 Key]
    K -->|in memory only| D
```

The embedding generation happens **before** encryption to preserve semantic search capabilities while maintaining zero-knowledge guarantees. The server stores encrypted content and pre-computed embeddings but cannot decrypt the actual memory content.

资料来源：[memoraeu_mcp/crypto.py:1-15]()

---

## Key Derivation

### PBKDF2 Configuration

| Parameter | Value | Notes |
|-----------|-------|-------|
| Algorithm | PBKDF2-HMAC-SHA256 | NIST recommended |
| Iterations | 210,000 | OWASP 2024 recommendation |
| Key Length | 32 bytes | AES-256 requirement |
| Salt | User-specific | Server-generated, stored in dashboard |

The key derivation uses a high iteration count to make brute-force attacks computationally expensive. The salt is unique per user account and generated server-side to prevent rainbow table attacks.

资料来源：[memoraeu_mcp/crypto.py:22-23]()

### Derivation Function

```python
def derive_key(password: str, salt: str) -> bytes:
    salt_bytes = salt.encode() if isinstance(salt, str) else salt
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt_bytes,
        iterations=PBKDF2_ITERATIONS,
    )
    return kdf.derive(password.encode())
```

The function accepts `MEMORAEU_SECRET` (user's account password) and `MEMORAEU_SALT` (server-generated salt) to derive the encryption key.

资料来源：[memoraeu_mcp/crypto.py:28-41]()

---

## Encryption

### AES-256-GCM

The implementation uses the `cryptography` library's AESGCM implementation for authenticated encryption. GCM mode provides both confidentiality and integrity protection.

| Property | Value |
|----------|-------|
| Cipher | AES-256 |
| Mode | GCM (Galois/Counter Mode) |
| Nonce | Random per encryption |
| Authentication | Included in GCM mode |

### Encrypted Value Format

Encrypted values are prefixed with `ENCv1:` to enable detection:

```
ENCv1:<base64-encoded nonce + ciphertext + auth_tag>
```

This prefix allows the decryption function to distinguish between encrypted and plaintext values.

资料来源：[memoraeu_mcp/crypto.py:20-23]()

---

## Key Management

### Initialization Flow

```mermaid
sequenceDiagram
    participant App as MCP Server
    participant Crypto as crypto module
    participant Env as Environment
    
    App->>Env: Read MEMORAEU_SECRET, MEMORAEU_SALT
    App->>App: init_crypto()
    App->>Crypto: derive_key(secret, salt)
    Crypto-->>App: 32-byte AES key
    App->>App: Store in _key global
    
    Note over App: Key held only in memory
```

### Environment Variables

| Variable | Purpose | Source |
|----------|---------|--------|
| `MEMORAEU_SECRET` | User password for key derivation | User's account password |
| `MEMORAEU_SALT` | KDF salt, unique per account | Dashboard → Settings → Encryption Keys |
| `MEMORAEU_API_KEY` | HTTP Bearer authentication | Dashboard → Settings → API Keys |

资料来源：[server.py:1-30]()

### Key Storage

The derived key is stored in the `_key` global variable and is never persisted to disk or transmitted to the server:

```python
_key: bytes | None = None

def get_key() -> bytes | None:
    return _key
```

资料来源：[memoraeu_mcp/main.py:1-30]()

---

## Encryption/Decryption Wrappers

### Content Encryption

```python
def encrypt_content(content: str) -> str:
    key = get_key()
    if not key:
        return content  # Fallback to plaintext
    from memoraeu_mcp.crypto import encrypt
    return encrypt(content, key)
```

If the encryption key is not available (e.g., `MEMORAEU_SECRET` not configured), content is stored in plaintext with a warning message.

资料来源：[server.py:50-60]()

### Content Decryption

```python
def decrypt_content(value: str) -> str:
    key = get_key()
    if not key:
        return value
    from memoraeu_mcp.crypto import decrypt, is_encrypted
    if not is_encrypted(value):
        return value
    try:
        return decrypt(value, key)
    except Exception:
        return "[contenu chiffré — clé incorrecte]"
```

Decryption failures (e.g., wrong key) return a placeholder message rather than exposing error details.

资料来源：[memoraeu_mcp/main.py:60-80]()

---

## Dependency Requirements

The security implementation requires the `cryptography` library:

```
cryptography>=42.0.0
```

This ensures access to the `cryptography.hazmat` primitives used for AES-GCM and PBKDF2.

资料来源：[requirements.txt:1-5]()

---

## Security Properties

### Guarantees

| Property | Implementation |
|----------|----------------|
| Confidentiality | AES-256-GCM encryption, key never leaves client |
| Integrity | GCM authentication tag verification |
| Authentication | PBKDF2 key derivation from user password |
| Non-repudiation | User-specific salt ensures key uniqueness |

### Threat Model

| Threat | Mitigation |
|--------|------------|
| Server compromise | Server stores only encrypted data |
| Man-in-middle | HTTPS transport + client-side encryption |
| Brute force | 210,000 PBKDF2 iterations |
| Rainbow tables | Unique per-user salt |
| Replay attacks | Random nonce per encryption operation |

---

## Configuration Examples

### Full Zero-Knowledge Setup

```json
{
  "mcpServers": {
    "memoraeu": {
      "command": "uvx",
      "args": ["memoraeu-mcp"],
      "env": {
        "MEMORAEU_API_URL": "https://api.memoraeu.com",
        "MEMORAEU_API_KEY": "meu-sk-...",
        "MEMORAEU_SECRET": "your-memoraeu-password",
        "MEMORAEU_SALT": "server-generated-salt",
        "MISTRAL_API_KEY": "your-mistral-key"
      }
    }
  }
}
```

### Remote SSE Mode (Reduced Security)

In remote SSE mode, content is processed on the server and is **not zero-knowledge encrypted**:

> **Note:** En mode SSE distant, le contenu n'est pas chiffré zero-knowledge (le serveur traite le texte en clair). Utilisez l'installation locale `stdio` pour les garanties zero-knowledge complètes.

资料来源：[README.md:1-30]()

---

## Startup Behavior

On server initialization:

```
[memoraeu] ✅ Chiffrement zero-knowledge activé
```

Or if `MEMORAEU_SECRET` is missing:

```
[memoraeu] ⚠️  MEMORAEU_SECRET absent — stockage en clair
```

资料来源：[server.py:45-50]()

---

<a id='page-auto-memory'></a>

## Auto-Memory System

### 相关页面

相关主题：[MCP Tools Reference](#page-mcp-tools), [Structured Facts System](#page-structured-facts)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this documentation:

- [memoraeu_mcp/main.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)
- [server.py](https://github.com/pquattro/memoraeu-mcp/blob/main/server.py)
- [README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)
- [CHANGELOG.md](https://github.com/pquattro/memoraeu-mcp/blob/main/CHANGELOG.md)
- [requirements.txt](https://github.com/pquattro/memoraeu-mcp/blob/main/requirements.txt)
</details>

# Auto-Memory System

The Auto-Memory System is a zero-knowledge, privacy-preserving memory management layer built into the MemoraEU MCP (Model Context Protocol) server. It enables AI assistants to automatically remember user preferences, decisions, biographical facts, and technical constraints across conversations without requiring manual intervention.

## Overview

The system operates on a **client-side encryption** model where:

- All memory content is encrypted locally before transmission
- Embeddings for semantic search are computed from plaintext before encryption
- The server processes encrypted data without visibility into content
- A PBKDF2-HMAC-SHA256 key derivation scheme (210,000 iterations) protects the encryption key derived from the user's password

```mermaid
graph TD
    A[User Message] --> B{Auto-Recall Trigger}
    B --> C[Extract Topic Query]
    C --> D[Semantic Search<br/>memoraeu://context]
    D --> E[Load Recent Memories]
    E --> F[Inject into Session Context]
    
    G[User Expresses<br/>Preference/Fact] --> H{Auto-Remember Trigger}
    H --> I[Compress Content]
    I --> J[Categorize Locally]
    J --> K[Generate Embedding]
    K --> L{Check Duplicates<br/>Similarity ≥ 94%}
    L -->|No Duplicate| M[Encrypt Content]
    L -->|Duplicate Found| N[Skip Storage]
    M --> O[Store Memory]
```

## Core Components

### 1. Automatic Recall

On the first user message of each session, the MCP server automatically triggers a `recall` operation using the detected topic as the search query. 资料来源：[README.md:40-45]()

**Behavior:**
- Retrieves relevant memories via semantic search
- Loads recent memories through the `memoraeu://context` resource
- Injects memories as session context automatically
- No manual invocation required

```mermaid
sequenceDiagram
    participant U as User
    participant MCP as MCP Server
    participant API as MemoraEU API
    participant LLM as Claude Model
    
    U->>MCP: First Message
    MCP->>MCP: Detect Topic
    MCP->>API: recall(topic, limit=3)
    API->>MCP: Relevant Memories
    MCP->>LLM: Inject Context
    MCP->>LLM: Inject System Prompt
```

### 2. Automatic Remember

When the LLM detects a durable piece of information (preference, decision, biographical fact, or technical constraint), it autonomously calls the `remember` tool without waiting to be asked. 资料来源：[README.md:47-52]()

**Triggers for automatic memory:**
- User expresses a preference
- User makes a decision
- User shares biographical information
- User mentions technical constraints or configurations

**Confirmation:** The system confirms storage with a single discreet line.

### 3. System Prompt Injection

On the first `recall` call of a session, the full behavior system prompt is injected into Claude's context. This reinforces the auto-memory rules for the remainder of the session. 资料来源：[README.md:54-58]()

The system prompt includes:
```
## Ce qu'il faut mémoriser
- Préférences et configurations utilisateur
- Décisions et choix récurrents ou contraintes durables
- Informations techniques propres à l'utilisateur (stack, config, credentials non-sensibles)

## Rappel automatique
Dès le premier message de l'utilisateur, utilise `recall` avec le sujet détecté comme query.
N'attends pas qu'on te le demande — c'est automatique.

## Règles
- Ne mémorise pas les informations générales ou éphémères (météo du jour, blagues, calculs ponctuels)
- Si l'utilisateur dit "oublie ça" ou "ne retiens pas", utilise `forget`
- Confirme discrètement les mémorisations : une ligne, pas plus
- Optimisation tokens : limite recall à 3 résultats par défaut, mémoires compactes
```

## Available Tools

| Tool | Description | Input Schema |
|------|-------------|--------------|
| `remember` | Memorizes important information automatically | `content`, `category`, `tags` |
| `recall` | Semantic search across stored memories | `query`, `limit` (default: 3), `category` |
| `forget` | Deletes a memory by ID | `memory_id` |
| `list_memories` | Lists recent memories with optional category filter | `category`, `limit` (default: 20) |
| `list_categories` | Returns existing categories sorted by usage | — |
| `remember_fact` | Stores structured fact with temporal validity | `subject`, `predicate`, `object`, `valid_from`, `valid_to`, `scope` |
| `recall_facts` | Retrieves active facts for a subject | `subject`, `predicate`, `scope`, `history` |
| `invalidate_fact` | Marks a fact as expired | `fact_id`, `valid_to` |

### Tool Configuration in MCP

Tools are registered via the MCP manifest in `list_tools()`:

```python
Tool(
    name="remember",
    description=(
        "Mémorise automatiquement une information importante. "
        "UTILISE CET OUTIL SANS QU'ON TE LE DEMANDE dès que l'utilisateur exprime "
        "une préférence, une décision, un fait biographique, une config technique, "
        "ou une contrainte durable. Confirme en une ligne discrète."
    ),
    inputSchema={
        "type": "object",
        "properties": {
            "content": {"type": "string"},
            "category": {"type": "string"},
            "tags": {"type": "array", "items": {"type": "string"}}
        },
        "required": ["content"]
    }
)
```

资料来源：[memoraeu_mcp/main.py:60-80]()

## Data Processing Pipeline

### Memory Storage Flow

```mermaid
graph LR
    A[Content Input] --> B[Compression<br/>via Mistral]
    B --> C[Category Suggestion<br/>via Mistral]
    C --> D[Embedding Generation<br/>via Mistral]
    D --> E{Duplicate Check<br/>Similarity ≥ 0.94?}
    E -->|Similar Found| F[Skip or Warn]
    E -->|No Duplicate| G[AES-256-GCM Encryption]
    G --> H[API POST /memories]
    H --> I[Return Memory ID]
```

### Pre-Processing Steps (Before Encryption)

The system performs several operations on plaintext before encryption: 资料来源：[memoraeu_mcp/main.py:140-180]()

| Step | Description | Purpose |
|------|-------------|---------|
| 1. Compression | Summarizes text via Mistral if > 500 chars | Token optimization |
| 2. Categorization | Suggests category using existing categories | Organization |
| 3. Embedding | Generates vector via Mistral Embed | Semantic search |
| 4. Deduplication | Checks vector similarity | Avoid storage bloat |

### Local Processing Functions

```python
async def compress_locally(content: str) -> str:
    """Compression en clair (avant chiffrement)."""
    if len(content) <= COMPRESSION_THRESHOLD:
        return content
    prompt = (
        "Résume ce texte en 1-3 phrases concises, en français, en gardant l'essentiel. "
        "Réponds uniquement avec le résumé, sans introduction ni conclusion.\n\n"
        f"{content}"
    )
    compressed = await _mistral_chat(prompt)
    if compressed and len(compressed) < len(content):
        return compressed
    return content
```

资料来源：[memoraeu_mcp/main.py:145-160]()

```python
async def suggest_category_locally(content: str, existing: list[str]) -> str:
    """Suggère une catégorie pour le contenu en clair."""
    existing_str = ", ".join(existing) if existing else "aucune"
    prompt = (
        f"Catégories existantes : {existing_str}\n\n"
        f"Texte : {content[:500]}\n\n"
        "Quelle catégorie courte (1-2 mots, en français, minuscules) correspond le mieux ? "
        "Utilise une existante si pertinent, sinon crée-en une. Réponds uniquement avec la catégorie."
    )
    cat = await _mistral_chat(prompt)
    if cat:
        return cat.lower().strip().strip('"').strip("'")[:30]
    return "personnel"
```

资料来源：[memoraeu_mcp/main.py:162-175]()

## Deduplication & Compression

### Similarity Thresholds

Before storing a memory, the MCP checks for near-duplicates using vector similarity:

| Similarity Score | Action |
|------------------|--------|
| ≥ 94% | Memory ignored — exact duplicate |
| < 94% | Memory stored (with warning logged) |

资料来源：[README.md:70-76]()

### Duplicate Detection Implementation

```python
async def check_duplicate(embedding: list[float]) -> dict | None:
    """
    Recherche une mémoire similaire via le vecteur pré-calculé (zero-knowledge).
    Retourne la mémoire existante si similarité ≥ seuil, sinon None.
    """
    # Implementation checks against stored embeddings
    # Returns duplicate info if similarity threshold met
```

资料来源：[memoraeu_mcp/main.py:177-185]()

## Structured Facts System

For temporal data that changes over time, the system provides structured fact management:

### Fact Data Model

```python
{
    "id": "uuid-string",
    "subject": "User/Entity name",
    "predicate": "property-name",
    "object": "encrypted-value",
    "valid_from": "YYYY-MM-DD",
    "valid_to": "YYYY-MM-DD | null",
    "scope": "private | org",
    "supersedes": "previous-fact-id | null"
}
```

### Temporal Validity

Facts support time-bound validity:

- `valid_from`: Start date (defaults to today)
- `valid_to`: End date (null means currently active)
- When a new fact replaces an old one, `supersedes` links them
- `recall_facts` with `history=False` returns only active facts

资料来源：[server.py:35-55]()

## Resource Injection

The MCP server exposes a resource endpoint for automatic context loading:

```python
@app.list_resources()
async def list_resources() -> list[Resource]:
    return [
        Resource(
            uri="memoraeu://context",
            name="Contexte mémoire MemoraEU",
            description="Mémoires récentes injectées automatiquement en début de session",
            mimeType="text/plain"
        )
    ]

@app.read_resource()
async def read_resource(uri: str) -> list[ResourceContents]:
    if uri == "memoraeu://context":
        context = await load_session_context()
        text = context if context else "Aucune mémoire enregistrée."
        return [TextResourceContents(uri=uri, mimeType="text/plain", text=text)]
```

资料来源：[memoraeu_mcp/main.py:90-105]()

## Session Context Loading

```python
async def load_session_context() -> str:
    """Charge le contexte de session depuis l'API."""
    try:
        memories = await api_get("/memories", params={"limit": 10, "scope": "private"})
        if not memories:
            return ""
        lines = []
        for m in memories:
            content = decrypt_content(m["content"])
            preview = content[:100] + ("…" if len(content) > 100 else "")
            lines.append(f"[{m.get('category') or '—'}] {preview}")
        return "\n".join(lines)
    except Exception:
        return ""
```

## Recall Flow Implementation

```python
@app.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
    if name == "recall":
        global _first_recall
        is_first = _first_recall
        _first_recall = False

        # Load session context on first recall
        context = await load_session_context()

        response = await api_post("/memories/search", {
            "query": arguments["query"],
            "limit": arguments.get("limit", 3),
            "category": arguments.get("category"),
            "scope": "private"
        })
        results = response.get("results", [])

        lines = []

        # Inject system prompt only on first recall
        if is_first:
            lines.append(SYSTEM_PROMPT_TEXT)
            lines.append("---")
        # ... format results
```

资料来源：[memoraeu_mcp/main.py:220-250]()

## Zero-Knowledge Architecture

```mermaid
graph TD
    subgraph Client["Client (MCP)"]
        A[Plaintext Content] --> B[Mistral Embedding]
        A --> C[Compression]
        A --> D[Categorization]
        B --> E[Duplicate Check]
        C --> F[AES-256-GCM Encryption]
        D --> F
        E -->|No Duplicate| F
    end
    
    subgraph Server["MemoraEU Server"]
        G[Encrypted Payload] --> H[Store]
        H --> I[Semantic Search]
        G --> I
    end
    
    F --> G
    I --> J[Return Encrypted Results]
    J --> K[Client Decrypts]
```

### Encryption Specification

| Parameter | Value |
|-----------|-------|
| Algorithm | AES-256-GCM |
| Key Derivation | PBKDF2-HMAC-SHA256 |
| Iterations | 210,000 (OWASP 2024) |
| Ciphertext Prefix | `ENCv1:` |
| Salt | Per-account, from dashboard |

## Configuration Variables

| Variable | Purpose | Required |
|----------|---------|----------|
| `MEMORAEU_API_KEY` | HTTP Bearer authentication | Yes |
| `MEMORAEU_SECRET` | User password for key derivation | Yes |
| `MEMORAEU_SALT` | KDF salt from dashboard | Yes |
| `MEMORAEU_API_URL` | API endpoint (default: `https://api.memoraeu.com`) | Yes |
| `MISTRAL_API_KEY` | Embedding generation | Yes |

资料来源：[README.md:95-115]()

## Dependencies

| Package | Version | Purpose |
|---------|---------|---------|
| `mcp` | ≥1.1.0, <1.2.0 | MCP protocol implementation |
| `httpx` | 0.28.1 | HTTP client |
| `python-dotenv` | 1.0.1 | Environment configuration |
| `starlette` | ≥0.40.0, <0.42.0 | Web framework |
| `cryptography` | ≥42.0.0 | AES encryption |

资料来源：[requirements.txt:1-5]()

## Version History

| Version | Date | Changes |
|---------|------|---------|
| 0.1.9 | 2026-05-12 | Added `remember_fact`, `recall_facts`, `invalidate_fact`; PBKDF2 210k iterations |
| 0.1.5 | 2026-04-28 | Added `ENCv1:` prefix; deduplication threshold refinement |

资料来源：[CHANGELOG.md:1-30]()

---

<a id='page-deduplication'></a>

## Deduplication and Compression

### 相关页面

相关主题：[Auto-Memory System](#page-auto-memory), [Security and Encryption](#page-security-encryption)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [memoraeu_mcp/main.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)
- [server.py](https://github.com/pquattro/memoraeu-mcp/blob/main/server.py)
- [CHANGELOG.md](https://github.com/pquattro/memoraeu-mcp/blob/main/CHANGELOG.md)
- [README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)
- [requirements.txt](https://github.com/pquattro/memoraeu-mcp/blob/main/requirements.txt)
</details>

# Deduplication and Compression

The MemoraEU MCP server implements intelligent data optimization through two complementary mechanisms: **compression** and **deduplication**. These features operate on plaintext data locally before encryption, ensuring that only processed, non-redundant information is transmitted to the server.

## Overview

MemoraEU's optimization pipeline runs entirely on the client side before any data leaves the user's machine. This approach provides several benefits:

- **Token efficiency**: Reduced payload sizes minimize API costs and response times
- **Bandwidth optimization**: Less data transmitted over the network
- **Storage savings**: Server-side storage requirements are reduced
- **Zero-knowledge preservation**: Compression and deduplication occur before encryption, maintaining the security model

## Compression System

### Purpose and Scope

The compression system applies text summarization to memory content that exceeds a configurable length threshold. Unlike generic compression algorithms, this system uses LLM-based summarization to distill essential information into concise, human-readable summaries.

**资料来源：** [memoraeu_mcp/main.py:1-200](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

### Compression Threshold

| Parameter | Description | Default Value |
|-----------|-------------|---------------|
| `COMPRESSION_THRESHOLD` | Minimum content length to trigger compression | Configurable in source |

The compression logic follows a decision tree:

```mermaid
graph TD
    A[New Memory Content] --> B{Content Length > Threshold?}
    B -->|No| C[Return Original Content]
    B -->|Yes| D[Call Mistral Chat API]
    D --> E{Summary Shorter Than Original?}
    E -->|Yes| F[Return Compressed Summary]
    E -->|No| C
```

**资料来源：** [memoraeu_mcp/main.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

### The `compress_locally` Function

The compression function `compress_locally()` implements the following workflow:

1. **Threshold Check**: Only processes content exceeding `COMPRESSION_THRESHOLD` characters
2. **Prompt Engineering**: Sends the content to Mistral Chat with a French-language summarization prompt
3. **Validation**: Accepts the summary only if it's shorter than the original
4. **Fallback**: Returns original content if compression doesn't yield improvement

```python
async def compress_locally(content: str) -> str:
    """Compress content locally before encryption."""
    if len(content) <= COMPRESSION_THRESHOLD:
        return content
    prompt = (
        "Résume ce texte en 1-3 phrases concises, en français, en gardant l'essentiel. "
        "Réponds uniquement avec le résumé, sans introduction ni conclusion.\n\n"
        f"{content}"
    )
    compressed = await _mistral_chat(prompt)
    if compressed and len(compressed) < len(content):
        print(f"[mcp] Compression: {len(content)} → {len(compressed)} chars", file=sys.stderr)
        return compressed
    return content
```

**资料来源：** [memoraeu_mcp/main.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

### Integration with `remember` Tool

Compression is automatically applied during the `remember` tool execution:

```mermaid
sequenceDiagram
    participant User
    participant MCP as MCP Server
    participant Mistral as Mistral API
    
    User->>MCP: remember(content)
    MCP->>MCP: compress_locally(content)
    MCP->>Mistral: Summarization Request
    Mistral-->>MCP: Compressed Summary
    MCP->>MCP: encrypt_content()
    MCP->>MCP: api_post("/memories")
```

**资料来源：** [memoraeu_mcp/main.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py) and [server.py](https://github.com/pquattro/memoraeu-mcp/blob/main/server.py)

## Deduplication System

### Purpose and Scope

The deduplication system prevents storing near-identical memories by comparing content embeddings before storage. This feature uses vector similarity to detect duplicates while maintaining zero-knowledge guarantees.

**资料来源：** [README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md) and [CHANGELOG.md](https://github.com/pquattro/memoraeu-mcp/blob/main/CHANGELOG.md)

### Similarity Thresholds

| Similarity Score | Action |
|------------------|--------|
| ≥ 94% (0.94) | Memory ignored — exact duplicate |
| < 94% | Memory stored with warning logged |

**资料来源：** [README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

### The `check_duplicate` Function

The `check_duplicate()` function searches for similar memories using pre-computed vector embeddings:

```python
async def check_duplicate(embedding: list[float]) -> dict | None:
    """
    Recherche une mémoire similaire via le vecteur pré-calculé (zero-knowledge).
    Retourne la mémoire la plus similaire si le seuil est dépassé.
    """
```

**资料来源：** [memoraeu_mcp/main.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

### Zero-Knowledge Embedding Model

Embeddings are computed from plaintext content locally using the Mistral Embed API before any encryption occurs. This ensures the server never receives unencrypted content or embeddings derived from it.

```mermaid
graph LR
    A[Plaintext Content] -->|Before Encryption| B[Mistral Embed API]
    B --> C[Embedding Vector]
    C --> D[check_duplicate]
    A -->|After Encryption| E[Encrypted Content]
    E --> F[Server Storage]
    
    style B fill:#90EE90
    style D fill:#FFE4B5
```

**资料来源：** [CHANGELOG.md](https://github.com/pquattro/memoraeu-mcp/blob/main/CHANGELOG.md) and [memoraeu_mcp/main.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

### Deduplication Workflow

```mermaid
graph TD
    A[New Memory] --> B[Generate Embedding]
    B --> C[Call check_duplicate]
    C --> D{Similar Memory Found?}
    D -->|No| E[Store Memory Normally]
    D -->|Yes| F{Score >= 94%?}
    F -->|Yes| G[Skip - Show Duplicate Warning]
    F -->|No| H[Log Warning - Store Anyway]
    
    G --> I[Display Existing Memory ID]
    H --> E
```

**资料来源：** [memoraeu_mcp/main.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py) and [server.py](https://github.com/pquattro/memoraeu-mcp/blob/main/server.py)

### Duplicate Detection Response

When a duplicate is detected, the system returns a formatted warning message:

```
⚠️ Doublon détecté (95% similaire) — mémoire non créée.
→ Existante : [memory preview] (ID: abc12345...)
```

**资料来源：** [server.py](https://github.com/pquattro/memoraeu-mcp/blob/main/server.py)

## Processing Pipeline

The complete optimization pipeline executes in the following order during the `remember` operation:

```mermaid
flowchart LR
    subgraph Phase1["Phase 1: Pre-Encryption Processing"]
        A1[Raw Content] --> B1[Compression<br/>compress_locally]
        B1 --> C1[Categorization<br/>suggest_category_locally]
        C1 --> D1[Embedding<br/>embed_locally]
    end
    
    subgraph Phase2["Phase 2: Deduplication Check"]
        D1 --> E1[check_duplicate]
        E1 --> F1{Skip?}
    end
    
    subgraph Phase3["Phase 3: Encryption & Storage"]
        F1 -->|No| G1[encrypt_content]
        G1 --> H1[api_post /memories]
    end
    
    F1 -->|Yes| I1[Return Duplicate Warning]
```

**资料来源：** [memoraeu_mcp/main.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

## Dependencies

The optimization features depend on the following packages:

| Package | Version | Purpose |
|---------|---------|---------|
| `httpx` | 0.28.1 | Async HTTP client for Mistral API calls |
| `starlette` | ≥0.40.0,<0.42.0 | Web framework components |
| `cryptography` | ≥42.0.0 | Encryption primitives |
| `python-dotenv` | 1.0.1 | Environment variable management |

**资料来源：** [requirements.txt](https://github.com/pquattro/memoraeu-mcp/blob/main/requirements.txt)

## Configuration Variables

The system uses environment variables for Mistral API integration:

| Variable | Purpose | Required |
|----------|---------|----------|
| `MISTRAL_API_KEY` | Authentication for Mistral Embed and Chat APIs | Yes (for stdio install) |
| `MEMORAEU_API_KEY` | MemoraEU API authentication | Yes |
| `MEMORAEU_SECRET` | Password for key derivation | Yes (stdio) |
| `MEMORAEU_SALT` | KDF salt for encryption | Yes (stdio) |

**资料来源：** [README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Version History

| Version | Date | Changes |
|---------|------|---------|
| 0.1.9 | 2026-05-12 | PBKDF2 updated to 210,000 iterations, `ENCv1:` prefix added |
| 0.1.5 | 2026-04-28 | PBKDF2 updated to 210k iterations, refactoring |
| Initial | — | Near-duplicate detection with 0.94 threshold |

**资料来源：** [CHANGELOG.md](https://github.com/pquattro/memoraeu-mcp/blob/main/CHANGELOG.md)

## Security Considerations

### Zero-Knowledge Guarantee

The optimization pipeline preserves zero-knowledge encryption by:

1. **Embedding before encryption**: Vector embeddings are computed from plaintext locally
2. **Compression before encryption**: Summarization occurs on plaintext content
3. **Local-only processing**: All LLM calls (Mistral) happen client-side
4. **Server receives encrypted data**: Only encrypted content and pre-computed embeddings travel to the server

### Limitations

- Compression quality depends on Mistral model's summarization capabilities
- Deduplication threshold (94%) is fixed and not configurable at runtime
- Similarity search requires pre-computed embeddings, which must be generated during initial storage

---

<a id='page-structured-facts'></a>

## Structured Facts System

### 相关页面

相关主题：[MCP Tools Reference](#page-mcp-tools), [Auto-Memory System](#page-auto-memory)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [memoraeu_mcp/main.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)
- [CHANGELOG.md](https://github.com/pquattro/memoraeu-mcp/blob/main/CHANGELOG.md)
- [README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)
- [requirements.txt](https://github.com/pquattro/memoraeu-mcp/blob/main/requirements.txt)
</details>

# Structured Facts System

The Structured Facts System is a feature within the MemoraEU MCP server that provides persistent, temporally-validated knowledge storage. Unlike free-form memories, structured facts use a subject-predicate-object (SPO) pattern commonly found in knowledge graphs, enabling precise entity state tracking with automatic validity periods.

## Overview

Traditional memory tools store unstructured text that must be parsed semantically. The Structured Facts System introduces typed, queryable assertions about entities with built-in temporal semantics:

- **Subject**: The entity being described (e.g., "Project Alpha")
- **Predicate**: The property or relation (e.g., "status", "manager")
- **Object**: The value or target (e.g., "active", "John Doe")
- **Validity Period**: Time-bounded truth (from/to dates)

资料来源：[CHANGELOG.md:12-14]()

```mermaid
graph TD
    subgraph "Structured Facts Architecture"
        A[User Query] --> B[recall_facts]
        B --> C[API GET /facts]
        D[New Fact] --> E[remember_fact]
        E --> F[Client Encryption]
        F --> G[API POST /facts]
        G --> H[(Encrypted Storage)]
        C --> I[Decrypt & Filter]
        I --> J[Active Facts Only]
        K[Expired Fact] --> L[invalidate_fact]
        L --> M[API PUT /facts/:id]
    end
```

## Data Model

Each structured fact follows this schema:

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | UUID | Auto | Unique fact identifier |
| `subject` | string | Yes | Entity being described |
| `predicate` | string | Yes | Property or relation name |
| `object` | string | Yes | Encrypted value (E2E) |
| `scope` | enum | No | `private` (default) or `org` |
| `valid_from` | date | Auto | When fact became true |
| `valid_to` | date | No | When fact ceased to be true |
| `supersedes` | UUID | Auto | Previous fact ID this replaces |

资料来源：[memoraeu_mcp/main.py:60-75]()

### Fact Validity States

```mermaid
stateDiagram-v2
    [*] --> Active: valid_from <= today
    Active --> Expired: invalidate_fact called
    Active --> Superseded: remember_fact same subject+predicate
    Expired --> [*]
    Superseded --> [*]
    
    state Active {
        [*] --> Current
    }
```

## MCP Tools

### remember_fact

Stores a structured fact with automatic encryption and temporal tracking.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `subject` | string | Yes | Entity name |
| `predicate` | string | Yes | Property name |
| `object` | string | Yes | Value (encrypted before storage) |
| `scope` | string | No | `private` or `org` (default: `private`) |
| `valid_from` | string | No | Start date YYYY-MM-DD |

**Response Format:**
```
✅ Fait mémorisé 🔒 (remplace {id}…)
  {subject} → {predicate}
  Depuis: {valid_from} | ID: {id}…
```

**Key Behaviors:**

1. **Encryption**: `object` value is encrypted client-side before transmission
2. **Auto-supersession**: If a fact with the same `subject` + `predicate` exists, the new fact automatically replaces it (old one marked invalid via `supersedes` field)
3. **Timestamp**: `valid_from` defaults to today if not specified

资料来源：[memoraeu_mcp/main.py:76-106]()

### recall_facts

Retrieves active facts for a specific subject entity.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `subject` | string | Yes | Entity to query |
| `predicate` | string | No | Filter by specific property |
| `scope` | string | No | `private` or `org` (default: `private`) |
| `history` | boolean | No | Include expired facts (default: false) |

**Response Format:**
```
📊 {count} fait(s) pour '{subject}' :

• {predicate}: {decrypted_value}
  [{valid_from} → {valid_to}] | ID: {id}…
```

资料来源：[memoraeu_mcp/main.py:107-136]()

### invalidate_fact

Marks a fact as expired, indicating the information is no longer true.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `fact_id` | string | Yes | UUID of fact to expire |
| `valid_to` | string | No | End date YYYY-MM-DD (default: today) |

**Behavior:**
- Sets `valid_to` to specified date or current date
- Expired facts are excluded from default `recall_facts` queries
- Use `history=true` in `recall_facts` to see expired facts

资料来源：[memoraeu_mcp/main.py:137-152]()

## Workflows

### Creating a New Fact

```mermaid
sequenceDiagram
    participant U as User/Claude
    participant M as MCP Server
    participant C as Crypto Layer
    participant A as MemoraEU API
    
    U->>M: remember_fact(subject, predicate, object)
    M->>C: encrypt_content(object)
    C-->>M: encrypted_blob
    M->>M: Check for existing fact (same subject+predicate)
    M->>A: POST /facts {subject, predicate, encrypted_blob, scope}
    A->>A: Set valid_from=today
    A->>A: Mark old fact as superseded
    A-->>M: {id, supersedes, valid_from}
    M-->>U: Confirmation with ID
```

### Querying Facts

```mermaid
sequenceDiagram
    participant U as User/Claude
    participant M as MCP Server
    participant A as MemoraEU API
    participant C as Crypto Layer
    
    U->>M: recall_facts(subject, history=false)
    M->>A: GET /facts?subject={subject}
    A-->>M: [facts with valid_to=null]
    M->>C: decrypt_content(facts[].object)
    C-->>M: decrypted_values
    M-->>U: Active facts only
```

## Security Model

All structured facts leverage the same zero-knowledge encryption as regular memories:

| Layer | Implementation |
|-------|----------------|
| Key Derivation | PBKDF2-HMAC-SHA256, 210,000 iterations (OWASP 2024) |
| Symmetric Cipher | AES-256-GCM |
| Ciphertext Format | `ENCv1:{base64_ciphertext}` |

资料来源：[CHANGELOG.md:18-19]()

**Encryption Flow for Facts:**

1. `object` value encrypted client-side before API transmission
2. `subject` and `predicate` transmitted in plaintext (used for routing/indexing)
3. Server never sees decrypted values

```python
# From memoraeu_mcp/main.py:78-79
encrypted_object = encrypt_content(arguments["object"])
payload = {
    "subject": arguments["subject"],
    "predicate": arguments["predicate"],
    "object": encrypted_object,
    ...
}
```

## Use Cases

### Preference Tracking

```
remember_fact(subject="Alice", predicate="preferred_language", object="French")
```

### Status Changes

```
remember_fact(subject="Project X", predicate="status", object="completed", valid_from="2024-01-15")
```

### Configuration State

```
remember_fact(subject="dev-environment", predicate="python_version", object="3.12.1")
```

### Relationship Management

```
remember_fact(subject="Team Alpha", predicate="lead", object="bob@example.com")
```

## Comparison with Regular Memories

| Aspect | Regular Memory | Structured Facts |
|--------|----------------|-------------------|
| Content | Free-form text | Subject-predicate-object |
| Query | Semantic search | Entity-based retrieval |
| Deduplication | Vector similarity ≥94% | Auto-supersession by predicate |
| Temporal | Implicit | Explicit valid_from/valid_to |
| Use Case | Context, preferences, notes | Entity state, relationships |

资料来源：[README.md:34-45]()

## Configuration

Structured Facts require no additional configuration beyond the base MCP server setup:

| Variable | Purpose | Required |
|----------|---------|----------|
| `MEMORAEU_API_KEY` | Bearer token authentication | Yes |
| `MEMORAEU_SECRET` | Password for PBKDF2 key derivation | Yes (for encryption) |
| `MEMORAEU_SALT` | KDF salt from server | Yes (for encryption) |
| `MEMORAEU_API_URL` | API endpoint | Yes |
| `MISTRAL_API_KEY` | Embedding generation | Yes (stdio mode) |

资料来源：[README.md:60-74]()

## Implementation Notes

### Duplicate Detection Strategy

Unlike regular memories which use vector similarity thresholds, structured facts handle duplicates through **predicate-based supersession**:

```
Same subject + Same predicate = Automatic supersession
Same subject + Different predicate = Distinct facts (no conflict)
```

### API Endpoints Used

| Tool | Endpoint | Method |
|------|----------|--------|
| `remember_fact` | `/facts` | POST |
| `recall_facts` | `/facts` | GET |
| `invalidate_fact` | `/facts/{id}` | PUT |

### Response Formatting

The system uses emoji indicators in responses:
- 🔒 — Indicates content is encrypted
- 📝 — Indicates content is unencrypted (no key configured)
- 📊 — Prefixed fact list headers

资料来源：[memoraeu_mcp/main.py:93-98]()

## Version History

| Version | Date | Changes |
|---------|------|---------|
| 0.1.9 | 2026-05-12 | Initial structured facts release: `remember_fact`, `recall_facts`, `invalidate_fact` |

资料来源：[CHANGELOG.md:10-15]()

---

<a id='page-mcp-tools'></a>

## MCP Tools Reference

### 相关页面

相关主题：[Auto-Memory System](#page-auto-memory), [Structured Facts System](#page-structured-facts)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [memoraeu_mcp/main.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)
- [memoraeu_mcp/server.py](https://github.com/pquattro/memoraeu-mcp/blob/main/moraeu_mcp/server.py)
- [requirements.txt](https://github.com/pquattro/memoraeu-mcp/blob/main/requirements.txt)
- [README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)
- [CHANGELOG.md](https://github.com/pquattro/memoraeu-mcp/blob/main/CHANGELOG.md)
</details>

# MCP Tools Reference

## Overview

The `memoraeu-mcp` project exposes a comprehensive set of MCP (Model Context Protocol) tools that enable AI assistants to persistently store, retrieve, and manage semantic memories. The MCP server acts as a bridge between the AI client and the MemoraEU cloud API, providing zero-knowledge encrypted storage with local pre-processing capabilities.

**资料来源：** [requirements.txt:1]()

**Key Capabilities:**

- Semantic memory storage with automatic categorization
- Structured fact management with temporal validity
- Client-side encryption using AES-256-GCM
- Near-duplicate detection before storage
- Automatic context injection on session start

**资料来源：** [README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

---

## Architecture

### System Components

```mermaid
graph TD
    A["Claude Desktop / AI Client"] -->|MCP Protocol| B["memoraeu-mcp Server"]
    B -->|API Calls| C["MemoraEU Cloud API"]
    
    B --> D["Local Pre-processing"]
    D --> E["Mistral API<br/>(Embeddings + Categorization)"]
    
    B --> F["Encryption Layer<br/>(PBKDF2 + AES-256-GCM)"]
    F --> C
    
    style E fill:#f9f,stroke:#333
    style F fill:#ff9,stroke:#333
```

### Memory Storage Flow

```mermaid
sequenceDiagram
    participant Client as AI Client
    participant MCP as memoraeu-mcp
    participant Mistral as Mistral API
    participant Crypto as Encryption Layer
    participant API as MemoraEU API
    
    Client->>MCP: remember(content, category?)
    MCP->>Mistral: compress_locally(content)
    Mistral-->>MCP: compressed_content
    MCP->>Mistral: suggest_category(content, existing)
    Mistral-->>MCP: category
    MCP->>Mistral: generate_embedding(content)
    Mistral-->>MCP: embedding
    MCP->>MCP: check_duplicates(embedding)
    MCP->>Crypto: encrypt(compressed_content)
    Crypto-->>MCP: encrypted_blob
    MCP->>API: POST /memories<br/>(encrypted + embedding)
    API-->>MCP: memory_id
    MCP-->>Client: ✅ Memorized
```

**资料来源：** [memoraeu_mcp/main.py:60-100](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

---

## Core Memory Tools

### `remember`

Stores a memory with automatic compression, categorization, and duplicate detection.

**Tool Definition:**

```json
{
  "name": "remember",
  "inputSchema": {
    "type": "object",
    "properties": {
      "content": {"type": "string"},
      "category": {"type": "string"},
      "tags": {"type": "array", "items": {"type": "string"}}
    },
    "required": ["content"]
  }
}
```

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `content` | string | Yes | The memory content to store |
| `category` | string | No | Category name; auto-suggested if omitted |
| `tags` | array[string] | No | Custom tags for the memory |

**Workflow:**

1. Compress content locally via Mistral API
2. Suggest or use provided category
3. Generate embedding from plaintext (before encryption)
4. Check for near-duplicates using vector similarity (threshold: 0.94)
5. Encrypt content with AES-256-GCM
6. Send to `/memories` endpoint with `pre_processed: true`

**Duplicate Detection Behavior:**

| Similarity Score | Action |
|------------------|--------|
| ≥ 94% | Skip storage, return existing memory ID |
| < 94% | Store anyway with warning logged |

**资料来源：** [memoraeu_mcp/main.py:90-130](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

**Response Format:**

```
✅ Memorized 🔒 (ID: abc12345…, catégorie: preferences)
```

The 🔒 lock icon indicates encryption is active (key available).

---

### `recall`

Performs semantic search across stored memories.

**Tool Definition:**

```json
{
  "name": "recall",
  "inputSchema": {
    "type": "object",
    "properties": {
      "query": {"type": "string"},
      "limit": {"type": "integer", "default": 3},
      "category": {"type": "string"}
    },
    "required": ["query"]
  }
}
```

**Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `query` | string | Yes | — | Semantic search query |
| `limit` | integer | No | 3 | Maximum results to return |
| `category` | string | No | — | Filter by category |

**Auto-Recall Behavior:**

The MCP server is designed to automatically invoke `recall` on the first user message of each session using the detected topic as the query. This behavior is encoded in the tool description and reinforced via system prompt injection.

**资料来源：** [README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

**Special Behavior on First Recall:**

1. Loads session context from `memoraeu://context` resource
2. Injects the full system prompt into Claude's context
3. Returns results merged with existing context

---

### `forget`

Deletes a memory by its ID.

**Tool Definition:**

```json
{
  "name": "forget",
  "inputSchema": {
    "type": "object",
    "properties": {
      "memory_id": {"type": "string"}
    },
    "required": ["memory_id"]
  }
}
```

**Response:**

```
🗑️ Supprimée.
```

Or `Introuvable.` if the memory does not exist.

**资料来源：** [memoraeu_mcp/main.py:145-150](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

---

### `list_memories`

Lists recent memories with optional category filtering.

**Tool Definition:**

```json
{
  "name": "list_memories",
  "inputSchema": {
    "type": "object",
    "properties": {
      "category": {"type": "string"},
      "limit": {"type": "integer", "default": 20}
    }
  }
}
```

**Response Format:**

```
📋 5 mémoire(s) :

• [preferences] User prefers dark mode... (ID: abc12345…)
• [config] Python 3.11 installed... (ID: def67890…)
```

---

### `list_categories`

Returns existing categories sorted by usage frequency.

**Tool Definition:**

```json
{
  "name": "list_categories",
  "inputSchema": {"type": "object", "properties": {}}
}
```

**Response Format:**

```
📂 Catégories :

• preferences (42 usages)
• config (18 usages)
• projects (7 usages)
```

**资料来源：** [memoraeu_mcp/main.py:160-175](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

---

## Structured Fact Tools

### `remember_fact`

Stores a structured fact with subject/predicate/object pattern and temporal validity.

**Tool Definition:**

```json
{
  "name": "remember_fact",
  "inputSchema": {
    "type": "object",
    "properties": {
      "subject": {"type": "string"},
      "predicate": {"type": "string"},
      "object": {"type": "string"},
      "valid_from": {"type": "string"},
      "valid_to": {"type": "string"},
      "scope": {"type": "string", "enum": ["private", "org"], "default": "private"}
    },
    "required": ["subject", "predicate", "object"]
  }
}
```

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `subject` | string | Yes | Entity being described |
| `predicate` | string | Yes | Property/relationship name |
| `object` | string | Yes | Value of the property |
| `valid_from` | string | No | Start date (YYYY-MM-DD) |
| `valid_to` | string | No | End date (YYYY-MM-DD) |
| `scope` | string | No | `private` (default) or `org` |

**Key Features:**

- **Auto-invalidation**: Automatically invalidates previous fact with same subject+predicate
- **Temporal validity**: Supports date ranges for time-sensitive facts
- **Encryption**: Object value is encrypted before transmission

**Response Format:**

```
✅ Fait mémorisé 🔒
  User → prefers_color
  Depuis: 2026-01-15 | ID: abc12345…
```

Or if superseded:

```
✅ Fait mémorisé 🔒 (remplace abc12345…)
  User → prefers_color
  Depuis: 2026-01-20 | ID: def67890…
```

**资料来源：** [CHANGELOG.md](https://github.com/pquattro/memoraeu-mcp/blob/main/CHANGELOG.md)

---

### `recall_facts`

Retrieves active (non-expired) facts for a given subject.

**Tool Definition:**

```json
{
  "name": "recall_facts",
  "inputSchema": {
    "type": "object",
    "properties": {
      "subject": {"type": "string"},
      "predicate": {"type": "string"},
      "scope": {"type": "string", "enum": ["private", "org"], "default": "private"},
      "history": {"type": "boolean", "default": False}
    },
    "required": ["subject"]
  }
}
```

**Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `subject` | string | Yes | — | Entity to query |
| `predicate` | string | No | — | Filter by specific property |
| `scope` | string | No | private | `private` or `org` |
| `history` | boolean | No | false | Include expired facts |

**Response Format:**

```
📊 2 fait(s) pour 'User' :

• prefers_color: blue
  [2026-01-15 → aujourd'hui] | ID: abc12345…

• works_at: Acme Corp
  [2025-03-01 → 2026-02-28 (expiré)] | ID: def67890…
```

**资料来源：** [memoraeu_mcp/main.py:180-210](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

---

### `invalidate_fact`

Marks a fact as expired, indicating it is no longer true.

**Tool Definition:**

```json
{
  "name": "invalidate_fact",
  "inputSchema": {
    "type": "object",
    "properties": {
      "fact_id": {"type": "string"},
      "valid_to": {"type": "string"}
    },
    "required": ["fact_id"]
  }
}
```

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `fact_id` | string | Yes | ID of fact to invalidate |
| `valid_to` | string | No | End date (default: today) |

**资料来源：** [memoraeu_mcp/main.py:212-220](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

---

## MCP Resources

### `memoraeu://context`

A read-only resource that provides session context with recent memories.

**Resource Definition:**

```python
Resource(
    uri="memoraeu://context",
    name="Contexte mémoire MemoraEU",
    description="Mémoires récentes injectées automatiquement en début de session",
    mimeType="text/plain"
)
```

**Usage in Tool Calls:**

On the first `recall` invocation, the MCP server automatically:

1. Reads from `memoraeu://context` resource
2. Injects session context into the response
3. Loads relevant memories via `/memories/recent` endpoint

**资料来源：** [memoraeu_mcp/main.py:45-60](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

---

## MCP Prompts

### `memoraeu_system`

A system prompt that reinforces automatic memory behavior rules for Claude.

**Prompt Content:**

```
## Rôle
Tu es un assistant qui mémorise automatiquement les informations importantes pour l'utilisateur.

## Ce qu'il faut retenir
- Préférences et choix de l'utilisateur
- Décisions prises au cours de la conversation
- Faits biographiques ou informations récurrentes ou contraintes durables
- Informations techniques propres à l'utilisateur (stack, config, credentials non-sensibles)

## Rappel automatique
Dès le premier message de l'utilisateur, utilise `recall` avec le sujet détecté comme query.
N'attends pas qu'on te le demande — c'est automatique.

## Règles
- Ne mémorise pas les informations générales ou éphémères (météo du jour, blagues, calculs ponctuels)
- Si l'utilisateur dit "oublie ça" ou "ne retiens pas", utilise `forget`
- Confirme discrètement les mémorisations : une ligne, pas plus
- Optimisation tokens : limite recall à 3 résultats par défaut, mémoires compactes
```

**资料来源：** [memoraeu_mcp/main.py:25-45](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

---

## Security Model

### Zero-Knowledge Architecture

```mermaid
graph LR
    subgraph Client["Client Side (Encrypted)"]
        P["Plaintext"] -->|PBKDF2<br/>100k iterations| K["Key"]
        P -->|AES-256-GCM| E["Encrypted"]
        K --> E
    end
    
    subgraph Server["Server Side"]
        E -->|"ENCv1:..."| DB["Encrypted Blob Storage"]
    end
    
    style P fill:#9f6
    style K fill:#f96
    style DB fill:#99f
```

**Encryption Details:**

| Component | Specification |
|-----------|---------------|
| Key Derivation | PBKDF2-HMAC-SHA256 |
| Iterations | 100,000 (OWASP 2024 recommendation: 210,000) |
| Cipher | AES-256-GCM |
| Ciphertext Format | `ENCv1:<base64_ciphertext>` |
| Salt | Unique per user, stored server-side |

**资料来源：** [CHANGELOG.md](https://github.com/pquattro/memoraeu-mcp/blob/main/CHANGELOG.md)

### Local Pre-processing

To maintain zero-knowledge guarantees, the following operations occur **before** encryption:

1. **Compression** — Content is compressed via Mistral API
2. **Categorization** — Category is suggested using existing categories
3. **Embedding Generation** — Vector embeddings computed from plaintext

Only the **content** is encrypted. Embeddings, categories, and metadata are stored in cleartext for search functionality.

**资料来源：** [README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

---

## API Endpoints

| Endpoint | Method | Tool | Purpose |
|----------|--------|------|---------|
| `/memories` | POST | `remember` | Create encrypted memory |
| `/memories/search` | POST | `recall` | Semantic search |
| `/memories/{id}` | DELETE | `forget` | Delete memory |
| `/memories` | GET | `list_memories` | List recent memories |
| `/memories/categories` | GET | `list_categories` | List categories |
| `/facts` | POST | `remember_fact` | Create structured fact |
| `/facts` | GET | `recall_facts` | Query facts |
| `/facts/{id}` | PUT | `invalidate_fact` | Expire fact |

**资料来源：** [memoraeu_mcp/main.py:130-220](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

---

## Environment Configuration

| Variable | Purpose | Required |
|----------|---------|----------|
| `MEMORAEU_API_URL` | API endpoint | Yes |
| `MEMORAEU_API_KEY` | Bearer token authentication | Yes |
| `MEMORAEU_SECRET` | Password for PBKDF2 key derivation | For local/stdio |
| `MEMORAEU_SALT` | KDF salt (unique per account) | For local/stdio |
| `MISTRAL_API_KEY` | Embedding generation | For local/stdio |

**资料来源：** [README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

---

## Tool Summary Table

| Tool | Category | Auto-Inject | Encryption |
|------|----------|-------------|------------|
| `remember` | Memory | No | Yes |
| `recall` | Memory | Yes (first call) | Decrypted output |
| `forget` | Memory | No | N/A |
| `list_memories` | Memory | No | Decrypted output |
| `list_categories` | Memory | No | No |
| `remember_fact` | Facts | No | Object only |
| `recall_facts` | Facts | No | Decrypted output |
| `invalidate_fact` | Facts | No | N/A |

---

<a id='page-configuration'></a>

## Configuration Reference

### 相关页面

相关主题：[Installation Guide](#page-installation), [Security and Encryption](#page-security-encryption)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)
- [memoraeu_mcp/main.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)
- [server.py](https://github.com/pquattro/memoraeu-mcp/blob/main/server.py)
- [requirements.txt](https://github.com/pquattro/memoraeu-mcp/blob/main/requirements.txt)
- [CHANGELOG.md](https://github.com/pquattro/memoraeu-mcp/blob/main/CHANGELOG.md)
</details>

# Configuration Reference

This page provides comprehensive documentation for configuring the MemoraEU MCP (Model Context Protocol) server. It covers environment variables, MCP client configuration, zero-knowledge encryption setup, and tool-specific parameters.

---

## Overview

The MemoraEU MCP server acts as an intermediary between AI assistants (such as Claude) and the MemoraEU memory API. It enables automatic memory management with end-to-end encryption where the server never sees plaintext content. Configuration involves setting up environment variables for authentication, encryption, and API access, as well as defining the MCP server connection in your AI client's configuration file.

资料来源：[README.md:1-45]()

---

## Environment Variables

### Required Variables

The following environment variables are mandatory for MCP server operation. They are **not interchangeable** and serve distinct purposes in the authentication and encryption pipeline.

| Variable | Purpose | Source |
|----------|---------|--------|
| `MEMORAEU_API_KEY` | HTTP Bearer token sent with every request for API authentication | Dashboard → Settings → API Keys |
| `MEMORAEU_SECRET` | User's MemoraEU login password; used as PBKDF2 input to derive the encryption key locally | Your account password |
| `MEMORAEU_SALT` | KDF salt generated by the server, unique to your account; combined with `MEMORAEU_SECRET` to produce the encryption key | Dashboard → Settings → Encryption Keys |
| `MEMORAEU_API_URL` | API endpoint for the hosted service | Use `https://api.memoraeu.com` |
| `MISTRAL_API_KEY` | Required for generating embeddings locally before encryption; enables zero-knowledge semantic search | [console.mistral.ai](https://console.mistral.ai) |

资料来源：[README.md:60-85]()

### Variable Dependency Graph

```mermaid
graph TD
    A[User Password] --> B[PBKDF2 Key Derivation]
    C[MEMORAEU_SALT] --> B
    B --> D[ AES-256-GCM Encryption]
    
    E[Plaintext Content] --> F[Mistral Embed API]
    F --> G[Embedding Vector]
    G --> D
    D --> H[Encrypted Blob]
    
    I[API Request] --> J[MEMORAEU_API_KEY]
    J --> K[Bearer Header]
    K --> I
```

### Optional Behavior Without `MISTRAL_API_KEY`

If `MISTRAL_API_KEY` is not provided, the MCP server continues to function with degraded semantic search capabilities:

- `remember` and `recall` tools remain operational
- Semantic search falls back to **keyword-based search on the server side**
- Zero-knowledge encryption is **not affected**

资料来源：[README.md:88-92]()

---

## MCP Client Configuration

### stdio Mode (Local Installation)

For full zero-knowledge guarantees, use the stdio transport mode with local installation. Add the following configuration to your `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "memoraeu": {
      "command": "uvx",
      "args": ["memoraeu-mcp"],
      "env": {
        "MEMORAEU_API_URL": "https://api.memoraeu.com",
        "MEMORAEU_API_KEY": "meu-sk-...",
        "MEMORAEU_SECRET": "your-memoraeu-password",
        "MEMORAEU_SALT": "your-kdf-salt",
        "MISTRAL_API_KEY": "your-mistral-key"
      }
    }
  }
}
```

资料来源：[README.md:38-52]()

### SSE Mode (Remote Connection)

For remote connections without local installation, use Server-Sent Events (SSE) transport. This mode works with Claude.ai web, Cursor, Windsurf, or any MCP-compatible remote client.

```json
{
  "mcpServers": {
    "memoraeu": {
      "type": "sse",
      "url": "https://api.memoraeu.com/mcp/sse",
      "headers": {
        "Authorization": "Bearer meu-sk-..."
      }
    }
  }
}
```

资料来源：[README.md:5-14]()

### Security Warning for SSE Mode

> **Note:** In remote SSE mode, content is **not** zero-knowledge encrypted because the server processes plaintext. Use the local `stdio` installation for full zero-knowledge guarantees.

资料来源：[README.md:15-17]()

---

## Zero-Knowledge Encryption Configuration

### Encryption Architecture

The zero-knowledge architecture ensures the server never sees plaintext content. Embeddings are generated locally before encryption:

```mermaid
sequenceDiagram
    participant User as User/AI
    participant MCP as MCP Server
    participant Mistral as Mistral API
    participant Server as MemoraEU API
    participant DB as Encrypted DB

    User->>MCP: Raw memory content
    MCP->>Mistral: Plaintext for embedding
    Mistral-->>MCP: Embedding vector
    MCP->>MCP: AES-256-GCM encryption
    MCP->>Server: Encrypted blob + embedding vector
    Server->>DB: Store opaque data
```

资料来源：[README.md:80-84]()

### PBKDF2 Configuration

The encryption key derivation uses PBKDF2-HMAC-SHA256 with the following parameters:

| Parameter | Value | Source |
|-----------|-------|--------|
| Iterations | 210,000 | CHANGELOG.md:20 |
| Hash Algorithm | SHA256 | CHANGELOG.md:20 |
| Cipher | AES-256-GCM | CHANGELOG.md:4 |
| Ciphertext Prefix | `ENCv1:` | CHANGELOG.md:20 |

资料来源：[CHANGELOG.md:17-21]()

---

## Tool Input Schemas

### Core Memory Tools

#### `remember`

Memorizes important information automatically. The AI assistant should call this tool without being asked when the user expresses preferences, decisions, biographical facts, technical configurations, or durable constraints.

```json
{
  "name": "remember",
  "inputSchema": {
    "type": "object",
    "properties": {
      "content": {"type": "string"},
      "category": {"type": "string"},
      "tags": {"type": "array", "items": {"type": "string"}}
    },
    "required": ["content"]
  }
}
```

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `content` | string | Yes | The memory content to store |
| `category` | string | No | Category for organization; auto-suggested if omitted |
| `tags` | array | No | Array of string tags for filtering |

资料来源：[memoraeu_mcp/main.py:180-200]()

#### `recall`

Semantic search across stored memories. Called automatically on the first user message of each session.

```json
{
  "name": "recall",
  "inputSchema": {
    "type": "object",
    "properties": {
      "query": {"type": "string"},
      "limit": {"type": "integer", "default": 3},
      "category": {"type": "string"}
    },
    "required": ["query"]
  }
}
```

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `query` | string | — | Semantic search query |
| `limit` | integer | 3 | Maximum number of results (token optimization) |
| `category` | string | — | Filter by category name |

资料来源：[memoraeu_mcp/main.py:202-220]()

#### `forget`

Deletes a memory by its ID.

```json
{
  "name": "forget",
  "inputSchema": {
    "type": "object",
    "properties": {
      "memory_id": {"type": "string"}
    },
    "required": ["memory_id"]
  }
}
```

资料来源：[memoraeu_mcp/main.py:222-230]()

#### `list_memories`

Lists recent memories with optional category filter.

```json
{
  "name": "list_memories",
  "inputSchema": {
    "type": "object",
    "properties": {
      "category": {"type": "string"},
      "limit": {"type": "integer", "default": 20}
    }
  }
}
```

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `category` | string | — | Filter by category name |
| `limit` | integer | 20 | Maximum number of results |

资料来源：[memoraeu_mcp/main.py:244-252]()

#### `list_categories`

Returns existing categories sorted by usage frequency.

```json
{
  "name": "list_categories",
  "inputSchema": {
    "type": "object",
    "properties": {}
  }
}
```

资料来源：[memoraeu_mcp/main.py:254-258]()

### Structured Fact Tools

#### `remember_fact`

Stores a structured fact with temporal validity (subject/predicate/object model).

```json
{
  "name": "remember_fact",
  "inputSchema": {
    "type": "object",
    "properties": {
      "subject": {"type": "string"},
      "predicate": {"type": "string"},
      "object": {"type": "string"},
      "scope": {"type": "string", "enum": ["private", "org"]},
      "valid_from": {"type": "string"}
    },
    "required": ["subject", "predicate", "object"]
  }
}
```

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `subject` | string | — | Entity being described |
| `predicate` | string | — | Property or relationship |
| `object` | string | — | Value of the property |
| `scope` | string | "private" | Access scope (private or org) |
| `valid_from` | string | — | Start date in YYYY-MM-DD format |

资料来源：[server.py:60-80]()

#### `recall_facts`

Retrieves active facts for a given subject.

```json
{
  "name": "recall_facts",
  "inputSchema": {
    "type": "object",
    "properties": {
      "subject": {"type": "string"},
      "predicate": {"type": "string"},
      "scope": {"type": "string", "enum": ["private", "org"]},
      "history": {"type": "boolean", "default": false}
    },
    "required": ["subject"]
  }
}
```

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `subject` | string | — | Entity to query |
| `predicate` | string | — | Specific property to retrieve |
| `scope` | string | "private" | Access scope |
| `history` | boolean | false | Include expired facts |

资料来源：[server.py:82-105]()

#### `invalidate_fact`

Marks a fact as expired.

```json
{
  "name": "invalidate_fact",
  "inputSchema": {
    "type": "object",
    "properties": {
      "fact_id": {"type": "string"},
      "valid_to": {"type": "string"}
    },
    "required": ["fact_id"]
  }
}
```

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `fact_id` | string | — | ID of the fact to invalidate |
| `valid_to` | string | today | End date in YYYY-MM-DD format |

资料来源：[server.py:107-120]()

---

## Deduplication Configuration

Before storing a memory, the MCP checks for near-duplicates using vector similarity:

| Similarity Threshold | Action |
|---------------------|--------|
| ≥ 94% | Memory ignored — exact duplicate |
| < 94% | Memory stored as new |

资料来源：[README.md:110-115]()

---

## Dependencies

The following Python packages are required for the MCP server:

| Package | Version | Purpose |
|---------|---------|---------|
| `mcp` | ≥1.1.0, <1.2.0 | Model Context Protocol framework |
| `httpx` | 0.28.1 | HTTP client for API requests |
| `python-dotenv` | 1.0.1 | Environment variable loading |
| `starlette` | ≥0.40.0, <0.42.0 | ASGI framework |
| `cryptography` | ≥42.0.0 | Encryption utilities |

资料来源：[requirements.txt:1-5]()

---

## API Endpoints

The MCP server communicates with the MemoraEU API using the following endpoints:

| Method | Endpoint | Purpose |
|--------|----------|---------|
| `POST` | `/memories/search` | Semantic search for memories |
| `POST` | `/facts` | Store structured facts |
| `GET` | `/facts` | Retrieve facts for a subject |
| `PUT` | `/facts/{id}/invalidate` | Mark fact as expired |
| `GET` | `/memories` | List recent memories |
| `DELETE` | `/memories/{id}` | Delete a memory |
| `GET` | `/memories/categories` | Get existing categories |

资料来源：[memoraeu_mcp/main.py:280-310]()

---

## Quick Setup Checklist

1. Create an account at [app.memoraeu.com](https://app.memoraeu.com)
2. Navigate to **Settings → Encryption Keys** → copy `MEMORAEU_SALT`
3. Set `MEMORAEU_SECRET` to your MemoraEU login password
4. Navigate to **Settings → API Keys** → create a key → copy `MEMORAEU_API_KEY`
5. Obtain a Mistral API key from [console.mistral.ai](https://console.mistral.ai)
6. Add the MCP server configuration to your client's config file
7. Set all five environment variables in your configuration

资料来源：[README.md:93-99]()

---

## Security Considerations

| Concern | Mitigation |
|---------|------------|
| Server sees plaintext | Use local `stdio` mode; SSE sends plaintext |
| API key exposure | Store in environment variables, not in config files |
| Encryption key derivation | PBKDF2 with 210k iterations per OWASP 2024 |
| Near-duplicate leakage | 94% similarity threshold prevents similar content storage |

---

<a id='page-deployment'></a>

## Deployment Guide

### 相关页面

相关主题：[Installation Guide](#page-installation), [Configuration Reference](#page-configuration)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)
- [requirements.txt](https://github.com/pquattro/memoraeu-mcp/blob/main/requirements.txt)
- [CHANGELOG.md](https://github.com/pquattro/memoraeu-mcp/blob/main/CHANGELOG.md)
- [memoraeu_mcp/main.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)
</details>

# Deployment Guide

This guide covers all deployment scenarios for the **memoraeu-mcp** Model Context Protocol server, including local stdio installations for zero-knowledge encryption guarantees and remote SSE connections for quick setup without local dependencies.

## Overview

memoraeu-mcp is an MCP server that enables semantic memory management with client-side AES-256-GCM encryption. The server supports two deployment modes:

| Deployment Mode | Use Case | Encryption | Setup Complexity |
|-----------------|----------|------------|------------------|
| **Local (stdio)** | Full zero-knowledge guarantees | Client-side, server never sees plaintext | Higher |
| **Remote (SSE)** | Quick testing, no install | Server processes plaintext | Minimal |

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Prerequisites

Before deploying, ensure you have:

- **Python 3.10+** with `uvx` or pip access
- **API Keys**: MemoraEU account, Mistral API key for embeddings
- **MCP-compatible client**: Claude Desktop, Cursor, Windsurf, or any MCP client

### Python Dependencies

```text
mcp>=1.1.0,<1.2.0
httpx==0.28.1
python-dotenv==1.0.1
starlette>=0.40.0,<0.42.0
cryptography>=42.0.0
```

资料来源：[requirements.txt](https://github.com/pquattro/memoraeu-mcp/blob/main/requirements.txt)

## Local Deployment (stdio)

The stdio mode provides complete zero-knowledge encryption. All content is encrypted on the client before transmission.

### Architecture

```mermaid
graph TD
    subgraph "Client Machine"
        A[MCP Client] -->|stdio| B[memoraeu-mcp]
        B --> C[Mistral API]
        B -->|Encrypt| D[Encrypted Payload]
    end
    D -->|AES-256-GCM| E[MemoraEU API]
    C -->|Embedding| B
    
    style A fill:#e1f5fe
    style E fill:#fff3e0
    style D fill:#f3e5f5
```

### Configuration Steps

#### 1. Create Claude Desktop Configuration

Edit your Claude Desktop config file:

| OS | Config Location |
|----|-----------------|
| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |
| Windows | `%APPDATA%\Claude\claude_desktop_config.json` |
| Linux | `~/.config/Claude/claude_desktop_config.json` |

#### 2. Add Server Configuration

```json
{
  "mcpServers": {
    "memoraeu": {
      "command": "uvx",
      "args": ["memoraeu-mcp"],
      "env": {
        "MEMORAEU_API_URL": "https://api.memoraeu.com",
        "MEMORAEU_API_KEY": "meu-sk-...",
        "MEMORAEU_SECRET": "your-memoraeu-password",
        "MEMORAEU_SALT": "your-kdf-salt",
        "MISTRAL_API_KEY": "your-mistral-key"
      }
    }
  }
}
```

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

### Environment Variables Reference

| Variable | Purpose | Required | Source |
|----------|---------|----------|--------|
| `MEMORAEU_API_KEY` | HTTP Bearer authentication | Yes | Dashboard → Settings → API Keys |
| `MEMORAEU_SECRET` | PBKDF2 password input for key derivation | Yes | Your MemoraEU login password |
| `MEMORAEU_SALT` | KDF salt unique to your account | Yes | Dashboard → Settings → Encryption Keys |
| `MEMORAEU_API_URL` | API endpoint | Yes | Use `https://api.memoraeu.com` for hosted |
| `MISTRAL_API_KEY` | Local embedding generation | Yes* | Mistral Console |

*Without `MISTRAL_API_KEY`, semantic search falls back to server-side keyword matching.

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

### Why Local Embeddings?

The zero-knowledge architecture requires embeddings to be computed **before encryption**:

```mermaid
sequenceDiagram
    participant User
    participant MCP as memoraeu-mcp
    participant Mistral
    participant Server
    
    User->>MCP: remember("I prefer dark mode")
    MCP->>Mistral: Generate embedding
    Mistral-->>MCP: Embedding vector
    MCP->>MCP: AES-256-GCM encrypt content
    MCP->>Server: Encrypted content + embedding
    Note over Server: Never sees plaintext
```

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Remote Deployment (SSE)

SSE mode connects directly to the hosted MemoraEU MCP endpoint without local installation.

### Configuration for Cursor/Windsurf

```json
{
  "mcpServers": {
    "memoraeu": {
      "type": "sse",
      "url": "https://api.memoraeu.com/mcp/sse",
      "headers": {
        "Authorization": "Bearer meu-sk-..."
      }
    }
  }
}
```

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

### SSE Endpoint Details

| Property | Value |
|----------|-------|
| Protocol | Server-Sent Events (SSE) |
| Endpoint | `https://api.memoraeu.com/mcp/sse` |
| Authentication | Bearer token in header |
| Encryption | Not zero-knowledge* |

> **Warning**: In remote SSE mode, content is processed as plaintext by the server. Use local stdio installation for zero-knowledge guarantees.

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Obtaining Credentials

Follow these steps to obtain all required credentials:

### Step 1: MemoraEU Account

1. Create account at [app.memoraeu.com](https://app.memoraeu.com)

### Step 2: Get Encryption Salt

1. Go to **Settings → Encryption Keys**
2. Copy the `MEMORAEU_SALT` value

### Step 3: Set Secret

1. `MEMORAEU_SECRET` is your MemoraEU login password
2. Used as PBKDF2 input to derive encryption key

### Step 4: Get API Key

1. Go to **Settings → API Keys**
2. Create a new key
3. Copy the `MEMORAEU_API_KEY` (format: `meu-sk-xxx`)

### Step 5: Get Mistral API Key

1. Obtain key at [console.mistral.ai](https://console.mistral.ai)
2. Required for local embedding generation

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Security Considerations

### Encryption Implementation

| Aspect | Detail |
|--------|--------|
| Algorithm | AES-256-GCM |
| Key Derivation | PBKDF2-HMAC-SHA256 |
| Iterations | 210,000 (OWASP 2024 recommendation) |
| Ciphertext Prefix | `ENCv1:` |
| Salt | Server-generated, unique per account |

资料来源：[CHANGELOG.md](https://github.com/pquattro/memoraeu-mcp/blob/main/CHANGELOG.md)

### Security Comparison

| Feature | stdio (Local) | SSE (Remote) |
|---------|---------------|--------------|
| Zero-knowledge | ✅ Yes | ❌ No |
| Embeddings | Local (via Mistral) | Server-processed |
| Content encryption | Client-side | Server-side |
| PBKDF2 iterations | 210,000 | 210,000 |

资料来源：[README.md](https://github.com/pquattro/memoraeu-mcp/blob/main/README.md)

## Available MCP Tools

Once deployed, the following tools are available:

| Tool | Description |
|------|-------------|
| `remember` | Automatically memorize important information |
| `recall` | Semantic search across stored memories |
| `forget` | Delete a memory by ID |
| `list_memories` | List recent memories with optional category filter |
| `list_categories` | Return existing categories sorted by usage |
| `remember_fact` | Store structured fact with temporal validity |
| `recall_facts` | Retrieve active facts for a subject |
| `invalidate_fact` | Mark a fact as expired |

资料来源：[memoraeu_mcp/main.py](https://github.com/pquattro/memoraeu-mcp/blob/main/memoraeu_mcp/main.py)

## Troubleshooting

### Common Issues

| Issue | Solution |
|-------|----------|
| `MISTRAL_API_KEY` missing | MCP continues working but semantic search falls back to keyword matching |
| Authentication failed | Verify `MEMORAEU_API_KEY` format is `meu-sk-xxx` |
| Encryption errors | Ensure `MEMORAEU_SECRET` and `MEMORAEU_SALT` are correct |
| stdio connection refused | Restart Claude Desktop after config changes |

### Verification Steps

1. Check config file syntax is valid JSON
2. Verify all required environment variables are set
3. Confirm API keys are active in MemoraEU dashboard
4. Restart the MCP client after configuration changes

## Version History

| Version | Date | Key Changes |
|---------|------|-------------|
| 0.1.9 | 2026-05-12 | Added fact tools, PBKDF2 210k iterations, ENCv1 prefix |
| 0.1.5 | 2026-04-28 | Initial fact support, PBKDF2 updates |

资料来源：[CHANGELOG.md](https://github.com/pquattro/memoraeu-mcp/blob/main/CHANGELOG.md)

---

---

## Doramagic Pitfall Log

Project: pquattro/memoraeu-mcp

Summary: Found 7 potential pitfall items; 0 are high/blocking. Highest priority: configuration - 可能修改宿主 AI 配置.

## 1. configuration · 可能修改宿主 AI 配置

- Severity: medium
- Evidence strength: source_linked
- Finding: 项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。
- User impact: 安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。
- Suggested check: 列出会写入的配置文件、目录和卸载/回滚步骤。
- Guardrail action: 涉及宿主配置目录时必须给回滚路径，不能只给安装命令。
- Evidence: capability.host_targets | github_repo:1215050856 | https://github.com/pquattro/memoraeu-mcp | host_targets=mcp_host, claude

## 2. capability · 能力判断依赖假设

- Severity: medium
- Evidence strength: source_linked
- Finding: README/documentation is current enough for a first validation pass.
- User impact: 假设不成立时，用户拿不到承诺的能力。
- Suggested check: 将假设转成下游验证清单。
- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。
- Evidence: capability.assumptions | github_repo:1215050856 | https://github.com/pquattro/memoraeu-mcp | README/documentation is current enough for a first validation pass.

## 3. maintenance · 维护活跃度未知

- Severity: medium
- Evidence strength: source_linked
- Finding: 未记录 last_activity_observed。
- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。
- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。
- Evidence: evidence.maintainer_signals | github_repo:1215050856 | https://github.com/pquattro/memoraeu-mcp | last_activity_observed missing

## 4. security_permissions · 下游验证发现风险项

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 下游已经要求复核，不能在页面中弱化。
- Suggested check: 进入安全/权限治理复核队列。
- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。
- Evidence: downstream_validation.risk_items | github_repo:1215050856 | https://github.com/pquattro/memoraeu-mcp | no_demo; severity=medium

## 5. security_permissions · 存在评分风险

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 风险会影响是否适合普通用户安装。
- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。
- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。
- Evidence: risks.scoring_risks | github_repo:1215050856 | https://github.com/pquattro/memoraeu-mcp | no_demo; severity=medium

## 6. maintenance · issue/PR 响应质量未知

- Severity: low
- Evidence strength: source_linked
- Finding: issue_or_pr_quality=unknown。
- User impact: 用户无法判断遇到问题后是否有人维护。
- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。
- Guardrail action: issue/PR 响应未知时，必须提示维护风险。
- Evidence: evidence.maintainer_signals | github_repo:1215050856 | https://github.com/pquattro/memoraeu-mcp | issue_or_pr_quality=unknown

## 7. maintenance · 发布节奏不明确

- Severity: low
- Evidence strength: source_linked
- Finding: release_recency=unknown。
- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。
- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。
- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。
- Evidence: evidence.maintainer_signals | github_repo:1215050856 | https://github.com/pquattro/memoraeu-mcp | release_recency=unknown

<!-- canonical_name: pquattro/memoraeu-mcp; human_manual_source: deepwiki_human_wiki -->
