-
Notifications
You must be signed in to change notification settings - Fork 664
Expand file tree
/
Copy pathmcp.go
More file actions
3061 lines (2761 loc) · 116 KB
/
Copy pathmcp.go
File metadata and controls
3061 lines (2761 loc) · 116 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
// Package mcp implements the Model Context Protocol server for Engram.
//
// This exposes memory tools via MCP stdio transport so ANY agent
// (OpenCode, Claude Code, Cursor, Windsurf, etc.) can use Engram's
// persistent memory just by adding it as an MCP server.
//
// Tool profiles allow agents to load only the tools they need:
//
// engram mcp → all 19 tools (default)
// engram mcp --tools=agent → 15 tools agents actually use (per skill files)
// engram mcp --tools=admin → 4 tools for TUI/CLI (delete, stats, timeline, merge)
// engram mcp --tools=agent,admin → combine profiles
// engram mcp --tools=mem_save,mem_search → individual tool names
package mcp
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/Gentleman-Programming/engram/internal/diagnostic"
projectpkg "github.com/Gentleman-Programming/engram/internal/project"
"github.com/Gentleman-Programming/engram/internal/store"
"github.com/Gentleman-Programming/engram/internal/timeutil"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
const sourceProcessOverride = "process_override"
// MCPConfig holds configuration for the MCP server.
type MCPConfig struct {
// DefaultProject is a trusted process-level project override supplied by
// long-lived MCP hosts (for example, `engram mcp --project NAME` or
// ENGRAM_PROJECT). When set, it is used before cwd detection for MCP
// auto-resolution; per-call project arguments remain separately validated.
DefaultProject string
// BM25Floor overrides the default BM25 score floor used by FindCandidates
// during conflict candidate detection (REQ-001). The floor is the minimum
// acceptable BM25 rank (negative; closer to 0 = better match). Candidates
// whose score falls below this threshold are excluded.
//
// nil means "use the store default" (-2.0). An explicit pointer value
// (including 0.0) is forwarded directly. Using a pointer avoids the
// zero-value ambiguity where 0.0 would otherwise be indistinguishable
// from "not set".
BM25Floor *float64
// Limit overrides the maximum number of conflict candidates returned per
// mem_save call (REQ-001). nil means "use the store default" (3).
// An explicit pointer value (including 0) is forwarded directly.
Limit *int
}
var suggestTopicKey = store.SuggestTopicKey
var addPromptIfMissing = func(s *store.Store, params store.AddPromptParams) (int64, bool, error) {
return s.AddPromptIfMissing(params)
}
var loadMCPStats = func(s *store.Store) (*store.Stats, error) {
return s.Stats()
}
func currentWorkingDirectory() string {
cwd, err := os.Getwd()
if err != nil {
return ""
}
return cwd
}
func ensureImplicitSessionWithCWD(s *store.Store, sessionID, project string) error {
return s.CreateSession(sessionID, project, currentWorkingDirectory())
}
// ─── Tool Profiles ───────────────────────────────────────────────────────────
//
// "agent" — tools AI agents use during coding sessions:
// mem_save, mem_search, mem_context, mem_session_summary,
// mem_session_start, mem_session_end, mem_get_observation,
// mem_suggest_topic_key, mem_capture_passive, mem_save_prompt
//
// "admin" — tools for manual curation, TUI, and dashboards:
// mem_update, mem_delete, mem_stats, mem_timeline, mem_merge_projects
//
// "all" (default) — every tool registered.
// ProfileAgent contains the tool names that AI agents need.
// Sourced from actual skill files and memory protocol instructions
// across all 4 supported agents (Claude Code, OpenCode, Gemini CLI, Codex).
var ProfileAgent = map[string]bool{
"mem_save": true, // proactive save — referenced 17 times across protocols
"mem_search": true, // search past memories — referenced 6 times
"mem_find_project": true, // find projects by memory content
"mem_context": true, // recent context from previous sessions — referenced 10 times
"mem_session_summary": true, // end-of-session summary — referenced 16 times
"mem_session_start": true, // register session start
"mem_session_end": true, // mark session completed
"mem_get_observation": true, // full observation content after search — referenced 4 times
"mem_suggest_topic_key": true, // stable topic key for upserts — referenced 3 times
"mem_capture_passive": true, // extract learnings from text — referenced in Gemini/Codex protocol
"mem_save_prompt": true, // save user prompts
"mem_update": true, // update observation by ID — skills say "use mem_update when you have an exact ID to correct"
"mem_current_project": true, // detect current project — recommended first call for agents (REQ-313)
"mem_judge": true, // record verdict on a pending memory conflict (REQ-003, Phase D)
"mem_compare": true, // persist an agent-judged semantic verdict via JudgeBySemantic (REQ-011, Phase G)
"mem_doctor": true, // read-only operational diagnostics for agents
"mem_review": true, // list/mark observations whose review_after lifecycle is stale
"mem_pin": true, // local pin for context priority
"mem_unpin": true, // local unpin for context priority
}
// ProfileAdmin contains tools for TUI, dashboards, and manual curation
// that are NOT referenced in any agent skill or memory protocol.
var ProfileAdmin = map[string]bool{
"mem_delete": true, // only in OpenCode's ENGRAM_TOOLS filter, not in any agent instructions
"mem_stats": true, // only in OpenCode's ENGRAM_TOOLS filter, not in any agent instructions
"mem_timeline": true, // only in OpenCode's ENGRAM_TOOLS filter, not in any agent instructions
"mem_merge_projects": true, // destructive curation tool — not for agent use
}
// Profiles maps profile names to their tool sets.
var Profiles = map[string]map[string]bool{
"agent": ProfileAgent,
"admin": ProfileAdmin,
}
// ResolveTools takes a comma-separated string of profile names and/or
// individual tool names and returns the set of tool names to register.
// An empty input means "all" — every tool is registered.
func ResolveTools(input string) map[string]bool {
input = strings.TrimSpace(input)
if input == "" || input == "all" {
return nil // nil means register everything
}
result := make(map[string]bool)
for _, token := range strings.Split(input, ",") {
token = strings.TrimSpace(token)
if token == "" {
continue
}
if token == "all" {
return nil
}
if profile, ok := Profiles[token]; ok {
for tool := range profile {
result[tool] = true
}
} else {
// Treat as individual tool name
result[token] = true
}
}
if len(result) == 0 {
return nil
}
return result
}
// NewServer creates an MCP server with ALL tools registered (backwards compatible).
func NewServer(s *store.Store) *server.MCPServer {
return NewServerWithConfig(s, MCPConfig{}, nil)
}
// serverInstructions tells MCP clients when to use Engram's tools.
// 7 core tools are eager (always in context). The rest are deferred
// and require ToolSearch to load.
const serverInstructions = `Engram provides persistent memory that survives across sessions and compactions.
CORE TOOLS (always available — use without ToolSearch):
mem_save — save decisions, bugs, discoveries, conventions PROACTIVELY (do not wait to be asked)
mem_search — find past work, decisions, or context from previous sessions
mem_context — get recent session history (call at session start or after compaction)
mem_session_summary — save end-of-session summary (MANDATORY before saying "done")
mem_get_observation — get full untruncated content of a search result by ID
mem_save_prompt — save user prompt for context
mem_current_project — detect current project from cwd (recommended first call)
DEFERRED TOOLS (use ToolSearch when needed):
mem_update, mem_review, mem_pin, mem_unpin, mem_suggest_topic_key, mem_session_start, mem_session_end,
mem_stats, mem_delete, mem_timeline, mem_capture_passive, mem_merge_projects
PROACTIVE SAVE RULE: Call mem_save immediately after ANY decision, bug fix, discovery, or convention — not just when asked.
## CONFLICT SURFACING — when mem_save returns candidates
After every mem_save call, check the response envelope for judgment_required.
IF judgment_required IS TRUE:
Iterate candidates[] and call mem_judge once per candidate using the
judgment_id from that candidate entry. Do NOT use the top-level judgment_id
for multiple candidates — each candidate has its own.
HEURISTIC — when to ask the user vs. resolve autonomously:
ASK the user (conversationally, as part of your next reply) when:
- confidence is below 0.7, OR
- the relation you would choose is supersedes or conflicts_with AND the
observation type is architecture, policy, or decision
RESOLVE silently (call mem_judge without asking) when:
- confidence >= 0.7 AND the relation is not supersedes/conflicts_with, OR
- the relation is related, compatible, scoped, or not_conflict
HOW TO ASK (conversationally — never via blocking CLI or dashboard prompt):
Raise it naturally in your next reply to the user. Example phrasing:
"I noticed memory #abc123 might conflict with what we just saved.
Want me to mark the new one as superseding it, or are they about
different scopes? I can also mark them as compatible if both still apply."
AFTER RESOLUTION (both paths):
Call mem_judge with the chosen relation, a reason, and if the user gave
explicit direction, include their words as the evidence field. This persists
the verdict and closes the pending conflict row.`
// NewServerWithTools creates an MCP server registering only the tools in
// the allowlist. If allowlist is nil, all tools are registered.
func NewServerWithTools(s *store.Store, allowlist map[string]bool) *server.MCPServer {
return NewServerWithConfig(s, MCPConfig{}, allowlist)
}
// NewServerWithConfig creates an MCP server with full configuration including
// default project detection and optional tool allowlist.
func NewServerWithConfig(s *store.Store, cfg MCPConfig, allowlist map[string]bool) *server.MCPServer {
return newServerWithActivity(s, cfg, allowlist, NewSessionActivity(10*time.Minute))
}
func newServerWithActivity(s *store.Store, cfg MCPConfig, allowlist map[string]bool, activity *SessionActivity) *server.MCPServer {
srv := server.NewMCPServer(
"engram",
"0.1.0",
server.WithToolCapabilities(true),
server.WithInstructions(serverInstructions),
)
registerTools(srv, s, cfg, allowlist, activity)
return srv
}
// shouldRegister returns true if the tool should be registered given the
// allowlist. If allowlist is nil, everything is allowed.
func shouldRegister(name string, allowlist map[string]bool) bool {
if allowlist == nil {
return true
}
return allowlist[name]
}
// registerTools registers all enabled MCP tools on the given server.
func registerTools(srv *server.MCPServer, s *store.Store, cfg MCPConfig, allowlist map[string]bool, activity *SessionActivity) {
writeQueue := newWriteQueue(defaultMCPWriteQueueSize)
// ─── mem_search (profile: agent, core — always in context) ─────────
if shouldRegister("mem_search", allowlist) {
srv.AddTool(
mcp.NewTool("mem_search",
mcp.WithDescription("Search your persistent memory across all sessions. Use this to find past decisions, bugs fixed, patterns used, files changed, or any context from previous coding sessions."),
mcp.WithTitleAnnotation("Search Memory"),
mcp.WithReadOnlyHintAnnotation(true),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(true),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithString("query",
mcp.Required(),
mcp.Description("Search query — natural language or keywords"),
),
mcp.WithString("type",
mcp.Description("Filter by type: tool_use, file_change, command, file_read, search, manual, decision, architecture, bugfix, pattern"),
),
mcp.WithString("project",
mcp.Description("Filter by project name. Ignored when all_projects=true."),
),
mcp.WithBoolean("all_projects",
mcp.Description("Search across every project instead of the current one. When true, the project argument is ignored and results may come from any project. Useful for recalling decisions logged elsewhere when you don't know the project key."),
),
mcp.WithString("scope",
mcp.Description("Filter by scope: project (default) or personal"),
),
mcp.WithString("match_mode",
mcp.Description("Token matching: \"all\" (default — every token must match, FTS5 AND) or \"any\" (any token matches — broader recall for multi-token queries). Any other value returns an error."),
),
mcp.WithNumber("limit",
mcp.Description("Max results (default: 10, max: 20)"),
),
),
handleSearch(s, cfg, activity),
)
}
// ─── mem_find_project ─────────────────────────────────────────────
if shouldRegister("mem_find_project", allowlist) {
srv.AddTool(
mcp.NewTool("mem_find_project",
mcp.WithDescription("Search for projects containing relevant memories. Use this when you don't know which project holds a past decision. It returns the top matching projects, their match counts, and rank. You can then use mem_search with a specific project name to read those memories."),
mcp.WithTitleAnnotation("Find Projects"),
mcp.WithReadOnlyHintAnnotation(true),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(true),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithString("query",
mcp.Required(),
mcp.Description("Search query — natural language or keywords to find across all projects"),
),
mcp.WithString("match_mode",
mcp.Description("Token matching: \"all\" (default — every token must match, FTS5 AND) or \"any\" (any token matches)."),
),
),
handleFindProject(s, cfg),
)
}
// ─── mem_save (profile: agent, core — always in context) ───────────
if shouldRegister("mem_save", allowlist) {
srv.AddTool(
mcp.NewTool("mem_save",
mcp.WithTitleAnnotation("Save Memory"),
mcp.WithReadOnlyHintAnnotation(false),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(false),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithDescription(`Save an important observation to persistent memory. Call this PROACTIVELY after completing significant work — don't wait to be asked.
WHEN to save (call this after each of these):
- Architectural decisions or tradeoffs
- Bug fixes (what was wrong, why, how you fixed it)
- New patterns or conventions established
- Configuration changes or environment setup
- Important discoveries or gotchas
- File structure changes
FORMAT for content — use this structured format:
**What**: [concise description of what was done]
**Why**: [the reasoning, user request, or problem that drove it]
**Where**: [files/paths affected, e.g. src/auth/middleware.ts, internal/store/store.go]
**Learned**: [any gotchas, edge cases, or decisions made — omit if none]
TITLE should be short and searchable, like: "JWT auth middleware", "FTS5 query sanitization", "Fixed N+1 in user list"
Examples:
title: "Switched from sessions to JWT"
type: "decision"
content: "**What**: Replaced express-session with jsonwebtoken for auth\n**Why**: Session storage doesn't scale across multiple instances\n**Where**: src/middleware/auth.ts, src/routes/login.ts\n**Learned**: Must set httpOnly and secure flags on the cookie, refresh tokens need separate rotation logic"
title: "Fixed FTS5 syntax error on special chars"
type: "bugfix"
content: "**What**: Wrapped each search term in quotes before passing to FTS5 MATCH\n**Why**: Users typing queries like 'fix auth bug' would crash because FTS5 interprets special chars as operators\n**Where**: internal/store/store.go — sanitizeFTS() function\n**Learned**: FTS5 MATCH syntax is NOT the same as LIKE — always sanitize user input"`),
mcp.WithString("title",
mcp.Required(),
mcp.Description("Short, searchable title (e.g. 'JWT auth middleware', 'Fixed N+1 query')"),
),
mcp.WithString("content",
mcp.Description("Structured content using **What**, **Why**, **Where**, **Learned** format. Required unless observation alias is provided."),
),
mcp.WithString("observation",
mcp.Description("Backward-compatible alias for content. Prefer content for new clients."),
),
mcp.WithString("type",
mcp.Description("Category: decision, architecture, bugfix, pattern, config, discovery, learning (default: manual)"),
),
mcp.WithString("session_id",
mcp.Description("Session ID to associate with (default: manual-save-{project})"),
),
mcp.WithString("scope",
mcp.Description("Scope for this observation: project (default) or personal"),
),
mcp.WithString("topic_key",
mcp.Description("Optional topic identifier for upserts (e.g. architecture/auth-model). Reuses and updates the latest observation in same project+scope."),
),
mcp.WithString("project",
mcp.Description("Optional explicit project for this memory. Accepted only when backed by known context (existing project, matching session, repo config, or ambiguous-project recovery); invalid or unbacked names fail loudly."),
),
mcp.WithString("project_choice_reason",
mcp.Description("Must be user_selected_after_ambiguous_project, and only after the user explicitly chose one of available_projects from an ambiguous_project error."),
),
mcp.WithString("recovery_token",
mcp.Description("Short-lived token returned by an ambiguous_project error. Required with project_choice_reason=user_selected_after_ambiguous_project."),
),
mcp.WithBoolean("capture_prompt",
mcp.Description("Automatically capture the current user prompt when available (default: true). Set false for SDD artifacts or automated saves."),
),
),
queuedWriteHandler(writeQueue, handleSave(s, cfg, activity)),
)
}
// ─── mem_update (profile: agent, deferred) ──────────────────────────
if shouldRegister("mem_update", allowlist) {
srv.AddTool(
mcp.NewTool("mem_update",
mcp.WithDescription("Update an existing observation by ID. Only provided fields are changed."),
mcp.WithDeferLoading(true),
mcp.WithTitleAnnotation("Update Memory"),
mcp.WithReadOnlyHintAnnotation(false),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(false),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithNumber("id",
mcp.Required(),
mcp.Description("Observation ID to update"),
),
mcp.WithString("title",
mcp.Description("New title"),
),
mcp.WithString("content",
mcp.Description("New content"),
),
mcp.WithString("type",
mcp.Description("New type/category"),
),
mcp.WithString("scope",
mcp.Description("New scope: project or personal"),
),
mcp.WithString("topic_key",
mcp.Description("New topic key (normalized internally)"),
),
),
queuedWriteHandler(writeQueue, handleUpdate(s)),
)
}
// ─── mem_review (profile: agent, deferred) ──────────────────────────
if shouldRegister("mem_review", allowlist) {
srv.AddTool(
mcp.NewTool("mem_review",
mcp.WithDescription("Review observation lifecycle state. action=list returns observations whose review_after has passed; action=mark_reviewed resets one observation's review_after using its type decay policy."),
mcp.WithDeferLoading(true),
mcp.WithTitleAnnotation("Review Memories"),
mcp.WithReadOnlyHintAnnotation(false),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(false),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithString("action", mcp.Required(), mcp.Description("Action: list | mark_reviewed")),
mcp.WithString("project", mcp.Description("Optional project filter for action=list; omit to list all projects.")),
mcp.WithNumber("limit", mcp.Description("Max results for action=list (default: 10).")),
mcp.WithNumber("observation_id", mcp.Description("Observation id for action=mark_reviewed.")),
mcp.WithNumber("id", mcp.Description("Backward-compatible alias for observation_id.")),
),
queuedWriteHandler(writeQueue, handleReview(s, cfg)),
)
}
// ─── mem_suggest_topic_key (profile: agent, deferred) ───────────────
if shouldRegister("mem_suggest_topic_key", allowlist) {
srv.AddTool(
mcp.NewTool("mem_suggest_topic_key",
mcp.WithDescription("Suggest a stable topic_key for memory upserts. Use this before mem_save when you want evolving topics (like architecture decisions) to update a single observation over time."),
mcp.WithDeferLoading(true),
mcp.WithTitleAnnotation("Suggest Topic Key"),
mcp.WithReadOnlyHintAnnotation(true),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(true),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithString("type",
mcp.Description("Observation type/category, e.g. architecture, decision, bugfix"),
),
mcp.WithString("title",
mcp.Description("Observation title (preferred input for stable keys)"),
),
mcp.WithString("content",
mcp.Description("Observation content used as fallback if title is empty"),
),
),
handleSuggestTopicKey(),
)
}
// ─── mem_delete (profile: admin, deferred) ──────────────────────────
if shouldRegister("mem_delete", allowlist) {
srv.AddTool(
mcp.NewTool("mem_delete",
mcp.WithDescription("Delete an observation by ID. Soft-delete by default; set hard_delete=true for permanent deletion."),
mcp.WithDeferLoading(true),
mcp.WithTitleAnnotation("Delete Memory"),
mcp.WithReadOnlyHintAnnotation(false),
mcp.WithDestructiveHintAnnotation(true),
mcp.WithIdempotentHintAnnotation(false),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithNumber("id",
mcp.Required(),
mcp.Description("Observation ID to delete"),
),
mcp.WithBoolean("hard_delete",
mcp.Description("If true, permanently deletes the observation"),
),
),
queuedWriteHandler(writeQueue, handleDelete(s)),
)
}
// ─── mem_save_prompt (profile: agent, eager) ────────────────────────
if shouldRegister("mem_save_prompt", allowlist) {
srv.AddTool(
mcp.NewTool("mem_save_prompt",
mcp.WithDescription("Save a user prompt to persistent memory. Use this to record what the user asked — their intent, questions, and requests — so future sessions have context about the user's goals."),
mcp.WithTitleAnnotation("Save User Prompt"),
mcp.WithReadOnlyHintAnnotation(false),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(false),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithString("content",
mcp.Required(),
mcp.Description("The user's prompt text"),
),
mcp.WithString("session_id",
mcp.Description("Session ID to associate with (default: manual-save-{project})"),
),
mcp.WithString("project",
mcp.Description("Optional recovery target only after ambiguous_project. Ignored unless project_choice_reason is user_selected_after_ambiguous_project."),
),
mcp.WithString("project_choice_reason",
mcp.Description("Must be user_selected_after_ambiguous_project, and only after the user explicitly chose one of available_projects from an ambiguous_project error."),
),
mcp.WithString("recovery_token",
mcp.Description("Short-lived token returned by an ambiguous_project error. Required with project_choice_reason=user_selected_after_ambiguous_project."),
),
),
queuedWriteHandler(writeQueue, handleSavePrompt(s, cfg, activity)),
)
}
// ─── mem_pin / mem_unpin (profile: agent, deferred) ──────────────────
if shouldRegister("mem_pin", allowlist) {
srv.AddTool(
mcp.NewTool("mem_pin",
mcp.WithDescription("Pin a local observation so it appears before recent observations in memory context. Pinned state is local to this device and is not synced."),
mcp.WithDeferLoading(true),
mcp.WithTitleAnnotation("Pin Memory"),
mcp.WithReadOnlyHintAnnotation(false),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(true),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithNumber("id", mcp.Required(), mcp.Description("Observation ID to pin")),
),
handlePin(s, true),
)
}
if shouldRegister("mem_unpin", allowlist) {
srv.AddTool(
mcp.NewTool("mem_unpin",
mcp.WithDescription("Unpin a local observation so it only appears in normal recency order. Pinned state is local to this device and is not synced."),
mcp.WithDeferLoading(true),
mcp.WithTitleAnnotation("Unpin Memory"),
mcp.WithReadOnlyHintAnnotation(false),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(true),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithNumber("id", mcp.Required(), mcp.Description("Observation ID to unpin")),
),
handlePin(s, false),
)
}
// ─── mem_context (profile: agent, core — always in context) ────────
if shouldRegister("mem_context", allowlist) {
srv.AddTool(
mcp.NewTool("mem_context",
mcp.WithDescription("Get recent memory context from previous sessions. Shows recent sessions and observations to understand what was done before."),
mcp.WithTitleAnnotation("Get Memory Context"),
mcp.WithReadOnlyHintAnnotation(true),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(true),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithString("project",
mcp.Description("Filter by project (omit for all projects)"),
),
mcp.WithString("scope",
mcp.Description("Filter observations by scope: project (default) or personal"),
),
// JW7: limit param removed — schema advertised it but handleContext never read it.
),
handleContext(s, cfg, activity),
)
}
// ─── mem_stats (profile: admin, deferred) ───────────────────────────
if shouldRegister("mem_stats", allowlist) {
srv.AddTool(
mcp.NewTool("mem_stats",
mcp.WithDescription("Show memory system statistics — total sessions, observations, and projects tracked."),
mcp.WithDeferLoading(true),
mcp.WithTitleAnnotation("Memory Stats"),
mcp.WithReadOnlyHintAnnotation(true),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(true),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithString("project",
mcp.Description("Project to echo in envelope context (omit for auto-detect; stats themselves are global aggregates)"),
),
),
handleStats(s, cfg),
)
}
// ─── mem_timeline (profile: admin, deferred) ────────────────────────
if shouldRegister("mem_timeline", allowlist) {
srv.AddTool(
mcp.NewTool("mem_timeline",
mcp.WithDescription("Show chronological context around a specific observation. Use after mem_search to drill into the timeline of events surrounding a search result. This is the progressive disclosure pattern: search first, then timeline to understand context."),
mcp.WithDeferLoading(true),
mcp.WithTitleAnnotation("Memory Timeline"),
mcp.WithReadOnlyHintAnnotation(true),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(true),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithNumber("observation_id",
mcp.Required(),
mcp.Description("The observation ID to center the timeline on (from mem_search results)"),
),
mcp.WithNumber("before",
mcp.Description("Number of observations to show before the focus (default: 5)"),
),
mcp.WithNumber("after",
mcp.Description("Number of observations to show after the focus (default: 5)"),
),
mcp.WithString("project",
mcp.Description("Filter by project name (omit for auto-detect)"),
),
),
handleTimeline(s, cfg),
)
}
// ─── mem_get_observation (profile: agent, eager) ────────────────────
if shouldRegister("mem_get_observation", allowlist) {
srv.AddTool(
mcp.NewTool("mem_get_observation",
mcp.WithDescription("Get the full content of a specific observation by ID. Use when you need the complete, untruncated content of an observation found via mem_search or mem_timeline."),
mcp.WithTitleAnnotation("Get Observation"),
mcp.WithReadOnlyHintAnnotation(true),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(true),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithNumber("id",
mcp.Required(),
mcp.Description("The observation ID to retrieve"),
),
),
handleGetObservation(s, cfg),
)
}
// ─── mem_session_summary (profile: agent, core — always in context) ─
if shouldRegister("mem_session_summary", allowlist) {
srv.AddTool(
mcp.NewTool("mem_session_summary",
mcp.WithTitleAnnotation("Save Session Summary"),
mcp.WithReadOnlyHintAnnotation(false),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(false),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithDescription(`Save a comprehensive end-of-session summary. Call this when a session is ending or when significant work is complete. This creates a structured summary that future sessions will use to understand what happened.
FORMAT — use this exact structure in the content field:
## Goal
[One sentence: what were we building/working on in this session]
## Instructions
[User preferences, constraints, or context discovered during this session. Things a future agent needs to know about HOW the user wants things done. Skip if nothing notable.]
## Discoveries
- [Technical finding, gotcha, or learning 1]
- [Technical finding 2]
- [Important API behavior, config quirk, etc.]
## Accomplished
- ✅ [Completed task 1 — with key implementation details]
- ✅ [Completed task 2 — mention files changed]
- 🔲 [Identified but not yet done — for next session]
## Next Steps
- [What remains to be done — for the next session]
## Relevant Files
- path/to/file.ts — [what it does or what changed]
- path/to/other.go — [role in the architecture]
GUIDELINES:
- Be CONCISE but don't lose important details (file paths, error messages, decisions)
- Focus on WHAT and WHY, not HOW (the code itself is in the repo)
- Include things that would save a future agent time
- The Discoveries section is the most valuable — capture gotchas and non-obvious learnings
- Relevant Files should only include files that were significantly changed or are important for context`),
mcp.WithString("content",
mcp.Required(),
mcp.Description("Full session summary using the Goal/Instructions/Discoveries/Accomplished/Next Steps/Relevant Files format"),
),
mcp.WithString("session_id",
mcp.Description("Session ID (default: manual-save-{project})"),
),
mcp.WithString("project",
mcp.Description("Optional explicit project for this memory. Accepted only when backed by known context (existing project, matching session, repo config, or ambiguous-project recovery); invalid or unbacked names fail loudly."),
),
mcp.WithString("project_choice_reason",
mcp.Description("Must be user_selected_after_ambiguous_project, and only after the user explicitly chose one of available_projects from an ambiguous_project error."),
),
mcp.WithString("recovery_token",
mcp.Description("Short-lived token returned by an ambiguous_project error. Required with project_choice_reason=user_selected_after_ambiguous_project."),
),
),
queuedWriteHandler(writeQueue, handleSessionSummary(s, cfg, activity)),
)
}
// ─── mem_session_start (profile: agent, deferred) ───────────────────
if shouldRegister("mem_session_start", allowlist) {
srv.AddTool(
mcp.NewTool("mem_session_start",
mcp.WithDescription("Register the start of a new coding session. Call this at the beginning of a session to track activity."),
mcp.WithDeferLoading(true),
mcp.WithTitleAnnotation("Start Session"),
mcp.WithReadOnlyHintAnnotation(false),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(true),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithString("id",
mcp.Required(),
mcp.Description("Unique session identifier"),
),
mcp.WithString("directory",
mcp.Description("Working directory"),
),
),
queuedWriteHandler(writeQueue, handleSessionStart(s, cfg, activity)),
)
}
// ─── mem_session_end (profile: agent, deferred) ─────────────────────
if shouldRegister("mem_session_end", allowlist) {
srv.AddTool(
mcp.NewTool("mem_session_end",
mcp.WithDescription("Mark a coding session as completed with an optional summary."),
mcp.WithDeferLoading(true),
mcp.WithTitleAnnotation("End Session"),
mcp.WithReadOnlyHintAnnotation(false),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(true),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithString("id",
mcp.Required(),
mcp.Description("Session identifier to close"),
),
mcp.WithString("summary",
mcp.Description("Summary of what was accomplished"),
),
),
queuedWriteHandler(writeQueue, handleSessionEnd(s, cfg, activity)),
)
}
// ─── mem_capture_passive (profile: agent, deferred) ─────────────────
if shouldRegister("mem_capture_passive", allowlist) {
srv.AddTool(
mcp.NewTool("mem_capture_passive",
mcp.WithDeferLoading(true),
mcp.WithTitleAnnotation("Capture Learnings"),
mcp.WithReadOnlyHintAnnotation(false),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(true),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithDescription(`Extract and save structured learnings from text output. Use this at the end of a task to capture knowledge automatically.
The tool looks for sections like "## Key Learnings:" or "## Aprendizajes Clave:" and extracts numbered or bulleted items. Each item is saved as a separate observation.
Duplicates are automatically detected and skipped — safe to call multiple times with the same content.`),
mcp.WithString("content",
mcp.Required(),
mcp.Description("The text output containing a '## Key Learnings:' section with numbered or bulleted items"),
),
mcp.WithString("session_id",
mcp.Description("Session ID (default: manual-save-{project})"),
),
mcp.WithString("source",
mcp.Description("Source identifier (e.g. 'subagent-stop', 'session-end')"),
),
),
queuedWriteHandler(writeQueue, handleCapturePassive(s, cfg, activity)),
)
}
// ─── mem_merge_projects (profile: admin, deferred) ──────────────────
if shouldRegister("mem_merge_projects", allowlist) {
srv.AddTool(
mcp.NewTool("mem_merge_projects",
mcp.WithDescription("Merge memories from multiple project name variants into one canonical name. Use when you discover project name drift (e.g. 'Engram' and 'engram' should be the same project). DESTRUCTIVE — moves all records from source names to the canonical name."),
mcp.WithDeferLoading(true),
mcp.WithTitleAnnotation("Merge Projects"),
mcp.WithReadOnlyHintAnnotation(false),
mcp.WithDestructiveHintAnnotation(true),
mcp.WithIdempotentHintAnnotation(true),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithString("from",
mcp.Required(),
mcp.Description("Comma-separated list of project names to merge FROM (e.g. 'Engram,engram-memory,ENGRAM')"),
),
mcp.WithString("to",
mcp.Required(),
mcp.Description("The canonical project name to merge INTO (e.g. 'engram')"),
),
),
queuedWriteHandler(writeQueue, handleMergeProjects(s)),
)
}
// ─── mem_current_project (profile: agent) ────────────────────────────
if shouldRegister("mem_current_project", allowlist) {
srv.AddTool(
mcp.NewTool("mem_current_project",
mcp.WithDescription("Detect the current project from the working directory. Returns project name, source (how it was detected), path, and available alternatives. NEVER errors — use this for discovery before writing. Recommended as the first call when starting a new session."),
mcp.WithTitleAnnotation("Detect Current Project"),
mcp.WithReadOnlyHintAnnotation(true),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(true),
mcp.WithOpenWorldHintAnnotation(false),
),
handleCurrentProject(s, cfg),
)
}
// ─── mem_doctor (profile: agent, deferred) ──────────────────────────
if shouldRegister("mem_doctor", allowlist) {
srv.AddTool(
mcp.NewTool("mem_doctor",
mcp.WithDescription("Run read-only operational diagnostics. Returns the same structured envelope as `engram doctor --json`."),
mcp.WithDeferLoading(true),
mcp.WithTitleAnnotation("Run Engram Doctor"),
mcp.WithReadOnlyHintAnnotation(true),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(true),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithString("project", mcp.Description("Project to diagnose (omit for auto-detect)")),
mcp.WithString("check", mcp.Description("Optional diagnostic check code to run")),
),
handleDoctor(s, cfg),
)
}
// ─── mem_judge (profile: agent, eager) — REQ-003, Design §6 ─────────
if shouldRegister("mem_judge", allowlist) {
srv.AddTool(
mcp.NewTool("mem_judge",
mcp.WithDescription(`Record a verdict on a pending memory conflict surfaced by mem_save.
WHEN TO CALL: After mem_save returns judgment_required=true, iterate candidates[] and call mem_judge once per entry using that entry's judgment_id.
PARAMS:
judgment_id (required) — from candidates[].judgment_id in the mem_save response
relation (required) — one of: related, compatible, scoped, conflicts_with, supersedes, not_conflict
reason (optional) — free-text explanation of the verdict
evidence (optional) — JSON or text supporting the verdict
confidence (optional) — float 0..1; default 1.0
WHEN TO ASK USER:
- confidence < 0.7: surface to user before judging
- relation in {supersedes, conflicts_with} AND type in {architecture, policy, decision}: ask user
- otherwise: resolve silently
SUCCESS: Returns the updated relation row with judgment_status="judged".
ERROR: Returns IsError=true if judgment_id is unknown or relation verb is invalid. Row is NOT mutated on error.
Re-judging an already-judged ID overwrites the verdict (deliberate revision).`),
mcp.WithTitleAnnotation("Judge Memory Conflict"),
mcp.WithReadOnlyHintAnnotation(false),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(false),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithString("judgment_id",
mcp.Required(),
mcp.Description("The judgment_id from candidates[] in the mem_save response (format: rel-<hex>)"),
),
mcp.WithString("relation",
mcp.Required(),
mcp.Description("Verdict: related | compatible | scoped | conflicts_with | supersedes | not_conflict"),
),
mcp.WithString("reason",
mcp.Description("Free-text explanation of the verdict"),
),
mcp.WithString("evidence",
mcp.Description("Supporting evidence (JSON or free text)"),
),
mcp.WithNumber("confidence",
mcp.Description("Confidence score 0.0..1.0 (default: 1.0)"),
),
mcp.WithString("session_id",
mcp.Description("Session ID for provenance (default: auto)"),
),
),
queuedWriteHandler(writeQueue, handleJudge(s, activity)),
)
}
// ─── mem_compare (profile: agent, eager) — REQ-011, Design §9 ────────
if shouldRegister("mem_compare", allowlist) {
srv.AddTool(
mcp.NewTool("mem_compare",
mcp.WithDescription(`Persist a semantic verdict you have already judged externally (with your LLM) into Engram.
WHEN TO CALL: After you have evaluated two memories and reached a verdict, call mem_compare to PERSIST that verdict into the relation store. You do the judgment; mem_compare records it.
PARAMS:
memory_id_a (required) — integer id of the first observation (from mem_search or mem_get_observation)
memory_id_b (required) — integer id of the second observation
relation (required) — one of: related, compatible, scoped, conflicts_with, supersedes, not_conflict
confidence (required) — float 0..1; your self-reported confidence in the verdict
reasoning (required) — explanation of the verdict, max 200 chars
model (optional) — your model identifier, stored for provenance (e.g. "claude-haiku-4-5")
BEHAVIOR:
- Persists the verdict via JudgeBySemantic with system provenance (marked_by_actor="engram").
- not_conflict: no row is inserted; tool returns success with empty sync_id (the verdict is recorded but not stored — it means "we evaluated these and they do not conflict").
- Idempotent: calling again for the same pair updates the existing row.
- Cross-project pairs are rejected.
SUCCESS: Returns { "sync_id": "rel-..." } on persist, { "sync_id": "" } on not_conflict.
ERROR: Returns IsError=true if IDs are unknown, relation is invalid, or cross-project pair.`),
mcp.WithTitleAnnotation("Compare Memory Pair (Persist Semantic Verdict)"),
mcp.WithReadOnlyHintAnnotation(false),
mcp.WithDestructiveHintAnnotation(false),
mcp.WithIdempotentHintAnnotation(true),
mcp.WithOpenWorldHintAnnotation(false),
mcp.WithNumber("memory_id_a",
mcp.Required(),
mcp.Description("Integer id of the first observation (from mem_search #id)"),
),
mcp.WithNumber("memory_id_b",
mcp.Required(),
mcp.Description("Integer id of the second observation (from mem_search #id)"),
),
mcp.WithString("relation",
mcp.Required(),
mcp.Description("Verdict: related | compatible | scoped | conflicts_with | supersedes | not_conflict"),
),
mcp.WithNumber("confidence",
mcp.Required(),
mcp.Description("Confidence score 0.0..1.0"),
),
mcp.WithString("reasoning",
mcp.Required(),
mcp.Description("Brief explanation of the verdict (max 200 chars)"),
),
mcp.WithString("model",
mcp.Description("Your model identifier for provenance (e.g. \"claude-haiku-4-5\")"),
),
),
handleCompare(s, activity),
)
}
}
// ─── Tool Handlers ───────────────────────────────────────────────────────────
// handleCurrentProject implements mem_current_project. It NEVER returns an error
// even on ambiguous cwd — it always returns a success result with whatever
// detection info is available (REQ-313).
func handleCurrentProject(s *store.Store, cfg MCPConfig) server.ToolHandlerFunc {
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
cwd, _ := os.Getwd()
res := projectpkg.DetectProjectFull(cwd)
if processRes, ok := processProjectResult(cfg.DefaultProject); ok {
res = processRes
}
envelope := map[string]any{
"project": res.Project,
"project_source": res.Source,
"project_path": res.Path,
"cwd": cwd,
"available_projects": res.AvailableProjects,
}
if res.Warning != "" {
envelope["warning"] = res.Warning
}
if res.Error != nil {
// REQ-313: not an error response — just surface the info.
envelope["error_hint"] = res.Error.Error()
}
out, _ := jsonMarshal(envelope)
return mcp.NewToolResultText(string(out)), nil
}
}
func handleSearch(s *store.Store, cfg MCPConfig, activity *SessionActivity) server.ToolHandlerFunc {
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
query, _ := req.GetArguments()["query"].(string)
typ, _ := req.GetArguments()["type"].(string)
projectOverride, _ := req.GetArguments()["project"].(string)
scope, _ := req.GetArguments()["scope"].(string)
matchMode, _ := req.GetArguments()["match_mode"].(string)
allProjects := boolArg(req, "all_projects", false)
limit := intArg(req, "limit", 10)