@mindstone/mcp-server-google-workspace 0.4.2 → 0.5.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 (39) hide show
  1. package/README.md +43 -5
  2. package/dist/modules/docs/service.d.ts +76 -6
  3. package/dist/modules/docs/service.js +791 -103
  4. package/dist/modules/docs/tabCopy.d.ts +266 -0
  5. package/dist/modules/docs/tabCopy.js +794 -0
  6. package/dist/modules/docs/tabs.d.ts +161 -0
  7. package/dist/modules/docs/tabs.js +416 -0
  8. package/dist/modules/docs/types.d.ts +141 -1
  9. package/dist/modules/drive/service.d.ts +15 -0
  10. package/dist/modules/drive/service.js +77 -2
  11. package/dist/modules/drive/types.d.ts +1 -1
  12. package/dist/modules/sheets/a1Utils.d.ts +13 -0
  13. package/dist/modules/sheets/a1Utils.js +33 -7
  14. package/dist/modules/sheets/formatters.d.ts +33 -2
  15. package/dist/modules/sheets/formatters.js +84 -5
  16. package/dist/modules/sheets/service.d.ts +26 -1
  17. package/dist/modules/sheets/service.js +264 -8
  18. package/dist/modules/sheets/types.d.ts +71 -0
  19. package/dist/modules/sheets/types.js +12 -1
  20. package/dist/modules/sheets/writeGuards.js +2 -2
  21. package/dist/tools/definitions/destructive-overrides.json +8 -0
  22. package/dist/tools/definitions/docs.js +395 -9
  23. package/dist/tools/definitions/drive.js +9 -4
  24. package/dist/tools/definitions/open-world-overrides.json +8 -0
  25. package/dist/tools/definitions/sheets.js +177 -1
  26. package/dist/tools/docs-handlers.d.ts +125 -0
  27. package/dist/tools/docs-handlers.js +397 -15
  28. package/dist/tools/param-normalizer.js +16 -0
  29. package/dist/tools/server.js +35 -3
  30. package/dist/tools/sheets-handlers.d.ts +54 -1
  31. package/dist/tools/sheets-handlers.js +107 -13
  32. package/dist/tools/type-guards.d.ts +89 -0
  33. package/dist/tools/type-guards.js +190 -6
  34. package/dist/tools/types.d.ts +1 -1
  35. package/dist/utils/apiError.d.ts +6 -0
  36. package/dist/utils/apiError.js +12 -0
  37. package/dist/utils/tabPosition.d.ts +20 -0
  38. package/dist/utils/tabPosition.js +19 -0
  39. package/package.json +1 -1
@@ -1,17 +1,30 @@
1
1
  import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
2
2
  import { getAccountManager, resolveEmail } from '../modules/accounts/index.js';
3
3
  import { getDocsService } from '../modules/docs/index.js';
4
+ import { getDriveService } from '../modules/drive/index.js';
5
+ import { idFromUri } from '../modules/docs/tabCopy.js';
4
6
  import { extractDocumentIdFromUrl } from '../modules/docs/formatters.js';
5
7
  import { readAliasedBoolean, readAliasedNumber, readAliasedString, readAliasedValue } from './arg-aliases.js';
6
8
  import { wrapUntrustedContent, wrapUntrustedJsonStrings } from '../utils/untrusted-content.js';
7
9
  /**
8
10
  * Format DocumentResponse as human-readable text
9
11
  */
