@mindstone/mcp-server-google-workspace 0.5.9 → 0.5.11

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.
package/README.md CHANGED
@@ -8,7 +8,7 @@ Google Workspace MCP server — Gmail, Calendar, Drive, Docs, Sheets, Slides, Co
8
8
 
9
9
  ## Status
10
10
 
11
- - **Version:** [0.5.9](./CHANGELOG.md) · npm: not yet published
11
+ - **Version:** [0.5.11](./CHANGELOG.md) · npm: not yet published
12
12
  - **Auth:** OAuth (host-orchestrated) ([`GOOGLE_CLIENT_SECRET`](./server.json))
13
13
  - **Tools:** [123](./src/tools/definitions/) (Gmail, Calendar, Drive, Docs, Sheets, Slides, Contacts, Chat, Meet, Tasks, Forms, Comments, Account)
14
14
  - **Surface:** cloud-api
@@ -124,6 +124,148 @@ function planThisAndFollowing(series, occurrence) {
124
124
  });
125
125
  return { kind: 'cut', recurrence };
126
126
  }
127
+ const hasOffset = (dateTime) => /(Z|[+-]\d\d:?\d\d)$/i.test(dateTime);
128
+ /** The date an entry falls on in the series' own time zone, whatever zone Google wrote its time in. */
129
+ const dayOf = (slot, timeZone) => {
130
+ if (slot?.date)
131
+ return slot.date;
132
+ if (!slot?.dateTime)
133
+ return undefined;
134
+ if (!hasOffset(slot.dateTime) || !timeZone)
135
+ return slot.dateTime.slice(0, 10);
136
+ return new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(slot.dateTime));
137
+ };
138
+ /** True only when both are surely the same moment: a time without an offset is compared as written, zone included. */
139
+ const sameInstant = (a, b) => {
140
+ if (a?.date || b?.date)
141
+ return a?.date === b?.date;
142
+ if (!a?.dateTime || !b?.dateTime)
143
+ return false;
144
+ if (hasOffset(a.dateTime) && hasOffset(b.dateTime))
145
+ return Date.parse(a.dateTime) === Date.parse(b.dateTime);
146
+ return a.dateTime === b.dateTime && (a.timeZone ?? '') === (b.timeZone ?? '');
147
+ };
148
+ /** Fields Google sets on each entry itself, or that can't be edited on one entry: never compared or written back. */
149
+ const PER_ENTRY = new Set(['kind', 'etag', 'id', 'status', 'htmlLink', 'created', 'updated', 'iCalUID', 'sequence', 'recurringEventId',
150
+ 'originalStartTime', 'start', 'end', 'recurrence', 'creator', 'organizer', 'eventType', 'hangoutLink', 'privateCopy', 'locked', 'attendeesOmitted']);
151
+ /** Plain text details, written back on a single entry; Google leaves a cleared one out, so a clear is written as an empty value. */
152
+ const TEXT_FIELDS = new Set(['summary', 'description', 'location']);
153
+ const stable = (value) => Array.isArray(value) ? `[${value.map(stable).join(',')}]`
154
+ : value && typeof value === 'object' ? `{${Object.keys(value).sort().map(key => `${key}:${stable(value[key])}`).join(',')}}`
155
+ : JSON.stringify(value ?? null);
156
+ /** A field's value as an edit would change it: guests by who is invited, since each guest's reply to one entry is theirs. */
157
+ const comparable = (field, value) => {
158
+ if (field === 'attendees')
159
+ return stable((value ?? []).map(a => `${a.email}|${!!a.optional}`).sort());
160
+ return TEXT_FIELDS.has(field) ? stable(value ?? '') : stable(value);
161
+ };
162
+ /** The fields of one entry that differ from another: what the person edited on it. */
163
+ const differingFields = (entry, from) => {
164
+ const a = entry;
165
+ const b = from;
166
+ return [...new Set([...Object.keys(a), ...Object.keys(b)])].filter(field => !PER_ENTRY.has(field) && comparable(field, a[field]) !== comparable(field, b[field]));
167
+ };
168
+ const lengthOf = (event) => Date.parse(event.end?.dateTime ?? event.end?.date ?? '') - Date.parse(event.start?.dateTime ?? event.start?.date ?? '');
169
+ const describeChange = (c) => c.deleted ? 'deleted' : [c.moved && 'moved', c.edited.length > 0 && 'edited'].filter(Boolean).join(' and ');
170
+ async function listEntries(calendar, calendarId, seriesId, showDeleted) {
171
+ const entries = [];
172
+ let pageToken;
173
+ do {
174
+ const { data } = await calendar.events.instances({ calendarId, eventId: seriesId, showDeleted, maxResults: 2500, pageToken });
175
+ entries.push(...(data.items ?? []));
176
+ pageToken = data.nextPageToken ?? undefined;
177
+ } while (pageToken);
178
+ return entries;
179
+ }
180
+ /**
181
+ * Google keys a change to one entry of a series to that entry's original start, so a new series time
182
+ * leaves every such change behind: a moved entry snaps back and a deleted one returns. This reads them
183
+ * before the series changes, so they can be put back on the entry for the same date afterwards.
184
+ */
185
+ async function readSingleChanges(calendar, calendarId, series) {
186
+ const zone = series.start?.timeZone ?? undefined;
187
+ const changes = [];
188
+ const entries = await listEntries(calendar, calendarId, series.id, true);
189
+ const perDate = new Map();
190
+ for (const entry of entries)
191
+ perDate.set(dayOf(entry.originalStartTime, zone), (perDate.get(dayOf(entry.originalStartTime, zone)) ?? 0) + 1);
192
+ for (const entry of entries) {
193
+ const deleted = entry.status === 'cancelled';
194
+ const moved = !deleted && (!sameInstant(entry.start, entry.originalStartTime) || lengthOf(entry) !== lengthOf(series));
195
+ const edited = deleted ? [] : differingFields(entry, series);
196
+ const date = dayOf(entry.originalStartTime, zone);
197
+ if (date && (deleted || moved || edited.length > 0))
198
+ changes.push({ date, entry, deleted, moved, edited, alone: perDate.get(date) === 1 });
199
+ }
200
+ return changes;
201
+ }
202
+ /**
203
+ * Puts each change back on the series' entry for the same date (dates in the series' zone after the change,
204
+ * which may differ from before it), writing only what differs, so a change
205
+ * still in place is kept as it is. One that has no entry on that date any more (the series moved to
206
+ * another day), that cannot be read back, or that Google refuses is returned as not kept, never dropped.
207
+ */
208
+ async function restoreSingleChanges(calendar, calendarId, seriesId, zone, changes) {
209
+ const kept = [];
210
+ const notKept = [];
211
+ if (changes.length === 0)
212
+ return { kept, notKept };
213
+ let entries;
214
+ try {
215
+ entries = await listEntries(calendar, calendarId, seriesId, true);
216
+ }
217
+ catch (error) {
218
+ // The series has already changed: a thrown error here would be retried from the top and lose these.
219
+ const reason = `the series' entries could not be read back: ${error instanceof Error ? error.message : String(error)}`;
220
+ return { kept, notKept: changes.map(change => ({ date: change.date, change: describeChange(change), reason })) };
221
+ }
222
+ for (const change of changes) {
223
+ const outcome = { date: change.date, change: describeChange(change) };
224
+ // A date is matched only when it holds one entry of the series before and after, deleted ones counted:
225
+ // with two on one day, the one left could be one the person never touched.
226
+ const onDate = entries.filter(entry => dayOf(entry.originalStartTime, zone) === change.date);
227
+ try {
228
+ if (!change.alone || onDate.length > 1) {
229
+ notKept.push({ ...outcome, reason: 'the series has more than one entry on that date' });
230
+ continue;
231
+ }
232
+ const target = onDate[0];
233
+ if (change.deleted && target?.status === 'cancelled') {
234
+ kept.push(outcome);
235
+ continue;
236
+ }
237
+ if (!target || target.status === 'cancelled') {
238
+ notKept.push({ ...outcome, reason: 'the series no longer has one entry on that date' });
239
+ continue;
240
+ }
241
+ // Only times, deletions and plain text are written back: guests, reminders and other details are
242
+ // nested or carry other people's replies, so they are reported for the person to redo instead.
243
+ const left = change.edited.filter(field => !TEXT_FIELDS.has(field));
244
+ if (change.deleted) {
245
+ await calendar.events.delete({ calendarId, eventId: target.id, sendUpdates: 'none' });
246
+ }
247
+ else {
248
+ const requestBody = {
249
+ ...(change.moved && !(sameInstant(target.start, change.entry.start) && sameInstant(target.end, change.entry.end))
250
+ ? { start: change.entry.start, end: change.entry.end } : {}),
251
+ ...Object.fromEntries(differingFields(change.entry, target).filter(field => TEXT_FIELDS.has(field) && change.edited.includes(field))
252
+ .map(field => [field, change.entry[field] ?? ''])),
253
+ };
254
+ if (Object.keys(requestBody).length > 0) {
255
+ await calendar.events.patch({ calendarId, eventId: target.id, sendUpdates: 'none', requestBody });
256
+ }
257
+ }
258
+ if (change.deleted || change.moved || left.length < change.edited.length)
259
+ kept.push(outcome);
260
+ if (left.length > 0)
261
+ notKept.push({ ...outcome, reason: `these details changed on that entry are not carried over: ${left.join(', ')}` });
262
+ }
263
+ catch (error) {
264
+ notKept.push({ ...outcome, reason: error instanceof Error ? error.message : String(error) });
265
+ }
266
+ }
267
+ return { kept, notKept };
268
+ }
127
269
  export class CalendarService {
128
270
  oauth2Client;
129
271
  driveService;
@@ -643,6 +785,13 @@ export class CalendarService {
643
785
  if (!hasNewTime && summary === undefined) {
644
786
  throw new CalendarError('No new time provided', 'INVALID_REQUEST', 'Please provide the new time for the event');
645
787
  }
788
+ // A new time for a whole series drops the person's changes to single entries of it; keep them.
789
+ const series = event.data;
790
+ // The zone counts too: the series repeats by its zone's clock, so a new zone re-keys its entries.
791
+ const newZone = hasNewTime ? newTimes[0].start?.timeZone ?? series.start?.timeZone : series.start?.timeZone;
792
+ const seriesTimeChanges = hasNewTime && !!series.recurrence?.length &&
793
+ (!sameInstant(newTimes[0].start, series.start) || !sameInstant(newTimes[0].end, series.end) || newZone !== series.start?.timeZone);
794
+ const singleChanges = seriesTimeChanges ? await readSingleChanges(calendar, targetCalendarId, series) : [];
646
795
  const { data: updatedEvent } = await calendar.events.patch({
647
796
  calendarId: targetCalendarId,
648
797
  eventId,
@@ -653,12 +802,15 @@ export class CalendarService {
653
802
  },
654
803
  sendUpdates: 'all'
655
804
  });
805
+ const { kept, notKept } = await restoreSingleChanges(calendar, targetCalendarId, eventId, updatedEvent.start?.timeZone ?? newZone ?? undefined, singleChanges);
656
806
  return {
657
807
  success: true,
658
808
  eventId,
659
809
  action,
660
810
  status: 'updated',
661
- htmlLink: updatedEvent.htmlLink || undefined
811
+ htmlLink: updatedEvent.htmlLink || undefined,
812
+ ...(kept.length ? { singleEntryChangesKept: kept } : {}),
813
+ ...(notKept.length ? { singleEntryChangesNotKept: notKept } : {})
662
814
  };
663
815
  }
664
816
  default:
@@ -127,6 +127,17 @@ export interface ManageEventResponse {
127
127
  start: EventTime;
128
128
  end: EventTime;
129
129
  }[];
130
+ /** After a series' time changed: the person's changes to single entries that were put back, by date. */
131
+ singleEntryChangesKept?: {
132
+ date: string;
133
+ change: string;
134
+ }[];
135
+ /** And those that could not be, with why: the reply must tell the person. */
136
+ singleEntryChangesNotKept?: {
137
+ date: string;
138
+ change: string;
139
+ reason?: string;
140
+ }[];
130
141
  }
