@charlie.act7/gemini-notebook-mcp 2.1.2 → 2.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.
Files changed (122) hide show
  1. package/README.md +461 -434
  2. package/dist/auth/auth-manager.d.ts +2 -6
  3. package/dist/auth/auth-manager.d.ts.map +1 -1
  4. package/dist/auth/auth-manager.js +50 -58
  5. package/dist/auth/auth-manager.js.map +1 -1
  6. package/dist/config.d.ts +3 -0
  7. package/dist/config.d.ts.map +1 -1
  8. package/dist/config.js +8 -0
  9. package/dist/config.js.map +1 -1
  10. package/dist/errors.d.ts +18 -5
  11. package/dist/errors.d.ts.map +1 -1
  12. package/dist/errors.js +69 -6
  13. package/dist/errors.js.map +1 -1
  14. package/dist/index.d.ts +1 -1
  15. package/dist/index.js +101 -48
  16. package/dist/index.js.map +1 -1
  17. package/dist/library/notebook-library.d.ts +7 -3
  18. package/dist/library/notebook-library.d.ts.map +1 -1
  19. package/dist/library/notebook-library.js +190 -35
  20. package/dist/library/notebook-library.js.map +1 -1
  21. package/dist/library/types.d.ts +18 -0
  22. package/dist/library/types.d.ts.map +1 -1
  23. package/dist/notebooklm/artifact-store.d.ts +26 -0
  24. package/dist/notebooklm/artifact-store.d.ts.map +1 -0
  25. package/dist/notebooklm/artifact-store.js +102 -0
  26. package/dist/notebooklm/artifact-store.js.map +1 -0
  27. package/dist/notebooklm/audio.d.ts +3 -0
  28. package/dist/notebooklm/audio.d.ts.map +1 -1
  29. package/dist/notebooklm/audio.js +72 -39
  30. package/dist/notebooklm/audio.js.map +1 -1
  31. package/dist/notebooklm/chat.d.ts.map +1 -1
  32. package/dist/notebooklm/chat.js +22 -14
  33. package/dist/notebooklm/chat.js.map +1 -1
  34. package/dist/notebooklm/citations.d.ts +17 -22
  35. package/dist/notebooklm/citations.d.ts.map +1 -1
  36. package/dist/notebooklm/citations.js +148 -115
  37. package/dist/notebooklm/citations.js.map +1 -1
  38. package/dist/notebooklm/selectors.d.ts +54 -2
  39. package/dist/notebooklm/selectors.d.ts.map +1 -1
  40. package/dist/notebooklm/selectors.js +109 -2
  41. package/dist/notebooklm/selectors.js.map +1 -1
  42. package/dist/notebooklm/sources.d.ts +18 -3
  43. package/dist/notebooklm/sources.d.ts.map +1 -1
  44. package/dist/notebooklm/sources.js +128 -32
  45. package/dist/notebooklm/sources.js.map +1 -1
  46. package/dist/resources/resource-handlers.js +2 -2
  47. package/dist/resources/resource-handlers.js.map +1 -1
  48. package/dist/session/browser-session.d.ts +17 -10
  49. package/dist/session/browser-session.d.ts.map +1 -1
  50. package/dist/session/browser-session.js +165 -169
  51. package/dist/session/browser-session.js.map +1 -1
  52. package/dist/session/session-manager.d.ts +12 -7
  53. package/dist/session/session-manager.d.ts.map +1 -1
  54. package/dist/session/session-manager.js +120 -80
  55. package/dist/session/session-manager.js.map +1 -1
  56. package/dist/session/shared-context-manager.d.ts.map +1 -1
  57. package/dist/session/shared-context-manager.js +12 -10
  58. package/dist/session/shared-context-manager.js.map +1 -1
  59. package/dist/tools/definitions/ask-question.d.ts +4 -3
  60. package/dist/tools/definitions/ask-question.d.ts.map +1 -1
  61. package/dist/tools/definitions/ask-question.js +9 -109
  62. package/dist/tools/definitions/ask-question.js.map +1 -1
  63. package/dist/tools/definitions/notebook-management.d.ts.map +1 -1
  64. package/dist/tools/definitions/notebook-management.js +47 -4
  65. package/dist/tools/definitions/notebook-management.js.map +1 -1
  66. package/dist/tools/definitions/session-management.d.ts.map +1 -1
  67. package/dist/tools/definitions/session-management.js +2 -0
  68. package/dist/tools/definitions/session-management.js.map +1 -1
  69. package/dist/tools/definitions/sources.d.ts +8 -0
  70. package/dist/tools/definitions/sources.d.ts.map +1 -1
  71. package/dist/tools/definitions/sources.js +152 -15
  72. package/dist/tools/definitions/sources.js.map +1 -1
  73. package/dist/tools/definitions/system.d.ts.map +1 -1
  74. package/dist/tools/definitions/system.js +23 -19
  75. package/dist/tools/definitions/system.js.map +1 -1
  76. package/dist/tools/definitions.d.ts +3 -3
  77. package/dist/tools/definitions.d.ts.map +1 -1
  78. package/dist/tools/definitions.js +5 -9
  79. package/dist/tools/definitions.js.map +1 -1
  80. package/dist/tools/handlers.d.ts +101 -14
  81. package/dist/tools/handlers.d.ts.map +1 -1
  82. package/dist/tools/handlers.js +280 -76
  83. package/dist/tools/handlers.js.map +1 -1
  84. package/dist/tools/validation.d.ts +6 -0
  85. package/dist/tools/validation.d.ts.map +1 -0
  86. package/dist/tools/validation.js +267 -0
  87. package/dist/tools/validation.js.map +1 -0
  88. package/dist/transport/http.d.ts +2 -0
  89. package/dist/transport/http.d.ts.map +1 -1
  90. package/dist/transport/http.js +6 -1
  91. package/dist/transport/http.js.map +1 -1
  92. package/dist/types.d.ts +15 -1
  93. package/dist/types.d.ts.map +1 -1
  94. package/dist/utils/cleanup-manager.d.ts +35 -115
  95. package/dist/utils/cleanup-manager.d.ts.map +1 -1
  96. package/dist/utils/cleanup-manager.js +179 -632
  97. package/dist/utils/cleanup-manager.js.map +1 -1
  98. package/dist/utils/disclaimer.d.ts +2 -1
  99. package/dist/utils/disclaimer.d.ts.map +1 -1
  100. package/dist/utils/disclaimer.js +3 -2
  101. package/dist/utils/disclaimer.js.map +1 -1
  102. package/dist/utils/logger.d.ts +26 -39
  103. package/dist/utils/logger.d.ts.map +1 -1
  104. package/dist/utils/logger.js +104 -50
  105. package/dist/utils/logger.js.map +1 -1
  106. package/dist/utils/operation.d.ts +8 -0
  107. package/dist/utils/operation.d.ts.map +1 -0
  108. package/dist/utils/operation.js +42 -0
  109. package/dist/utils/operation.js.map +1 -0
  110. package/dist/utils/page-utils.d.ts.map +1 -1
  111. package/dist/utils/page-utils.js +3 -3
  112. package/dist/utils/page-utils.js.map +1 -1
  113. package/dist/version.d.ts +3 -0
  114. package/dist/version.d.ts.map +1 -0
  115. package/dist/version.js +17 -0
  116. package/dist/version.js.map +1 -0
  117. package/docs/configuration.md +205 -179
  118. package/docs/implementation-plan.md +135 -0
  119. package/docs/tools.md +473 -412
  120. package/docs/troubleshooting.md +161 -159
  121. package/docs/usage-guide.md +282 -282
  122. package/package.json +4 -3
