@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.
- package/README.md +19 -1
- package/dist/file-read-context.d.ts +57 -0
- package/dist/file-read-context.js +36 -0
- package/dist/modules/calendar/service.js +97 -90
- package/dist/modules/comments/service.js +6 -6
- package/dist/modules/docs/service.js +15 -11
- package/dist/modules/docs/types.d.ts +4 -0
- package/dist/modules/drive/service.js +1 -17
- package/dist/modules/forms/service.js +4 -4
- package/dist/modules/gmail/services/attachment.js +3 -1
- package/dist/modules/gmail/services/base.js +3 -1
- package/dist/modules/gmail/services/draft.js +13 -1
- package/dist/modules/gmail/services/email.js +13 -4
- package/dist/modules/gmail/services/label.js +19 -1
- package/dist/modules/gmail/services/settings.js +7 -1
- package/dist/modules/sheets/service.js +18 -18
- package/dist/modules/slides/service.js +7 -7
- package/dist/modules/tasks/service.js +7 -7
- package/dist/services/base/BaseGoogleService.js +2 -2
- package/dist/services/chat/index.js +3 -0
- package/dist/services/contacts/index.js +8 -5
- package/dist/services/meet/index.js +3 -0
- package/dist/tools/calendar-handlers.js +7 -7
- package/dist/tools/chat-handlers.js +4 -4
- package/dist/tools/contacts-handlers.js +5 -5
- package/dist/tools/definitions/gmail.js +4 -0
- package/dist/tools/docs-handlers.js +14 -6
- package/dist/tools/drive-handlers.d.ts +2 -1
- package/dist/tools/drive-handlers.js +21 -16
- package/dist/tools/gmail-handlers.d.ts +6 -5
- package/dist/tools/gmail-handlers.js +39 -27
- package/dist/tools/meet-handlers.js +4 -4
- package/dist/tools/server.js +24 -10
- package/dist/tools/sheets-handlers.js +4 -4
- package/dist/tools/slides-handlers.js +4 -4
- package/dist/utils/apiError.d.ts +7 -3
- package/dist/utils/apiError.js +37 -16
- package/dist/utils/google-retry.d.ts +15 -0
- package/dist/utils/google-retry.js +108 -0
- package/dist/utils/request-timeout.js +2 -0
- package/dist/utils/untrusted-content.d.ts +9 -0
- package/dist/utils/untrusted-content.js +37 -0
- package/package.json +3 -2
package/dist/tools/server.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
|
+
import { FILE_READ_CAPABILITIES, fileReadContext } from '../file-read-context.js';
|
|
1
2
|
import { createRequire } from 'node:module';
|
|
2
3
|
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
3
4
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
5
|
import logger from '../utils/logger.js';
|
|
6
|
+
import { GOOGLE_RATE_LIMIT_NEXT_STEP, isGoogleRecoveryExhausted, isShortWindowRateLimit } from '../utils/google-retry.js';
|
|
7
|
+
import { describeApiErrorUntrusted } from '../utils/apiError.js';
|
|
5
8
|
import { CallToolRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
|
|
6
9
|
const require = createRequire(import.meta.url);
|
|
7
10
|
const pkg = require('../../package.json');
|
|
@@ -93,6 +96,7 @@ export class GSuiteServer {
|
|
|
93
96
|
version: SERVER_VERSION
|
|
94
97
|
}, {
|
|
95
98
|
capabilities: {
|
|
99
|
+
...FILE_READ_CAPABILITIES,
|
|
96
100
|
tools: {
|
|
97
101
|
list: true,
|
|
98
102
|
call: true
|
|
@@ -118,6 +122,7 @@ export class GSuiteServer {
|
|
|
118
122
|
name: tool.name,
|
|
119
123
|
description: tool.description,
|
|
120
124
|
inputSchema: tool.inputSchema,
|
|
125
|
+
_meta: tool._meta,
|
|
121
126
|
annotations: tool.annotations
|
|
122
127
|
}));
|
|
123
128
|
}
|
|
@@ -126,6 +131,7 @@ export class GSuiteServer {
|
|
|
126
131
|
name: tool.name,
|
|
127
132
|
description: tool.description,
|
|
128
133
|
inputSchema: tool.inputSchema,
|
|
134
|
+
_meta: tool._meta,
|
|
129
135
|
annotations: tool.annotations
|
|
130
136
|
})),
|
|
131
137
|
_meta: {
|
|
@@ -149,6 +155,7 @@ export class GSuiteServer {
|
|
|
149
155
|
// Handle tool calls
|
|
150
156
|
this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
|
|
151
157
|
try {
|
|
158
|
+
const reads = fileReadContext(this.server.getClientCapabilities(), { _meta: request.params._meta });
|
|
152
159
|
const rawArgs = request.params.arguments;
|
|
153
160
|
const args = rawArgs && typeof rawArgs === 'object' && !Array.isArray(rawArgs)
|
|
154
161
|
? normalizeArgs(rawArgs)
|
|
@@ -190,7 +197,7 @@ export class GSuiteServer {
|
|
|
190
197
|
break;
|
|
191
198
|
case 'send_workspace_email':
|
|
192
199
|
assertSendEmailArgs(args);
|
|
193
|
-
result = await handleSendWorkspaceEmail(args);
|
|
200
|
+
result = await handleSendWorkspaceEmail(args, reads);
|
|
194
201
|
break;
|
|
195
202
|
case 'get_workspace_gmail_settings':
|
|
196
203
|
assertBaseToolArguments(args);
|
|
@@ -236,11 +243,11 @@ export class GSuiteServer {
|
|
|
236
243
|
break;
|
|
237
244
|
case 'create_workspace_draft':
|
|
238
245
|
assertBaseToolArguments(args);
|
|
239
|
-
result = await handleCreateWorkspaceDraft(args);
|
|
246
|
+
result = await handleCreateWorkspaceDraft(args, reads);
|
|
240
247
|
break;
|
|
241
248
|
case 'update_workspace_draft':
|
|
242
249
|
assertBaseToolArguments(args);
|
|
243
|
-
result = await handleUpdateWorkspaceDraft(args);
|
|
250
|
+
result = await handleUpdateWorkspaceDraft(args, reads);
|
|
244
251
|
break;
|
|
245
252
|
case 'delete_workspace_draft':
|
|
246
253
|
assertBaseToolArguments(args);
|
|
@@ -253,7 +260,7 @@ export class GSuiteServer {
|
|
|
253
260
|
// Draft Management (deprecated)
|
|
254
261
|
case 'manage_workspace_draft':
|
|
255
262
|
assertManageDraftParams(args);
|
|
256
|
-
result = await handleManageWorkspaceDraft(args);
|
|
263
|
+
result = await handleManageWorkspaceDraft(args, reads);
|
|
257
264
|
break;
|
|
258
265
|
// Individual Attachment Operations
|
|
259
266
|
case 'download_workspace_attachment':
|
|
@@ -723,7 +730,10 @@ export class GSuiteServer {
|
|
|
723
730
|
};
|
|
724
731
|
}
|
|
725
732
|
catch (error) {
|
|
726
|
-
const response =
|
|
733
|
+
const response = {
|
|
734
|
+
...this.formatErrorResponse(error),
|
|
735
|
+
...(isGoogleRecoveryExhausted(error) ? { recoveryExhausted: true } : {}),
|
|
736
|
+
};
|
|
727
737
|
return {
|
|
728
738
|
content: [{ type: 'text', text: JSON.stringify(response, null, 2) }],
|
|
729
739
|
isError: true,
|
|
@@ -733,7 +743,7 @@ export class GSuiteServer {
|
|
|
733
743
|
});
|
|
734
744
|
}
|
|
735
745
|
formatErrorResponse(error) {
|
|
736
|
-
const
|
|
746
|
+
const recoveryExhausted = isGoogleRecoveryExhausted(error);
|
|
737
747
|
// Read the string domain-error `code` from ANY domain error, not just AccountError:
|
|
738
748
|
// CalendarError/GmailError/ContactsError all expose a string `code`, and a
|
|
739
749
|
// `getCalendarClient` auth failure surfaces as `CalendarError('AUTH_REQUIRED')`, not an
|
|
@@ -773,18 +783,22 @@ export class GSuiteServer {
|
|
|
773
783
|
setupToolName: 'authenticate_workspace_account'
|
|
774
784
|
};
|
|
775
785
|
}
|
|
776
|
-
|
|
786
|
+
const rateLimited = numericStatus === 429 || recoveryExhausted || isShortWindowRateLimit(error);
|
|
787
|
+
const message = rateLimited
|
|
788
|
+
? describeApiErrorUntrusted(error, 'google-workspace:api-error')
|
|
789
|
+
: error instanceof Error ? error.message : 'Unknown error occurred';
|
|
790
|
+
if (rateLimited) {
|
|
777
791
|
return {
|
|
778
792
|
ok: false,
|
|
779
793
|
action_required: message,
|
|
780
|
-
next_step:
|
|
794
|
+
next_step: GOOGLE_RATE_LIMIT_NEXT_STEP
|
|
781
795
|
};
|
|
782
796
|
}
|
|
783
|
-
if (numericStatus ===
|
|
797
|
+
if (numericStatus === 403) {
|
|
784
798
|
return {
|
|
785
799
|
ok: false,
|
|
786
800
|
action_required: message,
|
|
787
|
-
next_step: 'Google Workspace
|
|
801
|
+
next_step: 'Google Workspace rejected the request due to insufficient permissions or scopes. Reconnect the account with the required scope or ask the file/calendar owner for access, then retry.'
|
|
788
802
|
};
|
|
789
803
|
}
|
|
790
804
|
if (numericStatus !== undefined && numericStatus >= 500 && numericStatus <= 599) {
|
|
@@ -5,7 +5,7 @@ import { ActionableA1Error, normaliseA1Range } from '../modules/sheets/a1Utils.j
|
|
|
5
5
|
import { rewriteSheetsApiError } from '../modules/sheets/errorRewriter.js';
|
|
6
6
|
import { VALUES_TRUNCATION_NOTICE, extractSpreadsheetIdFromUrl, firstSheetRowNumber, formatAnchorReadResponse, formatSpreadsheetAsText, formatOperationResult, formatShapedReadResponse, formatValuesAsTable, formatSheetListResultAsText, formatSheetAddedAsText, formatSheetDuplicatedAsText, formatSheetUpdatedAsText, formatDimensionInsertedAsText, } from '../modules/sheets/formatters.js';
|
|
7
7
|
import { readAliasedBoolean, readAliasedNumber, readAliasedString, readAliasedValue } from './arg-aliases.js';
|
|
8
|
-
import {
|
|
8
|
+
import { wrapUntrustedJsonControls } from '../utils/untrusted-content.js';
|
|
9
9
|
function normaliseRangeOrThrow(range) {
|
|
10
10
|
try {
|
|
11
11
|
return normaliseA1Range(range);
|
|
@@ -88,7 +88,7 @@ export async function handleReadSpreadsheet(args) {
|
|
|
88
88
|
throw new McpError(ErrorCode.InternalError, rewriteSheetsHandlerError(result.error, 'Failed to read spreadsheet', 'read_workspace_spreadsheet', rawArgs));
|
|
89
89
|
}
|
|
90
90
|
if (returnJson) {
|
|
91
|
-
return
|
|
91
|
+
return wrapUntrustedJsonControls(result.data, `google-workspace:sheets:spreadsheet/${spreadsheetId}`, ['spreadsheetId', 'continuationToken', 'data.continuationToken']);
|
|
92
92
|
}
|
|
93
93
|
// Format as human-readable text
|
|
94
94
|
const response = result.data;
|
|
@@ -148,7 +148,7 @@ export async function handleReadSpreadsheetValues(args) {
|
|
|
148
148
|
throw new McpError(ErrorCode.InternalError, rewriteSheetsHandlerError(result.error, 'Failed to read spreadsheet values', 'read_workspace_spreadsheet_values', rawArgs));
|
|
149
149
|
}
|
|
150
150
|
if (returnJson) {
|
|
151
|
-
return
|
|
151
|
+
return wrapUntrustedJsonControls(result.data, `google-workspace:sheets:values/${spreadsheetId}`, ['spreadsheetId', 'continuationToken', 'data.continuationToken']);
|
|
152
152
|
}
|
|
153
153
|
if (isAnchorReadResponse(result.data)) {
|
|
154
154
|
return formatAnchorReadResponse(result.data);
|
|
@@ -503,7 +503,7 @@ export async function handleBatchGetValues(args) {
|
|
|
503
503
|
throw new McpError(ErrorCode.InternalError, rewriteSheetsHandlerError(result.error, 'Failed to batch read values', 'batch_read_workspace_spreadsheet_values', rawArgs));
|
|
504
504
|
}
|
|
505
505
|
if (returnJson) {
|
|
506
|
-
return
|
|
506
|
+
return wrapUntrustedJsonControls(result.data, `google-workspace:sheets:batch/${spreadsheetId}`, ['*.data.continuationToken']);
|
|
507
507
|
}
|
|
508
508
|
if (valueView === 'shaped') {
|
|
509
509
|
const shapedRanges = result.data;
|
|
@@ -3,7 +3,7 @@ import { getAccountManager, resolveEmail } from '../modules/accounts/index.js';
|
|
|
3
3
|
import { getSlidesService } from '../modules/slides/index.js';
|
|
4
4
|
import { extractPresentationIdFromUrl } from '../modules/slides/formatters.js';
|
|
5
5
|
import { readAliasedBoolean, readAliasedNumber, readAliasedString, readAliasedValue } from './arg-aliases.js';
|
|
6
|
-
import { wrapUntrustedContent,
|
|
6
|
+
import { wrapUntrustedContent, wrapUntrustedJsonControls } from '../utils/untrusted-content.js';
|
|
7
7
|
/**
|
|
8
8
|
* Format PresentationResponse as human-readable text
|
|
9
9
|
*/
|
|
@@ -100,7 +100,7 @@ export async function handleReadPresentation(args) {
|
|
|
100
100
|
throw new McpError(ErrorCode.InternalError, result.error || 'Failed to read presentation');
|
|
101
101
|
}
|
|
102
102
|
if (returnJson) {
|
|
103
|
-
return
|
|
103
|
+
return wrapUntrustedJsonControls(result.data, `google-workspace:slides:presentation/${presentationId}`, ['presentationId']);
|
|
104
104
|
}
|
|
105
105
|
// Format as human-readable text
|
|
106
106
|
const presResponse = result.data;
|
|
@@ -172,7 +172,7 @@ export async function handleGetSlide(args) {
|
|
|
172
172
|
throw new McpError(ErrorCode.InternalError, result.error || 'Failed to get slide');
|
|
173
173
|
}
|
|
174
174
|
if (returnJson) {
|
|
175
|
-
return
|
|
175
|
+
return wrapUntrustedJsonControls(result.data, `google-workspace:slides:slide/${presentationId}`, ['presentationId']);
|
|
176
176
|
}
|
|
177
177
|
// Format as human-readable text
|
|
178
178
|
const slides = result.data;
|
|
@@ -220,7 +220,7 @@ export async function handleBatchUpdatePresentation(args) {
|
|
|
220
220
|
throw new McpError(ErrorCode.InternalError, result.error || 'Failed to update presentation');
|
|
221
221
|
}
|
|
222
222
|
if (returnJson) {
|
|
223
|
-
return
|
|
223
|
+
return wrapUntrustedJsonControls(result.data, `google-workspace:slides:batch/${presentationId}`, ['presentationId']);
|
|
224
224
|
}
|
|
225
225
|
// Format as human-readable text
|
|
226
226
|
const response = result.data;
|
package/dist/utils/apiError.d.ts
CHANGED
|
@@ -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.
|
|
51
|
-
*
|
|
52
|
-
*
|
|
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
|
package/dist/utils/apiError.js
CHANGED
|
@@ -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
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
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.
|
|
95
|
-
*
|
|
96
|
-
*
|
|
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
|
-
:
|
|
106
|
-
|
|
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.
|
|
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",
|