google-mcp-suite 1.11.0 → 1.11.2

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.
@@ -5,6 +5,14 @@ import { OAuth2Client } from 'google-auth-library';
5
5
  * token as needed.
6
6
  */
7
7
  export declare function authorizedClient(account?: string): Promise<OAuth2Client>;
8
+ /**
9
+ * True when an error is Google's token endpoint refusing the stored refresh
10
+ * token (`invalid_grant`: expired or revoked). No retry with the same client
11
+ * can succeed, but a rebuild from disk heals the instance after a re-auth.
12
+ * A false negative degrades to the plain error envelope; the shape check
13
+ * makes a false positive structurally impossible.
14
+ */
15
+ export declare function isInvalidGrant(error: unknown): boolean;
8
16
  /**
9
17
  * Run the browser consent flow for `account` and persist its token. The token
10
18
  * file is written 0600 inside a 0700 tokens dir; the consent requests offline
@@ -1 +1 @@
1
- {"version":3,"file":"oauth.d.ts","sourceRoot":"","sources":["../../src/auth/oauth.ts"],"names":[],"mappings":"AAGA,OAAO,EAAuB,YAAY,EAAE,MAAM,qBAAqB,CAAC;AA6DxE;;;;GAIG;AACH,wBAAsB,gBAAgB,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC,CAQ9E;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,WAAW,CAC/B,OAAO,CAAC,EAAE,MAAM,EAChB,OAAO,GAAE;IACP,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC;IACvC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;CACf,GACL,OAAO,CAAC,IAAI,CAAC,CAmGf"}
1
+ {"version":3,"file":"oauth.d.ts","sourceRoot":"","sources":["../../src/auth/oauth.ts"],"names":[],"mappings":"AAGA,OAAO,EAAuB,YAAY,EAAE,MAAM,qBAAqB,CAAC;AA6DxE;;;;GAIG;AACH,wBAAsB,gBAAgB,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC,CAQ9E;AAYD;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAGtD;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,WAAW,CAC/B,OAAO,CAAC,EAAE,MAAM,EAChB,OAAO,GAAE;IACP,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC;IACvC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;CACf,GACL,OAAO,CAAC,IAAI,CAAC,CAmGf"}
@@ -64,6 +64,26 @@ export async function authorizedClient(account) {
64
64
  client.setCredentials(forGoogle(token));
65
65
  return client;
66
66
  }
67
+ /**
68
+ * The shape gaxios gives an error when Google's token endpoint rejects a
69
+ * refresh: `response.data.error` carries the OAuth 2.0 error code (RFC 6749
70
+ * section 5.2). Typed on the response body, never on message text, so an
71
+ * operation error that merely mentions "invalid_grant" cannot match.
72
+ */
73
+ const TokenEndpointError = z.object({
74
+ response: z.object({ data: z.object({ error: z.string() }) }),
75
+ });
76
+ /**
77
+ * True when an error is Google's token endpoint refusing the stored refresh
78
+ * token (`invalid_grant`: expired or revoked). No retry with the same client
79
+ * can succeed, but a rebuild from disk heals the instance after a re-auth.
80
+ * A false negative degrades to the plain error envelope; the shape check
81
+ * makes a false positive structurally impossible.
82
+ */
83
+ export function isInvalidGrant(error) {
84
+ const parsed = TokenEndpointError.safeParse(error);
85
+ return parsed.success && parsed.data.response.data.error === 'invalid_grant';
86
+ }
67
87
  /**
68
88
  * Run the browser consent flow for `account` and persist its token. The token
69
89
  * file is written 0600 inside a 0700 tokens dir; the consent requests offline
@@ -1 +1 @@
1
- {"version":3,"file":"oauth.js","sourceRoot":"","sources":["../../src/auth/oauth.ts"],"names":[],"mappings":"AAAA,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YAC5B,MAAM,CAAC,KAAK,EAAE,CAAC;YACf,MAAM,CAAC,IAAI,KAAK,CAAC,iCAAiC,SAAS,wBAAwB,CAAC,CAAC,CAAC;QACxF,CAAC,EAAE,SAAS,CAAC,CAAC;QACd,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;YACzB,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,MAAM,CAAC,GAAG,CAAC,CAAC;QACd,CAAC,CAAC,CAAC;QACH,uEAAuE;QACvE,2DAA2D;QAC3D,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;QACjC,OAAO,CAAC,KAAK,CAAC,+BAA+B,IAAI,MAAM,OAAO,EAAE,CAAC,CAAC;QAClE,KAAK,WAAW,CAAC,OAAO,CAAC,CAAC;IAC5B,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { randomBytes } from 'node:crypto';\nimport { chmodSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';\nimport { createServer } from 'node:http';\nimport { CodeChallengeMethod, OAuth2Client } from 'google-auth-library';\nimport open from 'open';\nimport { z } from 'zod';\nimport { forGoogle } from '../lib/optionality.js';\nimport { readJsonFile } from '../lib/utils/json.js';\nimport { loadConfig, resolveAccount, SCOPES, tokenPath } from './config.js';\n\n// The loopback IP literal, not `localhost` (RFC 8252 section 8.3, and Google's\n// loopback guidance): name resolution is host-file-manipulable and can point\n// `localhost` at ::1 where nothing listens.\nconst redirectUri = (port: number) => `http://127.0.0.1:${port}/oauth2callback`;\n\nconst ClientKeys = z.object({\n client_id: z.string().optional(),\n client_secret: z.string().optional(),\n});\n\n/** The two shapes Google's console downloads use; everything else is rejected below. */\nconst ClientSecretFile = z.object({\n installed: ClientKeys.optional(),\n web: ClientKeys.optional(),\n});\n\ntype ClientSecret = { client_id: string; client_secret: string };\n\nfunction loadClientSecret(): ClientSecret {\n const secretPath = loadConfig().clientSecretPath;\n let raw: z.infer<typeof ClientSecretFile>;\n try {\n raw = readJsonFile(secretPath, ClientSecretFile);\n } catch (err) {\n if (err instanceof z.ZodError) {\n throw new Error(\n `Invalid OAuth client secret at ${secretPath} (expected \"installed\" or \"web\").`,\n );\n }\n throw err;\n }\n const keys = raw.installed ?? raw.web;\n if (!keys?.client_id || !keys.client_secret) {\n throw new Error(\n `Invalid OAuth client secret at ${secretPath} (expected \"installed\" or \"web\").`,\n );\n }\n return { client_id: keys.client_id, client_secret: keys.client_secret };\n}\n\n/**\n * The token fields the library refreshes from; everything else Google stores\n * in the file rides along untyped (the file is this suite's own write).\n */\nconst StoredToken = z.looseObject({\n access_token: z.string().optional(),\n refresh_token: z.string().optional(),\n});\n\nfunction newClient(port = 3000): OAuth2Client {\n const { client_id, client_secret } = loadClientSecret();\n return new OAuth2Client(client_id, client_secret, redirectUri(port));\n}\n\n/**\n * Build an authenticated client for `account` (default: GOOGLE_MCP_ACCOUNT) from\n * its stored token. The library auto-refreshes the access token from the refresh\n * token as needed.\n */\nexport async function authorizedClient(account?: string): Promise<OAuth2Client> {\n const client = newClient();\n const config = loadConfig();\n const token = readJsonFile(tokenPath(resolveAccount(account, config), config), StoredToken);\n // forGoogle drops undefined-valued keys, reconciling zod's `?: T | undefined`\n // with the library's exactOptionalPropertyTypes-strict Credentials.\n client.setCredentials(forGoogle(token));\n return client;\n}\n\n/**\n * Run the browser consent flow for `account` and persist its token. The token\n * file is written 0600 inside a 0700 tokens dir; the consent requests offline\n * access and forces the screen so a refresh token is always returned. The flow\n * carries a random `state` (verified at the callback: any browser tab can fire\n * requests at the loopback port, since CORS blocks reads, not sends, so only\n * the redirect Google issued for this flow is accepted) and PKCE (RFC 8252\n * section 8.1: a local process that wins a race for the port cannot exchange\n * an intercepted code without the verifier). `port`, `openBrowser`, and\n * `timeoutMs` are injectable for testing; the callback server is closed on\n * every exit path, including an abandoned consent. `loginHint` prefills the\n * Google account chooser when the account label is not itself an email\n * (e.g. a short alias like `personal`).\n */\nexport async function runAuthFlow(\n account?: string,\n options: {\n port?: number;\n openBrowser?: (url: string) => unknown;\n loginHint?: string;\n timeoutMs?: number;\n } = {},\n): Promise<void> {\n const port = options.port ?? 3000;\n const openBrowser = options.openBrowser ?? open;\n const timeoutMs = options.timeoutMs ?? 5 * 60 * 1000;\n const config = loadConfig();\n const acct = resolveAccount(account, config);\n const client = newClient(port);\n const loginHint = options.loginHint ?? (acct.includes('@') ? acct : undefined);\n const { codeVerifier, codeChallenge } = await client.generateCodeVerifierAsync();\n if (!codeChallenge) {\n throw new Error('PKCE challenge generation failed; cannot start the consent flow.');\n }\n const state = randomBytes(16).toString('hex');\n const authUrl = client.generateAuthUrl({\n access_type: 'offline',\n prompt: 'consent',\n scope: SCOPES,\n state,\n code_challenge_method: CodeChallengeMethod.S256,\n code_challenge: codeChallenge,\n ...(loginHint ? { login_hint: loginHint } : {}),\n });\n\n await new Promise<void>((resolve, reject) => {\n const server = createServer(async (req, res) => {\n // Absolute-form request targets reach req.url verbatim, and an\n // unparseable one (proxy-style \"GET http:// HTTP/1.1\") would throw in\n // the URL constructor; answer 400 rather than crash the flow on an\n // unhandled rejection.\n let requested: URL;\n try {\n requested = new URL(req.url ?? '/', redirectUri(port));\n } catch {\n res.writeHead(400);\n res.end();\n return;\n }\n if (requested.pathname !== '/oauth2callback') {\n // Browsers probe for favicons; answer rather than leave sockets hanging.\n res.writeHead(404);\n res.end();\n return;\n }\n const finish = (status: number, body: string, err?: unknown) => {\n res.writeHead(status);\n res.end(body);\n clearTimeout(timer);\n server.close();\n if (err) {\n reject(err);\n } else {\n resolve();\n }\n };\n const params = requested.searchParams;\n if (params.get('state') !== state) {\n finish(403, 'State mismatch.', new Error('OAuth state mismatch; possible CSRF.'));\n return;\n }\n const code = params.get('code');\n if (!code) {\n finish(\n 400,\n 'No authorization code provided.',\n new Error('No authorization code provided.'),\n );\n return;\n }\n try {\n const { tokens } = await client.getToken({ code, codeVerifier });\n mkdirSync(config.tokensDir, { recursive: true, mode: 0o700 });\n // mkdir's mode applies only on create; tighten a pre-existing dir so\n // token filenames (account labels) stay unreadable to other users.\n chmodSync(config.tokensDir, 0o700);\n const file = tokenPath(acct, config);\n // Recreate rather than overwrite: writeFileSync applies mode only on\n // create, and tightening afterwards would leave fresh token bytes\n // briefly readable through a pre-existing looser mode.\n rmSync(file, { force: true });\n writeFileSync(file, JSON.stringify(tokens), { mode: 0o600 });\n finish(200, `Authorized ${acct}. You can close this window.`);\n } catch (error) {\n finish(500, 'Authentication failed.', error);\n }\n });\n const timer = setTimeout(() => {\n server.close();\n reject(new Error(`Authorization timed out after ${timeoutMs}ms; rerun doctor auth.`));\n }, timeoutMs);\n server.on('error', (err) => {\n clearTimeout(timer);\n reject(err);\n });\n // Loopback only (RFC 8252 section 8.3): with no host, Node binds every\n // interface and the consent port is briefly LAN-reachable.\n server.listen(port, '127.0.0.1');\n console.error(`Visit this URL to authorize ${acct}:\\n${authUrl}`);\n void openBrowser(authUrl);\n });\n}\n"]}
1
+ {"version":3,"file":"oauth.js","sourceRoot":"","sources":["../../src/auth/oauth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACtE,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACxE,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE5E,+EAA+E;AAC/E,6EAA6E;AAC7E,4CAA4C;AAC5C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AAS,wBAAwB,CAAC,CAAC,CAAC;QACxF,CAAC,EAAE,SAAS,CAAC,CAAC;QACd,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;YACzB,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,MAAM,CAAC,GAAG,CAAC,CAAC;QACd,CAAC,CAAC,CAAC;QACH,uEAAuE;QACvE,2DAA2D;QAC3D,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;QACjC,OAAO,CAAC,KAAK,CAAC,+BAA+B,IAAI,MAAM,OAAO,EAAE,CAAC,CAAC;QAClE,KAAK,WAAW,CAAC,OAAO,CAAC,CAAC;IAC5B,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { randomBytes } from 'node:crypto';\nimport { chmodSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';\nimport { createServer } from 'node:http';\nimport { CodeChallengeMethod, OAuth2Client } from 'google-auth-library';\nimport open from 'open';\nimport { z } from 'zod';\nimport { forGoogle } from '../lib/optionality.js';\nimport { readJsonFile } from '../lib/utils/json.js';\nimport { loadConfig, resolveAccount, SCOPES, tokenPath } from './config.js';\n\n// The loopback IP literal, not `localhost` (RFC 8252 section 8.3, and Google's\n// loopback guidance): name resolution is host-file-manipulable and can point\n// `localhost` at ::1 where nothing listens.\nconst redirectUri = (port: number) => `http://127.0.0.1:${port}/oauth2callback`;\n\nconst ClientKeys = z.object({\n client_id: z.string().optional(),\n client_secret: z.string().optional(),\n});\n\n/** The two shapes Google's console downloads use; everything else is rejected below. */\nconst ClientSecretFile = z.object({\n installed: ClientKeys.optional(),\n web: ClientKeys.optional(),\n});\n\ntype ClientSecret = { client_id: string; client_secret: string };\n\nfunction loadClientSecret(): ClientSecret {\n const secretPath = loadConfig().clientSecretPath;\n let raw: z.infer<typeof ClientSecretFile>;\n try {\n raw = readJsonFile(secretPath, ClientSecretFile);\n } catch (err) {\n if (err instanceof z.ZodError) {\n throw new Error(\n `Invalid OAuth client secret at ${secretPath} (expected \"installed\" or \"web\").`,\n );\n }\n throw err;\n }\n const keys = raw.installed ?? raw.web;\n if (!keys?.client_id || !keys.client_secret) {\n throw new Error(\n `Invalid OAuth client secret at ${secretPath} (expected \"installed\" or \"web\").`,\n );\n }\n return { client_id: keys.client_id, client_secret: keys.client_secret };\n}\n\n/**\n * The token fields the library refreshes from; everything else Google stores\n * in the file rides along untyped (the file is this suite's own write).\n */\nconst StoredToken = z.looseObject({\n access_token: z.string().optional(),\n refresh_token: z.string().optional(),\n});\n\nfunction newClient(port = 3000): OAuth2Client {\n const { client_id, client_secret } = loadClientSecret();\n return new OAuth2Client(client_id, client_secret, redirectUri(port));\n}\n\n/**\n * Build an authenticated client for `account` (default: GOOGLE_MCP_ACCOUNT) from\n * its stored token. The library auto-refreshes the access token from the refresh\n * token as needed.\n */\nexport async function authorizedClient(account?: string): Promise<OAuth2Client> {\n const client = newClient();\n const config = loadConfig();\n const token = readJsonFile(tokenPath(resolveAccount(account, config), config), StoredToken);\n // forGoogle drops undefined-valued keys, reconciling zod's `?: T | undefined`\n // with the library's exactOptionalPropertyTypes-strict Credentials.\n client.setCredentials(forGoogle(token));\n return client;\n}\n\n/**\n * The shape gaxios gives an error when Google's token endpoint rejects a\n * refresh: `response.data.error` carries the OAuth 2.0 error code (RFC 6749\n * section 5.2). Typed on the response body, never on message text, so an\n * operation error that merely mentions \"invalid_grant\" cannot match.\n */\nconst TokenEndpointError = z.object({\n response: z.object({ data: z.object({ error: z.string() }) }),\n});\n\n/**\n * True when an error is Google's token endpoint refusing the stored refresh\n * token (`invalid_grant`: expired or revoked). No retry with the same client\n * can succeed, but a rebuild from disk heals the instance after a re-auth.\n * A false negative degrades to the plain error envelope; the shape check\n * makes a false positive structurally impossible.\n */\nexport function isInvalidGrant(error: unknown): boolean {\n const parsed = TokenEndpointError.safeParse(error);\n return parsed.success && parsed.data.response.data.error === 'invalid_grant';\n}\n\n/**\n * Run the browser consent flow for `account` and persist its token. The token\n * file is written 0600 inside a 0700 tokens dir; the consent requests offline\n * access and forces the screen so a refresh token is always returned. The flow\n * carries a random `state` (verified at the callback: any browser tab can fire\n * requests at the loopback port, since CORS blocks reads, not sends, so only\n * the redirect Google issued for this flow is accepted) and PKCE (RFC 8252\n * section 8.1: a local process that wins a race for the port cannot exchange\n * an intercepted code without the verifier). `port`, `openBrowser`, and\n * `timeoutMs` are injectable for testing; the callback server is closed on\n * every exit path, including an abandoned consent. `loginHint` prefills the\n * Google account chooser when the account label is not itself an email\n * (e.g. a short alias like `personal`).\n */\nexport async function runAuthFlow(\n account?: string,\n options: {\n port?: number;\n openBrowser?: (url: string) => unknown;\n loginHint?: string;\n timeoutMs?: number;\n } = {},\n): Promise<void> {\n const port = options.port ?? 3000;\n const openBrowser = options.openBrowser ?? open;\n const timeoutMs = options.timeoutMs ?? 5 * 60 * 1000;\n const config = loadConfig();\n const acct = resolveAccount(account, config);\n const client = newClient(port);\n const loginHint = options.loginHint ?? (acct.includes('@') ? acct : undefined);\n const { codeVerifier, codeChallenge } = await client.generateCodeVerifierAsync();\n if (!codeChallenge) {\n throw new Error('PKCE challenge generation failed; cannot start the consent flow.');\n }\n const state = randomBytes(16).toString('hex');\n const authUrl = client.generateAuthUrl({\n access_type: 'offline',\n prompt: 'consent',\n scope: SCOPES,\n state,\n code_challenge_method: CodeChallengeMethod.S256,\n code_challenge: codeChallenge,\n ...(loginHint ? { login_hint: loginHint } : {}),\n });\n\n await new Promise<void>((resolve, reject) => {\n const server = createServer(async (req, res) => {\n // Absolute-form request targets reach req.url verbatim, and an\n // unparseable one (proxy-style \"GET http:// HTTP/1.1\") would throw in\n // the URL constructor; answer 400 rather than crash the flow on an\n // unhandled rejection.\n let requested: URL;\n try {\n requested = new URL(req.url ?? '/', redirectUri(port));\n } catch {\n res.writeHead(400);\n res.end();\n return;\n }\n if (requested.pathname !== '/oauth2callback') {\n // Browsers probe for favicons; answer rather than leave sockets hanging.\n res.writeHead(404);\n res.end();\n return;\n }\n const finish = (status: number, body: string, err?: unknown) => {\n res.writeHead(status);\n res.end(body);\n clearTimeout(timer);\n server.close();\n if (err) {\n reject(err);\n } else {\n resolve();\n }\n };\n const params = requested.searchParams;\n if (params.get('state') !== state) {\n finish(403, 'State mismatch.', new Error('OAuth state mismatch; possible CSRF.'));\n return;\n }\n const code = params.get('code');\n if (!code) {\n finish(\n 400,\n 'No authorization code provided.',\n new Error('No authorization code provided.'),\n );\n return;\n }\n try {\n const { tokens } = await client.getToken({ code, codeVerifier });\n mkdirSync(config.tokensDir, { recursive: true, mode: 0o700 });\n // mkdir's mode applies only on create; tighten a pre-existing dir so\n // token filenames (account labels) stay unreadable to other users.\n chmodSync(config.tokensDir, 0o700);\n const file = tokenPath(acct, config);\n // Recreate rather than overwrite: writeFileSync applies mode only on\n // create, and tightening afterwards would leave fresh token bytes\n // briefly readable through a pre-existing looser mode.\n rmSync(file, { force: true });\n writeFileSync(file, JSON.stringify(tokens), { mode: 0o600 });\n finish(200, `Authorized ${acct}. You can close this window.`);\n } catch (error) {\n finish(500, 'Authentication failed.', error);\n }\n });\n const timer = setTimeout(() => {\n server.close();\n reject(new Error(`Authorization timed out after ${timeoutMs}ms; rerun doctor auth.`));\n }, timeoutMs);\n server.on('error', (err) => {\n clearTimeout(timer);\n reject(err);\n });\n // Loopback only (RFC 8252 section 8.3): with no host, Node binds every\n // interface and the consent port is briefly LAN-reachable.\n server.listen(port, '127.0.0.1');\n console.error(`Visit this URL to authorize ${acct}:\\n${authUrl}`);\n void openBrowser(authUrl);\n });\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { calendar } from '@googleapis/calendar';
3
- import { authorizedClient, runAuthFlow } from '../auth/oauth.js';
3
+ import { authorizedClient, isInvalidGrant, runAuthFlow } from '../auth/oauth.js';
4
4
  import { mergeOperations } from '../lib/operation.js';
5
5
  import { server } from '../lib/server.js';
6
6
  import { instructions } from './instructions.js';
@@ -19,5 +19,6 @@ await server({
19
19
  operations: mergeOperations(tools, methods),
20
20
  client: async (account) => calendar({ version: 'v3', auth: await authorizedClient(account) }),
21
21
  runAuth: runAuthFlow,
22
+ staleCredentials: isInvalidGrant,
22
23
  });
23
24
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/calendar/index.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAE5C,iFAAiF;AACjF,oFAAoF;AACpF,qFAAqF;AACrF,gFAAgF;AAChF,8DAA8D;AAC9D,MAAM,MAAM,CAAC;IACX,IAAI,EAAE,UAAU;IAChB,KAAK,EAAE,oCAAoC;IAC3C,WAAW,EACT,qGAAqG;IACvG,YAAY;IACZ,UAAU,EAAE,eAAe,CAAC,KAAK,EAAE,OAAO,CAAC;IAC3C,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC;IAC7F,OAAO,EAAE,WAAW;CACrB,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { calendar } from '@googleapis/calendar';\nimport { authorizedClient, runAuthFlow } from '../auth/oauth.js';\nimport { mergeOperations } from '../lib/operation.js';\nimport { server } from '../lib/server.js';\nimport { instructions } from './instructions.js';\nimport { methods } from './methods/registry.js';\nimport { tools } from './tools/registry.js';\n\n// Cloning this for a new service? Add that service's OAuth scopes to `SCOPES` in\n// src/auth/config.ts BEFORE the first auth. The scope union is front-loaded so each\n// account consents once, and Google only re-issues a refresh token on a fresh grant;\n// adding a scope later forces re-consent of every account. Nothing in this file\n// references scopes, which is exactly why it is easy to miss.\nawait server({\n name: 'calendar',\n title: 'Google Calendar (google-mcp-suite)',\n description:\n 'Per-account Google Calendar MCP server: events, calendars, free/busy, and meeting-time suggestions.',\n instructions,\n operations: mergeOperations(tools, methods),\n client: async (account) => calendar({ version: 'v3', auth: await authorizedClient(account) }),\n runAuth: runAuthFlow,\n});\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/calendar/index.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACjF,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAE5C,iFAAiF;AACjF,oFAAoF;AACpF,qFAAqF;AACrF,gFAAgF;AAChF,8DAA8D;AAC9D,MAAM,MAAM,CAAC;IACX,IAAI,EAAE,UAAU;IAChB,KAAK,EAAE,oCAAoC;IAC3C,WAAW,EACT,qGAAqG;IACvG,YAAY;IACZ,UAAU,EAAE,eAAe,CAAC,KAAK,EAAE,OAAO,CAAC;IAC3C,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC;IAC7F,OAAO,EAAE,WAAW;IACpB,gBAAgB,EAAE,cAAc;CACjC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { calendar } from '@googleapis/calendar';\nimport { authorizedClient, isInvalidGrant, runAuthFlow } from '../auth/oauth.js';\nimport { mergeOperations } from '../lib/operation.js';\nimport { server } from '../lib/server.js';\nimport { instructions } from './instructions.js';\nimport { methods } from './methods/registry.js';\nimport { tools } from './tools/registry.js';\n\n// Cloning this for a new service? Add that service's OAuth scopes to `SCOPES` in\n// src/auth/config.ts BEFORE the first auth. The scope union is front-loaded so each\n// account consents once, and Google only re-issues a refresh token on a fresh grant;\n// adding a scope later forces re-consent of every account. Nothing in this file\n// references scopes, which is exactly why it is easy to miss.\nawait server({\n name: 'calendar',\n title: 'Google Calendar (google-mcp-suite)',\n description:\n 'Per-account Google Calendar MCP server: events, calendars, free/busy, and meeting-time suggestions.',\n instructions,\n operations: mergeOperations(tools, methods),\n client: async (account) => calendar({ version: 'v3', auth: await authorizedClient(account) }),\n runAuth: runAuthFlow,\n staleCredentials: isInvalidGrant,\n});\n"]}
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { docs } from '@googleapis/docs';
3
- import { authorizedClient, runAuthFlow } from '../auth/oauth.js';
3
+ import { authorizedClient, isInvalidGrant, runAuthFlow } from '../auth/oauth.js';
4
4
  import { mergeOperations } from '../lib/operation.js';
5
5
  import { server } from '../lib/server.js';
6
6
  import { instructions } from './instructions.js';
@@ -22,5 +22,6 @@ await server({
22
22
  operations: mergeOperations(methods),
23
23
  client: async (account) => docs({ version: 'v1', auth: await authorizedClient(account) }),
24
24
  runAuth: runAuthFlow,
25
+ staleCredentials: isInvalidGrant,
25
26
  });
26
27
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/docs/index.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACxC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAEhD,iFAAiF;AACjF,oFAAoF;AACpF,qFAAqF;AACrF,gFAAgF;AAChF,8DAA8D;AAC9D,EAAE;AACF,sEAAsE;AACtE,iFAAiF;AACjF,0EAA0E;AAC1E,MAAM,MAAM,CAAC;IACX,IAAI,EAAE,MAAM;IACZ,KAAK,EAAE,gCAAgC;IACvC,WAAW,EACT,wGAAwG;IAC1G,YAAY;IACZ,UAAU,EAAE,eAAe,CAAC,OAAO,CAAC;IACpC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC;IACzF,OAAO,EAAE,WAAW;CACrB,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { docs } from '@googleapis/docs';\nimport { authorizedClient, runAuthFlow } from '../auth/oauth.js';\nimport { mergeOperations } from '../lib/operation.js';\nimport { server } from '../lib/server.js';\nimport { instructions } from './instructions.js';\nimport { methods } from './methods/registry.js';\n\n// Cloning this for a new service? Add that service's OAuth scopes to `SCOPES` in\n// src/auth/config.ts BEFORE the first auth. The scope union is front-loaded so each\n// account consents once, and Google only re-issues a refresh token on a fresh grant;\n// adding a scope later forces re-consent of every account. Nothing in this file\n// references scopes, which is exactly why it is easy to miss.\n//\n// Docs is methods-only: Google publishes no MCP toolset for Docs (its\n// MCP-supported products are Gmail, Drive, Calendar, Chat, and People), so there\n// is no tools/ folder and the REST-sourced methods are the whole surface.\nawait server({\n name: 'docs',\n title: 'Google Docs (google-mcp-suite)',\n description:\n 'Per-account Google Docs MCP server: document reads and creation plus curated text editing and styling.',\n instructions,\n operations: mergeOperations(methods),\n client: async (account) => docs({ version: 'v1', auth: await authorizedClient(account) }),\n runAuth: runAuthFlow,\n});\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/docs/index.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACxC,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACjF,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAEhD,iFAAiF;AACjF,oFAAoF;AACpF,qFAAqF;AACrF,gFAAgF;AAChF,8DAA8D;AAC9D,EAAE;AACF,sEAAsE;AACtE,iFAAiF;AACjF,0EAA0E;AAC1E,MAAM,MAAM,CAAC;IACX,IAAI,EAAE,MAAM;IACZ,KAAK,EAAE,gCAAgC;IACvC,WAAW,EACT,wGAAwG;IAC1G,YAAY;IACZ,UAAU,EAAE,eAAe,CAAC,OAAO,CAAC;IACpC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC;IACzF,OAAO,EAAE,WAAW;IACpB,gBAAgB,EAAE,cAAc;CACjC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { docs } from '@googleapis/docs';\nimport { authorizedClient, isInvalidGrant, runAuthFlow } from '../auth/oauth.js';\nimport { mergeOperations } from '../lib/operation.js';\nimport { server } from '../lib/server.js';\nimport { instructions } from './instructions.js';\nimport { methods } from './methods/registry.js';\n\n// Cloning this for a new service? Add that service's OAuth scopes to `SCOPES` in\n// src/auth/config.ts BEFORE the first auth. The scope union is front-loaded so each\n// account consents once, and Google only re-issues a refresh token on a fresh grant;\n// adding a scope later forces re-consent of every account. Nothing in this file\n// references scopes, which is exactly why it is easy to miss.\n//\n// Docs is methods-only: Google publishes no MCP toolset for Docs (its\n// MCP-supported products are Gmail, Drive, Calendar, Chat, and People), so there\n// is no tools/ folder and the REST-sourced methods are the whole surface.\nawait server({\n name: 'docs',\n title: 'Google Docs (google-mcp-suite)',\n description:\n 'Per-account Google Docs MCP server: document reads and creation plus curated text editing and styling.',\n instructions,\n operations: mergeOperations(methods),\n client: async (account) => docs({ version: 'v1', auth: await authorizedClient(account) }),\n runAuth: runAuthFlow,\n staleCredentials: isInvalidGrant,\n});\n"]}
@@ -9,8 +9,7 @@ import { errorMessage } from '../lib/utils/error.js';
9
9
  import { runAuth } from './auth.js';
10
10
  import { diagnose, renderScopes } from './diagnose.js';
11
11
  import { renderStatus } from './status.js';
12
- function printHelp() {
13
- console.log(`google-mcp-doctor: provisioning & auth health for google-mcp-suite
12
+ const usage = `google-mcp-doctor: provisioning & auth health for google-mcp-suite
14
13
 
15
14
  Usage:
16
15
  google-mcp-doctor [check] full diagnostic: provisioning, accounts, services
@@ -23,8 +22,7 @@ Usage:
23
22
  google-mcp-doctor help
24
23
 
25
24
  Flags:
26
- --no-probe skip the live service health checks (offline/fast)`);
27
- }
25
+ --no-probe skip the live service health checks (offline/fast)`;
28
26
  const [cmd = 'check', ...rest] = process.argv.slice(2);
29
27
  try {
30
28
  switch (cmd) {
@@ -45,11 +43,10 @@ try {
45
43
  case 'help':
46
44
  case '--help':
47
45
  case '-h':
48
- printHelp();
46
+ console.log(usage);
49
47
  break;
50
48
  default:
51
- console.error(`Unknown command: ${cmd}\n`);
52
- printHelp();
49
+ console.error(`Unknown command: ${cmd}\n\n${usage}`);
53
50
  process.exit(1);
54
51
  }
55
52
  }
@@ -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CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC;IACjC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { errorMessage } from '../lib/utils/error.js';\n/**\n * google-mcp-doctor: a micro-CLI for provisioning and auth health.\n *\n * Doctor knows the services; the services never know doctor. It imports the auth\n * layer and stable `@googleapis/*` surfaces only, never a service's internals.\n */\nimport { runAuth } from './auth.js';\nimport { diagnose, renderScopes } from './diagnose.js';\nimport { renderStatus } from './status.js';\n\nfunction printHelp(): void {\n console.log(`google-mcp-doctor: provisioning & auth health for google-mcp-suite\n\nUsage:\n google-mcp-doctor [check] full diagnostic: provisioning, accounts, services\n google-mcp-doctor status refresh-token countdown table\n google-mcp-doctor auth [<acct>…] authorize accounts\n no args → re-auth what is expired/due\n --all → every account in the roster\n <acct> → an email (no config needed) or roster label\n google-mcp-doctor scopes the APIs + scopes to enable in Google Cloud\n google-mcp-doctor help\n\nFlags:\n --no-probe skip the live service health checks (offline/fast)`);\n}\n\nconst [cmd = 'check', ...rest] = process.argv.slice(2);\n\ntry {\n switch (cmd) {\n case 'check':\n case 'diagnose':\n await diagnose({ probe: !rest.includes('--no-probe') });\n break;\n case 'status':\n case 'tokens':\n renderStatus();\n break;\n case 'auth':\n await runAuth(rest);\n break;\n case 'scopes':\n renderScopes();\n break;\n case 'help':\n case '--help':\n case '-h':\n printHelp();\n break;\n default:\n console.error(`Unknown command: ${cmd}\\n`);\n printHelp();\n process.exit(1);\n }\n} catch (err) {\n console.error(errorMessage(err));\n process.exit(1);\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/doctor/index.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD;;;;;GAKG;AACH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C,MAAM,KAAK,GAAG;;;;;;;;;;;;;kEAaoD,CAAC;AAEnE,MAAM,CAAC,GAAG,GAAG,OAAO,EAAE,GAAG,IAAI,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAEvD,IAAI,CAAC;IACH,QAAQ,GAAG,EAAE,CAAC;QACZ,KAAK,OAAO,CAAC;QACb,KAAK,UAAU;YACb,MAAM,QAAQ,CAAC,EAAE,KAAK,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC;YACxD,MAAM;QACR,KAAK,QAAQ,CAAC;QACd,KAAK,QAAQ;YACX,YAAY,EAAE,CAAC;YACf,MAAM;QACR,KAAK,MAAM;YACT,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;YACpB,MAAM;QACR,KAAK,QAAQ;YACX,YAAY,EAAE,CAAC;YACf,MAAM;QACR,KAAK,MAAM,CAAC;QACZ,KAAK,QAAQ,CAAC;QACd,KAAK,IAAI;YACP,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;YACnB,MAAM;QACR;YACE,OAAO,CAAC,KAAK,CAAC,oBAAoB,GAAG,OAAO,KAAK,EAAE,CAAC,CAAC;YACrD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;AACH,CAAC;AAAC,OAAO,GAAG,EAAE,CAAC;IACb,OAAO,CAAC,KAAK,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC;IACjC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { errorMessage } from '../lib/utils/error.js';\n/**\n * google-mcp-doctor: a micro-CLI for provisioning and auth health.\n *\n * Doctor knows the services; the services never know doctor. It imports the auth\n * layer and stable `@googleapis/*` surfaces only, never a service's internals.\n */\nimport { runAuth } from './auth.js';\nimport { diagnose, renderScopes } from './diagnose.js';\nimport { renderStatus } from './status.js';\n\nconst usage = `google-mcp-doctor: provisioning & auth health for google-mcp-suite\n\nUsage:\n google-mcp-doctor [check] full diagnostic: provisioning, accounts, services\n google-mcp-doctor status refresh-token countdown table\n google-mcp-doctor auth [<acct>…] authorize accounts\n no args → re-auth what is expired/due\n --all → every account in the roster\n <acct> → an email (no config needed) or roster label\n google-mcp-doctor scopes the APIs + scopes to enable in Google Cloud\n google-mcp-doctor help\n\nFlags:\n --no-probe skip the live service health checks (offline/fast)`;\n\nconst [cmd = 'check', ...rest] = process.argv.slice(2);\n\ntry {\n switch (cmd) {\n case 'check':\n case 'diagnose':\n await diagnose({ probe: !rest.includes('--no-probe') });\n break;\n case 'status':\n case 'tokens':\n renderStatus();\n break;\n case 'auth':\n await runAuth(rest);\n break;\n case 'scopes':\n renderScopes();\n break;\n case 'help':\n case '--help':\n case '-h':\n console.log(usage);\n break;\n default:\n console.error(`Unknown command: ${cmd}\\n\\n${usage}`);\n process.exit(1);\n }\n} catch (err) {\n console.error(errorMessage(err));\n process.exit(1);\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { drive } from '@googleapis/drive';
3
- import { authorizedClient, runAuthFlow } from '../auth/oauth.js';
3
+ import { authorizedClient, isInvalidGrant, runAuthFlow } from '../auth/oauth.js';
4
4
  import { mergeOperations } from '../lib/operation.js';
5
5
  import { server } from '../lib/server.js';
6
6
  import { instructions } from './instructions.js';
@@ -19,5 +19,6 @@ await server({
19
19
  operations: mergeOperations(tools, methods),
20
20
  client: async (account) => drive({ version: 'v3', auth: await authorizedClient(account) }),
21
21
  runAuth: runAuthFlow,
22
+ staleCredentials: isInvalidGrant,
22
23
  });
23
24
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/drive/index.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAE5C,iFAAiF;AACjF,oFAAoF;AACpF,qFAAqF;AACrF,gFAAgF;AAChF,8DAA8D;AAC9D,MAAM,MAAM,CAAC;IACX,IAAI,EAAE,OAAO;IACb,KAAK,EAAE,iCAAiC;IACxC,WAAW,EACT,qFAAqF;IACvF,YAAY;IACZ,UAAU,EAAE,eAAe,CAAC,KAAK,EAAE,OAAO,CAAC;IAC3C,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC;IAC1F,OAAO,EAAE,WAAW;CACrB,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { drive } from '@googleapis/drive';\nimport { authorizedClient, runAuthFlow } from '../auth/oauth.js';\nimport { mergeOperations } from '../lib/operation.js';\nimport { server } from '../lib/server.js';\nimport { instructions } from './instructions.js';\nimport { methods } from './methods/registry.js';\nimport { tools } from './tools/registry.js';\n\n// Cloning this for a new service? Add that service's OAuth scopes to `SCOPES` in\n// src/auth/config.ts BEFORE the first auth. The scope union is front-loaded so each\n// account consents once, and Google only re-issues a refresh token on a fresh grant;\n// adding a scope later forces re-consent of every account. Nothing in this file\n// references scopes, which is exactly why it is easy to miss.\nawait server({\n name: 'drive',\n title: 'Google Drive (google-mcp-suite)',\n description:\n 'Per-account Google Drive MCP server: files, comments, revisions, and shared drives.',\n instructions,\n operations: mergeOperations(tools, methods),\n client: async (account) => drive({ version: 'v3', auth: await authorizedClient(account) }),\n runAuth: runAuthFlow,\n});\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/drive/index.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACjF,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAE5C,iFAAiF;AACjF,oFAAoF;AACpF,qFAAqF;AACrF,gFAAgF;AAChF,8DAA8D;AAC9D,MAAM,MAAM,CAAC;IACX,IAAI,EAAE,OAAO;IACb,KAAK,EAAE,iCAAiC;IACxC,WAAW,EACT,qFAAqF;IACvF,YAAY;IACZ,UAAU,EAAE,eAAe,CAAC,KAAK,EAAE,OAAO,CAAC;IAC3C,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC;IAC1F,OAAO,EAAE,WAAW;IACpB,gBAAgB,EAAE,cAAc;CACjC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { drive } from '@googleapis/drive';\nimport { authorizedClient, isInvalidGrant, runAuthFlow } from '../auth/oauth.js';\nimport { mergeOperations } from '../lib/operation.js';\nimport { server } from '../lib/server.js';\nimport { instructions } from './instructions.js';\nimport { methods } from './methods/registry.js';\nimport { tools } from './tools/registry.js';\n\n// Cloning this for a new service? Add that service's OAuth scopes to `SCOPES` in\n// src/auth/config.ts BEFORE the first auth. The scope union is front-loaded so each\n// account consents once, and Google only re-issues a refresh token on a fresh grant;\n// adding a scope later forces re-consent of every account. Nothing in this file\n// references scopes, which is exactly why it is easy to miss.\nawait server({\n name: 'drive',\n title: 'Google Drive (google-mcp-suite)',\n description:\n 'Per-account Google Drive MCP server: files, comments, revisions, and shared drives.',\n instructions,\n operations: mergeOperations(tools, methods),\n client: async (account) => drive({ version: 'v3', auth: await authorizedClient(account) }),\n runAuth: runAuthFlow,\n staleCredentials: isInvalidGrant,\n});\n"]}
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { gmail } from '@googleapis/gmail';
3
- import { authorizedClient, runAuthFlow } from '../auth/oauth.js';
3
+ import { authorizedClient, isInvalidGrant, runAuthFlow } from '../auth/oauth.js';
4
4
  import { mergeOperations } from '../lib/operation.js';
5
5
  import { server } from '../lib/server.js';
6
6
  import { instructions } from './instructions.js';
@@ -19,5 +19,6 @@ await server({
19
19
  operations: mergeOperations(tools, methods),
20
20
  client: async (account) => gmail({ version: 'v1', auth: await authorizedClient(account) }),
21
21
  runAuth: runAuthFlow,
22
+ staleCredentials: isInvalidGrant,
22
23
  });
23
24
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/gmail/index.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAE5C,iFAAiF;AACjF,oFAAoF;AACpF,qFAAqF;AACrF,gFAAgF;AAChF,8DAA8D;AAC9D,MAAM,MAAM,CAAC;IACX,IAAI,EAAE,OAAO;IACb,KAAK,EAAE,0BAA0B;IACjC,WAAW,EACT,4FAA4F;IAC9F,YAAY;IACZ,UAAU,EAAE,eAAe,CAAC,KAAK,EAAE,OAAO,CAAC;IAC3C,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC;IAC1F,OAAO,EAAE,WAAW;CACrB,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { gmail } from '@googleapis/gmail';\nimport { authorizedClient, runAuthFlow } from '../auth/oauth.js';\nimport { mergeOperations } from '../lib/operation.js';\nimport { server } from '../lib/server.js';\nimport { instructions } from './instructions.js';\nimport { methods } from './methods/registry.js';\nimport { tools } from './tools/registry.js';\n\n// Cloning this for a new service? Add that service's OAuth scopes to `SCOPES` in\n// src/auth/config.ts BEFORE the first auth. The scope union is front-loaded so each\n// account consents once, and Google only re-issues a refresh token on a fresh grant;\n// adding a scope later forces re-consent of every account. Nothing in this file\n// references scopes, which is exactly why it is easy to miss.\nawait server({\n name: 'gmail',\n title: 'Gmail (google-mcp-suite)',\n description:\n 'Per-account Gmail MCP server: threads, messages, drafts, labels, filters, and attachments.',\n instructions,\n operations: mergeOperations(tools, methods),\n client: async (account) => gmail({ version: 'v1', auth: await authorizedClient(account) }),\n runAuth: runAuthFlow,\n});\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/gmail/index.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACjF,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAE5C,iFAAiF;AACjF,oFAAoF;AACpF,qFAAqF;AACrF,gFAAgF;AAChF,8DAA8D;AAC9D,MAAM,MAAM,CAAC;IACX,IAAI,EAAE,OAAO;IACb,KAAK,EAAE,0BAA0B;IACjC,WAAW,EACT,4FAA4F;IAC9F,YAAY;IACZ,UAAU,EAAE,eAAe,CAAC,KAAK,EAAE,OAAO,CAAC;IAC3C,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC;IAC1F,OAAO,EAAE,WAAW;IACpB,gBAAgB,EAAE,cAAc;CACjC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { gmail } from '@googleapis/gmail';\nimport { authorizedClient, isInvalidGrant, runAuthFlow } from '../auth/oauth.js';\nimport { mergeOperations } from '../lib/operation.js';\nimport { server } from '../lib/server.js';\nimport { instructions } from './instructions.js';\nimport { methods } from './methods/registry.js';\nimport { tools } from './tools/registry.js';\n\n// Cloning this for a new service? Add that service's OAuth scopes to `SCOPES` in\n// src/auth/config.ts BEFORE the first auth. The scope union is front-loaded so each\n// account consents once, and Google only re-issues a refresh token on a fresh grant;\n// adding a scope later forces re-consent of every account. Nothing in this file\n// references scopes, which is exactly why it is easy to miss.\nawait server({\n name: 'gmail',\n title: 'Gmail (google-mcp-suite)',\n description:\n 'Per-account Gmail MCP server: threads, messages, drafts, labels, filters, and attachments.',\n instructions,\n operations: mergeOperations(tools, methods),\n client: async (account) => gmail({ version: 'v1', auth: await authorizedClient(account) }),\n runAuth: runAuthFlow,\n staleCredentials: isInvalidGrant,\n});\n"]}
@@ -32,6 +32,15 @@ export type ServerOptions<Client> = {
32
32
  client: (account: string | undefined) => Promise<Client>;
33
33
  /** Optional consent flow, invoked by the `auth` subcommand. */
34
34
  runAuth?: (account: string | undefined) => Promise<void>;
35
+ /**
36
+ * Certify an error as stale stored credentials (e.g. OAuth `invalid_grant`).
37
+ * A certified failure rebuilds the client from disk, so a re-auth heals a
38
+ * running instance, and retries once only when the operation's annotations
39
+ * make a second attempt safe (read-only or idempotent); otherwise the error
40
+ * envelope tells the agent to retry. Typed like `runAuth`: the auth layer
41
+ * supplies the predicate, this generic layer never inspects error shapes.
42
+ */
43
+ staleCredentials?: (error: unknown) => boolean;
35
44
  /** Transport to connect; defaults to stdio. Injectable for tests. */
36
45
  transport?: Transport;
37
46
  };
@@ -56,14 +65,17 @@ export declare function toolDefinitions<Client>(operations: Record<string, AnyOp
56
65
  * Run one operation by name: resolve it, validate input against its schema, run
57
66
  * the handler, validate the output, and return both a structured result and a text
58
67
  * rendering (for clients that do not yet read `structuredContent`). All failure
59
- * paths return an `isError` result rather than throwing. Exported for tests.
68
+ * paths return an `isError` result rather than throwing, with one exception:
69
+ * a handler error that `rethrows` certifies escapes untouched, so the
70
+ * credential-healing layer in `server()` can see it typed rather than
71
+ * flattened into envelope text. Exported for tests.
60
72
  */
61
- export declare function callOperation<Client>(operations: Record<string, AnyOperation<Client>>, client: Client, name: string, rawArgs: unknown): Promise<CallToolResult>;
73
+ export declare function callOperation<Client>(operations: Record<string, AnyOperation<Client>>, client: Client, name: string, rawArgs: unknown, rethrows?: (error: unknown) => boolean): Promise<CallToolResult>;
62
74
  /**
63
75
  * Turn a service's operations into a running stdio MCP server. Identical for every
64
76
  * service; only the bound `Client` type and the operations differ. Owns the
65
77
  * cross-cutting concerns: the `auth` subcommand, account binding, the `tools/list`
66
- * payload, dispatch, validation, and error wrapping.
78
+ * payload, dispatch, validation, error wrapping, and stale-credential healing.
67
79
  */
68
80
  export declare function server<Client>(options: ServerOptions<Client>): Promise<void>;
69
81
  //# sourceMappingURL=server.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/lib/server.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+CAA+C,CAAC;AAC/E,OAAO,EAEL,KAAK,cAAc,EAEpB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,KAAK,YAAY,EAAmB,MAAM,gBAAgB,CAAC;AAIpE,MAAM,MAAM,aAAa,CAAC,MAAM,IAAI;IAClC,mDAAmD;IACnD,IAAI,EAAE,MAAM,CAAC;IACb,uDAAuD;IACvD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;;OAKG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,iFAAiF;IACjF,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,sGAAsG;IACtG,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;;OAMG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,0FAA0F;IAC1F,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC;IACjD,gFAAgF;IAChF,MAAM,EAAE,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACzD,+DAA+D;IAC/D,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACzD,qEAAqE;IACrE,SAAS,CAAC,EAAE,SAAS,CAAC;CACvB,CAAC;AAMF;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CA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+DAA+D;IAC/D,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACzD;;;;;;;OAOG;IACH,gBAAgB,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,CAAC;IAC/C,qEAAqE;IACrE,SAAS,CAAC,EAAE,SAAS,CAAC;CACvB,CAAC;AAMF;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC;;;;;;;;;IASvF;AAED;;;;;;;;GAQG;AACH,wBAAsB,aAAa,CAAC,MAAM,EACxC,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC,EAChD,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,OAAO,EAChB,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,GACrC,OAAO,CAAC,cAAc,CAAC,CAyCzB;AAED;;;;;GAKG;AACH,wBAAsB,MAAM,CAAC,MAAM,EAAE,OAAO,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CA0DlF"}
@@ -30,9 +30,12 @@ export function toolDefinitions(operations) {
30
30
  * Run one operation by name: resolve it, validate input against its schema, run
31
31
  * the handler, validate the output, and return both a structured result and a text
32
32
  * rendering (for clients that do not yet read `structuredContent`). All failure
33
- * paths return an `isError` result rather than throwing. Exported for tests.
33
+ * paths return an `isError` result rather than throwing, with one exception:
34
+ * a handler error that `rethrows` certifies escapes untouched, so the
35
+ * credential-healing layer in `server()` can see it typed rather than
36
+ * flattened into envelope text. Exported for tests.
34
37
  */
35
- export async function callOperation(operations, client, name, rawArgs) {
38
+ export async function callOperation(operations, client, name, rawArgs, rethrows) {
36
39
  // ownLookup: a bare `operations[name]` would resolve inherited keys
37
40
  // (`__proto__`, `toString`, ...) to truthy non-operations and throw past the
38
41
  // error envelope when an agent sends one as a tool name.
@@ -64,6 +67,9 @@ export async function callOperation(operations, client, name, rawArgs) {
64
67
  };
65
68
  }
66
69
  catch (error) {
70
+ if (rethrows?.(error)) {
71
+ throw error;
72
+ }
67
73
  if (error instanceof z.ZodError) {
68
74
  return errorResult(`Invalid output from ${name}:\n${z.prettifyError(error)}`);
69
75
  }
@@ -74,10 +80,10 @@ export async function callOperation(operations, client, name, rawArgs) {
74
80
  * Turn a service's operations into a running stdio MCP server. Identical for every
75
81
  * service; only the bound `Client` type and the operations differ. Owns the
76
82
  * cross-cutting concerns: the `auth` subcommand, account binding, the `tools/list`
77
- * payload, dispatch, validation, and error wrapping.
83
+ * payload, dispatch, validation, error wrapping, and stale-credential healing.
78
84
  */
79
85
  export async function server(options) {
80
- const { name, version = pkg.version, operations, client, runAuth } = options;
86
+ const { name, version = pkg.version, operations, client, runAuth, staleCredentials } = options;
81
87
  const { title, description, websiteUrl = pkg.homepage, instructions } = options;
82
88
  if (process.argv[2] === 'auth') {
83
89
  if (!runAuth) {
@@ -87,7 +93,7 @@ export async function server(options) {
87
93
  await runAuth(process.argv[3] ?? process.env['GOOGLE_MCP_ACCOUNT']);
88
94
  process.exit(0);
89
95
  }
90
- const authed = await client(process.env['GOOGLE_MCP_ACCOUNT']);
96
+ let authed = await client(process.env['GOOGLE_MCP_ACCOUNT']);
91
97
  const mcp = new Server({
92
98
  name,
93
99
  version,
@@ -98,7 +104,33 @@ export async function server(options) {
98
104
  mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
99
105
  tools: toolDefinitions(operations),
100
106
  }));
101
- mcp.setRequestHandler(CallToolRequestSchema, (request) => callOperation(operations, authed, request.params.name, request.params.arguments));
107
+ mcp.setRequestHandler(CallToolRequestSchema, async (request) => {
108
+ const { name: opName, arguments: args } = request.params;
109
+ try {
110
+ return await callOperation(operations, authed, opName, args, staleCredentials);
111
+ }
112
+ catch (error) {
113
+ // Only a staleCredentials-certified error reaches here: the stored
114
+ // refresh token died, and this long-lived process never re-reads its
115
+ // token file, so a `google-mcp-doctor auth` re-auth cannot heal it
116
+ // without a rebuild. invalid_grant is raised while refreshing the
117
+ // access token, normally before the operation executes, but a
118
+ // multi-call handler can die mid-flight, so the retry is gated on the
119
+ // operation's own annotations: read-only or idempotent retries here;
120
+ // anything else hands the retry decision back to the agent.
121
+ try {
122
+ authed = await client(process.env['GOOGLE_MCP_ACCOUNT']);
123
+ }
124
+ catch (rebuildError) {
125
+ return errorResult(errorMessage(rebuildError));
126
+ }
127
+ const hints = ownLookup(operations, opName)?.annotations;
128
+ if (hints?.readOnlyHint !== true && hints?.idempotentHint !== true) {
129
+ return errorResult(`${errorMessage(error)} (stale credentials, now reloaded from disk; retry ${opName})`);
130
+ }
131
+ return callOperation(operations, authed, opName, args);
132
+ }
133
+ });
102
134
  await mcp.connect(options.transport ?? new StdioServerTransport());
103
135
  }
104
136
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/lib/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAEjF,OAAO,EACL,qBAAqB,EAErB,sBAAsB,GACvB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,GAAG,MAAM,oBAAoB,CAAC,OAAO,IAAI,EAAE,MAAM,EAAE,CAAC;AAC3D,OAAO,EAAqB,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACpE,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAoC9C,SAAS,WAAW,CAAC,OAAe;IAClC,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAA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ACjF,CAAC;IAEF,MAAM,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,IAAI,IAAI,oBAAoB,EAAE,CAAC,CAAC;AACrE,CAAC","sourcesContent":["import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';\nimport {\n CallToolRequestSchema,\n type CallToolResult,\n ListToolsRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\nimport { z } from 'zod';\nimport pkg from '../../package.json' with { type: 'json' };\nimport { type AnyOperation, SOURCE_META_KEY } from './operation.js';\nimport { errorMessage } from './utils/error.js';\nimport { ownLookup } from './utils/lookup.js';\n\nexport type ServerOptions<Client> = {\n /** MCP server name (the service, e.g. 'gmail'). */\n name: string;\n /** Server version; defaults to the package version. */\n version?: string;\n /**\n * Human-readable server name for client UIs (MCP `Implementation.title`).\n * `description` and `websiteUrl` postdate the 2025-06-18 `Implementation`\n * (the shipped SDK carries them); clients that predate them ignore them.\n * @see https://modelcontextprotocol.io/specification/2025-06-18/schema (Implementation)\n */\n title?: string;\n /** One-line server summary for client UIs (MCP `Implementation.description`). */\n description?: string;\n /** Project URL for client UIs (MCP `Implementation.websiteUrl`); defaults to the package homepage. */\n websiteUrl?: string;\n /**\n * Usage notes served in the MCP initialize result (`InitializeResult.instructions`);\n * clients typically inject this into the agent's context at connect time,\n * making it the primary server-authored channel for usage guidance (support\n * varies by client; it is a hint, like the tool annotations).\n * @see https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle\n */\n instructions?: string;\n /** Every operation this server exposes, keyed by wire name (tools and methods merged). */\n operations: Record<string, AnyOperation<Client>>;\n /** Build the authenticated client for the account this instance is bound to. */\n client: (account: string | undefined) => Promise<Client>;\n /** Optional consent flow, invoked by the `auth` subcommand. */\n runAuth?: (account: string | undefined) => Promise<void>;\n /** Transport to connect; defaults to stdio. Injectable for tests. */\n transport?: Transport;\n};\n\nfunction errorResult(message: string): CallToolResult {\n return { content: [{ type: 'text', text: `Error: ${message}` }], isError: true };\n}\n\n/**\n * Build the MCP `tools/list` payload from the operations: each one's input and\n * output JSON Schema, the four-hint annotations quad declared on its\n * definition, and the source reference page under `_meta[SOURCE_META_KEY]`.\n * On the wire, every operation is a \"tool\" (MCP has no other word). Pure;\n * exported for tests.\n */\nexport function toolDefinitions<Client>(operations: Record<string, AnyOperation<Client>>) {\n return Object.entries(operations).map(([name, op]) => ({\n name,\n description: op.description,\n inputSchema: z.toJSONSchema(op.schema.input, { io: 'input' }),\n outputSchema: z.toJSONSchema(op.schema.output, { io: 'output' }),\n annotations: op.annotations,\n _meta: { [SOURCE_META_KEY]: op.source },\n }));\n}\n\n/**\n * Run one operation by name: resolve it, validate input against its schema, run\n * the handler, validate the output, and return both a structured result and a text\n * rendering (for clients that do not yet read `structuredContent`). All failure\n * paths return an `isError` result rather than throwing. Exported for tests.\n */\nexport async function callOperation<Client>(\n operations: Record<string, AnyOperation<Client>>,\n client: Client,\n name: string,\n rawArgs: unknown,\n): Promise<CallToolResult> {\n // ownLookup: a bare `operations[name]` would resolve inherited keys\n // (`__proto__`, `toString`, ...) to truthy non-operations and throw past the\n // error envelope when an agent sends one as a tool name.\n // Deliberate spec deviation: MCP files unknown tools and invalid arguments\n // under protocol error -32602, but this server answers every operation-level\n // failure as a uniform isError tool result so an agent can read the message\n // and self-correct instead of hitting a protocol-layer failure.\n const op = ownLookup(operations, name);\n if (!op) {\n return errorResult(`Unknown tool: ${name}`);\n }\n\n const parsed = op.schema.input.safeParse(rawArgs ?? {});\n if (!parsed.success) {\n // prettifyError renders \"✖ <issue> → at <path>\" lines; the raw ZodError\n // message is a JSON dump of the issue array, which agents misread.\n return errorResult(`Invalid arguments for ${name}:\\n${z.prettifyError(parsed.error)}`);\n }\n\n try {\n // `parsed.data` was just validated against this op's input schema, so it is\n // the handler's real input shape. The `AnyOperation` boundary types the\n // handler's args as `never` (so any concrete Operation stays assignable; see\n // operation.ts), and `as never` is the only call form. The validation above\n // is what makes this safe: do not call the handler before parsing.\n const result = await op.handler(client, parsed.data as never);\n const validated = op.schema.output.parse(result);\n return {\n content: [{ type: 'text', text: JSON.stringify(validated, null, 2) }],\n structuredContent: validated,\n };\n } catch (error) {\n if (error instanceof z.ZodError) {\n return errorResult(`Invalid output from ${name}:\\n${z.prettifyError(error)}`);\n }\n return errorResult(errorMessage(error));\n }\n}\n\n/**\n * Turn a service's operations into a running stdio MCP server. Identical for every\n * service; only the bound `Client` type and the operations differ. Owns the\n * cross-cutting concerns: the `auth` subcommand, account binding, the `tools/list`\n * payload, dispatch, validation, and error wrapping.\n */\nexport async function server<Client>(options: ServerOptions<Client>): Promise<void> {\n const { name, version = pkg.version, operations, client, runAuth } = options;\n const { title, description, websiteUrl = pkg.homepage, instructions } = options;\n\n if (process.argv[2] === 'auth') {\n if (!runAuth) {\n console.error(`${name}: no auth flow configured.`);\n process.exit(1);\n }\n await runAuth(process.argv[3] ?? process.env['GOOGLE_MCP_ACCOUNT']);\n process.exit(0);\n }\n\n const authed = await client(process.env['GOOGLE_MCP_ACCOUNT']);\n const mcp = new Server(\n {\n name,\n version,\n websiteUrl,\n ...(title ? { title } : {}),\n ...(description ? { description } : {}),\n },\n { capabilities: { tools: {} }, ...(instructions ? { instructions } : {}) },\n );\n\n mcp.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: toolDefinitions(operations),\n }));\n\n mcp.setRequestHandler(CallToolRequestSchema, (request) =>\n callOperation(operations, authed, request.params.name, request.params.arguments),\n );\n\n await mcp.connect(options.transport ?? new StdioServerTransport());\n}\n"]}
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/lib/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAEjF,OAAO,EACL,qBAAqB,EAErB,sBAAsB,GACvB,MAAM,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AC;YACJ,CAAC;YACD,OAAO,aAAa,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;QACzD,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,MAAM,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,IAAI,IAAI,oBAAoB,EAAE,CAAC,CAAC;AACrE,CAAC","sourcesContent":["import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';\nimport {\n CallToolRequestSchema,\n type CallToolResult,\n ListToolsRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\nimport { z } from 'zod';\nimport pkg from '../../package.json' with { type: 'json' };\nimport { type AnyOperation, SOURCE_META_KEY } from './operation.js';\nimport { errorMessage } from './utils/error.js';\nimport { ownLookup } from './utils/lookup.js';\n\nexport type ServerOptions<Client> = {\n /** MCP server name (the service, e.g. 'gmail'). */\n name: string;\n /** Server version; defaults to the package version. */\n version?: string;\n /**\n * Human-readable server name for client UIs (MCP `Implementation.title`).\n * `description` and `websiteUrl` postdate the 2025-06-18 `Implementation`\n * (the shipped SDK carries them); clients that predate them ignore them.\n * @see https://modelcontextprotocol.io/specification/2025-06-18/schema (Implementation)\n */\n title?: string;\n /** One-line server summary for client UIs (MCP `Implementation.description`). */\n description?: string;\n /** Project URL for client UIs (MCP `Implementation.websiteUrl`); defaults to the package homepage. */\n websiteUrl?: string;\n /**\n * Usage notes served in the MCP initialize result (`InitializeResult.instructions`);\n * clients typically inject this into the agent's context at connect time,\n * making it the primary server-authored channel for usage guidance (support\n * varies by client; it is a hint, like the tool annotations).\n * @see https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle\n */\n instructions?: string;\n /** Every operation this server exposes, keyed by wire name (tools and methods merged). */\n operations: Record<string, AnyOperation<Client>>;\n /** Build the authenticated client for the account this instance is bound to. */\n client: (account: string | undefined) => Promise<Client>;\n /** Optional consent flow, invoked by the `auth` subcommand. */\n runAuth?: (account: string | undefined) => Promise<void>;\n /**\n * Certify an error as stale stored credentials (e.g. OAuth `invalid_grant`).\n * A certified failure rebuilds the client from disk, so a re-auth heals a\n * running instance, and retries once only when the operation's annotations\n * make a second attempt safe (read-only or idempotent); otherwise the error\n * envelope tells the agent to retry. Typed like `runAuth`: the auth layer\n * supplies the predicate, this generic layer never inspects error shapes.\n */\n staleCredentials?: (error: unknown) => boolean;\n /** Transport to connect; defaults to stdio. Injectable for tests. */\n transport?: Transport;\n};\n\nfunction errorResult(message: string): CallToolResult {\n return { content: [{ type: 'text', text: `Error: ${message}` }], isError: true };\n}\n\n/**\n * Build the MCP `tools/list` payload from the operations: each one's input and\n * output JSON Schema, the four-hint annotations quad declared on its\n * definition, and the source reference page under `_meta[SOURCE_META_KEY]`.\n * On the wire, every operation is a \"tool\" (MCP has no other word). Pure;\n * exported for tests.\n */\nexport function toolDefinitions<Client>(operations: Record<string, AnyOperation<Client>>) {\n return Object.entries(operations).map(([name, op]) => ({\n name,\n description: op.description,\n inputSchema: z.toJSONSchema(op.schema.input, { io: 'input' }),\n outputSchema: z.toJSONSchema(op.schema.output, { io: 'output' }),\n annotations: op.annotations,\n _meta: { [SOURCE_META_KEY]: op.source },\n }));\n}\n\n/**\n * Run one operation by name: resolve it, validate input against its schema, run\n * the handler, validate the output, and return both a structured result and a text\n * rendering (for clients that do not yet read `structuredContent`). All failure\n * paths return an `isError` result rather than throwing, with one exception:\n * a handler error that `rethrows` certifies escapes untouched, so the\n * credential-healing layer in `server()` can see it typed rather than\n * flattened into envelope text. Exported for tests.\n */\nexport async function callOperation<Client>(\n operations: Record<string, AnyOperation<Client>>,\n client: Client,\n name: string,\n rawArgs: unknown,\n rethrows?: (error: unknown) => boolean,\n): Promise<CallToolResult> {\n // ownLookup: a bare `operations[name]` would resolve inherited keys\n // (`__proto__`, `toString`, ...) to truthy non-operations and throw past the\n // error envelope when an agent sends one as a tool name.\n // Deliberate spec deviation: MCP files unknown tools and invalid arguments\n // under protocol error -32602, but this server answers every operation-level\n // failure as a uniform isError tool result so an agent can read the message\n // and self-correct instead of hitting a protocol-layer failure.\n const op = ownLookup(operations, name);\n if (!op) {\n return errorResult(`Unknown tool: ${name}`);\n }\n\n const parsed = op.schema.input.safeParse(rawArgs ?? {});\n if (!parsed.success) {\n // prettifyError renders \"✖ <issue> → at <path>\" lines; the raw ZodError\n // message is a JSON dump of the issue array, which agents misread.\n return errorResult(`Invalid arguments for ${name}:\\n${z.prettifyError(parsed.error)}`);\n }\n\n try {\n // `parsed.data` was just validated against this op's input schema, so it is\n // the handler's real input shape. The `AnyOperation` boundary types the\n // handler's args as `never` (so any concrete Operation stays assignable; see\n // operation.ts), and `as never` is the only call form. The validation above\n // is what makes this safe: do not call the handler before parsing.\n const result = await op.handler(client, parsed.data as never);\n const validated = op.schema.output.parse(result);\n return {\n content: [{ type: 'text', text: JSON.stringify(validated, null, 2) }],\n structuredContent: validated,\n };\n } catch (error) {\n if (rethrows?.(error)) {\n throw error;\n }\n if (error instanceof z.ZodError) {\n return errorResult(`Invalid output from ${name}:\\n${z.prettifyError(error)}`);\n }\n return errorResult(errorMessage(error));\n }\n}\n\n/**\n * Turn a service's operations into a running stdio MCP server. Identical for every\n * service; only the bound `Client` type and the operations differ. Owns the\n * cross-cutting concerns: the `auth` subcommand, account binding, the `tools/list`\n * payload, dispatch, validation, error wrapping, and stale-credential healing.\n */\nexport async function server<Client>(options: ServerOptions<Client>): Promise<void> {\n const { name, version = pkg.version, operations, client, runAuth, staleCredentials } = options;\n const { title, description, websiteUrl = pkg.homepage, instructions } = options;\n\n if (process.argv[2] === 'auth') {\n if (!runAuth) {\n console.error(`${name}: no auth flow configured.`);\n process.exit(1);\n }\n await runAuth(process.argv[3] ?? process.env['GOOGLE_MCP_ACCOUNT']);\n process.exit(0);\n }\n\n let authed = await client(process.env['GOOGLE_MCP_ACCOUNT']);\n const mcp = new Server(\n {\n name,\n version,\n websiteUrl,\n ...(title ? { title } : {}),\n ...(description ? { description } : {}),\n },\n { capabilities: { tools: {} }, ...(instructions ? { instructions } : {}) },\n );\n\n mcp.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: toolDefinitions(operations),\n }));\n\n mcp.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name: opName, arguments: args } = request.params;\n try {\n return await callOperation(operations, authed, opName, args, staleCredentials);\n } catch (error) {\n // Only a staleCredentials-certified error reaches here: the stored\n // refresh token died, and this long-lived process never re-reads its\n // token file, so a `google-mcp-doctor auth` re-auth cannot heal it\n // without a rebuild. invalid_grant is raised while refreshing the\n // access token, normally before the operation executes, but a\n // multi-call handler can die mid-flight, so the retry is gated on the\n // operation's own annotations: read-only or idempotent retries here;\n // anything else hands the retry decision back to the agent.\n try {\n authed = await client(process.env['GOOGLE_MCP_ACCOUNT']);\n } catch (rebuildError) {\n return errorResult(errorMessage(rebuildError));\n }\n const hints = ownLookup(operations, opName)?.annotations;\n if (hints?.readOnlyHint !== true && hints?.idempotentHint !== true) {\n return errorResult(\n `${errorMessage(error)} (stale credentials, now reloaded from disk; retry ${opName})`,\n );\n }\n return callOperation(operations, authed, opName, args);\n }\n });\n\n await mcp.connect(options.transport ?? new StdioServerTransport());\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { sheets } from '@googleapis/sheets';
3
- import { authorizedClient, runAuthFlow } from '../auth/oauth.js';
3
+ import { authorizedClient, isInvalidGrant, runAuthFlow } from '../auth/oauth.js';
4
4
  import { mergeOperations } from '../lib/operation.js';
5
5
  import { server } from '../lib/server.js';
6
6
  import { instructions } from './instructions.js';
@@ -22,5 +22,6 @@ await server({
22
22
  operations: mergeOperations(methods),
23
23
  client: async (account) => sheets({ version: 'v4', auth: await authorizedClient(account) }),
24
24
  runAuth: runAuthFlow,
25
+ staleCredentials: isInvalidGrant,
25
26
  });
26
27
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/sheets/index.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAEhD,iFAAiF;AACjF,oFAAoF;AACpF,qFAAqF;AACrF,gFAAgF;AAChF,8DAA8D;AAC9D,EAAE;AACF,0EAA0E;AAC1E,iFAAiF;AACjF,0EAA0E;AAC1E,MAAM,MAAM,CAAC;IACX,IAAI,EAAE,QAAQ;IACd,KAAK,EAAE,kCAAkC;IACzC,WAAW,EACT,6HAA6H;IAC/H,YAAY;IACZ,UAAU,EAAE,eAAe,CAAC,OAAO,CAAC;IACpC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC;IAC3F,OAAO,EAAE,WAAW;CACrB,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { sheets } from '@googleapis/sheets';\nimport { authorizedClient, runAuthFlow } from '../auth/oauth.js';\nimport { mergeOperations } from '../lib/operation.js';\nimport { server } from '../lib/server.js';\nimport { instructions } from './instructions.js';\nimport { methods } from './methods/registry.js';\n\n// Cloning this for a new service? Add that service's OAuth scopes to `SCOPES` in\n// src/auth/config.ts BEFORE the first auth. The scope union is front-loaded so each\n// account consents once, and Google only re-issues a refresh token on a fresh grant;\n// adding a scope later forces re-consent of every account. Nothing in this file\n// references scopes, which is exactly why it is easy to miss.\n//\n// Sheets is methods-only: Google publishes no MCP toolset for Sheets (its\n// MCP-supported products are Gmail, Drive, Calendar, Chat, and People), so there\n// is no tools/ folder and the REST-sourced methods are the whole surface.\nawait server({\n name: 'sheets',\n title: 'Google Sheets (google-mcp-suite)',\n description:\n 'Per-account Google Sheets MCP server: spreadsheets, values, batch and data-filter reads and writes, and developer metadata.',\n instructions,\n operations: mergeOperations(methods),\n client: async (account) => sheets({ version: 'v4', auth: await authorizedClient(account) }),\n runAuth: runAuthFlow,\n});\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/sheets/index.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACjF,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAEhD,iFAAiF;AACjF,oFAAoF;AACpF,qFAAqF;AACrF,gFAAgF;AAChF,8DAA8D;AAC9D,EAAE;AACF,0EAA0E;AAC1E,iFAAiF;AACjF,0EAA0E;AAC1E,MAAM,MAAM,CAAC;IACX,IAAI,EAAE,QAAQ;IACd,KAAK,EAAE,kCAAkC;IACzC,WAAW,EACT,6HAA6H;IAC/H,YAAY;IACZ,UAAU,EAAE,eAAe,CAAC,OAAO,CAAC;IACpC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC;IAC3F,OAAO,EAAE,WAAW;IACpB,gBAAgB,EAAE,cAAc;CACjC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { sheets } from '@googleapis/sheets';\nimport { authorizedClient, isInvalidGrant, runAuthFlow } from '../auth/oauth.js';\nimport { mergeOperations } from '../lib/operation.js';\nimport { server } from '../lib/server.js';\nimport { instructions } from './instructions.js';\nimport { methods } from './methods/registry.js';\n\n// Cloning this for a new service? Add that service's OAuth scopes to `SCOPES` in\n// src/auth/config.ts BEFORE the first auth. The scope union is front-loaded so each\n// account consents once, and Google only re-issues a refresh token on a fresh grant;\n// adding a scope later forces re-consent of every account. Nothing in this file\n// references scopes, which is exactly why it is easy to miss.\n//\n// Sheets is methods-only: Google publishes no MCP toolset for Sheets (its\n// MCP-supported products are Gmail, Drive, Calendar, Chat, and People), so there\n// is no tools/ folder and the REST-sourced methods are the whole surface.\nawait server({\n name: 'sheets',\n title: 'Google Sheets (google-mcp-suite)',\n description:\n 'Per-account Google Sheets MCP server: spreadsheets, values, batch and data-filter reads and writes, and developer metadata.',\n instructions,\n operations: mergeOperations(methods),\n client: async (account) => sheets({ version: 'v4', auth: await authorizedClient(account) }),\n runAuth: runAuthFlow,\n staleCredentials: isInvalidGrant,\n});\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "google-mcp-suite",
3
- "version": "1.11.0",
3
+ "version": "1.11.2",
4
4
  "type": "module",
5
5
  "description": "Google Workspace MCP servers for AI agents, one per service per account: Gmail, Google Calendar, Google Drive, Google Docs, and Google Sheets. Identity is bound to the running instance, so an agent (Claude, Cursor, or any MCP client) can never act on the wrong account; each server exposes Google's curated MCP toolset (where one exists) plus the broader REST surface.",
6
6
  "keywords": [