-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.py
More file actions
722 lines (622 loc) · 28.1 KB
/
server.py
File metadata and controls
722 lines (622 loc) · 28.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
#!/usr/bin/env python3
"""SQLite-backed MCP Memory Server — Core Knowledge Graph (9 tools).
Production-quality persistent memory with WAL concurrent safety,
FTS5 BM25-ranked search. Tools 1-9: entity/observation/relation CRUD,
read_graph, search_nodes, open_nodes.
Other tools split into domain micro-servers (session, bridge, collab,
entity, intel) to stay under Claude Code's ~9 tool visibility limit.
"""
from __future__ import annotations
import json
import sqlite3
from pathlib import Path
from typing import Any
from fastmcp_compat import FastMCP
from db_utils import (
get_conn as _get_conn,
get_entity_id as _get_entity_id,
fts_query as _fts_query,
VISIBILITY_LEVELS as _VISIBILITY_LEVELS,
now_iso as _now,
fts_sync_entity as _fts_sync,
serialize_entity as _serialize_entity,
setup_logger,
export_relations as _export_relations,
record_memory_event,
)
# Optional vector search (graceful fallback to FTS5-only)
try:
from vec_search import (
VEC_AVAILABLE as _VEC_AVAILABLE,
vec_sync_entity as _vec_sync,
vec_remove_entity as _vec_remove,
vector_search as _vector_search,
rrf_merge as _rrf_merge,
)
except ImportError:
_VEC_AVAILABLE = False
# ── Logging setup (file-only, NEVER stdout — breaks MCP stdio) ──────────
logger = setup_logger("sqlite-kb", "server.log")
# ── FastMCP app ──────────────────────────────────────────────────────────
mcp = FastMCP(
"sqlite-kb",
instructions=(
"Core knowledge graph tools: create/read/delete entities, "
"observations, relations. FTS5 BM25-ranked search."
),
)
# ── FTS helpers ──────────────────────────────────────────────────────────
def _fts_remove(conn, entity_id: int) -> None:
"""Remove entity from FTS index."""
conn.execute("DELETE FROM memory_fts WHERE rowid = ?", (entity_id,))
# ── One-time JSONL migration ────────────────────────────────────────────
def _migrate_jsonl() -> None:
"""One-time migration from the old @modelcontextprotocol memory.json JSONL format."""
json_path = Path.home() / ".claude" / "memory" / "memory.json"
if not json_path.exists():
return
logger.info("Migrating from %s", json_path)
entities: list[dict] = []
relations: list[dict] = []
try:
with open(json_path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
obj = json.loads(line)
obj_type = obj.get("type", "")
if obj_type == "entity":
entities.append(obj)
elif obj_type == "relation":
relations.append(obj)
except (json.JSONDecodeError, OSError) as exc:
logger.error("Migration parse error: %s", exc)
return
now = _now()
with _get_conn() as conn:
for ent in entities:
conn.execute(
"INSERT OR IGNORE INTO entities (name, entity_type, created_at, updated_at) "
"VALUES (?, ?, ?, ?)",
(ent["name"], ent.get("entityType", "unknown"), now, now),
)
eid = _get_entity_id(conn, ent["name"])
if eid:
for obs in ent.get("observations", []):
conn.execute(
"INSERT OR IGNORE INTO observations (entity_id, content, created_at) "
"VALUES (?, ?, ?)",
(eid, obs, now),
)
_fts_sync(conn, eid)
for rel in relations:
from_id = _get_entity_id(conn, rel["from"])
to_id = _get_entity_id(conn, rel["to"])
if from_id and to_id:
conn.execute(
"INSERT OR IGNORE INTO relations "
"(from_id, to_id, relation_type, created_at) VALUES (?, ?, ?, ?)",
(from_id, to_id, rel.get("relationType", "related_to"), now),
)
migrated_path = json_path.with_suffix(".json.migrated")
json_path.rename(migrated_path)
logger.info(
"Migration complete: %d entities, %d relations. Old file → %s",
len(entities),
len(relations),
migrated_path,
)
# ═══════════════════════════════════════════════════════════════════════════
# Tool 1: create_entities
# ═══════════════════════════════════════════════════════════════════════════
@mcp.tool()
def create_entities(entities: list[dict[str, Any]]) -> str:
"""Create new entities in the knowledge graph.
Each entity dict has: name (str), entityType (str), observations (list[str]).
Optional: project (str). Duplicates are silently ignored.
"""
now = _now()
created = 0
with _get_conn() as conn:
for ent in entities:
name = ent["name"]
etype = ent["entityType"]
project = ent.get("project")
observations = ent.get("observations", [])
vis = ent.get("visibility", "private")
if vis not in _VISIBILITY_LEVELS:
vis = "private"
cur = conn.execute(
"INSERT OR IGNORE INTO entities "
"(name, entity_type, project, visibility, created_at, updated_at) "
"VALUES (?, ?, ?, ?, ?, ?)",
(name, etype, project, vis, now, now),
)
if cur.rowcount > 0:
created += 1
eid = _get_entity_id(conn, name)
if eid:
if cur.rowcount > 0:
record_memory_event(
conn,
event_type="entity_create",
aggregate_kind="entity",
aggregate_id=str(eid),
tool_name="sqlite-kb.create_entities",
event_ts=now,
new_value={
"name": name,
"entity_type": etype,
"project": project,
"visibility": vis,
},
source_kind="entity",
source_ref=str(eid),
)
if project is not None and cur.rowcount == 0:
conn.execute(
"UPDATE entities SET project = ?, updated_at = ? "
"WHERE id = ? AND (project IS NULL OR project != ?)",
(project, now, eid, project),
)
new_obs_ids: list[tuple[int, str]] = []
for obs in observations:
cur_obs = conn.execute(
"INSERT OR IGNORE INTO observations "
"(entity_id, content, created_at) VALUES (?, ?, ?)",
(eid, obs, now),
)
if cur_obs.rowcount > 0:
new_obs_ids.append((cur_obs.lastrowid, obs))
record_memory_event(
conn,
event_type="observation_add",
aggregate_kind="observation",
aggregate_id=str(cur_obs.lastrowid),
tool_name="sqlite-kb.create_entities",
event_ts=now,
new_value={"entity_id": eid, "content": obs},
source_kind="entity",
source_ref=str(eid),
source_excerpt=obs[:300],
)
_fts_sync(conn, eid)
if _VEC_AVAILABLE:
try:
_vec_sync(conn, eid)
except Exception:
pass
if new_obs_ids:
try:
from lazy_enrichment import extract_inline_claims
for obs_id, obs_text in new_obs_ids:
extract_inline_claims(conn, eid, obs_id, obs_text)
except (ImportError, sqlite3.OperationalError):
pass
logger.info(
"create_entities: %d created out of %d requested", created, len(entities)
)
return json.dumps({"created": created, "total_requested": len(entities)})
# ═══════════════════════════════════════════════════════════════════════════
# Tool 2: add_observations
# ═══════════════════════════════════════════════════════════════════════════
@mcp.tool()
def add_observations(observations: list[dict[str, Any]]) -> str:
"""Add new observations to existing entities.
Each dict has: entityName (str), contents (list[str]).
Duplicate observations are silently ignored.
"""
now = _now()
added = 0
with _get_conn() as conn:
for item in observations:
entity_name = item["entityName"]
eid = _get_entity_id(conn, entity_name)
if eid is None:
logger.warning("add_observations: entity %r not found", entity_name)
continue
contents = item.get("contents", [])
for content in contents:
cur = conn.execute(
"INSERT OR IGNORE INTO observations "
"(entity_id, content, created_at) VALUES (?, ?, ?)",
(eid, content, now),
)
added += cur.rowcount
if cur.rowcount > 0:
record_memory_event(
conn,
event_type="observation_add",
aggregate_kind="observation",
aggregate_id=str(cur.lastrowid),
tool_name="sqlite-kb.add_observations",
event_ts=now,
new_value={"entity_id": eid, "content": content},
source_kind="entity",
source_ref=str(eid),
source_excerpt=content[:300],
)
conn.execute("UPDATE entities SET updated_at = ? WHERE id = ?", (now, eid))
_fts_sync(conn, eid)
if _VEC_AVAILABLE:
try:
_vec_sync(conn, eid)
except Exception:
pass
if contents:
try:
from lazy_enrichment import extract_inline_claims
for content in contents:
obs_row = conn.execute(
"SELECT id FROM observations WHERE entity_id = ? AND content = ?",
(eid, content),
).fetchone()
if obs_row:
extract_inline_claims(conn, eid, obs_row["id"], content)
except (ImportError, sqlite3.OperationalError):
pass
logger.info("add_observations: %d observations added", added)
return json.dumps({"added": added})
# ═══════════════════════════════════════════════════════════════════════════
# Tool 3: create_relations
# ═══════════════════════════════════════════════════════════════════════════
@mcp.tool()
def create_relations(relations: list[dict[str, Any]]) -> str:
"""Create relations between entities in the knowledge graph.
Each dict has: from (str), to (str), relationType (str).
Duplicate relations are silently ignored.
"""
now = _now()
created = 0
with _get_conn() as conn:
for rel in relations:
from_name = rel["from"]
to_name = rel["to"]
rel_type = rel["relationType"]
from_id = _get_entity_id(conn, from_name)
to_id = _get_entity_id(conn, to_name)
if from_id is None or to_id is None:
logger.warning(
"create_relations: missing entity for %r -> %r", from_name, to_name
)
continue
cur = conn.execute(
"INSERT OR IGNORE INTO relations "
"(from_id, to_id, relation_type, created_at) VALUES (?, ?, ?, ?)",
(from_id, to_id, rel_type, now),
)
created += cur.rowcount
if cur.rowcount > 0:
record_memory_event(
conn,
event_type="relation_create",
aggregate_kind="relation",
aggregate_id=f"{from_id}:{rel_type}:{to_id}",
tool_name="sqlite-kb.create_relations",
event_ts=now,
new_value={
"from_id": from_id,
"to_id": to_id,
"relation_type": rel_type,
},
source_kind="entity",
source_ref=str(from_id),
)
logger.info(
"create_relations: %d created out of %d requested", created, len(relations)
)
return json.dumps({"created": created, "total_requested": len(relations)})
# ═══════════════════════════════════════════════════════════════════════════
# Tools 4-6: Delete
# ═══════════════════════════════════════════════════════════════════════════
@mcp.tool()
def delete_entities(entityNames: list[str]) -> str:
"""Delete entities and their associated observations and relations (CASCADE).
Also cleans up the FTS index.
"""
deleted = 0
now = _now()
with _get_conn() as conn:
for name in entityNames:
eid = _get_entity_id(conn, name)
if eid is None:
continue
record_memory_event(
conn,
event_type="entity_delete",
aggregate_kind="entity",
aggregate_id=str(eid),
tool_name="sqlite-kb.delete_entities",
event_ts=now,
old_value={"name": name},
source_kind="entity",
source_ref=str(eid),
)
_fts_remove(conn, eid)
if _VEC_AVAILABLE:
try:
_vec_remove(conn, eid)
except Exception:
pass
conn.execute("DELETE FROM entities WHERE id = ?", (eid,))
deleted += 1
logger.info("delete_entities: %d deleted", deleted)
return json.dumps({"deleted": deleted})
@mcp.tool()
def delete_observations(deletions: list[dict[str, Any]]) -> str:
"""Delete specific observations from entities.
Each dict has: entityName (str), observations (list[str]).
"""
deleted = 0
now = _now()
with _get_conn() as conn:
for item in deletions:
entity_name = item["entityName"]
eid = _get_entity_id(conn, entity_name)
if eid is None:
continue
for obs in item.get("observations", []):
row = conn.execute(
"SELECT id FROM observations WHERE entity_id = ? AND content = ?",
(eid, obs),
).fetchone()
cur = conn.execute(
"DELETE FROM observations WHERE entity_id = ? AND content = ?",
(eid, obs),
)
deleted += cur.rowcount
if cur.rowcount > 0 and row:
record_memory_event(
conn,
event_type="observation_delete",
aggregate_kind="observation",
aggregate_id=str(row["id"]),
tool_name="sqlite-kb.delete_observations",
event_ts=now,
old_value={"entity_id": eid, "content": obs},
source_kind="entity",
source_ref=str(eid),
source_excerpt=obs[:300],
)
_fts_sync(conn, eid)
if _VEC_AVAILABLE:
try:
_vec_sync(conn, eid)
except Exception:
pass
logger.info("delete_observations: %d deleted", deleted)
return json.dumps({"deleted": deleted})
@mcp.tool()
def delete_relations(relations: list[dict[str, Any]]) -> str:
"""Delete specific relations from the knowledge graph.
Each dict has: from (str), to (str), relationType (str).
"""
deleted = 0
now = _now()
with _get_conn() as conn:
for rel in relations:
from_id = _get_entity_id(conn, rel["from"])
to_id = _get_entity_id(conn, rel["to"])
if from_id is None or to_id is None:
continue
cur = conn.execute(
"DELETE FROM relations "
"WHERE from_id = ? AND to_id = ? AND relation_type = ?",
(from_id, to_id, rel["relationType"]),
)
deleted += cur.rowcount
if cur.rowcount > 0:
record_memory_event(
conn,
event_type="relation_delete",
aggregate_kind="relation",
aggregate_id=f"{from_id}:{rel['relationType']}:{to_id}",
tool_name="sqlite-kb.delete_relations",
event_ts=now,
old_value={
"from_id": from_id,
"to_id": to_id,
"relation_type": rel["relationType"],
},
source_kind="entity",
source_ref=str(from_id),
)
logger.info("delete_relations: %d deleted", deleted)
return json.dumps({"deleted": deleted})
# ═══════════════════════════════════════════════════════════════════════════
# Tool 7: read_graph
# ═══════════════════════════════════════════════════════════════════════════
@mcp.tool()
def read_graph(offset: int = 0, limit: int = 500) -> str:
"""Read the full knowledge graph with pagination.
Returns JSON: {entities: [{name, entityType, observations: [...]}],
relations: [{from, to, relationType}],
total: int, has_more: bool}
"""
with _get_conn() as conn:
total = (
conn.execute("SELECT COUNT(*) FROM entities").fetchone()[0]
if offset == 0
else -1
)
ent_rows = conn.execute(
"SELECT id, name, entity_type, project FROM entities ORDER BY name LIMIT ? OFFSET ?",
(limit, offset),
).fetchall()
# Batch-fetch observations for all entities on this page in one query
eids = [r[0] for r in ent_rows]
obs_by_entity: dict[int, list[str]] = {r[0]: [] for r in ent_rows}
if eids:
ph = ",".join("?" * len(eids))
obs_rows = conn.execute(
f"SELECT entity_id, content FROM observations WHERE entity_id IN ({ph}) ORDER BY entity_id, id",
eids,
).fetchall()
for entity_id, content in obs_rows:
obs_by_entity[entity_id].append(content)
entities_out = [
{
"name": name,
"entityType": entity_type,
"project": project,
"observations": obs_by_entity.get(eid, []),
}
for eid, name, entity_type, project in ent_rows
]
relations_out = _export_relations(conn)
return json.dumps(
{
"entities": entities_out,
"relations": relations_out,
"total": total,
"has_more": offset + limit < total,
}
)
# ═══════════════════════════════════════════════════════════════════════════
# Tool 8: search_nodes (FTS5 BM25)
# ═══════════════════════════════════════════════════════════════════════════
@mcp.tool()
def search_nodes(query: str, project: str | None = None) -> str:
"""Search the knowledge graph using hybrid BM25 + semantic search.
When sqlite-vec is installed, combines FTS5 keyword matching with vector
cosine similarity via Reciprocal Rank Fusion. Falls back to FTS5-only
otherwise. Results are re-ranked with 6 contextual signals (recency,
project affinity, graph proximity, richness, canonical facts, session).
"""
fts_q = _fts_query(query)
with _get_conn() as conn:
if not query.strip():
rows = conn.execute(
"SELECT e.id AS eid, e.name, e.entity_type, e.project, 0 AS rank "
"FROM entities e ORDER BY e.name LIMIT 50"
).fetchall()
else:
try:
from smart_retrieval import RERANKING_POOL_SIZE
pool_size = RERANKING_POOL_SIZE
except ImportError:
pool_size = 50
rows = conn.execute(
"SELECT memory_fts.rowid AS eid, memory_fts.name, "
"memory_fts.entity_type, e.project, memory_fts.rank "
"FROM memory_fts "
"JOIN entities e ON e.id = memory_fts.rowid "
"WHERE memory_fts MATCH ? ORDER BY memory_fts.rank LIMIT ?",
(fts_q, pool_size),
).fetchall()
# Optional: parallel vector search + RRF merge
if _VEC_AVAILABLE and query.strip():
try:
vec_rows = _vector_search(conn, query, pool_size)
if vec_rows and rows:
rows = _rrf_merge(rows, vec_rows)
elif vec_rows and not rows:
# Vector found results that FTS5 missed (semantic match)
rows = _rrf_merge([], vec_rows)
except Exception as e:
logger.debug("Vector search failed: %s", e)
if not rows:
return json.dumps({"entities": [], "query": query})
reranked = None
try:
from smart_retrieval import rerank_entities
reranked = rerank_entities(
conn,
rows,
current_project=project,
session_id=None,
query_entity_ids=None,
limit=50,
)
except (ImportError, sqlite3.OperationalError) as e:
logger.warning("Rerank failed: %s", e)
if reranked:
eids = [r["eid"] for r in reranked]
else:
eids = [r["eid"] for r in rows[:50]]
ph = ",".join("?" * len(eids))
obs_rows = conn.execute(
f"SELECT entity_id, content FROM observations "
f"WHERE entity_id IN ({ph}) ORDER BY entity_id, id",
eids,
).fetchall()
obs_by_eid: dict[int, list[str]] = {}
for o in obs_rows:
obs_by_eid.setdefault(o["entity_id"], []).append(o["content"])
results = []
if reranked:
for r in reranked:
entity: dict[str, Any] = {
"name": r["name"],
"entityType": r["entity_type"],
"observations": obs_by_eid.get(r["eid"], []),
}
if r["project"]:
entity["project"] = r["project"]
entity["_score"] = r["_score"]
results.append(entity)
else:
for r in rows[:50]:
entity = {
"name": r["name"],
"entityType": r["entity_type"],
"observations": obs_by_eid.get(r["eid"], []),
}
if r["project"]:
entity["project"] = r["project"]
results.append(entity)
now = _now()
try:
for eid in eids:
conn.execute(
"INSERT INTO entity_access_log (entity_id, tool_name, accessed_at) "
"VALUES (?, 'search_nodes', ?)",
(eid, now),
)
except sqlite3.OperationalError as e:
logger.debug("Access log write failed: %s", e)
logger.info("search_nodes: query=%r matched=%d", query, len(results))
return json.dumps({"entities": results, "query": query})
# ═══════════════════════════════════════════════════════════════════════════
# Tool 9: open_nodes
# ═══════════════════════════════════════════════════════════════════════════
@mcp.tool()
def open_nodes(names: list[str]) -> str:
"""Open specific entities and retrieve their inter-relations.
Returns the requested entities with observations and all relations
that exist between them.
"""
with _get_conn() as conn:
entities_out = []
found_ids: list[int] = []
for name in names:
row = conn.execute(
"SELECT id, name, entity_type, project FROM entities WHERE name = ?",
(name,),
).fetchone()
if row is None:
continue
found_ids.append(row["id"])
entities_out.append(_serialize_entity(conn, row))
relations_out = (
_export_relations(conn, found_ids) if len(found_ids) >= 2 else []
)
if found_ids:
now = _now()
try:
for eid in found_ids:
conn.execute(
"INSERT INTO entity_access_log (entity_id, tool_name, accessed_at) "
"VALUES (?, 'open_nodes', ?)",
(eid, now),
)
except sqlite3.OperationalError:
pass
return json.dumps({"entities": entities_out, "relations": relations_out})
# ═══════════════════════════════════════════════════════════════════════════
# Startup
# ═══════════════════════════════════════════════════════════════════════════
if __name__ == "__main__":
_migrate_jsonl()
mcp.run(transport="stdio")