-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver_daemon_client.py
More file actions
2243 lines (2051 loc) · 77.4 KB
/
Copy pathserver_daemon_client.py
File metadata and controls
2243 lines (2051 loc) · 77.4 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 thin daemon-client MCP server.
This entrypoint is for multi-session agent clients. It does not import the
local storage manager, ChromaDB, sentence-transformers, graph stores, or
document extractors. Every tool delegates to a loopback `engramd` daemon so one
process owns mutable Engram storage and indexes.
"""
from __future__ import annotations
import argparse
import asyncio
import os
from typing import Any
from fastmcp import FastMCP
from core.engramd_client import (
DEFAULT_DAEMON_TIMEOUT,
EngramDaemonClient,
EngramDaemonClientError,
)
from core.hub_client_config import (
build_hub_headers,
describe_hub_mode,
read_hub_client_config,
validate_hub_client_config,
)
from core.memory_os.runtime_paths import resolve_data_root
from core.mcp.tool_registry import build_memory_protocol_sections
mcp = FastMCP("engram")
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_DAEMON_URL = "http://127.0.0.1:8765"
def _daemon_url() -> str:
hub_config = read_hub_client_config()
if hub_config.get("hub_configured"):
return str(hub_config.get("hub_url") or "invalid-hub-url")
configured = os.environ.get("ENGRAM_DAEMON_URL", "").strip().rstrip("/")
return configured or DEFAULT_DAEMON_URL
def _daemon_timeout() -> float:
configured = os.environ.get("ENGRAM_DAEMON_TIMEOUT", "").strip()
if not configured:
return DEFAULT_DAEMON_TIMEOUT
try:
timeout = float(configured)
except ValueError:
return DEFAULT_DAEMON_TIMEOUT
return max(1.0, timeout)
def _daemon_client() -> EngramDaemonClient:
hub_config = read_hub_client_config()
if hub_config.get("hub_configured"):
validation = validate_hub_client_config(hub_config)
if validation.get("status") != "ready":
code = (validation.get("error") or {}).get("code") or "hub_config_invalid"
raise EngramDaemonClientError(
f"hub mode configured but unavailable before request: {code}"
)
return EngramDaemonClient(
str(hub_config.get("hub_url")),
timeout=_daemon_timeout(),
headers=build_hub_headers(hub_config),
)
return EngramDaemonClient(_daemon_url(), timeout=_daemon_timeout())
async def _call_daemon(method_name: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
client = _daemon_client()
method = getattr(client, method_name)
if payload is None:
return await asyncio.to_thread(method)
return await asyncio.to_thread(method, payload)
def _tool_error(code: str, message: str) -> dict[str, str]:
if code == "runtime_error":
hub_config = read_hub_client_config()
if hub_config.get("hub_configured"):
hub_validation = validate_hub_client_config(hub_config)
if hub_validation.get("status") != "ready":
hub_code = str(
(hub_validation.get("error") or {}).get("code")
or "hub_config_invalid"
)
return {
"code": hub_code,
"message": (
"Hub mode is configured but its client configuration is invalid. "
f"{message}"
),
}
return {
"code": "hub_unreachable",
"message": (
"Hub mode is configured and failed closed before local storage "
f"could be used. {message}"
),
}
return {"code": code, "message": message}
def _daemon_exception_message(exc: EngramDaemonClientError) -> str:
error = _tool_error("runtime_error", f"Engram daemon error: {exc}")
return f"{error['code']}: {error['message']}"
def _normalize_string_list(value: Any) -> list[str]:
if value is None:
return []
raw_items = value.split(",") if isinstance(value, str) else list(value)
result: 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)
result.append(text)
return result
def _optional_text(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None
def _format_daemon_store_response(key: str, response: dict[str, Any]) -> str:
error = response.get("error")
if error:
message = error.get("message") if isinstance(error, dict) else str(error)
return f"Failed to store '{key}': {message}"
if not response.get("stored"):
return f"Failed to store '{key}': daemon did not store memory"
result = response.get("result")
if not isinstance(result, dict):
return f"Failed to store '{key}': daemon returned an invalid response"
title = result.get("title") or key
chunk_count = result.get("chunk_count", 0)
chars = result.get("chars", 0)
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_suffix = f", {graph_count} graph edges" if graph_count else ""
return f"Stored: '{title}' ({chunk_count} chunks, {chars} chars{graph_suffix})"
@mcp.tool()
def memory_protocol() -> dict[str, Any]:
"""Describe the daemon-client Engram MCP contract for agents."""
protocol_sections = build_memory_protocol_sections(thin_client=True)
hub_config = read_hub_client_config()
hub_validation = validate_hub_client_config(hub_config)
hub_description = dict(describe_hub_mode(hub_config))
hub_description["status"] = hub_validation.get("status")
if hub_validation.get("error"):
hub_description["error"] = hub_validation.get("error")
warnings = [
"Start or autostart engramd before using this entrypoint.",
"Use daemon_status() to prove daemon reachability before blaming missing memory.",
"Use memory_os_status() to inspect the rebuilt SQLite/LanceDB/Kuzu runtime container.",
"Backend promotion remains config-gated; live storage belongs to engramd.",
]
protocol_error = None
if hub_config.get("hub_configured") and hub_validation.get("status") != "ready":
protocol_error = _tool_error(
str((hub_validation.get("error") or {}).get("code") or "hub_config_invalid"),
"Hub mode is configured but its client configuration is invalid.",
)
warnings.append(
"Hub clients fail closed until ENGRAM_HUB_ACCESS_TOKEN is configured with a valid token."
)
return {
"product": {
"name": PRODUCT_NAME,
"version": PRODUCT_VERSION,
"release_track": PRODUCT_RELEASE_TRACK,
"stability": PRODUCT_STABILITY,
},
"protocol": {
"version": PROTOCOL_VERSION,
"schema_version": PROTOCOL_SCHEMA_VERSION,
"entrypoint": "server_daemon_client.py",
"mode": "daemon_client",
},
"daemon": {
"url": _daemon_url(),
"hub_mode": hub_description,
"single_owner_rule": (
"This MCP process is a thin client. It never opens local ChromaDB, "
"Kuzu, LanceDB, memory JSON, graph JSON, or document extraction state."
),
},
"retrieval_ladder": [
"search_memories(query, limit=5) returns scored snippets and key/chunk_id refs.",
"retrieve_chunk(key, chunk_id) reads one cited chunk.",
"retrieve_memory(key) reads a full memory only when chunks are insufficient.",
],
"preferred_shortcut": "context_pack is available on the full server; this thin entrypoint keeps stable daemon-owned CRUD/search tools only.",
"knowledge_contract": protocol_sections["knowledge_contract"],
"memory_taxonomy": protocol_sections["memory_taxonomy"],
"aliases": protocol_sections["aliases"],
"document_workflow": protocol_sections["document_workflow"],
"document_artifact_workflow": protocol_sections["document_artifact_workflow"],
"knowledge_pr_workflow": protocol_sections["knowledge_pr_workflow"],
"benchmark_workflow": protocol_sections["benchmark_workflow"],
"sync_identity_workflow": protocol_sections["sync_identity_workflow"],
"sync_changeset_workflow": protocol_sections["sync_changeset_workflow"],
"sync_transport_workflow": protocol_sections["sync_transport_workflow"],
"tool_groups": protocol_sections["tool_groups"],
"canonical_tools": protocol_sections["canonical_tools"],
"warnings": warnings,
"error": protocol_error,
}
@mcp.tool()
async def daemon_status() -> dict[str, Any]:
"""Report whether the configured daemon is reachable without reading or writing memory."""
hub_config = read_hub_client_config()
hub_validation = validate_hub_client_config(hub_config)
hub_description = describe_hub_mode(hub_config)
if hub_config.get("hub_configured") and hub_validation.get("status") != "ready":
return {
"mode": "hub",
"daemon_url": _daemon_url(),
"reachable": False,
"health": None,
"hub_mode": hub_description,
"error": _tool_error(
str((hub_validation.get("error") or {}).get("code") or "hub_config_invalid"),
"Hub mode is configured but its client configuration is invalid.",
),
}
try:
health = await _call_daemon("health")
except EngramDaemonClientError as exc:
error_code = "hub_unreachable" if hub_config.get("hub_configured") else "runtime_error"
return {
"mode": "hub" if hub_config.get("hub_configured") else "daemon_client",
"daemon_url": _daemon_url(),
"reachable": False,
"health": None,
"hub_mode": hub_description,
"error": _tool_error(error_code, str(exc)),
}
return {
"mode": "hub" if hub_config.get("hub_configured") else "daemon_client",
"daemon_url": _daemon_url(),
"reachable": health.get("status") == "ok" and health.get("error") is None,
"health": health,
"hub_mode": hub_description,
"error": health.get("error"),
}
@mcp.tool()
async def memory_os_status() -> dict[str, Any]:
"""Report daemon-owned Memory OS SQLite, LanceDB, Kuzu, job, transaction, and firewall readiness."""
try:
return await _call_daemon("memory_os_status")
except EngramDaemonClientError as exc:
return {
"status": "degraded",
"components": {},
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def ensure_sync_device_identity(device_name: str = "local") -> dict[str, Any]:
"""Ensure this daemon-owned Memory OS runtime has a public sync identity."""
try:
return await _call_daemon(
"ensure_sync_device_identity",
{"device_name": _optional_text(device_name) or "local"},
)
except EngramDaemonClientError as exc:
return {
"status": "unavailable",
"local_device": None,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def export_local_sync_identity() -> dict[str, Any]:
"""Export this runtime's public-only sync identity packet."""
try:
return await _call_daemon("export_local_sync_identity", {})
except EngramDaemonClientError as exc:
return {
"record_type": "sync_public_identity",
"device_id": None,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def register_sync_peer(
peer_identity_packet: dict[str, Any],
accept: bool = False,
approved_by: str | None = None,
) -> dict[str, Any]:
"""Register a reviewed peer public sync identity packet through the daemon."""
try:
return await _call_daemon(
"register_sync_peer",
{
"peer_identity_packet": peer_identity_packet,
"accept": accept,
"approved_by": approved_by,
},
)
except EngramDaemonClientError as exc:
return {
"status": "unavailable",
"write_performed": False,
"peer": None,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def inspect_sync_state() -> dict[str, Any]:
"""Inspect sync identity, cursor, changeset, and conflict state through the daemon."""
try:
return await _call_daemon("inspect_sync_state", {})
except EngramDaemonClientError as exc:
return {
"schema_version": "2026-05-26.sync-state.v1",
"write_performed": False,
"status": {"status": "unavailable"},
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def prepare_sync_changeset(peer_id: str) -> dict[str, Any]:
"""Prepare a no-write reviewed changeset export packet for a registered peer."""
normalized_peer_id = _optional_text(peer_id)
if not normalized_peer_id:
return {
"schema_version": "2026-05-26.sync-prepare.v1",
"status": "policy_denied",
"write_performed": False,
"error": _tool_error("invalid_request", "peer_id is required"),
}
try:
return await _call_daemon("prepare_sync_changeset", {"peer_id": normalized_peer_id})
except EngramDaemonClientError as exc:
return {
"schema_version": "2026-05-26.sync-prepare.v1",
"status": "unavailable",
"write_performed": False,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def export_sync_changeset(
plan: dict[str, Any],
accept: bool = False,
approved_by: str | None = None,
) -> dict[str, Any]:
"""Export a reviewed sync changeset as a signed encrypted bundle through the daemon."""
try:
return await _call_daemon(
"export_sync_changeset",
{
"plan": plan,
"accept": accept,
"approved_by": approved_by,
},
)
except EngramDaemonClientError as exc:
return {
"schema_version": "2026-05-26.sync-export.v1",
"status": "unavailable",
"write_performed": False,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def prepare_sync_apply(bundle_b64: str) -> dict[str, Any]:
"""Prepare a no-write apply plan for a signed encrypted sync bundle."""
normalized_bundle = _optional_text(bundle_b64)
if not normalized_bundle:
return {
"schema_version": "2026-05-26.sync-apply.v1",
"status": "policy_denied",
"write_performed": False,
"error": _tool_error("invalid_request", "bundle_b64 is required"),
}
try:
return await _call_daemon("prepare_sync_apply", {"bundle_b64": normalized_bundle})
except EngramDaemonClientError as exc:
return {
"schema_version": "2026-05-26.sync-apply.v1",
"status": "unavailable",
"write_performed": False,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def apply_sync_changeset(
bundle_b64: str,
plan: dict[str, Any],
accept: bool = False,
approved_by: str | None = None,
) -> dict[str, Any]:
"""Apply a reviewed sync bundle only after re-verification and explicit acceptance."""
normalized_bundle = _optional_text(bundle_b64)
if not normalized_bundle:
return {
"schema_version": "2026-05-26.sync-apply.v1",
"status": "policy_denied",
"write_performed": False,
"error": _tool_error("invalid_request", "bundle_b64 is required"),
}
try:
return await _call_daemon(
"apply_sync_changeset",
{
"bundle_b64": normalized_bundle,
"plan": plan,
"accept": accept,
"approved_by": approved_by,
},
)
except EngramDaemonClientError as exc:
return {
"schema_version": "2026-05-26.sync-apply.v1",
"status": "unavailable",
"write_performed": False,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def inspect_sync_convergence(peer_id: str) -> dict[str, Any]:
"""Inspect unresolved sync conflicts for a registered peer."""
normalized_peer_id = _optional_text(peer_id)
if not normalized_peer_id:
return {
"schema_version": "2026-05-26.sync-convergence.v1",
"status": "policy_denied",
"write_performed": False,
"error": _tool_error("invalid_request", "peer_id is required"),
}
try:
return await _call_daemon("inspect_sync_convergence", {"peer_id": normalized_peer_id})
except EngramDaemonClientError as exc:
return {
"schema_version": "2026-05-26.sync-convergence.v1",
"status": "unavailable",
"write_performed": False,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def list_sync_conflicts(status: str | None = None) -> dict[str, Any]:
"""List sync conflict review records without full remote payload bodies."""
try:
return await _call_daemon("list_sync_conflicts", {"status": _optional_text(status)})
except EngramDaemonClientError as exc:
return {
"schema_version": "2026-05-26.sync-conflicts.v1",
"status": "unavailable",
"write_performed": False,
"conflicts": [],
"unresolved_conflict_count": 0,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def resolve_sync_conflict(
conflict_id: str,
resolution: str,
accept: bool = False,
approved_by: str | None = None,
) -> dict[str, Any]:
"""Resolve a sync conflict review record without directly overwriting memory."""
try:
return await _call_daemon(
"resolve_sync_conflict",
{
"conflict_id": conflict_id,
"resolution": resolution,
"accept": accept,
"approved_by": approved_by,
},
)
except EngramDaemonClientError as exc:
return {
"schema_version": "2026-05-26.sync-conflict.v1",
"status": "unavailable",
"write_performed": False,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def configure_sync_peer_transport(
peer_id: str,
url: str,
mode: str = "manual",
allow_pull: bool = False,
accept: bool = False,
approved_by: str | None = None,
) -> dict[str, Any]:
"""Configure reviewed LAN/Tailscale sync listener coordinates for a registered peer."""
try:
return await _call_daemon(
"configure_sync_peer_transport",
{
"peer_id": _optional_text(peer_id),
"url": _optional_text(url),
"mode": _optional_text(mode) or "manual",
"allow_pull": bool(allow_pull),
"accept": accept,
"approved_by": approved_by,
},
)
except EngramDaemonClientError as exc:
return {
"schema_version": "2026-05-26.sync-peer-transport.v1",
"status": "unavailable",
"write_performed": False,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def inspect_sync_peer(peer_id: str) -> dict[str, Any]:
"""Inspect one registered sync peer and its transport coordinates."""
try:
return await _call_daemon("inspect_sync_peer", {"peer_id": _optional_text(peer_id)})
except EngramDaemonClientError as exc:
return {
"schema_version": "2026-05-26.sync-peer-transport.v1",
"status": "unavailable",
"write_performed": False,
"peer": None,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def push_sync_changeset(
peer_id: str,
accept: bool = False,
approved_by: str | None = None,
) -> dict[str, Any]:
"""Prepare, export, and push a reviewed encrypted changeset to a sync-only peer listener."""
try:
return await _call_daemon(
"push_sync_changeset",
{
"peer_id": _optional_text(peer_id),
"accept": accept,
"approved_by": approved_by,
},
)
except EngramDaemonClientError as exc:
return {
"schema_version": "2026-05-26.sync-peer-transport.v1",
"status": "unavailable",
"write_performed": False,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def list_sync_inbox(peer_id: str | None = None) -> dict[str, Any]:
"""List encrypted inbound sync bundles without applying or returning bundle bytes."""
try:
return await _call_daemon("list_sync_inbox", {"peer_id": _optional_text(peer_id)})
except EngramDaemonClientError as exc:
return {
"schema_version": "2026-05-26.sync-inbox.v1",
"status": "unavailable",
"write_performed": False,
"inbox": [],
"inbox_count": 0,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def prepare_sync_inbox_apply(peer_id: str | None = None, limit: int = 50) -> dict[str, Any]:
"""Prepare a no-write plan for applying already staged sync inbox bundles."""
try:
return await _call_daemon(
"prepare_sync_inbox_apply",
{"peer_id": _optional_text(peer_id), "limit": int(limit or 0)},
)
except EngramDaemonClientError as exc:
return {
"schema_version": "2026-05-27.sync-inbox-apply.v1",
"status": "unavailable",
"write_performed": False,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def apply_sync_inbox(
accept: bool = False,
approved_by: str | None = None,
peer_id: str | None = None,
limit: int = 50,
stop_on_error: bool = True,
) -> dict[str, Any]:
"""Apply already staged signed sync inbox bundles after explicit acceptance."""
try:
return await _call_daemon(
"apply_sync_inbox",
{
"peer_id": _optional_text(peer_id),
"limit": int(limit or 0),
"accept": accept,
"approved_by": _optional_text(approved_by),
"stop_on_error": stop_on_error,
},
)
except EngramDaemonClientError as exc:
return {
"schema_version": "2026-05-27.sync-inbox-apply.v1",
"status": "unavailable",
"write_performed": False,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def discover_memory_capabilities(
query: str = "",
budget_chars: int = 4000,
) -> dict[str, Any]:
"""Return a budgeted, no-write catalog of daemon-owned Memory OS capabilities."""
payload = {"query": str(query or ""), "budget_chars": int(budget_chars or 4000)}
try:
return await _call_daemon("discover_memory_capabilities", payload)
except EngramDaemonClientError as exc:
return {
"schema_version": "2026-05-26.capability-discovery.v1",
"write_performed": False,
"capability_groups": {},
"warnings": [],
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def query_knowledge(request: dict[str, Any]) -> dict[str, Any]:
"""
Return an Engram Knowledge Contract 1.0 response for task-shaped orientation.
EKC 1.0 supports project_orientation, source_orientation,
document_orientation, review_preparation, evidence_audit, graph_evidence,
entity_profile, decision_packet, implementation_context, and
evidence_bundle requests with citations, freshness, policy, budget,
planner, and explicit errors. The envelope remains
engram.knowledge.*.v0 for compatibility. This tool is read-only.
"""
try:
return await _call_daemon("query_knowledge", request)
except EngramDaemonClientError as exc:
error = _tool_error("runtime_error", f"Engram daemon error: {exc}")
return {
"contract_version": "engram.knowledge.response.v0",
"request_id": str((request or {}).get("request_id") or ""),
"status": "unavailable",
"answer": None,
"citations": [],
"freshness": {"state": "unknown"},
"policy": {
"unreviewed_sources_used": False,
"unsupported_inferences_used": False,
"review_state_available": False,
"review_filter_enforced": False,
"review_state_basis": "not_available_in_current_memory_os_records",
},
"budget_used": {
"artifacts_built": 0,
"artifacts_read": 0,
"source_reads": 0,
"tokens_out_estimate": 0,
},
"planner": {
"strategy": "none",
"methods_used": [],
"omissions": [],
"budget": {
"requested": {},
"used": {
"artifacts_built": 0,
"artifacts_read": 0,
"source_reads": 0,
"tokens_out_estimate": 0,
},
},
"failure_receipts": [
{
"code": error["code"],
"category": "infrastructure",
"message": error["message"],
"recoverable": True,
}
],
"response_status": "unavailable",
},
"errors": [
{
"code": error["code"],
"category": "infrastructure",
"message": error["message"],
}
],
}
@mcp.tool()
async def search_memories(
query: str,
limit: int = 5,
project: str | None = None,
exact_project_match: bool = False,
domain: str | None = None,
tags: str | list[str] | None = None,
include_stale: bool = True,
canonical_only: bool = False,
pinned_first: bool = False,
retrieval_mode: str = "semantic",
) -> dict[str, Any]:
"""
Semantic search through the daemon. Start here before retrieving chunks.
Results include activation metadata as a rank-only signal. Receipts include
backend_used/fallback fields so agents can tell whether Memory OS retrieval
or legacy JSON/Chroma served the request.
"""
payload = {
"query": query,
"limit": limit,
"project": _optional_text(project),
"exact_project_match": exact_project_match,
"domain": _optional_text(domain),
"tags": _normalize_string_list(tags),
"include_stale": include_stale,
"canonical_only": canonical_only,
"pinned_keys": [],
"pinned_first": pinned_first,
"retrieval_mode": retrieval_mode,
}
try:
return await _call_daemon("search_memories", payload)
except EngramDaemonClientError as exc:
return {
"query": query,
"count": 0,
"results": [],
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def find_memories(
query: str,
limit: int = 5,
project: str | None = None,
exact_project_match: bool = False,
domain: str | None = None,
tags: str | list[str] | None = None,
include_stale: bool = True,
canonical_only: bool = False,
pinned_first: bool = False,
retrieval_mode: str = "semantic",
) -> dict[str, Any]:
"""Alias for search_memories()."""
return await search_memories(
query=query,
limit=limit,
project=project,
exact_project_match=exact_project_match,
domain=domain,
tags=tags,
include_stale=include_stale,
canonical_only=canonical_only,
pinned_first=pinned_first,
retrieval_mode=retrieval_mode,
)
@mcp.tool()
async def retrieve_chunk(key: str, chunk_id: int) -> dict[str, Any]:
"""Retrieve one memory chunk through the daemon after search identifies it."""
try:
return await _call_daemon("retrieve_chunk", {"key": key, "chunk_id": chunk_id})
except EngramDaemonClientError as exc:
return {
"key": key,
"chunk_id": chunk_id,
"found": False,
"chunk": None,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def read_chunk(key: str, chunk_id: int) -> dict[str, Any]:
"""Alias for retrieve_chunk()."""
return await retrieve_chunk(key, chunk_id)
@mcp.tool()
async def retrieve_chunks(requests: list[dict[str, Any]]) -> dict[str, Any]:
"""Retrieve multiple specific chunks through the daemon."""
try:
return await _call_daemon("retrieve_chunks", {"requests": requests})
except EngramDaemonClientError as exc:
return {
"requested_count": len(requests) if isinstance(requests, list) else 0,
"found_count": 0,
"results": [],
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def retrieve_memory(key: str) -> dict[str, Any]:
"""Retrieve a full memory through the daemon only after chunks are insufficient."""
try:
return await _call_daemon("retrieve_memory", {"key": key})
except EngramDaemonClientError as exc:
return {
"key": key,
"found": False,
"memory": None,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def read_memory(key: str) -> dict[str, Any]:
"""Alias for retrieve_memory()."""
return await retrieve_memory(key)
@mcp.tool()
async def store_memory(
key: str,
content: str,
tags: str | list[str] | None = None,
title: str | None = None,
related_to: str | list[str] | None = None,
force: bool = False,
project: str | None = None,
domain: str | None = None,
status: str | None = None,
canonical: bool | None = None,
memory_type: str | None = None,
scope: str | None = None,
trust_state: str | None = None,
retention_policy: str | None = None,
sync_policy: str | None = None,
) -> str:
"""Store one reviewed memory through the daemon with metadata and semantic graph treatment."""
payload = {
"key": key,
"content": content,
"tags": _normalize_string_list(tags),
"title": title or key,
"related_to": _normalize_string_list(related_to),
"force": force,
"project": _optional_text(project),
"domain": _optional_text(domain),
"status": _optional_text(status),
"canonical": canonical,
"memory_type": _optional_text(memory_type),
"scope": _optional_text(scope),
"trust_state": _optional_text(trust_state),
"retention_policy": _optional_text(retention_policy),
"sync_policy": _optional_text(sync_policy),
}
try:
response = await _call_daemon("store_memory", payload)
except EngramDaemonClientError as exc:
return _daemon_exception_message(exc)
return _format_daemon_store_response(key, response)
@mcp.tool()
async def write_memory(
key: str,
content: str,
tags: str | list[str] | None = None,
title: str | None = None,
related_to: str | list[str] | None = None,
force: bool = False,
project: str | None = None,
domain: str | None = None,
status: str | None = None,
canonical: bool | None = None,
memory_type: str | None = None,
scope: str | None = None,
trust_state: str | None = None,
retention_policy: str | None = None,
sync_policy: str | None = None,
) -> str:
"""Alias for store_memory()."""
return await store_memory(
key=key,
content=content,
tags=tags,
title=title,
related_to=related_to,
force=force,
project=project,
domain=domain,
status=status,
canonical=canonical,
memory_type=memory_type,
scope=scope,
trust_state=trust_state,
retention_policy=retention_policy,
sync_policy=sync_policy,
)
@mcp.tool()
async def check_duplicate(key: str, content: str) -> dict[str, Any]:
"""Check duplicate risk through the daemon before a reviewed write."""
try:
return await _call_daemon("check_duplicate", {"key": key, "content": content})
except EngramDaemonClientError as exc:
return {
"key": key,
"duplicate": False,
"match": None,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def prepare_source_memory(
source_text: str,
source_type: str,
source_uri: str | None = None,
project: str | None = None,
domain: str | None = None,
budget_chars: int = 6000,
pipeline: str = "generic",
) -> dict[str, Any]:
"""Prepare source drafts through the daemon; no active memory is promoted."""
payload = {
"source_text": source_text,
"source_type": source_type,
"source_uri": source_uri,
"project": project,
"domain": domain,
"budget_chars": budget_chars,
"pipeline": pipeline,
}
try:
return await _call_daemon("prepare_source_memory", payload)
except EngramDaemonClientError as exc:
return {
"draft": None,
"error": _tool_error("runtime_error", f"Engram daemon error: {exc}"),
}
@mcp.tool()
async def list_source_drafts(
project: str | None = None,