@mindstone/mcp-server-google-workspace 0.5.3 → 0.5.4

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 (43) hide show
  1. package/README.md +19 -1
  2. package/dist/file-read-context.d.ts +57 -0
  3. package/dist/file-read-context.js +36 -0
  4. package/dist/modules/calendar/service.js +97 -90
  5. package/dist/modules/comments/service.js +6 -6
  6. package/dist/modules/docs/service.js +15 -11
  7. package/dist/modules/docs/types.d.ts +4 -0
  8. package/dist/modules/drive/service.js +1 -17
  9. package/dist/modules/forms/service.js +4 -4
  10. package/dist/modules/gmail/services/attachment.js +3 -1
  11. package/dist/modules/gmail/services/base.js +3 -1
  12. package/dist/modules/gmail/services/draft.js +13 -1
  13. package/dist/modules/gmail/services/email.js +13 -4
  14. package/dist/modules/gmail/services/label.js +19 -1
  15. package/dist/modules/gmail/services/settings.js +7 -1
  16. package/dist/modules/sheets/service.js +18 -18
  17. package/dist/modules/slides/service.js +7 -7
  18. package/dist/modules/tasks/service.js +7 -7
  19. package/dist/services/base/BaseGoogleService.js +2 -2
  20. package/dist/services/chat/index.js +3 -0
  21. package/dist/services/contacts/index.js +8 -5
  22. package/dist/services/meet/index.js +3 -0
  23. package/dist/tools/calendar-handlers.js +7 -7
  24. package/dist/tools/chat-handlers.js +4 -4
  25. package/dist/tools/contacts-handlers.js +5 -5
  26. package/dist/tools/definitions/gmail.js +4 -0
  27. package/dist/tools/docs-handlers.js +14 -6
  28. package/dist/tools/drive-handlers.d.ts +2 -1
  29. package/dist/tools/drive-handlers.js +21 -16
  30. package/dist/tools/gmail-handlers.d.ts +6 -5
  31. package/dist/tools/gmail-handlers.js +39 -27
  32. package/dist/tools/meet-handlers.js +4 -4
  33. package/dist/tools/server.js +24 -10
  34. package/dist/tools/sheets-handlers.js +4 -4
  35. package/dist/tools/slides-handlers.js +4 -4
  36. package/dist/utils/apiError.d.ts +7 -3
  37. package/dist/utils/apiError.js +37 -16
  38. package/dist/utils/google-retry.d.ts +15 -0
  39. package/dist/utils/google-retry.js +108 -0
  40. package/dist/utils/request-timeout.js +2 -0
  41. package/dist/utils/untrusted-content.d.ts +9 -0
  42. package/dist/utils/untrusted-content.js +37 -0
  43. package/package.json +3 -2
@@ -4,7 +4,7 @@ import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
4
4
  import { toMcpError } from '../utils/apiError.js';
5
5
  import { getAccountManager, validateEmail, resolveEmail } from '../modules/accounts/index.js';
6
6
  import { google } from 'googleapis';
7
- import { wrapUntrustedContent, wrapUntrustedJsonStrings } from '../utils/untrusted-content.js';
7
+ import { wrapUntrustedContent, wrapUntrustedJsonStrings, wrapUntrustedJsonControls } from '../utils/untrusted-content.js';
8
8
  // Singleton instances
9
9
  let driveService;
10
10
  let calendarService;