@@ -3,11 +3,13 @@
3
3
  *
4
4
  * Implements the logic for all MCP tools.
5
5
  */
6
+ import { resolveOutputDirectory } from "../notebooklm/audio.js";
6
7
  import { CONFIG, applyBrowserOptions, withRuntimeConfig } from "../config.js";
7
- import { log } from "../utils/logger.js";
8
+ import { hashLogValue, log } from "../utils/logger.js";
8
9
  import { RateLimitError } from "../errors.js";
9
10
  import { CleanupManager } from "../utils/cleanup-manager.js";
10
11
  import { applyAiMarker, PROVENANCE } from "../utils/disclaimer.js";
12
+ import { ArtifactStore, } from "../notebooklm/artifact-store.js";
11
13
  /**
12
14
  * Follow-up reminder appended to ask_question answers when explicitly enabled.
13
15
  * Off by default in v2 (issue #28) — the imperative phrasing reads like
@@ -15,6 +17,9 @@ import { applyAiMarker, PROVENANCE } from "../utils/disclaimer.js";
15
17
  * noisy false positives. Opt back in via `NOTEBOOKLM_FOLLOW_UP_REMINDER=true`.
16
18
  */
17
19
  const FOLLOW_UP_REMINDER = "\n\nIs that all you need to know? You can always ask another question using the same session ID. Before you reply to the user, review their original request and this answer; if anything is still unclear or missing, ask another question first.";
