@mindstone/mcp-server-google-workspace 0.5.2 → 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 (45) hide show
  1. package/README.md +27 -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/resources/compose-email-template.d.ts +1 -1
  20. package/dist/resources/compose-email-template.js +107 -53
  21. package/dist/services/base/BaseGoogleService.js +2 -2
  22. package/dist/services/chat/index.js +3 -0
  23. package/dist/services/contacts/index.js +8 -5
  24. package/dist/services/meet/index.js +3 -0
  25. package/dist/tools/calendar-handlers.js +7 -7
  26. package/dist/tools/chat-handlers.js +4 -4
  27. package/dist/tools/contacts-handlers.js +5 -5
  28. package/dist/tools/definitions/gmail.js +4 -0
  29. package/dist/tools/docs-handlers.js +14 -6
  30. package/dist/tools/drive-handlers.d.ts +2 -1
  31. package/dist/tools/drive-handlers.js +21 -16
  32. package/dist/tools/gmail-handlers.d.ts +6 -5
  33. package/dist/tools/gmail-handlers.js +39 -27
  34. package/dist/tools/meet-handlers.js +4 -4
  35. package/dist/tools/server.js +24 -10
  36. package/dist/tools/sheets-handlers.js +4 -4
  37. package/dist/tools/slides-handlers.js +4 -4
  38. package/dist/utils/apiError.d.ts +7 -3
  39. package/dist/utils/apiError.js +37 -16
  40. package/dist/utils/google-retry.d.ts +15 -0
  41. package/dist/utils/google-retry.js +108 -0
  42. package/dist/utils/request-timeout.js +2 -0
  43. package/dist/utils/untrusted-content.d.ts +9 -0
  44. package/dist/utils/untrusted-content.js +37 -0
  45. package/package.json +3 -2
