@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.
@@ -0,0 +1,1001 @@
1
+ import { ReasoningAddStepInputSchema, ReasoningCompleteSessionInputSchema, ReasoningGetSessionOutlineInputSchema, ReasoningGetTraceInputSchema, ReasoningListMilestonesInputSchema, ReasoningListSessionsInputSchema, ReasoningMarkStepInputSchema, ReasoningSearchStepsInputSchema, ReasoningStartSessionInputSchema, } from "../schemas/reasoning.js";
2
+ import { handleToolError, newId, nowIso, toFtsQuery, toLimitedJson, } from "../utils.js";
3
+ import { withTelemetry } from "./telemetry.js";
4
+ function sessionRowToRecord(row, stepCount) {
5
+ return {
6
+ id: row.id,
7
+ title: row.title,
8
+ agent_id: row.agent_id,
9
+ status: row.status,
10
+ conclusion: row.conclusion,
11
+ created_at: row.created_at,
12
+ updated_at: row.updated_at,
13
+ step_count: stepCount,
14
+ };
15
+ }
16
+ function getStepCount(database, sessionId) {
17
+ const row = database
18
+ .prepare(`SELECT COUNT(*) as c FROM reasoning_steps WHERE session_id = ?`)
19
+ .get(sessionId);
20
+ return row.c;
21
+ }
22
+ function getNextStepNumber(database, sessionId) {
23
+ const row = database
24
+ .prepare(`SELECT COALESCE(MAX(step_number), 0) as max_step
25
+ FROM reasoning_steps
26
+ WHERE session_id = ?`)
27
+ .get(sessionId);
28
+ return row.max_step + 1;
29
+ }
30
+ function shouldAutoSaveMemory(params, stepCount) {
31
+ if (params.memory_mode === "never")
32
+ return false;
33
+ if (params.save_as_memory || params.memory_mode === "always")
34
+ return true;
35
+ return false;
36
+ }
37
+ function buildNotSavedReason(params, stepCount) {
38
+ if (params.memory_mode === "never") {
39
+ return params.not_saved_reason ?? "Skipped by caller request.";
40
+ }
41
+ if (params.status !== "completed") {
42
+ return "Session did not complete successfully.";
43
+ }
44
+ if (stepCount === 0) {
45
+ return "Session has no reasoning steps; skipping durable memory to avoid empty summaries.";
46
+ }
47
+ return null;
48
+ }
49
+ function runInTransaction(database, work) {
50
+ database.exec("BEGIN IMMEDIATE");
51
+ try {
52
+ const result = work();
53
+ database.exec("COMMIT");
54
+ return result;
55
+ }
56
+ catch (error) {
57
+ try {
58
+ database.exec("ROLLBACK");
59
+ }
60
+ catch {
61
+ // Ignore rollback errors so the original failure is preserved.
62
+ }
63
+ throw error;
64
+ }
65
+ }
66
+ function compactSnippetText(text) {
67
+ const compact = text.replace(/\s+/g, " ").trim();
68
+ return compact.length > 160 ? `${compact.slice(0, 157)}...` : compact;
69
+ }
70
+ function queryTokens(query) {
71
+ return query
72
+ .trim()
73
+ .split(/\s+/)
74
+ .filter(Boolean)
75
+ .map((token) => token.toLowerCase());
76
+ }
77
+ function buildReasoningSnippet(step, query) {
78
+ const fields = [step.thought, step.action, step.observation];
79
+ const tokens = queryTokens(query);
80
+ if (tokens.length > 0) {
81
+ const matchingField = fields.find((field) => {
82
+ if (!field)
83
+ return false;
84
+ const lower = field.toLowerCase();
85
+ return tokens.some((token) => lower.includes(token));
86
+ });
87
+ if (matchingField)
88
+ return compactSnippetText(matchingField);
89
+ }
90
+ const source = step.thought ?? step.action ?? step.observation ?? "";
91
+ return compactSnippetText(source);
92
+ }
93
+ function stepToOutlineRecord(step, mark_type = null, note = null) {
94
+ const { id, session_id, step_number, thought, action, observation, created_at, } = step;
95
+ return {
96
+ id,
97
+ session_id,
98
+ step_number,
99
+ thought,
100
+ action,
101
+ observation,
102
+ created_at,
103
+ mark_type,
104
+ note,
105
+ };
106
+ }
107
+ function selectFallbackOutlineSteps(steps) {
108
+ if (steps.length <= 2)
109
+ return steps;
110
+ const middleIndex = Math.floor((steps.length - 1) / 2);
111
+ return [steps[0], steps[middleIndex], steps[steps.length - 1]];
112
+ }
113
+ let defaultDatabasePromise = null;
114
+ async function resolveDatabase(database) {
115
+ if (database)
116
+ return database;
117
+ defaultDatabasePromise ??= import("../db.js").then((module) => module.db);
118
+ return defaultDatabasePromise;
119
+ }
120
+ export function registerReasoningTools(server, database) {
121
+ const databaseProvider = () => resolveDatabase(database);
122
+ server.registerTool("reasoning_start_session", {
123
+ title: "Start Reasoning Session",
124
+ description: `Start a new reasoning session to record a multi-step chain of thought for a task or question. Call this once at the start of a non-trivial task, then log each step with reasoning_add_step, and finish with reasoning_complete_session.
125
+
126
+ Args:
127
+ - title (string, required): Short description of the task/question, e.g. "Diagnose flaky checkout test".
128
+ - agent_id (string, optional): Identifier for the agent/persona running this session.
129
+
130
+ Returns: JSON with the new session's id, which must be passed to reasoning_add_step and reasoning_complete_session.
131
+
132
+ Examples:
133
+ - Use when: starting to debug a complex issue, plan a multi-step task, or work through a decision with tradeoffs.
134
+ - Don't use when: the answer is a single simple lookup (just use memory_save/memory_search directly).`,
135
+ inputSchema: ReasoningStartSessionInputSchema.shape,
136
+ annotations: {
137
+ readOnlyHint: false,
138
+ destructiveHint: false,
139
+ idempotentHint: false,
140
+ openWorldHint: false,
141
+ },
142
+ }, withTelemetry({
143
+ database: databaseProvider,
144
+ toolName: "reasoning_start_session",
145
+ operationType: "reasoning",
146
+ accessType: "write",
147
+ buildEvent: (params, result) => ({
148
+ agentId: params.agent_id ?? null,
149
+ sessionId: typeof result.structuredContent?.session_id === "string"
150
+ ? result.structuredContent.session_id
151
+ : null,
152
+ outputShape: {
153
+ session_id: result.structuredContent?.session_id ?? null,
154
+ },
155
+ }),
156
+ }, async (params) => {
157
+ try {
158
+ const activeDb = await resolveDatabase(database);
159
+ const id = newId("sess");
160
+ const ts = nowIso();
161
+ activeDb
162
+ .prepare(`INSERT INTO reasoning_sessions (id, title, agent_id, status, conclusion, created_at, updated_at)
163
+ VALUES (?, ?, ?, 'in_progress', NULL, ?, ?)`)
164
+ .run(id, params.title, params.agent_id ?? null, ts, ts);
165
+ const output = {
166
+ session_id: id,
167
+ title: params.title,
168
+ status: "in_progress",
169
+ };
170
+ return {
171
+ content: [
172
+ {
173
+ type: "text",
174
+ text: `Reasoning session started with id ${id}.\n\n${toLimitedJson(output)}`,
175
+ },
176
+ ],
177
+ structuredContent: output,
178
+ };
179
+ }
180
+ catch (error) {
181
+ return {
182
+ content: [{ type: "text", text: handleToolError(error) }],
183
+ isError: true,
184
+ };
185
+ }
186
+ }));
187
+ server.registerTool("reasoning_add_step", {
188
+ 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. Call this repeatedly as the agent works through a task.
190
+
191
+ Args:
192
+ - session_id (string, required): Id from reasoning_start_session.
193
+ - thought (string, optional): The reasoning/thinking at this step.
194
+ - action (string, optional): The action taken, if any.
195
+ - observation (string, optional): The result observed, if any.
196
+ (At least one of thought/action/observation is required.)
197
+
198
+ Returns: JSON with the new step's id and step_number.
199
+
200
+ Error Handling:
201
+ - Returns an error if session_id does not exist (call reasoning_start_session first, or reasoning_list_sessions to find the right id).
202
+ - Returns an error if the session is already 'completed' or 'abandoned'.`,
203
+ inputSchema: ReasoningAddStepInputSchema.shape,
204
+ annotations: {
205
+ readOnlyHint: false,
206
+ destructiveHint: false,
207
+ idempotentHint: false,
208
+ openWorldHint: false,
209
+ },
210
+ }, withTelemetry({
211
+ database: databaseProvider,
212
+ toolName: "reasoning_add_step",
213
+ operationType: "reasoning",
214
+ accessType: "write",
215
+ buildEvent: async (params, result, activeDb) => {
216
+ const session = activeDb
217
+ .prepare(`SELECT agent_id FROM reasoning_sessions WHERE id = ?`)
218
+ .get(params.session_id);
219
+ return {
220
+ agentId: session?.agent_id ?? null,
221
+ sessionId: params.session_id,
222
+ stepId: typeof result.structuredContent?.step_id === "string"
223
+ ? result.structuredContent.step_id
224
+ : null,
225
+ inputShape: {
226
+ thought_present: params.thought !== undefined,
227
+ action_present: params.action !== undefined,
228
+ observation_present: params.observation !== undefined,
229
+ thought_length: params.thought?.length ?? 0,
230
+ action_length: params.action?.length ?? 0,
231
+ observation_length: params.observation?.length ?? 0,
232
+ },
233
+ outputShape: {
234
+ step_number: result.structuredContent?.step_number ?? null,
235
+ },
236
+ };
237
+ },
238
+ }, async (params) => {
239
+ try {
240
+ const activeDb = await resolveDatabase(database);
241
+ if (params.thought === undefined &&
242
+ params.action === undefined &&
243
+ params.observation === undefined) {
244
+ return {
245
+ content: [
246
+ {
247
+ type: "text",
248
+ text: "Error: At least one of thought, action, or observation must be provided.",
249
+ },
250
+ ],
251
+ isError: true,
252
+ };
253
+ }
254
+ const session = activeDb
255
+ .prepare(`SELECT * FROM reasoning_sessions WHERE id = ?`)
256
+ .get(params.session_id);
257
+ if (!session) {
258
+ return {
259
+ content: [
260
+ {
261
+ type: "text",
262
+ text: `Error: Session '${params.session_id}' not found. Use reasoning_start_session to create one, or reasoning_list_sessions to find existing ids.`,
263
+ },
264
+ ],
265
+ isError: true,
266
+ };
267
+ }
268
+ if (session.status !== "in_progress") {
269
+ return {
270
+ content: [
271
+ {
272
+ type: "text",
273
+ text: `Error: Session '${params.session_id}' is already '${session.status}' and cannot accept new steps.`,
274
+ },
275
+ ],
276
+ isError: true,
277
+ };
278
+ }
279
+ const output = runInTransaction(activeDb, () => {
280
+ const lockedSession = activeDb
281
+ .prepare(`SELECT * FROM reasoning_sessions WHERE id = ?`)
282
+ .get(params.session_id);
283
+ if (!lockedSession) {
284
+ throw new Error(`Session '${params.session_id}' not found. Use reasoning_start_session to create one, or reasoning_list_sessions to find existing ids.`);
285
+ }
286
+ if (lockedSession.status !== "in_progress") {
287
+ throw new Error(`Session '${params.session_id}' is already '${lockedSession.status}' and cannot accept new steps.`);
288
+ }
289
+ const nextStepNumber = getNextStepNumber(activeDb, params.session_id);
290
+ const id = newId("step");
291
+ const ts = nowIso();
292
+ activeDb
293
+ .prepare(`INSERT INTO reasoning_steps (id, session_id, step_number, thought, action, observation, created_at)
294
+ VALUES (?, ?, ?, ?, ?, ?, ?)`)
295
+ .run(id, params.session_id, nextStepNumber, params.thought ?? null, params.action ?? null, params.observation ?? null, ts);
296
+ activeDb
297
+ .prepare(`UPDATE reasoning_sessions SET updated_at = ? WHERE id = ?`)
298
+ .run(ts, params.session_id);
299
+ return {
300
+ step_id: id,
301
+ session_id: params.session_id,
302
+ step_number: nextStepNumber,
303
+ };
304
+ });
305
+ return {
306
+ content: [{ type: "text", text: toLimitedJson(output) }],
307
+ structuredContent: output,
308
+ };
309
+ }
310
+ catch (error) {
311
+ if (error instanceof Error) {
312
+ return {
313
+ content: [{ type: "text", text: `Error: ${error.message}` }],
314
+ isError: true,
315
+ };
316
+ }
317
+ return {
318
+ content: [{ type: "text", text: handleToolError(error) }],
319
+ isError: true,
320
+ };
321
+ }
322
+ }));
323
+ server.registerTool("reasoning_get_trace", {
324
+ title: "Get Reasoning Trace",
325
+ description: `Retrieve the full ordered trace of steps for a reasoning session, plus its status and conclusion (if completed).
326
+
327
+ Args:
328
+ - session_id (string, required): The session id.
329
+
330
+ Returns: JSON with { session: {...}, steps: [{step_number, thought, action, observation, created_at}, ...] }.
331
+
332
+ Error Handling:
333
+ - Returns "Error: Session '<id>' not found" if the id does not exist.`,
334
+ inputSchema: ReasoningGetTraceInputSchema.shape,
335
+ annotations: {
336
+ readOnlyHint: true,
337
+ destructiveHint: false,
338
+ idempotentHint: true,
339
+ openWorldHint: false,
340
+ },
341
+ }, withTelemetry({
342
+ database: databaseProvider,
343
+ toolName: "reasoning_get_trace",
344
+ operationType: "reasoning",
345
+ accessType: "read",
346
+ buildEvent: (params, result) => ({
347
+ sessionId: params.session_id,
348
+ outputShape: {
349
+ step_count: Array.isArray(result.structuredContent?.steps)
350
+ ? result.structuredContent.steps.length
351
+ : 0,
352
+ },
353
+ }),
354
+ }, async (params) => {
355
+ try {
356
+ const activeDb = await resolveDatabase(database);
357
+ const sessionRow = activeDb
358
+ .prepare(`SELECT * FROM reasoning_sessions WHERE id = ?`)
359
+ .get(params.session_id);
360
+ if (!sessionRow) {
361
+ return {
362
+ content: [
363
+ {
364
+ type: "text",
365
+ text: `Error: Session '${params.session_id}' not found.`,
366
+ },
367
+ ],
368
+ isError: true,
369
+ };
370
+ }
371
+ const stepRows = activeDb
372
+ .prepare(`SELECT * FROM reasoning_steps WHERE session_id = ? ORDER BY step_number ASC`)
373
+ .all(params.session_id);
374
+ const steps = stepRows.map((row) => ({
375
+ id: row.id,
376
+ session_id: row.session_id,
377
+ step_number: row.step_number,
378
+ thought: row.thought,
379
+ action: row.action,
380
+ observation: row.observation,
381
+ created_at: row.created_at,
382
+ }));
383
+ const session = sessionRowToRecord(sessionRow, steps.length);
384
+ const output = { session, steps };
385
+ return {
386
+ content: [{ type: "text", text: toLimitedJson(output) }],
387
+ structuredContent: output,
388
+ };
389
+ }
390
+ catch (error) {
391
+ return {
392
+ content: [{ type: "text", text: handleToolError(error) }],
393
+ isError: true,
394
+ };
395
+ }
396
+ }));
397
+ server.registerTool("reasoning_list_sessions", {
398
+ title: "List Reasoning Sessions",
399
+ description: `List reasoning sessions with optional filters, most recently updated first. Use this to find past sessions (e.g. to check if a similar task was already worked through) before retrieving a full trace.
400
+
401
+ Args:
402
+ - agent_id (optional): Filter by agent.
403
+ - status ('in_progress'|'completed'|'abandoned', optional): Filter by status.
404
+ - limit (1-200, default 20), offset (default 0).
405
+
406
+ Returns: JSON with { total_returned, has_more, next_offset, sessions: [{id, title, status, step_count, conclusion, ...}] }.`,
407
+ inputSchema: ReasoningListSessionsInputSchema.shape,
408
+ annotations: {
409
+ readOnlyHint: true,
410
+ destructiveHint: false,
411
+ idempotentHint: true,
412
+ openWorldHint: false,
413
+ },
414
+ }, withTelemetry({
415
+ database: databaseProvider,
416
+ toolName: "reasoning_list_sessions",
417
+ operationType: "reasoning",
418
+ accessType: "read",
419
+ buildEvent: (params, result) => ({
420
+ agentId: params.agent_id ?? null,
421
+ inputShape: {
422
+ has_agent_id: params.agent_id !== undefined,
423
+ status: params.status ?? null,
424
+ limit: params.limit,
425
+ offset: params.offset,
426
+ },
427
+ outputShape: {
428
+ result_count: result.structuredContent?.total_returned ?? 0,
429
+ total: result.structuredContent?.total ?? 0,
430
+ },
431
+ }),
432
+ }, async (params) => {
433
+ try {
434
+ const activeDb = await resolveDatabase(database);
435
+ const conditions = ["1=1"];
436
+ const sqlParams = [];
437
+ if (params.agent_id) {
438
+ conditions.push("agent_id = ?");
439
+ sqlParams.push(params.agent_id);
440
+ }
441
+ if (params.status) {
442
+ conditions.push("status = ?");
443
+ sqlParams.push(params.status);
444
+ }
445
+ const countRow = activeDb
446
+ .prepare(`SELECT COUNT(*) as c FROM reasoning_sessions WHERE ${conditions.join(" AND ")}`)
447
+ .get(...sqlParams);
448
+ const rows = activeDb
449
+ .prepare(`SELECT
450
+ reasoning_sessions.*,
451
+ COUNT(reasoning_steps.id) AS step_count
452
+ FROM reasoning_sessions
453
+ LEFT JOIN reasoning_steps
454
+ ON reasoning_steps.session_id = reasoning_sessions.id
455
+ WHERE ${conditions.join(" AND ")}
456
+ GROUP BY reasoning_sessions.id
457
+ ORDER BY updated_at DESC LIMIT ? OFFSET ?`)
458
+ .all(...sqlParams, params.limit, params.offset);
459
+ const sessions = rows.map((row) => sessionRowToRecord(row, row.step_count));
460
+ const hasMore = countRow.c > params.offset + sessions.length;
461
+ const output = {
462
+ total: countRow.c,
463
+ total_returned: sessions.length,
464
+ offset: params.offset,
465
+ has_more: hasMore,
466
+ ...(hasMore ? { next_offset: params.offset + sessions.length } : {}),
467
+ sessions,
468
+ };
469
+ return {
470
+ content: [{ type: "text", text: toLimitedJson(output) }],
471
+ structuredContent: output,
472
+ };
473
+ }
474
+ catch (error) {
475
+ return {
476
+ content: [{ type: "text", text: handleToolError(error) }],
477
+ isError: true,
478
+ };
479
+ }
480
+ }));
481
+ server.registerTool("reasoning_list_milestones", {
482
+ title: "List Reasoning Milestones",
483
+ description: "List marked reasoning steps for audit review without loading full traces.",
484
+ inputSchema: ReasoningListMilestonesInputSchema.shape,
485
+ annotations: {
486
+ readOnlyHint: true,
487
+ destructiveHint: false,
488
+ idempotentHint: true,
489
+ openWorldHint: false,
490
+ },
491
+ }, withTelemetry({
492
+ database: databaseProvider,
493
+ toolName: "reasoning_list_milestones",
494
+ operationType: "reasoning",
495
+ accessType: "read",
496
+ buildEvent: (params, result) => ({
497
+ agentId: params.agent_id ?? null,
498
+ sessionId: params.session_id ?? null,
499
+ inputShape: {
500
+ has_session_id: params.session_id !== undefined,
501
+ has_agent_id: params.agent_id !== undefined,
502
+ mark_type: params.mark_type ?? null,
503
+ limit: params.limit,
504
+ offset: params.offset,
505
+ },
506
+ outputShape: {
507
+ result_count: result.structuredContent?.total_returned ?? 0,
508
+ has_more: result.structuredContent?.has_more === true,
509
+ },
510
+ }),
511
+ }, async (params) => {
512
+ try {
513
+ const activeDb = await resolveDatabase(database);
514
+ const conditions = ["1=1"];
515
+ const sqlParams = [];
516
+ if (params.session_id) {
517
+ conditions.push("reasoning_steps.session_id = ?");
518
+ sqlParams.push(params.session_id);
519
+ }
520
+ if (params.agent_id) {
521
+ conditions.push("reasoning_sessions.agent_id = ?");
522
+ sqlParams.push(params.agent_id);
523
+ }
524
+ if (params.mark_type) {
525
+ conditions.push("reasoning_step_marks.mark_type = ?");
526
+ sqlParams.push(params.mark_type);
527
+ }
528
+ const countRow = activeDb
529
+ .prepare(`SELECT COUNT(*) as c
530
+ FROM reasoning_step_marks
531
+ JOIN reasoning_steps
532
+ ON reasoning_steps.id = reasoning_step_marks.step_id
533
+ JOIN reasoning_sessions
534
+ ON reasoning_sessions.id = reasoning_steps.session_id
535
+ WHERE ${conditions.join(" AND ")}`)
536
+ .get(...sqlParams);
537
+ const rows = activeDb
538
+ .prepare(`SELECT
539
+ reasoning_steps.session_id,
540
+ reasoning_steps.id AS step_id,
541
+ reasoning_steps.step_number,
542
+ reasoning_step_marks.mark_type,
543
+ reasoning_step_marks.note,
544
+ reasoning_step_marks.created_at,
545
+ reasoning_steps.thought,
546
+ reasoning_steps.action,
547
+ reasoning_steps.observation
548
+ FROM reasoning_step_marks
549
+ JOIN reasoning_steps
550
+ ON reasoning_steps.id = reasoning_step_marks.step_id
551
+ JOIN reasoning_sessions
552
+ ON reasoning_sessions.id = reasoning_steps.session_id
553
+ WHERE ${conditions.join(" AND ")}
554
+ ORDER BY reasoning_step_marks.created_at ASC, reasoning_steps.step_number ASC
555
+ LIMIT ? OFFSET ?`)
556
+ .all(...sqlParams, params.limit, params.offset);
557
+ const results = rows.map((row) => ({
558
+ session_id: row.session_id,
559
+ step_id: row.step_id,
560
+ step_number: row.step_number,
561
+ mark_type: row.mark_type,
562
+ note: row.note,
563
+ created_at: row.created_at,
564
+ snippet: buildReasoningSnippet({
565
+ id: row.step_id,
566
+ session_id: row.session_id,
567
+ step_number: row.step_number,
568
+ thought: row.thought,
569
+ action: row.action,
570
+ observation: row.observation,
571
+ created_at: row.created_at,
572
+ }, row.note ?? row.mark_type),
573
+ }));
574
+ const hasMore = countRow.c > params.offset + results.length;
575
+ const output = {
576
+ total: countRow.c,
577
+ total_returned: results.length,
578
+ offset: params.offset,
579
+ has_more: hasMore,
580
+ ...(hasMore ? { next_offset: params.offset + results.length } : {}),
581
+ results,
582
+ };
583
+ return {
584
+ content: [{ type: "text", text: toLimitedJson(output) }],
585
+ structuredContent: output,
586
+ };
587
+ }
588
+ catch (error) {
589
+ return {
590
+ content: [{ type: "text", text: handleToolError(error) }],
591
+ isError: true,
592
+ };
593
+ }
594
+ }));
595
+ server.registerTool("reasoning_search_steps", {
596
+ title: "Search Reasoning Steps",
597
+ description: "Search reasoning steps across thought, action, and observation.",
598
+ inputSchema: ReasoningSearchStepsInputSchema.shape,
599
+ annotations: {
600
+ readOnlyHint: true,
601
+ destructiveHint: false,
602
+ idempotentHint: true,
603
+ openWorldHint: false,
604
+ },
605
+ }, withTelemetry({
606
+ database: databaseProvider,
607
+ toolName: "reasoning_search_steps",
608
+ operationType: "reasoning",
609
+ accessType: "read",
610
+ buildEvent: (params, result) => ({
611
+ agentId: params.agent_id ?? null,
612
+ sessionId: params.session_id ?? null,
613
+ inputShape: {
614
+ query_length: params.query.length,
615
+ token_count: params.query.trim().split(/\s+/).filter(Boolean).length,
616
+ has_session_id: params.session_id !== undefined,
617
+ has_agent_id: params.agent_id !== undefined,
618
+ mark_type: params.mark_type ?? null,
619
+ limit: params.limit,
620
+ offset: params.offset,
621
+ },
622
+ outputShape: {
623
+ result_count: Array.isArray(result.structuredContent?.results)
624
+ ? result.structuredContent.results.length
625
+ : 0,
626
+ },
627
+ }),
628
+ }, async (params) => {
629
+ try {
630
+ const activeDb = await resolveDatabase(database);
631
+ const conditions = [
632
+ "reasoning_steps.rowid IN (SELECT rowid FROM reasoning_steps_fts WHERE reasoning_steps_fts MATCH ?)",
633
+ ];
634
+ const sqlParams = [toFtsQuery(params.query)];
635
+ if (params.session_id) {
636
+ conditions.push("reasoning_steps.session_id = ?");
637
+ sqlParams.push(params.session_id);
638
+ }
639
+ if (params.agent_id) {
640
+ conditions.push("reasoning_sessions.agent_id = ?");
641
+ sqlParams.push(params.agent_id);
642
+ }
643
+ if (params.mark_type) {
644
+ conditions.push("EXISTS (SELECT 1 FROM reasoning_step_marks WHERE reasoning_step_marks.step_id = reasoning_steps.id AND reasoning_step_marks.mark_type = ?)");
645
+ sqlParams.push(params.mark_type);
646
+ }
647
+ const rows = activeDb
648
+ .prepare(`SELECT
649
+ reasoning_steps.id,
650
+ reasoning_steps.session_id,
651
+ reasoning_steps.step_number,
652
+ reasoning_steps.thought,
653
+ reasoning_steps.action,
654
+ reasoning_steps.observation,
655
+ reasoning_steps.created_at,
656
+ reasoning_sessions.agent_id
657
+ FROM reasoning_steps
658
+ JOIN reasoning_sessions
659
+ ON reasoning_sessions.id = reasoning_steps.session_id
660
+ WHERE ${conditions.join(" AND ")}
661
+ ORDER BY reasoning_steps.created_at DESC, reasoning_steps.step_number DESC
662
+ LIMIT ? OFFSET ?`)
663
+ .all(...sqlParams, params.limit, params.offset);
664
+ const results = rows.map((row) => ({
665
+ ...row,
666
+ snippet: buildReasoningSnippet(row, params.query),
667
+ }));
668
+ const output = { results };
669
+ return {
670
+ content: [{ type: "text", text: toLimitedJson(output) }],
671
+ structuredContent: output,
672
+ };
673
+ }
674
+ catch (error) {
675
+ return {
676
+ content: [{ type: "text", text: handleToolError(error) }],
677
+ isError: true,
678
+ };
679
+ }
680
+ }));
681
+ server.registerTool("reasoning_get_session_outline", {
682
+ title: "Get Reasoning Session Outline",
683
+ description: "Return an audit-oriented outline for a session, using marked steps when present and a deterministic fallback otherwise.",
684
+ inputSchema: ReasoningGetSessionOutlineInputSchema.shape,
685
+ annotations: {
686
+ readOnlyHint: true,
687
+ destructiveHint: false,
688
+ idempotentHint: true,
689
+ openWorldHint: false,
690
+ },
691
+ }, withTelemetry({
692
+ database: databaseProvider,
693
+ toolName: "reasoning_get_session_outline",
694
+ operationType: "reasoning",
695
+ accessType: "read",
696
+ buildEvent: (params, result) => ({
697
+ sessionId: params.session_id,
698
+ inputShape: {
699
+ session_id_present: true,
700
+ },
701
+ outputShape: {
702
+ used_fallback: result.structuredContent?.used_fallback === true,
703
+ step_count: Array.isArray(result.structuredContent?.steps)
704
+ ? result.structuredContent.steps.length
705
+ : 0,
706
+ },
707
+ }),
708
+ }, async (params) => {
709
+ try {
710
+ const activeDb = await resolveDatabase(database);
711
+ const sessionRow = activeDb
712
+ .prepare(`SELECT * FROM reasoning_sessions WHERE id = ?`)
713
+ .get(params.session_id);
714
+ if (!sessionRow) {
715
+ return {
716
+ content: [
717
+ {
718
+ type: "text",
719
+ text: `Error: Session '${params.session_id}' not found.`,
720
+ },
721
+ ],
722
+ isError: true,
723
+ };
724
+ }
725
+ const stepRows = activeDb
726
+ .prepare(`SELECT * FROM reasoning_steps WHERE session_id = ? ORDER BY step_number ASC`)
727
+ .all(params.session_id);
728
+ const markedRows = activeDb
729
+ .prepare(`SELECT
730
+ reasoning_steps.id,
731
+ reasoning_steps.session_id,
732
+ reasoning_steps.step_number,
733
+ reasoning_steps.thought,
734
+ reasoning_steps.action,
735
+ reasoning_steps.observation,
736
+ reasoning_steps.created_at,
737
+ reasoning_step_marks.mark_type,
738
+ reasoning_step_marks.note,
739
+ reasoning_step_marks.created_at AS mark_created_at
740
+ FROM reasoning_step_marks
741
+ JOIN reasoning_steps
742
+ ON reasoning_steps.id = reasoning_step_marks.step_id
743
+ WHERE reasoning_steps.session_id = ?
744
+ ORDER BY reasoning_step_marks.created_at ASC, reasoning_steps.step_number ASC`)
745
+ .all(params.session_id);
746
+ const session = sessionRowToRecord(sessionRow, stepRows.length);
747
+ const steps = markedRows.length > 0
748
+ ? markedRows.map((row) => stepToOutlineRecord(row, row.mark_type, row.note))
749
+ : selectFallbackOutlineSteps(stepRows).map((row) => stepToOutlineRecord(row));
750
+ const output = {
751
+ session,
752
+ used_fallback: markedRows.length === 0,
753
+ steps,
754
+ };
755
+ return {
756
+ content: [{ type: "text", text: toLimitedJson(output) }],
757
+ structuredContent: output,
758
+ };
759
+ }
760
+ catch (error) {
761
+ return {
762
+ content: [{ type: "text", text: handleToolError(error) }],
763
+ isError: true,
764
+ };
765
+ }
766
+ }));
767
+ server.registerTool("reasoning_mark_step", {
768
+ title: "Mark Reasoning Step",
769
+ description: "Attach an audit marker to an existing reasoning step. Repeating the same step_id + mark_type updates the note instead of creating a duplicate mark.",
770
+ inputSchema: ReasoningMarkStepInputSchema.shape,
771
+ annotations: {
772
+ readOnlyHint: false,
773
+ destructiveHint: false,
774
+ idempotentHint: true,
775
+ openWorldHint: false,
776
+ },
777
+ }, withTelemetry({
778
+ database: databaseProvider,
779
+ toolName: "reasoning_mark_step",
780
+ operationType: "reasoning",
781
+ accessType: "write",
782
+ buildEvent: (params, result) => ({
783
+ stepId: params.step_id,
784
+ inputShape: {
785
+ mark_type: params.mark_type,
786
+ note_present: params.note !== undefined,
787
+ note_length: params.note?.length ?? 0,
788
+ },
789
+ outputShape: {
790
+ step_id: result.structuredContent?.step_id ?? null,
791
+ mark_type: result.structuredContent?.mark_type ?? null,
792
+ note_present: result.structuredContent?.note !== null,
793
+ },
794
+ }),
795
+ }, async (params) => {
796
+ try {
797
+ const activeDb = await resolveDatabase(database);
798
+ const step = activeDb
799
+ .prepare(`SELECT id FROM reasoning_steps WHERE id = ?`)
800
+ .get(params.step_id);
801
+ if (!step) {
802
+ return {
803
+ content: [
804
+ {
805
+ type: "text",
806
+ text: `Error: Step '${params.step_id}' not found.`,
807
+ },
808
+ ],
809
+ isError: true,
810
+ };
811
+ }
812
+ const ts = nowIso();
813
+ activeDb
814
+ .prepare(`INSERT INTO reasoning_step_marks (id, step_id, mark_type, note, created_at)
815
+ VALUES (?, ?, ?, ?, ?)
816
+ ON CONFLICT(step_id, mark_type)
817
+ DO UPDATE SET note = CASE
818
+ WHEN ? THEN excluded.note
819
+ ELSE reasoning_step_marks.note
820
+ END`)
821
+ .run(newId("mark"), params.step_id, params.mark_type, params.note ?? null, ts, params.note !== undefined ? 1 : 0);
822
+ const mark = activeDb
823
+ .prepare(`SELECT id, step_id, mark_type, note, created_at
824
+ FROM reasoning_step_marks
825
+ WHERE step_id = ? AND mark_type = ?`)
826
+ .get(params.step_id, params.mark_type);
827
+ const output = {
828
+ step_id: mark.step_id,
829
+ mark_type: mark.mark_type,
830
+ note: mark.note,
831
+ };
832
+ return {
833
+ content: [{ type: "text", text: toLimitedJson(output) }],
834
+ structuredContent: output,
835
+ };
836
+ }
837
+ catch (error) {
838
+ return {
839
+ content: [{ type: "text", text: handleToolError(error) }],
840
+ isError: true,
841
+ };
842
+ }
843
+ }));
844
+ server.registerTool("reasoning_complete_session", {
845
+ title: "Complete Reasoning Session",
846
+ description: `Mark a reasoning session as finished, recording its final conclusion. Optionally also persist the conclusion as a long-term memory so it can be recalled later without replaying the full trace.
847
+
848
+ Args:
849
+ - session_id (string, required): The session id.
850
+ - conclusion (string, required): The final answer/decision reached.
851
+ - status ('completed'|'abandoned', default 'completed'): Use 'abandoned' if the task was dropped without a real conclusion.
852
+ - save_as_memory (boolean, default false): If true, also create a memory with this conclusion.
853
+ - memory_mode ('auto'|'always'|'never', optional): Auto-saves completed non-empty sessions by default, can be forced or disabled.
854
+ - memory_type (optional): Memory type to use when a completion is persisted.
855
+ - memory_importance (optional): Importance to use when a completion is persisted.
856
+ - memory_tags (string[], default []): Tags for the created memory.
857
+ - not_saved_reason (optional): Required when memory_mode='never'.
858
+
859
+ Returns: JSON with the updated session, created memory id if any, and skip warnings when memory is not saved.
860
+
861
+ Error Handling:
862
+ - Returns "Error: Session '<id>' not found" if the id does not exist.
863
+ - Returns an error if the session was already completed/abandoned (finalize only once).`,
864
+ inputSchema: ReasoningCompleteSessionInputSchema.shape,
865
+ annotations: {
866
+ readOnlyHint: false,
867
+ destructiveHint: false,
868
+ idempotentHint: false,
869
+ openWorldHint: false,
870
+ },
871
+ }, withTelemetry({
872
+ database: databaseProvider,
873
+ toolName: "reasoning_complete_session",
874
+ operationType: "reasoning",
875
+ accessType: "write",
876
+ buildEvent: async (params, result, activeDb) => {
877
+ const structured = result.structuredContent;
878
+ const session = activeDb
879
+ .prepare(`SELECT agent_id FROM reasoning_sessions WHERE id = ?`)
880
+ .get(params.session_id);
881
+ const notSavedReason = typeof structured?.not_saved_reason === "string"
882
+ ? structured.not_saved_reason
883
+ : null;
884
+ let reasonCategory = null;
885
+ if (params.memory_mode === "never")
886
+ reasonCategory = "caller_request";
887
+ else if (params.status === "abandoned")
888
+ reasonCategory = "not_completed";
889
+ else if (notSavedReason?.includes("zero reasoning steps")) {
890
+ reasonCategory = "zero_step";
891
+ }
892
+ return {
893
+ agentId: session?.agent_id ?? null,
894
+ sessionId: params.session_id,
895
+ memoryId: typeof structured?.memory_id === "string" ? structured.memory_id : null,
896
+ inputShape: {
897
+ status: params.status,
898
+ memory_mode: params.memory_mode ?? "auto",
899
+ save_as_memory: params.save_as_memory ?? false,
900
+ memory_type: params.memory_type ?? null,
901
+ memory_importance: params.memory_importance ?? null,
902
+ tag_count: params.memory_tags?.length ?? 0,
903
+ },
904
+ outputShape: {
905
+ memory_id_present: typeof structured?.memory_id === "string",
906
+ not_saved_reason_category: reasonCategory,
907
+ warning_count: Array.isArray(structured?.warnings)
908
+ ? structured.warnings.length
909
+ : 0,
910
+ },
911
+ };
912
+ },
913
+ }, async (params) => {
914
+ try {
915
+ const activeDb = await resolveDatabase(database);
916
+ const session = activeDb
917
+ .prepare(`SELECT * FROM reasoning_sessions WHERE id = ?`)
918
+ .get(params.session_id);
919
+ if (!session) {
920
+ return {
921
+ content: [
922
+ {
923
+ type: "text",
924
+ text: `Error: Session '${params.session_id}' not found.`,
925
+ },
926
+ ],
927
+ isError: true,
928
+ };
929
+ }
930
+ if (session.status !== "in_progress") {
931
+ return {
932
+ content: [
933
+ {
934
+ type: "text",
935
+ text: `Error: Session '${params.session_id}' is already '${session.status}'.`,
936
+ },
937
+ ],
938
+ isError: true,
939
+ };
940
+ }
941
+ const stepCount = getStepCount(activeDb, params.session_id);
942
+ if (params.memory_mode === "never" && !params.not_saved_reason) {
943
+ return {
944
+ content: [
945
+ {
946
+ type: "text",
947
+ text: "Error: not_saved_reason is required when memory_mode='never'.",
948
+ },
949
+ ],
950
+ isError: true,
951
+ };
952
+ }
953
+ const saveMemory = shouldAutoSaveMemory(params, stepCount);
954
+ const notSavedReason = saveMemory
955
+ ? null
956
+ : buildNotSavedReason(params, stepCount);
957
+ const memoryId = runInTransaction(activeDb, () => {
958
+ const ts = nowIso();
959
+ activeDb
960
+ .prepare(`UPDATE reasoning_sessions SET status = ?, conclusion = ?, updated_at = ? WHERE id = ?`)
961
+ .run(params.status, params.conclusion, ts, params.session_id);
962
+ if (!saveMemory)
963
+ return null;
964
+ const nextMemoryId = newId("mem");
965
+ activeDb
966
+ .prepare(`INSERT INTO memories (id, type, content, tags, agent_id, importance, metadata, created_at, updated_at)
967
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`)
968
+ .run(nextMemoryId, params.memory_type ?? "reasoning_summary", params.conclusion, JSON.stringify(params.memory_tags ?? []), session.agent_id, params.memory_importance ?? 3, JSON.stringify({
969
+ source_session_id: params.session_id,
970
+ session_title: session.title,
971
+ auto_saved: !(params.save_as_memory || params.memory_mode === "always"),
972
+ step_count: stepCount,
973
+ }), ts, ts);
974
+ return nextMemoryId;
975
+ });
976
+ const updatedRow = activeDb
977
+ .prepare(`SELECT * FROM reasoning_sessions WHERE id = ?`)
978
+ .get(params.session_id);
979
+ const record = sessionRowToRecord(updatedRow, stepCount);
980
+ const output = {
981
+ session: record,
982
+ memory_id: memoryId,
983
+ not_saved_reason: notSavedReason,
984
+ warnings: stepCount === 0 && params.status === "completed"
985
+ ? ["Session completed with zero reasoning steps."]
986
+ : [],
987
+ };
988
+ return {
989
+ content: [{ type: "text", text: toLimitedJson(output) }],
990
+ structuredContent: output,
991
+ };
992
+ }
993
+ catch (error) {
994
+ return {
995
+ content: [{ type: "text", text: handleToolError(error) }],
996
+ isError: true,
997
+ };
998
+ }
999
+ }));
1000
+ }
1001
+ //# sourceMappingURL=reasoning.js.map