@@ -388,7 +388,7 @@ export async function handleListWorkspaceCalendars(params) {
388
388
  return accountManager.withTokenRenewal(email, async () => {
389
389
  try {
390
390
  const calendars = await calendarService.listCalendars(email);
391
- return wrapUntrustedJsonStrings(calendars, 'google-workspace:calendar:list');
391
+ return wrapUntrustedJsonControls(calendars, 'google-workspace:calendar:list', [], [], ['*.id']);
392
392
  }
393
393
  catch (error) {
394
394
  throw toMcpError(error, 'Failed to list calendars');
@@ -455,7 +455,7 @@ export async function handleListWorkspaceCalendarEvents(params) {
455
455
  const tzInfo = await resolveTimezone(email, events[0]?.start?.timeZone, deviceTimezone);
456
456
  // Return JSON if requested, otherwise format as human-readable text
457
457
  if (returnJson) {
458
- return wrapUntrustedJsonStrings({
458
+ return wrapUntrustedJsonControls({
459
459
  timezoneInfo: {
460
460
  resolved: tzInfo.resolved,
461
461
  source: tzInfo.source,
@@ -465,7 +465,7 @@ export async function handleListWorkspaceCalendarEvents(params) {
465
465
  },
466
466
  referenceTimeUTC: new Date().toISOString(),
467
467
  events
468
- }, 'google-workspace:calendar:events');
468
+ }, 'google-workspace:calendar:events', ['events.*.attachments.*.fileId'], ['events.*.id']);
469
469
  }
470
470
  return formatEventsAsText(events, tzInfo);
471
471
  }
@@ -485,7 +485,7 @@ export async function handleGetWorkspaceCalendarEvent(params) {
485
485
  }
486
486
  return accountManager.withTokenRenewal(email, async () => {
487
487
  try {
488
- return wrapUntrustedJsonStrings(await calendarService.getEvent(email, eventId, calendarId), `google-workspace:calendar:event/${eventId}`);
488
+ return wrapUntrustedJsonControls(await calendarService.getEvent(email, eventId, calendarId), `google-workspace:calendar:event/${eventId}`, ['attachments.*.fileId'], ['id']);
489
489
  }
490
490
  catch (error) {
491
491
  throw toMcpError(error, 'Failed to get calendar event');
@@ -582,7 +582,7 @@ export async function handleCreateWorkspaceCalendarEvent(params) {
582
582
  colorId,
583
583
  transparency
584
584
  });
585
- return wrapUntrustedJsonStrings(createdEvent, 'google-workspace:calendar:event/create');
585
+ return wrapUntrustedJsonControls(createdEvent, 'google-workspace:calendar:event/create', ['attachments.*.fileId'], ['id']);
586
586
  }
587
587
  catch (error) {
588
588
  // CalendarError here is operational (auth/permission/API failure), not caller-arg
@@ -619,7 +619,7 @@ export async function handleManageWorkspaceCalendarEvent(params) {
619
619
  newTimes,
620
620
  colorId
621
621
  });
622
- return wrapUntrustedJsonStrings(managedEvent, `google-workspace:calendar:event/${eventId}`);
622
+ return wrapUntrustedJsonControls(managedEvent, `google-workspace:calendar:event/${eventId}`, ['attachments.*.fileId'], ['eventId']);
623
623
  }
624
624
  catch (error) {
625
625
  throw toMcpError(error, 'Failed to manage calendar event');
@@ -3,7 +3,7 @@ import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
3
3
  import { toMcpError } from "../utils/apiError.js";
4
4
  import { getAccountManager, resolveEmail } from "../modules/accounts/index.js";
5
5
  import { readAliasedNumber, readAliasedString } from './arg-aliases.js';
6
- import { wrapUntrustedJsonStrings } from "../utils/untrusted-content.js";
6
+ import { wrapUntrustedJsonControls } from "../utils/untrusted-content.js";
7
7
  // Cap page sizes well below the Chat API maximum (1000) to keep responses manageable
8
8
  const MAX_CHAT_PAGE_SIZE = 100;
9
9
  // Google Chat documents a maximum TOTAL message size of 32,000 bytes
@@ -55,7 +55,7 @@ export async function handleListChatSpaces(params) {
55
55
  pageToken,
56
56
  filter
57
57
  });
58
- return wrapUntrustedJsonStrings(result, 'google-workspace:chat:spaces');
58
+ return wrapUntrustedJsonControls(result, 'google-workspace:chat:spaces', ['nextPageToken', 'spaces.*.name']);
59
59
  }
60
60
  catch (error) {
61
61
  // toMcpError passes an McpError (and auth-handoff errors) through unchanged, and folds
@@ -86,7 +86,7 @@ export async function handleListChatMessages(params) {
86
86
  filter,
87
87
  orderBy
88
88
  });
89
- return wrapUntrustedJsonStrings(result, 'google-workspace:chat:messages');
89
+ return wrapUntrustedJsonControls(result, 'google-workspace:chat:messages', ['nextPageToken', 'messages.*.name', 'messages.*.thread.name']);
90
90
  }
91
91
  catch (error) {
92
92
  throw toMcpError(error, 'Failed to list chat messages');
@@ -116,7 +116,7 @@ export async function handleSendChatMessage(params) {
116
116
  parent: space,
117
117
  text
118
118
  });
119
- return wrapUntrustedJsonStrings(result, 'google-workspace:chat:message');
119
+ return wrapUntrustedJsonControls(result, 'google-workspace:chat:message', ['name', 'thread.name']);
120
120
  }
121
121
  catch (error) {
122
122
  throw toMcpError(error, 'Failed to send chat message');
@@ -3,7 +3,7 @@ import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
3
3
  import { toMcpError } from "../utils/apiError.js";
4
4
  import { getAccountManager, resolveEmail } from "../modules/accounts/index.js";
5
5
  import { readAliasedBoolean, readAliasedNumber, readAliasedString } from './arg-aliases.js';
6
- import { wrapUntrustedContent, wrapUntrustedJsonStrings } from "../utils/untrusted-content.js";
6
+ import { wrapUntrustedContent, wrapUntrustedJsonControls } from "../utils/untrusted-content.js";
7
7
  // Singleton instances - Initialize or inject as per project pattern
8
8
  let contactsService;
9
9
  let accountManager;
@@ -45,7 +45,7 @@ export async function handleGetContacts(params) {
45
45
  pageSize,
46
46
  pageToken
47
47
  });
48
- return wrapUntrustedJsonStrings(result, 'google-workspace:contacts:list');
48
+ return wrapUntrustedJsonControls(result, 'google-workspace:contacts:list', ['nextPageToken', 'connections.*.resourceName']);
49
49
  }
50
50
  catch (error) {
51
51
  // toMcpError passes an McpError through, and folds a ContactsError's details into
@@ -99,7 +99,7 @@ export async function handleSearchContacts(params) {
99
99
  pageSize,
100
100
  });
101
101
  if (returnJson) {
102
- return wrapUntrustedJsonStrings(result, 'google-workspace:contacts:search');
102
+ return wrapUntrustedJsonControls(result, 'google-workspace:contacts:search', ['results.*.resourceName']);
103
103
  }
104
104
  return formatContactsAsText(result.results, result.totalResults);
105
105
  }
@@ -144,8 +144,8 @@ function hasAnyWriteField(fields) {
144
144
  return Object.values(fields).some(value => value !== undefined);
145
145
  }
