@nhatnguyen9317/memory-mcp-server 1.1.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/GUIDELINES.md +44 -0
- package/README.md +265 -0
- package/dist/constants.js +16 -0
- package/dist/db.js +17 -0
- package/dist/index.js +32 -0
- package/dist/migrations/0001_initial.js +74 -0
- package/dist/migrations/0002_reasoning_step_marks.js +22 -0
- package/dist/migrations/0003_reasoning_steps_fts.js +34 -0
- package/dist/migrations/0004_tool_usage_events.js +48 -0
- package/dist/migrations/index.js +40 -0
- package/dist/schemas/memory.js +213 -0
- package/dist/schemas/reasoning.js +159 -0
- package/dist/tools/memory.js +998 -0
- package/dist/tools/reasoning.js +1001 -0
- package/dist/tools/telemetry.js +103 -0
- package/dist/tools/usage-guide.js +83 -0
- package/dist/types.js +2 -0
- package/dist/utils.js +67 -0
- package/package.json +41 -0
|
@@ -0,0 +1,998 @@
|
|
|
1
|
+
import { MemoryAdoptionReportInputSchema, MemoryAgentScorecardInputSchema, MemoryDeleteInputSchema, MemoryGetInputSchema, MemoryListInputSchema, MemoryRecordUsageFeedbackInputSchema, MemorySaveInputSchema, MemorySearchInputSchema, MemoryUpdateInputSchema, MemoryUsageReportInputSchema, } from "../schemas/memory.js";
|
|
2
|
+
import { newId, nowIso, parseJsonArray, parseJsonObject, toFtsQuery, toLimitedJson, } from "../utils.js";
|
|
3
|
+
import { withTelemetry, } from "./telemetry.js";
|
|
4
|
+
function rowToRecord(row) {
|
|
5
|
+
return {
|
|
6
|
+
id: row.id,
|
|
7
|
+
type: row.type,
|
|
8
|
+
content: row.content,
|
|
9
|
+
tags: parseJsonArray(row.tags),
|
|
10
|
+
agent_id: row.agent_id,
|
|
11
|
+
importance: row.importance,
|
|
12
|
+
metadata: parseJsonObject(row.metadata),
|
|
13
|
+
created_at: row.created_at,
|
|
14
|
+
updated_at: row.updated_at,
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
function tagsFilterClauses(tags) {
|
|
18
|
+
if (!tags || tags.length === 0)
|
|
19
|
+
return { clause: "", params: [] };
|
|
20
|
+
const clause = tags.map(() => `tags LIKE ?`).join(" AND ");
|
|
21
|
+
const params = tags.map((tag) => `%"${tag}"%`);
|
|
22
|
+
return { clause: ` AND ${clause}`, params };
|
|
23
|
+
}
|
|
24
|
+
function extractStructuredContent(result) {
|
|
25
|
+
return result.structuredContent ?? null;
|
|
26
|
+
}
|
|
27
|
+
function resultCount(result) {
|
|
28
|
+
const structured = extractStructuredContent(result);
|
|
29
|
+
if (structured?.total_returned !== undefined) {
|
|
30
|
+
return Number(structured.total_returned);
|
|
31
|
+
}
|
|
32
|
+
if (Array.isArray(structured?.results))
|
|
33
|
+
return structured.results.length;
|
|
34
|
+
return result.content[0]?.text.startsWith("No memories found") ? 0 : 1;
|
|
35
|
+
}
|
|
36
|
+
function telemetryPersistenceEnabled() {
|
|
37
|
+
return process.env.MEMORY_TELEMETRY !== "off";
|
|
38
|
+
}
|
|
39
|
+
function normalizeTextDate(value) {
|
|
40
|
+
if (!value)
|
|
41
|
+
return undefined;
|
|
42
|
+
return value.trim();
|
|
43
|
+
}
|
|
44
|
+
function normalizeDateBoundary(value, boundary) {
|
|
45
|
+
const normalized = normalizeTextDate(value);
|
|
46
|
+
if (!normalized)
|
|
47
|
+
return undefined;
|
|
48
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(normalized)) {
|
|
49
|
+
return `${normalized}${boundary === "start" ? "T00:00:00.000Z" : "T23:59:59.999Z"}`;
|
|
50
|
+
}
|
|
51
|
+
const parsed = new Date(normalized);
|
|
52
|
+
if (Number.isNaN(parsed.getTime())) {
|
|
53
|
+
throw new Error(`Invalid date '${normalized}'. Expected YYYY-MM-DD or a valid date-time string.`);
|
|
54
|
+
}
|
|
55
|
+
return parsed.toISOString();
|
|
56
|
+
}
|
|
57
|
+
function appendAgentFilter(conditions, args, fieldName, agentId) {
|
|
58
|
+
if (agentId === null) {
|
|
59
|
+
conditions.push(`${fieldName} IS NULL`);
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
if (agentId) {
|
|
63
|
+
conditions.push(`${fieldName} = ?`);
|
|
64
|
+
args.push(agentId);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
function buildTelemetryWhere(params) {
|
|
68
|
+
const conditions = ["1=1"];
|
|
69
|
+
const args = [];
|
|
70
|
+
appendAgentFilter(conditions, args, "agent_id", params.agent_id);
|
|
71
|
+
if (params.client_name) {
|
|
72
|
+
conditions.push("client_name = ?");
|
|
73
|
+
args.push(params.client_name);
|
|
74
|
+
}
|
|
75
|
+
if (params.mcp_version) {
|
|
76
|
+
conditions.push("mcp_version = ?");
|
|
77
|
+
args.push(params.mcp_version);
|
|
78
|
+
}
|
|
79
|
+
const dateFrom = normalizeDateBoundary(params.date_from, "start");
|
|
80
|
+
if (dateFrom) {
|
|
81
|
+
conditions.push("created_at >= ?");
|
|
82
|
+
args.push(dateFrom);
|
|
83
|
+
}
|
|
84
|
+
const dateTo = normalizeDateBoundary(params.date_to, "end");
|
|
85
|
+
if (dateTo) {
|
|
86
|
+
conditions.push("created_at <= ?");
|
|
87
|
+
args.push(dateTo);
|
|
88
|
+
}
|
|
89
|
+
return { clause: conditions.join(" AND "), args };
|
|
90
|
+
}
|
|
91
|
+
function buildSessionWhere(params) {
|
|
92
|
+
const conditions = ["1=1"];
|
|
93
|
+
const args = [];
|
|
94
|
+
appendAgentFilter(conditions, args, "agent_id", params.agent_id);
|
|
95
|
+
const dateFrom = normalizeDateBoundary(params.date_from, "start");
|
|
96
|
+
if (dateFrom) {
|
|
97
|
+
conditions.push("created_at >= ?");
|
|
98
|
+
args.push(dateFrom);
|
|
99
|
+
}
|
|
100
|
+
const dateTo = normalizeDateBoundary(params.date_to, "end");
|
|
101
|
+
if (dateTo) {
|
|
102
|
+
conditions.push("created_at <= ?");
|
|
103
|
+
args.push(dateTo);
|
|
104
|
+
}
|
|
105
|
+
return { clause: conditions.join(" AND "), args };
|
|
106
|
+
}
|
|
107
|
+
let defaultDatabasePromise = null;
|
|
108
|
+
async function resolveDatabase(database) {
|
|
109
|
+
if (database)
|
|
110
|
+
return database;
|
|
111
|
+
defaultDatabasePromise ??= import("../db.js").then((module) => module.db);
|
|
112
|
+
return defaultDatabasePromise;
|
|
113
|
+
}
|
|
114
|
+
export function registerMemoryTools(server, database) {
|
|
115
|
+
const databaseProvider = () => resolveDatabase(database);
|
|
116
|
+
server.registerTool("memory_save", {
|
|
117
|
+
title: "Save Memory",
|
|
118
|
+
description: "Persist a piece of long-term memory so it can be recalled in future sessions.",
|
|
119
|
+
inputSchema: MemorySaveInputSchema.shape,
|
|
120
|
+
annotations: {
|
|
121
|
+
readOnlyHint: false,
|
|
122
|
+
destructiveHint: false,
|
|
123
|
+
idempotentHint: false,
|
|
124
|
+
openWorldHint: false,
|
|
125
|
+
},
|
|
126
|
+
}, withTelemetry({
|
|
127
|
+
database: databaseProvider,
|
|
128
|
+
toolName: "memory_save",
|
|
129
|
+
operationType: "memory",
|
|
130
|
+
accessType: "write",
|
|
131
|
+
buildEvent: (params, result) => {
|
|
132
|
+
const structured = extractStructuredContent(result);
|
|
133
|
+
return {
|
|
134
|
+
agentId: params.agent_id ?? null,
|
|
135
|
+
memoryId: typeof structured?.id === "string" ? structured.id : null,
|
|
136
|
+
inputShape: {
|
|
137
|
+
content_length: params.content.length,
|
|
138
|
+
type: params.type,
|
|
139
|
+
tag_count: params.tags?.length ?? 0,
|
|
140
|
+
importance: params.importance,
|
|
141
|
+
},
|
|
142
|
+
outputShape: structured
|
|
143
|
+
? {
|
|
144
|
+
memory_id: structured.id,
|
|
145
|
+
type: structured.type,
|
|
146
|
+
tag_count: Array.isArray(structured.tags) ? structured.tags.length : 0,
|
|
147
|
+
}
|
|
148
|
+
: null,
|
|
149
|
+
};
|
|
150
|
+
},
|
|
151
|
+
}, async (params) => {
|
|
152
|
+
const activeDb = await resolveDatabase(database);
|
|
153
|
+
const id = newId("mem");
|
|
154
|
+
const ts = nowIso();
|
|
155
|
+
activeDb
|
|
156
|
+
.prepare(`INSERT INTO memories (id, type, content, tags, agent_id, importance, metadata, created_at, updated_at)
|
|
157
|
+
VALUES (@id, @type, @content, @tags, @agent_id, @importance, @metadata, @created_at, @updated_at)`)
|
|
158
|
+
.run({
|
|
159
|
+
id,
|
|
160
|
+
type: params.type,
|
|
161
|
+
content: params.content,
|
|
162
|
+
tags: JSON.stringify(params.tags ?? []),
|
|
163
|
+
agent_id: params.agent_id ?? null,
|
|
164
|
+
importance: params.importance,
|
|
165
|
+
metadata: params.metadata ? JSON.stringify(params.metadata) : null,
|
|
166
|
+
created_at: ts,
|
|
167
|
+
updated_at: ts,
|
|
168
|
+
});
|
|
169
|
+
const row = activeDb
|
|
170
|
+
.prepare(`SELECT * FROM memories WHERE id = ?`)
|
|
171
|
+
.get(id);
|
|
172
|
+
const record = rowToRecord(row);
|
|
173
|
+
return {
|
|
174
|
+
content: [
|
|
175
|
+
{
|
|
176
|
+
type: "text",
|
|
177
|
+
text: `Memory saved with id ${id}.\n\n${toLimitedJson(record)}`,
|
|
178
|
+
},
|
|
179
|
+
],
|
|
180
|
+
structuredContent: record,
|
|
181
|
+
};
|
|
182
|
+
}));
|
|
183
|
+
server.registerTool("memory_search", {
|
|
184
|
+
title: "Search Memories",
|
|
185
|
+
description: "Full-text search over saved memories (content and tags), ranked by relevance.",
|
|
186
|
+
inputSchema: MemorySearchInputSchema.shape,
|
|
187
|
+
annotations: {
|
|
188
|
+
readOnlyHint: true,
|
|
189
|
+
destructiveHint: false,
|
|
190
|
+
idempotentHint: true,
|
|
191
|
+
openWorldHint: false,
|
|
192
|
+
},
|
|
193
|
+
}, withTelemetry({
|
|
194
|
+
database: databaseProvider,
|
|
195
|
+
toolName: "memory_search",
|
|
196
|
+
operationType: "memory",
|
|
197
|
+
accessType: "read",
|
|
198
|
+
buildEvent: (params, result) => ({
|
|
199
|
+
agentId: params.agent_id ?? null,
|
|
200
|
+
inputShape: {
|
|
201
|
+
query_length: params.query.length,
|
|
202
|
+
query_term_count: params.query.trim().split(/\s+/).filter(Boolean).length,
|
|
203
|
+
has_type: params.type !== undefined,
|
|
204
|
+
has_agent_id: params.agent_id !== undefined,
|
|
205
|
+
has_tags: (params.tags?.length ?? 0) > 0,
|
|
206
|
+
limit: params.limit,
|
|
207
|
+
},
|
|
208
|
+
outputShape: {
|
|
209
|
+
result_count: resultCount(result),
|
|
210
|
+
has_more: extractStructuredContent(result)?.has_more === true,
|
|
211
|
+
},
|
|
212
|
+
}),
|
|
213
|
+
}, async (params) => {
|
|
214
|
+
const activeDb = await resolveDatabase(database);
|
|
215
|
+
const { clause: tagClause, params: tagParams } = tagsFilterClauses(params.tags);
|
|
216
|
+
const conditions = [
|
|
217
|
+
"m.rowid IN (SELECT rowid FROM memories_fts WHERE memories_fts MATCH ?)",
|
|
218
|
+
];
|
|
219
|
+
const sqlParams = [toFtsQuery(params.query)];
|
|
220
|
+
if (params.type) {
|
|
221
|
+
conditions.push("m.type = ?");
|
|
222
|
+
sqlParams.push(params.type);
|
|
223
|
+
}
|
|
224
|
+
if (params.agent_id) {
|
|
225
|
+
conditions.push("m.agent_id = ?");
|
|
226
|
+
sqlParams.push(params.agent_id);
|
|
227
|
+
}
|
|
228
|
+
const rows = activeDb
|
|
229
|
+
.prepare(`SELECT m.* FROM memories m
|
|
230
|
+
WHERE ${conditions.join(" AND ")}${tagClause}
|
|
231
|
+
ORDER BY m.importance DESC, m.updated_at DESC
|
|
232
|
+
LIMIT ? OFFSET ?`)
|
|
233
|
+
.all(...sqlParams, ...tagParams, params.limit, params.offset);
|
|
234
|
+
if (rows.length === 0) {
|
|
235
|
+
return {
|
|
236
|
+
content: [
|
|
237
|
+
{
|
|
238
|
+
type: "text",
|
|
239
|
+
text: `No memories found matching '${params.query}'.`,
|
|
240
|
+
},
|
|
241
|
+
],
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
const results = rows.map(rowToRecord);
|
|
245
|
+
const output = {
|
|
246
|
+
total_returned: results.length,
|
|
247
|
+
offset: params.offset,
|
|
248
|
+
results,
|
|
249
|
+
};
|
|
250
|
+
return {
|
|
251
|
+
content: [{ type: "text", text: toLimitedJson(output) }],
|
|
252
|
+
structuredContent: output,
|
|
253
|
+
};
|
|
254
|
+
}));
|
|
255
|
+
server.registerTool("memory_list", {
|
|
256
|
+
title: "List Memories",
|
|
257
|
+
description: "List saved memories with optional filters, sorted chronologically or by importance.",
|
|
258
|
+
inputSchema: MemoryListInputSchema.shape,
|
|
259
|
+
annotations: {
|
|
260
|
+
readOnlyHint: true,
|
|
261
|
+
destructiveHint: false,
|
|
262
|
+
idempotentHint: true,
|
|
263
|
+
openWorldHint: false,
|
|
264
|
+
},
|
|
265
|
+
}, withTelemetry({
|
|
266
|
+
database: databaseProvider,
|
|
267
|
+
toolName: "memory_list",
|
|
268
|
+
operationType: "memory",
|
|
269
|
+
accessType: "read",
|
|
270
|
+
buildEvent: (params, result) => ({
|
|
271
|
+
agentId: params.agent_id ?? null,
|
|
272
|
+
inputShape: {
|
|
273
|
+
has_type: params.type !== undefined,
|
|
274
|
+
has_agent_id: params.agent_id !== undefined,
|
|
275
|
+
has_tags: (params.tags?.length ?? 0) > 0,
|
|
276
|
+
min_importance: params.min_importance ?? null,
|
|
277
|
+
sort_by: params.sort_by,
|
|
278
|
+
limit: params.limit,
|
|
279
|
+
},
|
|
280
|
+
outputShape: {
|
|
281
|
+
result_count: resultCount(result),
|
|
282
|
+
has_more: extractStructuredContent(result)?.has_more === true,
|
|
283
|
+
},
|
|
284
|
+
}),
|
|
285
|
+
}, async (params) => {
|
|
286
|
+
const activeDb = await resolveDatabase(database);
|
|
287
|
+
const { clause: tagClause, params: tagParams } = tagsFilterClauses(params.tags);
|
|
288
|
+
const conditions = ["1=1"];
|
|
289
|
+
const sqlParams = [];
|
|
290
|
+
if (params.type) {
|
|
291
|
+
conditions.push("type = ?");
|
|
292
|
+
sqlParams.push(params.type);
|
|
293
|
+
}
|
|
294
|
+
if (params.agent_id) {
|
|
295
|
+
conditions.push("agent_id = ?");
|
|
296
|
+
sqlParams.push(params.agent_id);
|
|
297
|
+
}
|
|
298
|
+
if (params.min_importance !== undefined) {
|
|
299
|
+
conditions.push("importance >= ?");
|
|
300
|
+
sqlParams.push(params.min_importance);
|
|
301
|
+
}
|
|
302
|
+
const countRow = activeDb
|
|
303
|
+
.prepare(`SELECT COUNT(*) as c FROM memories WHERE ${conditions.join(" AND ")}${tagClause}`)
|
|
304
|
+
.get(...sqlParams, ...tagParams);
|
|
305
|
+
const rows = activeDb
|
|
306
|
+
.prepare(`SELECT * FROM memories WHERE ${conditions.join(" AND ")}${tagClause}
|
|
307
|
+
ORDER BY ${params.sort_by} DESC LIMIT ? OFFSET ?`)
|
|
308
|
+
.all(...sqlParams, ...tagParams, params.limit, params.offset);
|
|
309
|
+
const results = rows.map(rowToRecord);
|
|
310
|
+
const hasMore = countRow.c > params.offset + results.length;
|
|
311
|
+
const output = {
|
|
312
|
+
total: countRow.c,
|
|
313
|
+
total_returned: results.length,
|
|
314
|
+
offset: params.offset,
|
|
315
|
+
has_more: hasMore,
|
|
316
|
+
...(hasMore ? { next_offset: params.offset + results.length } : {}),
|
|
317
|
+
results,
|
|
318
|
+
};
|
|
319
|
+
return {
|
|
320
|
+
content: [{ type: "text", text: toLimitedJson(output) }],
|
|
321
|
+
structuredContent: output,
|
|
322
|
+
};
|
|
323
|
+
}));
|
|
324
|
+
server.registerTool("memory_get", {
|
|
325
|
+
title: "Get Memory",
|
|
326
|
+
description: "Retrieve a single memory by its id.",
|
|
327
|
+
inputSchema: MemoryGetInputSchema.shape,
|
|
328
|
+
annotations: {
|
|
329
|
+
readOnlyHint: true,
|
|
330
|
+
destructiveHint: false,
|
|
331
|
+
idempotentHint: true,
|
|
332
|
+
openWorldHint: false,
|
|
333
|
+
},
|
|
334
|
+
}, withTelemetry({
|
|
335
|
+
database: databaseProvider,
|
|
336
|
+
toolName: "memory_get",
|
|
337
|
+
operationType: "memory",
|
|
338
|
+
accessType: "read",
|
|
339
|
+
buildEvent: (params, result) => {
|
|
340
|
+
const structured = extractStructuredContent(result);
|
|
341
|
+
return {
|
|
342
|
+
memoryId: params.id,
|
|
343
|
+
outputShape: {
|
|
344
|
+
found: structured !== null && result.isError !== true,
|
|
345
|
+
},
|
|
346
|
+
};
|
|
347
|
+
},
|
|
348
|
+
}, async (params) => {
|
|
349
|
+
const activeDb = await resolveDatabase(database);
|
|
350
|
+
const row = activeDb.prepare(`SELECT * FROM memories WHERE id = ?`).get(params.id);
|
|
351
|
+
if (!row) {
|
|
352
|
+
return {
|
|
353
|
+
content: [
|
|
354
|
+
{
|
|
355
|
+
type: "text",
|
|
356
|
+
text: `Error: Memory '${params.id}' not found.`,
|
|
357
|
+
},
|
|
358
|
+
],
|
|
359
|
+
isError: true,
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
const record = rowToRecord(row);
|
|
363
|
+
return {
|
|
364
|
+
content: [{ type: "text", text: toLimitedJson(record) }],
|
|
365
|
+
structuredContent: record,
|
|
366
|
+
};
|
|
367
|
+
}));
|
|
368
|
+
server.registerTool("memory_update", {
|
|
369
|
+
title: "Update Memory",
|
|
370
|
+
description: "Update one or more fields of an existing memory.",
|
|
371
|
+
inputSchema: MemoryUpdateInputSchema.shape,
|
|
372
|
+
annotations: {
|
|
373
|
+
readOnlyHint: false,
|
|
374
|
+
destructiveHint: false,
|
|
375
|
+
idempotentHint: true,
|
|
376
|
+
openWorldHint: false,
|
|
377
|
+
},
|
|
378
|
+
}, withTelemetry({
|
|
379
|
+
database: databaseProvider,
|
|
380
|
+
toolName: "memory_update",
|
|
381
|
+
operationType: "memory",
|
|
382
|
+
accessType: "write",
|
|
383
|
+
buildEvent: (params, result) => {
|
|
384
|
+
const structured = extractStructuredContent(result);
|
|
385
|
+
const updatedFields = [
|
|
386
|
+
"content",
|
|
387
|
+
"type",
|
|
388
|
+
"tags",
|
|
389
|
+
"tags_append",
|
|
390
|
+
"tags_remove",
|
|
391
|
+
"importance",
|
|
392
|
+
"metadata",
|
|
393
|
+
"metadata_patch",
|
|
394
|
+
].filter((field) => field in params && params[field] !== undefined);
|
|
395
|
+
return {
|
|
396
|
+
memoryId: params.id,
|
|
397
|
+
inputShape: {
|
|
398
|
+
updated_fields: updatedFields,
|
|
399
|
+
tag_replace: params.tags !== undefined,
|
|
400
|
+
tag_patch: params.tags_append !== undefined || params.tags_remove !== undefined,
|
|
401
|
+
metadata_replace: params.metadata !== undefined,
|
|
402
|
+
metadata_patch: params.metadata_patch !== undefined,
|
|
403
|
+
},
|
|
404
|
+
outputShape: structured
|
|
405
|
+
? {
|
|
406
|
+
memory_id: structured.id,
|
|
407
|
+
type: structured.type,
|
|
408
|
+
tag_count: Array.isArray(structured.tags) ? structured.tags.length : 0,
|
|
409
|
+
}
|
|
410
|
+
: null,
|
|
411
|
+
};
|
|
412
|
+
},
|
|
413
|
+
}, async (params) => {
|
|
414
|
+
const activeDb = await resolveDatabase(database);
|
|
415
|
+
if (params.content === undefined &&
|
|
416
|
+
params.type === undefined &&
|
|
417
|
+
params.tags === undefined &&
|
|
418
|
+
params.tags_append === undefined &&
|
|
419
|
+
params.tags_remove === undefined &&
|
|
420
|
+
params.importance === undefined &&
|
|
421
|
+
params.metadata === undefined &&
|
|
422
|
+
params.metadata_patch === undefined) {
|
|
423
|
+
return {
|
|
424
|
+
content: [
|
|
425
|
+
{
|
|
426
|
+
type: "text",
|
|
427
|
+
text: "Error: At least one field to update (content, type, tags, tags_append, tags_remove, importance, metadata, metadata_patch) must be provided.",
|
|
428
|
+
},
|
|
429
|
+
],
|
|
430
|
+
isError: true,
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
const existing = activeDb.prepare(`SELECT * FROM memories WHERE id = ?`).get(params.id);
|
|
434
|
+
if (!existing) {
|
|
435
|
+
return {
|
|
436
|
+
content: [
|
|
437
|
+
{
|
|
438
|
+
type: "text",
|
|
439
|
+
text: `Error: Memory '${params.id}' not found.`,
|
|
440
|
+
},
|
|
441
|
+
],
|
|
442
|
+
isError: true,
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
const existingTags = parseJsonArray(existing.tags);
|
|
446
|
+
const mergedTags = params.tags !== undefined
|
|
447
|
+
? params.tags
|
|
448
|
+
: [
|
|
449
|
+
...new Set(existingTags
|
|
450
|
+
.filter((tag) => !(params.tags_remove ?? []).includes(tag))
|
|
451
|
+
.concat(params.tags_append ?? [])),
|
|
452
|
+
];
|
|
453
|
+
const existingMetadata = parseJsonObject(existing.metadata) ?? {};
|
|
454
|
+
const mergedMetadata = params.metadata !== undefined
|
|
455
|
+
? params.metadata
|
|
456
|
+
: params.metadata_patch !== undefined
|
|
457
|
+
? { ...existingMetadata, ...params.metadata_patch }
|
|
458
|
+
: existingMetadata;
|
|
459
|
+
activeDb
|
|
460
|
+
.prepare(`UPDATE memories
|
|
461
|
+
SET content=@content, type=@type, tags=@tags, importance=@importance, metadata=@metadata, updated_at=@updated_at
|
|
462
|
+
WHERE id=@id`)
|
|
463
|
+
.run({
|
|
464
|
+
id: params.id,
|
|
465
|
+
content: params.content ?? existing.content,
|
|
466
|
+
type: params.type ?? existing.type,
|
|
467
|
+
tags: JSON.stringify(mergedTags),
|
|
468
|
+
importance: params.importance ?? existing.importance,
|
|
469
|
+
metadata: JSON.stringify(mergedMetadata),
|
|
470
|
+
updated_at: nowIso(),
|
|
471
|
+
});
|
|
472
|
+
const row = activeDb
|
|
473
|
+
.prepare(`SELECT * FROM memories WHERE id = ?`)
|
|
474
|
+
.get(params.id);
|
|
475
|
+
const record = rowToRecord(row);
|
|
476
|
+
return {
|
|
477
|
+
content: [{ type: "text", text: toLimitedJson(record) }],
|
|
478
|
+
structuredContent: record,
|
|
479
|
+
};
|
|
480
|
+
}));
|
|
481
|
+
server.registerTool("memory_delete", {
|
|
482
|
+
title: "Delete Memory",
|
|
483
|
+
description: "Permanently delete a memory by id.",
|
|
484
|
+
inputSchema: MemoryDeleteInputSchema.shape,
|
|
485
|
+
annotations: {
|
|
486
|
+
readOnlyHint: false,
|
|
487
|
+
destructiveHint: true,
|
|
488
|
+
idempotentHint: true,
|
|
489
|
+
openWorldHint: false,
|
|
490
|
+
},
|
|
491
|
+
}, withTelemetry({
|
|
492
|
+
database: databaseProvider,
|
|
493
|
+
toolName: "memory_delete",
|
|
494
|
+
operationType: "memory",
|
|
495
|
+
accessType: "delete",
|
|
496
|
+
buildEvent: (params) => ({
|
|
497
|
+
memoryId: params.id,
|
|
498
|
+
outputShape: { deleted: true },
|
|
499
|
+
}),
|
|
500
|
+
}, async (params) => {
|
|
501
|
+
const activeDb = await resolveDatabase(database);
|
|
502
|
+
const result = activeDb.prepare(`DELETE FROM memories WHERE id = ?`).run(params.id);
|
|
503
|
+
if (result.changes === 0) {
|
|
504
|
+
return {
|
|
505
|
+
content: [
|
|
506
|
+
{
|
|
507
|
+
type: "text",
|
|
508
|
+
text: `Error: Memory '${params.id}' not found.`,
|
|
509
|
+
},
|
|
510
|
+
],
|
|
511
|
+
isError: true,
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
return {
|
|
515
|
+
content: [
|
|
516
|
+
{
|
|
517
|
+
type: "text",
|
|
518
|
+
text: `Memory '${params.id}' deleted.`,
|
|
519
|
+
},
|
|
520
|
+
],
|
|
521
|
+
};
|
|
522
|
+
}));
|
|
523
|
+
server.registerTool("memory_usage_report", {
|
|
524
|
+
title: "Memory Usage Report",
|
|
525
|
+
description: "Aggregate tool usage events by tool, agent, client, version, operation type, status, or day.",
|
|
526
|
+
inputSchema: MemoryUsageReportInputSchema.shape,
|
|
527
|
+
annotations: {
|
|
528
|
+
readOnlyHint: true,
|
|
529
|
+
destructiveHint: false,
|
|
530
|
+
idempotentHint: true,
|
|
531
|
+
openWorldHint: false,
|
|
532
|
+
},
|
|
533
|
+
}, withTelemetry({
|
|
534
|
+
database: databaseProvider,
|
|
535
|
+
toolName: "memory_usage_report",
|
|
536
|
+
operationType: "report",
|
|
537
|
+
accessType: "derived",
|
|
538
|
+
buildEvent: (_params, result) => ({
|
|
539
|
+
outputShape: {
|
|
540
|
+
row_count: Array.isArray(extractStructuredContent(result)?.groups)
|
|
541
|
+
? (extractStructuredContent(result)?.groups).length
|
|
542
|
+
: 0,
|
|
543
|
+
},
|
|
544
|
+
}),
|
|
545
|
+
}, async (params) => {
|
|
546
|
+
const activeDb = await resolveDatabase(database);
|
|
547
|
+
const { clause, args } = buildTelemetryWhere(params);
|
|
548
|
+
const groupBySql = {
|
|
549
|
+
tool_name: "tool_name",
|
|
550
|
+
agent_id: "COALESCE(agent_id, 'unknown')",
|
|
551
|
+
client_name: "COALESCE(client_name, 'unknown')",
|
|
552
|
+
mcp_version: "mcp_version",
|
|
553
|
+
operation_type: "operation_type",
|
|
554
|
+
status: "status",
|
|
555
|
+
day: "substr(created_at, 1, 10)",
|
|
556
|
+
};
|
|
557
|
+
const summaryRow = activeDb
|
|
558
|
+
.prepare(`SELECT
|
|
559
|
+
COUNT(*) as total_events,
|
|
560
|
+
SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as success_events,
|
|
561
|
+
SUM(CASE WHEN status = 'error' THEN 1 ELSE 0 END) as error_events
|
|
562
|
+
FROM tool_usage_events
|
|
563
|
+
WHERE ${clause}`)
|
|
564
|
+
.get(...args);
|
|
565
|
+
const groups = activeDb
|
|
566
|
+
.prepare(`SELECT
|
|
567
|
+
${groupBySql[params.group_by]} as key,
|
|
568
|
+
COUNT(*) as event_count,
|
|
569
|
+
SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as success_count,
|
|
570
|
+
SUM(CASE WHEN status = 'error' THEN 1 ELSE 0 END) as error_count
|
|
571
|
+
FROM tool_usage_events
|
|
572
|
+
WHERE ${clause}
|
|
573
|
+
GROUP BY key
|
|
574
|
+
ORDER BY event_count DESC, key ASC
|
|
575
|
+
LIMIT ?`)
|
|
576
|
+
.all(...args, params.limit);
|
|
577
|
+
const topErrors = activeDb
|
|
578
|
+
.prepare(`SELECT
|
|
579
|
+
COALESCE(error_code, 'unknown') as error_code,
|
|
580
|
+
COUNT(*) as count
|
|
581
|
+
FROM tool_usage_events
|
|
582
|
+
WHERE ${clause} AND status = 'error'
|
|
583
|
+
GROUP BY error_code
|
|
584
|
+
ORDER BY count DESC, error_code ASC
|
|
585
|
+
LIMIT 10`)
|
|
586
|
+
.all(...args);
|
|
587
|
+
const totalEvents = summaryRow.total_events ?? 0;
|
|
588
|
+
const successEvents = summaryRow.success_events ?? 0;
|
|
589
|
+
const errorEvents = summaryRow.error_events ?? 0;
|
|
590
|
+
const output = {
|
|
591
|
+
summary: {
|
|
592
|
+
total_events: totalEvents,
|
|
593
|
+
success_events: successEvents,
|
|
594
|
+
error_events: errorEvents,
|
|
595
|
+
success_rate: totalEvents === 0 ? 0 : successEvents / totalEvents,
|
|
596
|
+
error_rate: totalEvents === 0 ? 0 : errorEvents / totalEvents,
|
|
597
|
+
},
|
|
598
|
+
groups,
|
|
599
|
+
top_errors: topErrors,
|
|
600
|
+
time_range: {
|
|
601
|
+
date_from: params.date_from ?? null,
|
|
602
|
+
date_to: params.date_to ?? null,
|
|
603
|
+
},
|
|
604
|
+
};
|
|
605
|
+
return {
|
|
606
|
+
content: [{ type: "text", text: toLimitedJson(output) }],
|
|
607
|
+
structuredContent: output,
|
|
608
|
+
};
|
|
609
|
+
}));
|
|
610
|
+
server.registerTool("memory_adoption_report", {
|
|
611
|
+
title: "Memory Adoption Report",
|
|
612
|
+
description: "Summarize reasoning and memory adoption behavior using telemetry plus core session tables.",
|
|
613
|
+
inputSchema: MemoryAdoptionReportInputSchema.shape,
|
|
614
|
+
annotations: {
|
|
615
|
+
readOnlyHint: true,
|
|
616
|
+
destructiveHint: false,
|
|
617
|
+
idempotentHint: true,
|
|
618
|
+
openWorldHint: false,
|
|
619
|
+
},
|
|
620
|
+
}, withTelemetry({
|
|
621
|
+
database: databaseProvider,
|
|
622
|
+
toolName: "memory_adoption_report",
|
|
623
|
+
operationType: "report",
|
|
624
|
+
accessType: "derived",
|
|
625
|
+
buildEvent: (_params, result) => ({
|
|
626
|
+
outputShape: {
|
|
627
|
+
row_count: Array.isArray(extractStructuredContent(result)?.agent_breakdown)
|
|
628
|
+
? (extractStructuredContent(result)?.agent_breakdown).length
|
|
629
|
+
: 0,
|
|
630
|
+
},
|
|
631
|
+
}),
|
|
632
|
+
}, async (params) => {
|
|
633
|
+
const activeDb = await resolveDatabase(database);
|
|
634
|
+
const sessionFilter = buildSessionWhere(params);
|
|
635
|
+
const eventFilter = buildTelemetryWhere(params);
|
|
636
|
+
const sessionSummary = activeDb
|
|
637
|
+
.prepare(`SELECT
|
|
638
|
+
COUNT(*) as reasoning_started,
|
|
639
|
+
SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as reasoning_completed,
|
|
640
|
+
SUM(CASE WHEN status = 'abandoned' THEN 1 ELSE 0 END) as reasoning_abandoned
|
|
641
|
+
FROM reasoning_sessions
|
|
642
|
+
WHERE ${sessionFilter.clause}`)
|
|
643
|
+
.get(...sessionFilter.args);
|
|
644
|
+
const zeroStepRow = activeDb
|
|
645
|
+
.prepare(`SELECT COUNT(*) as zero_step_sessions
|
|
646
|
+
FROM reasoning_sessions
|
|
647
|
+
LEFT JOIN reasoning_steps
|
|
648
|
+
ON reasoning_steps.session_id = reasoning_sessions.id
|
|
649
|
+
WHERE ${sessionFilter.clause}
|
|
650
|
+
GROUP BY reasoning_sessions.id
|
|
651
|
+
HAVING COUNT(reasoning_steps.id) = 0`)
|
|
652
|
+
.all(...sessionFilter.args);
|
|
653
|
+
const completionEvents = activeDb
|
|
654
|
+
.prepare(`SELECT
|
|
655
|
+
COUNT(*) as total,
|
|
656
|
+
SUM(CASE WHEN json_extract(output_shape, '$.memory_id_present') = 1 THEN 1 ELSE 0 END) as with_memory,
|
|
657
|
+
SUM(CASE WHEN json_extract(output_shape, '$.memory_id_present') = 0 THEN 1 ELSE 0 END) as without_memory
|
|
658
|
+
FROM tool_usage_events
|
|
659
|
+
WHERE ${eventFilter.clause}
|
|
660
|
+
AND tool_name = 'reasoning_complete_session'
|
|
661
|
+
AND status = 'success'`)
|
|
662
|
+
.get(...eventFilter.args);
|
|
663
|
+
const skipReasonRows = activeDb
|
|
664
|
+
.prepare(`SELECT
|
|
665
|
+
COALESCE(json_extract(output_shape, '$.not_saved_reason_category'), 'none') as reason,
|
|
666
|
+
COUNT(*) as count
|
|
667
|
+
FROM tool_usage_events
|
|
668
|
+
WHERE ${eventFilter.clause}
|
|
669
|
+
AND tool_name = 'reasoning_complete_session'
|
|
670
|
+
AND status = 'success'
|
|
671
|
+
AND json_extract(output_shape, '$.not_saved_reason_category') IS NOT NULL
|
|
672
|
+
GROUP BY reason
|
|
673
|
+
ORDER BY count DESC, reason ASC`)
|
|
674
|
+
.all(...eventFilter.args);
|
|
675
|
+
const eventSummary = activeDb
|
|
676
|
+
.prepare(`SELECT
|
|
677
|
+
SUM(CASE WHEN tool_name = 'memory_save' AND status = 'success' THEN 1 ELSE 0 END) as direct_memory_saved,
|
|
678
|
+
SUM(CASE WHEN tool_name IN ('memory_search', 'memory_list', 'memory_get') AND status = 'success' THEN 1 ELSE 0 END) as memory_searched,
|
|
679
|
+
SUM(CASE WHEN tool_name = 'memory_update' AND status = 'success' THEN 1 ELSE 0 END) as memory_updated,
|
|
680
|
+
SUM(CASE
|
|
681
|
+
WHEN tool_name = 'memory_search' AND status = 'success'
|
|
682
|
+
THEN COALESCE(json_extract(output_shape, '$.result_count'), 0)
|
|
683
|
+
WHEN tool_name = 'memory_list' AND status = 'success'
|
|
684
|
+
THEN COALESCE(json_extract(output_shape, '$.result_count'), 0)
|
|
685
|
+
WHEN tool_name = 'memory_get' AND status = 'success'
|
|
686
|
+
AND COALESCE(json_extract(output_shape, '$.found'), 0) = 1
|
|
687
|
+
THEN 1
|
|
688
|
+
ELSE 0
|
|
689
|
+
END) as memory_recalled
|
|
690
|
+
FROM tool_usage_events
|
|
691
|
+
WHERE ${eventFilter.clause}`)
|
|
692
|
+
.get(...eventFilter.args);
|
|
693
|
+
const feedbackSummary = activeDb
|
|
694
|
+
.prepare(`SELECT
|
|
695
|
+
SUM(CASE WHEN json_extract(metadata, '$.usefulness') = 'used' THEN 1 ELSE 0 END) as used_count
|
|
696
|
+
FROM tool_usage_events
|
|
697
|
+
WHERE ${eventFilter.clause}
|
|
698
|
+
AND operation_type = 'feedback'
|
|
699
|
+
AND related_event_id IS NOT NULL
|
|
700
|
+
AND status = 'success'`)
|
|
701
|
+
.get(...eventFilter.args);
|
|
702
|
+
const agentBreakdown = activeDb
|
|
703
|
+
.prepare(`SELECT
|
|
704
|
+
COALESCE(agent_id, 'unknown') as agent_id,
|
|
705
|
+
COUNT(*) as event_count
|
|
706
|
+
FROM tool_usage_events
|
|
707
|
+
WHERE ${eventFilter.clause}
|
|
708
|
+
GROUP BY agent_id
|
|
709
|
+
ORDER BY event_count DESC, agent_id ASC
|
|
710
|
+
LIMIT ?`)
|
|
711
|
+
.all(...eventFilter.args, params.limit);
|
|
712
|
+
const versionBreakdown = activeDb
|
|
713
|
+
.prepare(`SELECT
|
|
714
|
+
mcp_version,
|
|
715
|
+
COUNT(*) as event_count
|
|
716
|
+
FROM tool_usage_events
|
|
717
|
+
WHERE ${eventFilter.clause}
|
|
718
|
+
GROUP BY mcp_version
|
|
719
|
+
ORDER BY event_count DESC, mcp_version ASC`)
|
|
720
|
+
.all(...eventFilter.args);
|
|
721
|
+
const reasoningStarted = sessionSummary.reasoning_started ?? 0;
|
|
722
|
+
const reasoningCompleted = sessionSummary.reasoning_completed ?? 0;
|
|
723
|
+
const zeroStepSessions = zeroStepRow.length;
|
|
724
|
+
const completedWithMemory = completionEvents.with_memory ?? 0;
|
|
725
|
+
const completedWithoutMemory = completionEvents.without_memory ?? 0;
|
|
726
|
+
const memorySaved = (eventSummary.direct_memory_saved ?? 0) + completedWithMemory;
|
|
727
|
+
const riskFlags = [];
|
|
728
|
+
if (reasoningStarted > 0 && zeroStepSessions / reasoningStarted > 0.25) {
|
|
729
|
+
riskFlags.push("high_zero_step_session_rate");
|
|
730
|
+
}
|
|
731
|
+
if (reasoningCompleted > 0 && completedWithMemory / reasoningCompleted < 0.3) {
|
|
732
|
+
riskFlags.push("low_completion_to_memory_rate");
|
|
733
|
+
}
|
|
734
|
+
if ((eventSummary.memory_searched ?? 0) > 0 && (feedbackSummary.used_count ?? 0) === 0) {
|
|
735
|
+
riskFlags.push("no_positive_feedback_recorded");
|
|
736
|
+
}
|
|
737
|
+
const output = {
|
|
738
|
+
funnel: {
|
|
739
|
+
reasoning_started: reasoningStarted,
|
|
740
|
+
reasoning_completed: reasoningCompleted,
|
|
741
|
+
reasoning_abandoned: sessionSummary.reasoning_abandoned ?? 0,
|
|
742
|
+
zero_step_sessions: zeroStepSessions,
|
|
743
|
+
completed_with_memory: completedWithMemory,
|
|
744
|
+
completed_without_memory: completedWithoutMemory,
|
|
745
|
+
skip_reason_count: skipReasonRows,
|
|
746
|
+
memory_saved: memorySaved,
|
|
747
|
+
memory_searched: eventSummary.memory_searched ?? 0,
|
|
748
|
+
memory_recalled: eventSummary.memory_recalled ?? 0,
|
|
749
|
+
memory_updated: eventSummary.memory_updated ?? 0,
|
|
750
|
+
feedback_used: feedbackSummary.used_count ?? 0,
|
|
751
|
+
},
|
|
752
|
+
agent_breakdown: agentBreakdown,
|
|
753
|
+
version_breakdown: versionBreakdown,
|
|
754
|
+
risk_flags: riskFlags,
|
|
755
|
+
};
|
|
756
|
+
return {
|
|
757
|
+
content: [{ type: "text", text: toLimitedJson(output) }],
|
|
758
|
+
structuredContent: output,
|
|
759
|
+
};
|
|
760
|
+
}));
|
|
761
|
+
server.registerTool("memory_agent_scorecard", {
|
|
762
|
+
title: "Memory Agent Scorecard",
|
|
763
|
+
description: "Compare how different agents use memory and reasoning tools in practice.",
|
|
764
|
+
inputSchema: MemoryAgentScorecardInputSchema.shape,
|
|
765
|
+
annotations: {
|
|
766
|
+
readOnlyHint: true,
|
|
767
|
+
destructiveHint: false,
|
|
768
|
+
idempotentHint: true,
|
|
769
|
+
openWorldHint: false,
|
|
770
|
+
},
|
|
771
|
+
}, withTelemetry({
|
|
772
|
+
database: databaseProvider,
|
|
773
|
+
toolName: "memory_agent_scorecard",
|
|
774
|
+
operationType: "report",
|
|
775
|
+
accessType: "derived",
|
|
776
|
+
buildEvent: (_params, result) => ({
|
|
777
|
+
outputShape: {
|
|
778
|
+
row_count: Array.isArray(extractStructuredContent(result)?.results)
|
|
779
|
+
? (extractStructuredContent(result)?.results).length
|
|
780
|
+
: 0,
|
|
781
|
+
},
|
|
782
|
+
}),
|
|
783
|
+
}, async (params) => {
|
|
784
|
+
const activeDb = await resolveDatabase(database);
|
|
785
|
+
const sessionFilter = buildSessionWhere(params);
|
|
786
|
+
const telemetryFilter = buildTelemetryWhere({
|
|
787
|
+
agent_id: params.agent_id,
|
|
788
|
+
date_from: params.date_from,
|
|
789
|
+
date_to: params.date_to,
|
|
790
|
+
});
|
|
791
|
+
const rows = activeDb
|
|
792
|
+
.prepare(`SELECT DISTINCT COALESCE(agent_id, 'unknown') as agent_id
|
|
793
|
+
FROM tool_usage_events
|
|
794
|
+
WHERE ${telemetryFilter.clause}
|
|
795
|
+
AND operation_type IN ('memory', 'reasoning', 'feedback')
|
|
796
|
+
UNION
|
|
797
|
+
SELECT DISTINCT COALESCE(agent_id, 'unknown') as agent_id
|
|
798
|
+
FROM reasoning_sessions
|
|
799
|
+
WHERE ${sessionFilter.clause}
|
|
800
|
+
LIMIT ?`)
|
|
801
|
+
.all(...telemetryFilter.args, ...sessionFilter.args, params.limit);
|
|
802
|
+
const results = rows.map((row) => {
|
|
803
|
+
const agentId = row.agent_id === "unknown" ? null : row.agent_id;
|
|
804
|
+
const agentSessionFilter = buildSessionWhere({
|
|
805
|
+
agent_id: agentId,
|
|
806
|
+
date_from: params.date_from,
|
|
807
|
+
date_to: params.date_to,
|
|
808
|
+
});
|
|
809
|
+
const agentEventFilter = buildTelemetryWhere({
|
|
810
|
+
agent_id: agentId,
|
|
811
|
+
date_from: params.date_from,
|
|
812
|
+
date_to: params.date_to,
|
|
813
|
+
});
|
|
814
|
+
const sessionSummary = activeDb
|
|
815
|
+
.prepare(`SELECT
|
|
816
|
+
COUNT(*) as started,
|
|
817
|
+
SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed
|
|
818
|
+
FROM reasoning_sessions
|
|
819
|
+
WHERE ${agentSessionFilter.clause}`)
|
|
820
|
+
.get(...agentSessionFilter.args);
|
|
821
|
+
const avgStepsRow = activeDb
|
|
822
|
+
.prepare(`SELECT AVG(step_count) as avg_steps
|
|
823
|
+
FROM (
|
|
824
|
+
SELECT reasoning_sessions.id, COUNT(reasoning_steps.id) as step_count
|
|
825
|
+
FROM reasoning_sessions
|
|
826
|
+
LEFT JOIN reasoning_steps
|
|
827
|
+
ON reasoning_steps.session_id = reasoning_sessions.id
|
|
828
|
+
WHERE ${agentSessionFilter.clause}
|
|
829
|
+
GROUP BY reasoning_sessions.id
|
|
830
|
+
)`)
|
|
831
|
+
.get(...agentSessionFilter.args);
|
|
832
|
+
const eventSummary = activeDb
|
|
833
|
+
.prepare(`SELECT
|
|
834
|
+
COUNT(*) as total_events,
|
|
835
|
+
SUM(CASE WHEN status = 'error' THEN 1 ELSE 0 END) as error_events,
|
|
836
|
+
SUM(CASE WHEN tool_name IN ('memory_search', 'memory_list', 'memory_get') AND status = 'success' THEN 1 ELSE 0 END) as search_events,
|
|
837
|
+
SUM(CASE WHEN tool_name = 'memory_save' AND status = 'success' THEN 1 ELSE 0 END) as direct_save_events,
|
|
838
|
+
SUM(CASE WHEN tool_name = 'reasoning_complete_session' AND status = 'success' AND json_extract(output_shape, '$.memory_id_present') = 1 THEN 1 ELSE 0 END) as completion_memory_events
|
|
839
|
+
FROM tool_usage_events
|
|
840
|
+
WHERE ${agentEventFilter.clause}
|
|
841
|
+
AND operation_type IN ('memory', 'reasoning', 'feedback')`)
|
|
842
|
+
.get(...agentEventFilter.args);
|
|
843
|
+
const feedbackUsed = activeDb
|
|
844
|
+
.prepare(`SELECT COUNT(*) as count
|
|
845
|
+
FROM tool_usage_events
|
|
846
|
+
WHERE ${agentEventFilter.clause}
|
|
847
|
+
AND operation_type = 'feedback'
|
|
848
|
+
AND related_event_id IS NOT NULL
|
|
849
|
+
AND status = 'success'
|
|
850
|
+
AND json_extract(metadata, '$.usefulness') = 'used'`)
|
|
851
|
+
.get(...agentEventFilter.args);
|
|
852
|
+
const sessionsStarted = sessionSummary.started ?? 0;
|
|
853
|
+
const sessionsCompleted = sessionSummary.completed ?? 0;
|
|
854
|
+
const saves = (eventSummary.direct_save_events ?? 0) +
|
|
855
|
+
(eventSummary.completion_memory_events ?? 0);
|
|
856
|
+
const searchRate = sessionsStarted === 0
|
|
857
|
+
? 0
|
|
858
|
+
: (eventSummary.search_events ?? 0) / sessionsStarted;
|
|
859
|
+
const saveRate = sessionsCompleted === 0 ? 0 : saves / sessionsCompleted;
|
|
860
|
+
const reuseRate = saves === 0 ? 0 : feedbackUsed.count / saves;
|
|
861
|
+
const errorRate = eventSummary.total_events === 0
|
|
862
|
+
? 0
|
|
863
|
+
: (eventSummary.error_events ?? 0) / eventSummary.total_events;
|
|
864
|
+
let dominantBehavior = "balanced";
|
|
865
|
+
if (sessionsStarted > 0 && saveRate < 0.3)
|
|
866
|
+
dominantBehavior = "reasoning-heavy";
|
|
867
|
+
if ((eventSummary.search_events ?? 0) === 0 && saves === 0) {
|
|
868
|
+
dominantBehavior = "memory-light";
|
|
869
|
+
}
|
|
870
|
+
if (searchRate > 1 && feedbackUsed.count === 0) {
|
|
871
|
+
dominantBehavior = "search-only";
|
|
872
|
+
}
|
|
873
|
+
if (saves > sessionsCompleted && reuseRate < 0.2) {
|
|
874
|
+
dominantBehavior = "noisy-writer";
|
|
875
|
+
}
|
|
876
|
+
if (errorRate > 0.2)
|
|
877
|
+
dominantBehavior = "error-prone";
|
|
878
|
+
const recommendationMap = {
|
|
879
|
+
balanced: "Current usage is balanced; keep validating save quality with feedback.",
|
|
880
|
+
"reasoning-heavy": "Persist more durable conclusions after completed sessions.",
|
|
881
|
+
"memory-light": "Use memory_search or memory_save when prior context or durable outcomes matter.",
|
|
882
|
+
"search-only": "Record feedback on recalled memories to measure usefulness.",
|
|
883
|
+
"noisy-writer": "Tighten save criteria and favor durable summaries over raw notes.",
|
|
884
|
+
"error-prone": "Audit failing tool calls and validate inputs before writes.",
|
|
885
|
+
};
|
|
886
|
+
return {
|
|
887
|
+
agent_id: row.agent_id,
|
|
888
|
+
sessions_started: sessionsStarted,
|
|
889
|
+
sessions_completed: sessionsCompleted,
|
|
890
|
+
avg_steps_per_session: avgStepsRow.avg_steps ?? 0,
|
|
891
|
+
save_rate: saveRate,
|
|
892
|
+
search_rate: searchRate,
|
|
893
|
+
reuse_rate: reuseRate,
|
|
894
|
+
error_rate: errorRate,
|
|
895
|
+
dominant_behavior: dominantBehavior,
|
|
896
|
+
recommendations: recommendationMap[dominantBehavior],
|
|
897
|
+
};
|
|
898
|
+
});
|
|
899
|
+
const output = { results };
|
|
900
|
+
return {
|
|
901
|
+
content: [{ type: "text", text: toLimitedJson(output) }],
|
|
902
|
+
structuredContent: output,
|
|
903
|
+
};
|
|
904
|
+
}));
|
|
905
|
+
server.registerTool("memory_record_usage_feedback", {
|
|
906
|
+
title: "Record Memory Usage Feedback",
|
|
907
|
+
description: "Record whether a recalled memory was used, ignored, stale, or unsafe to use.",
|
|
908
|
+
inputSchema: MemoryRecordUsageFeedbackInputSchema.shape,
|
|
909
|
+
annotations: {
|
|
910
|
+
readOnlyHint: false,
|
|
911
|
+
destructiveHint: false,
|
|
912
|
+
idempotentHint: false,
|
|
913
|
+
openWorldHint: false,
|
|
914
|
+
},
|
|
915
|
+
}, withTelemetry({
|
|
916
|
+
database: databaseProvider,
|
|
917
|
+
toolName: "memory_record_usage_feedback",
|
|
918
|
+
operationType: "feedback",
|
|
919
|
+
accessType: "write",
|
|
920
|
+
buildEvent: (params, result) => ({
|
|
921
|
+
agentId: params.agent_id ?? null,
|
|
922
|
+
memoryId: params.memory_id,
|
|
923
|
+
relatedEventId: params.event_id ?? null,
|
|
924
|
+
inputShape: {
|
|
925
|
+
has_event_id: params.event_id !== undefined,
|
|
926
|
+
usefulness: params.usefulness,
|
|
927
|
+
reason_length: params.reason?.length ?? 0,
|
|
928
|
+
},
|
|
929
|
+
outputShape: {
|
|
930
|
+
recorded: result.isError !== true,
|
|
931
|
+
event_id: typeof result.structuredContent?.event_id === "string"
|
|
932
|
+
? result.structuredContent.event_id
|
|
933
|
+
: null,
|
|
934
|
+
},
|
|
935
|
+
metadata: {
|
|
936
|
+
usefulness: params.usefulness,
|
|
937
|
+
reason: params.reason ?? null,
|
|
938
|
+
},
|
|
939
|
+
}),
|
|
940
|
+
}, async (params) => {
|
|
941
|
+
if (!telemetryPersistenceEnabled()) {
|
|
942
|
+
return {
|
|
943
|
+
content: [
|
|
944
|
+
{
|
|
945
|
+
type: "text",
|
|
946
|
+
text: "Error: Telemetry persistence is disabled; memory feedback cannot be recorded.",
|
|
947
|
+
},
|
|
948
|
+
],
|
|
949
|
+
isError: true,
|
|
950
|
+
};
|
|
951
|
+
}
|
|
952
|
+
const activeDb = await resolveDatabase(database);
|
|
953
|
+
const existing = activeDb
|
|
954
|
+
.prepare(`SELECT id FROM memories WHERE id = ?`)
|
|
955
|
+
.get(params.memory_id);
|
|
956
|
+
if (!existing) {
|
|
957
|
+
return {
|
|
958
|
+
content: [
|
|
959
|
+
{
|
|
960
|
+
type: "text",
|
|
961
|
+
text: `Error: Memory '${params.memory_id}' not found.`,
|
|
962
|
+
},
|
|
963
|
+
],
|
|
964
|
+
isError: true,
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
if (params.event_id) {
|
|
968
|
+
const relatedEvent = activeDb
|
|
969
|
+
.prepare(`SELECT id
|
|
970
|
+
FROM tool_usage_events
|
|
971
|
+
WHERE id = ?
|
|
972
|
+
AND tool_name = 'memory_get'
|
|
973
|
+
AND memory_id = ?`)
|
|
974
|
+
.get(params.event_id, params.memory_id);
|
|
975
|
+
if (!relatedEvent) {
|
|
976
|
+
return {
|
|
977
|
+
content: [
|
|
978
|
+
{
|
|
979
|
+
type: "text",
|
|
980
|
+
text: `Error: Related event '${params.event_id}' cannot be verified for memory '${params.memory_id}'. Use a matching memory_get event.`,
|
|
981
|
+
},
|
|
982
|
+
],
|
|
983
|
+
isError: true,
|
|
984
|
+
};
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
const output = {
|
|
988
|
+
event_id: null,
|
|
989
|
+
memory_id: params.memory_id,
|
|
990
|
+
usefulness: params.usefulness,
|
|
991
|
+
};
|
|
992
|
+
return {
|
|
993
|
+
content: [{ type: "text", text: toLimitedJson(output) }],
|
|
994
|
+
structuredContent: output,
|
|
995
|
+
};
|
|
996
|
+
}));
|
|
997
|
+
}
|
|
998
|
+
//# sourceMappingURL=memory.js.map
|