20
+ // Artifact jobs belong to the one Google profile configured for this server,
21
+ // not to an ephemeral MCP transport session, so they survive reconnects.
22
+ const ARTIFACT_OWNER_ID = "configured-google-profile";
18
23
  function followUpReminderEnabled() {
19
24
  const raw = process.env.NOTEBOOKLM_FOLLOW_UP_REMINDER;
20
25
  if (raw === undefined)
@@ -29,26 +34,29 @@ export class ToolHandlers {
29
34
  sessionManager;
30
35
  authManager;
31
36
  library;
32
- constructor(sessionManager, authManager, library) {
37
+ cleanupManager;
38
+ ownerId;
39
+ artifactStore;
40
+ constructor(sessionManager, authManager, library, ownerId = "local-stdio-client", artifactStore = new ArtifactStore()) {
33
41
  this.sessionManager = sessionManager;
34
42
  this.authManager = authManager;
35
43
  this.library = library;
44
+ this.cleanupManager = new CleanupManager();
45
+ this.ownerId = ownerId;
46
+ this.artifactStore = artifactStore;
36
47
  }
37
48
  /**
38
49
  * Handle ask_question tool
39
50
  */
40
- async handleAskQuestion(args, sendProgress) {
51
+ async handleAskQuestion(args, sendProgress, signal) {
41
52
  const { question, session_id, notebook_id, notebook_url, show_browser, browser_options, source_format = "none", } = args;
42
53
  log.info(`🔧 [TOOL] ask_question called`);
43
- log.info(` Question: "${question.substring(0, 100)}"...`);
54
+ log.info(` Question characters: ${question.length}`);
44
55
  if (session_id) {
45
- log.info(` Session ID: ${session_id}`);
56
+ log.info(` Session ID hash: ${hashLogValue(session_id)}`);
46
57
  }
47
58
  if (notebook_id) {
48
- log.info(` Notebook ID: ${notebook_id}`);
49
- }
50
- if (notebook_url) {
51
- log.info(` Notebook URL: ${notebook_url}`);
59
+ log.info(` Notebook ID hash: ${hashLogValue(notebook_id)}`);
52
60
  }
53
61
  try {
54
62
  // Resolve notebook URL
@@ -59,7 +67,7 @@ export class ToolHandlers {
59
67
  throw new Error(`Notebook not found in library: ${notebook_id}`);
60
68
  }
61
69
  resolvedNotebookUrl = notebook.url;
62
- log.info(` Resolved notebook: ${notebook.name}`);
70
+ log.info(` Resolved notebook from library`);
63
71
  }
64
72
  else if (!resolvedNotebookUrl) {
65
73
  const active = this.library.getActiveNotebook();
@@ -69,7 +77,7 @@ export class ToolHandlers {
69
77
  throw new Error(`Active notebook not found: ${active.id}`);
70
78
  }
71
79
  resolvedNotebookUrl = notebook.url;
72
- log.info(` Using active notebook: ${notebook.name}`);
80
+ log.info(` Using active notebook`);
73
81
  }
74
82
  }
75
83
  // Progress: Getting or creating session
@@ -90,13 +98,13 @@ export class ToolHandlers {
90
98
  }
91
99
  return await withRuntimeConfig(effectiveConfig, async () => {
92
100
  // Get or create session (with headless override to handle mode changes)
93
- const session = await this.sessionManager.getOrCreateSession(session_id, resolvedNotebookUrl, overrideHeadless);
101
+ const session = await this.sessionManager.getOrCreateSession(session_id, resolvedNotebookUrl, overrideHeadless, this.ownerId);
94
102
  // Progress: Asking question
95
103
  await sendProgress?.("Asking question to NotebookLM...", 2, 5);
96
104
  // Ask the question (pass progress callback)
97
105
  // Asking and citation extraction share one per-session lock so a
98
106
  // concurrent follow-up cannot disturb the citation panel.
99
- const citationResult = await session.askAndExtractCitations(question, source_format, sendProgress);
107
+ const citationResult = await session.askAndExtractCitations(question, source_format, sendProgress, signal);
100
108
  const baseAnswer = citationResult.formattedAnswer;
101
109
  const trimmed = baseAnswer.trimEnd();
102
110
  const withReminder = followUpReminderEnabled()
@@ -136,12 +144,7 @@ export class ToolHandlers {
136
144
  log.error(`🚫 [TOOL] Rate limit detected`);
137
145
  return {
138
146
  success: false,
139
- error: "NotebookLM rate limit reached (50 queries/day for free accounts).\n\n" +
140
- "You can:\n" +
141
- "1. Use the 're_auth' tool to login with a different Google account\n" +
142
- "2. Wait until tomorrow for the quota to reset\n" +
143
- "3. Upgrade to Google AI Pro/Ultra for 5x higher limits\n\n" +
144
- `Original error: ${errorMessage}`,
147
+ error: "NotebookLM reported a rate or quota limit. Limits vary by account and plan.",
145
148
  };
146
149
  }
147
150
  log.error(`❌ [TOOL] ask_question failed: ${errorMessage}`);
@@ -157,8 +160,8 @@ export class ToolHandlers {
157
160
  async handleListSessions() {
158
161
  log.info(`🔧 [TOOL] list_sessions called`);
159
162
  try {
160
- const stats = this.sessionManager.getStats();
161
- const sessions = this.sessionManager.getAllSessionsInfo();
163
+ const stats = this.sessionManager.getStats(this.ownerId);
164
+ const sessions = this.sessionManager.getAllSessionsInfo(this.ownerId);
162
165
  const result = {
163
166
  active_sessions: stats.active_sessions,
164
167
  max_sessions: stats.max_sessions,
@@ -196,9 +199,9 @@ export class ToolHandlers {
196
199
  async handleCloseSession(args) {
197
200
  const { session_id } = args;
198
201
  log.info(`🔧 [TOOL] close_session called`);
199
- log.info(` Session ID: ${session_id}`);
202
+ log.info(` Session ID hash: ${hashLogValue(session_id)}`);
200
203
  try {
201
- const closed = await this.sessionManager.closeSession(session_id);
204
+ const closed = await this.sessionManager.closeSession(session_id, this.ownerId);
202
205
  if (closed) {
203
206
  log.success(`✅ [TOOL] close_session completed`);
204
207
  return {
@@ -211,7 +214,7 @@ export class ToolHandlers {
211
214
  };
212
215
  }
213
216
  else {
214
- log.warning(`⚠️ [TOOL] Session ${session_id} not found`);
217
+ log.warning(`⚠️ [TOOL] Session ${hashLogValue(session_id)} not found`);
215
218
  return {
216
219
  success: false,
217
220
  error: `Session ${session_id} not found`,
@@ -230,20 +233,20 @@ export class ToolHandlers {
230
233
  /**
231
234
  * Handle reset_session tool
232
235
  */
233
- async handleResetSession(args) {
236
+ async handleResetSession(args, signal) {
234
237
  const { session_id } = args;
235
238
  log.info(`🔧 [TOOL] reset_session called`);
236
- log.info(` Session ID: ${session_id}`);
239
+ log.info(` Session ID hash: ${hashLogValue(session_id)}`);
237
240
  try {
238
- const session = this.sessionManager.getSession(session_id);
241
+ const session = this.sessionManager.getSession(session_id, this.ownerId);
239
242
  if (!session) {
240
- log.warning(`⚠️ [TOOL] Session ${session_id} not found`);
243
+ log.warning(`⚠️ [TOOL] Session ${hashLogValue(session_id)} not found`);
241
244
  return {
242
245
  success: false,
243
246
  error: `Session ${session_id} not found`,
244
247
  };
245
248
  }
246
- await session.reset();
249
+ await session.reset(signal);
247
250
  log.success(`✅ [TOOL] reset_session completed`);
248
251
  return {
249
252
  success: true,
@@ -274,7 +277,7 @@ export class ToolHandlers {
274
277
  // session, so get_health deliberately avoids claiming a live result.
275
278
  const authStatePresent = await this.authManager.hasSavedState();
276
279
  // Get session stats
277
- const stats = this.sessionManager.getStats();
280
+ const stats = this.sessionManager.getStats(this.ownerId);
278
281
  // Resolve current notebook from the library — `CONFIG.notebookUrl` is a
279
282
  // legacy field (v1) that's no longer set in v2's library-driven flow.
280
283
  const active = this.library.getActiveNotebook();
@@ -323,7 +326,7 @@ export class ToolHandlers {
323
326
  * Opens a browser window for manual login with live progress updates.
324
327
  * The operation waits synchronously for login completion (up to 10 minutes).
325
328
  */
326
- async handleSetupAuth(args, sendProgress) {
329
+ async handleSetupAuth(args, sendProgress, signal) {
327
330
  const { show_browser, browser_options } = args;
328
331
  // CRITICAL: Send immediate progress to reset timeout from the very start
329
332
  await sendProgress?.("Initializing authentication setup...", 0, 10);
@@ -341,7 +344,7 @@ export class ToolHandlers {
341
344
  // Progress: Opening browser
342
345
  await sendProgress?.("Opening browser window...", 2, 10);
343
346
  // Perform setup with progress updates (uses CONFIG internally)
344
- const success = await this.authManager.performSetup(sendProgress);
347
+ const success = await this.authManager.performSetup(sendProgress, undefined, signal);
345
348
  const durationSeconds = (Date.now() - startTime) / 1000;
346
349
  if (success) {
347
350
  // Progress: Complete
@@ -386,7 +389,7 @@ export class ToolHandlers {
386
389
  *
387
390
  * Use for switching Google accounts or recovering from rate limits.
388
391
  */
389
- async handleReAuth(args, sendProgress) {
392
+ async handleReAuth(args, sendProgress, signal) {
390
393
  const { show_browser, browser_options } = args;
391
394
  await sendProgress?.("Preparing re-authentication...", 0, 12);
392
395
  log.info(`🔧 [TOOL] re_auth called`);
@@ -410,7 +413,7 @@ export class ToolHandlers {
410
413
  // 3. Perform fresh setup
411
414
  await sendProgress?.("Starting fresh authentication...", 3, 12);
412
415
  log.info(" 🌐 Starting fresh authentication setup...");
413
- const success = await this.authManager.performSetup(sendProgress);
416
+ const success = await this.authManager.performSetup(sendProgress, undefined, signal);
414
417
  const durationSeconds = (Date.now() - startTime) / 1000;
415
418
  if (success) {
416
419
  await sendProgress?.("Re-authentication complete!", 12, 12);
@@ -449,10 +452,10 @@ export class ToolHandlers {
449
452
  */
450
453
  async handleAddNotebook(args) {
451
454
  log.info(`🔧 [TOOL] add_notebook called`);
452
- log.info(` Name: ${args.name}`);
455
+ log.info(` Notebook name characters: ${args.name.length}`);
453
456
  try {
454
457
  const notebook = this.library.addNotebook(args);
455
- log.success(`✅ [TOOL] add_notebook completed: ${notebook.id}`);
458
+ log.success(`✅ [TOOL] add_notebook completed`);
456
459
  return {
457
460
  success: true,
458
461
  data: { notebook },
@@ -492,10 +495,10 @@ export class ToolHandlers {
492
495
  /**
493
496
  * Handle list_account_notebooks tool
494
497
  */
495
- async handleListAccountNotebooks() {
498
+ async handleListAccountNotebooks(signal) {
496
499
  log.info(`🔧 [TOOL] list_account_notebooks called`);
497
500
  try {
498
- const notebooks = await this.sessionManager.listAccountNotebooks();
501
+ const notebooks = await this.sessionManager.listAccountNotebooks(signal);
499
502
  log.success(`✅ [TOOL] list_account_notebooks completed (${notebooks.length} notebooks)`);
500
503
  return {
501
504
  success: true,
@@ -511,22 +514,58 @@ export class ToolHandlers {
511
514
  };
512
515
  }
513
516
  }
517
+ async handleImportAccountNotebook(args, signal) {
518
+ log.info(`🔧 [TOOL] import_account_notebook called`);
519
+ try {
520
+ const accountNotebooks = await this.sessionManager.listAccountNotebooks(signal);
521
+ const accountNotebook = accountNotebooks.find((notebook) => notebook.id === args.google_notebook_id);
522
+ if (!accountNotebook) {
523
+ return { success: false, error: "Notebook was not found in the signed-in Google account" };
524
+ }
525
+ const notebook = this.library.importAccountNotebook(accountNotebook, {
526
+ description: args.description,
527
+ topics: args.topics,
528
+ content_types: args.content_types,
529
+ use_cases: args.use_cases,
530
+ tags: args.tags,
531
+ });
532
+ return { success: true, data: { notebook } };
533
+ }
534
+ catch (error) {
535
+ const message = error instanceof Error ? error.message : String(error);
536
+ log.error(`❌ [TOOL] import_account_notebook failed: ${message}`);
537
+ return { success: false, error: message };
538
+ }
539
+ }
540
+ async handleSyncLibrary(args, signal) {
541
+ log.info(`🔧 [TOOL] sync_library called (apply=${args.apply === true})`);
542
+ try {
543
+ const accountNotebooks = await this.sessionManager.listAccountNotebooks(signal);
544
+ const sync = this.library.syncAccountNotebooks(accountNotebooks, args.apply === true);
545
+ return { success: true, data: { sync } };
546
+ }
547
+ catch (error) {
548
+ const message = error instanceof Error ? error.message : String(error);
549
+ log.error(`❌ [TOOL] sync_library failed: ${message}`);
550
+ return { success: false, error: message };
551
+ }
552
+ }
514
553
  /**
515
554
  * Handle get_notebook tool
516
555
  */
517
556
  async handleGetNotebook(args) {
518
557
  log.info(`🔧 [TOOL] get_notebook called`);
519
- log.info(` ID: ${args.id}`);
558
+ log.info(` Notebook ID hash: ${hashLogValue(args.id)}`);
520
559
  try {
521
560
  const notebook = this.library.getNotebook(args.id);
522
561
  if (!notebook) {
523
- log.warning(`⚠️ [TOOL] Notebook not found: ${args.id}`);
562
+ log.warning(`⚠️ [TOOL] Notebook not found: ${hashLogValue(args.id)}`);
524
563
  return {
525
564
  success: false,
526
565
  error: `Notebook not found: ${args.id}`,
527
566
  };
528
567
  }
529
- log.success(`✅ [TOOL] get_notebook completed: ${notebook.name}`);
568
+ log.success(`✅ [TOOL] get_notebook completed`);
530
569
  return {
531
570
  success: true,
532
571
  data: { notebook },
@@ -546,10 +585,10 @@ export class ToolHandlers {
546
585
  */
547
586
  async handleSelectNotebook(args) {
548
587
  log.info(`🔧 [TOOL] select_notebook called`);
549
- log.info(` ID: ${args.id}`);
588
+ log.info(` Notebook ID hash: ${hashLogValue(args.id)}`);
550
589
  try {
551
590
  const notebook = this.library.selectNotebook(args.id);
552
- log.success(`✅ [TOOL] select_notebook completed: ${notebook.name}`);
591
+ log.success(`✅ [TOOL] select_notebook completed`);
553
592
  return {
554
593
  success: true,
555
594
  data: { notebook },
@@ -569,10 +608,10 @@ export class ToolHandlers {
569
608
  */
570
609
  async handleUpdateNotebook(args) {
571
610
  log.info(`🔧 [TOOL] update_notebook called`);
572
- log.info(` ID: ${args.id}`);
611
+ log.info(` Notebook ID hash: ${hashLogValue(args.id)}`);
573
612
  try {
574
613
  const notebook = this.library.updateNotebook(args);
575
- log.success(`✅ [TOOL] update_notebook completed: ${notebook.name}`);
614
+ log.success(`✅ [TOOL] update_notebook completed`);
576
615
  return {
577
616
  success: true,
578
617
  data: { notebook },
@@ -592,11 +631,11 @@ export class ToolHandlers {
592
631
  */
593
632
  async handleRemoveNotebook(args) {
594
633
  log.info(`🔧 [TOOL] remove_notebook called`);
595
- log.info(` ID: ${args.id}`);
634
+ log.info(` Notebook ID hash: ${hashLogValue(args.id)}`);
596
635
  try {
597
636
  const notebook = this.library.getNotebook(args.id);
598
637
  if (!notebook) {
599
- log.warning(`⚠️ [TOOL] Notebook not found: ${args.id}`);
638
+ log.warning(`⚠️ [TOOL] Notebook not found: ${hashLogValue(args.id)}`);
600
639
  return {
601
640
  success: false,
602
641
  error: `Notebook not found: ${args.id}`,
@@ -604,7 +643,7 @@ export class ToolHandlers {
604
643
  }
605
644
  const removed = this.library.removeNotebook(args.id);
606
645
  if (removed) {
607
- const closedSessions = await this.sessionManager.closeSessionsForNotebook(notebook.url);
646
+ const closedSessions = await this.sessionManager.closeSessionsForNotebook(notebook.url, this.ownerId);
608
647
  log.success(`✅ [TOOL] remove_notebook completed`);
609
648
  return {
610
649
  success: true,
@@ -612,7 +651,7 @@ export class ToolHandlers {
612
651
  };
613
652
  }
614
653
  else {
615
- log.warning(`⚠️ [TOOL] Notebook not found: ${args.id}`);
654
+ log.warning(`⚠️ [TOOL] Notebook not found: ${hashLogValue(args.id)}`);
616
655
  return {
617
656
  success: false,
618
657
  error: `Notebook not found: ${args.id}`,
@@ -633,7 +672,7 @@ export class ToolHandlers {
633
672
  */
634
673
  async handleSearchNotebooks(args) {
635
674
  log.info(`🔧 [TOOL] search_notebooks called`);
636
- log.info(` Query: "${args.query}"`);
675
+ log.info(` Search query characters: ${args.query.length}`);
637
676
  try {
638
677
  const notebooks = this.library.searchNotebooks(args.query);
639
678
  log.success(`✅ [TOOL] search_notebooks completed (${notebooks.length} results)`);
@@ -676,30 +715,28 @@ export class ToolHandlers {
676
715
  /**
677
716
  * Handle cleanup_data tool
678
717
  *
679
- * ULTRATHINK Deep Cleanup - scans entire system for ALL NotebookLM MCP files
718
+ * Constrained, token-bound cleanup of NOTEBOOKLM_DATA_DIR only.
680
719
  */
681
720
  async handleCleanupData(args) {
682
- const { confirm, preserve_library = false } = args;
721
+ const { confirm, preserve_library = false, preview_token } = args;
683
722
  log.info(`🔧 [TOOL] cleanup_data called`);
684
723
  log.info(` Confirm: ${confirm}`);
685
724
  log.info(` Preserve Library: ${preserve_library}`);
686
- const cleanupManager = new CleanupManager();
687
725
  try {
688
- // Always run in deep mode
689
- const mode = "deep";
726
+ const mode = "data";
690
727
  if (!confirm) {
691
- // Preview mode - show what would be deleted
692
- log.info(` 📋 Generating cleanup preview (mode: ${mode})...`);
693
- const preview = await cleanupManager.getCleanupPaths(mode, preserve_library);
694
- const platformInfo = cleanupManager.getPlatformInfo();
695
- log.info(` Found ${preview.totalPaths.length} items (${cleanupManager.formatBytes(preview.totalSizeBytes)})`);
696
- log.info(` Platform: ${platformInfo.platform}`);
728
+ await this.sessionManager.prepareForCleanup();
729
+ const preview = await this.cleanupManager.createPreview(preserve_library);
730
+ log.info(` Found ${preview.totalPaths.length} owned items (${this.cleanupManager.formatBytes(preview.totalSizeBytes)})`);
697
731
  return {
698
732
  success: true,
699
733
  data: {
700
734
  status: "preview",
701
735
  mode,
702
736
  preview: {
737
+ preview_token: preview.previewToken,
738
+ expires_at: preview.expiresAt,
739
+ path_digest: preview.pathDigest,
703
740
  categories: preview.categories,
704
741
  totalPaths: preview.totalPaths.length,
705
742
  totalSizeBytes: preview.totalSizeBytes,
@@ -708,9 +745,14 @@ export class ToolHandlers {
708
745
  };
709
746
  }
710
747
  else {
711
- // Cleanup mode - actually delete files
712
- log.info(` 🗑️ Performing cleanup (mode: ${mode})...`);
713
- const result = await cleanupManager.performCleanup(mode, preserve_library);
748
+ if (!preview_token) {
749
+ return {
750
+ success: false,
751
+ error: "preview_token is required when confirm=true; generate a fresh preview first",
752
+ };
753
+ }
754
+ await this.sessionManager.prepareForCleanup();
755
+ const result = await this.cleanupManager.performCleanup(preview_token);
714
756
  if (result.success) {
715
757
  log.success(`✅ [TOOL] cleanup_data completed - deleted ${result.deletedPaths.length} items`);
716
758
  }
@@ -760,19 +802,19 @@ export class ToolHandlers {
760
802
  /**
761
803
  * Handle add_source tool (issue #25).
762
804
  */
763
- async handleAddSource(args) {
805
+ async handleAddSource(args, signal) {
764
806
  log.info(`🔧 [TOOL] add_source called (type=${args.type})`);
765
807
  const effectiveConfig = applyBrowserOptions(undefined, args.show_browser);
766
808
  const overrideHeadless = args.show_browser === undefined ? undefined : args.show_browser;
767
809
  return await withRuntimeConfig(effectiveConfig, async () => {
768
810
  try {
769
811
  const url = await this.resolveNotebookUrl(args.notebook_id, args.notebook_url);
770
- const session = await this.sessionManager.getOrCreateSession(args.session_id, url, overrideHeadless);
812
+ const session = await this.sessionManager.getOrCreateSession(args.session_id, url, overrideHeadless, this.ownerId);
771
813
  const result = await session.addSource({
772
814
  type: args.type,
773
815
  content: args.content,
774
816
  title: args.title,
775
- });
817
+ }, signal);
776
818
  return { success: result.success, data: { result } };
777
819
  }
778
820
  catch (error) {
@@ -782,22 +824,183 @@ export class ToolHandlers {
782
824
  }
783
825
  });
784
826
  }
827
+ async handleListSources(args, signal) {
828
+ log.info(`🔧 [TOOL] list_sources called`);
829
+ const effectiveConfig = applyBrowserOptions(undefined, args.show_browser);
830
+ const overrideHeadless = args.show_browser === undefined ? undefined : args.show_browser;
831
+ return await withRuntimeConfig(effectiveConfig, async () => {
832
+ try {
833
+ const url = await this.resolveNotebookUrl(args.notebook_id, args.notebook_url);
834
+ const session = await this.sessionManager.getOrCreateSession(args.session_id, url, overrideHeadless, this.ownerId);
835
+ const sources = await session.listSources(signal);
836
+ return { success: true, data: { sources, count: sources.length } };
837
+ }
838
+ catch (error) {
839
+ const message = error instanceof Error ? error.message : String(error);
840
+ return { success: false, error: message };
841
+ }
842
+ });
843
+ }
844
+ async handleGetSource(args, signal) {
845
+ log.info(`🔧 [TOOL] get_source called`);
846
+ const effectiveConfig = applyBrowserOptions(undefined, args.show_browser);
847
+ const overrideHeadless = args.show_browser === undefined ? undefined : args.show_browser;
848
+ return await withRuntimeConfig(effectiveConfig, async () => {
849
+ try {
850
+ const url = await this.resolveNotebookUrl(args.notebook_id, args.notebook_url);
851
+ const session = await this.sessionManager.getOrCreateSession(args.session_id, url, overrideHeadless, this.ownerId);
852
+ const source = await session.getSource({ sourceId: args.source_id, name: args.name }, signal);
853
+ if (!source)
854
+ return { success: false, error: "Source not found" };
855
+ return { success: true, data: { source } };
856
+ }
857
+ catch (error) {
858
+ const message = error instanceof Error ? error.message : String(error);
859
+ return { success: false, error: message };
860
+ }
861
+ });
862
+ }
863
+ async handleBatchAddSources(args, signal) {
864
+ log.info(`🔧 [TOOL] batch_add_sources called (${args.sources.length} sources)`);
865
+ const effectiveConfig = applyBrowserOptions(undefined, args.show_browser);
866
+ const overrideHeadless = args.show_browser === undefined ? undefined : args.show_browser;
867
+ return await withRuntimeConfig(effectiveConfig, async () => {
868
+ try {
869
+ const url = await this.resolveNotebookUrl(args.notebook_id, args.notebook_url);
870
+ const session = await this.sessionManager.getOrCreateSession(args.session_id, url, overrideHeadless, this.ownerId);
871
+ const results = [];
872
+ for (const source of args.sources) {
873
+ const result = await session.addSource(source, signal);
874
+ results.push(result);
875
+ if (!result.success && args.stop_on_error !== false)
876
+ break;
877
+ }
878
+ const added = results.filter((result) => result.success).length;
879
+ return {
880
+ success: added === results.length,
881
+ data: { results, added, failed: results.length - added },
882
+ };
883
+ }
884
+ catch (error) {
885
+ const message = error instanceof Error ? error.message : String(error);
886
+ return { success: false, error: message };
887
+ }
888
+ });
889
+ }
890
+ async handleGenerateArtifact(args, signal) {
891
+ const effectiveConfig = applyBrowserOptions(undefined, args.show_browser);
892
+ const overrideHeadless = args.show_browser === undefined ? undefined : args.show_browser;
893
+ return await withRuntimeConfig(effectiveConfig, async () => {
894
+ const url = await this.resolveNotebookUrl(args.notebook_id, args.notebook_url);
895
+ if (!url)
896
+ throw new Error("No notebook selected. Provide notebook_id or notebook_url.");
897
+ const job = this.artifactStore.create(ARTIFACT_OWNER_ID, url, args.type);
898
+ try {
899
+ const session = await this.sessionManager.getOrCreateSession(args.session_id, url, overrideHeadless, this.ownerId);
900
+ const result = await session.generateAudio({
901
+ customPrompt: args.custom_prompt,
902
+ waitForCompletion: args.wait_for_completion,
903
+ timeoutMs: args.timeout_ms,
904
+ }, signal);
905
+ const status = result.status === "ready"
906
+ ? "ready"
907
+ : result.status === "error"
908
+ ? "error"
909
+ : result.status === "started"
910
+ ? "started"
911
+ : "in_progress";
912
+ const updated = this.artifactStore.update(job.job_id, ARTIFACT_OWNER_ID, {
913
+ status,
914
+ artifact_id: status === "ready" ? `audio-overview:${this.notebookKey(url)}` : null,
915
+ message: result.message,
916
+ });
917
+ return { success: status !== "error", data: { job: updated } };
918
+ }
919
+ catch (error) {
920
+ const message = error instanceof Error ? error.message : String(error);
921
+ this.artifactStore.update(job.job_id, ARTIFACT_OWNER_ID, { status: "error", message });
922
+ return { success: false, error: message };
923
+ }
924
+ });
925
+ }
926
+ async handleListArtifacts(args) {
927
+ try {
928
+ const hasTarget = Boolean(args.notebook_id || args.notebook_url);
929
+ const url = hasTarget
930
+ ? await this.resolveNotebookUrl(args.notebook_id, args.notebook_url)
931
+ : undefined;
932
+ return {
933
+ success: true,
934
+ data: { artifacts: this.artifactStore.list(ARTIFACT_OWNER_ID, url) },
935
+ };
936
+ }
937
+ catch (error) {
938
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
939
+ }
940
+ }
941
+ async handleGetArtifactStatus(args, signal) {
942
+ const job = this.artifactStore.get(args.job_id, ARTIFACT_OWNER_ID);
943
+ if (!job)
944
+ return { success: false, error: "Artifact job not found" };
945
+ const effectiveConfig = applyBrowserOptions(undefined, args.show_browser);
946
+ return await withRuntimeConfig(effectiveConfig, async () => {
947
+ try {
948
+ const session = await this.sessionManager.getOrCreateSession(undefined, job.notebook_url, args.show_browser, this.ownerId);
949
+ const result = await session.getAudioStatus(signal);
950
+ const status = result.status === "not_started" ? "error" : result.status;
951
+ const updated = this.artifactStore.update(job.job_id, ARTIFACT_OWNER_ID, {
952
+ status,
953
+ artifact_id: status === "ready"
954
+ ? (job.artifact_id ?? `audio-overview:${this.notebookKey(job.notebook_url)}`)
955
+ : job.artifact_id,
956
+ message: result.message,
957
+ });
958
+ return { success: status !== "error", data: { job: updated } };
959
+ }
960
+ catch (error) {
961
+ const message = error instanceof Error ? error.message : String(error);
962
+ return { success: false, error: message };
963
+ }
964
+ });
965
+ }
966
+ async handleDownloadArtifact(args, signal) {
967
+ const job = this.artifactStore.get(args.job_id, ARTIFACT_OWNER_ID);
968
+ if (!job)
969
+ return { success: false, error: "Artifact job not found" };
970
+ try {
971
+ resolveOutputDirectory(args.destination_dir);
972
+ const session = await this.sessionManager.getOrCreateSession(undefined, job.notebook_url, args.show_browser, this.ownerId);
973
+ const result = await session.downloadAudio(args.destination_dir, signal);
974
+ const updated = this.artifactStore.update(job.job_id, ARTIFACT_OWNER_ID, {
975
+ ...(result.success && { status: "ready" }),
976
+ ...(result.filePath && { file_path: result.filePath }),
977
+ message: result.message,
978
+ });
979
+ return { success: result.success, data: { job: updated, result } };
980
+ }
981
+ catch (error) {
982
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
983
+ }
984
+ }
985
+ notebookKey(url) {
986
+ return url.match(/\/notebook\/([^/?#]+)/)?.[1] ?? hashLogValue(url);
987
+ }
785
988
  /**
786
989
  * Handle generate_audio tool (issue #11).
787
990
  */
788
- async handleGenerateAudio(args) {
991
+ async handleGenerateAudio(args, signal) {
789
992
  log.info(`🔧 [TOOL] generate_audio called`);
790
993
  const effectiveConfig = applyBrowserOptions(undefined, args.show_browser);
791
994
  const overrideHeadless = args.show_browser === undefined ? undefined : args.show_browser;
792
995
  return await withRuntimeConfig(effectiveConfig, async () => {
793
996
  try {
794
997
  const url = await this.resolveNotebookUrl(args.notebook_id, args.notebook_url);
795
- const session = await this.sessionManager.getOrCreateSession(args.session_id, url, overrideHeadless);
998
+ const session = await this.sessionManager.getOrCreateSession(args.session_id, url, overrideHeadless, this.ownerId);
796
999
  const result = await session.generateAudio({
797
1000
  customPrompt: args.custom_prompt,
798
1001
  timeoutMs: args.timeout_ms,
799
1002
  waitForCompletion: args.wait_for_completion ?? false,
800
- });
1003
+ }, signal);
801
1004
  // `started` and `in_progress` count as success — the generation is on
802
1005
  // its way; the caller polls `get_audio_status` for completion.
803
1006
  const ok = result.status === "ready" ||
@@ -815,15 +1018,15 @@ export class ToolHandlers {
815
1018
  /**
816
1019
  * Handle get_audio_status tool — non-blocking poll for Audio Overview state.
817
1020
  */
818
- async handleGetAudioStatus(args) {
1021
+ async handleGetAudioStatus(args, signal) {
819
1022
  log.info(`🔧 [TOOL] get_audio_status called`);
820
1023
  const effectiveConfig = applyBrowserOptions(undefined, args.show_browser);
821
1024
  const overrideHeadless = args.show_browser === undefined ? undefined : args.show_browser;
822
1025
  return await withRuntimeConfig(effectiveConfig, async () => {
823
1026
  try {
824
1027
  const url = await this.resolveNotebookUrl(args.notebook_id, args.notebook_url);
825
- const session = await this.sessionManager.getOrCreateSession(args.session_id, url, overrideHeadless);
826
- const result = await session.getAudioStatus();
1028
+ const session = await this.sessionManager.getOrCreateSession(args.session_id, url, overrideHeadless, this.ownerId);
1029
+ const result = await session.getAudioStatus(signal);
827
1030
  return { success: true, data: { result } };
828
1031
  }
829
1032
  catch (error) {
@@ -836,15 +1039,16 @@ export class ToolHandlers {
836
1039
  /**
837
1040
  * Handle download_audio tool (issue #11).
838
1041
  */
839
- async handleDownloadAudio(args) {
1042
+ async handleDownloadAudio(args, signal) {
840
1043
  log.info(`🔧 [TOOL] download_audio called`);
841
1044
  const effectiveConfig = applyBrowserOptions(undefined, args.show_browser);
842
1045
  const overrideHeadless = args.show_browser === undefined ? undefined : args.show_browser;
843
1046
  return await withRuntimeConfig(effectiveConfig, async () => {
844
1047
  try {
1048
+ resolveOutputDirectory(args.destination_dir);
845
1049
  const url = await this.resolveNotebookUrl(args.notebook_id, args.notebook_url);
846
- const session = await this.sessionManager.getOrCreateSession(args.session_id, url, overrideHeadless);
847
- const result = await session.downloadAudio(args.destination_dir);
1050
+ const session = await this.sessionManager.getOrCreateSession(args.session_id, url, overrideHeadless, this.ownerId);
1051
+ const result = await session.downloadAudio(args.destination_dir, signal);
848
1052
  return { success: result.success, data: { result } };
849
1053
  }
850
1054
  catch (error) {