This repository was archived by the owner on May 31, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
1816 lines (1646 loc) · 69.7 KB
/
Copy path__init__.py
File metadata and controls
1816 lines (1646 loc) · 69.7 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
"""
basic-memory — Hermes Memory Provider plugin
Wraps the basic-memory MCP server (`bm mcp`) to provide knowledge-graph-backed
memory for Hermes. Analog of openclaw-basic-memory.
Architecture:
- `_BmMcpActor` owns a long-lived asyncio loop in a daemon thread that holds
the MCP `ClientSession` open across the agent's lifetime. Sync hooks dispatch
through `asyncio.run_coroutine_threadsafe`.
- `BasicMemoryProvider` implements Hermes's `MemoryProvider` ABC: tools,
prefetch, sync_turn (per-turn capture), on_session_end (summary).
The plugin loader text-greps for `register_memory_provider` or `MemoryProvider`
to detect this file as a memory provider — both tokens are present below.
"""
from __future__ import annotations
import asyncio
import atexit
import concurrent.futures
import json
import logging
import os
import re
import socket
import subprocess
import threading
import time
from datetime import datetime, timezone
from pathlib import Path
from shutil import which
from typing import Any, Callable, Dict, List, Optional, Tuple
# Hermes ABC + helpers — these resolve because Hermes adds its tree to sys.path
# when loading plugins (same pattern as plugins/memory/mem0/__init__.py:21).
from agent.memory_provider import MemoryProvider
from tools.registry import tool_error
__version__ = "0.2.2"
logger = logging.getLogger("hermes.memory.basic-memory")
# ---------------------------------------------------------------------------
# MCP SDK import — soft. If unavailable, is_available() returns False.
# ---------------------------------------------------------------------------
_MCP_AVAILABLE = False
_MCP_IMPORT_ERROR: Optional[BaseException] = None
try:
from mcp import ClientSession, StdioServerParameters # type: ignore
from mcp.client.stdio import stdio_client # type: ignore
_MCP_AVAILABLE = True
except Exception as _e: # pragma: no cover
_MCP_IMPORT_ERROR = _e
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
PROVIDER_NAME = "basic-memory"
# Hermes-side tool names → BM MCP tool names. Curated subset of BM's surface.
_HERMES_TO_BM: Dict[str, str] = {
"bm_search": "search_notes",
"bm_read": "read_note",
"bm_write": "write_note",
"bm_edit": "edit_note",
"bm_context": "build_context",
"bm_delete": "delete_note",
"bm_move": "move_note",
"bm_recent": "recent_activity",
"bm_projects": "list_memory_projects",
"bm_workspaces": "list_workspaces",
}
# Discovery tools that operate across all projects/workspaces. They don't
# accept project/project_id args (no per-call routing) and the user-facing
# schemas omit those properties.
_GLOBAL_TOOLS: frozenset = frozenset({"bm_projects", "bm_workspaces"})
TOOL_SCHEMAS: List[Dict[str, Any]] = [
{
"name": "bm_search",
"description": (
"Search the Basic Memory knowledge graph for notes, decisions, observations. "
"Use BEFORE answering questions about prior work — context may already exist."
),
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search terms (semantic + full-text)."},
"limit": {"type": "integer", "description": "Max results (default 10).", "default": 10},
},
"required": ["query"],
},
},
{
"name": "bm_read",
"description": "Read a specific note by title, permalink, or memory:// URL.",
"parameters": {
"type": "object",
"properties": {
"identifier": {"type": "string", "description": "Note title, permalink, or memory:// URL."},
},
"required": ["identifier"],
},
},
{
"name": "bm_write",
"description": (
"Create a new note in the knowledge graph. Use clear titles and a folder "
"(e.g. 'projects', 'decisions', 'meetings')."
),
"parameters": {
"type": "object",
"properties": {
"title": {"type": "string"},
"content": {"type": "string", "description": "Markdown body."},
"folder": {"type": "string", "description": "Folder path within the project."},
"tags": {"type": "array", "items": {"type": "string"}, "description": "Optional tags."},
},
"required": ["title", "content", "folder"],
},
},
{
"name": "bm_edit",
"description": (
"Edit an existing note. Operations: append, prepend, find_replace, replace_section. "
"find_replace requires find_text. replace_section requires section."
),
"parameters": {
"type": "object",
"properties": {
"identifier": {"type": "string"},
"operation": {
"type": "string",
"enum": ["append", "prepend", "find_replace", "replace_section"],
},
"content": {"type": "string"},
"find_text": {"type": "string", "description": "Required for find_replace."},
"section": {"type": "string", "description": "Required for replace_section."},
},
"required": ["identifier", "operation", "content"],
},
},
{
"name": "bm_context",
"description": (
"Navigate the knowledge graph from a memory:// URL or note identifier. "
"Returns the target note plus related notes via traversed relations."
),
"parameters": {
"type": "object",
"properties": {
"url": {"type": "string", "description": "memory:// URL or note identifier."},
"depth": {"type": "integer", "description": "Relation traversal depth (default 1).", "default": 1},
},
"required": ["url"],
},
},
{
"name": "bm_delete",
"description": "Delete a note from the knowledge graph.",
"parameters": {
"type": "object",
"properties": {"identifier": {"type": "string"}},
"required": ["identifier"],
},
},
{
"name": "bm_move",
"description": "Move a note to a different folder.",
"parameters": {
"type": "object",
"properties": {
"identifier": {"type": "string"},
"new_folder": {"type": "string"},
},
"required": ["identifier", "new_folder"],
},
},
{
"name": "bm_recent",
"description": (
"List notes updated recently. Use to surface what's been touched "
"without a specific search query."
),
"parameters": {
"type": "object",
"properties": {
"timeframe": {
"type": "string",
"description": "Lookback window. Accepts '7d', '2 weeks', 'yesterday', etc.",
"default": "7d",
},
"limit": {"type": "integer", "description": "Max results (default 10).", "default": 10},
"type": {
"type": "string",
"description": "Optional filter by item type (e.g. 'entity', 'observation').",
},
},
},
},
{
"name": "bm_projects",
"description": (
"List all available Basic Memory projects (local + cloud). Returns "
"JSON with name and `external_id` (UUID) per project. Use the UUID "
"as `project_id` on other bm_* tools for unambiguous routing across "
"cloud workspaces. Call this when the user names a project that "
"isn't the active one, or when you need to disambiguate same-name "
"projects."
),
"parameters": {"type": "object", "properties": {}},
},
{
"name": "bm_workspaces",
"description": (
"List Basic Memory Cloud workspaces the user belongs to. Workspaces "
"are a BM Cloud concept; local mode returns just the personal "
"workspace. Returns JSON with name, type, role, and default flag. "
"Pair with bm_projects to disambiguate when the same project name "
"exists in multiple workspaces."
),
"parameters": {"type": "object", "properties": {}},
},
]
# Per-call project routing. Every bm_* tool accepts these — the agent overrides
# Hermes's configured project to read/write against a different Basic Memory
# project (e.g. a personal "main" project on BM Cloud). project_id is the
# UUID-based unambiguous form: required when the same project name exists in
# multiple cloud workspaces. _translate_args sends only one of the two to BM,
# with project_id winning when both are passed.
_PROJECT_ROUTING_PROPS: Dict[str, Dict[str, Any]] = {
"project": {
"type": "string",
"description": (
"Optional. Override the active Basic Memory project (e.g. 'main'). "
"If the same project name exists in multiple cloud workspaces, "
"use project_id instead for unambiguous routing."
),
},
"project_id": {
"type": "string",
"description": (
"Optional. Override by project UUID (external_id from bm_projects). "
"Disambiguates when a project name appears in multiple workspaces. "
"Takes precedence over `project` if both are supplied."
),
},
}
for _schema in TOOL_SCHEMAS:
if _schema["name"] in _GLOBAL_TOOLS:
# Discovery tools (bm_projects, bm_workspaces) list everything —
# they don't take per-call routing.
continue
_schema["parameters"]["properties"].update(_PROJECT_ROUTING_PROPS)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _bm_binary_path() -> Optional[str]:
"""Find the bm CLI without making network calls. Used by is_available()."""
candidates = [
os.path.expanduser("~/.local/bin/bm"),
"/opt/homebrew/bin/bm",
"/usr/local/bin/bm",
]
for c in candidates:
if os.path.isfile(c) and os.access(c, os.X_OK):
return c
return which("bm")
def _uv_binary_path() -> Optional[str]:
"""Find the uv CLI. Used to bootstrap-install basic-memory when bm is missing."""
candidates = [
os.path.expanduser("~/.local/bin/uv"),
"/opt/homebrew/bin/uv",
"/usr/local/bin/uv",
]
for c in candidates:
if os.path.isfile(c) and os.access(c, os.X_OK):
return c
return which("uv")
def _install_bm_via_uv(timeout: float = 180.0) -> Optional[str]:
"""
Bootstrap-install basic-memory via `uv tool install`.
Idempotent — re-runs are no-ops when the tool is already installed, so this
converges with later manual `uv tool install basic-memory` calls and avoids
the two-installations-sharing-one-config-dir foot-gun.
Returns the resolved bm path on success, or None if uv is unavailable or
the install failed.
"""
uv = _uv_binary_path()
if not uv:
return None
try:
result = subprocess.run(
[uv, "tool", "install", "basic-memory", "--quiet"],
check=False,
capture_output=True,
timeout=timeout,
)
except Exception as e:
logger.warning("basic-memory: `uv tool install basic-memory` failed: %s", e)
return None
if result.returncode != 0:
# uv prints to stderr; capture the tail so the operator can debug.
stderr_tail = (result.stderr or b"").decode("utf-8", errors="replace")[-400:]
logger.warning(
"basic-memory: `uv tool install basic-memory` exited %s: %s",
result.returncode,
stderr_tail.strip(),
)
return None
return _bm_binary_path()
def _hostname() -> str:
return socket.gethostname().split(".")[0].lower().replace(" ", "-")
def _default_project() -> str:
# Each machine gets its own local project with this name. Cloud setups
# use a different name (e.g. hermes-memory-cloud) so the two don't
# collide in BM's per-workspace project registry.
return "hermes-memory"
def _default_project_path() -> str:
# ~/.basic-memory/ is reserved for BM's own application state; user
# project files live in user space, parallel to ~/basic-memory/.
return os.path.expanduser("~/hermes-memory/")
def _config_path(hermes_home: str) -> Path:
return Path(hermes_home) / "basic-memory.json"
def _bm_config_path() -> Path:
"""Location of bm's own project registry."""
return Path.home() / ".basic-memory" / "config.json"
def _bm_known_projects() -> Optional[Dict[str, Any]]:
"""
Read bm's project registry. Returns None if the file is absent or
unparseable — callers should treat that as "can't prove anything"
rather than "project is missing".
"""
path = _bm_config_path()
if not path.exists():
return None
try:
data = json.loads(path.read_text())
except Exception:
return None
if not isinstance(data, dict):
return None
projects = data.get("projects")
return projects if isinstance(projects, dict) else None
def _load_config(hermes_home: str) -> Dict[str, Any]:
p = _config_path(hermes_home)
if not p.exists():
return {}
try:
return json.loads(p.read_text())
except Exception as e:
logger.warning("could not parse %s: %s — using defaults", p, e)
return {}
def _truncate(s: Any, n: int) -> str:
if not isinstance(s, str):
s = "" if s is None else str(s)
if len(s) <= n:
return s
return s[: n - 3] + "..."
def _join_message_content(parts: Any) -> str:
if isinstance(parts, str):
return parts
if isinstance(parts, list):
out: List[str] = []
for p in parts:
if isinstance(p, dict):
t = p.get("text") or p.get("content")
if isinstance(t, str):
out.append(t)
elif isinstance(p, str):
out.append(p)
return "\n".join(out)
return str(parts) if parts is not None else ""
def _coerce_bool(v: Any) -> Any:
if isinstance(v, bool):
return v
if isinstance(v, str):
if v.lower() in ("true", "1", "yes", "y"):
return True
if v.lower() in ("false", "0", "no", "n"):
return False
return v
def _extract_mcp_text(result: Any) -> str:
"""
Extract text from an MCP CallToolResult.
Returns a JSON string for the agent. If the result is itself JSON, returns it
as-is. Otherwise wraps the text in `{"text": "..."}` for downstream parsing.
"""
is_error = bool(getattr(result, "isError", False))
parts: List[str] = []
for c in getattr(result, "content", None) or []:
text = getattr(c, "text", None)
if isinstance(text, str):
parts.append(text)
text = "\n".join(parts).strip()
if is_error:
return tool_error(text or "MCP tool returned error")
if not text:
return json.dumps({"ok": True})
# If it's already JSON, pass through verbatim
try:
json.loads(text)
return text
except Exception:
return json.dumps({"text": text})
_PERMALINK_JSON_RE = re.compile(r'"permalink"\s*:\s*"([^"]+)"')
_PERMALINK_MD_RE = re.compile(r"^\s*permalink\s*:\s*(\S+)\s*$", re.MULTILINE)
def _extract_permalink(text: str, fallback: str) -> str:
"""
Extract a note permalink from any plausible BM response shape:
1. Bare JSON dict with `permalink` key (output_format=json path)
2. `{"text": "..."}` wrapping inner JSON or markdown
3. Raw markdown response text (output_format=text default)
Falls back to the supplied fallback when nothing matches.
"""
if not isinstance(text, str) or not text:
return fallback
# Strategy 1: parse outer as JSON
try:
d = json.loads(text)
if isinstance(d, dict):
if isinstance(d.get("permalink"), str):
return d["permalink"]
inner = d.get("text")
if isinstance(inner, str):
# Strategy 2: inner is JSON
try:
d2 = json.loads(inner)
if isinstance(d2, dict) and isinstance(d2.get("permalink"), str):
return d2["permalink"]
except Exception:
pass
# Strategy 3a: inner is markdown with `permalink: ...` line
m = _PERMALINK_MD_RE.search(inner)
if m:
return m.group(1).rstrip(",.;")
# Strategy 3b: inner contains JSON substring with permalink
m = _PERMALINK_JSON_RE.search(inner)
if m:
return m.group(1)
except Exception:
pass
# Strategy 4: best-effort regex on raw text (covers exotic shapes)
m = _PERMALINK_JSON_RE.search(text)
if m:
return m.group(1)
m = _PERMALINK_MD_RE.search(text)
if m:
return m.group(1).rstrip(",.;")
return fallback
# ---------------------------------------------------------------------------
# MCP actor — single asyncio loop in a daemon thread, owns ClientSession
# ---------------------------------------------------------------------------
class _BmMcpActor:
"""
Owns the lifetime of one MCP ClientSession to the bm MCP server.
Why this exists: Hermes calls memory provider hooks synchronously from
a sync code path (memory_manager.py invokes provider.sync_turn / .prefetch
/ .handle_tool_call directly). MCP `ClientSession` is asyncio-bound and
not thread-safe across event loops. So we run one asyncio loop in a
daemon thread and ferry calls in via run_coroutine_threadsafe.
"""
def __init__(self, server_argv: List[str], env: Optional[Dict[str, str]] = None):
self._server_argv = list(server_argv)
self._env = dict(env) if env is not None else os.environ.copy()
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._thread: Optional[threading.Thread] = None
self._session: Optional["ClientSession"] = None
self._ready = threading.Event()
self._init_error: Optional[BaseException] = None
self._stop_future: Optional[asyncio.Future] = None
self._tools_cache: List[Dict[str, Any]] = []
self._running = False
def start(self, timeout: float = 25.0) -> None:
if self._thread and self._thread.is_alive():
return
self._running = True
self._thread = threading.Thread(
target=self._run, daemon=True, name="bm-mcp-actor"
)
self._thread.start()
if not self._ready.wait(timeout=timeout):
self._running = False
raise TimeoutError(
f"basic-memory MCP server didn't initialize within {timeout}s"
)
if self._init_error is not None:
self._running = False
raise RuntimeError(
f"basic-memory MCP server failed to start: {self._init_error}"
)
def _run(self) -> None:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
self._loop = loop
try:
loop.run_until_complete(self._main())
except BaseException as e:
if self._init_error is None:
self._init_error = e
self._ready.set()
logger.exception("basic-memory MCP actor terminated with error")
finally:
self._running = False
try:
loop.close()
except Exception:
pass
async def _main(self) -> None:
params = StdioServerParameters(
command=self._server_argv[0],
args=self._server_argv[1:],
env=self._env,
)
try:
async with stdio_client(params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
self._session = session
self._stop_future = asyncio.get_running_loop().create_future()
try:
listing = await session.list_tools()
self._tools_cache = [
{
"name": getattr(t, "name", ""),
"description": getattr(t, "description", "") or "",
}
for t in getattr(listing, "tools", []) or []
]
except Exception as e:
logger.warning("list_tools failed: %s", e)
self._tools_cache = []
self._ready.set()
await self._stop_future # blocks until shutdown
except BaseException as e:
if self._init_error is None:
self._init_error = e
self._ready.set()
raise
def call(self, tool_name: str, arguments: Dict[str, Any], timeout: float = 30.0) -> str:
if not self._running:
raise RuntimeError("basic-memory MCP actor not running")
if self._loop is None or self._session is None:
raise RuntimeError("basic-memory MCP actor not started")
future = asyncio.run_coroutine_threadsafe(
self._session.call_tool(tool_name, arguments),
self._loop,
)
try:
result = future.result(timeout=timeout)
except concurrent.futures.TimeoutError:
# Cancel the coroutine on the actor loop so we don't leak
# a stuck call_tool. cancel() on a run_coroutine_threadsafe
# future propagates cancellation into the wrapped coroutine.
future.cancel()
raise
return _extract_mcp_text(result)
def list_tools(self) -> List[Dict[str, Any]]:
return list(self._tools_cache)
def shutdown(self, timeout: float = 5.0) -> None:
self._running = False
if self._loop is not None and self._stop_future is not None:
try:
self._loop.call_soon_threadsafe(
lambda: (self._stop_future and not self._stop_future.done())
and self._stop_future.set_result(None)
)
except Exception:
# Loop may already be closed; safe to ignore.
pass
if self._thread is not None:
try:
self._thread.join(timeout=timeout)
except Exception:
pass
# ---------------------------------------------------------------------------
# Argument translation: Hermes-side tool args → BM MCP tool args
# ---------------------------------------------------------------------------
def _translate_args(
hermes_tool: str, args: Dict[str, Any], default_project: str
) -> Tuple[str, Dict[str, Any]]:
bm_tool = _HERMES_TO_BM[hermes_tool]
out: Dict[str, Any] = {}
# Project routing: project_id > project > configured default.
# The agent passes one of these to operate on a project other than the
# one Hermes is configured for. project_id (UUID from bm_projects) is
# the unambiguous form across cloud workspaces — preferred when project
# names might collide between workspaces. Only one of the two reaches
# BM so server-side precedence rules don't enter the picture.
#
# Global discovery tools (bm_projects, bm_workspaces) list everything
# and don't take routing args at all — skip the block for them.
if hermes_tool not in _GLOBAL_TOOLS:
project_id_override = args.get("project_id")
project_name_override = args.get("project")
if project_id_override:
out["project_id"] = str(project_id_override)
elif project_name_override:
out["project"] = str(project_name_override)
else:
out["project"] = default_project
if hermes_tool == "bm_search":
out["query"] = args["query"]
if "limit" in args and args["limit"] is not None:
out["page_size"] = int(args["limit"])
elif hermes_tool == "bm_read":
out["identifier"] = args["identifier"]
elif hermes_tool == "bm_write":
out["title"] = args["title"]
out["content"] = args["content"]
out["directory"] = args["folder"]
if args.get("tags"):
out["tags"] = list(args["tags"])
elif hermes_tool == "bm_edit":
out["identifier"] = args["identifier"]
out["operation"] = args["operation"]
out["content"] = args["content"]
if args.get("find_text") is not None:
out["find_text"] = args["find_text"]
if args.get("section") is not None:
out["section"] = args["section"]
elif hermes_tool == "bm_context":
out["url"] = args["url"]
if args.get("depth") is not None:
out["depth"] = int(args["depth"])
elif hermes_tool == "bm_delete":
out["identifier"] = args["identifier"]
elif hermes_tool == "bm_move":
out["identifier"] = args["identifier"]
out["destination_folder"] = args["new_folder"]
elif hermes_tool == "bm_recent":
if args.get("timeframe"):
out["timeframe"] = str(args["timeframe"])
if args.get("limit") is not None:
out["page_size"] = int(args["limit"])
if args.get("type"):
out["type"] = args["type"]
elif hermes_tool in _GLOBAL_TOOLS:
# The agent needs to parse identifiers (UUIDs, workspace slugs) out
# of the response, so request JSON regardless of BM's text default.
out["output_format"] = "json"
return bm_tool, out
# ---------------------------------------------------------------------------
# Provider
# ---------------------------------------------------------------------------
class BasicMemoryProvider(MemoryProvider):
"""Hermes Memory Provider backed by the basic-memory MCP server."""
def __init__(self) -> None:
self._actor: Optional[_BmMcpActor] = None
self._project: str = _default_project()
self._mode: str = "local"
self._project_path: str = _default_project_path()
self._capture_per_turn: bool = True
self._capture_session_end: bool = True
self._capture_folder: str = "hermes-sessions"
self._remember_folder: str = "bm-remember"
self._session_id: str = ""
self._hermes_home: str = ""
self._session_note_id: Optional[str] = None
self._session_started_at: Optional[datetime] = None
self._sync_thread: Optional[threading.Thread] = None
self._prefetch_thread: Optional[threading.Thread] = None
self._prefetch_lock = threading.Lock()
self._pending_prefetch: str = ""
self._failure_count: int = 0
self._failure_pause_until: float = 0.0
self._initialized: bool = False
self._first_user_msg: Optional[str] = None
# ---- Identity ----
@property
def name(self) -> str:
return PROVIDER_NAME
def is_available(self) -> bool:
# Discovery hot path. NEVER make network calls or spawn subprocesses here.
# We report available when either bm is present already OR uv is present
# (we bootstrap-install bm via `uv tool install` at initialize() time).
if not _MCP_AVAILABLE:
return False
if _bm_binary_path():
return True
if _uv_binary_path():
return True
return False
# ---- Lifecycle ----
def initialize(self, session_id: str, **kwargs: Any) -> None:
self._session_id = session_id or ""
self._hermes_home = kwargs.get("hermes_home") or os.path.expanduser("~/.hermes")
cfg = _load_config(self._hermes_home)
self._mode = cfg.get("mode") or "local"
self._project = cfg.get("project") or _default_project()
self._project_path = os.path.expanduser(
cfg.get("project_path") or _default_project_path()
)
self._capture_per_turn = bool(_coerce_bool(cfg.get("capture_per_turn", True)))
self._capture_session_end = bool(_coerce_bool(cfg.get("capture_session_end", True)))
self._capture_folder = cfg.get("capture_folder") or "hermes-sessions"
self._remember_folder = cfg.get("remember_folder") or "bm-remember"
if not _MCP_AVAILABLE:
logger.error(
"basic-memory: MCP SDK unavailable; provider will not initialize: %s",
_MCP_IMPORT_ERROR,
)
return
# Bootstrap-install bm via uv if it's not already on disk. One-time cost
# on a fresh machine; idempotent no-op once basic-memory is installed.
if not _bm_binary_path():
if _uv_binary_path() is None:
logger.error(
"basic-memory: bm CLI not found and uv is not installed. "
"Install uv (https://docs.astral.sh/uv/) or run "
"`pip install basic-memory` manually. Provider will not initialize."
)
return
logger.info(
"basic-memory: bm CLI not found — installing basic-memory via "
"`uv tool install` (one-time bootstrap)"
)
if _install_bm_via_uv() is None:
logger.error(
"basic-memory: auto-install via uv failed. Run "
"`uv tool install basic-memory` manually to debug. "
"Provider will not initialize."
)
return
if self._mode == "local":
self._ensure_local_project()
if not self._verify_project_registered():
self._log_missing_project()
return
try:
argv = self._server_argv()
except Exception as e:
logger.error("basic-memory: cannot determine server argv: %s", e)
return
actor = _BmMcpActor(argv)
try:
actor.start(timeout=25.0)
except Exception as e:
logger.error("basic-memory: MCP server failed to start: %s", e)
return
self._actor = actor
tools = actor.list_tools()
names = {t["name"] for t in tools}
missing = [bm for bm in _HERMES_TO_BM.values() if bm not in names]
if missing:
logger.warning(
"basic-memory: BM MCP missing expected tools: %s (got: %s)",
missing,
sorted(names),
)
self._session_started_at = datetime.now(timezone.utc)
self._initialized = True
logger.info(
"basic-memory provider ready: mode=%s project=%s tools=%d",
self._mode,
self._project,
len(tools),
)
def _ensure_local_project(self) -> None:
bm = _bm_binary_path()
if not bm:
return
os.makedirs(self._project_path, exist_ok=True)
try:
subprocess.run(
[bm, "project", "add", self._project, self._project_path],
check=False,
capture_output=True,
timeout=15,
)
except Exception as e:
logger.debug("bm project add: %s", e)
def _verify_project_registered(self) -> bool:
"""
Confirm the configured project is registered with bm.
Returns False only when we can prove the project is missing
(bm config exists, parses, and the project name is absent).
Otherwise returns True — including when bm's config doesn't exist
yet — so we don't false-positive-reject on first-run setups.
"""
projects = _bm_known_projects()
if projects is None:
return True
return self._project in projects
def _log_missing_project(self) -> None:
if self._mode == "cloud":
hint = (
f"`bm project add {self._project} --cloud` "
"(optionally with --local-path) first"
)
else:
hint = f"`bm project add {self._project} {self._project_path}` first"
logger.error(
"basic-memory: project %r is not registered with bm. Run %s. "
"Provider will not initialize.",
self._project,
hint,
)
def _server_argv(self) -> List[str]:
bm = _bm_binary_path()
if not bm:
raise RuntimeError("bm CLI not found on PATH")
# `bm mcp` works the same in local and cloud modes — bm reads
# ~/.basic-memory/config.json to know whether the active project is local
# or cloud-routed. We pass --project on each tool call.
return [bm, "mcp"]
def shutdown(self) -> None:
if self._actor is not None:
try:
self._actor.shutdown(timeout=5.0)
except Exception as e:
logger.debug("actor shutdown: %s", e)
self._actor = None
self._initialized = False
# ---- Tool surface ----
def system_prompt_block(self) -> str:
if not self._initialized:
return ""
return (
"## Basic Memory Knowledge Graph\n"
f"Active project: `{self._project}` ({self._mode}).\n"
"\n"
"**Use the `bm_*` tools below directly — do not shell out to the `bm` CLI.** "
"These tools route through a persistent MCP connection "
"(~0.1s/call); running `bm` from the shell spawns a fresh Python "
"process per call (~1-2s) and bypasses Hermes's automatic per-turn "
"capture.\n"
"\n"
"- `bm_search(query)` — call BEFORE answering about prior decisions, "
"projects, meetings, or anything that might already be documented\n"
"- `bm_read(identifier)` — fetch a note by title, permalink, or "
"memory:// URL\n"
"- `bm_context(url)` — navigate via memory:// URLs to find related "
"notes\n"
"- `bm_write(title, content, folder)` — capture decisions, insights, "
"meeting outcomes worth preserving\n"
"- `bm_edit(identifier, operation, content)` — append, prepend, "
"find_replace, replace_section\n"
"- `bm_delete(identifier)` / `bm_move(identifier, new_folder)` — "
"maintenance\n"
"- `bm_recent(timeframe)` — list notes updated within a window "
"(default 7d) when there's no specific query yet\n"
"- `bm_projects()` — list available projects (local + cloud) with "
"their UUIDs; call when the user names a project that isn't the "
"active one\n"
"- `bm_workspaces()` — list BM Cloud workspaces; pair with "
"`bm_projects` to disambiguate same-named projects\n"
"\n"
"**Cross-project routing.** Read/write tools accept optional `project` "
"(name) or `project_id` (UUID). Omit both to use the active "
f"project (`{self._project}`). Use `project_id` (from `bm_projects`) "
"when the same project name exists in multiple cloud workspaces."
)
def get_tool_schemas(self) -> List[Dict[str, Any]]:
# Static. Hermes captures the schema list at register time (before
# initialize() has run), so gating on `_initialized` would mean the
# tools never make it into MemoryManager._tool_to_provider, and every
# `bm_*` invocation returns "Unknown tool: bm_*" for the rest of the
# session. handle_tool_call() does the runtime gate on `_initialized`
# and returns a clean tool error if the actor isn't ready yet.
return [dict(s) for s in TOOL_SCHEMAS]
def handle_tool_call(self, tool_name: str, args: Dict[str, Any], **kwargs: Any) -> str:
if not self._initialized or self._actor is None:
return tool_error("basic-memory provider not initialized")
if tool_name not in _HERMES_TO_BM:
return tool_error(f"Unknown tool: {tool_name}")
try:
bm_tool, bm_args = _translate_args(tool_name, args or {}, self._project)
except KeyError as e:
return tool_error(f"{tool_name}: missing required arg {e}")
try:
return self._actor.call(bm_tool, bm_args, timeout=30.0)
except Exception as e:
self._record_failure(e)
logger.exception("bm tool call failed: %s", tool_name)
return tool_error(f"{tool_name}: {e}")
# ---- Recall (retrieve step) ----
def prefetch(self, query: str, *, session_id: str = "") -> str:
with self._prefetch_lock:
cached = self._pending_prefetch
self._pending_prefetch = ""
if cached:
return cached
if not self._initialized or self._actor is None or self._is_circuit_open():
return ""
try:
raw = self._actor.call(
"search_notes",
{
"project": self._project,
"query": query,
"page_size": 5,
"output_format": "json",
},
timeout=3.0,
)
return self._format_prefetch(raw)
except Exception as e:
self._record_failure(e)
return ""
def queue_prefetch(self, query: str, *, session_id: str = "") -> None:
if not self._initialized or self._actor is None or self._is_circuit_open():
return
if self._prefetch_thread and self._prefetch_thread.is_alive():
return
def _bg() -> None:
try: