-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.py
More file actions
6890 lines (6274 loc) · 245 KB
/
Copy pathserver.py
File metadata and controls
6890 lines (6274 loc) · 245 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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Engram 1.0.0 — MCP Server
Provides semantic memory tools to AI agents via the Model Context Protocol.
Three-tier retrieval pattern (agents should follow this):
1. search_memories(query) / search_memories_text(query)
→ scored snippets, identify key + chunk_id
2. retrieve_chunk(key, chunk_id) / retrieve_chunk_text(key, chunk_id)
→ one relevant section, usually sufficient
3. retrieve_memory(key) / retrieve_memory_text(key)
→ full content, use sparingly
"""
import asyncio
import json
import os
import re
import subprocess
import sys
import time
from contextvars import ContextVar
from ipaddress import ip_address
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
from core.memory_os.runtime_paths import resolve_data_root
os.environ.setdefault("ENGRAM_DATA_DIR", str(resolve_data_root()))
from fastmcp import FastMCP
from core.chunk_preview import preview_memory_chunks as build_chunk_preview
from core.codebase_mapper import codebase_mapping_manager
from core.context_builder import build_context_receipt, make_filters, merge_graph_candidates
from core.context_compiler import (
build_handoff_packet,
build_context_query,
compile_context_packet,
get_context_profile,
list_context_profiles as build_context_profile_catalog,
)
from core.document_intelligence import (
list_document_extractors as build_document_extractor_catalog,
prepare_document_draft as build_document_draft,
prepare_document_extraction_request as build_document_extraction_request,
prepare_document_extraction_result as build_document_extraction_result,
prepare_document_understanding_packet as build_document_understanding_packet,
prepare_document_promotion_transaction as build_document_promotion_transaction,
prepare_visual_extraction_request as build_visual_extraction_request,
preview_document_extraction as build_document_extraction_preview,
preview_visual_extraction as build_visual_extraction_preview,
)
from core.document_coverage_workbench import (
prepare_document_coverage_workbench as build_document_coverage_workbench,
)
from core.document_extractors import prepare_document_disassembly as build_document_disassembly
from core.document_intake_workflow import prepare_document_intake_review as build_document_intake_review
from core.embedder import embedder
from core.engramd_client import EngramDaemonClient, EngramDaemonClientError, normalize_daemon_base_url
from core.graph_backend_status import build_graph_backend_status
from core.graph_manager import graph_manager
from core.hybrid_retrieval import normalize_retrieval_mode
from core.ingestion_pipelines import list_ingestion_pipelines as build_ingestion_pipeline_catalog
from core.memory_manager import (
memory_manager,
DuplicateMemoryError,
_config,
is_chroma_availability_error,
)
from core.memory_os.capability_discovery import build_capability_catalog
from core.memory_os.memory_guardrails import evaluate_memory_write
from core.memory_os_migration import MemoryOSMigrationKernel, run_round_trip_check
from core.memory_quality import audit_memory_quality as build_memory_quality_audit
from core.mcp.backend_tools import (
graph_backend_status_payload as build_graph_backend_status_payload,
retrieval_backend_status_payload as build_retrieval_backend_status_payload,
)
from core.mcp.document_tools import (
prepare_document_artifact_store_payload as build_document_artifact_store_payload,
prepare_document_intake_review_payload as build_document_intake_review_payload,
)
from core.mcp.knowledge_tools import query_knowledge_payload
from core.mcp.tool_registry import (
build_memory_protocol_sections,
full_server_daemon_routed_tools,
)
from core.network_exposure import PublicBindDenied, validate_raw_service_bind
from core.operation_log import operation_log
from core.project_capsule import build_project_capsule_draft
from core.reliability_harness import run_agent_reliability_harness
from core.retrieval_backend_status import build_retrieval_backend_status
from core.retrieval_eval import run_retrieval_eval
from core.session_pins import SessionPinStore
from core.server_cli import ServerCliDependencies, run_server_cli
from core.source_intake import source_intake_manager
from core.source_connectors import preview_source_connector as build_source_connector_preview
from core.source_connectors import preview_document_source_connector as build_document_source_connector_preview
from core.tool_payloads import (
build_list_error_payload,
build_list_payload,
build_search_error_payload,
build_search_payload,
MemoryListPayload,
MemoryProtocolPayload,
render_list_payload,
render_search_payload,
SearchPayload,
)
from core.usage_meter import usage_meter
from core.workflow_templates import list_workflow_templates as build_workflow_templates
mcp = FastMCP("engram")
session_pin_store = SessionPinStore()
PRODUCT_NAME = "Engram"
PRODUCT_VERSION = "1.0.0"
PRODUCT_RELEASE_TRACK = "1.0"
PRODUCT_STABILITY = "stable"
PROTOCOL_VERSION = 2
PROTOCOL_SCHEMA_VERSION = "2026-04-27"
DEFAULT_SSE_HOST = "127.0.0.1"
DEFAULT_DAEMON_URL = "http://127.0.0.1:8765"
DAEMON_STATUS_SCHEMA_VERSION = "2026-05-12.daemon-status.v1"
_USAGE_METERING_ENABLED: ContextVar[bool] = ContextVar(
"engram_usage_metering_enabled",
default=True,
)
def _daemon_url() -> str | None:
configured = os.environ.get("ENGRAM_DAEMON_URL", "").strip()
return configured.rstrip("/") or None
def _normalize_daemon_url(value: str | None) -> str | None:
if value is None:
return None
normalized = value.strip()
if not normalized:
return None
return normalize_daemon_base_url(normalized)
def _mcp_env(daemon_url: str | None = None) -> dict[str, str]:
env = {"ENGRAM_DATA_DIR": str(resolve_data_root())}
normalized_daemon_url = _normalize_daemon_url(daemon_url)
if normalized_daemon_url is not None:
env["ENGRAM_DAEMON_URL"] = normalized_daemon_url
return env
def _daemon_enabled() -> bool:
return _daemon_url() is not None
def _configured_data_dir() -> Path:
configured = os.environ.get("ENGRAM_DATA_DIR", "").strip()
if configured:
return Path(configured).expanduser().resolve()
return Path(_mcp_env()["ENGRAM_DATA_DIR"]).resolve()
def _daemon_autostart_enabled() -> bool:
configured = os.environ.get("ENGRAM_DAEMON_AUTOSTART", "1").strip().lower()
return configured not in {"0", "false", "no", "off", "disabled"}
def _daemon_autostart_timeout_seconds() -> float:
configured = os.environ.get("ENGRAM_DAEMON_AUTOSTART_TIMEOUT", "12").strip()
try:
return max(float(configured), 0.1)
except ValueError:
return 12.0
def _daemon_autostart_poll_seconds() -> float:
configured = os.environ.get("ENGRAM_DAEMON_AUTOSTART_POLL_SECONDS", "0.25").strip()
try:
return min(max(float(configured), 0.05), 2.0)
except ValueError:
return 0.25
def _is_loopback_daemon_url(url: str) -> bool:
parsed = urlparse(url)
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
return False
hostname = parsed.hostname
if hostname.lower() == "localhost":
return True
try:
return ip_address(hostname).is_loopback
except ValueError:
return False
def _daemon_host_port(url: str) -> tuple[str, int]:
parsed = urlparse(url)
host = parsed.hostname or "127.0.0.1"
port = parsed.port
if port is None:
port = urlparse(DEFAULT_DAEMON_URL).port or 8765
return host, port
def _daemon_client() -> EngramDaemonClient:
url = _daemon_url()
if url is None:
raise EngramDaemonClientError("ENGRAM_DAEMON_URL is not configured")
return EngramDaemonClient(url)
def _probe_daemon_health() -> dict[str, Any]:
return _daemon_client().health()
def _sleep_for_daemon_start(seconds: float) -> None:
time.sleep(seconds)
def _start_local_daemon_process(url: str) -> dict[str, Any]:
host, port = _daemon_host_port(url)
repo_root = Path(__file__).resolve().parent
data_dir = _configured_data_dir()
log_dir = data_dir / "operations"
log_dir.mkdir(parents=True, exist_ok=True)
log_path = log_dir / "engramd-autostart.log"
env = os.environ.copy()
env["ENGRAM_DATA_DIR"] = str(data_dir)
args = [
sys.executable,
str((repo_root / "engramd.py").resolve()),
"--host",
host,
"--port",
str(port),
]
creationflags = 0
popen_kwargs: dict[str, Any] = {}
if os.name == "nt":
creationflags = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
creationflags |= getattr(subprocess, "DETACHED_PROCESS", 0)
popen_kwargs["creationflags"] = creationflags
else:
popen_kwargs["start_new_session"] = True
with log_path.open("a", encoding="utf-8") as log_file:
process = subprocess.Popen( # nosec B603
args,
cwd=str(repo_root),
env=env,
stdin=subprocess.DEVNULL,
stdout=log_file,
stderr=log_file,
**popen_kwargs,
)
return {"pid": process.pid, "log_path": str(log_path)}
def _daemon_startup_payload(
*,
reachable: bool,
health: dict[str, Any] | None,
autostart: dict[str, Any],
error: Exception | str | None = None,
) -> dict[str, Any]:
message = str(error) if error is not None else None
return {
"mode": "daemon_client",
"configured_url": _daemon_url(),
"reachable": reachable,
"health": health,
"autostart": autostart,
"error": _tool_error("runtime_error", message) if message else None,
}
def _ensure_daemon_available_for_mcp() -> dict[str, Any]:
configured_url = _daemon_url()
if configured_url is None:
return {
"mode": "direct",
"configured_url": None,
"reachable": False,
"health": None,
"autostart": {"attempted": False, "reason": "not_configured"},
"error": None,
}
try:
health = _probe_daemon_health()
return _daemon_startup_payload(
reachable=True,
health=health,
autostart={"attempted": False, "reason": "already_running"},
)
except Exception as first_error:
if not _daemon_autostart_enabled():
return _daemon_startup_payload(
reachable=False,
health=None,
autostart={"attempted": False, "reason": "disabled"},
error=first_error,
)
if not _is_loopback_daemon_url(configured_url):
return _daemon_startup_payload(
reachable=False,
health=None,
autostart={"attempted": False, "reason": "not_loopback_url"},
error=first_error,
)
try:
start_payload = _start_local_daemon_process(configured_url)
except Exception as start_error:
return _daemon_startup_payload(
reachable=False,
health=None,
autostart={
"attempted": True,
"started": False,
"reason": "start_failed",
"error": str(start_error),
},
error=start_error,
)
deadline = time.monotonic() + _daemon_autostart_timeout_seconds()
last_error: Exception | str = first_error
while time.monotonic() < deadline:
_sleep_for_daemon_start(_daemon_autostart_poll_seconds())
try:
health = _probe_daemon_health()
return _daemon_startup_payload(
reachable=True,
health=health,
autostart={
"attempted": True,
"started": True,
"pid": start_payload.get("pid"),
"log_path": start_payload.get("log_path"),
},
)
except Exception as poll_error:
last_error = poll_error
return _daemon_startup_payload(
reachable=False,
health=None,
autostart={
"attempted": True,
"started": True,
"pid": start_payload.get("pid"),
"log_path": start_payload.get("log_path"),
"reason": "health_timeout",
},
error=last_error,
)
def _prepare_mcp_runtime_before_start() -> dict[str, Any]:
if _daemon_enabled():
return _ensure_daemon_available_for_mcp()
print("[Engram] Pre-loading embedding model...", file=sys.stderr)
embedder._load()
print("[Engram] Model ready.", file=sys.stderr)
print("[Engram] ChromaDB will initialize on first vector operation.", file=sys.stderr)
return {
"mode": "direct",
"configured_url": None,
"reachable": False,
"health": None,
"autostart": {"attempted": False, "reason": "direct_mode"},
"error": None,
}
async def _call_daemon(method_name: str, payload: dict[str, Any]) -> dict[str, Any]:
client = _daemon_client()
method = getattr(client, method_name)
return await asyncio.to_thread(method, payload)
async def _daemon_health() -> dict[str, Any]:
return await asyncio.to_thread(_daemon_client().health)
def _build_health_payload() -> dict[str, Any]:
if _daemon_enabled():
configured_url = _daemon_url()
try:
daemon_health = _daemon_client().health()
except Exception as exc:
return {
"product": {
"name": PRODUCT_NAME,
"version": PRODUCT_VERSION,
"release_track": PRODUCT_RELEASE_TRACK,
"stability": PRODUCT_STABILITY,
},
"status": "degraded",
"model": "daemon_owned",
"mode": "daemon_client",
"daemon_url": configured_url,
"daemon_reachable": False,
"stats": memory_manager.get_json_fallback_stats(chroma_error=str(exc)),
"error": _tool_error("runtime_error", str(exc)),
}
daemon_ok = daemon_health.get("status") == "ok" and daemon_health.get("error") is None
return {
"product": {
"name": PRODUCT_NAME,
"version": PRODUCT_VERSION,
"release_track": PRODUCT_RELEASE_TRACK,
"stability": PRODUCT_STABILITY,
},
"status": "ok" if daemon_ok else "degraded",
"model": "daemon_owned",
"mode": "daemon_client",
"daemon_url": configured_url,
"daemon_reachable": daemon_ok,
"stats": daemon_health.get("stats") or memory_manager.get_json_fallback_stats(
chroma_error="daemon did not return stats"
),
"error": daemon_health.get("error"),
}
embedder._load()
try:
memory_manager._ensure_initialized()
stats = memory_manager.get_stats()
except RuntimeError as exc:
if not is_chroma_availability_error(exc):
raise
return {
"product": {
"name": PRODUCT_NAME,
"version": PRODUCT_VERSION,
"release_track": PRODUCT_RELEASE_TRACK,
"stability": PRODUCT_STABILITY,
},
"status": "degraded",
"model": "loaded" if embedder._model is not None else "not_loaded",
"mode": "daemon_client" if _daemon_enabled() else "direct",
"stats": memory_manager.get_json_fallback_stats(chroma_error=str(exc)),
"error": _tool_error("runtime_error", str(exc)),
}
return {
"product": {
"name": PRODUCT_NAME,
"version": PRODUCT_VERSION,
"release_track": PRODUCT_RELEASE_TRACK,
"stability": PRODUCT_STABILITY,
},
"status": "ok",
"model": "loaded" if embedder._model is not None else "not_loaded",
"mode": "daemon_client" if _daemon_enabled() else "direct",
"stats": {
**stats,
"vector_index": {
"available": True,
"error": None,
},
},
"error": None,
}
def _clamp_search_limit(limit: int) -> int:
return min(max(limit, 1), 20)
def _normalize_string_list(value: Any) -> list[str]:
"""Accept comma-separated strings or list-like values as a de-duped string list."""
if value is None:
return []
raw_items: list[str] = []
if isinstance(value, str):
raw_items = value.split(",")
else:
for item in value:
raw_items.extend(str(item).split(","))
normalized: list[str] = []
seen: set[str] = set()
for item in raw_items:
text = str(item).strip()
if not text or text in seen:
continue
seen.add(text)
normalized.append(text)
return normalized
def _slugify_memory_key(value: str) -> str:
"""Create a conservative snake_case key from a title or heading."""
slug = re.sub(r"[^a-zA-Z0-9]+", "_", value.strip().lower()).strip("_")
return slug or "untitled_memory"
def _clamp_list_limit(limit: int | None) -> int:
if limit is None:
return 50
normalized = int(limit)
if normalized <= 0:
return 0
return min(max(normalized, 1), 500)
def _normalize_offset(offset: int | None) -> int:
if offset is None:
return 0
return max(int(offset), 0)
def _validate_search_query(query: str) -> str | None:
if not query or not query.strip():
return "❌ Query cannot be empty."
if len(query) > 2000:
return "❌ Query too long (max 2,000 chars). Shorten your search query."
return None
def _normalize_session_id(session_id: str | None) -> str | None:
if session_id is None:
return None
normalized = str(session_id).strip()
return normalized or None
def _normalize_memory_key(key: str) -> str:
normalized = str(key).strip()
if not normalized:
raise ValueError("key is required")
return normalized
def _pin_payload(session_id: str, pins: list[str], **extra: Any) -> dict[str, Any]:
payload = {
"session_id": session_id,
"count": len(pins),
"pins": pins,
"error": None,
}
payload.update(extra)
return payload
def _runtime_error_payload(message: str, **payload: Any) -> dict[str, Any]:
"""Attach a stable structured runtime error payload."""
data = dict(payload)
data["error"] = {
"code": "runtime_error",
"message": message,
}
return data
def _format_store_success(key: str, result: dict[str, Any]) -> str:
graph_treatment = result.get("graph_treatment") if isinstance(result.get("graph_treatment"), dict) else {}
semantic_treatment = (
result.get("semantic_graph_treatment")
if isinstance(result.get("semantic_graph_treatment"), dict)
else {}
)
graph_count = len(graph_treatment.get("graph_edges_written") or []) + len(
semantic_treatment.get("graph_edges_written") or []
)
graph_line = f"\n Graph edges: {graph_count}" if graph_count else ""
return (
f"✅ Stored: '{result['title']}'\n"
f" Key: {key}\n"
f" Chunks: {result.get('chunk_count', '?')}\n"
f" Chars: {result['chars']}"
f"{graph_line}"
)
def _format_duplicate_warning(duplicate: dict[str, Any]) -> str:
threshold = _config.get("dedup_threshold", 0.92)
return (
f"⚠️ DUPLICATE DETECTED — similar memory already exists.\n"
f" Existing key: {duplicate['existing_key']}\n"
f" Existing title: {duplicate['existing_title']}\n"
f" Similarity: {duplicate['score']:.3f} (threshold: {threshold})\n\n"
f"To store anyway, call store_memory again with force=True."
)
def _format_daemon_store_response(key: str, response: dict[str, Any]) -> str:
error = response.get("error")
if response.get("stored") is True:
return _format_store_success(key, response["result"])
if isinstance(error, dict) and error.get("code") == "duplicate":
return _format_duplicate_warning(response.get("duplicate") or {})
if isinstance(error, dict):
return f"❌ Engram error: {error.get('message') or error.get('code')}"
return f"❌ Failed to store '{key}': daemon returned an invalid response"
def _tool_error(code: str, message: str) -> dict[str, str]:
return {"code": code, "message": message}
def _repo_path(path: str | None, default: str) -> Path:
raw = Path(path or default)
if raw.is_absolute():
return raw
return Path(__file__).resolve().parent / raw
def _default_migration_work_root() -> Path:
stamp = time.strftime("%Y%m%d-%H%M%S")
return Path(__file__).resolve().parent / ".engram" / f"migration-round-trip-{stamp}-{os.getpid()}"
def _compact_migration_import_report(
report: dict[str, Any],
*,
operation: str,
legacy_dir: Path,
write_performed: bool,
include_details: bool = False,
) -> dict[str, Any]:
unsupported = report.get("unsupported_fields") or {}
payload: dict[str, Any] = {
"schema_version": report.get("schema_version"),
"operation": operation,
"legacy_dir": str(legacy_dir),
"write_performed": write_performed,
"active_memory_write_performed": False,
"dry_run": report.get("dry_run"),
"source_count": report.get("source_count", 0),
"valid_count": report.get("valid_count", 0),
"invalid_count": report.get("invalid_count", 0),
"would_import_count": report.get("would_import_count", 0),
"imported_count": report.get("imported_count", 0),
"chunk_count_total": report.get("chunk_count_total", 0),
"derived_chunk_count_total": report.get("derived_chunk_count_total", 0),
"chunk_count_mismatch_count": len(report.get("chunk_count_mismatches") or []),
"related_to_count": report.get("related_to_count", 0),
"unsupported_field_count": sum(len(fields) for fields in unsupported.values()),
"unsupported_fields": unsupported,
"field_mappings": report.get("field_mappings", {}),
"error": None,
}
if include_details:
payload["key_set"] = report.get("key_set", [])
payload["artifact_hashes"] = report.get("artifact_hashes", {})
payload["chunk_count_mismatches"] = report.get("chunk_count_mismatches", [])
payload["invalid"] = report.get("invalid", [])
return payload
def _compact_round_trip_report(
report: dict[str, Any],
*,
legacy_dir: Path,
work_root: Path,
include_details: bool = False,
) -> dict[str, Any]:
dry_run = report.get("dry_run") or {}
restore = report.get("restore") or {}
payload: dict[str, Any] = {
"schema_version": report.get("schema_version"),
"operation": "memory_os_round_trip_check",
"status": report.get("status"),
"legacy_dir": str(legacy_dir),
"work_root": str(work_root),
"write_performed": True,
"active_memory_write_performed": False,
"source_count": dry_run.get("source_count", 0),
"valid_count": dry_run.get("valid_count", 0),
"invalid_count": dry_run.get("invalid_count", 0),
"chunk_count_total": dry_run.get("chunk_count_total", 0),
"derived_chunk_count_total": dry_run.get("derived_chunk_count_total", 0),
"chunk_count_mismatch_count": dry_run.get("chunk_count_mismatch_count", 0),
"related_to_count": dry_run.get("related_to_count", 0),
"unsupported_field_count": sum(
len(fields) for fields in (dry_run.get("unsupported_fields") or {}).values()
),
"imported_count": (report.get("import") or {}).get("imported_count", 0),
"bundle_memory_count": (report.get("bundle") or {}).get("memory_count", 0),
"restored_count": restore.get("restored_count", 0),
"legacy_json_restored_count": (report.get("legacy_json_restore") or {}).get("restored_count", 0),
"parity": report.get("parity", {}),
"error": None,
}
if include_details:
payload["report"] = report
return payload
def _payload_error_message(payload: Any) -> str | None:
if not isinstance(payload, dict):
return None
error = payload.get("error")
if not error:
return None
if isinstance(error, dict):
return str(error.get("message") or error.get("code") or error)
return str(error)
def _collect_context_conflict_scans(
context_payload: dict[str, Any],
*,
enabled: bool,
) -> list[dict[str, Any]]:
"""Return compact conflict_scan payloads for selected context memory refs."""
if not enabled:
return []
scans: list[dict[str, Any]] = []
seen_keys: set[str] = set()
for chunk in context_payload.get("chunks") or []:
key = str(chunk.get("key") or "").strip()
if not key or key in seen_keys:
continue
seen_keys.add(key)
ref = {"kind": "memory", "key": key}
try:
scans.append(graph_manager.conflict_scan(ref=ref, status="active"))
except Exception as exc:
scans.append(
{
"schema_version": None,
"ref": ref,
"status": "active",
"edge_types": [],
"count": 0,
"conflicts": [],
"error": _tool_error("runtime_error", str(exc)),
}
)
return scans
def _record_usage(
tool_name: str,
input_payload: dict[str, Any],
output_payload: Any,
started_at: float,
*,
status: str = "ok",
error: str | None = None,
) -> None:
if not _USAGE_METERING_ENABLED.get():
return
try:
usage_meter.record_tool_call(
tool=tool_name,
input_payload=input_payload,
output_payload=output_payload,
status=status,
duration_ms=int((time.perf_counter() - started_at) * 1000),
error=error,
)
except Exception:
# Telemetry must never break the memory transport path.
return
def _record_usage_for_payload(
tool_name: str,
input_payload: dict[str, Any],
output_payload: Any,
started_at: float,
) -> None:
error = _payload_error_message(output_payload)
_record_usage(
tool_name,
input_payload,
output_payload,
started_at,
status="error" if error else "ok",
error=error,
)
def _record_operation_job(
*,
operation_type: str,
status: str,
result: Any | None = None,
error: str | None = None,
metadata: dict[str, Any] | None = None,
) -> None:
try:
operation_log.record_job(
operation_type=operation_type,
status=status,
result=result,
error=error,
metadata=metadata,
)
except Exception:
return
def _record_operation_event(
*,
event_type: str,
subject: dict[str, Any],
summary: str,
metadata: dict[str, Any] | None = None,
) -> None:
try:
operation_log.record_event(
event_type=event_type,
subject=subject,
summary=summary,
metadata=metadata,
)
except Exception:
return
def _retrieve_chunk_payload(result: dict | None, key: str, chunk_id: int) -> dict[str, Any]:
"""Normalize chunk retrieval output into the structured contract."""
if not result:
return {
"key": key,
"chunk_id": chunk_id,
"found": False,
"chunk": None,
"error": None,
}
chunk = {
"title": result.get("title", key),
"text": result.get("text"),
"section_title": result.get("section_title"),
"heading_path": result.get("heading_path", []),
"chunk_kind": result.get("chunk_kind"),
}
error = result.get("error")
return {
"key": key,
"chunk_id": chunk_id,
"found": bool(result.get("found", True)),
"chunk": chunk if result.get("found", True) else None,
"error": error,
}
def _retrieve_memory_payload(key: str, memory: dict | None) -> dict[str, Any]:
"""Normalize full-memory retrieval output into the structured contract."""
return {
"key": key,
"found": memory is not None,
"memory": memory,
"error": None,
}
def _render_retrieve_chunk_payload(payload: dict[str, Any]) -> str:
"""Render the structured chunk payload for legacy text-returning callers."""
error = payload.get("error")
if error is not None:
return error["message"]
if not payload.get("found"):
return f"❌ Chunk not found: key='{payload['key']}' chunk_id={payload['chunk_id']}"
chunk = payload.get("chunk") or {}
title = chunk.get("title") or payload["key"]
text = chunk.get("text") or ""
return (
f"📄 Chunk {payload['chunk_id']} from '{title}'\n"
f"🔑 Key: {payload['key']}\n\n"
f"{text}"
)
def _render_retrieve_memory_payload(payload: dict[str, Any]) -> str:
"""Render the structured full-memory payload for legacy text-returning callers."""
error = payload.get("error")
if error is not None:
return error["message"]
if not payload.get("found"):
return f"❌ Memory not found: '{payload['key']}'"
memory = payload.get("memory") or {}
tags = ", ".join(memory.get("tags", [])) or "none"
updated_at = str(memory.get("updated_at", ""))[:16]
return (
f"📦 {memory.get('title', payload['key'])}\n"
f"🔑 Key: {memory.get('key', payload['key'])}\n"
f"🏷 Tags: {tags}\n"
f"📅 Updated: {updated_at}\n"
f"📊 {memory.get('chars', '?')} chars | {memory.get('chunk_count', '?')} chunks\n\n"
f"{memory.get('content', '')}"
)
@mcp.tool()
async def memory_protocol() -> MemoryProtocolPayload:
"""
Describe the agent-facing Engram tool contract.
Call this when a client needs to discover the intended retrieval ladder,
canonical tool names, compatibility aliases, or token-safety rules.
"""
protocol_sections = build_memory_protocol_sections(include_beta=True)
return {
"name": "Engram memory protocol",
"product": {
"name": PRODUCT_NAME,
"version": PRODUCT_VERSION,
"release_track": PRODUCT_RELEASE_TRACK,
"stability": PRODUCT_STABILITY,
},
"version": PROTOCOL_VERSION,
"schema_version": PROTOCOL_SCHEMA_VERSION,
"stability": protocol_sections["stability"],
"retrieval_ladder": [
{
"step": 1,
"tool": "search_memories",
"purpose": "Find scored snippets and capture key + chunk_id references.",
},
{
"step": 2,
"tool": "retrieve_chunk",
"purpose": "Read one relevant chunk by key + chunk_id; usually sufficient.",
},
{
"step": 3,
"tool": "retrieve_memory",
"purpose": "Read the full memory only when chunks are insufficient.",
},
],
"tool_groups": protocol_sections["tool_groups"],
"progressive_discovery": protocol_sections["progressive_discovery"],
"canonical_tools": protocol_sections["canonical_tools"],
"memory_taxonomy": protocol_sections["memory_taxonomy"],
"aliases": {
"find_memories": "search_memories",
"read_chunk": "retrieve_chunk",
"read_memory": "retrieve_chunk or retrieve_memory, depending on arguments",
"write_memory": "store_memory",
},
"examples": [
"search_memories(query='scheduler bug', limit=5)",
"retrieve_chunk(key='example_project_notes', chunk_id=3)",
"context_pack(query='agent memory protocol', project='engram', max_chunks=5)",
"prepare_context(task='resume repository work', project='C:/Dev/Engram', profile='repo_resume') for a cited working packet",
"make_handoff(task='continue rebuild', project='C:/Dev/Engram', next_steps='run validation') before ending a long session",
"context_pack(query='FSInventorySubsystem', retrieval_mode='hybrid') when exact identifiers matter",
"preview_memory_chunks(content=source_text, title='Transcript review') before promoting source drafts",
"list_document_extractors() before choosing a local parser, OCR/vision adapter, or agent-native preview path",
"preview_document_source_connector(connector_type='local_path', target='docs') before document extraction",
"prepare_document_disassembly(source_path='C:/docs/book.pdf') for no-write local PDF page/text/image inventory plus visual/OCR follow-up request",
"prepare_document_coverage_workbench(source_path='C:/docs/book.pdf', visual_request=req) for no-write page-render/OCR/table coverage packets",
"prepare_document_intake_review(source_path='C:/docs/book.pdf') for the no-write review packet, coverage receipts, and next extraction request",
"prepare_document_extraction_request(source_ref={'source_uri': 'file:///notes.pdf'}, source_type='pdf', requested_outputs=['markdown', 'page_images']) before running a local parser",
"prepare_document_extraction_result(extraction_request=req, title='Notes', content=markdown, media_type='text/markdown') before preview_document_extraction",
"prepare_document_understanding_packet(document_record=doc, analysis=agent_analysis) before preparing promotion decisions",
"prepare_document_draft(document_record=doc, analysis={'decisions': ['...']}) before promoting document evidence",
"prepare_document_promotion_transaction(document_draft=draft, approved_by='agent-review') before executing writes",
"prepare_document_artifact_store(review_packet=packet) then store_document_artifact(prepared_transaction_id=txn, accept=True, review_packet=packet) for explicit ledgered document evidence",
"prepare_document_ingestion_completion(document_id=doc_id, artifact_id=artifact_id, visual_preview=preview, understanding_packet=packet, document_promotion_transaction=txn) before marking a document usable",
"complete_document_ingestion(document_id=doc_id, accept=True, approved_by='agent-review') only after full reviewed coverage and graph evidence",
"prepare_visual_extraction_request(document_record=doc, image_refs=pages, requested_capabilities=['ocr_text']) before running external OCR",
"preview_visual_extraction(document_record=doc, observations=vision_notes) before promoting image-derived claims",
"migration_dry_run(legacy_dir='data/memories') before importing the current memory corpus into a Memory OS store",
"memory_os_round_trip_check(legacy_dir='data/memories', work_root='.engram/migration-round-trip-check') for migration parity proof",
"retrieval_backend_status(store_root='.engram/migration-round-trip-check/store', include_rebuild_probe=True) before considering a retrieval backend switch",
"graph_backend_status(store_root='.engram/migration-round-trip-check/store') before considering a graph backend switch",
"daemon_status() before assuming this MCP server is using engramd daemon-client mode",
"read_memory(key='engram_protocol', full=True) only after chunks are insufficient",
],
"warnings": [
"Do not call retrieve_memory before search_memories or retrieve_chunk unless the key is already known and full content is explicitly required.",
"Prefer context_pack when you need a compact working set rather than whole memories.",
"Use retrieval_mode='hybrid' intentionally for identifier-heavy queries; semantic remains the cheaper default.",
"Use list_memories for browsing metadata, not topic lookup.",
"Codex clients may lazy-load Engram; if mcp__engram__ tools are not initially visible, use tool discovery/search for Engram before concluding it is unavailable.",
"ENGRAM_DAEMON_URL opt-in daemon mode routes stable memory tools through engramd; call daemon_status() to verify direct vs daemon-client mode.",
"For ordinary multi-session Codex memory use, server_daemon_client.py is the thin entrypoint that delegates to engramd without importing local storage/index modules.",
"ENGRAM_RETRIEVAL_BACKEND and ENGRAM_GRAPH_BACKEND are intent-only readiness signals; they do not switch live Chroma or JSON graph storage.",
"ENGRAM_DAEMON_AUTOSTART defaults on for loopback daemon-client startup; set it to 0/false/no/off to require a manually started daemon.",
"When multiple stdio Engram servers are live, only one process owns ChromaDB; secondary processes keep JSON-first writes available, and vector search/context tools return a runtime error until the owner exits.",
],
}
@mcp.tool()
async def daemon_status() -> dict[str, Any]:
"""
Report whether this MCP server is using direct storage or engramd.
`ENGRAM_DAEMON_URL` enables daemon-client mode for routed MCP tools.
`ENGRAM_DAEMON_AUTOSTART` controls startup-time loopback daemon spawning.
This status tool verifies the configured mode and, when a daemon URL is