146
146
  function formatWriteResult(action, result) {
147
- // Every string field is enveloped, matching the read handlers' whole-result wrapping.
148
- return wrapUntrustedJsonStrings({ status: 'success', action, contact: result }, 'google-workspace:contacts:write');
147
+ // The provider-generated resource name is reusable; contact text stays enveloped.
148
+ return wrapUntrustedJsonControls({ status: 'success', action, contact: result }, 'google-workspace:contacts:write', ['contact.resourceName']);
149
149
  }
150
150
  /**
151
151
  * Handler for creating a new Google Contact.
@@ -433,6 +433,7 @@ This tool does not send the email directly. It prepares the draft and launches t
433
433
  },
434
434
  {
435
435
  name: 'send_workspace_email',
436
+ _meta: { 'files/readInputs': { version: 1, inputs: [{ selector: ['attachments', '*', 'path'], base: 'connectorCwd', expandTilde: false, when: [{ relativeTo: 'parent', selector: ['content'], test: 'falsy' }] }] } },
436
437
  category: 'Gmail/Messages',
437
438
  description: `Send an email from a Gmail account.
438
439
 
@@ -868,6 +869,7 @@ Attachments are NOT automatically carried over — you must explicitly download
868
869
  },
869
870
  {
870
871
  name: 'create_workspace_draft',
872
+ _meta: { 'files/readInputs': { version: 1, inputs: [{ selector: ['attachments', '*', 'path'], base: 'connectorCwd', expandTilde: false, when: [{ relativeTo: 'parent', selector: ['content'], test: 'falsy' }] }] } },
871
873
  category: 'Gmail/Drafts',
872
874
  description: `Create a new Gmail draft. Use this when the user asks to save to drafts, save/create a Gmail draft, or save an already-drafted email without sending or opening another review UI. Supports plain text and HTML bodies, CC/BCC, reply threading, and attachments.`,
873
875
  annotations: { readOnlyHint: false, destructiveHint: false },
@@ -944,6 +946,7 @@ Attachments are NOT automatically carried over — you must explicitly download
944
946
  },
945
947
  {
946
948
  name: 'update_workspace_draft',
949
+ _meta: { 'files/readInputs': { version: 1, inputs: [{ selector: ['attachments', '*', 'path'], base: 'connectorCwd', expandTilde: false, when: [{ relativeTo: 'parent', selector: ['content'], test: 'falsy' }] }] } },
947
950
  category: 'Gmail/Drafts',
948
951
  description: `Update an existing Gmail draft. Replaces the draft content with the provided fields. Supports attachments and reply threading.`,
949
952
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
@@ -1064,6 +1067,7 @@ Attachments are NOT automatically carried over — you must explicitly download
1064
1067
  },
1065
1068
  {
1066
1069
  name: 'manage_workspace_draft',
1070
+ _meta: { 'files/readInputs': { version: 1, inputs: [{ selector: ['data', 'attachments', '*', 'path'], base: 'connectorCwd', expandTilde: false, when: [{ relativeTo: 'parent', selector: ['content'], test: 'falsy' }, { relativeTo: 'root', selector: ['action'], test: 'equals', value: 'create' }] }, { selector: ['data', 'attachments', '*', 'path'], base: 'connectorCwd', expandTilde: false, when: [{ relativeTo: 'parent', selector: ['content'], test: 'falsy' }, { relativeTo: 'root', selector: ['action'], test: 'equals', value: 'update' }] }] } },
1067
1071
  category: 'Gmail/Drafts',
1068
1072
  description: `Legacy consolidated draft tool. Prefer the individual draft tools for new calls.`,
1069
1073
  aliases: ['manage_draft'],
@@ -5,7 +5,8 @@ import { getDriveService } from '../modules/drive/index.js';
5
5
  import { idFromUri } from '../modules/docs/tabCopy.js';
6
6
  import { extractDocumentIdFromUrl } from '../modules/docs/formatters.js';
7
7
  import { readAliasedBoolean, readAliasedNumber, readAliasedString, readAliasedValue } from './arg-aliases.js';
8
- import { wrapUntrustedContent, wrapUntrustedJsonStrings } from '../utils/untrusted-content.js';
8
+ import { wrapUntrustedContent, wrapUntrustedJsonControls } from '../utils/untrusted-content.js';
9
+ import { preserveGoogleRetryDecision } from '../utils/google-retry.js';
9
10
  /**
10
11
  * Format DocumentResponse as human-readable text
11
12
  */
@@ -103,7 +104,10 @@ export async function handleReadDocument(args) {
103
104
  throw new McpError(ErrorCode.InternalError, result.error || 'Failed to read document');
104
105
  }
105
106
  if (returnJson) {
106
- return wrapUntrustedJsonStrings(result.data, `google-workspace:docs:document/${documentId}`);
107
+ return wrapUntrustedJsonControls(result.data, `google-workspace:docs:document/${documentId}`, [
108
+ 'documentId', 'revisionId', 'tabs.*.tabId', 'tabs.*.parentTabId', 'shownTab.tabId', 'requestedTab.tabId',
109
+ 'tab.tabProperties.tabId', 'tab.tabProperties.parentTabId', 'childTabs.*.tabId',
110
+ ]);
107
111
  }
108
112
  // Format as human-readable text
109
113
  const docResponse = result.data;
@@ -255,12 +259,12 @@ export async function handleListDocumentTabs(args) {
255
259
  }
