@nhatnguyen9317/memory-mcp-server 1.2.0 → 1.3.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.
@@ -1,6 +1,6 @@
1
1
  import { ReasoningAddStepInputSchema, ReasoningCompleteSessionInputSchema, ReasoningGetSessionOutlineInputSchema, ReasoningGetTraceInputSchema, ReasoningListMilestonesInputSchema, ReasoningListSessionsInputSchema, ReasoningMarkStepInputSchema, ReasoningSearchStepsInputSchema, ReasoningStartSessionInputSchema, } from "../schemas/reasoning.js";
2
- import { AUTO_RECALL_LIMIT, SESSION_TTL_HOURS } from "../constants.js";
3
- import { handleToolError, newId, nowIso, parseJsonArray, toFtsOrQuery, toFtsQuery, toLimitedJson, } from "../utils.js";
2
+ import { AUTO_RECALL_LIMIT, SESSION_TTL_HOURS, getWorkspace } from "../constants.js";
3
+ import { handleToolError, newId, nowIso, parseJsonArray, parseJsonObject, toFtsQuery, toRecallTerms, toLimitedJson, } from "../utils.js";
4
4
  import { recordToolUsageEvent, withTelemetry } from "./telemetry.js";
5
5
  function sessionRowToRecord(row, stepCount) {
6
6
  return {
@@ -131,24 +131,85 @@ function abandonStaleSessions(database, now) {
131
131
  .run(now, cutoff);
132
132
  return Number(result.changes);
133
133
  }
134
+ /** Candidate pool fetched by BM25 before the floor/re-rank pass. */
135
+ const RECALL_CANDIDATE_POOL = 50;
134
136
  function recallRelatedMemories(database, title) {
135
137
  if (AUTO_RECALL_LIMIT <= 0)
136
138
  return [];
137
139
  try {
138
- const rows = database
139
- .prepare(`SELECT m.id, m.type, m.content, m.tags, m.importance
140
+ const terms = toRecallTerms(title);
141
+ if (terms.length === 0)
142
+ return [];
143
+ const candidates = database
144
+ .prepare(`SELECT m.rowid AS row_id, m.id, m.type, m.content, m.tags,
145
+ m.importance, m.metadata, m.created_at, m.updated_at,
146
+ f.rank AS fts_rank,
147
+ CASE
148
+ WHEN m.workspace = ? THEN 2
149
+ WHEN m.workspace IS NULL THEN 1
150
+ ELSE 0
151
+ END AS workspace_priority
140
152
  FROM memories m
141
- WHERE m.rowid IN (SELECT rowid FROM memories_fts WHERE memories_fts MATCH ?)
142
- ORDER BY m.importance DESC, m.updated_at DESC
153
+ JOIN (
154
+ SELECT rowid, rank FROM memories_fts WHERE memories_fts MATCH ?
155
+ ) f ON m.rowid = f.rowid
156
+ ORDER BY f.rank ASC
143
157
  LIMIT ?`)
144
- .all(toFtsOrQuery(title), AUTO_RECALL_LIMIT);
145
- return rows.map((row) => ({
146
- id: row.id,
147
- type: row.type,
148
- importance: row.importance,
149
- tags: parseJsonArray(row.tags),
150
- snippet: compactSnippetText(row.content),
158
+ .all(getWorkspace(), terms.join(" OR "), RECALL_CANDIDATE_POOL);
159
+ if (candidates.length === 0)
160
+ return [];
161
+ // Count how many title terms each candidate matches (one cheap FTS
162
+ // query per term, capped at 8 by toRecallTerms).
163
+ const matchCounts = new Map();
164
+ for (const term of terms) {
165
+ const rowIds = database
166
+ .prepare(`SELECT rowid FROM memories_fts WHERE memories_fts MATCH ?`)
167
+ .all(term);
168
+ for (const row of rowIds) {
169
+ matchCounts.set(row.rowid, (matchCounts.get(row.rowid) ?? 0) + 1);
170
+ }
171
+ }
172
+ const scored = candidates.map((candidate) => ({
173
+ ...candidate,
174
+ matched: matchCounts.get(candidate.row_id) ?? 1,
151
175
  }));
176
+ // Quality floor: multi-term titles require at least two matched terms.
177
+ // When nothing clears it, fall back to the single best-ranked match
178
+ // (serendipity lifeline) instead of padding every slot with junk.
179
+ const required = terms.length >= 3 ? 2 : 1;
180
+ let pool = scored.filter((candidate) => candidate.matched >= required);
181
+ let limit = AUTO_RECALL_LIMIT;
182
+ if (pool.length === 0) {
183
+ pool = scored;
184
+ limit = Math.min(1, AUTO_RECALL_LIMIT);
185
+ }
186
+ pool.sort((a, b) => b.matched - a.matched ||
187
+ b.workspace_priority - a.workspace_priority ||
188
+ a.fts_rank - b.fts_rank ||
189
+ b.importance - a.importance ||
190
+ (a.updated_at < b.updated_at ? 1 : a.updated_at > b.updated_at ? -1 : 0));
191
+ return pool.slice(0, limit).map((row) => {
192
+ const metadata = parseJsonObject(row.metadata);
193
+ const sourceSessionId = metadata?.source_session_id;
194
+ const sourceSessionTitle = metadata?.session_title;
195
+ return {
196
+ id: row.id,
197
+ type: row.type,
198
+ importance: row.importance,
199
+ tags: parseJsonArray(row.tags),
200
+ snippet: compactSnippetText(row.content),
201
+ ...(typeof sourceSessionId === "string" &&
202
+ typeof sourceSessionTitle === "string"
203
+ ? {
204
+ source: {
205
+ session_id: sourceSessionId,
206
+ session_title: sourceSessionTitle,
207
+ created_at: row.created_at,
208
+ },
209
+ }
210
+ : {}),
211
+ };
212
+ });
152
213
  }
153
214
  catch {
154
215
  // Recall is best-effort; a bad FTS query must never block session creation.
@@ -166,7 +227,7 @@ Args:
166
227
  - agent_id (string, optional): Identifier for the agent/persona running this session.
167
228
 
168
229
  Returns: JSON with the new session's id (pass it to reasoning_add_step and reasoning_complete_session), plus:
169
- - related_memories: up to a few saved memories relevant to the title, auto-recalled by the server. Review them before starting work; if one helps, report it later via used_memory_ids on reasoning_complete_session.
230
+ - related_memories: up to a few saved memories relevant to the title, auto-recalled by the server — ranked by text relevance, softly preferring the current workspace; weak one-word matches are filtered out, so a short or empty list is normal. Review them before starting work; if one helps, report it later via used_memory_ids on reasoning_complete_session. Memories persisted from a past reasoning session carry a 'source' field ({session_id, session_title, created_at}); pass source.session_id to reasoning_get_trace to replay how that conclusion was reached.
170
231
  - open_sessions / open_sessions_warning: other in_progress sessions you may have forgotten to close.
171
232
  - auto_abandoned_sessions: count of stale in_progress sessions the server just cleaned up, if any.
172
233
 
@@ -233,9 +294,21 @@ Examples:
233
294
  ? { auto_abandoned_sessions: autoAbandoned }
234
295
  : {}),
235
296
  };
236
- const recallNote = relatedMemories.length > 0
237
- ? ` Found ${relatedMemories.length} related memories — review them before starting.`
238
- : "";
297
+ let recallNote = "";
298
+ if (relatedMemories.length > 0) {
299
+ recallNote = ` Found ${relatedMemories.length} related memories — review them before starting.`;
300
+ }
301
+ else {
302
+ // One-time cold-start nudge: only while the store is completely
303
+ // empty, so it disappears forever after the first saved memory.
304
+ const anyMemory = activeDb
305
+ .prepare(`SELECT EXISTS(SELECT 1 FROM memories) as e`)
306
+ .get();
307
+ if (anyMemory.e === 0) {
308
+ recallNote =
309
+ " No memories yet — when you complete this session, persist durable conclusions with save_as_memory=true so future sessions can recall them.";
310
+ }
311
+ }
239
312
  return {
240
313
  content: [
241
314
  {
@@ -255,16 +328,17 @@ Examples:
255
328
  }));
256
329
  server.registerTool("reasoning_add_step", {
257
330
  title: "Add Reasoning Step",
258
- description: `Append one step (thought / action / observation) to an existing reasoning session. Steps are numbered automatically in the order added. Call this repeatedly as the agent works through a task.
331
+ description: `Append one step (thought / action / observation) — or a batch of steps — to an existing reasoning session. Steps are numbered automatically in the order added.
259
332
 
260
333
  Args:
261
334
  - session_id (string, required): Id from reasoning_start_session.
262
335
  - thought (string, optional): The reasoning/thinking at this step.
263
336
  - action (string, optional): The action taken, if any.
264
337
  - observation (string, optional): The result observed, if any.
265
- (At least one of thought/action/observation is required.)
338
+ - steps (array, optional): Batch mode — log up to 20 steps in one call, each {thought?, action?, observation?} with at least one field. Use INSTEAD of the top-level fields (not together), e.g. to record several steps of finished work at once.
339
+ (Either steps, or at least one of thought/action/observation, is required.)
266
340
 
267
- Returns: JSON with the new step's id and step_number.
341
+ Returns: single mode — JSON with the new step's id and step_number; batch mode — JSON with steps: [{step_id, step_number}, ...] in insertion order.
268
342
 
269
343
  Error Handling:
270
344
  - Returns an error if session_id does not exist (call reasoning_start_session first, or reasoning_list_sessions to find the right id).
@@ -292,6 +366,8 @@ Error Handling:
292
366
  ? result.structuredContent.step_id
293
367
  : null,
294
368
  inputShape: {
369
+ batch: params.steps !== undefined,
370
+ batch_size: params.steps?.length ?? null,
295
371
  thought_present: params.thought !== undefined,
296
372
  action_present: params.action !== undefined,
297
373
  observation_present: params.observation !== undefined,
@@ -301,20 +377,58 @@ Error Handling:
301
377
  },
302
378
  outputShape: {
303
379
  step_number: result.structuredContent?.step_number ?? null,
380
+ steps_added: Array.isArray(result.structuredContent?.steps)
381
+ ? result.structuredContent.steps.length
382
+ : result.structuredContent?.step_number !== undefined
383
+ ? 1
384
+ : 0,
304
385
  },
305
386
  };
306
387
  },
307
388
  }, async (params) => {
308
389
  try {
309
390
  const activeDb = await resolveDatabase(database);
310
- if (params.thought === undefined &&
311
- params.action === undefined &&
312
- params.observation === undefined) {
391
+ const hasSingleFields = params.thought !== undefined ||
392
+ params.action !== undefined ||
393
+ params.observation !== undefined;
394
+ if (params.steps !== undefined && hasSingleFields) {
313
395
  return {
314
396
  content: [
315
397
  {
316
398
  type: "text",
317
- text: "Error: At least one of thought, action, or observation must be provided.",
399
+ text: "Error: Provide either steps (batch mode) or top-level thought/action/observation (single mode), not both.",
400
+ },
401
+ ],
402
+ isError: true,
403
+ };
404
+ }
405
+ if (params.steps === undefined && !hasSingleFields) {
406
+ return {
407
+ content: [
408
+ {
409
+ type: "text",
410
+ text: "Error: Either steps (batch mode), or at least one of thought, action, or observation, must be provided.",
411
+ },
412
+ ],
413
+ isError: true,
414
+ };
415
+ }
416
+ const entries = params.steps ?? [
417
+ {
418
+ thought: params.thought,
419
+ action: params.action,
420
+ observation: params.observation,
421
+ },
422
+ ];
423
+ const invalidIndex = entries.findIndex((entry) => entry.thought === undefined &&
424
+ entry.action === undefined &&
425
+ entry.observation === undefined);
426
+ if (invalidIndex !== -1) {
427
+ return {
428
+ content: [
429
+ {
430
+ type: "text",
431
+ text: `Error: steps[${invalidIndex}] must include at least one of thought, action, or observation.`,
318
432
  },
319
433
  ],
320
434
  isError: true,
@@ -345,7 +459,7 @@ Error Handling:
345
459
  isError: true,
346
460
  };
347
461
  }
348
- const output = runInTransaction(activeDb, () => {
462
+ const insertedSteps = runInTransaction(activeDb, () => {
349
463
  const lockedSession = activeDb
350
464
  .prepare(`SELECT * FROM reasoning_sessions WHERE id = ?`)
351
465
  .get(params.session_id);
@@ -355,22 +469,31 @@ Error Handling:
355
469
  if (lockedSession.status !== "in_progress") {
356
470
  throw new Error(`Session '${params.session_id}' is already '${lockedSession.status}' and cannot accept new steps.`);
357
471
  }
358
- const nextStepNumber = getNextStepNumber(activeDb, params.session_id);
359
- const id = newId("step");
472
+ const firstStepNumber = getNextStepNumber(activeDb, params.session_id);
360
473
  const ts = nowIso();
361
- activeDb
362
- .prepare(`INSERT INTO reasoning_steps (id, session_id, step_number, thought, action, observation, created_at)
363
- VALUES (?, ?, ?, ?, ?, ?, ?)`)
364
- .run(id, params.session_id, nextStepNumber, params.thought ?? null, params.action ?? null, params.observation ?? null, ts);
474
+ const insertStep = activeDb.prepare(`INSERT INTO reasoning_steps (id, session_id, step_number, thought, action, observation, created_at)
475
+ VALUES (?, ?, ?, ?, ?, ?, ?)`);
476
+ const created = entries.map((entry, index) => {
477
+ const id = newId("step");
478
+ insertStep.run(id, params.session_id, firstStepNumber + index, entry.thought ?? null, entry.action ?? null, entry.observation ?? null, ts);
479
+ return { step_id: id, step_number: firstStepNumber + index };
480
+ });
365
481
  activeDb
366
482
  .prepare(`UPDATE reasoning_sessions SET updated_at = ? WHERE id = ?`)
367
483
  .run(ts, params.session_id);
368
- return {
369
- step_id: id,
484
+ return created;
485
+ });
486
+ const output = params.steps !== undefined
487
+ ? {
370
488
  session_id: params.session_id,
371
- step_number: nextStepNumber,
489
+ steps: insertedSteps,
490
+ step_count: insertedSteps.length,
491
+ }
492
+ : {
493
+ step_id: insertedSteps[0].step_id,
494
+ session_id: params.session_id,
495
+ step_number: insertedSteps[0].step_number,
372
496
  };
373
- });
374
497
  return {
375
498
  content: [{ type: "text", text: toLimitedJson(output) }],
376
499
  structuredContent: output,
@@ -1034,14 +1157,14 @@ Error Handling:
1034
1157
  return null;
1035
1158
  const nextMemoryId = newId("mem");
1036
1159
  activeDb
1037
- .prepare(`INSERT INTO memories (id, type, content, tags, agent_id, importance, metadata, created_at, updated_at)
1038
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`)
1160
+ .prepare(`INSERT INTO memories (id, type, content, tags, agent_id, importance, metadata, workspace, created_at, updated_at)
1161
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
1039
1162
  .run(nextMemoryId, params.memory_type ?? "reasoning_summary", params.conclusion, JSON.stringify(params.memory_tags ?? []), session.agent_id, params.memory_importance ?? 3, JSON.stringify({
1040
1163
  source_session_id: params.session_id,
1041
1164
  session_title: session.title,
1042
1165
  auto_saved: !(params.save_as_memory || params.memory_mode === "always"),
1043
1166
  step_count: stepCount,
1044
- }), ts, ts);
1167
+ }), getWorkspace(), ts, ts);
1045
1168
  return nextMemoryId;
1046
1169
  });
