mcp-google-extras 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +80 -0
  3. package/dist/auth.js +225 -0
  4. package/dist/cachedToolsList.js +38 -0
  5. package/dist/clients.js +92 -0
  6. package/dist/googleDocsApiHelpers.js +883 -0
  7. package/dist/googleSheetsApiHelpers.js +808 -0
  8. package/dist/index.js +54 -0
  9. package/dist/logger.js +58 -0
  10. package/dist/markdown-transformer/docsToMarkdown.js +259 -0
  11. package/dist/markdown-transformer/index.js +126 -0
  12. package/dist/markdown-transformer/markdownToDocs.js +834 -0
  13. package/dist/tools/docs/addTab.js +92 -0
  14. package/dist/tools/docs/appendToGoogleDoc.js +81 -0
  15. package/dist/tools/docs/comments/addComment.js +83 -0
  16. package/dist/tools/docs/comments/deleteComment.js +30 -0
  17. package/dist/tools/docs/comments/getComment.js +45 -0
  18. package/dist/tools/docs/comments/index.js +14 -0
  19. package/dist/tools/docs/comments/listComments.js +43 -0
  20. package/dist/tools/docs/comments/replyToComment.js +35 -0
  21. package/dist/tools/docs/comments/resolveComment.js +55 -0
  22. package/dist/tools/docs/deleteRange.js +72 -0
  23. package/dist/tools/docs/findAndReplace.js +54 -0
  24. package/dist/tools/docs/formatting/applyParagraphStyle.js +83 -0
  25. package/dist/tools/docs/formatting/applyTextStyle.js +49 -0
  26. package/dist/tools/docs/formatting/index.js +6 -0
  27. package/dist/tools/docs/index.js +38 -0
  28. package/dist/tools/docs/insertImage.js +122 -0
  29. package/dist/tools/docs/insertPageBreak.js +58 -0
  30. package/dist/tools/docs/insertTable.js +53 -0
  31. package/dist/tools/docs/insertTableWithData.js +135 -0
  32. package/dist/tools/docs/insertText.js +61 -0
  33. package/dist/tools/docs/listDocumentTabs.js +60 -0
  34. package/dist/tools/docs/modifyText.js +158 -0
  35. package/dist/tools/docs/readGoogleDoc.js +165 -0
  36. package/dist/tools/docs/renameTab.js +61 -0
  37. package/dist/tools/drive/copyFile.js +63 -0
  38. package/dist/tools/drive/createDocument.js +89 -0
  39. package/dist/tools/drive/createFolder.js +48 -0
  40. package/dist/tools/drive/createFromTemplate.js +82 -0
  41. package/dist/tools/drive/deleteFile.js +72 -0
  42. package/dist/tools/drive/getDocumentInfo.js +48 -0
  43. package/dist/tools/drive/getFolderInfo.js +48 -0
  44. package/dist/tools/drive/index.js +26 -0
  45. package/dist/tools/drive/listFolderContents.js +82 -0
  46. package/dist/tools/drive/listGoogleDocs.js +67 -0
  47. package/dist/tools/drive/moveFile.js +54 -0
  48. package/dist/tools/drive/renameFile.js +39 -0
  49. package/dist/tools/drive/searchGoogleDocs.js +73 -0
  50. package/dist/tools/extras/index.js +7 -0
  51. package/dist/tools/extras/readFile.js +82 -0
  52. package/dist/tools/extras/searchFileContents.js +81 -0
  53. package/dist/tools/index.js +15 -0
  54. package/dist/tools/sheets/addConditionalFormatting.js +143 -0
  55. package/dist/tools/sheets/addSpreadsheetSheet.js +34 -0
  56. package/dist/tools/sheets/appendSpreadsheetRows.js +43 -0
  57. package/dist/tools/sheets/appendTableRows.js +50 -0
  58. package/dist/tools/sheets/autoResizeColumns.js +67 -0
  59. package/dist/tools/sheets/batchWrite.js +59 -0
  60. package/dist/tools/sheets/clearSpreadsheetRange.js +31 -0
  61. package/dist/tools/sheets/copyFormatting.js +59 -0
  62. package/dist/tools/sheets/createSpreadsheet.js +71 -0
  63. package/dist/tools/sheets/createTable.js +120 -0
  64. package/dist/tools/sheets/deleteChart.js +41 -0
  65. package/dist/tools/sheets/deleteSheet.js +43 -0
  66. package/dist/tools/sheets/deleteTable.js +56 -0
  67. package/dist/tools/sheets/duplicateSheet.js +53 -0
  68. package/dist/tools/sheets/formatCells.js +106 -0
  69. package/dist/tools/sheets/freezeRowsAndColumns.js +58 -0
  70. package/dist/tools/sheets/getSpreadsheetInfo.js +44 -0
  71. package/dist/tools/sheets/getTable.js +48 -0
  72. package/dist/tools/sheets/groupRows.js +62 -0
  73. package/dist/tools/sheets/index.js +66 -0
  74. package/dist/tools/sheets/insertChart.js +225 -0
  75. package/dist/tools/sheets/listGoogleSheets.js +62 -0
  76. package/dist/tools/sheets/listTables.js +55 -0
  77. package/dist/tools/sheets/readCellFormat.js +143 -0
  78. package/dist/tools/sheets/readSpreadsheet.js +36 -0
  79. package/dist/tools/sheets/renameSheet.js +48 -0
  80. package/dist/tools/sheets/setColumnWidths.js +43 -0
  81. package/dist/tools/sheets/setDropdownValidation.js +51 -0
  82. package/dist/tools/sheets/ungroupAllRows.js +66 -0
  83. package/dist/tools/sheets/updateTableRange.js +51 -0
  84. package/dist/tools/sheets/writeSpreadsheet.js +43 -0
  85. package/dist/tools/utils/appendMarkdownToGoogleDoc.js +93 -0
  86. package/dist/tools/utils/index.js +6 -0
  87. package/dist/tools/utils/replaceDocumentWithMarkdown.js +154 -0
  88. package/dist/types.js +186 -0
  89. package/package.json +47 -0
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2025
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,80 @@
1
+ # mcp-google-extras
2
+
3
+ An MCP server for Google Docs, Sheets, and Drive — with added support for reading `.docx` and `.pdf` files directly from Google Drive.
4
+
5
+ Built on top of [@a-bonus/google-docs-mcp](https://www.npmjs.com/package/@a-bonus/google-docs-mcp) (ISC license), with additional tools for extracting text from Word documents and PDFs.
6
+
7
+ ## Features
8
+
9
+ All 44 tools from `@a-bonus/google-docs-mcp`, plus:
10
+
11
+ - **readFile** — Read the full text content of a `.docx` or `.pdf` file from Google Drive by file ID
12
+ - **searchFileContents** — Search Google Drive and extract matching text snippets from inside `.docx` and `.pdf` files
13
+
14
+ ## Setup
15
+
16
+ ### 1. Create Google OAuth credentials
17
+
18
+ 1. Go to the [Google Cloud Console](https://console.cloud.google.com/)
19
+ 2. Create a project (or use an existing one)
20
+ 3. Enable the Google Docs API, Google Sheets API, and Google Drive API
21
+ 4. Create OAuth 2.0 credentials (Desktop application type)
22
+ 5. Note your Client ID and Client Secret
23
+
24
+ ### 2. Configure your MCP client
25
+
26
+ Add this to your MCP configuration (e.g., `.mcp.json`):
27
+
28
+ ```json
29
+ {
30
+ "mcpServers": {
31
+ "google-docs": {
32
+ "command": "npx",
33
+ "args": ["-y", "mcp-google-extras"],
34
+ "env": {
35
+ "GOOGLE_CLIENT_ID": "your-client-id",
36
+ "GOOGLE_CLIENT_SECRET": "your-client-secret"
37
+ }
38
+ }
39
+ }
40
+ }
41
+ ```
42
+
43
+ ### 3. Authenticate
44
+
45
+ On first run, the server will open your browser for Google OAuth consent. The token is saved to `~/.config/google-docs-mcp/token.json` for future use.
46
+
47
+ You can also run the auth flow manually:
48
+
49
+ ```bash
50
+ npx mcp-google-extras auth
51
+ ```
52
+
53
+ ## Tools
54
+
55
+ ### Google Docs
56
+ `readDocument`, `appendText`, `appendMarkdown`, `insertText`, `deleteRange`, `modifyText`, `findAndReplace`, `insertTable`, `insertTableWithData`, `insertPageBreak`, `insertImage`, `listTabs`, `addTab`, `renameTab`, `applyTextStyle`, `applyParagraphStyle`, `addComment`, `deleteComment`, `getComment`, `listComments`, `replyToComment`, `resolveComment`, `replaceDocumentWithMarkdown`
57
+
58
+ ### Google Sheets
59
+ `readSpreadsheet`, `writeSpreadsheet`, `batchWrite`, `appendRows`, `clearRange`, `createSpreadsheet`, `getSpreadsheetInfo`, `addSheet`, `deleteSheet`, `duplicateSheet`, `renameSheet`, `formatCells`, `readCellFormat`, `autoResizeColumns`, `freezeRowsAndColumns`, `setColumnWidths`, `addConditionalFormatting`, `copyFormatting`, `setDropdownValidation`, `createTable`, `deleteTable`, `getTable`, `listTables`, `appendTableRows`, `updateTableRange`, `insertChart`, `deleteChart`, `groupRows`, `ungroupAllRows`
60
+
61
+ ### Google Drive
62
+ `listDocuments`, `searchDocuments`, `getDocumentInfo`, `createFolder`, `listFolderContents`, `getFolderInfo`, `moveFile`, `copyFile`, `renameFile`, `deleteFile`, `createDocument`, `createDocumentFromTemplate`, `listSpreadsheets`
63
+
64
+ ### Extras (new)
65
+ `readFile`, `searchFileContents`
66
+
67
+ ## Environment Variables
68
+
69
+ | Variable | Required | Description |
70
+ |---|---|---|
71
+ | `GOOGLE_CLIENT_ID` | Yes | OAuth 2.0 Client ID |
72
+ | `GOOGLE_CLIENT_SECRET` | Yes | OAuth 2.0 Client Secret |
73
+ | `GOOGLE_MCP_PROFILE` | No | Profile name for multi-account support |
74
+ | `LOG_LEVEL` | No | `debug`, `info`, `warn`, `error`, or `silent` |
75
+ | `SERVICE_ACCOUNT_PATH` | No | Path to service account JSON key (alternative to OAuth) |
76
+ | `GOOGLE_IMPERSONATE_USER` | No | Email to impersonate with service account |
77
+
78
+ ## License
79
+
80
+ ISC (based on [@a-bonus/google-docs-mcp](https://www.npmjs.com/package/@a-bonus/google-docs-mcp))
package/dist/auth.js ADDED
@@ -0,0 +1,225 @@
1
+ // src/auth.ts
2
+ import { google } from 'googleapis';
3
+ import { JWT } from 'google-auth-library';
4
+ import * as fs from 'fs/promises';
5
+ import * as path from 'path';
6
+ import * as os from 'os';
7
+ import * as http from 'http';
8
+ import { fileURLToPath } from 'url';
9
+ import { logger } from './logger.js';
10
+ // ---------------------------------------------------------------------------
11
+ // Paths
12
+ // ---------------------------------------------------------------------------
13
+ const __filename = fileURLToPath(import.meta.url);
14
+ const __dirname = path.dirname(__filename);
15
+ const projectRootDir = path.resolve(__dirname, '..');
16
+ /** Credentials file path (legacy dev workflow fallback). */
17
+ const CREDENTIALS_PATH = path.join(projectRootDir, 'credentials.json');
18
+ /**
19
+ * Token storage directory following XDG Base Directory spec.
20
+ * Uses $XDG_CONFIG_HOME if set, otherwise ~/.config.
21
+ *
22
+ * When GOOGLE_MCP_PROFILE is set, tokens are stored in a subdirectory
23
+ * per profile, allowing multiple Google accounts (one per project).
24
+ */
25
+ function getConfigDir() {
26
+ const xdg = process.env.XDG_CONFIG_HOME;
27
+ const base = xdg || path.join(os.homedir(), '.config');
28
+ const baseDir = path.join(base, 'google-docs-mcp');
29
+ const profile = process.env.GOOGLE_MCP_PROFILE;
30
+ return profile ? path.join(baseDir, profile) : baseDir;
31
+ }
32
+ function getTokenPath() {
33
+ return path.join(getConfigDir(), 'token.json');
34
+ }
35
+ // ---------------------------------------------------------------------------
36
+ // Scopes
37
+ // ---------------------------------------------------------------------------
38
+ const SCOPES = [
39
+ 'https://www.googleapis.com/auth/documents',
40
+ 'https://www.googleapis.com/auth/drive',
41
+ 'https://www.googleapis.com/auth/spreadsheets',
42
+ 'https://www.googleapis.com/auth/script.external_request',
43
+ ];
44
+ // ---------------------------------------------------------------------------
45
+ // Client secrets resolution
46
+ // ---------------------------------------------------------------------------
47
+ /**
48
+ * Resolves OAuth client ID and secret.
49
+ *
50
+ * Priority:
51
+ * 1. GOOGLE_CLIENT_ID + GOOGLE_CLIENT_SECRET env vars (npx / production)
52
+ * 2. credentials.json in the project root (local dev fallback)
53
+ */
54
+ async function loadClientSecrets() {
55
+ // 1. Environment variables
56
+ const envId = process.env.GOOGLE_CLIENT_ID;
57
+ const envSecret = process.env.GOOGLE_CLIENT_SECRET;
58
+ if (envId && envSecret) {
59
+ return { client_id: envId, client_secret: envSecret };
60
+ }
61
+ // 2. credentials.json fallback
62
+ try {
63
+ const content = await fs.readFile(CREDENTIALS_PATH, 'utf8');
64
+ const keys = JSON.parse(content);
65
+ const key = keys.installed || keys.web;
66
+ if (!key) {
67
+ throw new Error('Could not find client secrets in credentials.json.');
68
+ }
69
+ return {
70
+ client_id: key.client_id,
71
+ client_secret: key.client_secret,
72
+ };
73
+ }
74
+ catch (err) {
75
+ if (err.code === 'ENOENT') {
76
+ throw new Error('No OAuth credentials found. Set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET ' +
77
+ 'environment variables, or place a credentials.json file in the project root.');
78
+ }
79
+ throw err;
80
+ }
81
+ }
82
+ // ---------------------------------------------------------------------------
83
+ // Service account auth (unchanged)
84
+ // ---------------------------------------------------------------------------
85
+ async function authorizeWithServiceAccount() {
86
+ const serviceAccountPath = process.env.SERVICE_ACCOUNT_PATH;
87
+ const impersonateUser = process.env.GOOGLE_IMPERSONATE_USER;
88
+ try {
89
+ const keyFileContent = await fs.readFile(serviceAccountPath, 'utf8');
90
+ const serviceAccountKey = JSON.parse(keyFileContent);
91
+ const auth = new JWT({
92
+ email: serviceAccountKey.client_email,
93
+ key: serviceAccountKey.private_key,
94
+ scopes: SCOPES,
95
+ subject: impersonateUser,
96
+ });
97
+ await auth.authorize();
98
+ if (impersonateUser) {
99
+ logger.info(`Service Account authentication successful, impersonating: ${impersonateUser}`);
100
+ }
101
+ else {
102
+ logger.info('Service Account authentication successful!');
103
+ }
104
+ return auth;
105
+ }
106
+ catch (error) {
107
+ if (error.code === 'ENOENT') {
108
+ logger.error(`FATAL: Service account key file not found at path: ${serviceAccountPath}`);
109
+ throw new Error('Service account key file not found. Please check the path in SERVICE_ACCOUNT_PATH.');
110
+ }
111
+ logger.error('FATAL: Error loading or authorizing the service account key:', error.message);
112
+ throw new Error('Failed to authorize using the service account. Ensure the key file is valid and the path is correct.');
113
+ }
114
+ }
115
+ // ---------------------------------------------------------------------------
116
+ // Token persistence (XDG path)
117
+ // ---------------------------------------------------------------------------
118
+ async function loadSavedCredentialsIfExist() {
119
+ try {
120
+ const tokenPath = getTokenPath();
121
+ const content = await fs.readFile(tokenPath, 'utf8');
122
+ const credentials = JSON.parse(content);
123
+ const { client_secret, client_id } = await loadClientSecrets();
124
+ const client = new google.auth.OAuth2(client_id, client_secret);
125
+ client.setCredentials(credentials);
126
+ return client;
127
+ }
128
+ catch {
129
+ return null;
130
+ }
131
+ }
132
+ async function saveCredentials(client) {
133
+ const { client_secret, client_id } = await loadClientSecrets();
134
+ const configDir = getConfigDir();
135
+ await fs.mkdir(configDir, { recursive: true });
136
+ const tokenPath = getTokenPath();
137
+ const payload = JSON.stringify({
138
+ type: 'authorized_user',
139
+ client_id,
140
+ client_secret,
141
+ refresh_token: client.credentials.refresh_token,
142
+ }, null, 2);
143
+ await fs.writeFile(tokenPath, payload);
144
+ logger.info('Token stored to', tokenPath);
145
+ }
146
+ // ---------------------------------------------------------------------------
147
+ // Interactive OAuth browser flow
148
+ // ---------------------------------------------------------------------------
149
+ async function authenticate() {
150
+ const { client_secret, client_id } = await loadClientSecrets();
151
+ // Start a temporary local server to receive the OAuth callback
152
+ const server = http.createServer();
153
+ await new Promise((resolve) => server.listen(0, 'localhost', resolve));
154
+ const port = server.address().port;
155
+ const redirectUri = `http://localhost:${port}`;
156
+ const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirectUri);
157
+ const authorizeUrl = oAuth2Client.generateAuthUrl({
158
+ access_type: 'offline',
159
+ scope: SCOPES.join(' '),
160
+ });
161
+ logger.info('Authorize this app by visiting this url:', authorizeUrl);
162
+ // Wait for the OAuth callback
163
+ const code = await new Promise((resolve, reject) => {
164
+ server.on('request', (req, res) => {
165
+ const url = new URL(req.url, `http://localhost:${port}`);
166
+ const authCode = url.searchParams.get('code');
167
+ const error = url.searchParams.get('error');
168
+ if (error) {
169
+ res.writeHead(200, { 'Content-Type': 'text/html' });
170
+ res.end('<h1>Authorization failed</h1><p>You can close this tab.</p>');
171
+ reject(new Error(`Authorization error: ${error}`));
172
+ server.close();
173
+ return;
174
+ }
175
+ if (authCode) {
176
+ res.writeHead(200, { 'Content-Type': 'text/html' });
177
+ res.end('<h1>Authorization successful!</h1><p>You can close this tab.</p>');
178
+ resolve(authCode);
179
+ server.close();
180
+ }
181
+ });
182
+ });
183
+ const { tokens } = await oAuth2Client.getToken(code);
184
+ oAuth2Client.setCredentials(tokens);
185
+ if (tokens.refresh_token) {
186
+ await saveCredentials(oAuth2Client);
187
+ }
188
+ else {
189
+ logger.warn('Did not receive refresh token. Token might expire.');
190
+ }
191
+ logger.info('Authentication successful!');
192
+ return oAuth2Client;
193
+ }
194
+ // ---------------------------------------------------------------------------
195
+ // Public API
196
+ // ---------------------------------------------------------------------------
197
+ /**
198
+ * Main authorization entry point used by the server at startup.
199
+ *
200
+ * Resolution order:
201
+ * 1. SERVICE_ACCOUNT_PATH env var -> service account JWT
202
+ * 2. Saved token in ~/.config/google-docs-mcp/token.json -> OAuth2Client
203
+ * 3. Interactive browser OAuth flow -> OAuth2Client (saves token for next time)
204
+ */
205
+ export async function authorize() {
206
+ if (process.env.SERVICE_ACCOUNT_PATH) {
207
+ logger.info('Service account path detected. Attempting service account authentication...');
208
+ return authorizeWithServiceAccount();
209
+ }
210
+ logger.info('Attempting OAuth 2.0 authentication...');
211
+ const client = await loadSavedCredentialsIfExist();
212
+ if (client) {
213
+ logger.info('Using saved credentials.');
214
+ return client;
215
+ }
216
+ logger.info('No saved token found. Starting interactive authentication flow...');
217
+ return authenticate();
218
+ }
219
+ /**
220
+ * Forces the interactive OAuth browser flow, ignoring any saved token.
221
+ * Used by the `auth` CLI subcommand to let users (re-)authorize.
222
+ */
223
+ export async function runAuthFlow() {
224
+ await authenticate();
225
+ }
@@ -0,0 +1,38 @@
1
+ // FastMCP's default tools/list handler runs toJsonSchema() for every tool on every request.
2
+ // Hosts that poll tools/list frequently (or many concurrent sessions) then burn a full CPU core.
3
+ // We precompute the list once before stdio connects, then replace the handler to return that snapshot.
4
+ import { ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
5
+ import { toJsonSchema } from 'xsschema';
6
+ import { logger } from './logger.js';
7
+ export function collectToolsWhileRegistering(server, out) {
8
+ const add = server.addTool.bind(server);
9
+ server.addTool = (tool) => {
10
+ out.push(tool);
11
+ add(tool);
12
+ };
13
+ }
14
+ export async function buildCachedToolsListPayload(tools) {
15
+ return {
16
+ tools: await Promise.all(tools.map(async (tool) => ({
17
+ annotations: tool.annotations,
18
+ description: tool.description,
19
+ inputSchema: tool.parameters
20
+ ? await toJsonSchema(tool.parameters)
21
+ : {
22
+ additionalProperties: false,
23
+ properties: {},
24
+ type: 'object',
25
+ },
26
+ name: tool.name,
27
+ }))),
28
+ };
29
+ }
30
+ export function installCachedToolsListHandler(server, listPayload) {
31
+ const session = server.sessions[0];
32
+ if (!session) {
33
+ logger.warn('No MCP session; skipping tools/list cache install.');
34
+ return;
35
+ }
36
+ session.server.setRequestHandler(ListToolsRequestSchema, async () => listPayload);
37
+ logger.debug(`Installed cached tools/list (${listPayload.tools.length} tools).`);
38
+ }
@@ -0,0 +1,92 @@
1
+ // src/clients.ts
2
+ import { google } from 'googleapis';
3
+ import { UserError } from 'fastmcp';
4
+ import { authorize } from './auth.js';
5
+ import { logger } from './logger.js';
6
+ let authClient = null;
7
+ let googleDocs = null;
8
+ let googleDrive = null;
9
+ let googleSheets = null;
10
+ let googleScript = null;
11
+ // --- Initialization ---
12
+ export async function initializeGoogleClient() {
13
+ if (googleDocs && googleDrive && googleSheets)
14
+ return { authClient, googleDocs, googleDrive, googleSheets, googleScript };
15
+ if (!authClient) {
16
+ try {
17
+ logger.info('Attempting to authorize Google API client...');
18
+ const client = await authorize();
19
+ authClient = client;
20
+ googleDocs = google.docs({ version: 'v1', auth: authClient });
21
+ googleDrive = google.drive({ version: 'v3', auth: authClient });
22
+ googleSheets = google.sheets({ version: 'v4', auth: authClient });
23
+ googleScript = google.script({ version: 'v1', auth: authClient });
24
+ logger.info('Google API client authorized successfully.');
25
+ }
26
+ catch (error) {
27
+ logger.error('FATAL: Failed to initialize Google API client:', error);
28
+ authClient = null;
29
+ googleDocs = null;
30
+ googleDrive = null;
31
+ googleSheets = null;
32
+ googleScript = null;
33
+ throw new Error('Google client initialization failed. Cannot start server tools.');
34
+ }
35
+ }
36
+ if (authClient && !googleDocs) {
37
+ googleDocs = google.docs({ version: 'v1', auth: authClient });
38
+ }
39
+ if (authClient && !googleDrive) {
40
+ googleDrive = google.drive({ version: 'v3', auth: authClient });
41
+ }
42
+ if (authClient && !googleSheets) {
43
+ googleSheets = google.sheets({ version: 'v4', auth: authClient });
44
+ }
45
+ if (authClient && !googleScript) {
46
+ googleScript = google.script({ version: 'v1', auth: authClient });
47
+ }
48
+ if (!googleDocs || !googleDrive || !googleSheets) {
49
+ throw new Error('Google Docs, Drive, and Sheets clients could not be initialized.');
50
+ }
51
+ return { authClient, googleDocs, googleDrive, googleSheets, googleScript };
52
+ }
53
+ // --- Helper to get Docs client within tools ---
54
+ export async function getDocsClient() {
55
+ const { googleDocs: docs } = await initializeGoogleClient();
56
+ if (!docs) {
57
+ throw new UserError('Google Docs client is not initialized. Authentication might have failed during startup or lost connection.');
58
+ }
59
+ return docs;
60
+ }
61
+ // --- Helper to get Drive client within tools ---
62
+ export async function getDriveClient() {
63
+ const { googleDrive: drive } = await initializeGoogleClient();
64
+ if (!drive) {
65
+ throw new UserError('Google Drive client is not initialized. Authentication might have failed during startup or lost connection.');
66
+ }
67
+ return drive;
68
+ }
69
+ // --- Helper to get Sheets client within tools ---
70
+ export async function getSheetsClient() {
71
+ const { googleSheets: sheets } = await initializeGoogleClient();
72
+ if (!sheets) {
73
+ throw new UserError('Google Sheets client is not initialized. Authentication might have failed during startup or lost connection.');
74
+ }
75
+ return sheets;
76
+ }
77
+ // --- Helper to get Auth client for direct API usage ---
78
+ export async function getAuthClient() {
79
+ const { authClient: client } = await initializeGoogleClient();
80
+ if (!client) {
81
+ throw new UserError('Auth client is not initialized. Authentication might have failed during startup or lost connection.');
82
+ }
83
+ return client;
84
+ }
85
+ // --- Helper to get Script client within tools ---
86
+ export async function getScriptClient() {
87
+ const { googleScript: script } = await initializeGoogleClient();
88
+ if (!script) {
89
+ throw new UserError('Google Script client is not initialized. Authentication might have failed during startup or lost connection.');
90
+ }
91
+ return script;
92
+ }