@nhatnguyen9317/memory-mcp-server 1.1.5 → 1.3.0
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/CHANGELOG.md +74 -0
- package/GUIDELINES.md +86 -21
- package/README.md +156 -176
- package/dist/constants.js +30 -2
- package/dist/migrations/0005_memory_workspace.js +10 -0
- package/dist/migrations/index.js +2 -0
- package/dist/schemas/reasoning.js +33 -3
- package/dist/tools/memory.js +78 -50
- package/dist/tools/reasoning.js +259 -31
- package/dist/tools/telemetry.js +9 -2
- package/dist/utils.js +29 -3
- package/package.json +16 -3
package/dist/tools/reasoning.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ReasoningAddStepInputSchema, ReasoningCompleteSessionInputSchema, ReasoningGetSessionOutlineInputSchema, ReasoningGetTraceInputSchema, ReasoningListMilestonesInputSchema, ReasoningListSessionsInputSchema, ReasoningMarkStepInputSchema, ReasoningSearchStepsInputSchema, ReasoningStartSessionInputSchema, } from "../schemas/reasoning.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
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
|
+
import { recordToolUsageEvent, withTelemetry } from "./telemetry.js";
|
|
4
5
|
function sessionRowToRecord(row, stepCount) {
|
|
5
6
|
return {
|
|
6
7
|
id: row.id,
|
|
@@ -117,6 +118,104 @@ async function resolveDatabase(database) {
|
|
|
117
118
|
defaultDatabasePromise ??= import("../db.js").then((module) => module.db);
|
|
118
119
|
return defaultDatabasePromise;
|
|
119
120
|
}
|
|
121
|
+
function abandonStaleSessions(database, now) {
|
|
122
|
+
if (SESSION_TTL_HOURS <= 0)
|
|
123
|
+
return 0;
|
|
124
|
+
const cutoff = new Date(Date.now() - SESSION_TTL_HOURS * 3_600_000).toISOString();
|
|
125
|
+
const result = database
|
|
126
|
+
.prepare(`UPDATE reasoning_sessions
|
|
127
|
+
SET status = 'abandoned',
|
|
128
|
+
conclusion = COALESCE(conclusion, 'auto-abandoned: stale session'),
|
|
129
|
+
updated_at = ?
|
|
130
|
+
WHERE status = 'in_progress' AND updated_at < ?`)
|
|
131
|
+
.run(now, cutoff);
|
|
132
|
+
return Number(result.changes);
|
|
133
|
+
}
|
|
134
|
+
/** Candidate pool fetched by BM25 before the floor/re-rank pass. */
|
|
135
|
+
const RECALL_CANDIDATE_POOL = 50;
|
|
136
|
+
function recallRelatedMemories(database, title) {
|
|
137
|
+
if (AUTO_RECALL_LIMIT <= 0)
|
|
138
|
+
return [];
|
|
139
|
+
try {
|
|
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
|
|
152
|
+
FROM memories m
|
|
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
|
|
157
|
+
LIMIT ?`)
|
|
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,
|
|
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
|
+
});
|
|
213
|
+
}
|
|
214
|
+
catch {
|
|
215
|
+
// Recall is best-effort; a bad FTS query must never block session creation.
|
|
216
|
+
return [];
|
|
217
|
+
}
|
|
218
|
+
}
|
|
120
219
|
export function registerReasoningTools(server, database) {
|
|
121
220
|
const databaseProvider = () => resolveDatabase(database);
|
|
122
221
|
server.registerTool("reasoning_start_session", {
|
|
@@ -127,7 +226,10 @@ Args:
|
|
|
127
226
|
- title (string, required): Short description of the task/question, e.g. "Diagnose flaky checkout test".
|
|
128
227
|
- agent_id (string, optional): Identifier for the agent/persona running this session.
|
|
129
228
|
|
|
130
|
-
Returns: JSON with the new session's id
|
|
229
|
+
Returns: JSON with the new session's id (pass it to reasoning_add_step and reasoning_complete_session), plus:
|
|
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.
|
|
231
|
+
- open_sessions / open_sessions_warning: other in_progress sessions you may have forgotten to close.
|
|
232
|
+
- auto_abandoned_sessions: count of stale in_progress sessions the server just cleaned up, if any.
|
|
131
233
|
|
|
132
234
|
Examples:
|
|
133
235
|
- Use when: starting to debug a complex issue, plan a multi-step task, or work through a decision with tradeoffs.
|
|
@@ -151,6 +253,13 @@ Examples:
|
|
|
151
253
|
: null,
|
|
152
254
|
outputShape: {
|
|
153
255
|
session_id: result.structuredContent?.session_id ?? null,
|
|
256
|
+
related_memory_count: Array.isArray(result.structuredContent?.related_memories)
|
|
257
|
+
? result.structuredContent.related_memories.length
|
|
258
|
+
: 0,
|
|
259
|
+
open_session_count: Array.isArray(result.structuredContent?.open_sessions)
|
|
260
|
+
? result.structuredContent.open_sessions.length
|
|
261
|
+
: 0,
|
|
262
|
+
auto_abandoned_sessions: result.structuredContent?.auto_abandoned_sessions ?? 0,
|
|
154
263
|
},
|
|
155
264
|
}),
|
|
156
265
|
}, async (params) => {
|
|
@@ -158,20 +267,53 @@ Examples:
|
|
|
158
267
|
const activeDb = await resolveDatabase(database);
|
|
159
268
|
const id = newId("sess");
|
|
160
269
|
const ts = nowIso();
|
|
270
|
+
const autoAbandoned = abandonStaleSessions(activeDb, ts);
|
|
161
271
|
activeDb
|
|
162
272
|
.prepare(`INSERT INTO reasoning_sessions (id, title, agent_id, status, conclusion, created_at, updated_at)
|
|
163
273
|
VALUES (?, ?, ?, 'in_progress', NULL, ?, ?)`)
|
|
164
274
|
.run(id, params.title, params.agent_id ?? null, ts, ts);
|
|
275
|
+
const openSessions = activeDb
|
|
276
|
+
.prepare(`SELECT id, title, updated_at FROM reasoning_sessions
|
|
277
|
+
WHERE status = 'in_progress' AND id != ?
|
|
278
|
+
ORDER BY updated_at DESC
|
|
279
|
+
LIMIT 5`)
|
|
280
|
+
.all(id);
|
|
281
|
+
const relatedMemories = recallRelatedMemories(activeDb, params.title);
|
|
165
282
|
const output = {
|
|
166
283
|
session_id: id,
|
|
167
284
|
title: params.title,
|
|
168
285
|
status: "in_progress",
|
|
286
|
+
related_memories: relatedMemories,
|
|
287
|
+
...(openSessions.length > 0
|
|
288
|
+
? {
|
|
289
|
+
open_sessions_warning: `You have ${openSessions.length} other in_progress session(s). Close finished ones with reasoning_complete_session.`,
|
|
290
|
+
open_sessions: openSessions,
|
|
291
|
+
}
|
|
292
|
+
: {}),
|
|
293
|
+
...(autoAbandoned > 0
|
|
294
|
+
? { auto_abandoned_sessions: autoAbandoned }
|
|
295
|
+
: {}),
|
|
169
296
|
};
|
|
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
|
+
}
|
|
170
312
|
return {
|
|
171
313
|
content: [
|
|
172
314
|
{
|
|
173
315
|
type: "text",
|
|
174
|
-
text: `Reasoning session started with id ${id}
|
|
316
|
+
text: `Reasoning session started with id ${id}.${recallNote}\n\n${toLimitedJson(output)}`,
|
|
175
317
|
},
|
|
176
318
|
],
|
|
177
319
|
structuredContent: output,
|
|
@@ -186,16 +328,17 @@ Examples:
|
|
|
186
328
|
}));
|
|
187
329
|
server.registerTool("reasoning_add_step", {
|
|
188
330
|
title: "Add Reasoning Step",
|
|
189
|
-
description: `Append one step (thought / action / observation) to an existing reasoning session. Steps are numbered automatically in the order added.
|
|
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.
|
|
190
332
|
|
|
191
333
|
Args:
|
|
192
334
|
- session_id (string, required): Id from reasoning_start_session.
|
|
193
335
|
- thought (string, optional): The reasoning/thinking at this step.
|
|
194
336
|
- action (string, optional): The action taken, if any.
|
|
195
337
|
- observation (string, optional): The result observed, if any.
|
|
196
|
-
(
|
|
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.)
|
|
197
340
|
|
|
198
|
-
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.
|
|
199
342
|
|
|
200
343
|
Error Handling:
|
|
201
344
|
- Returns an error if session_id does not exist (call reasoning_start_session first, or reasoning_list_sessions to find the right id).
|
|
@@ -223,6 +366,8 @@ Error Handling:
|
|
|
223
366
|
? result.structuredContent.step_id
|
|
224
367
|
: null,
|
|
225
368
|
inputShape: {
|
|
369
|
+
batch: params.steps !== undefined,
|
|
370
|
+
batch_size: params.steps?.length ?? null,
|
|
226
371
|
thought_present: params.thought !== undefined,
|
|
227
372
|
action_present: params.action !== undefined,
|
|
228
373
|
observation_present: params.observation !== undefined,
|
|
@@ -232,20 +377,58 @@ Error Handling:
|
|
|
232
377
|
},
|
|
233
378
|
outputShape: {
|
|
234
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,
|
|
235
385
|
},
|
|
236
386
|
};
|
|
237
387
|
},
|
|
238
388
|
}, async (params) => {
|
|
239
389
|
try {
|
|
240
390
|
const activeDb = await resolveDatabase(database);
|
|
241
|
-
|
|
242
|
-
params.action
|
|
243
|
-
params.observation
|
|
391
|
+
const hasSingleFields = params.thought !== undefined ||
|
|
392
|
+
params.action !== undefined ||
|
|
393
|
+
params.observation !== undefined;
|
|
394
|
+
if (params.steps !== undefined && hasSingleFields) {
|
|
395
|
+
return {
|
|
396
|
+
content: [
|
|
397
|
+
{
|
|
398
|
+
type: "text",
|
|
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) {
|
|
244
427
|
return {
|
|
245
428
|
content: [
|
|
246
429
|
{
|
|
247
430
|
type: "text",
|
|
248
|
-
text:
|
|
431
|
+
text: `Error: steps[${invalidIndex}] must include at least one of thought, action, or observation.`,
|
|
249
432
|
},
|
|
250
433
|
],
|
|
251
434
|
isError: true,
|
|
@@ -276,7 +459,7 @@ Error Handling:
|
|
|
276
459
|
isError: true,
|
|
277
460
|
};
|
|
278
461
|
}
|
|
279
|
-
const
|
|
462
|
+
const insertedSteps = runInTransaction(activeDb, () => {
|
|
280
463
|
const lockedSession = activeDb
|
|
281
464
|
.prepare(`SELECT * FROM reasoning_sessions WHERE id = ?`)
|
|
282
465
|
.get(params.session_id);
|
|
@@ -286,22 +469,31 @@ Error Handling:
|
|
|
286
469
|
if (lockedSession.status !== "in_progress") {
|
|
287
470
|
throw new Error(`Session '${params.session_id}' is already '${lockedSession.status}' and cannot accept new steps.`);
|
|
288
471
|
}
|
|
289
|
-
const
|
|
290
|
-
const id = newId("step");
|
|
472
|
+
const firstStepNumber = getNextStepNumber(activeDb, params.session_id);
|
|
291
473
|
const ts = nowIso();
|
|
292
|
-
activeDb
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
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
|
+
});
|
|
296
481
|
activeDb
|
|
297
482
|
.prepare(`UPDATE reasoning_sessions SET updated_at = ? WHERE id = ?`)
|
|
298
483
|
.run(ts, params.session_id);
|
|
299
|
-
return
|
|
300
|
-
|
|
484
|
+
return created;
|
|
485
|
+
});
|
|
486
|
+
const output = params.steps !== undefined
|
|
487
|
+
? {
|
|
301
488
|
session_id: params.session_id,
|
|
302
|
-
|
|
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,
|
|
303
496
|
};
|
|
304
|
-
});
|
|
305
497
|
return {
|
|
306
498
|
content: [{ type: "text", text: toLimitedJson(output) }],
|
|
307
499
|
structuredContent: output,
|
|
@@ -850,13 +1042,14 @@ Args:
|
|
|
850
1042
|
- conclusion (string, required): The final answer/decision reached.
|
|
851
1043
|
- status ('completed'|'abandoned', default 'completed'): Use 'abandoned' if the task was dropped without a real conclusion.
|
|
852
1044
|
- save_as_memory (boolean, default false): If true, also create a memory with this conclusion.
|
|
853
|
-
- memory_mode ('auto'|'always'|'never', optional):
|
|
1045
|
+
- memory_mode ('auto'|'always'|'never', optional): 'auto' (default) does NOT save a memory on its own — a memory is only created when save_as_memory=true or memory_mode='always'; 'never' skips saving and requires not_saved_reason.
|
|
854
1046
|
- memory_type (optional): Memory type to use when a completion is persisted.
|
|
855
1047
|
- memory_importance (optional): Importance to use when a completion is persisted.
|
|
856
1048
|
- memory_tags (string[], default []): Tags for the created memory.
|
|
857
1049
|
- not_saved_reason (optional): Required when memory_mode='never'.
|
|
1050
|
+
- used_memory_ids (string[], default []): Ids of memories that actually helped during this session (e.g. from related_memories returned by reasoning_start_session). The server records a 'used' usage-feedback event for each.
|
|
858
1051
|
|
|
859
|
-
Returns: JSON with the updated session, created memory id if any, and skip warnings when memory is not saved.
|
|
1052
|
+
Returns: JSON with the updated session, created memory id if any, usage-feedback count, and skip warnings when memory is not saved.
|
|
860
1053
|
|
|
861
1054
|
Error Handling:
|
|
862
1055
|
- Returns "Error: Session '<id>' not found" if the id does not exist.
|
|
@@ -886,7 +1079,7 @@ Error Handling:
|
|
|
886
1079
|
reasonCategory = "caller_request";
|
|
887
1080
|
else if (params.status === "abandoned")
|
|
888
1081
|
reasonCategory = "not_completed";
|
|
889
|
-
else if (notSavedReason?.includes("
|
|
1082
|
+
else if (notSavedReason?.includes("no reasoning steps")) {
|
|
890
1083
|
reasonCategory = "zero_step";
|
|
891
1084
|
}
|
|
892
1085
|
return {
|
|
@@ -900,6 +1093,7 @@ Error Handling:
|
|
|
900
1093
|
memory_type: params.memory_type ?? null,
|
|
901
1094
|
memory_importance: params.memory_importance ?? null,
|
|
902
1095
|
tag_count: params.memory_tags?.length ?? 0,
|
|
1096
|
+
used_memory_count: params.used_memory_ids?.length ?? 0,
|
|
903
1097
|
},
|
|
904
1098
|
outputShape: {
|
|
905
1099
|
memory_id_present: typeof structured?.memory_id === "string",
|
|
@@ -963,16 +1157,46 @@ Error Handling:
|
|
|
963
1157
|
return null;
|
|
964
1158
|
const nextMemoryId = newId("mem");
|
|
965
1159
|
activeDb
|
|
966
|
-
.prepare(`INSERT INTO memories (id, type, content, tags, agent_id, importance, metadata, created_at, updated_at)
|
|
967
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
1160
|
+
.prepare(`INSERT INTO memories (id, type, content, tags, agent_id, importance, metadata, workspace, created_at, updated_at)
|
|
1161
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
968
1162
|
.run(nextMemoryId, params.memory_type ?? "reasoning_summary", params.conclusion, JSON.stringify(params.memory_tags ?? []), session.agent_id, params.memory_importance ?? 3, JSON.stringify({
|
|
969
1163
|
source_session_id: params.session_id,
|
|
970
1164
|
session_title: session.title,
|
|
971
1165
|
auto_saved: !(params.save_as_memory || params.memory_mode === "always"),
|
|
972
1166
|
step_count: stepCount,
|
|
973
|
-
}), ts, ts);
|
|
1167
|
+
}), getWorkspace(), ts, ts);
|
|
974
1168
|
return nextMemoryId;
|
|
975
1169
|
});
|
|
1170
|
+
const usedMemoryWarnings = [];
|
|
1171
|
+
let usedMemoryFeedbackRecorded = 0;
|
|
1172
|
+
for (const usedMemoryId of new Set(params.used_memory_ids ?? [])) {
|
|
1173
|
+
const exists = activeDb
|
|
1174
|
+
.prepare(`SELECT id FROM memories WHERE id = ?`)
|
|
1175
|
+
.get(usedMemoryId);
|
|
1176
|
+
if (!exists) {
|
|
1177
|
+
usedMemoryWarnings.push(`Memory '${usedMemoryId}' not found; usage feedback skipped.`);
|
|
1178
|
+
continue;
|
|
1179
|
+
}
|
|
1180
|
+
const feedbackEventId = await recordToolUsageEvent(activeDb, {
|
|
1181
|
+
toolName: "memory_record_usage_feedback",
|
|
1182
|
+
operationType: "feedback",
|
|
1183
|
+
accessType: "write",
|
|
1184
|
+
status: "success",
|
|
1185
|
+
agentId: session.agent_id,
|
|
1186
|
+
sessionId: params.session_id,
|
|
1187
|
+
memoryId: usedMemoryId,
|
|
1188
|
+
metadata: {
|
|
1189
|
+
usefulness: "used",
|
|
1190
|
+
source: "reasoning_complete_session",
|
|
1191
|
+
},
|
|
1192
|
+
});
|
|
1193
|
+
if (feedbackEventId) {
|
|
1194
|
+
usedMemoryFeedbackRecorded += 1;
|
|
1195
|
+
}
|
|
1196
|
+
else {
|
|
1197
|
+
usedMemoryWarnings.push(`Usage feedback for '${usedMemoryId}' could not be recorded.`);
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
976
1200
|
const updatedRow = activeDb
|
|
977
1201
|
.prepare(`SELECT * FROM reasoning_sessions WHERE id = ?`)
|
|
978
1202
|
.get(params.session_id);
|
|
@@ -981,9 +1205,13 @@ Error Handling:
|
|
|
981
1205
|
session: record,
|
|
982
1206
|
memory_id: memoryId,
|
|
983
1207
|
not_saved_reason: notSavedReason,
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
1208
|
+
used_memory_feedback_recorded: usedMemoryFeedbackRecorded,
|
|
1209
|
+
warnings: [
|
|
1210
|
+
...(stepCount === 0 && params.status === "completed"
|
|
1211
|
+
? ["Session completed with zero reasoning steps."]
|
|
1212
|
+
: []),
|
|
1213
|
+
...usedMemoryWarnings,
|
|
1214
|
+
],
|
|
987
1215
|
};
|
|
988
1216
|
return {
|
|
989
1217
|
content: [{ type: "text", text: toLimitedJson(output) }],
|
package/dist/tools/telemetry.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { MCP_VERSION,
|
|
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
|
-
|
|
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
|
@@ -30,12 +30,38 @@ export function parseJsonObject(text) {
|
|
|
30
30
|
}
|
|
31
31
|
/** FTS5 MATCH queries break on raw punctuation; wrap terms as a safe prefix query. */
|
|
32
32
|
export function toFtsQuery(raw) {
|
|
33
|
-
const terms = raw
|
|
33
|
+
const terms = ftsTerms(raw);
|
|
34
|
+
return terms.length ? terms.join(" ") : '""';
|
|
35
|
+
}
|
|
36
|
+
function ftsTerms(raw) {
|
|
37
|
+
return raw
|
|
34
38
|
.trim()
|
|
35
39
|
.split(/\s+/)
|
|
36
40
|
.filter(Boolean)
|
|
37
41
|
.map((t) => `"${t.replace(/"/g, '""')}"*`);
|
|
38
|
-
|
|
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, '""')}"*`);
|
|
39
65
|
}
|
|
40
66
|
/** Serialize a value to text, truncating with a clear message if it exceeds CHARACTER_LIMIT. */
|
|
41
67
|
export function toLimitedJson(value) {
|
|
@@ -50,7 +76,7 @@ export function toLimitedJson(value) {
|
|
|
50
76
|
}
|
|
51
77
|
export function handleToolError(error) {
|
|
52
78
|
if (error instanceof Error) {
|
|
53
|
-
//
|
|
79
|
+
// node:sqlite constraint violations
|
|
54
80
|
if (error.message.includes("CHECK constraint failed")) {
|
|
55
81
|
return `Error: Invalid value provided (${error.message}). Check allowed ranges/enums in the tool description.`;
|
|
56
82
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nhatnguyen9317/memory-mcp-server",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
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",
|
|
5
17
|
"type": "module",
|
|
6
18
|
"main": "dist/index.js",
|
|
@@ -14,7 +26,8 @@
|
|
|
14
26
|
"dist/types.js",
|
|
15
27
|
"dist/utils.js",
|
|
16
28
|
"README.md",
|
|
17
|
-
"GUIDELINES.md"
|
|
29
|
+
"GUIDELINES.md",
|
|
30
|
+
"CHANGELOG.md"
|
|
18
31
|
],
|
|
19
32
|
"bin": {
|
|
20
33
|
"memory-mcp-server": "dist/index.js"
|
|
@@ -24,7 +37,7 @@
|
|
|
24
37
|
"start": "node dist/index.js",
|
|
25
38
|
"dev": "tsx watch src/index.ts",
|
|
26
39
|
"build": "tsc && node -e \"require('fs').chmodSync('dist/index.js','755')\"",
|
|
27
|
-
"test": "npm run build && node --test dist/__tests__/*.test.js",
|
|
40
|
+
"test": "npm run build && MEMORY_TELEMETRY=on node --test dist/__tests__/*.test.js",
|
|
28
41
|
"clean": "rm -rf dist"
|
|
29
42
|
},
|
|
30
43
|
"engines": {
|