256
260
  const tabList = result.data;
257
261
  if (returnJson) {
258
- return wrapUntrustedJsonStrings({
262
+ return wrapUntrustedJsonControls({
259
263
  documentId: tabList.documentId,
260
264
  title: tabList.title,
261
265
  tabCount: tabList.tabs.length,
262
266
  tabs: tabList.tabs,
263
- }, `google-workspace:docs:tabs/${tabList.documentId}`);
267
+ }, `google-workspace:docs:tabs/${tabList.documentId}`, ['documentId', 'tabs.*.tabId', 'tabs.*.parentTabId']);
264
268
  }
265
269
  return formatTabsAsText(tabList);
266
270
  });
@@ -293,7 +297,7 @@ export async function handleBatchUpdateDocument(args) {
293
297
  throw new McpError(ErrorCode.InternalError, result.error || 'Failed to update document');
294
298
  }
295
299
  if (returnJson) {
296
- return wrapUntrustedJsonStrings(result.data, `google-workspace:docs:batch-update/${documentId}`);
300
+ return wrapUntrustedJsonControls(result.data, `google-workspace:docs:batch-update/${documentId}`, ['documentId']);
297
301
  }
298
302
  // Format as human-readable text
299
303
  const response = result.data;
@@ -617,7 +621,11 @@ export async function handleCopyDocumentTab(args) {
617
621
  ...(newTabPosition !== undefined ? { newTabPosition } : {}),
618
622
  }, checkChip);
619
623
  if (!result.success || !result.data) {
620
- throw new McpError(ErrorCode.InternalError, result.error || 'Failed to copy document tab');
624
+ const failure = new McpError(ErrorCode.InternalError, result.error || 'Failed to copy document tab');
625
+ Object.assign(failure, { cause: result.cause });
626
+ if (result.status !== undefined)
627
+ Object.assign(failure, { status: result.status });
628
+ throw preserveGoogleRetryDecision(failure, result);
621
629
  }
622
630
  const data = result.data;
623
631
  const text = formatTabCopyAsText(data);