@@ -38,6 +38,8 @@ export declare function hasErrorDetails(error: unknown): error is {
38
38
  * (re)authentication — i.e. it exposes a string `code` in {@link AUTH_HANDOFF_CODES}.
39
39
  */
40
40
  export declare function isAuthHandoffError(error: unknown): boolean;
41
+ /** Keep structured recovery decisions out of lossy string-only error results. */
42
+ export declare function isPassthroughGoogleError(error: unknown): boolean;
41
43
  /**
42
44
  * Normalizes any thrown value into an error suitable for a tool handler's outer
43
45
  * catch. An McpError (e.g. an InvalidParams validation failure raised earlier
@@ -47,9 +49,11 @@ export declare function isAuthHandoffError(error: unknown): boolean;
47
49
  * it into `McpError(InternalError)` would erase the domain `code` that
48
50
  * `formatErrorResponse` reads to emit the `auth_required` reconnect handoff,
49
51
  * silently degrading an expired-token failure to a generic "Failed to …"
50
- * message. Any other domain error surfaces its `details`; anything else is
51
- * described with its HTTP status. Prevents the "Failed to X" opaque-error class
52
- * where the real cause was silently dropped.
52
+ * message. A short-window rate-limit transport error is also passed through so
53
+ * the server can preserve its status and emit rate-limit guidance. Any other
54
+ * domain error surfaces its `details`; anything else is described with its HTTP
55
+ * status. Prevents the "Failed to X" opaque-error class where the real cause
56
+ * was silently dropped.
53
57
  */
54
58
  export declare function toMcpError(error: unknown, fallbackContext: string): Error;
55
59
  //# sourceMappingURL=apiError.d.ts.map
@@ -1,5 +1,9 @@
1
1
  import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
2
2
  import { wrapUntrustedContent } from './untrusted-content.js';
3
+ import { isGoogleRecoveryExhausted, isShortWindowRateLimit, preserveGoogleRetryDecision } from './google-retry.js';
4
+ function isHttpStatus(value) {
5
+ return typeof value === 'number' && Number.isInteger(value) && value >= 100 && value <= 599;
6
+ }
3
7
  /**
4
8
  * Extracts the HTTP status from a googleapis (GaxiosError-shaped) failure,
5
9
  * preferring `response.status` and falling back to a top-level `status` or a
@@ -7,17 +11,24 @@ import { wrapUntrustedContent } from './untrusted-content.js';
7
11
  * (e.g. a DNS `ENOTFOUND` where `code` is a non-numeric string).
8
12
  */
9
13
  export function extractHttpStatus(error) {
10
- if (typeof error !== 'object' || error === null)
11
- return undefined;
12
- const candidate = error;
13
- if (typeof candidate.response?.status === 'number')
14
- return candidate.response.status;
15
- if (typeof candidate.status === 'number')
16
- return candidate.status;
17
- if (typeof candidate.code === 'number')
18
- return candidate.code;
19
- if (typeof candidate.code === 'string' && /^\d+$/.test(candidate.code))
20
- return Number(candidate.code);
14
+ const seen = new Set();
15
+ let current = error;
16
+ while (typeof current === 'object' && current !== null && !seen.has(current)) {
17
+ const candidate = current;
18
+ if (isHttpStatus(candidate.response?.status))
19
+ return candidate.response.status;
20
+ if (isHttpStatus(candidate.status))
21
+ return candidate.status;
22
+ if (isHttpStatus(candidate.code))
23
+ return candidate.code;
24
+ if (typeof candidate.code === 'string' && /^\d+$/.test(candidate.code)) {
25
+ const status = Number(candidate.code);
26
+ if (isHttpStatus(status))
27
+ return status;
28
+ }
29
+ seen.add(current);
30
+ current = candidate.cause;
31
+ }
21
32
  return undefined;
22
33
  }
23
34
  /**
@@ -82,6 +93,10 @@ export function isAuthHandoffError(error) {
82
93
  const code = error.code;
83
94
  return typeof code === 'string' && AUTH_HANDOFF_CODES.has(code);
84
95
  }
96
+ /** Keep structured recovery decisions out of lossy string-only error results. */
97
+ export function isPassthroughGoogleError(error) {
98
+ return isAuthHandoffError(error) || isGoogleRecoveryExhausted(error) || extractHttpStatus(error) === 429 || isShortWindowRateLimit(error);
99
+ }
85
100
  /**
86
101
  * Normalizes any thrown value into an error suitable for a tool handler's outer
87
102
  * catch. An McpError (e.g. an InvalidParams validation failure raised earlier
@@ -91,18 +106,24 @@ export function isAuthHandoffError(error) {
91
106
  * it into `McpError(InternalError)` would erase the domain `code` that
92
107
  * `formatErrorResponse` reads to emit the `auth_required` reconnect handoff,
93
108
  * silently degrading an expired-token failure to a generic "Failed to …"
94
- * message. Any other domain error surfaces its `details`; anything else is
95
- * described with its HTTP status. Prevents the "Failed to X" opaque-error class
96
- * where the real cause was silently dropped.
109
+ * message. A short-window rate-limit transport error is also passed through so
110
+ * the server can preserve its status and emit rate-limit guidance. Any other
111
+ * domain error surfaces its `details`; anything else is described with its HTTP
112
+ * status. Prevents the "Failed to X" opaque-error class where the real cause
113
+ * was silently dropped.
97
114
  */
98
115
  export function toMcpError(error, fallbackContext) {
99
116
  if (error instanceof McpError)
100
117
  return error;
101
118
  if (isAuthHandoffError(error) && error instanceof Error)
102
119
  return error;
120
+ if ((extractHttpStatus(error) === 429 || isShortWindowRateLimit(error)) && error instanceof Error)
121
+ return error;
103
122
  const detail = hasErrorDetails(error) && error.details
104
123
  ? `${error.message}: ${error.details}`
105
- : describeApiError(error);
106
- return new McpError(ErrorCode.InternalError, `${fallbackContext}: ${detail}`);
124
+ : isGoogleRecoveryExhausted(error)
125
+ ? describeApiErrorUntrusted(error, 'google-workspace:api-error')
126
+ : describeApiError(error);
127
+ return preserveGoogleRetryDecision(new McpError(ErrorCode.InternalError, `${fallbackContext}: ${detail}`), error);
107
128
  }
108
129
  //# sourceMappingURL=apiError.js.map
@@ -0,0 +1,15 @@
1
+ import type { RetryConfig } from 'gaxios' with { 'resolution-mode': 'require' };
2
+ export declare const GOOGLE_RATE_LIMIT_NEXT_STEP = "Google Workspace rate limit reached. Back off before retrying, reduce the request size if possible, then try again.";
3
+ /** The error's message and response body, where Google puts structured reasons. */
4
+ export declare function errorText(error: unknown): string;
5
+ /** Keep Drive's existing daily-quota classification for file-access checks. */
6
+ export declare function rateLimitReason(error: unknown, status: number | undefined): string | undefined;
7
+ export declare function isShortWindowRateLimit(error: unknown): boolean;
8
+ /** Only this request policy can declare a terminal retry decision. */
9
+ export declare function isGoogleRecoveryExhausted(error: unknown): boolean;
10
+ export declare function preserveGoogleRetryDecision<T extends object>(target: T, cause: unknown): T;
11
+ export declare function createGoogleRetryConfig({ sleep, random, }?: {
12
+ sleep?: (ms: number) => Promise<void>;
13
+ random?: () => number;
14
+ }): RetryConfig;
15
+ //# sourceMappingURL=google-retry.d.ts.map
@@ -0,0 +1,108 @@
1
+ import { extractHttpStatus } from './apiError.js';
2
+ const TERMINAL_RETRY_DECISION = Symbol.for('google-workspace.terminal-retry-decision');
3
+ const RETRY_METHODS = new Set(['GET', 'HEAD', 'PUT', 'OPTIONS', 'DELETE']);
4
+ const EXTENDED_RATE_LIMIT_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
5
+ // Google's documented exponential backoff caps at 32–64 seconds. Our 32-second
6
+ // caps total 95 seconds over seven retries; jitter in [2/3, 1] guarantees at
7
+ // least 63 1/3 seconds of waiting, so one attempt follows a full minute window.
8
+ const MAX_RATE_LIMIT_RETRIES = 7;
9
+ const MAX_RETRY_AFTER_MS = 64_000;
10
+ const MAX_BACKOFF_MS = 32_000;
11
+ const LONG_WINDOW_QUOTA = /\b(?:dailyLimitExceeded|quotaExceeded)\b|per\s+day/i;
12
+ export const GOOGLE_RATE_LIMIT_NEXT_STEP = 'Google Workspace rate limit reached. Back off before retrying, reduce the request size if possible, then try again.';
13
+ /** The error's message and response body, where Google puts structured reasons. */
14
+ export function errorText(error) {
15
+ const seen = new Set();
16
+ const parts = [];
17
+ let current = error;
18
+ while (typeof current === 'object' && current !== null && !seen.has(current)) {
19
+ const candidate = current;
20
+ const message = current instanceof Error ? current.message : '';
21
+ const data = candidate.response?.data;
22
+ parts.push(`${message}\n${typeof data === 'string' ? data : JSON.stringify(data ?? '')}`);
23
+ seen.add(current);
24
+ current = candidate.cause;
25
+ }
26
+ return parts.join('\n');
27
+ }
28
+ /** Keep Drive's existing daily-quota classification for file-access checks. */
29
+ export function rateLimitReason(error, status) {
30
+ if (status !== 403 && status !== 429)
31
+ return undefined;
32
+ const reason = /\b(?:userRateLimitExceeded|rateLimitExceeded|dailyLimitExceeded)\b/.exec(errorText(error))?.[0];
33
+ return reason ?? (status === 429 ? 'too many requests' : undefined);
34
+ }
35
+ export function isShortWindowRateLimit(error) {
36
+ const text = errorText(error);
37
+ const status = extractHttpStatus(error);
38
+ if (LONG_WINDOW_QUOTA.test(text))
39
+ return false;
40
+ return status === 429 || (status === 403 && (/\b(?:rateLimitExceeded|userRateLimitExceeded|RATE_LIMIT_EXCEEDED)\b/.test(text) ||
41
+ /quota exceeded for quota metric[\s\S]*per\s+(?:minute|second|100\s+seconds)/i.test(text)));
42
+ }
43
+ /** Only this request policy can declare a terminal retry decision. */
44
+ export function isGoogleRecoveryExhausted(error) {
45
+ const seen = new Set();
46
+ while (typeof error === 'object' && error !== null && !seen.has(error)) {
47
+ if (error[TERMINAL_RETRY_DECISION] === true)
48
+ return true;
49
+ seen.add(error);
50
+ error = error.cause;
51
+ }
52
+ return false;
53
+ }
54
+ export function preserveGoogleRetryDecision(target, cause) {
55
+ if (isGoogleRecoveryExhausted(cause))
56
+ Object.defineProperty(target, TERMINAL_RETRY_DECISION, { value: true });
57
+ return target;
58
+ }
59
+ function retryAfterMs(error) {
60
+ // gaxios 7 uses Headers; accept plain objects as well for transport adapters.
61
+ const headers = error.response?.headers;
62
+ const value = headers && 'get' in headers && typeof headers.get === 'function'
63
+ ? headers.get('retry-after')
64
+ : headers?.['retry-after'];
65
+ if (typeof value !== 'string')
66
+ return 0;
67
+ if (/^\d+(?:\.\d+)?$/.test(value.trim()))
68
+ return Number(value) * 1000;
69
+ const date = Date.parse(value);
70
+ return Number.isFinite(date) ? Math.max(0, date - Date.now()) : 0;
71
+ }
72
+ export function createGoogleRetryConfig({ sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)), random = Math.random, } = {}) {
73
+ return {
74
+ shouldRetry(error) {
75
+ if ((error.config.signal?.aborted && error.code !== 'TimeoutError') || error.code === 'AbortError')
76
+ return false;
77
+ const method = error.config.method?.toUpperCase() ?? 'GET';
78
+ if (!RETRY_METHODS.has(method))
79
+ return false;
80
+ const attempt = error.config.retryConfig?.currentRetryAttempt ?? 0;
81
+ const extractedStatus = extractHttpStatus(error);
82
+ if (EXTENDED_RATE_LIMIT_METHODS.has(method) && (extractedStatus === 403 || extractedStatus === 429) && LONG_WINDOW_QUOTA.test(errorText(error)))
83
+ return false;
84
+ if (EXTENDED_RATE_LIMIT_METHODS.has(method) && isShortWindowRateLimit(error)) {
85
+ if (attempt >= MAX_RATE_LIMIT_RETRIES || retryAfterMs(error) > MAX_RETRY_AFTER_MS) {
86
+ Object.defineProperty(error, TERMINAL_RETRY_DECISION, { value: true });
87
+ return false;
88
+ }
89
+ return true;
90
+ }
91
+ if (!error.response)
92
+ return attempt < 2;
93
+ const status = error.response.status;
94
+ return attempt < 3 && ((status >= 100 && status <= 199) || status === 408 ||
95
+ status === 429 || (status >= 500 && status <= 599));
96
+ },
97
+ async retryBackoff(error, gaxiosDelay) {
98
+ const method = error.config.method?.toUpperCase() ?? 'GET';
99
+ if (!EXTENDED_RATE_LIMIT_METHODS.has(method) || !isShortWindowRateLimit(error))
100
+ return sleep(gaxiosDelay);
101
+ // gaxios increments currentRetryAttempt BEFORE calling retryBackoff.
102
+ const n = Math.max(0, (error.config.retryConfig?.currentRetryAttempt ?? 1) - 1);
103
+ const cap = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** n);
104
+ await sleep(Math.max(retryAfterMs(error), cap * (2 + random()) / 3));
105
+ },
106
+ };
107
+ }
108
+ //# sourceMappingURL=google-retry.js.map
@@ -1,5 +1,6 @@
1
1
  import { google } from 'googleapis';
