@nhatnguyen9317/memory-mcp-server 1.2.0 → 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.
@@ -3,11 +3,13 @@ import { migration0001Initial } from "./0001_initial.js";
3
3
  import { migration0002ReasoningStepMarks } from "./0002_reasoning_step_marks.js";
4
4
  import { migration0003ReasoningStepsFts } from "./0003_reasoning_steps_fts.js";
5
5
  import { migration0004ToolUsageEvents } from "./0004_tool_usage_events.js";
6
+ import { migration0005MemoryWorkspace } from "./0005_memory_workspace.js";
6
7
  const migrations = [
7
8
  migration0001Initial,
8
9
  migration0002ReasoningStepMarks,
9
10
  migration0003ReasoningStepsFts,
10
11
  migration0004ToolUsageEvents,
12
+ migration0005MemoryWorkspace,
11
13
  ];
12
14
  export function runMigrations(db) {
13
15
  db.exec(`
@@ -13,9 +13,28 @@ export const ReasoningStartSessionInputSchema = z
13
13
  .describe("Optional identifier for the agent/persona running this session."),
14
14
  })
15
15
  .strict();
16
+ export const ReasoningStepEntrySchema = z
17
+ .object({
18
+ thought: z
19
+ .string()
20
+ .max(4000)
21
+ .optional()
22
+ .describe("The agent's reasoning/thinking at this step."),
23
+ action: z
24
+ .string()
25
+ .max(2000)
26
+ .optional()
27
+ .describe("The action taken at this step, if any (e.g. a tool call description)."),
28
+ observation: z
29
+ .string()
30
+ .max(4000)
31
+ .optional()
32
+ .describe("The result/observation from the action, if any."),
33
+ })
34
+ .strict();
16
35
  // NOTE: kept as a plain ZodObject (no .refine()) so `.shape` stays available
17
- // for registerTool's inputSchema. The "at least one field" rule is enforced
18
- // in the tool handler instead.
36
+ // for registerTool's inputSchema. The "at least one field" and "single vs
37
+ // batch" rules are enforced in the tool handler instead.
19
38
  export const ReasoningAddStepInputSchema = z
20
39
  .object({
21
40
  session_id: z
@@ -37,6 +56,12 @@ export const ReasoningAddStepInputSchema = z
37
56
  .max(4000)
38
57
  .optional()
39
58
  .describe("The result/observation from the action, if any."),
59
+ steps: z
60
+ .array(ReasoningStepEntrySchema)
61
+ .min(1)
62
+ .max(20)
63
+ .optional()
64
+ .describe("Batch mode: log several steps in one call (each entry needs at least one of thought/action/observation). Use INSTEAD of the top-level thought/action/observation fields, e.g. to record the trace of work you just finished without one call per step."),
40
65
  })
41
66
  .strict();
42
67
  export const ReasoningGetTraceInputSchema = z
@@ -1,4 +1,5 @@
1
1
  import { MemoryAdoptionReportInputSchema, MemoryAgentScorecardInputSchema, MemoryDeleteInputSchema, MemoryGetInputSchema, MemoryListInputSchema, MemoryRecordUsageFeedbackInputSchema, MemorySaveInputSchema, MemorySearchInputSchema, MemoryUpdateInputSchema, MemoryUsageReportInputSchema, } from "../schemas/memory.js";
2
+ import { getWorkspace, isTelemetryEnabled } from "../constants.js";
2
3
  import { newId, nowIso, parseJsonArray, parseJsonObject, toFtsQuery, toLimitedJson, } from "../utils.js";
3
4
  import { withTelemetry, } from "./telemetry.js";
4
5
  function rowToRecord(row) {
@@ -27,6 +28,18 @@ function tagsFilterClauses(tags) {
27
28
  function extractStructuredContent(result) {
28
29
  return result.structuredContent ?? null;
29
30
  }
31
+ /**
32
+ * Reports aggregate tool_usage_events; with telemetry off only successful
33
+ * usage-feedback rows exist, so say so in the output itself — an agent
34
+ * reading only the JSON must not mistake empty funnels for real zeros.
35
+ */
36
+ function telemetryOffNote() {
37
+ return isTelemetryEnabled()
38
+ ? {}
39
+ : {
40
+ telemetry_note: "MEMORY_TELEMETRY is off (the default): only successful usage-feedback events are recorded, so counts other than feedback are incomplete. Set MEMORY_TELEMETRY=on for full data.",
41
+ };
42
+ }
30
43
  function resultCount(result) {
31
44
  const structured = extractStructuredContent(result);
32
45
  if (structured?.total_returned !== undefined) {
@@ -46,9 +59,6 @@ function returnedMemoryIds(result) {
46
59
  .map((row) => String(row.id))
47
60
  .filter((id) => id !== "undefined");
48
61
  }
49
- function telemetryPersistenceEnabled() {
50
- return process.env.MEMORY_TELEMETRY !== "off";
51
- }
52
62
  function normalizeTextDate(value) {
53
63
  if (!value)
54
64
  return undefined;
@@ -101,18 +111,21 @@ function buildTelemetryWhere(params) {
101
111
  }
102
112
  return { clause: conditions.join(" AND "), args };
103
113
  }
104
- function buildSessionWhere(params) {
114
+ function buildSessionWhere(params,
115
+ // Set when the query joins reasoning_steps: both tables have created_at,
116
+ // so unqualified column names are ambiguous.
117
+ columnPrefix = "") {
105
118
  const conditions = ["1=1"];
106
119
  const args = [];
107
- appendAgentFilter(conditions, args, "agent_id", params.agent_id);
120
+ appendAgentFilter(conditions, args, `${columnPrefix}agent_id`, params.agent_id);
108
121
  const dateFrom = normalizeDateBoundary(params.date_from, "start");
109
122
  if (dateFrom) {
110
- conditions.push("created_at >= ?");
123
+ conditions.push(`${columnPrefix}created_at >= ?`);
111
124
  args.push(dateFrom);
112
125
  }
113
126
  const dateTo = normalizeDateBoundary(params.date_to, "end");
114
127
  if (dateTo) {
115
- conditions.push("created_at <= ?");
128
+ conditions.push(`${columnPrefix}created_at <= ?`);
116
129
  args.push(dateTo);
117
130
  }
118
131
  return { clause: conditions.join(" AND "), args };
@@ -128,7 +141,7 @@ export function registerMemoryTools(server, database) {
128
141
  const databaseProvider = () => resolveDatabase(database);
129
142
  server.registerTool("memory_save", {
130
143
  title: "Save Memory",
131
- description: "Persist a piece of long-term memory so it can be recalled in future sessions.",
144
+ description: "Persist a piece of long-term memory so it can be recalled in future sessions. Tags describe topics ('sqlite', 'auth', 'perf'), not locations — do not put workspace or project names in tags; the server records the workspace automatically.",
132
145
  inputSchema: MemorySaveInputSchema.shape,
133
146
  annotations: {
134
147
  readOnlyHint: false,
@@ -166,8 +179,8 @@ export function registerMemoryTools(server, database) {
166
179
  const id = newId("mem");
167
180
  const ts = nowIso();
168
181
  activeDb
169
- .prepare(`INSERT INTO memories (id, type, content, tags, agent_id, importance, metadata, created_at, updated_at)
170
- VALUES (@id, @type, @content, @tags, @agent_id, @importance, @metadata, @created_at, @updated_at)`)
182
+ .prepare(`INSERT INTO memories (id, type, content, tags, agent_id, importance, metadata, workspace, created_at, updated_at)
183
+ VALUES (@id, @type, @content, @tags, @agent_id, @importance, @metadata, @workspace, @created_at, @updated_at)`)
171
184
  .run({
172
185
  id,
173
186
  type: params.type,
@@ -176,6 +189,7 @@ export function registerMemoryTools(server, database) {
176
189
  agent_id: params.agent_id ?? null,
177
190
  importance: params.importance,
178
191
  metadata: params.metadata ? JSON.stringify(params.metadata) : null,
192
+ workspace: getWorkspace(),
179
193
  created_at: ts,
180
194
  updated_at: ts,
181
195
  });
@@ -226,9 +240,7 @@ export function registerMemoryTools(server, database) {
226
240
  }, async (params) => {
227
241
  const activeDb = await resolveDatabase(database);
228
242
  const { clause: tagClause, params: tagParams } = tagsFilterClauses(params.tags);
229
- const conditions = [
230
- "m.rowid IN (SELECT rowid FROM memories_fts WHERE memories_fts MATCH ?)",
231
- ];
243
+ const conditions = [];
232
244
  const sqlParams = [toFtsQuery(params.query)];
233
245
  if (params.type) {
234
246
  conditions.push("m.type = ?");
@@ -238,10 +250,18 @@ export function registerMemoryTools(server, database) {
238
250
  conditions.push("m.agent_id = ?");
239
251
  sqlParams.push(params.agent_id);
240
252
  }
253
+ if (tagClause) {
254
+ // tagClause is " AND <clauses>"; strip the prefix to compose here.
255
+ conditions.push(tagClause.slice(" AND ".length));
256
+ }
257
+ // rank (bm25) sorts best text match first; importance/recency break ties.
241
258
  const rows = activeDb
242
259
  .prepare(`SELECT m.* FROM memories m
243
- WHERE ${conditions.join(" AND ")}${tagClause}
244
- ORDER BY m.importance DESC, m.updated_at DESC
260
+ JOIN (
261
+ SELECT rowid, rank FROM memories_fts WHERE memories_fts MATCH ?
262
+ ) f ON m.rowid = f.rowid
263
+ ${conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : ""}
264
+ ORDER BY f.rank ASC, m.importance DESC, m.updated_at DESC
245
265
  LIMIT ? OFFSET ?`)
246
266
  .all(...sqlParams, ...tagParams, params.limit, params.offset);
247
267
  if (rows.length === 0) {
@@ -536,7 +556,7 @@ export function registerMemoryTools(server, database) {
536
556
  }));
537
557
  server.registerTool("memory_usage_report", {
538
558
  title: "Memory Usage Report",
539
- description: "Aggregate tool usage events by tool, agent, client, version, operation type, status, or day.",
559
+ description: "Aggregate tool usage events by tool, agent, client, version, operation type, status, or day. With MEMORY_TELEMETRY off (the default) only usage-feedback events exist, so most groupings are empty; full aggregates need MEMORY_TELEMETRY=on.",
540
560
  inputSchema: MemoryUsageReportInputSchema.shape,
541
561
  annotations: {
542
562
  readOnlyHint: true,
@@ -602,6 +622,7 @@ export function registerMemoryTools(server, database) {
602
622
  const successEvents = summaryRow.success_events ?? 0;
603
623
  const errorEvents = summaryRow.error_events ?? 0;
604
624
  const output = {
625
+ ...telemetryOffNote(),
605
626
  summary: {
606
627
  total_events: totalEvents,
607
628
  success_events: successEvents,
@@ -623,7 +644,7 @@ export function registerMemoryTools(server, database) {
623
644
  }));
624
645
  server.registerTool("memory_adoption_report", {
625
646
  title: "Memory Adoption Report",
626
- description: "Summarize reasoning and memory adoption behavior using telemetry plus core session tables.",
647
+ description: "Summarize reasoning and memory adoption behavior using telemetry plus core session tables. With MEMORY_TELEMETRY off (the default) only usage-feedback events and session tables have data, so funnel counts and ratios that need recall/search events require MEMORY_TELEMETRY=on.",
627
648
  inputSchema: MemoryAdoptionReportInputSchema.shape,
628
649
  annotations: {
629
650
  readOnlyHint: true,
@@ -655,15 +676,16 @@ export function registerMemoryTools(server, database) {
655
676
  FROM reasoning_sessions
656
677
  WHERE ${sessionFilter.clause}`)
657
678
  .get(...sessionFilter.args);
679
+ const joinedSessionFilter = buildSessionWhere(params, "reasoning_sessions.");
658
680
  const zeroStepRow = activeDb
659
681
  .prepare(`SELECT COUNT(*) as zero_step_sessions
660
682
  FROM reasoning_sessions
661
683
  LEFT JOIN reasoning_steps
662
684
  ON reasoning_steps.session_id = reasoning_sessions.id
663
- WHERE ${sessionFilter.clause}
685
+ WHERE ${joinedSessionFilter.clause}
664
686
  GROUP BY reasoning_sessions.id
665
687
  HAVING COUNT(reasoning_steps.id) = 0`)
666
- .all(...sessionFilter.args);
688
+ .all(...joinedSessionFilter.args);
667
689
  const completionEvents = activeDb
668
690
  .prepare(`SELECT
669
691
  COUNT(*) as total,
@@ -748,6 +770,7 @@ export function registerMemoryTools(server, database) {
748
770
  riskFlags.push("no_positive_feedback_recorded");
749
771
  }
750
772
  const output = {
773
+ ...telemetryOffNote(),
751
774
  funnel: {
752
775
  reasoning_started: reasoningStarted,
753
776
  reasoning_completed: reasoningCompleted,
@@ -773,7 +796,7 @@ export function registerMemoryTools(server, database) {
773
796
  }));
774
797
  server.registerTool("memory_agent_scorecard", {
775
798
  title: "Memory Agent Scorecard",
776
- description: "Compare how different agents use memory and reasoning tools in practice.",
799
+ description: "Compare how different agents use memory and reasoning tools in practice. With MEMORY_TELEMETRY off (the default) only usage-feedback events are recorded, so per-agent activity counts require MEMORY_TELEMETRY=on.",
777
800
  inputSchema: MemoryAgentScorecardInputSchema.shape,
778
801
  annotations: {
779
802
  readOnlyHint: true,
@@ -814,11 +837,13 @@ export function registerMemoryTools(server, database) {
814
837
  .all(...telemetryFilter.args, ...sessionFilter.args, params.limit);
815
838
  const results = rows.map((row) => {
816
839
  const agentId = row.agent_id === "unknown" ? null : row.agent_id;
840
+ // Qualified so the same filter works in the reasoning_steps JOIN
841
+ // below; the prefix is harmless in the unjoined query.
817
842
  const agentSessionFilter = buildSessionWhere({
818
843
  agent_id: agentId,
819
844
  date_from: params.date_from,
820
845
  date_to: params.date_to,
821
- });
846
+ }, "reasoning_sessions.");
822
847
  const agentEventFilter = buildTelemetryWhere({
823
848
  agent_id: agentId,
824
849
  date_from: params.date_from,
@@ -908,7 +933,7 @@ export function registerMemoryTools(server, database) {
908
933
  recommendations: recommendationMap[dominantBehavior],
909
934
  };
910
935
  });
911
- const output = { results };
936
+ const output = { ...telemetryOffNote(), results };
912
937
  return {
913
938
  content: [{ type: "text", text: toLimitedJson(output) }],
914
939
  structuredContent: output,
@@ -916,7 +941,7 @@ export function registerMemoryTools(server, database) {
916
941
  }));
917
942
  server.registerTool("memory_record_usage_feedback", {
918
943
  title: "Record Memory Usage Feedback",
919
- description: "Record whether a recalled memory was used, ignored, stale, or unsafe to use.",
944
+ description: "Record whether a recalled memory was used, ignored, stale, or unsafe to use. Feedback is a first-party learning signal for recall quality and is always persisted locally, regardless of the MEMORY_TELEMETRY setting.",
920
945
  inputSchema: MemoryRecordUsageFeedbackInputSchema.shape,
921
946
  annotations: {
922
947
  readOnlyHint: false,
@@ -939,7 +964,7 @@ export function registerMemoryTools(server, database) {
939
964
  reason_length: params.reason?.length ?? 0,
940
965
  },
941
966
  outputShape: {
942
- recorded: result.isError !== true,
967
+ recorded: result.structuredContent?.recorded === true,
943
968
  },
944
969
  metadata: {
945
970
  usefulness: params.usefulness,
@@ -947,17 +972,6 @@ export function registerMemoryTools(server, database) {
947
972
  },
948
973
  }),
949
974
  }, async (params) => {
950
- if (!telemetryPersistenceEnabled()) {
951
- return {
952
- content: [
953
- {
954
- type: "text",
955
- text: "Error: Telemetry persistence is disabled; memory feedback cannot be recorded.",
956
- },
957
- ],
958
- isError: true,
959
- };
960
- }
961
975
  const activeDb = await resolveDatabase(database);
962
976
  const existing = activeDb
963
977
  .prepare(`SELECT id FROM memories WHERE id = ?`)
@@ -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