131
142
  export interface DeleteEventParams {
132
143
  email: string;
@@ -6,7 +6,7 @@ import { DOCS_SCOPES } from './scopes.js';
6
6
  import { describeApiError, describeApiErrorUntrusted, extractHttpStatus, failedResult, isAuthHandoffError, isPassthroughGoogleError, withCause } from '../../utils/apiError.js';
7
7
  import { preserveGoogleRetryDecision } from '../../utils/google-retry.js';
8
8
  import { wrapUntrustedJsonValues } from '../../utils/untrusted-content.js';
9
- import { ALL_TEXT_KEYS, DocsInputError, TAB_READ_TEXT_OPTIONS, TAB_TREE_FIELDS, TRUNCATION_MARKER, assertUniqueTitle, buildAllTabsText, bodyEndIndex, countWords, descendantsOf, extractBodyText, findAnchor, flatParagraphs, flattenTabs, nextParagraphInContainer, normalizeInsertText, paragraphSearchText, requireTabs, resolveTab, siblingsOf, } from './tabs.js';
9
+ import { ALL_TEXT_KEYS, DocsInputError, quoteTabId, TAB_READ_TEXT_OPTIONS, TAB_TREE_FIELDS, TRUNCATION_MARKER, assertUniqueTitle, buildAllTabsText, bodyEndIndex, countWords, descendantsOf, extractBodyText, findAnchor, flatParagraphs, flattenTabs, nextParagraphInContainer, normalizeInsertText, paragraphSearchText, requireTabs, resolveTab, siblingsOf, } from './tabs.js';
10
10
  const DEFAULT_MAX_CHARS = 50000;
11
11
  /** Cap on `read_workspace_document` with `tab_id` + `return_json` (enveloped size). */
12
12
  export const MAX_TAB_JSON_CHARS = 100_000;
@@ -764,7 +764,7 @@ export class DocsService extends BaseGoogleService {
764
764
  const descendants = descendantsOf(flat, target.tabId);
765
765
  if (descendants.length > 0 && options.deleteSubTabs !== true) {
766
766
  const count = descendants.length;
767
- throw new DocsInputError(`Tab "${target.tabId}" has ${count} sub-tab${count !== 1 ? 's' : ''}, which would be deleted with it. Nothing was deleted. ` +
767
+ throw new DocsInputError(`Tab ${quoteTabId(target.tabId)} has ${count} sub-tab${count !== 1 ? 's' : ''}, which would be deleted with it. Nothing was deleted. ` +
768
768
  'Check with list_workspace_document_tabs that this is the tab you mean, then pass delete_sub_tabs: true to delete it and all its sub-tabs.');
769
769
  }
770
770
  await client.documents.batchUpdate({
@@ -818,7 +818,7 @@ export class DocsService extends BaseGoogleService {
818
818
  const paragraphs = flatParagraphs(body);
819
819
  const matches = findAnchor(paragraphs, options.anchorText, options.matchCase);
820
820
  if (matches.length === 0) {
821
- throw new DocsInputError(`Anchor text not found in tab "${tab.tabId}". It must be plain text inside one paragraph (smart chips, people and dates can't be part of it); read the tab with tab_id to copy it exactly, leaving out the "• " and "[H1]"-style markers, which are not document text.`);
821
+ throw new DocsInputError(`Anchor text not found in tab ${quoteTabId(tab.tabId)}. It must be plain text inside one paragraph (smart chips, people and dates can't be part of it); read the tab with tab_id to copy it exactly, leaving out the "• " and "[H1]"-style markers, which are not document text.`);
822
822
  }
823
823
  if (matches.length > 1) {
824
824
  throw new DocsInputError(`Anchor text found ${matches.length} times in this tab; use a longer anchor that appears once.`);
@@ -8,6 +8,11 @@
8
8
  */
9
9
  import { docs_v1 } from 'googleapis';
10
10
  import { McpError } from '@modelcontextprotocol/sdk/types.js';
11
+ /**
12
+ * A tab id quoted in the connector's own text. A document's author can choose its tab ids, so the
13
+ * id stays in an untrusted-content envelope; the server strips it again when the id is passed back.
14
+ */
15
+ export declare function quoteTabId(tabId: string): string;
11
16
  export declare const TRUNCATION_MARKER = "\n\n[TRUNCATED - document exceeds character limit]";
12
17
  /**
13
18
  * Input error raised by the tab helpers (unknown tab id, refused `default`,
@@ -1,4 +1,12 @@
1
1
  import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
2
+ import { wrapUntrustedContent } from '../../utils/untrusted-controls.js';
3
+ /**
4
+ * A tab id quoted in the connector's own text. A document's author can choose its tab ids, so the
5
+ * id stays in an untrusted-content envelope; the server strips it again when the id is passed back.
6
+ */
7
+ export function quoteTabId(tabId) {
8
+ return wrapUntrustedContent(tabId, 'google-workspace:docs:tab-id');
9
+ }
2
10
  export const TRUNCATION_MARKER = '\n\n[TRUNCATED - document exceeds character limit]';
3
11
  /**
4
12
  * Input error raised by the tab helpers (unknown tab id, refused `default`,
@@ -66,7 +74,7 @@ export function resolveTab(flat, requested, opts) {
66
74
  if (match)
67
75
  return match;
68
76
  }
69
- throw new DocsInputError(`Tab "${requested}" not found in this document. Call list_workspace_document_tabs to see tab ids.`);
77
+ throw new DocsInputError(`Tab ${quoteTabId(requested)} not found in this document. Call list_workspace_document_tabs to see tab ids.`);
70
78
  }
71
79
  function inlineElementText(element, renderInline) {
72
80
  if (element.textRun?.content) {
@@ -352,7 +352,8 @@ export async function handleFindFreeSlots(params) {
352
352
  end: queryTimeMax
353
353
  });
354
354
  }
355
- results[calId] = {
355
+ // A calendar id is an address its owner chose, so the key is enveloped too.
356
+ results[wrapUntrustedContent(calId, 'google-workspace:calendar:freebusy')] = {
356
357
  busy: busyPeriods,
357
358
  free: freeSlots
358
359
  };
@@ -378,7 +379,7 @@ export async function handleListWorkspaceCalendars(params) {
378
379
  return accountManager.withTokenRenewal(email, async () => {
379
380
  try {
380
381
  const calendars = await calendarService.listCalendars(email);
381
- return wrapUntrustedJsonControls(calendars, 'google-workspace:calendar:list', [], [], ['*.id']);
382
+ return wrapUntrustedJsonControls(calendars, 'google-workspace:calendar:list', []);
382
383
  }
383
384
  catch (error) {
384
385
  throw toMcpError(error, 'Failed to list calendars');
@@ -455,7 +456,7 @@ export async function handleListWorkspaceCalendarEvents(params) {
455
456
  },
456
457
  referenceTimeUTC: new Date().toISOString(),
457
458
  events
458
- }, 'google-workspace:calendar:events', ['events.*.attachments.*.fileId'], ['events.*.id']);
459
+ }, 'google-workspace:calendar:events', ['events.*.attachments.*.fileId']);
459
460
  }
460
461
  return formatEventsAsText(events, tzInfo);
461
462
  }
@@ -475,7 +476,7 @@ export async function handleGetWorkspaceCalendarEvent(params) {
475
476
  }
476
477
  return accountManager.withTokenRenewal(email, async () => {
477
478
  try {
478
- return wrapUntrustedJsonControls(await calendarService.getEvent(email, eventId, calendarId), `google-workspace:calendar:event/${eventId}`, ['attachments.*.fileId'], ['id']);
479
+ return wrapUntrustedJsonControls(await calendarService.getEvent(email, eventId, calendarId), `google-workspace:calendar:event/${eventId}`, ['attachments.*.fileId']);
479
480
  }
480
481
  catch (error) {
481
482
  throw toMcpError(error, 'Failed to get calendar event');
@@ -572,7 +573,7 @@ export async function handleCreateWorkspaceCalendarEvent(params) {
572
573
  colorId,
573
574
  transparency
574
575
  });
575
- return wrapUntrustedJsonControls(createdEvent, 'google-workspace:calendar:event/create', ['attachments.*.fileId'], ['id']);
576
+ return wrapUntrustedJsonControls(createdEvent, 'google-workspace:calendar:event/create', ['attachments.*.fileId']);
576
577
  }
577
578
  catch (error) {
578
579
  // CalendarError here is operational (auth/permission/API failure), not caller-arg
@@ -616,7 +617,7 @@ export async function handleManageWorkspaceCalendarEvent(params) {
616
617
  summary,
617
618
  calendarId
618
619
  });
619
- return wrapUntrustedJsonControls(managedEvent, `google-workspace:calendar:event/${eventId}`, ['attachments.*.fileId'], ['eventId']);
620
+ return wrapUntrustedJsonControls(managedEvent, `google-workspace:calendar:event/${eventId}`, ['attachments.*.fileId']);
620
621
  }
621
622
  catch (error) {
622
623
  throw toMcpError(error, 'Failed to manage calendar event');
@@ -128,7 +128,7 @@ export const docsTools = [
128
128
  { "email": "user@example.com", "document_id": "1ABC123xyz", "tab_id": "t.abc123", "text": "\\nAction items reviewed." }
129
129
 
130
130
  The text is inserted at the end of the document body (or of the tab).
131
- Use \\n for line breaks in the appended text.`,
131
+ Write line breaks in the appended text as real line breaks.`,
132
132
  aliases: ['append_doc', 'add_to_document', 'document_append'],
133
133
  annotations: { readOnlyHint: false, destructiveHint: false },
134
134
  inputSchema: {
@@ -426,7 +426,14 @@ CRITICAL - PLAIN TEXT vs HTML:
426
426
  - If is_html: false (default), body is plain text (line breaks work naturally).
427
427
 
428
428
  PLAIN TEXT (default - use this most of the time):
429
- { "to": ["alice@example.com"], "subject": "Quick question", "body": "Hi Alice,\\n\\nCan we meet tomorrow at 3pm?\\n\\nThanks,\\nBob" }
429
+ { "to": ["alice@example.com"], "subject": "Quick question", "body": "..." }
430
+ where body is the text itself, with real line breaks:
431
+ Hi Alice,
432
+
433
+ Can we meet tomorrow at 3pm?
434
+
435
+ Thanks,
436
+ Bob
430
437
 
431
438
  HTML (only when formatting is needed):
432
439
  { "to": ["alice@example.com"], "subject": "Meeting Summary", "body": "<p>Hi Alice,</p><p>Key points from our meeting:</p><ul><li>Budget approved</li><li>Launch date: March 1st</li></ul><p>Thanks,<br>Bob</p>", "is_html": true }
@@ -437,13 +444,29 @@ COMMON MISTAKES TO AVOID:
437
444
  - Don't forget <br> or <p> tags for line breaks in HTML mode
438
445
 
439
446
  REPLY TO EXISTING EMAIL:
440
- { "to": ["original-sender@example.com"], "subject": "Re: Meeting Tomorrow", "body": "Sounds good!\\n\\nOn Mon, Jan 6, 2026 at 10:00 AM, Alice <alice@example.com> wrote:\\n> Hey, are we still on for tomorrow's meeting?\\n> Let me know if the time works.", "reply_to_message_id": "18c5a2b3d4e5f6g7" }
447
+ { "to": ["original-sender@example.com"], "subject": "Re: Meeting Tomorrow", "body": "...", "reply_to_message_id": "18c5a2b3d4e5f6g7" }
448
+ where body is:
449
+ Sounds good!
450
+
451
+ On Mon, Jan 6, 2026 at 10:00 AM, Alice <alice@example.com> wrote:
452
+ > Hey, are we still on for tomorrow's meeting?
453
+ > Let me know if the time works.
441
454
 
442
455
  IMPORTANT: For replies, use reply_to_message_id with the Gmail message ID. This auto-sets threading headers.
443
456
  The threading headers do not add earlier messages to the body, so quote the message you are answering below your reply: many recipients read outside a threaded view. Use get_workspace_email_thread to fetch it, then quote it conventionally (plain text: "> " prefix with an "On DATE, SENDER wrote:" line; HTML: <blockquote> tags). Quoting is good practice, never a reason to hold back an approved reply: if you can't quote, send the reply anyway, and pass on any threading warning the tool returns.
444
457
 
445
458
  FORWARD AN EMAIL:
446
- { "to": ["bob@example.com"], "subject": "Fwd: Meeting Tomorrow", "body": "FYI see below.\\n\\n---------- Forwarded message ----------\\nFrom: Alice <alice@example.com>\\nDate: Mon, Jan 6, 2026\\nSubject: Meeting Tomorrow\\nTo: You <you@example.com>\\n\\nHey, are we still on for tomorrow's meeting?" }
459
+ { "to": ["bob@example.com"], "subject": "Fwd: Meeting Tomorrow", "body": "..." }
460
+ where body is:
461
+ FYI see below.
462
+
463
+ ---------- Forwarded message ----------
464
+ From: Alice <alice@example.com>
465
+ Date: Mon, Jan 6, 2026
466
+ Subject: Meeting Tomorrow
467
+ To: You <you@example.com>
468
+
469
+ Hey, are we still on for tomorrow's meeting?
447
470
 
448
471
  For forwards, include the full original message with a forwarded message header block.
449
472
 
@@ -452,7 +475,7 @@ When the original email has attachments, you MUST download and re-attach them:
452
475
  1. Use get_workspace_email_thread to see which attachments exist (filenames listed per message)
453
476
  2. Use download_workspace_attachment for each attachment (source: "email", message_id, filename)
454
477
  3. Include them in the "attachments" array using the local file path returned by the download
455
- Example: { "to": ["bob@example.com"], "subject": "Fwd: Report", "body": "See attached.\\n\\n---------- Forwarded message ----------\\n...", "attachments": [{ "path": "/path/to/downloaded/report.pdf" }] }
478
+ Example: { "to": ["bob@example.com"], "subject": "Fwd: Report", "body": "...", "attachments": [{ "path": "/path/to/downloaded/report.pdf" }] }, with the body written like the forward above.
456
479
  Attachments are NOT automatically carried over — you must explicitly download and re-attach them.`,
457
480
  aliases: ['send_email', 'send_mail', 'create_email'],
458
481
  annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
@@ -871,7 +894,7 @@ Attachments are NOT automatically carried over — you must explicitly download
871
894
  },
872
895
  body: {
873
896
  type: 'string',
874
- description: 'Email body content. Plain text by default — use \\n for line breaks. If you need HTML formatting (bold, lists, links), you MUST also set is_html: true or HTML tags will show as raw text in Gmail.'
897
+ description: 'Email body content. Plain text by default, with real line breaks. If you need HTML formatting (bold, lists, links), you MUST also set is_html: true or HTML tags will show as raw text in Gmail.'
875
898
  },
876
899
  is_html: {
877
900
  type: 'boolean',
@@ -952,7 +975,7 @@ Attachments are NOT automatically carried over — you must explicitly download
952
975
  },
953
976
  body: {
954
977
  type: 'string',
955
- description: 'Email body content. Plain text by default — use \\n for line breaks. If you need HTML formatting (bold, lists, links), you MUST also set is_html: true or HTML tags will show as raw text in Gmail.'
978
+ description: 'Email body content. Plain text by default, with real line breaks. If you need HTML formatting (bold, lists, links), you MUST also set is_html: true or HTML tags will show as raw text in Gmail.'
956
979
  },
957
980
  is_html: {
958
981
  type: 'boolean',
@@ -70,11 +70,15 @@ export function formatTabsAsText(result) {
70
70
  function formatEnvelopedDocumentLine(doc, documentId) {
71
71
  return `Document: ${wrapUntrustedContent(doc.title ?? '', `google-workspace:docs:document/${documentId}`)}`;
72
72
  }
73
+ /** A tab id, enveloped: a document's author can choose it. */
74
+ function envelopedTabId(doc, tabId) {
75
+ return wrapUntrustedContent(tabId, `google-workspace:docs:document/${doc.documentId}`);
76
+ }
73
77
  /**
74
78
  * ` (tab <id>)` suffix for the first line of a tab-scoped edit result (id only).
75
79
  */
76
80
  function tabSuffix(doc) {
77
- return doc.requestedTab ? ` (tab ${doc.requestedTab.tabId})` : '';
81
+ return doc.requestedTab ? ` (tab ${envelopedTabId(doc, doc.requestedTab.tabId)})` : '';
78
82
  }
79
83
  /**
80
84
  * Read a Google Docs document
@@ -105,10 +109,7 @@ export async function handleReadDocument(args) {
105
109
  throw operationFailure(result, result.error || 'Failed to read document');
106
110
  }
107
111
  if (returnJson) {
108
- return wrapUntrustedJsonControls(result.data, `google-workspace:docs:document/${documentId}`, [
109
- 'documentId', 'revisionId', 'tabs.*.tabId', 'tabs.*.parentTabId', 'shownTab.tabId', 'requestedTab.tabId',
110
- 'tab.tabProperties.tabId', 'tab.tabProperties.parentTabId', 'childTabs.*.tabId',
111
- ]);
112
+ return wrapUntrustedJsonControls(result.data, `google-workspace:docs:document/${documentId}`, ['documentId', 'revisionId']);
112
113
  }
113
114
  // Format as human-readable text
114
115
  const docResponse = result.data;
@@ -221,7 +222,8 @@ export async function handleFindAndReplace(args) {
221
222
  : '';
222
223
  if (occurrences === 0) {
223
224
  // A tab-scoped miss names the tab searched, not the whole document.
224
- const searched = docResponse.requestedTab ? `tab ${docResponse.requestedTab.tabId}` : 'the document';
225
+ const searched = docResponse.requestedTab
226
+ ? `tab ${envelopedTabId(docResponse, docResponse.requestedTab.tabId)}` : 'the document';
225
227
  return `No occurrences of "${findText}" found in ${searched}.\n\n${documentLine}\nURL: ${docResponse.documentUrl}${scopeNote}`;
226
228
  }
227
229
  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}`;
@@ -265,7 +267,7 @@ export async function handleListDocumentTabs(args) {
265
267
  title: tabList.title,
266
268
  tabCount: tabList.tabs.length,
267
269
  tabs: tabList.tabs,
268
- }, `google-workspace:docs:tabs/${tabList.documentId}`, ['documentId', 'tabs.*.tabId', 'tabs.*.parentTabId']);
270
+ }, `google-workspace:docs:tabs/${tabList.documentId}`, ['documentId']);
269
271
  }
270
272
  return formatTabsAsText(tabList);
271
273
  });
@@ -1,2 +1,7 @@
1
1
  export declare function normalizeArgs(args: Record<string, unknown>): Record<string, unknown>;
2
+ /**
3
+ * Strip one envelope from every string under an id key, at any depth, so an id
4
+ * copied with its envelope from an earlier result works; other text is untouched.
5
+ */
6
+ export declare function unwrapIdArgs<T>(value: T, underIdKey?: boolean): T;
2
7
  //# sourceMappingURL=param-normalizer.d.ts.map
@@ -1,3 +1,4 @@
1
+ import { unwrapUntrusted } from '../utils/untrusted-content.js';
1
2
  const LEGACY_ALIASES = {
2
3
  hasAttachment: 'has_attachment',
3
4
  isUnread: 'is_unread',
@@ -101,12 +102,39 @@ const LEGACY_ALIASES = {
101
102
  filterId: 'filter_id',
102
103
  };
103
104
  export function normalizeArgs(args) {
104
- const normalized = { ...args };
105
+ const normalized = unwrapIdArgs({ ...args });
105
106
  for (const [legacyKey, canonicalKey] of Object.entries(LEGACY_ALIASES)) {
106
107
  if (!(canonicalKey in normalized) && legacyKey in args) {
107
- normalized[canonicalKey] = args[legacyKey];
108
+ normalized[canonicalKey] = normalized[legacyKey];
108
109
  }
109
110
  }
110
111
  return normalized;
111
112
  }
113
+ /**
114
+ * Argument names that carry an id the connector returns inside the
115
+ * untrusted-content envelope, because an outsider can choose it (an event's
116
+ * creator, a shared calendar's owner, a document's author). Docs batch-update
117
+ * requests carry tab ids under the API's own names.
118
+ */
119
+ const WRAPPED_ID_KEYS = new Set([
120
+ 'event_id', 'eventId', 'calendar_id', 'calendarId',
121
+ 'tab_id', 'tabId', 'parent_tab_id', 'parentTabId', 'source_tab_id', 'sourceTabId',
122
+ 'target_tab_id', 'targetTabId', 'new_tab_parent_id', 'newTabParentId', 'tabIds',
123
+ // find_free_slots takes calendar ids (addresses) as attendees.
124
+ 'attendees',
125
+ ]);
126
+ /**
127
+ * Strip one envelope from every string under an id key, at any depth, so an id
128
+ * copied with its envelope from an earlier result works; other text is untouched.
129
+ */
130
+ export function unwrapIdArgs(value, underIdKey = false) {
131
+ if (typeof value === 'string')
132
+ return (underIdKey ? unwrapUntrusted(value) : value);
133
+ if (Array.isArray(value))
134
+ return value.map(item => unwrapIdArgs(item, underIdKey));
135
+ if (value && typeof value === 'object') {
136
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, unwrapIdArgs(item, WRAPPED_ID_KEYS.has(key))]));
137
+ }
138
+ return value;
139
+ }
112
140
  //# sourceMappingURL=param-normalizer.js.map
@@ -2,11 +2,12 @@
2
2
  * Wrap external text, except provider-generated controls at declared response
3
3
  * paths. A `*` segment matches array items only; `{}` explicitly matches the
4
4
  * values of an object map at that path, without exempting other map content.
5
- * Calendar event ids use separate declared paths with Google's base32hex and
6
- * recurring-instance shape check. Other author-chosen ids (e.g. Slides object
7
- * ids), headers, titles, and metadata must not be declared as controls.
5
+ * Declare only ids an outsider cannot choose. Ids an author or sender can pick
6
+ * (Calendar event ids, calendar addresses, Docs tab ids, Slides object ids) stay
7
+ * wrapped, as do headers, titles and metadata; the server strips the envelope
8
+ * from id arguments (`unwrapIdArgs`), so a wrapped id still works when passed back.
8
9
  */
9
- export declare function wrapUntrustedJsonControls<T>(value: T, source: string, controlPaths: readonly string[], eventIdPaths?: readonly string[], calendarIdPaths?: readonly string[]): T;
10
+ export declare function wrapUntrustedJsonControls<T>(value: T, source: string, controlPaths: readonly string[]): T;
10
11
  /**
11
12
  * Connector-local alias for `wrapUntrusted` under the name the existing call
12
13
  * sites were written against. `content` is required (never `undefined`), so
@@ -8,17 +8,13 @@ import { wrapUntrusted } from './untrusted-content.js';
8
8
  * Wrap external text, except provider-generated controls at declared response
9
9
  * paths. A `*` segment matches array items only; `{}` explicitly matches the
10
10
  * values of an object map at that path, without exempting other map content.
11
- * Calendar event ids use separate declared paths with Google's base32hex and
12
- * recurring-instance shape check. Other author-chosen ids (e.g. Slides object
13
- * ids), headers, titles, and metadata must not be declared as controls.
11
+ * Declare only ids an outsider cannot choose. Ids an author or sender can pick
12
+ * (Calendar event ids, calendar addresses, Docs tab ids, Slides object ids) stay
13
+ * wrapped, as do headers, titles and metadata; the server strips the envelope
14
+ * from id arguments (`unwrapIdArgs`), so a wrapped id still works when passed back.
14
15
  */
15
- export function wrapUntrustedJsonControls(value, source, controlPaths, eventIdPaths = [], calendarIdPaths = []) {
16
- const paths = [
17
- ...controlPaths.map(path => ({ segments: path.split('.'), shape: /^[A-Za-z0-9_+/=.~!\-]+$/ })),
18
- ...eventIdPaths.map(path => ({ segments: path.split('.'), shape: /^[a-v0-9]{5,1024}(?:_R[0-9]{8}T[0-9]{6})?(?:_[0-9]{8}(?:T[0-9]{6}Z)?)?$/ })),
19
- // Calendar-list ids are provider-issued addresses, including public holiday calendars.
20
- ...calendarIdPaths.map(path => ({ segments: path.split('.'), shape: /^[A-Za-z0-9_.+%#=\-]+@[A-Za-z0-9.\-]+$/ })),
21
- ];
16
+ export function wrapUntrustedJsonControls(value, source, controlPaths) {
17
+ const paths = controlPaths.map(path => ({ segments: path.split('.'), shape: /^[A-Za-z0-9_+/=.~!\-]+$/ }));
22
18
  function visit(item, remaining) {
23
19
  if (typeof item === 'string') {
24
20
  // Compare the full match because JavaScript's $ also accepts a trailing newline.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mindstone/mcp-server-google-workspace",
3
- "version": "0.5.9",
3
+ "version": "0.5.11",
4
4
  "mcpName": "io.github.mindstone/mcp-server-google-workspace",
5
5
  "description": "Google Workspace MCP server for Gmail, Calendar, Drive, Docs, Sheets, Slides, Contacts, Tasks, and Forms",
6
6
  "license": "FSL-1.1-MIT",