10
- function formatDocumentResponseAsText(doc) {
12
+ export function formatDocumentResponseAsText(doc) {
11
13
  const lines = [];
12
14
  lines.push(`Document: ${doc.title}`);
13
15
  lines.push(`URL: ${doc.documentUrl}`);
14
16
  lines.push(`ID: ${doc.documentId}`);
17
+ if (doc.requestedTab) {
18
+ const subTabs = doc.requestedTab.childCount ?? 0;
19
+ const subTabNote = subTabs > 0
20
+ ? ` (${subTabs} sub-tab${subTabs !== 1 ? 's' : ''}, not included — read them by tab_id)`
21
+ : '';
22
+ lines.push(`Tab: ${doc.requestedTab.path} [tabId: ${doc.requestedTab.tabId}]${subTabNote}`);
23
+ }
24
+ else if (doc.shownTab && doc.tabCount !== undefined && doc.tabCount > 1) {
25
+ lines.push(`Tabs: ${doc.tabCount} — showing the first tab "${doc.shownTab.title}" [tabId: ${doc.shownTab.tabId}]. ` +
26
+ 'Pass tab_id (or all_tabs: true) to read others; list_workspace_document_tabs shows the tree.');
27
+ }
15
28
  if (doc.truncated) {
16
29
  lines.push('Status: TRUNCATED (content exceeded limit)');
17
30
  }
@@ -22,23 +35,44 @@ function formatDocumentResponseAsText(doc) {
22
35
  return wrapUntrustedContent(lines.join('\n'), `google-workspace:docs:document/${doc.documentId}`);
23
36
  }
24
37
  /**
25
- * Format TabInfo array as human-readable text
38
+ * Format a document's tab tree as human-readable text: one line per tab,
39
+ * indented by nesting level and numbered by path (1., 1.1., 1.1.1.).
26
40
  */
27
- function formatTabsAsText(tabs) {
41
+ export function formatTabsAsText(result) {
42
+ const tabs = result.tabs;
28
43
  if (!tabs || tabs.length === 0) {
29
44
  return 'No tabs found.';
30
45
  }
46
+ const topLevel = tabs.filter((tab) => tab.nestingLevel === 0).length;
31
47
  const lines = [];
32
- lines.push(`Tabs: ${tabs.length} tab${tabs.length !== 1 ? 's' : ''}\n`);
48
+ lines.push(`Tabs: ${tabs.length} (${topLevel} top-level)\n`);
49
+ const numbers = new Map();
33
50
  for (const tab of tabs) {
34
- let line = `${tab.index + 1}. ${tab.title}`;
51
+ const parentNumber = tab.parentTabId !== null ? numbers.get(tab.parentTabId) ?? '' : '';
52
+ const number = `${parentNumber}${tab.index + 1}.`;
53
+ numbers.set(tab.tabId, number);
54
+ let line = `${' '.repeat(tab.nestingLevel)}${number} ${tab.title} [tabId: ${tab.tabId}]`;
55
+ if (tab.childCount > 0) {
56
+ line += ` (${tab.childCount} sub-tab${tab.childCount !== 1 ? 's' : ''})`;
57
+ }
35
58
  if (tab.wordCount !== undefined) {
36
59
  line += ` (${tab.wordCount} words)`;
37
60
  }
38
- line += ` [tabId: ${tab.tabId}]`;
39
61
  lines.push(line);
40
62
  }
41
- return wrapUntrustedContent(lines.join('\n'), 'google-workspace:docs:tabs');
63
+ return wrapUntrustedContent(lines.join('\n'), `google-workspace:docs:tabs/${result.documentId}`);
64
+ }
65
+ /**
66
+ * `Document: <title>` line for edit results, with the Google-authored title enveloped.
67
+ */
68
+ function formatEnvelopedDocumentLine(doc, documentId) {
69
+ return `Document: ${wrapUntrustedContent(doc.title ?? '', `google-workspace:docs:document/${documentId}`)}`;
70
+ }
71
+ /**
72
+ * ` (tab <id>)` suffix for the first line of a tab-scoped edit result (id only).
73
+ */
74
+ function tabSuffix(doc) {
75
+ return doc.requestedTab ? ` (tab ${doc.requestedTab.tabId})` : '';
42
76
  }
43
77
  /**
44
78
  * Read a Google Docs document
@@ -49,6 +83,11 @@ export async function handleReadDocument(args) {
49
83
  const documentId = readAliasedString(rawArgs, 'document_id', 'documentId');
50
84
  const maxChars = readAliasedNumber(rawArgs, 'max_chars', 'maxChars');
51
85
  const returnJson = readAliasedBoolean(rawArgs, 'return_json', 'returnJson');
86
+ const tabId = readAliasedString(rawArgs, 'tab_id', 'tabId');
87
+ const allTabs = readAliasedBoolean(rawArgs, 'all_tabs', 'allTabs');
88
+ if (tabId !== undefined && allTabs === true) {
89
+ throw new McpError(ErrorCode.InvalidParams, 'Pass either tab_id or all_tabs, not both.');
90
+ }
52
91
  // Resolve email - uses instance account if not provided, validates if provided
53
92
  const email = await resolveEmail(args);
54
93
  return await accountManager.withTokenRenewal(email, async () => {
@@ -56,6 +95,8 @@ export async function handleReadDocument(args) {
56
95
  const options = {
57
96
  maxChars,
58
97
  returnJson,
98
+ ...(tabId !== undefined ? { tabId } : {}),
99
+ ...(allTabs === true ? { allTabs } : {}),
59
100
  };
60
101
  const result = await docsService.getDocument(email, documentId, options);
61
102
  if (!result.success || !result.data) {
@@ -95,7 +136,9 @@ export async function handleCreateDocument(args) {
95
136
  */
96
137
  export async function handleAppendDocument(args) {
97
138
  const accountManager = getAccountManager();
98
- const documentId = readAliasedString(args, 'document_id', 'documentId');
139
+ const rawArgs = args;
140
+ const documentId = readAliasedString(rawArgs, 'document_id', 'documentId');
141
+ const tabId = readAliasedString(rawArgs, 'tab_id', 'tabId');
99
142
  // Resolve email - uses instance account if not provided, validates if provided
100
143
  const email = await resolveEmail(args);
101
144
  return await accountManager.withTokenRenewal(email, async () => {
@@ -103,13 +146,14 @@ export async function handleAppendDocument(args) {
103
146
  const options = {
104
147
  documentId: documentId,
105
148
  text: args.text,
149
+ ...(tabId !== undefined ? { tabId } : {}),
106
150
  };
107
151
  const result = await docsService.appendToDocument(email, options);
108
152
  if (!result.success || !result.data) {
109
153
  throw new McpError(ErrorCode.InternalError, result.error || 'Failed to append to document');
110
154
  }
111
155
  const docResponse = result.data;
112
- return `Text appended successfully!\n\nDocument: ${docResponse.title}\nURL: ${docResponse.documentUrl}`;
156
+ return `Text appended successfully!${tabSuffix(docResponse)}\n\n${formatEnvelopedDocumentLine(docResponse, documentId)}\nURL: ${docResponse.documentUrl}`;
113
157
  });
114
158
  }
115
159
  /**
@@ -117,7 +161,9 @@ export async function handleAppendDocument(args) {
117
161
  */
118
162
  export async function handleReplaceDocument(args) {
119
163
  const accountManager = getAccountManager();
120
- const documentId = readAliasedString(args, 'document_id', 'documentId');
164
+ const rawArgs = args;
165
+ const documentId = readAliasedString(rawArgs, 'document_id', 'documentId');
166
+ const tabId = readAliasedString(rawArgs, 'tab_id', 'tabId');
121
167
  // Resolve email - uses instance account if not provided, validates if provided
122
168
  const email = await resolveEmail(args);
123
169
  return await accountManager.withTokenRenewal(email, async () => {
@@ -125,13 +171,14 @@ export async function handleReplaceDocument(args) {
125
171
  const options = {
126
172
  documentId: documentId,
127
173
  content: args.content,
174
+ ...(tabId !== undefined ? { tabId } : {}),
128
175
  };
129
176
  const result = await docsService.replaceDocument(email, options);
130
177
  if (!result.success || !result.data) {
131
178
  throw new McpError(ErrorCode.InternalError, result.error || 'Failed to replace document content');
132
179
  }
133
180
  const docResponse = result.data;
134
- return `Document content replaced successfully!\n\nDocument: ${docResponse.title}\nURL: ${docResponse.documentUrl}`;
181
+ return `Document content replaced successfully!${tabSuffix(docResponse)}\n\n${formatEnvelopedDocumentLine(docResponse, documentId)}\nURL: ${docResponse.documentUrl}`;
135
182
  });
136
183
  }
137
184
  /**
@@ -144,6 +191,7 @@ export async function handleFindAndReplace(args) {
144
191
  const findText = readAliasedString(rawArgs, 'find_text', 'findText');
145
192
  const replaceText = readAliasedString(rawArgs, 'replace_text', 'replaceText');
146
193
  const matchCase = readAliasedBoolean(rawArgs, 'match_case', 'matchCase');
194
+ const tabId = readAliasedString(rawArgs, 'tab_id', 'tabId');
147
195
  // Resolve email - uses instance account if not provided, validates if provided
148
196
  const email = await resolveEmail(args);
149
197
  return await accountManager.withTokenRenewal(email, async () => {
@@ -153,6 +201,7 @@ export async function handleFindAndReplace(args) {
153
201
  findText: findText,
154
202
  replaceText: replaceText,
155
203
  matchCase,
204
+ ...(tabId !== undefined ? { tabId } : {}),
156
205
  };
157
206
  const result = await docsService.findAndReplace(email, options);
158
207
  if (!result.success || !result.data) {
@@ -160,10 +209,17 @@ export async function handleFindAndReplace(args) {
160
209
  }
161
210
  const occurrences = result.occurrencesChanged ?? 0;
162
211
  const docResponse = result.data;
212
+ const documentLine = formatEnvelopedDocumentLine(docResponse, documentId);
213
+ // Without tab_id the replace covers every tab; say so on multi-tab documents.
214
+ const scopeNote = tabId === undefined && (docResponse.tabCount ?? 0) > 1
215
+ ? `\nSearched all ${docResponse.tabCount} tabs. Pass tab_id to limit a replace to one tab.`
216
+ : '';
163
217
  if (occurrences === 0) {
164
- return `No occurrences of "${findText}" found in the document.\n\nDocument: ${docResponse.title}\nURL: ${docResponse.documentUrl}`;
218
+ // A tab-scoped miss names the tab searched, not the whole document.
219
+ const searched = docResponse.requestedTab ? `tab ${docResponse.requestedTab.tabId}` : 'the document';
220
+ return `No occurrences of "${findText}" found in ${searched}.\n\n${documentLine}\nURL: ${docResponse.documentUrl}${scopeNote}`;
165
221
  }
166
- return `Find and replace completed!\n\nReplaced ${occurrences} occurrence${occurrences !== 1 ? 's' : ''} of "${findText}" with "${replaceText}"\n\nDocument: ${docResponse.title}\nURL: ${docResponse.documentUrl}`;
222
+ return `Find and replace completed!${tabSuffix(docResponse)}\n\nReplaced ${occurrences} occurrence${occurrences !== 1 ? 's' : ''} of "${findText}" with "${replaceText}"\n\n${documentLine}\nURL: ${docResponse.documentUrl}${scopeNote}`;
167
223
  });
168
224
  }
169
225
  /**
@@ -184,6 +240,7 @@ export async function handleListDocumentTabs(args) {
184
240
  const rawArgs = args;
185
241
  const documentId = readAliasedString(rawArgs, 'document_id', 'documentId');
186
242
  const includeWordCount = readAliasedBoolean(rawArgs, 'include_word_count', 'includeWordCount');
243
+ const returnJson = readAliasedBoolean(rawArgs, 'return_json', 'returnJson');
187
244
  // Resolve email - uses instance account if not provided, validates if provided
188
245
  const email = await resolveEmail(args);
189
246
  return await accountManager.withTokenRenewal(email, async () => {
@@ -196,8 +253,16 @@ export async function handleListDocumentTabs(args) {
196
253
  if (!result.success || !result.data) {
197
254
  throw new McpError(ErrorCode.InternalError, result.error || 'Failed to list document tabs');
198
255
  }
199
- const tabs = result.data;
200
- return formatTabsAsText(tabs);
256
+ const tabList = result.data;
257
+ if (returnJson) {
258
+ return wrapUntrustedJsonStrings({
259
+ documentId: tabList.documentId,
260
+ title: tabList.title,
261
+ tabCount: tabList.tabs.length,
262
+ tabs: tabList.tabs,
263
+ }, `google-workspace:docs:tabs/${tabList.documentId}`);
264
+ }
265
+ return formatTabsAsText(tabList);
201
266
  });
202
267
  }
203
268
  /**
@@ -247,4 +312,321 @@ export async function handleBatchUpdateDocument(args) {
247
312
  return lines.join('\n');
248
313
  });
249
314
  }
315
+ /**
316
+ * `under "<parent path>"` / `at the top level` for a tab's placement.
317
+ */
318
+ function placementPhrase(parent) {
319
+ return parent ? `under "${parent.path}"` : 'at the top level';
320
+ }
321
+ /**
322
+ * A WARNING line naming any difference between where the caller asked the tab
323
+ * to go and where the document reports it after the write (no silent mismatch).
324
+ */
325
+ function placementMismatch(data) {
326
+ const notes = [];
327
+ const actualParent = data.parent?.tabId ?? null;
328
+ if (actualParent !== data.requestedParentTabId) {
329
+ const wanted = data.requestedParentTabId !== null
330
+ ? `under tab ${data.requestedParentTabId}`
331
+ : 'at the top level';
332
+ notes.push(`it was meant to go ${wanted}, but the document shows it ${placementPhrase(data.parent)}`);
333
+ }
334
+ if (data.tab.index !== data.requestedPosition) {
335
+ notes.push(`the requested position was ${data.requestedPosition}, but the document reports position ${data.tab.index}`);
336
+ }
337
+ return notes.length > 0 ? `WARNING: ${notes.join('; ')}. Check the tab list before going on.` : undefined;
338
+ }
339
+ /**
340
+ * Result of add_workspace_document_tab (titles enveloped).
341
+ */
342
+ export function formatTabAddedAsText(data) {
343
+ const where = data.parent
344
+ ? `under "${data.parent.path}" at position ${data.tab.index}`
345
+ : `at the top level, position ${data.tab.index}`;
346
+ const lines = [`Tab added: "${data.tab.title}" [tabId: ${data.tab.tabId}] ${where} (0 = first).`];
347
+ const mismatch = placementMismatch(data);
348
+ if (mismatch)
349
+ lines.push(mismatch);
350
+ return wrapUntrustedContent(lines.join('\n'), `google-workspace:docs:tabs/${data.documentId}`);
351
+ }
352
+ /**
353
+ * Result of update_workspace_document_tab (titles enveloped).
354
+ */
355
+ export function formatTabUpdatedAsText(data) {
356
+ if (!data.changed) {
357
+ return wrapUntrustedContent(`No change: tab "${data.tab.path}" [tabId: ${data.tab.tabId}] already has that title, parent and position.`, `google-workspace:docs:tabs/${data.documentId}`);
358
+ }
359
+ const lines = [
360
+ `Tab updated: "${data.tab.title}" [tabId: ${data.tab.tabId}] — now ${placementPhrase(data.parent)}, position ${data.tab.index} (0 = first).`,
361
+ ];
362
+ const mismatch = placementMismatch(data);
363
+ if (mismatch)
364
+ lines.push(mismatch);
365
+ return wrapUntrustedContent(lines.join('\n'), `google-workspace:docs:tabs/${data.documentId}`);
366
+ }
367
+ /**
368
+ * Result of delete_workspace_document_tab: the tab and every sub-tab deleted with it.
369
+ */
370
+ export function formatTabDeletedAsText(data) {
371
+ const head = `Deleted tab "${data.deleted.path}" [tabId: ${data.deleted.tabId}]`;
372
+ const count = data.descendants.length;
373
+ const text = count === 0
374
+ ? `${head}. It had no sub-tabs.`
375
+ : [
376
+ `${head} and ${count} sub-tab${count !== 1 ? 's' : ''}:`,
377
+ ...data.descendants.map((tab) => `- "${tab.path}" [tabId: ${tab.tabId}]`),
378
+ ].join('\n');
379
+ return wrapUntrustedContent(text, `google-workspace:docs:tabs/${data.documentId}`);
380
+ }
381
+ const INSERT_POSITION_PHRASES = {
382
+ after: 'after the anchor',
383
+ before: 'before the anchor',
384
+ next_paragraph_start: 'at the start of the paragraph after the anchor',
385
+ };
386
+ /**
387
+ * Result of insert_workspace_document_text (tab title enveloped).
388
+ */
389
+ export function formatInsertTextAsText(data) {
390
+ const target = data.targetParagraph;
391
+ const text = `Inserted ${data.insertedChars} characters (${data.newParagraphs} new paragraph${data.newParagraphs !== 1 ? 's' : ''}) ` +
392
+ `${INSERT_POSITION_PHRASES[data.position]} in tab "${data.tab.path}" [tabId: ${data.tab.tabId}]. ` +
393
+ `The paragraph there was ${target.wasEmpty ? 'empty' : 'not empty'}, ${target.bulleted ? 'bulleted' : 'not bulleted'}, style ${target.namedStyleType}.` +
394
+ (data.removedChars > 0
395
+ ? ` ${data.removedChars} control or private-use character${data.removedChars !== 1 ? 's' : ''} that Google Docs can't store ${data.removedChars !== 1 ? 'were' : 'was'} left out.`
396
+ : '');
397
+ return wrapUntrustedContent(text, `google-workspace:docs:document/${data.documentId}`);
398
+ }
399
+ /**
400
+ * `position` as a number, or undefined (the type guard has already checked it).
401
+ */
402
+ function readPosition(rawArgs) {
403
+ return typeof rawArgs.position === 'number' ? rawArgs.position : undefined;
404
+ }
405
+ /**
406
+ * Add a tab to a Google Docs document
407
+ */
408
+ export async function handleAddDocumentTab(args) {
409
+ const accountManager = getAccountManager();
410
+ const rawArgs = args;
411
+ const documentId = readAliasedString(rawArgs, 'document_id', 'documentId');
412
+ const parentTabId = readAliasedString(rawArgs, 'parent_tab_id', 'parentTabId');
413
+ const position = readPosition(rawArgs);
414
+ const email = await resolveEmail(args);
415
+ return await accountManager.withTokenRenewal(email, async () => {
416
+ const result = await getDocsService().addTab(email, {
417
+ documentId: documentId,
418
+ title: args.title,
419
+ ...(parentTabId !== undefined ? { parentTabId } : {}),
420
+ ...(position !== undefined ? { position } : {}),
421
+ });
422
+ if (!result.success || !result.data) {
423
+ throw new McpError(ErrorCode.InternalError, result.error || 'Failed to add document tab');
424
+ }
425
+ return formatTabAddedAsText(result.data);
426
+ });
427
+ }
428
+ /**
429
+ * Rename and/or move a tab in a Google Docs document
430
+ */
431
+ export async function handleUpdateDocumentTab(args) {
432
+ const accountManager = getAccountManager();
433
+ const rawArgs = args;
434
+ const documentId = readAliasedString(rawArgs, 'document_id', 'documentId');
435
+ const tabId = readAliasedString(rawArgs, 'tab_id', 'tabId');
436
+ const parentTabId = readAliasedString(rawArgs, 'parent_tab_id', 'parentTabId');
437
+ const position = readPosition(rawArgs);
438
+ const email = await resolveEmail(args);
439
+ return await accountManager.withTokenRenewal(email, async () => {
440
+ const result = await getDocsService().updateTab(email, {
441
+ documentId: documentId,
442
+ tabId: tabId,
443
+ ...(args.title !== undefined ? { title: args.title } : {}),
444
+ ...(parentTabId !== undefined ? { parentTabId } : {}),
445
+ ...(position !== undefined ? { position } : {}),
446
+ });
447
+ if (!result.success || !result.data) {
448
+ throw new McpError(ErrorCode.InternalError, result.error || 'Failed to update document tab');
449
+ }
450
+ return formatTabUpdatedAsText(result.data);
451
+ });
452
+ }
453
+ /**
454
+ * Delete a tab (and all its sub-tabs) from a Google Docs document
455
+ */
456
+ export async function handleDeleteDocumentTab(args) {
457
+ const accountManager = getAccountManager();
458
+ const rawArgs = args;
459
+ const documentId = readAliasedString(rawArgs, 'document_id', 'documentId');
460
+ const tabId = readAliasedString(rawArgs, 'tab_id', 'tabId');
461
+ const deleteSubTabs = readAliasedBoolean(rawArgs, 'delete_sub_tabs', 'deleteSubTabs');
462
+ const email = await resolveEmail(args);
463
+ return await accountManager.withTokenRenewal(email, async () => {
464
+ const result = await getDocsService().deleteTab(email, {
465
+ documentId: documentId,
466
+ tabId: tabId,
467
+ ...(deleteSubTabs === true ? { deleteSubTabs } : {}),
468
+ });
469
+ if (!result.success || !result.data) {
470
+ throw new McpError(ErrorCode.InternalError, result.error || 'Failed to delete document tab');
471
+ }
472
+ return formatTabDeletedAsText(result.data);
473
+ });
474
+ }
475
+ /**
476
+ * Insert plain text into one tab next to a unique anchor
477
+ */
478
+ export async function handleInsertDocumentText(args) {
479
+ const accountManager = getAccountManager();
480
+ const rawArgs = args;
481
+ const documentId = readAliasedString(rawArgs, 'document_id', 'documentId');
482
+ const tabId = readAliasedString(rawArgs, 'tab_id', 'tabId');
483
+ const anchorText = readAliasedString(rawArgs, 'anchor_text', 'anchorText');
484
+ const matchCase = readAliasedBoolean(rawArgs, 'match_case', 'matchCase');
485
+ const expectEmptyParagraph = readAliasedBoolean(rawArgs, 'expect_empty_paragraph', 'expectEmptyParagraph');
486
+ const position = (typeof rawArgs.position === 'string' ? rawArgs.position : 'after');
487
+ const email = await resolveEmail(args);
488
+ return await accountManager.withTokenRenewal(email, async () => {
489
+ const result = await getDocsService().insertText(email, {
490
+ documentId: documentId,
491
+ ...(tabId !== undefined ? { tabId } : {}),
492
+ anchorText: anchorText,
493
+ position,
494
+ text: args.text,
495
+ matchCase: matchCase ?? true,
496
+ // Unset → the service's default (on for next_paragraph_start); an explicit false is kept.
497
+ ...(expectEmptyParagraph !== undefined ? { expectEmptyParagraph } : {}),
498
+ });
499
+ if (!result.success || !result.data) {
500
+ throw new McpError(ErrorCode.InternalError, result.error || 'Failed to insert text');
501
+ }
502
+ return formatInsertTextAsText(result.data);
503
+ });
504
+ }
505
+ /** Plain-language names for element kinds a copy can't reproduce. */
506
+ const NOT_COPIED_LABELS = {
507
+ inlineObjectElement: 'images',
508
+ positionedObject: 'floating images',
509
+ footnoteReference: 'footnotes',
510
+ equation: 'equations',
511
+ horizontalRule: 'horizontal lines',
512
+ columnBreak: 'column breaks',
513
+ autoText: 'page numbers and other auto text',
514
+ tableOfContents: 'tables of contents',
515
+ person: 'people chips without a name or email',
516
+ dateElement: 'date chips without display text',
517
+ richLink: 'smart chips without a link',
518
+ };
519
+ /** Chip-fallback titles listed by name in a copy result; the rest are counted. */
520
+ const MAX_FALLBACK_TITLES = 10;
521
+ function plural(n, word) {
522
+ return `${n} ${word}${n !== 1 ? 's' : ''}`;
523
+ }
524
+ /**
525
+ * Result of copy_workspace_document_tab: what was copied, the verification
526
+ * outcome, what fell back or was left out, and the cost. Titles, paths and
527
+ * chip titles are document content, so the whole result is enveloped.
528
+ */
529
+ export function formatTabCopyAsText(data) {
530
+ const lines = [];
531
+ const into = data.mode === 'new' ? 'new' : 'existing (cleared first)';
532
+ lines.push(`Copied tab "${data.source.path}" [${data.source.tabId}] into ${into} tab "${data.target.path}" [${data.target.tabId}].`);
533
+ const v = data.verification;
534
+ if (v.passed) {
535
+ let line = `Verification: passed — ${plural(v.checkedParagraphs, 'paragraph')}, ${plural(v.tables, 'table')}, ${plural(v.lists, 'list')} checked: ` +
536
+ 'text, heading types, paragraph formatting, bullets, list grouping and table shapes match the source ' +
537
+ '(bold/links and table cell styles are not checked).';
538
+ if (v.placeholders > 0) {
539
+ line += ` ${v.placeholders} placeholder(s) stand in for elements that could not be copied (see Not copied).`;
540
+ }
541
+ lines.push(line);
542
+ }
543
+ else {
544
+ const places = v.mismatches.map((mismatch) => mismatch.tableIndex !== undefined
545
+ ? `table ${mismatch.tableIndex + 1} ${mismatch.kind}`
546
+ : mismatch.paragraphIndex !== undefined
547
+ ? `paragraph ${mismatch.paragraphIndex + 1} ${mismatch.kind}`
548
+ : mismatch.kind);
549
+ // Verification keeps only the first few mismatches; say so when there are more.
550
+ const where = places.length === 0
551
+ ? 'first: unknown'
552
+ : `${places.length < v.mismatchCount ? 'first: ' : ''}${places.join(', ')}`;
553
+ const kept = data.mode === 'new'
554
+ ? ` The new tab "${data.target.path}" [${data.target.tabId}] was kept so it can be checked. If it isn't usable, delete it with delete_workspace_document_tab before copying again with the same title.`
555
+ : ` Tab "${data.target.path}" [${data.target.tabId}] was kept as copied so it can be checked; its earlier content can be restored from the document's version history.`;
556
+ lines.push(`Verification: FAILED — ${plural(v.mismatchCount, 'difference')} (${where}).${kept} Do not delete or reset the source until the copy is confirmed.`);
557
+ }
558
+ const fallbacks = data.chipFallbacks.length;
559
+ if (data.chipsCopied > 0 || fallbacks > 0) {
560
+ let line = `${plural(data.chipsCopied, 'smart chip')} copied`;
561
+ if (fallbacks > 0) {
562
+ const shown = data.chipFallbacks.slice(0, MAX_FALLBACK_TITLES).map((chip) => `"${chip.title}"`).join(', ');
563
+ const more = fallbacks > MAX_FALLBACK_TITLES ? `, and ${fallbacks - MAX_FALLBACK_TITLES} more` : '';
564
+ line += `; ${fallbacks} replaced by titled links because you can't open these files: ${shown}${more}`;
565
+ }
566
+ lines.push(`${line}.`);
567
+ }
568
+ const { people, dates } = data.convertedToText;
569
+ if (people > 0 || dates > 0) {
570
+ lines.push(`${people} people and ${dates} dates copied as text.`);
571
+ }
572
+ if (data.namedStylesCopied > 0) {
573
+ lines.push(`Named styles copied: ${data.namedStylesCopied}.`);
574
+ }
575
+ const notCopied = ['headers and footers', 'sub-tabs'];
576
+ for (const [kind, count] of Object.entries(data.notCopied)) {
577
+ notCopied.push(`${NOT_COPIED_LABELS[kind] ?? kind} (${count})`);
578
+ }
579
+ const lost = Object.keys(data.notCopied).length > 0
580
+ ? ' Check these can be lost before deleting or resetting the source.'
581
+ : '';
582
+ lines.push(`Not copied: ${notCopied.join(', ')}.${lost}`);
583
+ if (data.notes.length > 0) {
584
+ lines.push(`Notes: ${data.notes.join('; ')}.`);
585
+ }
586
+ lines.push(`Requests: ${data.requests} in ${data.rounds} rounds; took ${(data.durationMs / 1000).toFixed(1)}s.`);
587
+ return wrapUntrustedContent(lines.join('\n'), `google-workspace:docs:tab-copy/${data.documentId}`);
588
+ }
589
+ /**
590
+ * Copy one tab's content into a new tab or into an existing tab (cleared first)
591
+ */
592
+ export async function handleCopyDocumentTab(args) {
593
+ const accountManager = getAccountManager();
594
+ const rawArgs = args;
595
+ const documentId = readAliasedString(rawArgs, 'document_id', 'documentId');
596
+ const sourceTabId = readAliasedString(rawArgs, 'source_tab_id', 'sourceTabId');
597
+ const targetTabId = readAliasedString(rawArgs, 'target_tab_id', 'targetTabId');
598
+ const overwriteExisting = readAliasedBoolean(rawArgs, 'overwrite_existing', 'overwriteExisting');
599
+ const newTabTitle = readAliasedString(rawArgs, 'new_tab_title', 'newTabTitle');
600
+ const newTabParentId = readAliasedString(rawArgs, 'new_tab_parent_id', 'newTabParentId');
601
+ const newTabPosition = readAliasedNumber(rawArgs, 'new_tab_position', 'newTabPosition');
602
+ const email = await resolveEmail(args);
603
+ return await accountManager.withTokenRenewal(email, async () => {
604
+ const driveService = await getDriveService();
605
+ // Same account as the copy; a link that isn't a Drive file can't be checked, so it becomes a titled link.
606
+ const checkChip = (uri) => {
607
+ const fileId = idFromUri(uri);
608
+ return fileId ? driveService.checkFileAccess(email, fileId) : Promise.resolve(false);
609
+ };
610
+ const result = await getDocsService().copyTab(email, {
611
+ documentId: documentId,
612
+ sourceTabId: sourceTabId,
613
+ ...(targetTabId !== undefined ? { targetTabId } : {}),
614
+ ...(overwriteExisting !== undefined ? { overwriteExisting } : {}),
615
+ ...(newTabTitle !== undefined ? { newTabTitle } : {}),
616
+ ...(newTabParentId !== undefined ? { newTabParentId } : {}),
617
+ ...(newTabPosition !== undefined ? { newTabPosition } : {}),
618
+ }, checkChip);
619
+ if (!result.success || !result.data) {
620
+ throw new McpError(ErrorCode.InternalError, result.error || 'Failed to copy document tab');
621
+ }
622
+ const data = result.data;
623
+ const text = formatTabCopyAsText(data);
624
+ if (!data.verification.passed) {
625
+ // An error result keeps the full report while telling the host and model the copy is not good.
626
+ const response = { content: [{ type: 'text', text }], isError: true, _meta: {} };
627
+ return response;
628
+ }
629
+ return text;
630
+ });
631
+ }
250
632
  //# sourceMappingURL=docs-handlers.js.map
@@ -34,6 +34,18 @@ const LEGACY_ALIASES = {
34
34
  replaceText: 'replace_text',
35
35
  matchCase: 'match_case',
36
36
  includeWordCount: 'include_word_count',
37
+ tabId: 'tab_id',
38
+ allTabs: 'all_tabs',
39
+ parentTabId: 'parent_tab_id',
40
+ anchorText: 'anchor_text',
41
+ expectEmptyParagraph: 'expect_empty_paragraph',
42
+ deleteSubTabs: 'delete_sub_tabs',
43
+ sourceTabId: 'source_tab_id',
44
+ targetTabId: 'target_tab_id',
45
+ overwriteExisting: 'overwrite_existing',
46
+ newTabTitle: 'new_tab_title',
47
+ newTabParentId: 'new_tab_parent_id',
48
+ newTabPosition: 'new_tab_position',
37
49
  writeControl: 'write_control',
38
50
  spreadsheetId: 'spreadsheet_id',
39
51
  maxRows: 'max_rows',
@@ -46,6 +58,10 @@ const LEGACY_ALIASES = {
46
58
  valueInputOption: 'value_input_option',
47
59
  overwriteFormulas: 'overwrite_formulas',
48
60
  sheetId: 'sheet_id',
61
+ newTitle: 'new_title',
62
+ sheetTitle: 'sheet_title',
63
+ startIndex: 'start_index',
64
+ inheritFrom: 'inherit_from',
49
65
  rowCount: 'row_count',
50
66
  columnCount: 'column_count',
51
67
  matchEntireCell: 'match_entire_cell',
@@ -18,13 +18,13 @@ import { handleListDriveFiles, handleSearchDriveFiles, handleListSharedDrives, h
18
18
  // Import contact handlers
19
19
  import { handleGetContacts, handleSearchContacts, handleCreateContact, handleUpdateContact } from './contacts-handlers.js';
20
20
  // Import docs handlers
21
- import { handleReadDocument, handleCreateDocument, handleAppendDocument, handleReplaceDocument, handleFindAndReplace, handleExtractDocumentId, handleListDocumentTabs, handleBatchUpdateDocument } from './docs-handlers.js';
21
+ import { handleReadDocument, handleCreateDocument, handleAppendDocument, handleReplaceDocument, handleFindAndReplace, handleExtractDocumentId, handleListDocumentTabs, handleBatchUpdateDocument, handleAddDocumentTab, handleUpdateDocumentTab, handleDeleteDocumentTab, handleInsertDocumentText, handleCopyDocumentTab } from './docs-handlers.js';
22
22
  // Import comments handlers
23
23
  import { handleListComments, handleCreateComment, handleResolveComment, handleReplyToComment, handleDeleteComment } from './comments-handlers.js';
24
24
  // Import slides handlers
25
25
  import { handleReadPresentation, handleCreatePresentation, handleListSlides, handleGetSlide, handleExtractPresentationId, handleBatchUpdatePresentation, handleGetSlideThumbnail } from './slides-handlers.js';
26
26
  // Import sheets handlers
27
- import { handleReadSpreadsheet, handleReadSpreadsheetValues, handleCreateSpreadsheet, handleAppendValues, handleUpdateValues, handleClearValues, handleListSheets, handleAddSheet, handleDeleteSheet, handleExtractSpreadsheetId, handleBatchGetValues, handleBatchUpdateValues, handleFindReplace, handleFormatCells } from './sheets-handlers.js';
27
+ import { handleReadSpreadsheet, handleReadSpreadsheetValues, handleCreateSpreadsheet, handleAppendValues, handleUpdateValues, handleClearValues, handleListSheets, handleAddSheet, handleDeleteSheet, handleDuplicateSheet, handleUpdateSheet, handleInsertDimension, handleExtractSpreadsheetId, handleBatchGetValues, handleBatchUpdateValues, handleFindReplace, handleFormatCells } from './sheets-handlers.js';
28
28
  // Import tasks handlers
29
29
  import { handleListTaskLists, handleListTasks, handleCreateTask, handleUpdateTask, handleCompleteTask, handleDeleteTask } from './tasks-handlers.js';
30
30
  // Import forms handlers
@@ -40,7 +40,7 @@ import { CalendarError } from '../modules/calendar/types.js';
40
40
  import { ContactsError } from '../modules/contacts/types.js';
41
41
  // Import service initializer
42
42
  import { initializeAllServices } from '../utils/service-initializer.js';
43
- import { assertBaseToolArguments, assertListCalendarsArgs, assertCalendarEventParams, assertEmailEventIdArgs, assertSendEmailArgs, assertManageDraftParams, assertManageLabelParams, assertManageLabelAssignmentParams, assertManageLabelFilterParams, assertDriveFileListArgs, assertDriveSearchArgs, assertListSharedDrivesArgs, assertDriveUploadArgs, assertDriveDownloadArgs, assertDriveFolderArgs, assertDrivePermissionArgs, assertDriveDeleteArgs, assertDriveCopyArgs, assertDriveMoveArgs, assertDriveTrashArgs, assertDriveRevisionsArgs, assertDriveDownloadRevisionArgs, assertManageAttachmentParams, assertGetContactsParams, assertReadDocumentArgs, assertCreateDocumentArgs, assertAppendDocumentArgs, assertReplaceDocumentArgs, assertFindReplaceArgs, assertExtractIdArgs, assertListTabsArgs, assertBatchUpdateDocumentArgs, assertReadPresentationArgs, assertCreatePresentationArgs, assertListSlidesArgs, assertGetSlideArgs, assertExtractPresentationIdArgs, assertReadSpreadsheetArgs, assertReadSpreadsheetValuesArgs, assertCreateSpreadsheetArgs, assertAppendSpreadsheetArgs, assertUpdateSpreadsheetValuesArgs, assertClearSpreadsheetValuesArgs, assertListSpreadsheetSheetsArgs, assertAddSpreadsheetSheetArgs, assertDeleteSpreadsheetSheetArgs, assertExtractSpreadsheetIdArgs, assertBatchGetSpreadsheetValuesArgs, assertBatchUpdateSpreadsheetValuesArgs, assertFindReplaceSpreadsheetArgs, assertFormatSpreadsheetCellsArgs, assertBatchUpdatePresentationArgs, assertGetSlideThumbnailArgs, assertListTaskListsArgs, assertListTasksArgs, assertCreateTaskArgs, assertUpdateTaskArgs, assertCompleteTaskArgs, assertDeleteTaskArgs, assertListFormsArgs, assertGetFormArgs, assertListFormResponsesArgs, assertGetFormResponseArgs, assertListCommentsArgs, assertCreateCommentArgs, assertResolveCommentArgs, assertReplyToCommentArgs, assertDeleteCommentArgs, assertGmailQuickActionArgs } from './type-guards.js';
43
+ import { assertBaseToolArguments, assertListCalendarsArgs, assertCalendarEventParams, assertEmailEventIdArgs, assertSendEmailArgs, assertManageDraftParams, assertManageLabelParams, assertManageLabelAssignmentParams, assertManageLabelFilterParams, assertDriveFileListArgs, assertDriveSearchArgs, assertListSharedDrivesArgs, assertDriveUploadArgs, assertDriveDownloadArgs, assertDriveFolderArgs, assertDrivePermissionArgs, assertDriveDeleteArgs, assertDriveCopyArgs, assertDriveMoveArgs, assertDriveTrashArgs, assertDriveRevisionsArgs, assertDriveDownloadRevisionArgs, assertManageAttachmentParams, assertGetContactsParams, assertReadDocumentArgs, assertCreateDocumentArgs, assertAppendDocumentArgs, assertReplaceDocumentArgs, assertFindReplaceArgs, assertExtractIdArgs, assertListTabsArgs, assertBatchUpdateDocumentArgs, assertAddDocumentTabArgs, assertUpdateDocumentTabArgs, assertDeleteDocumentTabArgs, assertInsertDocumentTextArgs, assertCopyDocumentTabArgs, assertReadPresentationArgs, assertCreatePresentationArgs, assertListSlidesArgs, assertGetSlideArgs, assertExtractPresentationIdArgs, assertReadSpreadsheetArgs, assertReadSpreadsheetValuesArgs, assertCreateSpreadsheetArgs, assertAppendSpreadsheetArgs, assertUpdateSpreadsheetValuesArgs, assertClearSpreadsheetValuesArgs, assertListSpreadsheetSheetsArgs, assertAddSpreadsheetSheetArgs, assertDuplicateSpreadsheetSheetArgs, assertUpdateSpreadsheetSheetArgs, assertInsertSpreadsheetDimensionArgs, assertDeleteSpreadsheetSheetArgs, assertExtractSpreadsheetIdArgs, assertBatchGetSpreadsheetValuesArgs, assertBatchUpdateSpreadsheetValuesArgs, assertFindReplaceSpreadsheetArgs, assertFormatSpreadsheetCellsArgs, assertBatchUpdatePresentationArgs, assertGetSlideThumbnailArgs, assertListTaskListsArgs, assertListTasksArgs, assertCreateTaskArgs, assertUpdateTaskArgs, assertCompleteTaskArgs, assertDeleteTaskArgs, assertListFormsArgs, assertGetFormArgs, assertListFormResponsesArgs, assertGetFormResponseArgs, assertListCommentsArgs, assertCreateCommentArgs, assertResolveCommentArgs, assertReplyToCommentArgs, assertDeleteCommentArgs, assertGmailQuickActionArgs } from './type-guards.js';
44
44
  import { COMPOSE_EMAIL_HTML } from '../resources/compose-email-template.js';
45
45
  import { normalizeArgs } from './param-normalizer.js';
46
46
  function isInlineUiToolResult(result) {
@@ -472,6 +472,26 @@ export class GSuiteServer {
472
472
  assertBatchUpdateDocumentArgs(args);
473
473
  result = await handleBatchUpdateDocument(args);
474
474
  break;
475
+ case 'add_workspace_document_tab':
476
+ assertAddDocumentTabArgs(args);
477
+ result = await handleAddDocumentTab(args);
478
+ break;
479
+ case 'update_workspace_document_tab':
480
+ assertUpdateDocumentTabArgs(args);
481
+ result = await handleUpdateDocumentTab(args);
482
+ break;
483
+ case 'delete_workspace_document_tab':
484
+ assertDeleteDocumentTabArgs(args);
485
+ result = await handleDeleteDocumentTab(args);
486
+ break;
487
+ case 'insert_workspace_document_text':
488
+ assertInsertDocumentTextArgs(args);
489
+ result = await handleInsertDocumentText(args);
490
+ break;
491
+ case 'copy_workspace_document_tab':
492
+ assertCopyDocumentTabArgs(args);
493
+ result = await handleCopyDocumentTab(args);
494
+ break;
475
495
  // Google Slides Operations
476
496
  case 'read_workspace_presentation':
477
497
  assertReadPresentationArgs(args);
@@ -559,6 +579,18 @@ export class GSuiteServer {
559
579
  assertDeleteSpreadsheetSheetArgs(args);
560
580
  result = await handleDeleteSheet(args);
561
581
  break;
582
+ case 'duplicate_workspace_spreadsheet_sheet':
583
+ assertDuplicateSpreadsheetSheetArgs(args);
584
+ result = await handleDuplicateSheet(args);
585
+ break;
586
+ case 'update_workspace_spreadsheet_sheet':
587
+ assertUpdateSpreadsheetSheetArgs(args);
588
+ result = await handleUpdateSheet(args);
589
+ break;
590
+ case 'insert_workspace_spreadsheet_dimension':
591
+ assertInsertSpreadsheetDimensionArgs(args);
592
+ result = await handleInsertDimension(args);
593
+ break;
562
594
  case 'extract_workspace_spreadsheet_id':
563
595
  assertExtractSpreadsheetIdArgs(args);
564
596
  result = await handleExtractSpreadsheetId(args);