@membank/mcp 0.10.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,7 +4,7 @@ MCP server for membank. Exposes memory tools to LLMs via the [Model Context Prot
4
4
 
5
5
  ## Overview
6
6
 
7
- Runs as a stdio MCP server. LLM harnesses (Claude Code, GitHub Copilot, etc.) connect to it and can call five tools to query, save, update, and delete memories.
7
+ Runs as a stdio MCP server. LLM harnesses (Claude Code, GitHub Copilot, etc.) connect to it and can call tools to query, save, update, delete, pin, and migrate memories.
8
8
 
9
9
  In most cases you don't need to use this package directly — `@membank/cli` starts the server via the `--mcp` flag and `membank setup` writes the harness config automatically.
10
10
 
@@ -42,10 +42,11 @@ If you're configuring a harness by hand, point it at:
42
42
  Semantic search over stored memories.
43
43
 
44
44
  ```
45
- query string required Natural language search query
46
- type enum optional Filter by memory type
47
- scope string optional Filter by project scope
48
- limit number optional Max results (default: 10)
45
+ query string required Natural language search query
46
+ type enum optional Filter by memory type
47
+ limit number optional Max results (default: 10)
48
+ includePinned boolean optional Include pinned memories in results (excluded by default to avoid duplicates)
49
+ global boolean optional Query global memories only; omit or false to query current project scope
49
50
  ```
50
51
 
51
52
  Returns an array of memories with scores.
@@ -55,21 +56,22 @@ Returns an array of memories with scores.
55
56
  Store a new memory. Deduplication runs automatically.
56
57
 
57
58
  ```
58
- content string required Memory content
59
- type enum required correction | preference | decision | learning | fact
60
- tags array optional String tags for grouping
61
- scope string optional Project scope (auto-resolved if omitted)
59
+ content string required Memory content
60
+ type enum required correction | preference | decision | learning | fact
61
+ tags array optional String tags for grouping
62
+ global boolean optional Save as a global memory, not tied to any project
62
63
  ```
63
64
 
64
65
  Returns the saved Memory object.
65
66
 
66
67
  ### `update_memory`
67
68
 
68
- Update the content or tags of an existing memory.
69
+ Update the content, type, and/or tags of an existing memory.
69
70
 
70
71
  ```
71
72
  id string required Memory ID
72
- content string required New content
73
+ content string optional New content
74
+ type enum optional New type (reclassification)
73
75
  tags array optional Replacement tags
74
76
  ```
75
77
 
@@ -89,6 +91,49 @@ Returns `{ success: true, id }`.
89
91
 
90
92
  Returns the ordered list of valid memory type values. No input required.
91
93
 
94
+ ### `pin_memory`
95
+
96
+ Pin a memory so it is always injected into session context.
97
+
98
+ ```
99
+ id string required Memory ID to pin
100
+ ```
101
+
102
+ ### `unpin_memory`
103
+
104
+ Remove a memory from guaranteed session injection.
105
+
106
+ ```
107
+ id string required Memory ID to unpin
108
+ ```
109
+
110
+ ### `get_memory_summary`
111
+
112
+ Returns aggregate stats: total memories, counts by type, pinned count, and review queue size. No input required.
113
+
114
+ ### `list_flagged_memories`
115
+
116
+ List memories with unresolved dedup review events (similarity 0.75–0.92). No input required.
117
+
118
+ ### `resolve_review`
119
+
120
+ Dismiss all open review events for a memory after reviewing it.
121
+
122
+ ```
123
+ id string required Memory ID to resolve review events for
124
+ ```
125
+
126
+ Returns `{ success: true, id }`.
127
+
128
+ ### `migrate`
129
+
130
+ List or run named data migrations.
131
+
132
+ ```
133
+ mode enum required "list" to see available migrations, "run" to execute one
134
+ name string optional Migration name (required when mode is "run")
135
+ ```
136
+
92
137
  ## Architecture
93
138
 
94
139
  ```
package/dist/index.mjs CHANGED
@@ -1,8 +1,12 @@
1
1
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
2
- import { DatabaseManager, EmbeddingService, MEMORY_TYPE_VALUES, MIGRATIONS, MemoryRepository, MemoryTypeSchema, ProjectRepository, QueryEngine, listMemoryTypes, resolveProject, runScopeToProjectsMigration } from "@membank/core";
2
+ import { readFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { DatabaseManager, EmbeddingService, MEMORY_TYPE_VALUES, MIGRATIONS, MemoryRepository, MemoryTypeSchema, PIN_BUDGET_THRESHOLD, ProjectRepository, QueryEngine, SynthesisRepository, isSynthesisEnabled, listMemoryTypes, resolveProject, runScopeToProjectsMigration } from "@membank/core";
3
6
  import { Server } from "@modelcontextprotocol/sdk/server";
4
7
  import { CallToolRequestSchema, ErrorCode, ListToolsRequestSchema, McpError } from "@modelcontextprotocol/sdk/types.js";
5
8
  import { ZodError, z } from "zod";
9
+ import { createSdkMcpServer, query, tool } from "@anthropic-ai/claude-agent-sdk";
6
10
  //#region src/schemas.ts
7
11
  const SaveMemoryArgsSchema = z.object({
8
12
  content: z.string().min(1),
@@ -12,7 +16,8 @@ const SaveMemoryArgsSchema = z.object({
12
16
  });
13
17
  const UpdateMemoryArgsSchema = z.object({
14
18
  id: z.string().min(1),
15
- content: z.string().min(1),
19
+ content: z.string().min(1).optional(),
20
+ type: MemoryTypeSchema.optional(),
16
21
  tags: z.array(z.string()).optional()
17
22
  });
18
23
  const DeleteMemoryArgsSchema = z.object({ id: z.string().min(1) });
@@ -20,28 +25,207 @@ const QueryMemoryArgsSchema = z.object({
20
25
  query: z.string().min(1),
21
26
  type: MemoryTypeSchema.optional(),
22
27
  limit: z.number().int().positive().optional(),
23
- includePinned: z.boolean().optional()
28
+ includePinned: z.boolean().optional(),
29
+ global: z.boolean().optional()
24
30
  });
25
31
  const MigrateArgsSchema = z.discriminatedUnion("mode", [z.object({ mode: z.literal("list") }), z.object({
26
32
  mode: z.literal("run"),
27
33
  name: z.string().min(1)
28
34
  })]);
29
35
  const PinMemoryArgsSchema = z.object({ id: z.string().min(1) });
36
+ const ResolveReviewArgsSchema = z.object({ id: z.string().min(1) });
37
+ //#endregion
38
+ //#region src/synthesis/agent-loop.ts
39
+ const SYNTHESIS_SYSTEM_PROMPT = "You are a memory synthesizer. Your job is to read the user's stored memories and produce a concise, well-structured summary of what's most important to remember about this user — their preferences, corrections, decisions, and key facts. Pinned memories are higher fidelity and should be weighted more heavily. Exclude transient or ephemeral details. Output plain text suitable for injection into an LLM context window. Be concise — target 200-400 words.";
40
+ const MAX_TURNS = 3;
41
+ var SynthesisAgentLoop = class {
42
+ #tools;
43
+ constructor(tools, _config) {
44
+ this.#tools = tools;
45
+ }
46
+ async run(scope) {
47
+ const mcpServer = createSdkMcpServer({
48
+ name: "membank-synthesis-tools",
49
+ version: "1.0.0",
50
+ tools: [tool("query_memory", "Search memories by semantic similarity", {
51
+ query: z.string().describe("Search text"),
52
+ limit: z.number().optional().describe("Maximum results to return"),
53
+ global: z.boolean().optional().describe("Query global memories only when true, otherwise current project scope")
54
+ }, async ({ query: q, limit, global: isGlobal }) => {
55
+ return { content: [{
56
+ type: "text",
57
+ text: await this.#tools.queryMemory({
58
+ query: q,
59
+ limit,
60
+ global: isGlobal
61
+ })
62
+ }] };
63
+ }, { annotations: { readOnlyHint: true } }), tool("get_memory_summary", "Returns aggregate stats: total memories, counts by type, pinned count, review queue size", {}, async () => {
64
+ return { content: [{
65
+ type: "text",
66
+ text: await this.#tools.getMemorySummary()
67
+ }] };
68
+ }, { annotations: { readOnlyHint: true } })]
69
+ });
70
+ const prompt = `Synthesize the memories for ${scope === "global" ? "global (across all projects)" : `project scope: ${scope}`}. Use get_memory_summary first to understand the overall state, then use query_memory to retrieve relevant memories (query with broad terms like "preferences", "corrections", "decisions", "key facts"). After gathering information, produce a concise synthesis of the most important things to remember about this user. Output only the synthesis text — no preamble, no metadata.`;
71
+ const startTime = Date.now();
72
+ const env = Object.fromEntries(Object.entries(process.env).filter((e) => e[1] !== void 0));
73
+ const agentQuery = query({
74
+ prompt,
75
+ options: {
76
+ model: "claude-haiku-4-5-20251001",
77
+ maxTurns: MAX_TURNS,
78
+ systemPrompt: SYNTHESIS_SYSTEM_PROMPT,
79
+ mcpServers: { "membank-synthesis-tools": mcpServer },
80
+ allowedTools: ["query_memory", "get_memory_summary"],
81
+ permissionMode: "dontAsk",
82
+ env
83
+ }
84
+ });
85
+ let finalResult = "";
86
+ for await (const message of agentQuery) if (message.type === "result") if (message.subtype === "success") finalResult = message.result;
87
+ else {
88
+ const details = "errors" in message && Array.isArray(message.errors) ? `: ${message.errors.join("; ")}` : "";
89
+ throw new Error(`Synthesis agent failed: ${message.subtype}${details}`);
90
+ }
91
+ const durationMs = Date.now() - startTime;
92
+ process.stderr.write(`membank synthesis: scope=${scope} duration=${durationMs}ms\n`);
93
+ if (finalResult === "") throw new Error("Synthesis agent returned empty result");
94
+ return finalResult;
95
+ }
96
+ };
97
+ //#endregion
98
+ //#region src/synthesis/engine.ts
99
+ const DEFAULT_DEBOUNCE_MS = 45e3;
100
+ const DEFAULT_IN_FLIGHT_TIMEOUT_MS = 12e4;
101
+ const MAX_BACKOFF_MULTIPLIER = 5;
102
+ var SynthesisEngine = class {
103
+ #synthRepo;
104
+ #config;
105
+ #agentLoop;
106
+ #dirtyScopes = /* @__PURE__ */ new Set();
107
+ #failureCounts = /* @__PURE__ */ new Map();
108
+ #running = false;
109
+ #loopTimer;
110
+ #inFlightPromises = /* @__PURE__ */ new Map();
111
+ constructor(_db, synthRepo, config, agentLoop) {
112
+ this.#synthRepo = synthRepo;
113
+ this.#config = config;
114
+ this.#agentLoop = agentLoop;
115
+ }
116
+ async init() {
117
+ this.#synthRepo.expireStale();
118
+ const stale = this.#synthRepo.getExpiredOrDirtyScopes();
119
+ for (const { scope } of stale) this.#dirtyScopes.add(scope);
120
+ this.#running = true;
121
+ await this.#debounceLoop();
122
+ }
123
+ shutdown() {
124
+ this.#running = false;
125
+ if (this.#loopTimer !== void 0) {
126
+ clearTimeout(this.#loopTimer);
127
+ this.#loopTimer = void 0;
128
+ }
129
+ const inFlight = [...this.#inFlightPromises.values()];
130
+ if (inFlight.length === 0) return Promise.resolve();
131
+ const graceMs = 5e3;
132
+ return Promise.race([Promise.allSettled(inFlight).then(() => void 0), new Promise((resolve) => setTimeout(resolve, graceMs))]);
133
+ }
134
+ markDirty(scope) {
135
+ this.#dirtyScopes.add(scope);
136
+ }
137
+ #scheduleNextCycle() {
138
+ if (!this.#running) return;
139
+ const debounceMs = this.#config.debounceMs ?? DEFAULT_DEBOUNCE_MS;
140
+ this.#loopTimer = setTimeout(() => {
141
+ this.#debounceLoop();
142
+ }, debounceMs);
143
+ }
144
+ async #debounceLoop() {
145
+ const scopesToProcess = [...this.#dirtyScopes];
146
+ for (const scope of scopesToProcess) {
147
+ const inFlightTimeoutMs = this.#config.inFlightTimeoutMs ?? DEFAULT_IN_FLIGHT_TIMEOUT_MS;
148
+ const synthesis = this.#synthRepo.getSynthesis(scope);
149
+ if (synthesis?.inFlightSince !== null && synthesis?.inFlightSince !== void 0) {
150
+ if (Date.now() - new Date(synthesis.inFlightSince).getTime() < inFlightTimeoutMs) continue;
151
+ this.#synthRepo.clearInFlight(scope);
152
+ }
153
+ this.#dirtyScopes.delete(scope);
154
+ const promise = this.#synthesizeScope(scope).finally(() => {
155
+ this.#inFlightPromises.delete(scope);
156
+ });
157
+ this.#inFlightPromises.set(scope, promise);
158
+ }
159
+ this.#scheduleNextCycle();
160
+ }
161
+ async #synthesizeScope(scope) {
162
+ this.#synthRepo.markInFlight(scope);
163
+ try {
164
+ const content = await this.#agentLoop.run(scope);
165
+ const sourceHash = this.#synthRepo.computeSourceMemoryHash(scope);
166
+ this.#synthRepo.saveSynthesis(scope, content, sourceHash);
167
+ this.#failureCounts.delete(scope);
168
+ } catch (err) {
169
+ const failures = (this.#failureCounts.get(scope) ?? 0) + 1;
170
+ this.#failureCounts.set(scope, failures);
171
+ const backoffMultiplier = Math.min(failures, MAX_BACKOFF_MULTIPLIER);
172
+ const backoffMs = (this.#config.debounceMs ?? DEFAULT_DEBOUNCE_MS) * backoffMultiplier;
173
+ process.stderr.write(`membank synthesis: error for scope=${scope} failures=${failures} backoff=${backoffMs}ms: ${err instanceof Error ? err.message : String(err)}\n`);
174
+ setTimeout(() => {
175
+ this.#dirtyScopes.add(scope);
176
+ }, backoffMs);
177
+ this.#synthRepo.clearInFlight(scope);
178
+ }
179
+ }
180
+ };
30
181
  //#endregion
31
182
  //#region src/server.ts
32
183
  const SERVER_NAME = "membank";
33
184
  const SERVER_VERSION = "0.1.0";
185
+ function loadSynthesisConfig() {
186
+ const configPath = join(homedir(), ".membank", "config.json");
187
+ try {
188
+ const raw = readFileSync(configPath, "utf8");
189
+ const parsed = JSON.parse(raw);
190
+ return {
191
+ enabled: parsed.synthesis?.enabled === true,
192
+ maxTokensPerRun: parsed.synthesis?.maxTokensPerRun,
193
+ debounceMs: parsed.synthesis?.debounceMs,
194
+ stalenessDays: parsed.synthesis?.stalenessDays,
195
+ inFlightTimeoutMs: parsed.synthesis?.inFlightTimeoutMs
196
+ };
197
+ } catch {
198
+ return { enabled: false };
199
+ }
200
+ }
34
201
  function initCore(options = {}) {
35
202
  const db = options.useInMemoryDb ? DatabaseManager.openInMemory() : DatabaseManager.open(options.dbPath);
36
203
  const embedding = new EmbeddingService();
37
204
  const projects = new ProjectRepository(db);
38
205
  const repo = new MemoryRepository(db, embedding, projects);
206
+ const query = new QueryEngine(db, embedding, repo);
207
+ const synthConfig = loadSynthesisConfig();
208
+ let synthEngine;
209
+ if (synthConfig.enabled) synthEngine = new SynthesisEngine(db, new SynthesisRepository(db), synthConfig, new SynthesisAgentLoop({
210
+ queryMemory: async (args) => {
211
+ const projectHash = args.global === true ? void 0 : (await resolveProject()).hash;
212
+ const results = await query.query({
213
+ query: args.query,
214
+ projectHash,
215
+ limit: args.limit ?? 20,
216
+ includePinned: true
217
+ });
218
+ return JSON.stringify(results);
219
+ },
220
+ getMemorySummary: async () => JSON.stringify(repo.stats())
221
+ }, synthConfig));
39
222
  return {
40
223
  db,
41
224
  embedding,
42
225
  repo,
43
- query: new QueryEngine(db, embedding, repo),
44
- projects
226
+ query,
227
+ projects,
228
+ synthEngine
45
229
  };
46
230
  }
47
231
  function parseArgs(schema, raw) {
@@ -97,7 +281,7 @@ function createServer(core) {
97
281
  },
98
282
  {
99
283
  name: "update_memory",
100
- description: "Update the content and/or tags of an existing memory by id.",
284
+ description: "Update the content, type, and/or tags of an existing memory by id. All fields except id are optional.",
101
285
  inputSchema: {
102
286
  type: "object",
103
287
  properties: {
@@ -109,13 +293,18 @@ function createServer(core) {
109
293
  type: "string",
110
294
  description: "New content for the memory"
111
295
  },
296
+ type: {
297
+ type: "string",
298
+ enum: [...MEMORY_TYPE_VALUES],
299
+ description: "New type for the memory (reclassification)"
300
+ },
112
301
  tags: {
113
302
  type: "array",
114
303
  items: { type: "string" },
115
304
  description: "Replacement tags (optional)"
116
305
  }
117
306
  },
118
- required: ["id", "content"]
307
+ required: ["id"]
119
308
  }
120
309
  },
121
310
  {
@@ -152,6 +341,10 @@ function createServer(core) {
152
341
  includePinned: {
153
342
  type: "boolean",
154
343
  description: "Include pinned memories in results. Pinned memories are already injected into session context, so excluded by default to avoid duplicates."
344
+ },
345
+ global: {
346
+ type: "boolean",
347
+ description: "Query global memories only. When omitted or false, queries the current project scope."
155
348
  }
156
349
  },
157
350
  required: ["query"]
@@ -199,6 +392,36 @@ function createServer(core) {
199
392
  } },
200
393
  required: ["id"]
201
394
  }
395
+ },
396
+ {
397
+ name: "get_memory_summary",
398
+ description: "Returns aggregate stats for session orientation: total memories, counts by type, pinned count, and review queue size.",
399
+ inputSchema: {
400
+ type: "object",
401
+ properties: {},
402
+ required: []
403
+ }
404
+ },
405
+ {
406
+ name: "list_flagged_memories",
407
+ description: "List memories that have unresolved dedup review events. These were flagged automatically when a near-duplicate was saved (cosine similarity 0.75–0.92).",
408
+ inputSchema: {
409
+ type: "object",
410
+ properties: {},
411
+ required: []
412
+ }
413
+ },
414
+ {
415
+ name: "resolve_review",
416
+ description: "Dismiss all unresolved review events for a memory. Use after reviewing the memory and deciding it should be kept as-is.",
417
+ inputSchema: {
418
+ type: "object",
419
+ properties: { id: {
420
+ type: "string",
421
+ description: "Memory id to resolve review events for"
422
+ } },
423
+ required: ["id"]
424
+ }
202
425
  }
203
426
  ] }));
204
427
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
@@ -226,6 +449,10 @@ function createServer(core) {
226
449
  tags: args.tags,
227
450
  projectScope
228
451
  });
452
+ if (core.synthEngine !== void 0) {
453
+ const scope = memory.projects.length > 0 ? memory.projects[0]?.scopeHash ?? "global" : "global";
454
+ core.synthEngine.markDirty(scope);
455
+ }
229
456
  return { content: [{
230
457
  type: "text",
231
458
  text: JSON.stringify(memory)
@@ -245,8 +472,13 @@ function createServer(core) {
245
472
  try {
246
473
  const memory = await core.repo.update(args.id, {
247
474
  content: args.content,
475
+ type: args.type,
248
476
  tags: args.tags
249
477
  });
478
+ if (core.synthEngine !== void 0) {
479
+ const scope = memory.projects.length > 0 ? memory.projects[0]?.scopeHash ?? "global" : "global";
480
+ core.synthEngine.markDirty(scope);
481
+ }
250
482
  return { content: [{
251
483
  type: "text",
252
484
  text: JSON.stringify(memory)
@@ -271,7 +503,12 @@ function createServer(core) {
271
503
  }],
272
504
  isError: true
273
505
  };
506
+ let memoryScopeBeforeDelete;
507
+ if (core.synthEngine !== void 0) memoryScopeBeforeDelete = core.db.db.prepare(`SELECT p.scope_hash FROM projects p
508
+ JOIN memory_projects mp ON mp.project_id = p.id
509
+ WHERE mp.memory_id = ?`).get(args.id)?.scope_hash ?? "global";
274
510
  await core.repo.delete(args.id);
511
+ if (core.synthEngine !== void 0 && memoryScopeBeforeDelete !== void 0) core.synthEngine.markDirty(memoryScopeBeforeDelete);
275
512
  return { content: [{
276
513
  type: "text",
277
514
  text: JSON.stringify({
@@ -291,10 +528,12 @@ function createServer(core) {
291
528
  }
292
529
  if (request.params.name === "query_memory") {
293
530
  const args = parseArgs(QueryMemoryArgsSchema, request.params.arguments);
531
+ const projectHash = args.global === true ? void 0 : (await resolveProject()).hash;
294
532
  try {
295
533
  const serialised = (await core.query.query({
296
534
  query: args.query,
297
535
  type: args.type,
536
+ projectHash,
298
537
  limit: args.limit ?? 10,
299
538
  includePinned: args.includePinned
300
539
  })).map((r) => ({
@@ -305,6 +544,9 @@ function createServer(core) {
305
544
  projects: r.projects,
306
545
  pinned: r.pinned,
307
546
  reviewEvents: r.reviewEvents,
547
+ createdAt: r.createdAt,
548
+ updatedAt: r.updatedAt,
549
+ sourceHarness: r.sourceHarness,
308
550
  score: r.score
309
551
  }));
310
552
  return { content: [{
@@ -356,6 +598,19 @@ function createServer(core) {
356
598
  const pinned = request.params.name === "pin_memory";
357
599
  try {
358
600
  const memory = core.repo.setPin(args.id, pinned);
601
+ if (pinned) {
602
+ const charCount = core.repo.getPinnedCharCount();
603
+ if (charCount > PIN_BUDGET_THRESHOLD && !isSynthesisEnabled()) {
604
+ const result = {
605
+ ...memory,
606
+ pinBudgetWarning: `Pinned memories now use ${charCount} characters (threshold: ${PIN_BUDGET_THRESHOLD}). Consider unpinning older memories or enabling synthesis to compress them.`
607
+ };
608
+ return { content: [{
609
+ type: "text",
610
+ text: JSON.stringify(result)
611
+ }] };
612
+ }
613
+ }
359
614
  return { content: [{
360
615
  type: "text",
361
616
  text: JSON.stringify(memory)
@@ -370,6 +625,63 @@ function createServer(core) {
370
625
  };
371
626
  }
372
627
  }
628
+ if (request.params.name === "get_memory_summary") try {
629
+ return { content: [{
630
+ type: "text",
631
+ text: JSON.stringify(core.repo.stats())
632
+ }] };
633
+ } catch (err) {
634
+ return {
635
+ content: [{
636
+ type: "text",
637
+ text: err instanceof Error ? err.message : String(err)
638
+ }],
639
+ isError: true
640
+ };
641
+ }
642
+ if (request.params.name === "list_flagged_memories") try {
643
+ const memories = core.repo.listFlagged();
644
+ return { content: [{
645
+ type: "text",
646
+ text: JSON.stringify(memories)
647
+ }] };
648
+ } catch (err) {
649
+ return {
650
+ content: [{
651
+ type: "text",
652
+ text: err instanceof Error ? err.message : String(err)
653
+ }],
654
+ isError: true
655
+ };
656
+ }
657
+ if (request.params.name === "resolve_review") {
658
+ const args = parseArgs(ResolveReviewArgsSchema, request.params.arguments);
659
+ try {
660
+ if (!(core.db.db.prepare(`SELECT id FROM memories WHERE id = ?`).get(args.id) !== void 0)) return {
661
+ content: [{
662
+ type: "text",
663
+ text: `Memory not found: ${args.id}`
664
+ }],
665
+ isError: true
666
+ };
667
+ core.repo.resolveReviewEvents(args.id);
668
+ return { content: [{
669
+ type: "text",
670
+ text: JSON.stringify({
671
+ success: true,
672
+ id: args.id
673
+ })
674
+ }] };
675
+ } catch (err) {
676
+ return {
677
+ content: [{
678
+ type: "text",
679
+ text: err instanceof Error ? err.message : String(err)
680
+ }],
681
+ isError: true
682
+ };
683
+ }
684
+ }
373
685
  throw new Error(`Unknown tool: ${request.params.name}`);
374
686
  });
375
687
  return server;
@@ -385,6 +697,22 @@ async function startServer() {
385
697
  process.stderr.write(`membank: failed to initialise core: ${message}\n`);
386
698
  process.exit(1);
387
699
  }
700
+ if (core.synthEngine !== void 0) try {
701
+ await core.synthEngine.init();
702
+ } catch (err) {
703
+ const message = err instanceof Error ? err.message : String(err);
704
+ process.stderr.write(`membank: synthesis engine init failed: ${message}\n`);
705
+ }
706
+ const shutdown = async () => {
707
+ if (core.synthEngine !== void 0) await core.synthEngine.shutdown();
708
+ process.exit(0);
709
+ };
710
+ process.on("SIGTERM", () => {
711
+ shutdown();
712
+ });
713
+ process.on("SIGINT", () => {
714
+ shutdown();
715
+ });
388
716
  const server = createServer(core);
389
717
  const transport = new StdioServerTransport();
390
718
  await server.connect(transport);
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/schemas.ts","../src/server.ts","../src/index.ts"],"sourcesContent":["import { MemoryTypeSchema } from \"@membank/core\";\nimport { z } from \"zod\";\n\nexport const SaveMemoryArgsSchema = z.object({\n content: z.string().min(1),\n type: MemoryTypeSchema,\n tags: z.array(z.string()).optional(),\n global: z.boolean().optional(),\n});\n\nexport const UpdateMemoryArgsSchema = z.object({\n id: z.string().min(1),\n content: z.string().min(1),\n tags: z.array(z.string()).optional(),\n});\n\nexport const DeleteMemoryArgsSchema = z.object({\n id: z.string().min(1),\n});\n\nexport const QueryMemoryArgsSchema = z.object({\n query: z.string().min(1),\n type: MemoryTypeSchema.optional(),\n limit: z.number().int().positive().optional(),\n includePinned: z.boolean().optional(),\n});\n\nexport const MigrateArgsSchema = z.discriminatedUnion(\"mode\", [\n z.object({ mode: z.literal(\"list\") }),\n z.object({ mode: z.literal(\"run\"), name: z.string().min(1) }),\n]);\n\nexport const PinMemoryArgsSchema = z.object({\n id: z.string().min(1),\n});\n","import {\n DatabaseManager,\n EmbeddingService,\n listMemoryTypes,\n MEMORY_TYPE_VALUES,\n MemoryRepository,\n MIGRATIONS,\n ProjectRepository,\n QueryEngine,\n resolveProject,\n runScopeToProjectsMigration,\n} from \"@membank/core\";\nimport { Server } from \"@modelcontextprotocol/sdk/server\";\nimport {\n CallToolRequestSchema,\n ErrorCode,\n ListToolsRequestSchema,\n McpError,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { ZodError } from \"zod\";\nimport {\n DeleteMemoryArgsSchema,\n MigrateArgsSchema,\n PinMemoryArgsSchema,\n QueryMemoryArgsSchema,\n SaveMemoryArgsSchema,\n UpdateMemoryArgsSchema,\n} from \"./schemas.js\";\n\nconst SERVER_NAME = \"membank\";\nconst SERVER_VERSION = \"0.1.0\";\n\nexport interface CoreServices {\n db: DatabaseManager;\n embedding: EmbeddingService;\n repo: MemoryRepository;\n query: QueryEngine;\n projects: ProjectRepository;\n}\n\nexport interface ServerOptions {\n dbPath?: string;\n useInMemoryDb?: boolean;\n}\n\nexport function initCore(options: ServerOptions = {}): CoreServices {\n const db = options.useInMemoryDb\n ? DatabaseManager.openInMemory()\n : DatabaseManager.open(options.dbPath);\n const embedding = new EmbeddingService();\n const projects = new ProjectRepository(db);\n const repo = new MemoryRepository(db, embedding, projects);\n const query = new QueryEngine(db, embedding, repo);\n return { db, embedding, repo, query, projects };\n}\n\nfunction parseArgs<T>(schema: { parse: (v: unknown) => T }, raw: unknown): T {\n try {\n return schema.parse(raw);\n } catch (e) {\n const msg = e instanceof ZodError ? (e.issues[0]?.message ?? e.message) : String(e);\n throw new McpError(ErrorCode.InvalidParams, msg);\n }\n}\n\nexport function createServer(core: CoreServices): Server {\n const server = new Server(\n { name: SERVER_NAME, version: SERVER_VERSION },\n { capabilities: { tools: {} } }\n );\n\n server.setRequestHandler(ListToolsRequestSchema, () => ({\n tools: [\n {\n name: \"list_memory_types\",\n description: \"Returns the ordered list of memory type values supported by membank.\",\n inputSchema: { type: \"object\", properties: {}, required: [] },\n },\n {\n name: \"save_memory\",\n description:\n \"Save a new memory. Handles deduplication automatically — near-identical memories (cosine similarity >0.92, same type and project) overwrite the existing record.\",\n inputSchema: {\n type: \"object\",\n properties: {\n content: { type: \"string\", description: \"Memory content to save\" },\n type: {\n type: \"string\",\n enum: [...MEMORY_TYPE_VALUES],\n description: \"Memory type\",\n },\n tags: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Optional tags\",\n },\n global: {\n type: \"boolean\",\n description: \"Save as a global memory, not tied to any project\",\n },\n },\n required: [\"content\", \"type\"],\n },\n },\n {\n name: \"update_memory\",\n description: \"Update the content and/or tags of an existing memory by id.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: \"Memory id to update\" },\n content: { type: \"string\", description: \"New content for the memory\" },\n tags: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Replacement tags (optional)\",\n },\n },\n required: [\"id\", \"content\"],\n },\n },\n {\n name: \"delete_memory\",\n description: \"Delete a memory by id.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: \"Memory id to delete\" },\n },\n required: [\"id\"],\n },\n },\n {\n name: \"query_memory\",\n description:\n \"Search memories by semantic similarity. Returns results ranked by confidence score.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Search text\" },\n type: {\n type: \"string\",\n enum: [...MEMORY_TYPE_VALUES],\n description: \"Filter by memory type\",\n },\n limit: { type: \"number\", description: \"Maximum results to return (default 10)\" },\n includePinned: {\n type: \"boolean\",\n description:\n \"Include pinned memories in results. Pinned memories are already injected into session context, so excluded by default to avoid duplicates.\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"migrate\",\n description:\n 'List or run named data migrations. Use mode \"list\" to see available migrations; mode \"run\" with a migration name to execute one.',\n inputSchema: {\n type: \"object\",\n properties: {\n mode: {\n type: \"string\",\n enum: [\"list\", \"run\"],\n description: 'Mode: \"list\" to see available migrations, \"run\" to execute one',\n },\n name: {\n type: \"string\",\n description: 'Migration name (required when mode is \"run\")',\n },\n },\n required: [\"mode\"],\n },\n },\n {\n name: \"pin_memory\",\n description:\n \"Pin a memory by id. Pinned memories are always injected into the session context.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: \"Memory id to pin\" },\n },\n required: [\"id\"],\n },\n },\n {\n name: \"unpin_memory\",\n description: \"Unpin a memory by id. Removes the memory from guaranteed session injection.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: \"Memory id to unpin\" },\n },\n required: [\"id\"],\n },\n },\n ],\n }));\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n if (request.params.name === \"list_memory_types\") {\n try {\n return {\n content: [{ type: \"text\", text: JSON.stringify(listMemoryTypes()) }],\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: [{ type: \"text\", text: message }], isError: true };\n }\n }\n\n if (request.params.name === \"save_memory\") {\n const args = parseArgs(SaveMemoryArgsSchema, request.params.arguments);\n const projectScope = args.global === true ? undefined : await resolveProject();\n\n try {\n const memory = await core.repo.save({\n content: args.content,\n type: args.type,\n tags: args.tags,\n projectScope,\n });\n\n return {\n content: [{ type: \"text\", text: JSON.stringify(memory) }],\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: [{ type: \"text\", text: message }], isError: true };\n }\n }\n\n if (request.params.name === \"update_memory\") {\n const args = parseArgs(UpdateMemoryArgsSchema, request.params.arguments);\n\n try {\n const memory = await core.repo.update(args.id, {\n content: args.content,\n tags: args.tags,\n });\n return { content: [{ type: \"text\", text: JSON.stringify(memory) }] };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: [{ type: \"text\", text: message }], isError: true };\n }\n }\n\n if (request.params.name === \"delete_memory\") {\n const args = parseArgs(DeleteMemoryArgsSchema, request.params.arguments);\n\n try {\n const exists =\n core.db.db\n .prepare<[string], { id: string }>(`SELECT id FROM memories WHERE id = ?`)\n .get(args.id) !== undefined;\n\n if (!exists) {\n return {\n content: [{ type: \"text\", text: `Memory not found: ${args.id}` }],\n isError: true,\n };\n }\n\n await core.repo.delete(args.id);\n return {\n content: [{ type: \"text\", text: JSON.stringify({ success: true, id: args.id }) }],\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: [{ type: \"text\", text: message }], isError: true };\n }\n }\n\n if (request.params.name === \"query_memory\") {\n const args = parseArgs(QueryMemoryArgsSchema, request.params.arguments);\n\n try {\n const results = await core.query.query({\n query: args.query,\n type: args.type,\n limit: args.limit ?? 10,\n includePinned: args.includePinned,\n });\n\n const serialised = results.map((r) => ({\n id: r.id,\n content: r.content,\n type: r.type,\n tags: r.tags,\n projects: r.projects,\n pinned: r.pinned,\n reviewEvents: r.reviewEvents,\n score: r.score,\n }));\n\n return {\n content: [{ type: \"text\", text: JSON.stringify(serialised) }],\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: [{ type: \"text\", text: message }], isError: true };\n }\n }\n\n if (request.params.name === \"migrate\") {\n const args = parseArgs(MigrateArgsSchema, request.params.arguments);\n\n if (args.mode === \"list\") {\n return {\n content: [{ type: \"text\", text: JSON.stringify(MIGRATIONS) }],\n };\n }\n\n if (args.name === \"scope-to-projects\") {\n try {\n const result = await runScopeToProjectsMigration(core.projects);\n if (result === null) {\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify({ error: \"No project found for current directory.\" }),\n },\n ],\n isError: true,\n };\n }\n return {\n content: [{ type: \"text\", text: JSON.stringify(result) }],\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: [{ type: \"text\", text: message }], isError: true };\n }\n }\n\n throw new McpError(\n ErrorCode.InvalidParams,\n `Unknown migration: \"${args.name}\". Available: ${MIGRATIONS.map((m) => m.name).join(\", \")}`\n );\n }\n\n if (request.params.name === \"pin_memory\" || request.params.name === \"unpin_memory\") {\n const args = parseArgs(PinMemoryArgsSchema, request.params.arguments);\n const pinned = request.params.name === \"pin_memory\";\n\n try {\n const memory = core.repo.setPin(args.id, pinned);\n return { content: [{ type: \"text\", text: JSON.stringify(memory) }] };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: [{ type: \"text\", text: message }], isError: true };\n }\n }\n\n throw new Error(`Unknown tool: ${request.params.name}`);\n });\n\n return server;\n}\n","import { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport type { CoreServices } from \"./server.js\";\nimport { createServer, initCore } from \"./server.js\";\n\nexport async function startServer(): Promise<void> {\n let core: CoreServices;\n try {\n core = initCore();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`membank: failed to initialise core: ${message}\\n`);\n process.exit(1);\n }\n\n const server = createServer(core);\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n"],"mappings":";;;;;;AAGA,MAAa,uBAAuB,EAAE,OAAO;CAC3C,SAAS,EAAE,QAAQ,CAAC,IAAI,EAAE;CAC1B,MAAM;CACN,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,UAAU;CACpC,QAAQ,EAAE,SAAS,CAAC,UAAU;CAC/B,CAAC;AAEF,MAAa,yBAAyB,EAAE,OAAO;CAC7C,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE;CACrB,SAAS,EAAE,QAAQ,CAAC,IAAI,EAAE;CAC1B,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,UAAU;CACrC,CAAC;AAEF,MAAa,yBAAyB,EAAE,OAAO,EAC7C,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,EACtB,CAAC;AAEF,MAAa,wBAAwB,EAAE,OAAO;CAC5C,OAAO,EAAE,QAAQ,CAAC,IAAI,EAAE;CACxB,MAAM,iBAAiB,UAAU;CACjC,OAAO,EAAE,QAAQ,CAAC,KAAK,CAAC,UAAU,CAA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AAS;AAEvC,OAAI;IACF,MAAM,SAAS,KAAK,KAAK,OAAO,KAAK,IAAI,OAAO;AAChD,WAAO,EAAE,SAAS,CAAC;KAAE,MAAM;KAAQ,MAAM,KAAK,UAAU,OAAO;KAAE,CAAC,EAAE;YAC7D,KAAK;AAEZ,WAAO;KAAE,SAAS,CAAC;MAAE,MAAM;MAAQ,MADnB,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;MACd,CAAC;KAAE,SAAS;KAAM;;;AAIxE,QAAM,IAAI,MAAM,iBAAiB,QAAQ,OAAO,OAAO;GACvD;AAEF,QAAO;;;;ACpWT,eAAsB,cAA6B;CACjD,IAAI;AACJ,KAAI;AACF,SAAO,UAAU;UACV,KAAK;EACZ,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;AAChE,UAAQ,OAAO,MAAM,uCAAuC,QAAQ,IAAI;AACxE,UAAQ,KAAK,EAAE;;CAGjB,MAAM,SAAS,aAAa,KAAK;CACjC,MAAM,YAAY,IAAI,sBAAsB;AAC5C,OAAM,OAAO,QAAQ,UAAU"}
1
+ {"version":3,"file":"index.mjs","names":["#tools","#synthRepo","#config","#agentLoop","#dirtyScopes","#failureCounts","#running","#debounceLoop","#loopTimer","#inFlightPromises","#synthesizeScope","#scheduleNextCycle"],"sources":["../src/schemas.ts","../src/synthesis/agent-loop.ts","../src/synthesis/engine.ts","../src/server.ts","../src/index.ts"],"sourcesContent":["import { MemoryTypeSchema } from \"@membank/core\";\nimport { z } from \"zod\";\n\nexport const SaveMemoryArgsSchema = z.object({\n content: z.string().min(1),\n type: MemoryTypeSchema,\n tags: z.array(z.string()).optional(),\n global: z.boolean().optional(),\n});\n\nexport const UpdateMemoryArgsSchema = z.object({\n id: z.string().min(1),\n content: z.string().min(1).optional(),\n type: MemoryTypeSchema.optional(),\n tags: z.array(z.string()).optional(),\n});\n\nexport const DeleteMemoryArgsSchema = z.object({\n id: z.string().min(1),\n});\n\nexport const QueryMemoryArgsSchema = z.object({\n query: z.string().min(1),\n type: MemoryTypeSchema.optional(),\n limit: z.number().int().positive().optional(),\n includePinned: z.boolean().optional(),\n global: z.boolean().optional(),\n});\n\nexport const MigrateArgsSchema = z.discriminatedUnion(\"mode\", [\n z.object({ mode: z.literal(\"list\") }),\n z.object({ mode: z.literal(\"run\"), name: z.string().min(1) }),\n]);\n\nexport const PinMemoryArgsSchema = z.object({\n id: z.string().min(1),\n});\n\nexport const ResolveReviewArgsSchema = z.object({\n id: z.string().min(1),\n});\n","import { createSdkMcpServer, query, tool } from \"@anthropic-ai/claude-agent-sdk\";\nimport { z } from \"zod\";\n\nconst SYNTHESIS_SYSTEM_PROMPT =\n \"You are a memory synthesizer. Your job is to read the user's stored memories and produce a concise, well-structured summary of what's most important to remember about this user — their preferences, corrections, decisions, and key facts. Pinned memories are higher fidelity and should be weighted more heavily. Exclude transient or ephemeral details. Output plain text suitable for injection into an LLM context window. Be concise — target 200-400 words.\";\n\nconst MAX_TURNS = 3;\n\nexport interface SynthesisConfig {\n enabled: boolean;\n maxTokensPerRun?: number;\n debounceMs?: number;\n stalenessDays?: number;\n inFlightTimeoutMs?: number;\n}\n\ninterface SynthesisTools {\n queryMemory: (args: { query: string; limit?: number; global?: boolean }) => Promise<string>;\n getMemorySummary: () => Promise<string>;\n}\n\nexport class SynthesisAgentLoop {\n readonly #tools: SynthesisTools;\n\n constructor(tools: SynthesisTools, _config: SynthesisConfig) {\n this.#tools = tools;\n }\n\n async run(scope: string): Promise<string> {\n const queryMemoryTool = tool(\n \"query_memory\",\n \"Search memories by semantic similarity\",\n {\n query: z.string().describe(\"Search text\"),\n limit: z.number().optional().describe(\"Maximum results to return\"),\n global: z\n .boolean()\n .optional()\n .describe(\"Query global memories only when true, otherwise current project scope\"),\n },\n async ({ query: q, limit, global: isGlobal }) => {\n const result = await this.#tools.queryMemory({\n query: q,\n limit,\n global: isGlobal,\n });\n return { content: [{ type: \"text\" as const, text: result }] };\n },\n { annotations: { readOnlyHint: true } }\n );\n\n const getMemorySummaryTool = tool(\n \"get_memory_summary\",\n \"Returns aggregate stats: total memories, counts by type, pinned count, review queue size\",\n {},\n async () => {\n const result = await this.#tools.getMemorySummary();\n return { content: [{ type: \"text\" as const, text: result }] };\n },\n { annotations: { readOnlyHint: true } }\n );\n\n const mcpServer = createSdkMcpServer({\n name: \"membank-synthesis-tools\",\n version: \"1.0.0\",\n tools: [queryMemoryTool, getMemorySummaryTool],\n });\n\n const isGlobal = scope === \"global\";\n const scopeDescription = isGlobal ? \"global (across all projects)\" : `project scope: ${scope}`;\n\n const prompt = `Synthesize the memories for ${scopeDescription}. Use get_memory_summary first to understand the overall state, then use query_memory to retrieve relevant memories (query with broad terms like \"preferences\", \"corrections\", \"decisions\", \"key facts\"). After gathering information, produce a concise synthesis of the most important things to remember about this user. Output only the synthesis text — no preamble, no metadata.`;\n\n const startTime = Date.now();\n\n const env = Object.fromEntries(\n Object.entries(process.env).filter((e): e is [string, string] => e[1] !== undefined)\n );\n\n const agentQuery = query({\n prompt,\n options: {\n model: \"claude-haiku-4-5-20251001\",\n maxTurns: MAX_TURNS,\n systemPrompt: SYNTHESIS_SYSTEM_PROMPT,\n mcpServers: { \"membank-synthesis-tools\": mcpServer },\n allowedTools: [\"query_memory\", \"get_memory_summary\"],\n permissionMode: \"dontAsk\",\n env,\n },\n });\n\n let finalResult = \"\";\n\n for await (const message of agentQuery) {\n if (message.type === \"result\") {\n if (message.subtype === \"success\") {\n finalResult = message.result;\n } else {\n const details =\n \"errors\" in message && Array.isArray(message.errors)\n ? `: ${message.errors.join(\"; \")}`\n : \"\";\n throw new Error(`Synthesis agent failed: ${message.subtype}${details}`);\n }\n }\n }\n\n const durationMs = Date.now() - startTime;\n process.stderr.write(`membank synthesis: scope=${scope} duration=${durationMs}ms\\n`);\n\n if (finalResult === \"\") {\n throw new Error(\"Synthesis agent returned empty result\");\n }\n\n return finalResult;\n }\n}\n","import type { DatabaseManager, SynthesisRepository } from \"@membank/core\";\nimport type { SynthesisAgentLoop, SynthesisConfig } from \"./agent-loop.js\";\n\nconst DEFAULT_DEBOUNCE_MS = 45_000;\nconst DEFAULT_IN_FLIGHT_TIMEOUT_MS = 120_000;\nconst MAX_BACKOFF_MULTIPLIER = 5;\n\nexport class SynthesisEngine {\n readonly #synthRepo: SynthesisRepository;\n readonly #config: SynthesisConfig;\n readonly #agentLoop: SynthesisAgentLoop;\n readonly #dirtyScopes = new Set<string>();\n readonly #failureCounts = new Map<string, number>();\n #running = false;\n #loopTimer: ReturnType<typeof setTimeout> | undefined;\n #inFlightPromises = new Map<string, Promise<void>>();\n\n constructor(\n _db: DatabaseManager,\n synthRepo: SynthesisRepository,\n config: SynthesisConfig,\n agentLoop: SynthesisAgentLoop\n ) {\n this.#synthRepo = synthRepo;\n this.#config = config;\n this.#agentLoop = agentLoop;\n }\n\n async init(): Promise<void> {\n this.#synthRepo.expireStale();\n\n const stale = this.#synthRepo.getExpiredOrDirtyScopes();\n for (const { scope } of stale) {\n this.#dirtyScopes.add(scope);\n }\n\n this.#running = true;\n // Process any scopes discovered at startup immediately, then begin the periodic cycle\n await this.#debounceLoop();\n }\n\n shutdown(): Promise<void> {\n this.#running = false;\n\n if (this.#loopTimer !== undefined) {\n clearTimeout(this.#loopTimer);\n this.#loopTimer = undefined;\n }\n\n const inFlight = [...this.#inFlightPromises.values()];\n if (inFlight.length === 0) return Promise.resolve();\n\n const graceMs = 5_000;\n return Promise.race([\n Promise.allSettled(inFlight).then(() => undefined),\n new Promise<void>((resolve) => setTimeout(resolve, graceMs)),\n ]);\n }\n\n markDirty(scope: string): void {\n this.#dirtyScopes.add(scope);\n }\n\n #scheduleNextCycle(): void {\n if (!this.#running) return;\n const debounceMs = this.#config.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n this.#loopTimer = setTimeout(() => {\n void this.#debounceLoop();\n }, debounceMs);\n }\n\n async #debounceLoop(): Promise<void> {\n const scopesToProcess = [...this.#dirtyScopes];\n\n for (const scope of scopesToProcess) {\n const inFlightTimeoutMs = this.#config.inFlightTimeoutMs ?? DEFAULT_IN_FLIGHT_TIMEOUT_MS;\n const synthesis = this.#synthRepo.getSynthesis(scope);\n\n if (synthesis?.inFlightSince !== null && synthesis?.inFlightSince !== undefined) {\n const inFlightMs = Date.now() - new Date(synthesis.inFlightSince).getTime();\n if (inFlightMs < inFlightTimeoutMs) {\n continue;\n }\n // Stale in-flight — clear it and allow resynthesis\n this.#synthRepo.clearInFlight(scope);\n }\n\n this.#dirtyScopes.delete(scope);\n const promise = this.#synthesizeScope(scope).finally(() => {\n this.#inFlightPromises.delete(scope);\n });\n this.#inFlightPromises.set(scope, promise);\n }\n\n this.#scheduleNextCycle();\n }\n\n async #synthesizeScope(scope: string): Promise<void> {\n this.#synthRepo.markInFlight(scope);\n\n try {\n const content = await this.#agentLoop.run(scope);\n const sourceHash = this.#synthRepo.computeSourceMemoryHash(scope);\n this.#synthRepo.saveSynthesis(scope, content, sourceHash);\n this.#failureCounts.delete(scope);\n } catch (err) {\n const failures = (this.#failureCounts.get(scope) ?? 0) + 1;\n this.#failureCounts.set(scope, failures);\n\n // Exponential backoff: re-queue with multiplied debounce up to MAX_BACKOFF_MULTIPLIER\n const backoffMultiplier = Math.min(failures, MAX_BACKOFF_MULTIPLIER);\n const backoffMs = (this.#config.debounceMs ?? DEFAULT_DEBOUNCE_MS) * backoffMultiplier;\n\n process.stderr.write(\n `membank synthesis: error for scope=${scope} failures=${failures} backoff=${backoffMs}ms: ${err instanceof Error ? err.message : String(err)}\\n`\n );\n\n setTimeout(() => {\n this.#dirtyScopes.add(scope);\n }, backoffMs);\n\n this.#synthRepo.clearInFlight(scope);\n }\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport {\n DatabaseManager,\n EmbeddingService,\n isSynthesisEnabled,\n listMemoryTypes,\n MEMORY_TYPE_VALUES,\n MemoryRepository,\n MIGRATIONS,\n PIN_BUDGET_THRESHOLD,\n ProjectRepository,\n QueryEngine,\n resolveProject,\n runScopeToProjectsMigration,\n SynthesisRepository,\n} from \"@membank/core\";\nimport { Server } from \"@modelcontextprotocol/sdk/server\";\nimport {\n CallToolRequestSchema,\n ErrorCode,\n ListToolsRequestSchema,\n McpError,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { ZodError } from \"zod\";\nimport {\n DeleteMemoryArgsSchema,\n MigrateArgsSchema,\n PinMemoryArgsSchema,\n QueryMemoryArgsSchema,\n ResolveReviewArgsSchema,\n SaveMemoryArgsSchema,\n UpdateMemoryArgsSchema,\n} from \"./schemas.js\";\nimport type { SynthesisConfig } from \"./synthesis/index.js\";\nimport { SynthesisAgentLoop, SynthesisEngine } from \"./synthesis/index.js\";\n\nconst SERVER_NAME = \"membank\";\nconst SERVER_VERSION = \"0.1.0\";\n\nexport interface CoreServices {\n db: DatabaseManager;\n embedding: EmbeddingService;\n repo: MemoryRepository;\n query: QueryEngine;\n projects: ProjectRepository;\n synthEngine?: SynthesisEngine;\n}\n\nexport interface ServerOptions {\n dbPath?: string;\n useInMemoryDb?: boolean;\n}\n\nfunction loadSynthesisConfig(): SynthesisConfig {\n const configPath = join(homedir(), \".membank\", \"config.json\");\n try {\n const raw = readFileSync(configPath, \"utf8\");\n const parsed = JSON.parse(raw) as {\n synthesis?: Partial<SynthesisConfig>;\n };\n return {\n enabled: parsed.synthesis?.enabled === true,\n maxTokensPerRun: parsed.synthesis?.maxTokensPerRun,\n debounceMs: parsed.synthesis?.debounceMs,\n stalenessDays: parsed.synthesis?.stalenessDays,\n inFlightTimeoutMs: parsed.synthesis?.inFlightTimeoutMs,\n };\n } catch {\n return { enabled: false };\n }\n}\n\nexport function initCore(options: ServerOptions = {}): CoreServices {\n const db = options.useInMemoryDb\n ? DatabaseManager.openInMemory()\n : DatabaseManager.open(options.dbPath);\n const embedding = new EmbeddingService();\n const projects = new ProjectRepository(db);\n const repo = new MemoryRepository(db, embedding, projects);\n const query = new QueryEngine(db, embedding, repo);\n\n const synthConfig = loadSynthesisConfig();\n let synthEngine: SynthesisEngine | undefined;\n\n if (synthConfig.enabled) {\n const synthRepo = new SynthesisRepository(db);\n const agentLoop = new SynthesisAgentLoop(\n {\n queryMemory: async (args) => {\n const projectHash = args.global === true ? undefined : (await resolveProject()).hash;\n const results = await query.query({\n query: args.query,\n projectHash,\n limit: args.limit ?? 20,\n includePinned: true,\n });\n return JSON.stringify(results);\n },\n getMemorySummary: async () => JSON.stringify(repo.stats()),\n },\n synthConfig\n );\n synthEngine = new SynthesisEngine(db, synthRepo, synthConfig, agentLoop);\n }\n\n return { db, embedding, repo, query, projects, synthEngine };\n}\n\nfunction parseArgs<T>(schema: { parse: (v: unknown) => T }, raw: unknown): T {\n try {\n return schema.parse(raw);\n } catch (e) {\n const msg = e instanceof ZodError ? (e.issues[0]?.message ?? e.message) : String(e);\n throw new McpError(ErrorCode.InvalidParams, msg);\n }\n}\n\nexport function createServer(core: CoreServices): Server {\n const server = new Server(\n { name: SERVER_NAME, version: SERVER_VERSION },\n { capabilities: { tools: {} } }\n );\n\n server.setRequestHandler(ListToolsRequestSchema, () => ({\n tools: [\n {\n name: \"list_memory_types\",\n description: \"Returns the ordered list of memory type values supported by membank.\",\n inputSchema: { type: \"object\", properties: {}, required: [] },\n },\n {\n name: \"save_memory\",\n description:\n \"Save a new memory. Handles deduplication automatically — near-identical memories (cosine similarity >0.92, same type and project) overwrite the existing record.\",\n inputSchema: {\n type: \"object\",\n properties: {\n content: { type: \"string\", description: \"Memory content to save\" },\n type: {\n type: \"string\",\n enum: [...MEMORY_TYPE_VALUES],\n description: \"Memory type\",\n },\n tags: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Optional tags\",\n },\n global: {\n type: \"boolean\",\n description: \"Save as a global memory, not tied to any project\",\n },\n },\n required: [\"content\", \"type\"],\n },\n },\n {\n name: \"update_memory\",\n description:\n \"Update the content, type, and/or tags of an existing memory by id. All fields except id are optional.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: \"Memory id to update\" },\n content: { type: \"string\", description: \"New content for the memory\" },\n type: {\n type: \"string\",\n enum: [...MEMORY_TYPE_VALUES],\n description: \"New type for the memory (reclassification)\",\n },\n tags: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Replacement tags (optional)\",\n },\n },\n required: [\"id\"],\n },\n },\n {\n name: \"delete_memory\",\n description: \"Delete a memory by id.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: \"Memory id to delete\" },\n },\n required: [\"id\"],\n },\n },\n {\n name: \"query_memory\",\n description:\n \"Search memories by semantic similarity. Returns results ranked by confidence score.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Search text\" },\n type: {\n type: \"string\",\n enum: [...MEMORY_TYPE_VALUES],\n description: \"Filter by memory type\",\n },\n limit: { type: \"number\", description: \"Maximum results to return (default 10)\" },\n includePinned: {\n type: \"boolean\",\n description:\n \"Include pinned memories in results. Pinned memories are already injected into session context, so excluded by default to avoid duplicates.\",\n },\n global: {\n type: \"boolean\",\n description:\n \"Query global memories only. When omitted or false, queries the current project scope.\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"migrate\",\n description:\n 'List or run named data migrations. Use mode \"list\" to see available migrations; mode \"run\" with a migration name to execute one.',\n inputSchema: {\n type: \"object\",\n properties: {\n mode: {\n type: \"string\",\n enum: [\"list\", \"run\"],\n description: 'Mode: \"list\" to see available migrations, \"run\" to execute one',\n },\n name: {\n type: \"string\",\n description: 'Migration name (required when mode is \"run\")',\n },\n },\n required: [\"mode\"],\n },\n },\n {\n name: \"pin_memory\",\n description:\n \"Pin a memory by id. Pinned memories are always injected into the session context.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: \"Memory id to pin\" },\n },\n required: [\"id\"],\n },\n },\n {\n name: \"unpin_memory\",\n description: \"Unpin a memory by id. Removes the memory from guaranteed session injection.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: \"Memory id to unpin\" },\n },\n required: [\"id\"],\n },\n },\n {\n name: \"get_memory_summary\",\n description:\n \"Returns aggregate stats for session orientation: total memories, counts by type, pinned count, and review queue size.\",\n inputSchema: { type: \"object\", properties: {}, required: [] },\n },\n {\n name: \"list_flagged_memories\",\n description:\n \"List memories that have unresolved dedup review events. These were flagged automatically when a near-duplicate was saved (cosine similarity 0.75–0.92).\",\n inputSchema: { type: \"object\", properties: {}, required: [] },\n },\n {\n name: \"resolve_review\",\n description:\n \"Dismiss all unresolved review events for a memory. Use after reviewing the memory and deciding it should be kept as-is.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: \"Memory id to resolve review events for\" },\n },\n required: [\"id\"],\n },\n },\n ],\n }));\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n if (request.params.name === \"list_memory_types\") {\n try {\n return {\n content: [{ type: \"text\", text: JSON.stringify(listMemoryTypes()) }],\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: [{ type: \"text\", text: message }], isError: true };\n }\n }\n\n if (request.params.name === \"save_memory\") {\n const args = parseArgs(SaveMemoryArgsSchema, request.params.arguments);\n const projectScope = args.global === true ? undefined : await resolveProject();\n\n try {\n const memory = await core.repo.save({\n content: args.content,\n type: args.type,\n tags: args.tags,\n projectScope,\n });\n\n if (core.synthEngine !== undefined) {\n const scope =\n memory.projects.length > 0 ? (memory.projects[0]?.scopeHash ?? \"global\") : \"global\";\n core.synthEngine.markDirty(scope);\n }\n\n return {\n content: [{ type: \"text\", text: JSON.stringify(memory) }],\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: [{ type: \"text\", text: message }], isError: true };\n }\n }\n\n if (request.params.name === \"update_memory\") {\n const args = parseArgs(UpdateMemoryArgsSchema, request.params.arguments);\n\n try {\n const memory = await core.repo.update(args.id, {\n content: args.content,\n type: args.type,\n tags: args.tags,\n });\n\n if (core.synthEngine !== undefined) {\n const scope =\n memory.projects.length > 0 ? (memory.projects[0]?.scopeHash ?? \"global\") : \"global\";\n core.synthEngine.markDirty(scope);\n }\n\n return { content: [{ type: \"text\", text: JSON.stringify(memory) }] };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: [{ type: \"text\", text: message }], isError: true };\n }\n }\n\n if (request.params.name === \"delete_memory\") {\n const args = parseArgs(DeleteMemoryArgsSchema, request.params.arguments);\n\n try {\n const exists =\n core.db.db\n .prepare<[string], { id: string }>(`SELECT id FROM memories WHERE id = ?`)\n .get(args.id) !== undefined;\n\n if (!exists) {\n return {\n content: [{ type: \"text\", text: `Memory not found: ${args.id}` }],\n isError: true,\n };\n }\n\n let memoryScopeBeforeDelete: string | undefined;\n if (core.synthEngine !== undefined) {\n const projectRow = core.db.db\n .prepare<[string], { scope_hash: string }>(\n `SELECT p.scope_hash FROM projects p\n JOIN memory_projects mp ON mp.project_id = p.id\n WHERE mp.memory_id = ?`\n )\n .get(args.id);\n memoryScopeBeforeDelete = projectRow?.scope_hash ?? \"global\";\n }\n\n await core.repo.delete(args.id);\n\n if (core.synthEngine !== undefined && memoryScopeBeforeDelete !== undefined) {\n core.synthEngine.markDirty(memoryScopeBeforeDelete);\n }\n\n return {\n content: [{ type: \"text\", text: JSON.stringify({ success: true, id: args.id }) }],\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: [{ type: \"text\", text: message }], isError: true };\n }\n }\n\n if (request.params.name === \"query_memory\") {\n const args = parseArgs(QueryMemoryArgsSchema, request.params.arguments);\n const projectHash = args.global === true ? undefined : (await resolveProject()).hash;\n\n try {\n const results = await core.query.query({\n query: args.query,\n type: args.type,\n projectHash,\n limit: args.limit ?? 10,\n includePinned: args.includePinned,\n });\n\n const serialised = results.map((r) => ({\n id: r.id,\n content: r.content,\n type: r.type,\n tags: r.tags,\n projects: r.projects,\n pinned: r.pinned,\n reviewEvents: r.reviewEvents,\n createdAt: r.createdAt,\n updatedAt: r.updatedAt,\n sourceHarness: r.sourceHarness,\n score: r.score,\n }));\n\n return {\n content: [{ type: \"text\", text: JSON.stringify(serialised) }],\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: [{ type: \"text\", text: message }], isError: true };\n }\n }\n\n if (request.params.name === \"migrate\") {\n const args = parseArgs(MigrateArgsSchema, request.params.arguments);\n\n if (args.mode === \"list\") {\n return {\n content: [{ type: \"text\", text: JSON.stringify(MIGRATIONS) }],\n };\n }\n\n if (args.name === \"scope-to-projects\") {\n try {\n const result = await runScopeToProjectsMigration(core.projects);\n if (result === null) {\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify({ error: \"No project found for current directory.\" }),\n },\n ],\n isError: true,\n };\n }\n return {\n content: [{ type: \"text\", text: JSON.stringify(result) }],\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: [{ type: \"text\", text: message }], isError: true };\n }\n }\n\n throw new McpError(\n ErrorCode.InvalidParams,\n `Unknown migration: \"${args.name}\". Available: ${MIGRATIONS.map((m) => m.name).join(\", \")}`\n );\n }\n\n if (request.params.name === \"pin_memory\" || request.params.name === \"unpin_memory\") {\n const args = parseArgs(PinMemoryArgsSchema, request.params.arguments);\n const pinned = request.params.name === \"pin_memory\";\n\n try {\n const memory = core.repo.setPin(args.id, pinned);\n\n if (pinned) {\n const charCount = core.repo.getPinnedCharCount();\n if (charCount > PIN_BUDGET_THRESHOLD && !isSynthesisEnabled()) {\n const result = {\n ...memory,\n pinBudgetWarning: `Pinned memories now use ${charCount} characters (threshold: ${PIN_BUDGET_THRESHOLD}). Consider unpinning older memories or enabling synthesis to compress them.`,\n };\n return { content: [{ type: \"text\", text: JSON.stringify(result) }] };\n }\n }\n\n return { content: [{ type: \"text\", text: JSON.stringify(memory) }] };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: [{ type: \"text\", text: message }], isError: true };\n }\n }\n\n if (request.params.name === \"get_memory_summary\") {\n try {\n return { content: [{ type: \"text\", text: JSON.stringify(core.repo.stats()) }] };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: [{ type: \"text\", text: message }], isError: true };\n }\n }\n\n if (request.params.name === \"list_flagged_memories\") {\n try {\n const memories = core.repo.listFlagged();\n return { content: [{ type: \"text\", text: JSON.stringify(memories) }] };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: [{ type: \"text\", text: message }], isError: true };\n }\n }\n\n if (request.params.name === \"resolve_review\") {\n const args = parseArgs(ResolveReviewArgsSchema, request.params.arguments);\n\n try {\n const exists =\n core.db.db\n .prepare<[string], { id: string }>(`SELECT id FROM memories WHERE id = ?`)\n .get(args.id) !== undefined;\n\n if (!exists) {\n return {\n content: [{ type: \"text\", text: `Memory not found: ${args.id}` }],\n isError: true,\n };\n }\n\n core.repo.resolveReviewEvents(args.id);\n return {\n content: [{ type: \"text\", text: JSON.stringify({ success: true, id: args.id }) }],\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: [{ type: \"text\", text: message }], isError: true };\n }\n }\n\n throw new Error(`Unknown tool: ${request.params.name}`);\n });\n\n return server;\n}\n","import { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport type { CoreServices } from \"./server.js\";\nimport { createServer, initCore } from \"./server.js\";\n\nexport async function startServer(): Promise<void> {\n let core: CoreServices;\n try {\n core = initCore();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`membank: failed to initialise core: ${message}\\n`);\n process.exit(1);\n }\n\n if (core.synthEngine !== undefined) {\n try {\n await core.synthEngine.init();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`membank: synthesis engine init failed: ${message}\\n`);\n }\n }\n\n const shutdown = async (): Promise<void> => {\n if (core.synthEngine !== undefined) {\n await core.synthEngine.shutdown();\n }\n process.exit(0);\n };\n\n process.on(\"SIGTERM\", () => {\n void shutdown();\n });\n process.on(\"SIGINT\", () => {\n void shutdown();\n });\n\n const server = createServer(core);\n const transport = new StdioServerTransport();\n await server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eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;EAChE,QAAQ,OAAO,MAAM,uCAAuC,QAAQ,IAAI;EACxE,QAAQ,KAAK,EAAE;;CAGjB,IAAI,KAAK,gBAAgB,KAAA,GACvB,IAAI;EACF,MAAM,KAAK,YAAY,MAAM;UACtB,KAAK;EACZ,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;EAChE,QAAQ,OAAO,MAAM,0CAA0C,QAAQ,IAAI;;CAI/E,MAAM,WAAW,YAA2B;EAC1C,IAAI,KAAK,gBAAgB,KAAA,GACvB,MAAM,KAAK,YAAY,UAAU;EAEnC,QAAQ,KAAK,EAAE;;CAGjB,QAAQ,GAAG,iBAAiB;EAC1B,UAAe;GACf;CACF,QAAQ,GAAG,gBAAgB;EACzB,UAAe;GACf;CAEF,MAAM,SAAS,aAAa,KAAK;CACjC,MAAM,YAAY,IAAI,sBAAsB;CAC5C,MAAM,OAAO,QAAQ,UAAU"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@membank/mcp",
3
- "version": "0.10.0",
3
+ "version": "0.11.1",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -17,9 +17,10 @@
17
17
  "dist"
18
18
  ],
19
19
  "dependencies": {
20
+ "@anthropic-ai/claude-agent-sdk": "^0.2.131",
20
21
  "@modelcontextprotocol/sdk": "^1.29.0",
21
22
  "zod": "^4.4.3",
22
- "@membank/core": "0.8.0"
23
+ "@membank/core": "0.9.1"
23
24
  },
24
25
  "devDependencies": {
25
26
  "@types/node": "^25.6.0",