memoraeu-mcp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ # Environment
2
+ env/
3
+ .env
4
+
5
+ # MCP config (contains secrets — use .mcp.json.example as template)
6
+ .mcp.json
7
+
8
+ # Database
9
+ memoraeu.db
10
+
11
+ # Python
12
+ __pycache__/
13
+ *.pyc
14
+ *.pyo
15
+ .DS_Store
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.4
2
+ Name: memoraeu-mcp
3
+ Version: 0.1.0
4
+ Summary: Zero-knowledge persistent memory layer for Claude — MCP server
5
+ Project-URL: Homepage, https://app.memoraeu.isquarecube.fr
6
+ Project-URL: Repository, https://github.com/memoraeu/memoraeu-mcp
7
+ Project-URL: Documentation, https://docs.memoraeu.com
8
+ Author-email: MemoraEU <contact@memoraeu.com>
9
+ License: MIT
10
+ Keywords: ai,claude,llm,mcp,memory,zero-knowledge
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Requires-Python: >=3.11
19
+ Requires-Dist: cryptography>=42.0.0
20
+ Requires-Dist: httpx>=0.27.0
21
+ Requires-Dist: mcp>=1.0.0
22
+ Description-Content-Type: text/markdown
23
+
24
+ # memoraeu-mcp
25
+
26
+ Zero-knowledge persistent memory layer for Claude — MCP server.
27
+
28
+ ## Installation
29
+
30
+ ```bash
31
+ pip install memoraeu-mcp
32
+ ```
33
+
34
+ ## Usage
35
+
36
+ Add to your `claude_desktop_config.json`:
37
+
38
+ ```json
39
+ {
40
+ "mcpServers": {
41
+ "memoraeu": {
42
+ "command": "memoraeu-mcp",
43
+ "args": [],
44
+ "env": {
45
+ "MEMORAEU_API_URL": "https://api.memoraeu.isquarecube.fr",
46
+ "MEMORAEU_API_KEY": "meu-sk-...",
47
+ "MEMORAEU_SECRET": "your-secret",
48
+ "MEMORAEU_SALT": "your-salt",
49
+ "MISTRAL_API_KEY": "your-mistral-key"
50
+ }
51
+ }
52
+ }
53
+ }
54
+ ```
55
+
56
+ Or with `uvx` (no install required):
57
+
58
+ ```json
59
+ {
60
+ "mcpServers": {
61
+ "memoraeu": {
62
+ "command": "uvx",
63
+ "args": ["memoraeu-mcp"],
64
+ "env": { ... }
65
+ }
66
+ }
67
+ }
68
+ ```
69
+
70
+ ## Features
71
+
72
+ - 🔒 **Zero-knowledge** — AES-256-GCM encryption, key never leaves your machine
73
+ - 🧠 **Semantic search** — Mistral embeddings + Qdrant vector store
74
+ - 🔄 **Auto memory** — remembers and recalls context automatically
75
+ - 🇪🇺 **EU hosted** — GDPR compliant infrastructure
76
+
77
+ ## Getting your keys
78
+
79
+ Generate `MEMORAEU_SECRET` and `MEMORAEU_SALT` from your dashboard at [app.memoraeu.isquarecube.fr](https://app.memoraeu.isquarecube.fr) → Settings.
@@ -0,0 +1,56 @@
1
+ # memoraeu-mcp
2
+
3
+ Zero-knowledge persistent memory layer for Claude — MCP server.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install memoraeu-mcp
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ Add to your `claude_desktop_config.json`:
14
+
15
+ ```json
16
+ {
17
+ "mcpServers": {
18
+ "memoraeu": {
19
+ "command": "memoraeu-mcp",
20
+ "args": [],
21
+ "env": {
22
+ "MEMORAEU_API_URL": "https://api.memoraeu.isquarecube.fr",
23
+ "MEMORAEU_API_KEY": "meu-sk-...",
24
+ "MEMORAEU_SECRET": "your-secret",
25
+ "MEMORAEU_SALT": "your-salt",
26
+ "MISTRAL_API_KEY": "your-mistral-key"
27
+ }
28
+ }
29
+ }
30
+ }
31
+ ```
32
+
33
+ Or with `uvx` (no install required):
34
+
35
+ ```json
36
+ {
37
+ "mcpServers": {
38
+ "memoraeu": {
39
+ "command": "uvx",
40
+ "args": ["memoraeu-mcp"],
41
+ "env": { ... }
42
+ }
43
+ }
44
+ }
45
+ ```
46
+
47
+ ## Features
48
+
49
+ - 🔒 **Zero-knowledge** — AES-256-GCM encryption, key never leaves your machine
50
+ - 🧠 **Semantic search** — Mistral embeddings + Qdrant vector store
51
+ - 🔄 **Auto memory** — remembers and recalls context automatically
52
+ - 🇪🇺 **EU hosted** — GDPR compliant infrastructure
53
+
54
+ ## Getting your keys
55
+
56
+ Generate `MEMORAEU_SECRET` and `MEMORAEU_SALT` from your dashboard at [app.memoraeu.isquarecube.fr](https://app.memoraeu.isquarecube.fr) → Settings.
@@ -0,0 +1,66 @@
1
+ """
2
+ MemoraEU — Chiffrement zero-knowledge côté client
3
+ AES-256-GCM + PBKDF2-HMAC-SHA256
4
+
5
+ Le serveur ne voit jamais le texte clair ni la clé.
6
+ L'embedding est calculé AVANT chiffrement pour préserver la recherche sémantique.
7
+ """
8
+ import os
9
+ import base64
10
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
11
+ from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
12
+ from cryptography.hazmat.primitives import hashes
13
+
14
+
15
+ # Salt fixe par installation (stocké dans .env)
16
+ # En phase 2 : un salt par user stocké côté serveur
17
+ PBKDF2_ITERATIONS = 100_000
18
+
19
+
20
+ def derive_key(password: str, salt: str) -> bytes:
21
+ """
22
+ Dérive une clé AES-256 depuis un mot de passe et un salt.
23
+ Appelé une seule fois au démarrage du MCP server.
24
+ """
25
+ salt_bytes = salt.encode() if isinstance(salt, str) else salt
26
+ kdf = PBKDF2HMAC(
27
+ algorithm=hashes.SHA256(),
28
+ length=32,
29
+ salt=salt_bytes,
30
+ iterations=PBKDF2_ITERATIONS,
31
+ )
32
+ return kdf.derive(password.encode())
33
+
34
+
35
+ def encrypt(plaintext: str, key: bytes) -> str:
36
+ """
37
+ Chiffre un texte avec AES-256-GCM.
38
+ Retourne : base64(nonce[12] + ciphertext + tag[16])
39
+ """
40
+ nonce = os.urandom(12)
41
+ ciphertext = AESGCM(key).encrypt(nonce, plaintext.encode("utf-8"), None)
42
+ return base64.b64encode(nonce + ciphertext).decode("ascii")
43
+
44
+
45
+ def decrypt(ciphertext_b64: str, key: bytes) -> str:
46
+ """
47
+ Déchiffre un texte chiffré par encrypt().
48
+ Lève une exception si la clé est mauvaise ou les données corrompues.
49
+ """
50
+ data = base64.b64decode(ciphertext_b64)
51
+ nonce = data[:12]
52
+ ciphertext = data[12:]
53
+ plaintext = AESGCM(key).decrypt(nonce, ciphertext, None)
54
+ return plaintext.decode("utf-8")
55
+
56
+
57
+ def is_encrypted(value: str) -> bool:
58
+ """
59
+ Détecte si une valeur est déjà chiffrée (base64 valide de longueur minimale).
60
+ Permet la compatibilité avec les mémoires existantes en clair.
61
+ """
62
+ try:
63
+ data = base64.b64decode(value)
64
+ return len(data) > 12 # nonce(12) + au moins 1 octet
65
+ except Exception:
66
+ return False
@@ -0,0 +1,2 @@
1
+ """memoraeu-mcp — Zero-knowledge MCP server for MemoraEU."""
2
+ __version__ = "0.1.0"
@@ -0,0 +1,19 @@
1
+ """Entry point pour le package memoraeu-mcp installé via pip/uvx."""
2
+ import sys
3
+ import os
4
+
5
+ def run():
6
+ """Lance le serveur MCP MemoraEU (stdio transport)."""
7
+ # Ajouter le dossier parent au path pour trouver server.py et crypto.py
8
+ parent = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
9
+ if parent not in sys.path:
10
+ sys.path.insert(0, parent)
11
+
12
+ import asyncio
13
+ # Import du vrai server (server.py à la racine de mcp/)
14
+ from server import main # type: ignore
15
+ asyncio.run(main())
16
+
17
+
18
+ if __name__ == "__main__":
19
+ run()
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "memoraeu-mcp"
7
+ version = "0.1.0"
8
+ description = "Zero-knowledge persistent memory layer for Claude — MCP server"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.11"
12
+ authors = [{ name = "MemoraEU", email = "contact@memoraeu.com" }]
13
+ keywords = ["mcp", "memory", "llm", "claude", "zero-knowledge", "ai"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
22
+ ]
23
+ dependencies = [
24
+ "mcp>=1.0.0",
25
+ "httpx>=0.27.0",
26
+ "cryptography>=42.0.0",
27
+ ]
28
+
29
+ [project.scripts]
30
+ memoraeu-mcp = "memoraeu_mcp.server:run"
31
+
32
+ [project.urls]
33
+ Homepage = "https://app.memoraeu.isquarecube.fr"
34
+ Repository = "https://github.com/memoraeu/memoraeu-mcp"
35
+ Documentation = "https://docs.memoraeu.com"
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["memoraeu_mcp"]
@@ -0,0 +1,5 @@
1
+ mcp>=1.1.0,<1.2.0
2
+ httpx==0.28.1
3
+ python-dotenv==1.0.1
4
+ starlette>=0.40.0,<0.42.0
5
+ cryptography>=42.0.0
@@ -0,0 +1,483 @@
1
+ """
2
+ MemoraEU MCP Server
3
+ Transport : stdio (Claude Desktop)
4
+
5
+ Chiffrement : AES-256-GCM zero-knowledge
6
+ - MEMORAEU_SECRET : mot de passe dans .env
7
+ - MEMORAEU_SALT : salt dans .env
8
+ - La clé est dérivée au démarrage, jamais transmise au serveur
9
+
10
+ Mémoire automatique :
11
+ - La ressource memoraeu://context est lue automatiquement en début de session
12
+ - recall est déclenché automatiquement sur le sujet du premier message
13
+ - remember est utilisé automatiquement sur les infos importantes
14
+ """
15
+ import asyncio
16
+ import httpx
17
+ import os
18
+ import sys
19
+ from mcp.server import Server
20
+ from mcp.server.stdio import stdio_server
21
+ from mcp.types import Tool, TextContent, Prompt, PromptMessage, GetPromptResult
22
+ from mcp.types import Resource, ResourceContents, TextResourceContents
23
+
24
+ API_URL = os.getenv("MEMORAEU_API_URL", "http://localhost:8000")
25
+ MEMORAEU_API_KEY = os.getenv("MEMORAEU_API_KEY", "")
26
+ MEMORAEU_SECRET = os.getenv("MEMORAEU_SECRET", "")
27
+ MEMORAEU_SALT = os.getenv("MEMORAEU_SALT", "memoraeu-default-salt-v1")
28
+ MISTRAL_API_KEY = os.getenv("MISTRAL_API_KEY", "")
29
+ MISTRAL_BASE_URL = os.getenv("MISTRAL_BASE_URL", "https://api.mistral.ai/v1")
30
+ MISTRAL_MODEL = os.getenv("MISTRAL_MODEL", "mistral-small-latest")
31
+ COMPRESSION_THRESHOLD = 300
32
+ DEDUP_SKIP_THRESHOLD = 0.94 # score ≥ 0.94 → doublon exact, on skip
33
+ DEDUP_WARN_THRESHOLD = 0.85 # score ≥ 0.85 → très similaire, on avertit mais on stocke
34
+
35
+ _key: bytes | None = None
36
+ _context_loaded: bool = False
37
+ _session_context: str = ""
38
+ _first_recall: bool = True
39
+
40
+ def get_key() -> bytes | None:
41
+ return _key
42
+
43
+ def init_crypto():
44
+ global _key
45
+ if MEMORAEU_SECRET:
46
+ from crypto import derive_key
47
+ _key = derive_key(MEMORAEU_SECRET, MEMORAEU_SALT)
48
+ print("[memoraeu] ✅ Chiffrement zero-knowledge activé", file=sys.stderr)
49
+ else:
50
+ print("[memoraeu] ⚠️ MEMORAEU_SECRET absent — stockage en clair", file=sys.stderr)
51
+
52
+ def encrypt_content(content: str) -> str:
53
+ key = get_key()
54
+ if not key:
55
+ return content
56
+ from crypto import encrypt
57
+ return encrypt(content, key)
58
+
59
+ def decrypt_content(value: str) -> str:
60
+ key = get_key()
61
+ if not key:
62
+ return value
63
+ from crypto import decrypt, is_encrypted
64
+ if not is_encrypted(value):
65
+ return value
66
+ try:
67
+ return decrypt(value, key)
68
+ except Exception:
69
+ return "[contenu chiffré — clé incorrecte]"
70
+
71
+ async def _mistral_chat(prompt: str) -> str | None:
72
+ """Appel direct à Mistral pour compression ou catégorisation (avant chiffrement)."""
73
+ if not MISTRAL_API_KEY:
74
+ return None
75
+ try:
76
+ async with httpx.AsyncClient(timeout=30.0) as client:
77
+ r = await client.post(
78
+ f"{MISTRAL_BASE_URL}/chat/completions",
79
+ headers={"Authorization": f"Bearer {MISTRAL_API_KEY}", "Content-Type": "application/json"},
80
+ json={"model": MISTRAL_MODEL, "messages": [{"role": "user", "content": prompt}], "max_tokens": 400, "temperature": 0.1}
81
+ )
82
+ r.raise_for_status()
83
+ return r.json()["choices"][0]["message"]["content"].strip()
84
+ except Exception as e:
85
+ print(f"[mcp] Mistral error: {e}", file=sys.stderr)
86
+ return None
87
+
88
+ async def embed_locally(content: str) -> list[float] | None:
89
+ """Génère l'embedding depuis le texte clair (avant chiffrement) — zero-knowledge."""
90
+ if not MISTRAL_API_KEY:
91
+ return None
92
+ try:
93
+ async with httpx.AsyncClient(timeout=30.0) as client:
94
+ r = await client.post(
95
+ f"{MISTRAL_BASE_URL}/embeddings",
96
+ headers={"Authorization": f"Bearer {MISTRAL_API_KEY}", "Content-Type": "application/json"},
97
+ json={"model": "mistral-embed", "inputs": [content]}
98
+ )
99
+ r.raise_for_status()
100
+ return r.json()["data"][0]["embedding"]
101
+ except Exception as e:
102
+ print(f"[mcp] Embedding error: {e}", file=sys.stderr)
103
+ return None
104
+
105
+ async def compress_locally(content: str) -> str:
106
+ """Compresse le contenu en clair avant chiffrement."""
107
+ if len(content) <= COMPRESSION_THRESHOLD:
108
+ return content
109
+ prompt = (
110
+ "Résume ce texte en 1-3 phrases concises, en français, en gardant l'essentiel. "
111
+ "Réponds uniquement avec le résumé, sans introduction ni conclusion.\n\n"
112
+ f"{content}"
113
+ )
114
+ compressed = await _mistral_chat(prompt)
115
+ if compressed and len(compressed) < len(content):
116
+ print(f"[mcp] Compression: {len(content)} → {len(compressed)} chars", file=sys.stderr)
117
+ return compressed
118
+ return content
119
+
120
+ async def suggest_category_locally(content: str, existing: list[str]) -> str:
121
+ """Suggère une catégorie pour le contenu en clair."""
122
+ existing_str = ", ".join(existing) if existing else "aucune"
123
+ prompt = (
124
+ f"Catégories existantes : {existing_str}\n\n"
125
+ f"Texte : {content[:500]}\n\n"
126
+ "Quelle catégorie courte (1-2 mots, en français, minuscules) correspond le mieux ? "
127
+ "Utilise une existante si pertinente, sinon crée-en une. Réponds uniquement avec la catégorie."
128
+ )
129
+ cat = await _mistral_chat(prompt)
130
+ if cat:
131
+ return cat.lower().strip().strip('"').strip("'")[:30]
132
+ return "personnel"
133
+
134
+ async def check_duplicate(embedding: list[float]) -> dict | None:
135
+ """
136
+ Recherche une mémoire similaire via le vecteur pré-calculé (zero-knowledge).
137
+ Retourne {"id", "score", "preview"} si un doublon est trouvé, sinon None.
138
+ """
139
+ if not embedding:
140
+ return None
141
+ try:
142
+ response = await api_post("/memories/search-by-vector", {
143
+ "vector": embedding,
144
+ "limit": 1,
145
+ "scope": "private",
146
+ "threshold": DEDUP_WARN_THRESHOLD,
147
+ })
148
+ results = response.get("results", [])
149
+ if not results:
150
+ return None
151
+ best = results[0]
152
+ m = best["memory"]
153
+ return {
154
+ "id": m["id"],
155
+ "score": best["score"],
156
+ "preview": decrypt_content(m["content"])[:120],
157
+ }
158
+ except Exception as e:
159
+ print(f"[mcp] Dedup check error: {e}", file=sys.stderr)
160
+ return None
161
+
162
+
163
+ def _auth_headers() -> dict:
164
+ return {"Authorization": f"Bearer {MEMORAEU_API_KEY}"} if MEMORAEU_API_KEY else {}
165
+
166
+ async def api_post(path: str, body: dict, timeout: float = 90.0) -> dict:
167
+ async with httpx.AsyncClient(timeout=timeout) as client:
168
+ r = await client.post(f"{API_URL}{path}", json=body, headers=_auth_headers())
169
+ r.raise_for_status()
170
+ return r.json()
171
+
172
+ async def api_get(path: str, params: dict = None) -> dict:
173
+ async with httpx.AsyncClient(timeout=30.0) as client:
174
+ r = await client.get(f"{API_URL}{path}", params=params, headers=_auth_headers())
175
+ r.raise_for_status()
176
+ return r.json()
177
+
178
+ async def api_delete(path: str) -> bool:
179
+ async with httpx.AsyncClient(timeout=30.0) as client:
180
+ r = await client.delete(f"{API_URL}{path}", headers=_auth_headers())
181
+ return r.status_code == 204
182
+
183
+ async def load_session_context() -> str:
184
+ """
185
+ Charge les mémoires récentes au premier appel de la session.
186
+ Injecté automatiquement dans recall pour enrichir le contexte.
187
+ """
188
+ global _context_loaded, _session_context
189
+ if _context_loaded:
190
+ return _session_context
191
+ try:
192
+ memories = await api_get("/memories", params={"limit": 10, "scope": "private"})
193
+ if memories:
194
+ lines = ["[Contexte mémoire automatique — MemoraEU]"]
195
+ for m in memories:
196
+ content = decrypt_content(m["content"])
197
+ cat = m.get("category") or "—"
198
+ lines.append(f"[{cat}] {content[:120]}")
199
+ _session_context = "\n".join(lines)
200
+ else:
201
+ _session_context = ""
202
+ except Exception:
203
+ _session_context = ""
204
+ _context_loaded = True
205
+ return _session_context
206
+
207
+ app = Server("memoraeu")
208
+
209
+ SYSTEM_PROMPT_TEXT = """Tu as accès à une mémoire persistante via les outils MemoraEU.
210
+
211
+ ## Mémorisation automatique
212
+ Sans que l'utilisateur ait besoin de te le demander, utilise `remember` dès qu'une information mérite d'être retenue :
213
+ - Préférences personnelles ("j'aime", "je préfère", "je veux toujours")
214
+ - Décisions importantes ("on a décidé", "le choix final est")
215
+ - Faits biographiques (lieu, famille, travail, projets)
216
+ - Habitudes récurrentes ou contraintes durables
217
+ - Informations techniques propres à l'utilisateur (stack, config, credentials non-sensibles)
218
+
219
+ ## Rappel automatique
220
+ Dès le premier message de l'utilisateur, utilise `recall` avec le sujet détecté comme query.
221
+ N'attends pas qu'on te le demande — c'est automatique.
222
+
223
+ ## Règles
224
+ - Ne mémorise pas les informations générales ou éphémères (météo du jour, blagues, calculs ponctuels)
225
+ - Si l'utilisateur dit "oublie ça" ou "ne retiens pas", utilise `forget`
226
+ - Confirme discrètement les mémorisations : une ligne, pas plus
227
+ - Optimisation tokens : limite recall à 3 résultats par défaut, mémoires compactes
228
+ """
229
+
230
+ @app.list_prompts()
231
+ async def list_prompts() -> list[Prompt]:
232
+ return [
233
+ Prompt(
234
+ name="memoraeu_system",
235
+ description="Système de mémorisation automatique MemoraEU — injecter en system prompt.",
236
+ arguments=[]
237
+ )
238
+ ]
239
+
240
+ @app.get_prompt()
241
+ async def get_prompt(name: str, arguments: dict | None = None) -> GetPromptResult:
242
+ if name == "memoraeu_system":
243
+ return GetPromptResult(
244
+ description="Comportement de mémorisation automatique",
245
+ messages=[
246
+ PromptMessage(
247
+ role="user",
248
+ content=TextContent(type="text", text=SYSTEM_PROMPT_TEXT)
249
+ )
250
+ ]
251
+ )
252
+ raise ValueError(f"Prompt inconnu : {name}")
253
+
254
+ @app.list_resources()
255
+ async def list_resources() -> list[Resource]:
256
+ return [
257
+ Resource(
258
+ uri="memoraeu://context",
259
+ name="Contexte mémoire MemoraEU",
260
+ description="Mémoires récentes injectées automatiquement en début de session",
261
+ mimeType="text/plain"
262
+ )
263
+ ]
264
+
265
+ @app.read_resource()
266
+ async def read_resource(uri: str) -> list[ResourceContents]:
267
+ if uri == "memoraeu://context":
268
+ context = await load_session_context()
269
+ text = context if context else "Aucune mémoire enregistrée."
270
+ return [TextResourceContents(uri=uri, mimeType="text/plain", text=text)]
271
+ raise ValueError(f"Ressource inconnue : {uri}")
272
+
273
+ @app.list_tools()
274
+ async def list_tools() -> list[Tool]:
275
+ return [
276
+ Tool(
277
+ name="remember",
278
+ description=(
279
+ "Mémorise automatiquement une information importante. "
280
+ "UTILISE CET OUTIL SANS QU'ON TE LE DEMANDE dès que l'utilisateur exprime "
281
+ "une préférence, une décision, un fait biographique, une config technique, "
282
+ "ou une contrainte durable. Confirme en une ligne discrète."
283
+ ),
284
+ inputSchema={
285
+ "type": "object",
286
+ "properties": {
287
+ "content": {"type": "string"},
288
+ "category": {"type": "string"},
289
+ "tags": {"type": "array", "items": {"type": "string"}}
290
+ },
291
+ "required": ["content"]
292
+ }
293
+ ),
294
+ Tool(
295
+ name="recall",
296
+ description=(
297
+ "APPELLE CET OUTIL AUTOMATIQUEMENT dès le premier message de chaque conversation. "
298
+ "Utilise le sujet du message comme query pour récupérer le contexte pertinent. "
299
+ "Recherche sémantique — pas besoin de mots exacts. "
300
+ "Limite à 3 résultats pour économiser les tokens (augmente seulement si nécessaire)."
301
+ ),
302
+ inputSchema={
303
+ "type": "object",
304
+ "properties": {
305
+ "query": {"type": "string"},
306
+ "limit": {"type": "integer", "default": 3},
307
+ "category": {"type": "string"}
308
+ },
309
+ "required": ["query"]
310
+ }
311
+ ),
312
+ Tool(
313
+ name="forget",
314
+ description="Supprime une mémoire par son ID.",
315
+ inputSchema={
316
+ "type": "object",
317
+ "properties": {"memory_id": {"type": "string"}},
318
+ "required": ["memory_id"]
319
+ }
320
+ ),
321
+ Tool(
322
+ name="list_memories",
323
+ description="Liste les mémoires récentes.",
324
+ inputSchema={
325
+ "type": "object",
326
+ "properties": {
327
+ "category": {"type": "string"},
328
+ "limit": {"type": "integer", "default": 20}
329
+ }
330
+ }
331
+ ),
332
+ Tool(
333
+ name="list_categories",
334
+ description="Retourne les catégories existantes triées par usage.",
335
+ inputSchema={"type": "object", "properties": {}}
336
+ ),
337
+ ]
338
+
339
+ @app.call_tool()
340
+ async def call_tool(name: str, arguments: dict) -> list[TextContent]:
341
+
342
+ if name == "remember":
343
+ try:
344
+ raw_content = arguments["content"]
345
+
346
+ # 1. Compression en clair (avant chiffrement)
347
+ content = await compress_locally(raw_content)
348
+
349
+ # 2. Catégorisation en clair (avant chiffrement)
350
+ category = arguments.get("category")
351
+ if not category:
352
+ try:
353
+ cats_resp = await api_get("/memories/categories")
354
+ existing = [c["name"] for c in cats_resp.get("categories", [])]
355
+ except Exception:
356
+ existing = []
357
+ category = await suggest_category_locally(content, existing)
358
+
359
+ # 3. Embedding depuis le texte clair (zero-knowledge)
360
+ embedding = await embed_locally(content)
361
+
362
+ # 3b. Déduplication — recherche par vecteur avant chiffrement
363
+ if embedding:
364
+ dup = await check_duplicate(embedding)
365
+ if dup:
366
+ score_pct = round(dup["score"] * 100)
367
+ if dup["score"] >= DEDUP_SKIP_THRESHOLD:
368
+ return [TextContent(type="text", text=(
369
+ f"⚠️ Doublon détecté ({score_pct}% similaire) — mémoire non créée.\n"
370
+ f"→ Existante : {dup['preview']} (ID: {dup['id'][:8]}…)"
371
+ ))]
372
+ else:
373
+ print(f"[mcp] Mémoire similaire à {score_pct}% (ID: {dup['id'][:8]}…) — stockage quand même", file=sys.stderr)
374
+
375
+ # 4. Chiffrement du contenu traité
376
+ encrypted = encrypt_content(content)
377
+
378
+ # 5. Envoi à l'API avec pre_processed=True + embedding pré-calculé
379
+ payload = {
380
+ "content": encrypted,
381
+ "category": category,
382
+ "tags": arguments.get("tags", []),
383
+ "source": "claude_desktop",
384
+ "scope": "private",
385
+ "pre_processed": True,
386
+ }
387
+ if embedding:
388
+ payload["embedding"] = embedding
389
+ memory = await api_post("/memories", payload)
390
+ cat = memory.get("category") or "non catégorisé"
391
+ lock = "🔒" if get_key() else "📝"
392
+ return [TextContent(type="text", text=f"✅ Mémorisé {lock} (ID: {memory['id'][:8]}…, catégorie: {cat})")]
393
+ except Exception as e:
394
+ return [TextContent(type="text", text=f"❌ Erreur : {e}")]
395
+
396
+ elif name == "recall":
397
+ global _first_recall
398
+ try:
399
+ is_first = _first_recall
400
+ _first_recall = False
401
+
402
+ # Chargement du contexte session au premier recall
403
+ context = await load_session_context()
404
+
405
+ response = await api_post("/memories/search", {
406
+ "query": arguments["query"],
407
+ "limit": arguments.get("limit", 3),
408
+ "category": arguments.get("category"),
409
+ "scope": "private"
410
+ })
411
+ results = response.get("results", [])
412
+
413
+ lines = []
414
+
415
+ # Injection du system prompt uniquement au premier recall
416
+ if is_first:
417
+ lines.append(SYSTEM_PROMPT_TEXT)
418
+ lines.append("---")
419
+
420
+ if context and not results:
421
+ lines.append(context)
422
+ elif not results:
423
+ if not is_first:
424
+ return [TextContent(type="text", text="Aucune mémoire trouvée.")]
425
+ else:
426
+ lines.append(f"🔍 {len(results)} mémoire(s) :\n")
427
+ for r in results:
428
+ m = r["memory"]
429
+ content = decrypt_content(m["content"])
430
+ cat = m.get("category") or "—"
431
+ tags = ", ".join(m.get("tags", [])) or "—"
432
+ lines.append(
433
+ f"• [{round(r['score']*100)}%] {content}\n"
434
+ f" catégorie: {cat} | tags: {tags} | ID: {m['id'][:8]}…"
435
+ )
436
+ return [TextContent(type="text", text="\n".join(lines))]
437
+ except Exception as e:
438
+ return [TextContent(type="text", text=f"❌ Erreur : {e}")]
439
+
440
+ elif name == "forget":
441
+ try:
442
+ deleted = await api_delete(f"/memories/{arguments['memory_id']}")
443
+ return [TextContent(type="text", text="🗑️ Supprimée." if deleted else "Introuvable.")]
444
+ except Exception as e:
445
+ return [TextContent(type="text", text=f"❌ Erreur : {e}")]
446
+
447
+ elif name == "list_memories":
448
+ try:
449
+ params = {"limit": arguments.get("limit", 20), "scope": "private"}
450
+ if arguments.get("category"):
451
+ params["category"] = arguments["category"]
452
+ memories = await api_get("/memories", params=params)
453
+ if not memories:
454
+ return [TextContent(type="text", text="Aucune mémoire.")]
455
+ lines = [f"📋 {len(memories)} mémoire(s) :\n"]
456
+ for m in memories:
457
+ content = decrypt_content(m["content"])
458
+ preview = content[:100] + ("…" if len(content) > 100 else "")
459
+ lines.append(f"• [{m.get('category') or '—'}] {preview} (ID: {m['id'][:8]}…)")
460
+ return [TextContent(type="text", text="\n".join(lines))]
461
+ except Exception as e:
462
+ return [TextContent(type="text", text=f"❌ Erreur : {e}")]
463
+
464
+ elif name == "list_categories":
465
+ try:
466
+ response = await api_get("/memories/categories")
467
+ cats = response.get("categories", [])
468
+ if not cats:
469
+ return [TextContent(type="text", text="Aucune catégorie.")]
470
+ lines = ["📁 Catégories :\n"] + [f"• {c['name']} ({c['usage_count']})" for c in cats]
471
+ return [TextContent(type="text", text="\n".join(lines))]
472
+ except Exception as e:
473
+ return [TextContent(type="text", text=f"❌ Erreur : {e}")]
474
+
475
+ return [TextContent(type="text", text=f"Outil inconnu : {name}")]
476
+
477
+ async def main():
478
+ init_crypto()
479
+ async with stdio_server() as (read_stream, write_stream):
480
+ await app.run(read_stream, write_stream, app.create_initialization_options())
481
+
482
+ if __name__ == "__main__":
483
+ asyncio.run(main())