@@ -2,9 +2,10 @@ import { FileListOptions, FileSearchOptions, FileUploadOptions, PermissionOption
2
2
  import { McpToolResponse } from './types.js';
3
3
  /** @internal Exported for tests. */
4
4
  export declare function formatDriveRecoveryError(operation: string, error: unknown): {
5
- ok: boolean;
6
5
  action_required: string;
7
6
  next_step: string;
7
+ recoveryExhausted?: boolean | undefined;
8
+ ok: boolean;
8
9
  };
9
10
  interface DriveFileListArgs {
10
11
  email?: string;
@@ -2,9 +2,10 @@ import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
2
2
  import { getAccountManager, resolveEmail } from '../modules/accounts/index.js';
3
3
  import { getDriveService, getDriveActivityService } from '../modules/drive/index.js';
4
4
  import { normalizeDriveItemName } from '../modules/drive/activity-service.js';
5
- import { toMcpError } from '../utils/apiError.js';
5
+ import { GOOGLE_RATE_LIMIT_NEXT_STEP, isGoogleRecoveryExhausted, isShortWindowRateLimit } from '../utils/google-retry.js';
6
+ import { extractHttpStatus, toMcpError } from '../utils/apiError.js';
6
7
  import { readAliasedBoolean, readAliasedNumber, readAliasedString } from './arg-aliases.js';
7
- import { wrapUntrustedContent, wrapUntrustedJsonStrings } from '../utils/untrusted-content.js';
8
+ import { wrapUntrustedContent, wrapUntrustedJsonStrings, wrapUntrustedJsonControls } from '../utils/untrusted-content.js';
8
9
  const HOST_TIMEZONE = Intl.DateTimeFormat().resolvedOptions().timeZone;
9
10
  /**
10
11
  * Get human-readable label for MIME type
@@ -79,20 +80,22 @@ function formatSharedDrivesAsText(drives) {
79
80
  }
80
81
  /** @internal Exported for tests. */
81
82
  export function formatDriveRecoveryError(operation, error) {
82
- const status = error && typeof error === 'object'
83
- ? error.response?.status
84
- ?? error.code
85
- : undefined;
86
- const statusText = status ? ` (${status})` : '';
83
+ const status = extractHttpStatus(error);
84
+ const statusText = status === undefined ? '' : ` (${status})`;
87
85
  const message = error instanceof Error
88
86
  ? error.message
89
87
  : error && typeof error === 'object' && typeof error.message === 'string'
90
88
  ? error.message
91
89
  : 'Unknown error';
90
+ const recoveryExhausted = isGoogleRecoveryExhausted(error);
91
+ const rateLimited = status === 429 || isShortWindowRateLimit(error);
92
92
  return {
93
93
  ok: false,
94
+ ...(recoveryExhausted ? { recoveryExhausted: true } : {}),
94
95
  action_required: `Drive ${operation} failed${statusText}`,
95
- next_step: `${message}. Check Google Workspace authentication and Drive permissions, then retry.`,
96
+ next_step: recoveryExhausted || rateLimited
97
+ ? GOOGLE_RATE_LIMIT_NEXT_STEP
98
+ : `${message}. Check Google Workspace authentication and Drive permissions, then retry.`,
96
99
  };
97
100
  }
98
101
  function formatDriveToolResponse(operation, error) {
@@ -107,7 +110,9 @@ function formatDriveJsonResult(operation, result, source) {
107
110
  if (result.success === false) {
108
111
  return formatDriveRecoveryError(operation, new Error(result.error || 'Unknown error'));
109
112
  }
110
- return wrapUntrustedJsonStrings(result, source);
113
+ return wrapUntrustedJsonControls(result, source, [
114
+ 'data.nextPageToken', 'data.files.*.id', 'data.drives.*.id',
115
+ ]);
111
116
  }
112
117
  export async function handleListDriveFiles(args) {
113
118
  const accountManager = getAccountManager();
@@ -247,7 +252,7 @@ export async function handleUploadDriveFile(args) {
247
252
  return {
248
253
  content: [{
249
254
  type: 'text',
250
- text: JSON.stringify(wrapUntrustedJsonStrings(result, 'google-workspace:drive:file-upload'), null, 2)
255
+ text: JSON.stringify(wrapUntrustedJsonControls(result, 'google-workspace:drive:file-upload', ['data.id', 'data.parents.*']), null, 2)
251
256
  }]
252
257
  };
253
258
  }
@@ -301,7 +306,7 @@ export async function handleCreateDriveFolder(args) {
301
306
  return {
302
307
  content: [{
303
308
  type: 'text',
304
- text: JSON.stringify(wrapUntrustedJsonStrings(result, 'google-workspace:drive:folder/create'), null, 2)
309
+ text: JSON.stringify(wrapUntrustedJsonControls(result, 'google-workspace:drive:folder/create', ['data.id', 'data.parents.*']), null, 2)
305
310
  }]
306
311
  };
307
312
  }
@@ -394,7 +399,7 @@ export async function handleCopyDriveFile(args) {
394
399
  return {
395
400
  content: [{
396
401
  type: 'text',
397
- text: JSON.stringify(wrapUntrustedJsonStrings(result, `google-workspace:drive:file/${fileId}/copy`), null, 2)
402
+ text: JSON.stringify(wrapUntrustedJsonControls(result, `google-workspace:drive:file/${fileId}/copy`, ['data.id', 'data.parents.*']), null, 2)
398
403
  }]
399
404
  };
400
405
  }
@@ -430,7 +435,7 @@ export async function handleMoveDriveFile(args) {
430
435
  return {
431
436
  content: [{
432
437
  type: 'text',
433
- text: JSON.stringify(wrapUntrustedJsonStrings(result, `google-workspace:drive:file/${fileId}/move`), null, 2)
438
+ text: JSON.stringify(wrapUntrustedJsonControls(result, `google-workspace:drive:file/${fileId}/move`, ['data.id', 'data.parents.*']), null, 2)
434
439
  }]
435
440
  };
436
441
  }
@@ -457,7 +462,7 @@ export async function handleTrashDriveFile(args) {
457
462
  return {
458
463
  content: [{
459
464
  type: 'text',
460
- text: JSON.stringify(wrapUntrustedJsonStrings(result, `google-workspace:drive:file/${fileId}/trash`), null, 2)
465
+ text: JSON.stringify(wrapUntrustedJsonControls(result, `google-workspace:drive:file/${fileId}/trash`, ['data.id', 'data.parents.*']), null, 2)
461
466
  }]
462
467
  };
463
468
  }
@@ -484,7 +489,7 @@ export async function handleUntrashDriveFile(args) {
484
489
  return {
485
490
  content: [{
486
491
  type: 'text',
487
- text: JSON.stringify(wrapUntrustedJsonStrings(result, `google-workspace:drive:file/${fileId}/untrash`), null, 2)
492
+ text: JSON.stringify(wrapUntrustedJsonControls(result, `google-workspace:drive:file/${fileId}/untrash`, ['data.id', 'data.parents.*']), null, 2)
488
493
  }]
489
494
  };
490
495
  }
@@ -511,7 +516,7 @@ export async function handleListFileRevisions(args) {
511
516
  return {
512
517
  content: [{
513
518
  type: 'text',
514
- text: JSON.stringify(wrapUntrustedJsonStrings(result, `google-workspace:drive:file/${fileId}/revisions`), null, 2)
519
+ text: JSON.stringify(wrapUntrustedJsonControls(result, `google-workspace:drive:file/${fileId}/revisions`, ['data.nextPageToken', 'data.revisions.*.id']), null, 2)
515
520
  }]
516
521
  };
517
522
  }
@@ -1,9 +1,10 @@
1
+ import { type FileReadContext } from '../file-read-context.js';
1
2
  import { ManageLabelParams, ManageLabelAssignmentParams, ManageLabelFilterParams } from '../modules/gmail/services/label.js';
2
3
  import { McpToolResponse } from './types.js';
3
4
  import { OutgoingGmailAttachment } from '../modules/gmail/types.js';
4
5
  import { ManageAttachmentParams } from './types.js';
5
6
  /** @internal Exported for tests. */
6
- export declare function resolveAttachmentFromPath(filePath: string): {
7
+ export declare function resolveAttachmentFromPath(filePath: string, context?: FileReadContext, location?: (string | number)[]): {
7
8
  content: string;
8
9
  name: string;
9
10
  mimeType: string;
@@ -211,7 +212,7 @@ export declare function handleGetWorkspaceEmailThread(params: GetThreadParams):
211
212
  }>;
212
213
  }>;
213
214
  }>;
214
- export declare function handleSendWorkspaceEmail(params: SendEmailRequestParams & Record<string, unknown>): Promise<{
215
+ export declare function handleSendWorkspaceEmail(params: SendEmailRequestParams & Record<string, unknown>, context?: FileReadContext): Promise<{
215
216
  content: {
216
217
  type: "text";
217
218
  text: string;
@@ -245,7 +246,7 @@ export declare function handleListWorkspaceSendAs(params: {
245
246
  }): Promise<{
246
247
  sendAs: import("../modules/gmail/types.js").SendAsAlias[];
247
248
  }>;
248
- export declare function handleManageWorkspaceDraft(params: ManageDraftParams): Promise<void | import("../modules/gmail/types.js").DraftResponse | import("../modules/gmail/types.js").GetDraftsResponse | import("../modules/gmail/types.js").SendEmailResponse>;
249
+ export declare function handleManageWorkspaceDraft(params: ManageDraftParams, context?: FileReadContext, attachmentLocation?: (string | number)[]): Promise<void | import("../modules/gmail/types.js").DraftResponse | import("../modules/gmail/types.js").GetDraftsResponse | import("../modules/gmail/types.js").SendEmailResponse>;
249
250
  export declare function handleManageWorkspaceLabel(params: ManageLabelParams): Promise<void | import("../modules/gmail/types.js").Label | import("../modules/gmail/types.js").GetLabelsResponse>;
250
251
  export declare function handleManageWorkspaceLabelAssignment(params: ManageLabelAssignmentParams): Promise<{
251
252
  content: {
@@ -265,8 +266,8 @@ export declare function handleGetWorkspaceDraft(params: {
265
266
  email?: string;
266
267
  draftId: string;
267
268
  }): Promise<void | import("../modules/gmail/types.js").DraftResponse | import("../modules/gmail/types.js").GetDraftsResponse | import("../modules/gmail/types.js").SendEmailResponse>;
268
- export declare function handleCreateWorkspaceDraft(params: Record<string, unknown>): Promise<void | import("../modules/gmail/types.js").DraftResponse | import("../modules/gmail/types.js").GetDraftsResponse | import("../modules/gmail/types.js").SendEmailResponse>;
269
- export declare function handleUpdateWorkspaceDraft(params: Record<string, unknown>): Promise<void | import("../modules/gmail/types.js").DraftResponse | import("../modules/gmail/types.js").GetDraftsResponse | import("../modules/gmail/types.js").SendEmailResponse>;
269
+ export declare function handleCreateWorkspaceDraft(params: Record<string, unknown>, context?: FileReadContext): Promise<void | import("../modules/gmail/types.js").DraftResponse | import("../modules/gmail/types.js").GetDraftsResponse | import("../modules/gmail/types.js").SendEmailResponse>;
270
+ export declare function handleUpdateWorkspaceDraft(params: Record<string, unknown>, context?: FileReadContext): Promise<void | import("../modules/gmail/types.js").DraftResponse | import("../modules/gmail/types.js").GetDraftsResponse | import("../modules/gmail/types.js").SendEmailResponse>;
270
271
  export declare function handleDeleteWorkspaceDraft(params: {
271
272
  email?: string;
272
273
  draft_id?: string;
@@ -1,12 +1,13 @@
1
+ import { centralReadPath } from '../file-read-context.js';
1
2
  import { getGmailService } from '../modules/gmail/index.js';
2
3
  import { getAccountManager, validateEmail, resolveEmail } from '../modules/accounts/index.js';
3
4
  import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
4
- import { toMcpError } from '../utils/apiError.js';
5
+ import { isPassthroughGoogleError, toMcpError } from '../utils/apiError.js';
5
6
  import { AttachmentService } from '../modules/attachments/service.js';
6
7
  import { ATTACHMENT_FOLDERS } from '../modules/attachments/types.js';
7
8
  import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, realpathSync, statSync } from 'fs';
8
9
  import path from 'path';
9
- import { wrapUntrustedContent, wrapUntrustedJsonStrings } from '../utils/untrusted-content.js';
10
+ import { wrapUntrustedContent, wrapUntrustedJsonStrings, wrapUntrustedJsonControls } from '../utils/untrusted-content.js';
10
11
  import logger from '../utils/logger.js';
11
12
  // Singleton instances
12
13
  let gmailService;
@@ -77,6 +78,8 @@ async function resolveReplyThreading(email, replyToMessageId) {
77
78
  return { headers: result };
78
79
  }
79
80
  catch (error) {
81
+ if (isPassthroughGoogleError(error))
82
+ throw error;
80
83
  logger.warn(`[gmail-handlers] Reply threading degraded: failed to fetch original message ${replyToMessageId} for account ${email}:`, error instanceof Error ? error.message : error);
81
84
  return { headers: {}, degradedReason: unthreadedReplyReason(replyToMessageId) };
82
85
  }
@@ -116,16 +119,22 @@ function getAttachmentWorkspaceRoot() {
116
119
  return realpathSync.native(rootPath);
117
120
  }
118
121
  /** @internal Exported for tests. */
119
- export function resolveAttachmentFromPath(filePath) {
120
- const rootRealpath = getAttachmentWorkspaceRoot();
121
- const candidatePath = path.resolve(filePath);
122
- const candidateStats = lstatSync(candidatePath);
123
- if (candidateStats.isSymbolicLink()) {
124
- throw new McpError(ErrorCode.InvalidParams, 'Attachment path must not be a symbolic link.');
122
+ export function resolveAttachmentFromPath(filePath, context, location = []) {
123
+ let candidateRealpath = centralReadPath(context, filePath, location);
124
+ if (candidateRealpath === undefined) {
125
+ const rootRealpath = getAttachmentWorkspaceRoot();
126
+ const candidatePath = path.resolve(filePath);
127
+ const candidateStats = lstatSync(candidatePath);
128
+ if (candidateStats.isSymbolicLink()) {
129
+ throw new McpError(ErrorCode.InvalidParams, 'Attachment path must not be a symbolic link.');
130
+ }
131
+ candidateRealpath = realpathSync.native(candidatePath);
132
+ if (!isPathInsideDirectory(candidateRealpath, rootRealpath)) {
133
+ throw new McpError(ErrorCode.InvalidParams, `Attachment path must be within the workspace directory. Got: ${filePath}`);
134
+ }
125
135
  }
126
- const candidateRealpath = realpathSync.native(candidatePath);
127
- if (!isPathInsideDirectory(candidateRealpath, rootRealpath)) {
128
- throw new McpError(ErrorCode.InvalidParams, `Attachment path must be within the workspace directory. Got: ${filePath}`);
136
+ if (context?.mode === 'central' && realpathSync(candidateRealpath) !== candidateRealpath) {
137
+ throw new McpError(ErrorCode.InvalidParams, 'Attachment file changed while it was being verified; refusing to read it.');
129
138
  }
130
139
  // Pin the identity (device + inode) of the object that passed containment.
131
140
  // O_NOFOLLOW only refuses a symlink in the FINAL path component — an
@@ -167,10 +176,10 @@ export function resolveAttachmentFromPath(filePath) {
167
176
  closeSync(fd);
168
177
  }
169
178
  }
170
- function processOutgoingAttachments(attachments) {
171
- return attachments?.map(attachment => {
179
+ function processOutgoingAttachments(attachments, context, prefix = ['attachments']) {
180
+ return attachments?.map((attachment, index) => {
172
181
  if (attachment.path && !attachment.content) {
173
- const resolved = resolveAttachmentFromPath(attachment.path);
182
+ const resolved = resolveAttachmentFromPath(attachment.path, context, [...prefix, index, 'path']);
174
183
  return {
175
184
  id: attachment.id || resolved.name,
176
185
  name: attachment.name || resolved.name,
@@ -407,7 +416,10 @@ export async function handleSearchWorkspaceEmails(params) {
407
416
  const result = await gmailService.getEmails({ email, search: normalizedSearch, options, messageIds });
408
417
  // Return formatted text by default, JSON only when explicitly requested
409
418
  if (returnJson) {
410
- return wrapUntrustedJsonStrings(result, 'google-workspace:gmail:search');
419
+ return wrapUntrustedJsonControls(result, 'google-workspace:gmail:search', [
420
+ 'nextPageToken', 'emails.*.id', 'emails.*.threadId', 'emails.*.attachments.*.id',
421
+ 'threads.{}.messages.*',
422
+ ]);
411
423
  }
412
424
  return formatEmailsAsText(result);
413
425
  }
@@ -507,13 +519,13 @@ export async function handleGetWorkspaceEmailThread(params) {
507
519
  // Snippet field is preserved so callers can still see what was elided.
508
520
  if (includeBody && !includeFullBodies && result.messages.length > DEFAULT_FULL_BODY_TAIL) {
509
521
  const tailStart = result.messages.length - DEFAULT_FULL_BODY_TAIL;
510
- return wrapUntrustedJsonStrings({
522
+ return wrapUntrustedJsonControls({
511
523
  ...result,
512
524
  bodies_abbreviated: tailStart,
513
525
  messages: result.messages.map((m, i) => i < tailStart ? { ...m, body: undefined } : m),
514
- }, `google-workspace:gmail:thread/${threadId}`);
526
+ }, `google-workspace:gmail:thread/${threadId}`, ['threadId', 'messages.*.id', 'messages.*.attachments.*.id']);
515
527
  }
516
- return wrapUntrustedJsonStrings(result, `google-workspace:gmail:thread/${threadId}`);
528
+ return wrapUntrustedJsonControls(result, `google-workspace:gmail:thread/${threadId}`, ['threadId', 'messages.*.id', 'messages.*.attachments.*.id']);
517
529
  }
518
530
  return formatThreadAsText(result, offset, includeFullBodies);
519
531
  }
@@ -522,7 +534,7 @@ export async function handleGetWorkspaceEmailThread(params) {
522
534
  }
523
535
  });
524
536
  }
525
- export async function handleSendWorkspaceEmail(params) {
537
+ export async function handleSendWorkspaceEmail(params, context) {
526
538
  await initializeServices();
527
539
  const { to, subject, body, cc, bcc, attachments } = params;
528
540
  const rawParams = params;
@@ -588,7 +600,7 @@ export async function handleSendWorkspaceEmail(params) {
588
600
  threadId: threadingResolution.headers.threadId,
589
601
  inReplyTo: threadingResolution.headers.inReplyTo,
590
602
  references: threadingResolution.headers.references,
591
- attachments: processOutgoingAttachments(attachments)
603
+ attachments: processOutgoingAttachments(attachments, context)
592
604
  };
593
605
  const sendResult = await gmailService.sendEmail(emailParams);
594
606
  // Degraded reply threading is observable in the result (additive
@@ -701,7 +713,7 @@ export async function handleListWorkspaceSendAs(params) {
701
713
  }
702
714
  });
703
715
  }
704
- export async function handleManageWorkspaceDraft(params) {
716
+ export async function handleManageWorkspaceDraft(params, context, attachmentLocation = ['data', 'attachments']) {
705
717
  await initializeServices();
706
718
  const rawParams = params;
707
719
  const action = params.action;
@@ -745,7 +757,7 @@ export async function handleManageWorkspaceDraft(params) {
745
757
  threadId: data.threadId ?? threading.threadId,
746
758
  inReplyTo: data.inReplyTo ?? threading.inReplyTo,
747
759
  references: data.references ?? threading.references,
748
- attachments: processOutgoingAttachments(data.attachments)
760
+ attachments: processOutgoingAttachments(data.attachments, context, attachmentLocation)
749
761
  }
750
762
  });
751
763
  }
@@ -779,7 +791,7 @@ export async function handleManageWorkspaceDraft(params) {
779
791
  threadId: data.threadId ?? threading.threadId,
780
792
  inReplyTo: data.inReplyTo ?? threading.inReplyTo,
781
793
  references: data.references ?? threading.references,
782
- attachments: processOutgoingAttachments(data.attachments)
794
+ attachments: processOutgoingAttachments(data.attachments, context, attachmentLocation)
783
795
  }
784
796
  });
785
797
  }
@@ -1001,15 +1013,15 @@ export async function handleListWorkspaceDrafts(params) {
1001
1013
  export async function handleGetWorkspaceDraft(params) {
1002
1014
  return handleManageWorkspaceDraft({ ...params, action: 'read' });
1003
1015
  }
1004
- export async function handleCreateWorkspaceDraft(params) {
1016
+ export async function handleCreateWorkspaceDraft(params, context) {
1005
1017
  const { email, ...data } = params;
1006
- return handleManageWorkspaceDraft({ email: email, action: 'create', data: data });
1018
+ return handleManageWorkspaceDraft({ email: email, action: 'create', data: data }, context, ['attachments']);
1007
1019
  }
1008
- export async function handleUpdateWorkspaceDraft(params) {
1020
+ export async function handleUpdateWorkspaceDraft(params, context) {
1009
1021
  const email = params.email;
1010
1022
  const draftId = readAliasedString(params, 'draft_id', 'draftId');
1011
1023
  const { draft_id: _draftIdSnake, draftId: _draftIdCamel, ...data } = params;
1012
- return handleManageWorkspaceDraft({ email, action: 'update', draftId, data: data });
1024
+ return handleManageWorkspaceDraft({ email, action: 'update', draftId, data: data }, context, ['attachments']);
1013
1025
  }
1014
1026
  export async function handleDeleteWorkspaceDraft(params) {
1015
1027
  const draftId = readAliasedString(params, 'draft_id', 'draftId');
@@ -3,7 +3,7 @@ import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
3
3
  import { toMcpError } from "../utils/apiError.js";
4
4
  import { getAccountManager, resolveEmail } from "../modules/accounts/index.js";
5
5
  import { readAliasedNumber, readAliasedString } from './arg-aliases.js';
6
- import { wrapUntrustedJsonStrings } from "../utils/untrusted-content.js";
6
+ import { wrapUntrustedJsonControls } from "../utils/untrusted-content.js";
7
7
  // Singleton instances - Initialize or inject as per project pattern
8
8
  let meetService;
9
9
  let accountManager;
@@ -68,7 +68,7 @@ export async function handleListMeetConferenceRecords(params) {
68
68
  pageToken,
69
69
  filter
70
70
  });
71
- return wrapUntrustedJsonStrings(result, 'google-workspace:meet:conference-records');
71
+ return wrapUntrustedJsonControls(result, 'google-workspace:meet:conference-records', ['nextPageToken', 'conferenceRecords.*.name']);
72
72
  }
73
73
  catch (error) {
74
74
  // toMcpError passes an McpError (and auth-handoff errors) through, and folds a
@@ -100,7 +100,7 @@ export async function handleListMeetTranscripts(params) {
100
100
  pageSize: pageSize !== undefined ? Math.min(pageSize, MEET_MAX_PAGE_SIZE) : undefined,
101
101
  pageToken
102
102
  });
103
- return wrapUntrustedJsonStrings(result, 'google-workspace:meet:transcripts');
103
+ return wrapUntrustedJsonControls(result, 'google-workspace:meet:transcripts', ['nextPageToken', 'transcripts.*.name', 'transcripts.*.docsDestination.document']);
104
104
  }
105
105
  catch (error) {
106
106
  // See handleListMeetConferenceRecords: toMcpError surfaces the real cause.
@@ -133,7 +133,7 @@ export async function handleGetMeetTranscriptEntries(params) {
133
133
  pageSize: pageSize !== undefined ? Math.min(pageSize, MEET_MAX_PAGE_SIZE) : undefined,
134
134
  pageToken
135
135
  });
136
- return wrapUntrustedJsonStrings(result, 'google-workspace:meet:transcript-entries');
136
+ return wrapUntrustedJsonControls(result, 'google-workspace:meet:transcript-entries', ['nextPageToken']);
137
137
  }
138
138
  catch (error) {
139
139
  // See handleListMeetConferenceRecords: toMcpError surfaces the real cause.