2
2
  import logger from './logger.js';
3
+ import { createGoogleRetryConfig } from './google-retry.js';
3
4
  export const DEFAULT_GOOGLE_WORKSPACE_REQUEST_TIMEOUT_MS = 60_000;
4
5
  const MAX_GOOGLE_WORKSPACE_REQUEST_TIMEOUT_MS = 5 * 60_000;
5
6
  export function resolveRequestTimeoutMs() {
@@ -22,6 +23,7 @@ export function composeAbortSignal(caller) {
22
23
  export function applyDefaultGoogleRequestOptions() {
23
24
  google.options({
24
25
  timeout: resolveRequestTimeoutMs(),
26
+ retryConfig: createGoogleRetryConfig(),
25
27
  });
26
28
  }
27
29
  //# sourceMappingURL=request-timeout.js.map
@@ -30,6 +30,15 @@ export declare function wrapUntrusted(text: string | null | undefined, source: s
30
30
  * structural and NOT wrapped; non-string leaves pass through unchanged.
31
31
  */
32
32
  export declare function wrapUntrustedJsonStrings<T>(value: T, source: string): T;
33
+ /**
34
+ * Wrap external text, except provider-generated controls at declared response
35
+ * paths. A `*` segment matches array items only; `{}` explicitly matches the
36
+ * values of an object map at that path, without exempting other map content.
37
+ * Calendar event ids use separate declared paths with Google's base32hex and
38
+ * recurring-instance shape check. Other author-chosen ids (e.g. Slides object
39
+ * ids), headers, titles, and metadata must not be declared as controls.
40
+ */
41
+ export declare function wrapUntrustedJsonControls<T>(value: T, source: string, controlPaths: readonly string[], eventIdPaths?: readonly string[], calendarIdPaths?: readonly string[]): T;
33
42
  /**
34
43
  * Connector-local alias for `wrapUntrusted` under the name the existing call
35
44
  * sites were written against. `content` is required (never `undefined`), so
@@ -63,6 +63,43 @@ export function wrapUntrustedJsonStrings(value, source) {
63
63
  }
64
64
  return value;
65
65
  }
66
+ /**
67
+ * Wrap external text, except provider-generated controls at declared response
68
+ * paths. A `*` segment matches array items only; `{}` explicitly matches the
69
+ * values of an object map at that path, without exempting other map content.
70
+ * Calendar event ids use separate declared paths with Google's base32hex and
71
+ * recurring-instance shape check. Other author-chosen ids (e.g. Slides object
72
+ * ids), headers, titles, and metadata must not be declared as controls.
73
+ */
74
+ export function wrapUntrustedJsonControls(value, source, controlPaths, eventIdPaths = [], calendarIdPaths = []) {
75
+ const paths = [
76
+ ...controlPaths.map(path => ({ segments: path.split('.'), shape: /^[A-Za-z0-9_+/=.~!\-]+$/ })),
77
+ ...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)?)?$/ })),
78
+ // Calendar-list ids are provider-issued addresses, including public holiday calendars.
79
+ ...calendarIdPaths.map(path => ({ segments: path.split('.'), shape: /^[A-Za-z0-9_.+%#=\-]+@[A-Za-z0-9.\-]+$/ })),
80
+ ];
81
+ function visit(item, remaining) {
82
+ if (typeof item === 'string') {
83
+ // Compare the full match because JavaScript's $ also accepts a trailing newline.
84
+ return remaining.some(path => path.segments.length === 0 && path.shape.exec(item)?.[0] === item)
85
+ ? item : wrapUntrusted(item, source);
86
+ }
87
+ if (Array.isArray(item)) {
88
+ const children = remaining.filter(path => path.segments[0] === '*')
89
+ .map(path => ({ ...path, segments: path.segments.slice(1) }));
90
+ return item.map(child => visit(child, children));
91
+ }
92
+ if (item && typeof item === 'object') {
93
+ return Object.fromEntries(Object.entries(item).map(([key, child]) => [key,
94
+ visit(child, remaining.filter(path => path.segments[0] === '{}' ||
95
+ (path.segments[0] !== '*' && path.segments[0] === key))
96
+ .map(path => ({ ...path, segments: path.segments.slice(1) }))),
97
+ ]));
98
+ }
99
+ return item;
100
+ }
101
+ return visit(value, paths);
102
+ }
66
103
  /**
67
104
  * Connector-local alias for `wrapUntrusted` under the name the existing call
68
105
  * sites were written against. `content` is required (never `undefined`), so
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mindstone/mcp-server-google-workspace",
3
- "version": "0.5.2",
3
+ "version": "0.5.4",
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",
@@ -46,7 +46,8 @@
46
46
  "@modelcontextprotocol/sdk": "^0.7.0",
47
47
  "google-auth-library": "^10.2.0",
48
48
  "googleapis": "^171.4.0",
49
- "uuid": "^11.1.0"
49
+ "uuid": "^11.1.0",
50
+ "zod": "^3.23.0"
50
51
  },
51
52
  "devDependencies": {
52
53
  "@mindstone/mcp-app-compose": "file:../../packages/mcp-app-compose",