1047
1170
  const usedMemoryWarnings = [];
@@ -1071,7 +1194,7 @@ Error Handling:
1071
1194
  usedMemoryFeedbackRecorded += 1;
1072
1195
  }
1073
1196
  else {
1074
- usedMemoryWarnings.push(`Telemetry is disabled; usage feedback for '${usedMemoryId}' was not recorded.`);
1197
+ usedMemoryWarnings.push(`Usage feedback for '${usedMemoryId}' could not be recorded.`);
1075
1198
  }
1076
1199
  }
1077
1200
  const updatedRow = activeDb
@@ -1,4 +1,4 @@
1
- import { MCP_VERSION, TELEMETRY_ENABLED } from "../constants.js";
1
+ import { MCP_VERSION, isTelemetryEnabled } from "../constants.js";
2
2
  import { handleToolError, newId, nowIso } from "../utils.js";
3
3
  function toJsonText(value) {
4
4
  if (!value)
@@ -24,8 +24,15 @@ async function resolveDatabase(provider) {
24
24
  return typeof provider === "function" ? provider() : provider;
25
25
  }
26
26
  export async function recordToolUsageEvent(database, event) {
27
- if (!TELEMETRY_ENABLED)
27
+ // Successful usage-feedback is a first-party learning signal, not
28
+ // diagnostics: it is always recorded locally so recall quality can be
29
+ // evaluated and (later) improved. Everything else — including failed
30
+ // feedback attempts (error_code/latency are diagnostics data) — stays
31
+ // opt-in via MEMORY_TELEMETRY.
32
+ if (!isTelemetryEnabled() &&
33
+ !(event.operationType === "feedback" && event.status === "success")) {
28
34
  return null;
35
+ }
29
36
  try {
30
37
  const id = newId("evt");
31
38
  database
package/dist/utils.js CHANGED
@@ -33,11 +33,6 @@ export function toFtsQuery(raw) {
33
33
  const terms = ftsTerms(raw);
34
34
  return terms.length ? terms.join(" ") : '""';
35
35
  }
36
- /** Like toFtsQuery but matches ANY term — used for fuzzy recall by title. */
37
- export function toFtsOrQuery(raw) {
38
- const terms = ftsTerms(raw);
39
- return terms.length ? terms.join(" OR ") : '""';
40
- }
41
36
  function ftsTerms(raw) {
42
37
  return raw
43
38
  .trim()
@@ -45,6 +40,29 @@ function ftsTerms(raw) {
45
40
  .filter(Boolean)
46
41
  .map((t) => `"${t.replace(/"/g, '""')}"*`);
47
42
  }
43
+ /**
44
+ * Term preparation for auto-recall only. Drops noise tokens (<=2 chars,
45
+ * the main source of one-word junk matches) and caps the count so long
46
+ * titles stay cheap. memory_search keeps raw ftsTerms behavior — an
47
+ * explicit query is the caller's intent.
48
+ */
49
+ export function toRecallTerms(raw) {
50
+ const tokens = raw.trim().split(/\s+/).filter(Boolean);
51
+ const significant = tokens.filter((token) => token.length > 2);
52
+ // Dedupe case-insensitively: a repeated word must not raise the
53
+ // match floor or double-count as two matched terms.
54
+ const seen = new Set();
55
+ const chosen = (significant.length > 0 ? significant : tokens)
56
+ .filter((token) => {
57
+ const key = token.toLowerCase();
58
+ if (seen.has(key))
59
+ return false;
60
+ seen.add(key);
61
+ return true;
62
+ })
63
+ .slice(0, 8);
64
+ return chosen.map((t) => `"${t.replace(/"/g, '""')}"*`);
65
+ }
48
66
  /** Serialize a value to text, truncating with a clear message if it exceeds CHARACTER_LIMIT. */
49
67
  export function toLimitedJson(value) {
50
68
  const text = JSON.stringify(value, null, 2);
package/package.json CHANGED
@@ -1,11 +1,33 @@
1
1
  {
2
2
  "name": "@nhatnguyen9317/memory-mcp-server",
3
- "version": "1.2.0",
3
+ "version": "1.3.1",
4
+ "keywords": [
5
+ "mcp",
6
+ "model-context-protocol",
7
+ "mcp-server",
8
+ "memory",
9
+ "agent-memory",
10
+ "long-term-memory",
11
+ "reasoning-trace",
12
+ "claude",
13
+ "codex",
14
+ "sqlite"
15
+ ],
4
16
  "description": "MCP server for persisting agent long-term memory and step-by-step reasoning traces in SQLite",
17
+ "homepage": "https://github.com/ngquocnhat9317/memory-mcp-server/blob/master/README.md",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/ngquocnhat9317/memory-mcp-server.git"
21
+ },
22
+ "bugs": {
23
+ "url": "https://github.com/ngquocnhat9317/memory-mcp-server/issues"
24
+ },
5
25
  "type": "module",
6
26
  "main": "dist/index.js",
7
27
  "files": [
8
28
  "dist/index.js",
29
+ "dist/server.js",
30
+ "dist/install-agents.js",
9
31
  "dist/constants.js",
10
32
  "dist/db.js",
11
33
  "dist/migrations/*.js",
@@ -25,7 +47,7 @@
25
47
  "start": "node dist/index.js",
26
48
  "dev": "tsx watch src/index.ts",
27
49
  "build": "tsc && node -e \"require('fs').chmodSync('dist/index.js','755')\"",
28
- "test": "npm run build && node --test dist/__tests__/*.test.js",
50
+ "test": "npm run build && MEMORY_TELEMETRY=on node --test dist/__tests__/*.test.js",
29
51
  "clean": "rm -rf dist"
30
52
  },
31
53
  "engines": {