n3memorycore-mcp-lite 1.1.0__py3-none-any.whl
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.
- n3mc_mcp/__init__.py +17 -0
- n3mc_mcp/__main__.py +27 -0
- n3mc_mcp/config.py +85 -0
- n3mc_mcp/database.py +391 -0
- n3mc_mcp/instructions.py +60 -0
- n3mc_mcp/paths.py +37 -0
- n3mc_mcp/processor.py +178 -0
- n3mc_mcp/server.py +351 -0
- n3memorycore_mcp_lite-1.1.0.dist-info/METADATA +427 -0
- n3memorycore_mcp_lite-1.1.0.dist-info/RECORD +14 -0
- n3memorycore_mcp_lite-1.1.0.dist-info/WHEEL +4 -0
- n3memorycore_mcp_lite-1.1.0.dist-info/entry_points.txt +2 -0
- n3memorycore_mcp_lite-1.1.0.dist-info/licenses/LICENSE +190 -0
- n3memorycore_mcp_lite-1.1.0.dist-info/licenses/NOTICE +25 -0
n3mc_mcp/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""
|
|
2
|
+
N3MemoryCore MCP Server — Lite
|
|
3
|
+
================================
|
|
4
|
+
|
|
5
|
+
A Model Context Protocol (MCP) server that provides **ephemeral**
|
|
6
|
+
hybrid (vector + BM25) memory across conversations, backed by Redis
|
|
7
|
+
Stack with a 7d TTL per entry.
|
|
8
|
+
|
|
9
|
+
Tools:
|
|
10
|
+
- search_memory : hybrid search over stored memories
|
|
11
|
+
- save_memory : persist a memory entry (7d TTL)
|
|
12
|
+
- list_memories : list recent entries
|
|
13
|
+
- delete_memory : remove an entry by id
|
|
14
|
+
- repair_memory : re-create the RediSearch index if missing
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
__version__ = "1.1.0"
|
n3mc_mcp/__main__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Entry point: ``python -m n3mc_mcp`` or ``n3mc-mcp``."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from .server import run
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _reconfigure_utf8() -> None:
|
|
11
|
+
"""Windows cp932 fix: force UTF-8 on stdio."""
|
|
12
|
+
for stream_name in ("stdin", "stdout", "stderr"):
|
|
13
|
+
stream = getattr(sys, stream_name, None)
|
|
14
|
+
if stream is not None and hasattr(stream, "reconfigure"):
|
|
15
|
+
try:
|
|
16
|
+
stream.reconfigure(encoding="utf-8")
|
|
17
|
+
except Exception:
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def main() -> None:
|
|
22
|
+
_reconfigure_utf8()
|
|
23
|
+
asyncio.run(run())
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
if __name__ == "__main__":
|
|
27
|
+
main()
|
n3mc_mcp/config.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Config management for the N3MemoryCore MCP **Lite** server.
|
|
3
|
+
|
|
4
|
+
Config is a JSON file in the user data directory. Missing fields are filled
|
|
5
|
+
with defaults and UUIDs are auto-generated on first run. Unlike the paid
|
|
6
|
+
variant there is no DB-side fallback — Redis is ephemeral, so if the config
|
|
7
|
+
file is lost a fresh pair of UUIDs is simply generated.
|
|
8
|
+
|
|
9
|
+
The Redis connection URL can be overridden via:
|
|
10
|
+
- ``N3MC_REDIS_URL`` environment variable (highest priority)
|
|
11
|
+
- ``redis_url`` field in config.json
|
|
12
|
+
- Default: ``redis://localhost:6379/0``
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import sys
|
|
19
|
+
import uuid
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from .paths import config_path
|
|
23
|
+
|
|
24
|
+
DEFAULT_REDIS_URL = "redis://localhost:6379/0"
|
|
25
|
+
DEFAULT_TTL_SECONDS = 7 * 24 * 60 * 60 # 7 days
|
|
26
|
+
|
|
27
|
+
DEFAULT_CONFIG: dict[str, Any] = {
|
|
28
|
+
"owner_id": None,
|
|
29
|
+
"local_id": None,
|
|
30
|
+
"redis_url": DEFAULT_REDIS_URL,
|
|
31
|
+
"ttl_seconds": DEFAULT_TTL_SECONDS,
|
|
32
|
+
"dedup_threshold": 0.95,
|
|
33
|
+
"half_life_days": 3,
|
|
34
|
+
"bm25_min_threshold": 0.1,
|
|
35
|
+
"search_result_limit": 20,
|
|
36
|
+
"context_char_limit": 3000,
|
|
37
|
+
"min_score": 0.2,
|
|
38
|
+
"search_query_max_chars": 2000,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def load_config() -> dict:
|
|
43
|
+
"""Load config, auto-generating UUIDs and persisting on first run."""
|
|
44
|
+
cfg = dict(DEFAULT_CONFIG)
|
|
45
|
+
path = config_path()
|
|
46
|
+
|
|
47
|
+
if path.exists():
|
|
48
|
+
try:
|
|
49
|
+
with path.open("r", encoding="utf-8") as f:
|
|
50
|
+
loaded = json.load(f)
|
|
51
|
+
cfg.update(loaded)
|
|
52
|
+
except Exception as e:
|
|
53
|
+
print(f"[N3MC-Lite] WARNING: config.json parse error: {e}", file=sys.stderr)
|
|
54
|
+
|
|
55
|
+
# Env var override for Redis URL (wins over file)
|
|
56
|
+
env_url = os.environ.get("N3MC_REDIS_URL")
|
|
57
|
+
if env_url:
|
|
58
|
+
cfg["redis_url"] = env_url
|
|
59
|
+
|
|
60
|
+
changed = False
|
|
61
|
+
if not cfg.get("owner_id"):
|
|
62
|
+
cfg["owner_id"] = str(uuid.uuid4())
|
|
63
|
+
changed = True
|
|
64
|
+
if not cfg.get("local_id"):
|
|
65
|
+
cfg["local_id"] = str(uuid.uuid4())
|
|
66
|
+
changed = True
|
|
67
|
+
|
|
68
|
+
for k, v in DEFAULT_CONFIG.items():
|
|
69
|
+
if k not in cfg and v is not None:
|
|
70
|
+
cfg[k] = v
|
|
71
|
+
changed = True
|
|
72
|
+
|
|
73
|
+
if changed:
|
|
74
|
+
save_config(cfg)
|
|
75
|
+
|
|
76
|
+
return cfg
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def save_config(cfg: dict) -> None:
|
|
80
|
+
path = config_path()
|
|
81
|
+
try:
|
|
82
|
+
with path.open("w", encoding="utf-8") as f:
|
|
83
|
+
json.dump(cfg, f, indent=2, ensure_ascii=False)
|
|
84
|
+
except Exception as e:
|
|
85
|
+
print(f"[N3MC-Lite] WARNING: failed to write config.json: {e}", file=sys.stderr)
|
n3mc_mcp/database.py
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Redis-backed storage layer for the N3MemoryCore MCP **Lite** server.
|
|
3
|
+
|
|
4
|
+
The Lite variant is deliberately ephemeral:
|
|
5
|
+
- Every entry is written with a 7d (configurable) TTL.
|
|
6
|
+
- No SQLite file, no migrations, no integrity checks.
|
|
7
|
+
- Redis Stack (RediSearch + RedisJSON) is required — the user runs
|
|
8
|
+
``docker run -p 6379:6379 redis/redis-stack-server:latest``.
|
|
9
|
+
|
|
10
|
+
Data layout
|
|
11
|
+
-----------
|
|
12
|
+
mem:<uuid> HASH the memory record
|
|
13
|
+
id string (same uuid)
|
|
14
|
+
content string original text
|
|
15
|
+
timestamp string ISO-8601 UTC
|
|
16
|
+
timestamp_epoch number unix seconds (sortable)
|
|
17
|
+
owner_id string user/tenant uuid
|
|
18
|
+
local_id string install uuid
|
|
19
|
+
agent_name string "claude" / "user" / ""
|
|
20
|
+
session_id string per-process uuid
|
|
21
|
+
embedding bytes float32 * 768 (little-endian)
|
|
22
|
+
|
|
23
|
+
mem:sha:<sha1> STRING value = mem id (exact-duplicate guard,
|
|
24
|
+
same TTL)
|
|
25
|
+
|
|
26
|
+
n3mc_idx RediSearch index over the mem:* prefix
|
|
27
|
+
|
|
28
|
+
Both keys are deleted automatically by Redis once their TTL expires; no
|
|
29
|
+
background cleanup is required.
|
|
30
|
+
"""
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import hashlib
|
|
34
|
+
import re
|
|
35
|
+
import struct
|
|
36
|
+
import time
|
|
37
|
+
from datetime import datetime, timezone
|
|
38
|
+
from typing import Any, Optional
|
|
39
|
+
|
|
40
|
+
from redis import Redis
|
|
41
|
+
from redis.commands.search.field import (
|
|
42
|
+
NumericField,
|
|
43
|
+
TagField,
|
|
44
|
+
TextField,
|
|
45
|
+
VectorField,
|
|
46
|
+
)
|
|
47
|
+
try: # redis-py >= 6: snake_case module
|
|
48
|
+
from redis.commands.search.index_definition import IndexDefinition, IndexType
|
|
49
|
+
except ImportError: # redis-py <= 5: legacy camelCase module
|
|
50
|
+
from redis.commands.search.indexDefinition import IndexDefinition, IndexType # type: ignore
|
|
51
|
+
from redis.commands.search.query import Query
|
|
52
|
+
from redis.exceptions import ResponseError
|
|
53
|
+
|
|
54
|
+
# ---------------------------------------------------------------------------
|
|
55
|
+
# Constants
|
|
56
|
+
# ---------------------------------------------------------------------------
|
|
57
|
+
INDEX_NAME = "n3mc_idx"
|
|
58
|
+
KEY_PREFIX = "mem:"
|
|
59
|
+
HASH_PREFIX = "mem:sha:"
|
|
60
|
+
VECTOR_DIM = 768
|
|
61
|
+
|
|
62
|
+
# RediSearch query special characters that must be escaped in user input.
|
|
63
|
+
# https://redis.io/docs/interact/search-and-query/advanced-concepts/escaping/
|
|
64
|
+
_FTS_SPECIAL_RE = re.compile(r'([,\.<>\{\}\[\]"\':;!@#\$%\^&\*\(\)\-\+=~\|\\/?])')
|
|
65
|
+
|
|
66
|
+
# A soft punctuation stripper for the user's query text (keeps letters /
|
|
67
|
+
# digits / whitespace / CJK). We strip first and escape what remains.
|
|
68
|
+
_PUNCT_STRIP_RE = re.compile(r'[,\.<>\{\}\[\]"\':;!@#\$%\^&\*\(\)\-\+=~\|\\/?`]')
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# ---------------------------------------------------------------------------
|
|
72
|
+
# Client / index setup
|
|
73
|
+
# ---------------------------------------------------------------------------
|
|
74
|
+
def get_redis_client(url: str) -> Redis:
|
|
75
|
+
"""Construct a Redis client for the given URL (decode_responses=False)."""
|
|
76
|
+
# decode_responses=False because embeddings are raw bytes.
|
|
77
|
+
return Redis.from_url(url, decode_responses=False)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def ensure_index(client: Redis) -> None:
|
|
81
|
+
"""Create the RediSearch index if it does not already exist."""
|
|
82
|
+
schema = (
|
|
83
|
+
TextField("content", weight=1.0),
|
|
84
|
+
NumericField("timestamp_epoch", sortable=True),
|
|
85
|
+
TagField("owner_id"),
|
|
86
|
+
TagField("local_id"),
|
|
87
|
+
TagField("agent_name"),
|
|
88
|
+
TagField("session_id"),
|
|
89
|
+
VectorField(
|
|
90
|
+
"embedding",
|
|
91
|
+
"FLAT",
|
|
92
|
+
{
|
|
93
|
+
"TYPE": "FLOAT32",
|
|
94
|
+
"DIM": VECTOR_DIM,
|
|
95
|
+
"DISTANCE_METRIC": "COSINE",
|
|
96
|
+
},
|
|
97
|
+
),
|
|
98
|
+
)
|
|
99
|
+
definition = IndexDefinition(prefix=[KEY_PREFIX], index_type=IndexType.HASH)
|
|
100
|
+
try:
|
|
101
|
+
client.ft(INDEX_NAME).create_index(schema, definition=definition)
|
|
102
|
+
except ResponseError as e:
|
|
103
|
+
if "already exists" in str(e).lower():
|
|
104
|
+
return
|
|
105
|
+
raise
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def ping(client: Redis) -> bool:
|
|
109
|
+
try:
|
|
110
|
+
return bool(client.ping())
|
|
111
|
+
except Exception:
|
|
112
|
+
return False
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
# ---------------------------------------------------------------------------
|
|
116
|
+
# Vector serialization
|
|
117
|
+
# ---------------------------------------------------------------------------
|
|
118
|
+
def vector_to_bytes(vec: list[float]) -> bytes:
|
|
119
|
+
"""Pack a Python float list as little-endian FLOAT32 bytes."""
|
|
120
|
+
return struct.pack(f"<{len(vec)}f", *vec)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def bytes_to_vector(b: bytes) -> list[float]:
|
|
124
|
+
n = len(b) // 4
|
|
125
|
+
return list(struct.unpack(f"<{n}f", b))
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# ---------------------------------------------------------------------------
|
|
129
|
+
# Text helpers
|
|
130
|
+
# ---------------------------------------------------------------------------
|
|
131
|
+
def strip_fts_punctuation(text: str) -> str:
|
|
132
|
+
"""Collapse punctuation for BM25-style tokenization."""
|
|
133
|
+
return _PUNCT_STRIP_RE.sub(" ", text)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _escape_redis_query(text: str) -> str:
|
|
137
|
+
"""Backslash-escape RediSearch special chars in a user query string."""
|
|
138
|
+
return _FTS_SPECIAL_RE.sub(r"\\\1", text)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _escape_tag(value: str) -> str:
|
|
142
|
+
"""Escape a TAG value for use inside ``@field:{value}`` expressions."""
|
|
143
|
+
return re.sub(
|
|
144
|
+
r'([ ,\.<>\{\}\[\]"\':;!@#\$%\^&\*\(\)\-\+=~\|\\/?])', r"\\\1", value
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def sha1_of(text: str) -> str:
|
|
149
|
+
return hashlib.sha1(text.encode("utf-8")).hexdigest()
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
# ---------------------------------------------------------------------------
|
|
153
|
+
# Core CRUD
|
|
154
|
+
# ---------------------------------------------------------------------------
|
|
155
|
+
def insert_memory(
|
|
156
|
+
client: Redis,
|
|
157
|
+
record_id: str,
|
|
158
|
+
content: str,
|
|
159
|
+
timestamp: str,
|
|
160
|
+
owner_id: str,
|
|
161
|
+
embedding: Optional[list[float]],
|
|
162
|
+
local_id: Optional[str] = None,
|
|
163
|
+
agent_name: Optional[str] = None,
|
|
164
|
+
session_id: Optional[str] = None,
|
|
165
|
+
ttl_seconds: int = 604800,
|
|
166
|
+
) -> None:
|
|
167
|
+
"""Insert a memory record with TTL. Embedding is required for vector search."""
|
|
168
|
+
try:
|
|
169
|
+
ts_dt = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
|
|
170
|
+
if ts_dt.tzinfo is None:
|
|
171
|
+
ts_dt = ts_dt.replace(tzinfo=timezone.utc)
|
|
172
|
+
ts_epoch = ts_dt.timestamp()
|
|
173
|
+
except Exception:
|
|
174
|
+
ts_epoch = time.time()
|
|
175
|
+
|
|
176
|
+
mapping: dict[str, Any] = {
|
|
177
|
+
"id": record_id,
|
|
178
|
+
"content": content,
|
|
179
|
+
"timestamp": timestamp,
|
|
180
|
+
"timestamp_epoch": ts_epoch,
|
|
181
|
+
"owner_id": owner_id or "",
|
|
182
|
+
"local_id": local_id or "",
|
|
183
|
+
"agent_name": agent_name or "",
|
|
184
|
+
"session_id": session_id or "",
|
|
185
|
+
}
|
|
186
|
+
if embedding is not None:
|
|
187
|
+
mapping["embedding"] = vector_to_bytes(embedding)
|
|
188
|
+
|
|
189
|
+
key = f"{KEY_PREFIX}{record_id}"
|
|
190
|
+
pipe = client.pipeline()
|
|
191
|
+
pipe.hset(key, mapping=mapping)
|
|
192
|
+
pipe.expire(key, ttl_seconds)
|
|
193
|
+
|
|
194
|
+
sha_key = f"{HASH_PREFIX}{sha1_of(content)}"
|
|
195
|
+
pipe.set(sha_key, record_id, ex=ttl_seconds)
|
|
196
|
+
pipe.execute()
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def delete_memory(client: Redis, record_id: str) -> bool:
|
|
200
|
+
"""Delete a memory record and its sha1 guard. Returns True if it existed."""
|
|
201
|
+
key = f"{KEY_PREFIX}{record_id}"
|
|
202
|
+
content = client.hget(key, "content")
|
|
203
|
+
if content is None:
|
|
204
|
+
return False
|
|
205
|
+
pipe = client.pipeline()
|
|
206
|
+
pipe.delete(key)
|
|
207
|
+
if isinstance(content, bytes):
|
|
208
|
+
try:
|
|
209
|
+
content_str = content.decode("utf-8")
|
|
210
|
+
except Exception:
|
|
211
|
+
content_str = ""
|
|
212
|
+
else:
|
|
213
|
+
content_str = content
|
|
214
|
+
if content_str:
|
|
215
|
+
pipe.delete(f"{HASH_PREFIX}{sha1_of(content_str)}")
|
|
216
|
+
results = pipe.execute()
|
|
217
|
+
return bool(results and results[0])
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def check_exact_duplicate(client: Redis, content: str) -> bool:
|
|
221
|
+
"""O(1) exact-content duplicate check."""
|
|
222
|
+
return bool(client.exists(f"{HASH_PREFIX}{sha1_of(content)}"))
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def count_memories(client: Redis, owner_id: Optional[str] = None) -> int:
|
|
226
|
+
"""Total memory count (optionally filtered by owner)."""
|
|
227
|
+
q_str = "*"
|
|
228
|
+
if owner_id:
|
|
229
|
+
q_str = f"@owner_id:{{{_escape_tag(owner_id)}}}"
|
|
230
|
+
q = Query(q_str).no_content().paging(0, 0).dialect(2)
|
|
231
|
+
res = client.ft(INDEX_NAME).search(q)
|
|
232
|
+
return int(res.total)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def get_all_memories(
|
|
236
|
+
client: Redis,
|
|
237
|
+
limit: int = 20,
|
|
238
|
+
owner_id: Optional[str] = None,
|
|
239
|
+
) -> list[dict]:
|
|
240
|
+
"""Return the most recent memories, newest first."""
|
|
241
|
+
q_str = "*"
|
|
242
|
+
if owner_id:
|
|
243
|
+
q_str = f"@owner_id:{{{_escape_tag(owner_id)}}}"
|
|
244
|
+
q = (
|
|
245
|
+
Query(q_str)
|
|
246
|
+
.sort_by("timestamp_epoch", asc=False)
|
|
247
|
+
.return_fields("id", "content", "timestamp", "agent_name")
|
|
248
|
+
.paging(0, limit)
|
|
249
|
+
.dialect(2)
|
|
250
|
+
)
|
|
251
|
+
res = client.ft(INDEX_NAME).search(q)
|
|
252
|
+
rows: list[dict] = []
|
|
253
|
+
for doc in res.docs:
|
|
254
|
+
rows.append({
|
|
255
|
+
"id": _strip_key_prefix(_as_str(getattr(doc, "id", ""))),
|
|
256
|
+
"content": _as_str(getattr(doc, "content", "")),
|
|
257
|
+
"timestamp": _as_str(getattr(doc, "timestamp", "")),
|
|
258
|
+
"agent_name": _as_str(getattr(doc, "agent_name", "")),
|
|
259
|
+
})
|
|
260
|
+
return rows
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def get_memory_by_id(client: Redis, record_id: str) -> Optional[dict]:
|
|
264
|
+
"""Fetch a single memory record by id (HGETALL; embedding stripped)."""
|
|
265
|
+
key = f"{KEY_PREFIX}{record_id}"
|
|
266
|
+
raw = client.hgetall(key)
|
|
267
|
+
if not raw:
|
|
268
|
+
return None
|
|
269
|
+
out: dict[str, Any] = {}
|
|
270
|
+
for k, v in raw.items():
|
|
271
|
+
k_s = k.decode("utf-8") if isinstance(k, bytes) else k
|
|
272
|
+
if k_s == "embedding":
|
|
273
|
+
continue
|
|
274
|
+
if isinstance(v, bytes):
|
|
275
|
+
try:
|
|
276
|
+
out[k_s] = v.decode("utf-8")
|
|
277
|
+
except Exception:
|
|
278
|
+
out[k_s] = ""
|
|
279
|
+
else:
|
|
280
|
+
out[k_s] = v
|
|
281
|
+
return out
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
# ---------------------------------------------------------------------------
|
|
285
|
+
# Search
|
|
286
|
+
# ---------------------------------------------------------------------------
|
|
287
|
+
def search_vector(
|
|
288
|
+
client: Redis,
|
|
289
|
+
query_vec: list[float],
|
|
290
|
+
k: int = 50,
|
|
291
|
+
owner_id: Optional[str] = None,
|
|
292
|
+
) -> list[tuple[str, float]]:
|
|
293
|
+
"""
|
|
294
|
+
KNN vector search. Returns list of (record_id, cosine_distance).
|
|
295
|
+
|
|
296
|
+
Cosine distance is in [0, 2]; cosine similarity = 1.0 - distance.
|
|
297
|
+
"""
|
|
298
|
+
prefilter = "*"
|
|
299
|
+
if owner_id:
|
|
300
|
+
prefilter = f"@owner_id:{{{_escape_tag(owner_id)}}}"
|
|
301
|
+
|
|
302
|
+
q = (
|
|
303
|
+
Query(f"({prefilter})=>[KNN {k} @embedding $vec AS vector_distance]")
|
|
304
|
+
.sort_by("vector_distance")
|
|
305
|
+
.return_fields("id", "vector_distance")
|
|
306
|
+
.paging(0, k)
|
|
307
|
+
.dialect(2)
|
|
308
|
+
)
|
|
309
|
+
try:
|
|
310
|
+
res = client.ft(INDEX_NAME).search(
|
|
311
|
+
q, query_params={"vec": vector_to_bytes(query_vec)}
|
|
312
|
+
)
|
|
313
|
+
except ResponseError:
|
|
314
|
+
return []
|
|
315
|
+
|
|
316
|
+
out: list[tuple[str, float]] = []
|
|
317
|
+
for doc in res.docs:
|
|
318
|
+
rid = _strip_key_prefix(_as_str(getattr(doc, "id", "")))
|
|
319
|
+
dist_raw = getattr(doc, "vector_distance", None)
|
|
320
|
+
try:
|
|
321
|
+
dist = float(_as_str(dist_raw)) if dist_raw is not None else 2.0
|
|
322
|
+
except Exception:
|
|
323
|
+
dist = 2.0
|
|
324
|
+
if rid:
|
|
325
|
+
out.append((rid, dist))
|
|
326
|
+
return out
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def search_fts(
|
|
330
|
+
client: Redis,
|
|
331
|
+
query: str,
|
|
332
|
+
limit: int = 50,
|
|
333
|
+
owner_id: Optional[str] = None,
|
|
334
|
+
) -> list[tuple[str, float]]:
|
|
335
|
+
"""
|
|
336
|
+
BM25 text search over the ``content`` field.
|
|
337
|
+
|
|
338
|
+
Returns list of (record_id, bm25_score). Higher score = more relevant
|
|
339
|
+
(RediSearch BM25 scores are already non-negative).
|
|
340
|
+
"""
|
|
341
|
+
cleaned = strip_fts_punctuation(query).strip()
|
|
342
|
+
if not cleaned:
|
|
343
|
+
return []
|
|
344
|
+
escaped = _escape_redis_query(cleaned)
|
|
345
|
+
|
|
346
|
+
if owner_id:
|
|
347
|
+
q_str = f"(@content:({escaped}) @owner_id:{{{_escape_tag(owner_id)}}})"
|
|
348
|
+
else:
|
|
349
|
+
q_str = f"@content:({escaped})"
|
|
350
|
+
|
|
351
|
+
q = (
|
|
352
|
+
Query(q_str)
|
|
353
|
+
.scorer("BM25")
|
|
354
|
+
.with_scores()
|
|
355
|
+
.return_fields("id")
|
|
356
|
+
.paging(0, limit)
|
|
357
|
+
.dialect(2)
|
|
358
|
+
)
|
|
359
|
+
try:
|
|
360
|
+
res = client.ft(INDEX_NAME).search(q)
|
|
361
|
+
except ResponseError:
|
|
362
|
+
return []
|
|
363
|
+
|
|
364
|
+
out: list[tuple[str, float]] = []
|
|
365
|
+
for doc in res.docs:
|
|
366
|
+
rid = _strip_key_prefix(_as_str(getattr(doc, "id", "")))
|
|
367
|
+
score = float(getattr(doc, "score", 0.0) or 0.0)
|
|
368
|
+
if rid:
|
|
369
|
+
out.append((rid, score))
|
|
370
|
+
return out
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
# ---------------------------------------------------------------------------
|
|
374
|
+
# Internal helpers
|
|
375
|
+
# ---------------------------------------------------------------------------
|
|
376
|
+
def _strip_key_prefix(key: str) -> str:
|
|
377
|
+
"""Strip the ``mem:`` prefix so callers see bare record ids (uuids)."""
|
|
378
|
+
if key.startswith(KEY_PREFIX):
|
|
379
|
+
return key[len(KEY_PREFIX):]
|
|
380
|
+
return key
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _as_str(v: Any) -> str:
|
|
384
|
+
if v is None:
|
|
385
|
+
return ""
|
|
386
|
+
if isinstance(v, bytes):
|
|
387
|
+
try:
|
|
388
|
+
return v.decode("utf-8")
|
|
389
|
+
except Exception:
|
|
390
|
+
return ""
|
|
391
|
+
return str(v)
|
n3mc_mcp/instructions.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""
|
|
2
|
+
MCP server instructions — behavioral guidance delivered to the LLM client
|
|
3
|
+
during the MCP ``initialize`` handshake.
|
|
4
|
+
|
|
5
|
+
These instructions implement the "auto-save" strategy: the client is told
|
|
6
|
+
to call ``search_memory`` at the start of each turn and ``save_memory``
|
|
7
|
+
after each meaningful exchange.
|
|
8
|
+
|
|
9
|
+
The Lite build's storage is **ephemeral** (Redis with 7d TTL), so the
|
|
10
|
+
instructions emphasise that expectation to the LLM client.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
SERVER_INSTRUCTIONS = """\
|
|
14
|
+
N3MemoryCore — Lite (Ephemeral Memory)
|
|
15
|
+
|
|
16
|
+
This MCP server gives you hybrid-search memory (vector + BM25) backed by
|
|
17
|
+
Redis Stack. It is the free *Lite* build of N3MemoryCore: every entry
|
|
18
|
+
expires 7 days after it was saved. Treat it as a short-lived scratchpad,
|
|
19
|
+
not a long-term store.
|
|
20
|
+
|
|
21
|
+
BEHAVIORAL RULES
|
|
22
|
+
================
|
|
23
|
+
|
|
24
|
+
1. SEARCH FIRST
|
|
25
|
+
At the start of every user turn, call `search_memory` with a concise
|
|
26
|
+
representation of the user's intent (key nouns + verbs). Use the
|
|
27
|
+
returned snippets as context when formulating your answer. Do this
|
|
28
|
+
silently — do not announce the search.
|
|
29
|
+
|
|
30
|
+
2. SAVE AFTER EACH EXCHANGE
|
|
31
|
+
After completing a meaningful response, call `save_memory` to persist:
|
|
32
|
+
- The user's intent / question (short paraphrase, not verbatim)
|
|
33
|
+
- Your key conclusions, decisions, or facts established
|
|
34
|
+
Keep each saved entry short (50-200 characters). Use one `save_memory`
|
|
35
|
+
call per distinct fact. Remember: entries vanish after 7 days.
|
|
36
|
+
|
|
37
|
+
3. EXTRACT FROM LONG PASTES
|
|
38
|
+
When the user pastes a long text (spec, article, log, code dump), do
|
|
39
|
+
NOT save it as one blob. Read it, extract each key fact as a short
|
|
40
|
+
sentence, and call `save_memory` once per fact.
|
|
41
|
+
|
|
42
|
+
4. DO NOT SAVE NOISE
|
|
43
|
+
Skip trivial greetings, clarifying questions, and mechanical
|
|
44
|
+
acknowledgements. Save substantive content only: facts, decisions,
|
|
45
|
+
user preferences, project context, unresolved questions.
|
|
46
|
+
|
|
47
|
+
5. RESPECT EXPLICIT REQUESTS
|
|
48
|
+
If the user says "don't save this" or "forget that", comply — call
|
|
49
|
+
`delete_memory` when asked to forget specific entries.
|
|
50
|
+
|
|
51
|
+
OPERATIONAL NOTES
|
|
52
|
+
=================
|
|
53
|
+
- Storage is ephemeral: 7d TTL per entry; nothing survives a fresh
|
|
54
|
+
Redis container.
|
|
55
|
+
- Exact and semantic duplicates are auto-rejected by the server.
|
|
56
|
+
- Search ranks by: 0.7 * cosine_similarity + 0.3 * BM25, decayed by age.
|
|
57
|
+
- The server is local — Redis runs on the user's machine (no cloud).
|
|
58
|
+
- For durable memory, the user can upgrade to the paid SQLite-backed
|
|
59
|
+
N3MemoryCore build.
|
|
60
|
+
"""
|
n3mc_mcp/paths.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Path resolution for the N3MemoryCore MCP **Lite** server.
|
|
3
|
+
|
|
4
|
+
Lite is ephemeral (Redis-backed, 7d TTL) and therefore owns no database
|
|
5
|
+
file. Only the local ``config.json`` (owner_id / local_id / ranking
|
|
6
|
+
parameters / Redis URL) lives on disk.
|
|
7
|
+
|
|
8
|
+
Default location:
|
|
9
|
+
- Windows: %LOCALAPPDATA%\\n3memorycore-lite
|
|
10
|
+
- macOS: ~/Library/Application Support/n3memorycore-lite
|
|
11
|
+
- Linux: ~/.local/share/n3memorycore-lite
|
|
12
|
+
|
|
13
|
+
Override via the environment variable ``N3MC_DATA_DIR``.
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import os
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from platformdirs import user_data_dir
|
|
21
|
+
|
|
22
|
+
_APP_NAME = "n3memorycore-lite"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def data_dir() -> Path:
|
|
26
|
+
"""Return the directory that holds the local config file."""
|
|
27
|
+
override = os.environ.get("N3MC_DATA_DIR")
|
|
28
|
+
if override:
|
|
29
|
+
p = Path(override).expanduser().resolve()
|
|
30
|
+
else:
|
|
31
|
+
p = Path(user_data_dir(_APP_NAME, appauthor=False))
|
|
32
|
+
p.mkdir(parents=True, exist_ok=True)
|
|
33
|
+
return p
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def config_path() -> Path:
|
|
37
|
+
return data_dir() / "config.json"
|