@a1-x-tech/mcp-google-sheets 0.1.0 → 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.
- package/README.md +36 -43
- package/README.ru.md +35 -42
- package/dist/client.js +31 -5
- package/dist/index.js +8 -8
- package/dist/tools/auth.js +38 -0
- package/package.json +2 -1
- package/test/dist-smoke.test.js +37 -4
package/README.md
CHANGED
|
@@ -3,15 +3,16 @@
|
|
|
3
3
|
**English** | [Русский](./README.ru.md)
|
|
4
4
|
|
|
5
5
|
[](https://www.npmjs.com/package/@a1-x-tech/mcp-google-sheets)
|
|
6
|
-
[](https://github.com/A1-x-Tech/mcp-google-sheets/actions/workflows/ci.yml)
|
|
7
6
|
[](https://glama.ai/mcp/servers/A1-x-Tech/mcp-google-sheets)
|
|
7
|
+
[](https://github.com/A1-x-Tech/mcp-google-sheets/actions/workflows/ci.yml)
|
|
8
8
|
[](./LICENSE)
|
|
9
9
|
|
|
10
10
|
**A1 Google Sheets MCP** lets an AI app work with Google Sheets in plain language. Find a spreadsheet, read its data, write and append rows, shape sheets and formatting, build charts and share the result.
|
|
11
11
|
|
|
12
12
|
It uses the Google Sheets API with your Google account. It separates reading from writing, keeps destructive operations explicit and makes the limits of the Sheets API clear instead of implying that every spreadsheet task is possible.
|
|
13
13
|
|
|
14
|
-
- **
|
|
14
|
+
- **26 tools.** Search and create spreadsheets, read and write ranges, manage sheets, formatting, data validation, protected ranges, conditional formats, structured tables, charts and access.
|
|
15
|
+
- **Connects from the conversation.** Say "connect Google Sheets": the server walks you through the OAuth client, catches Google's redirect on `127.0.0.1` with PKCE and keeps the tokens itself — no config files, no restart.
|
|
15
16
|
- **Writes are deliberate.** A write is never replayed after an ambiguous failure — a replayed append would duplicate rows — and destructive tools are marked so your AI client can ask first.
|
|
16
17
|
- **Sheets only.** Drive is an internal dependency for spreadsheet search and sharing alone; there is no generic Drive tool, and `raw_request` cannot reach Drive.
|
|
17
18
|
- **Minimal Google scopes.** `spreadsheets` covers every Sheets tool; a Drive scope is needed only for spreadsheet search and sharing.
|
|
@@ -52,10 +53,10 @@ Start with a read-only question:
|
|
|
52
53
|
|
|
53
54
|
## Quick start
|
|
54
55
|
|
|
55
|
-
You need Node.js 20
|
|
56
|
+
You need Node.js 20+ and a Google account. Credentials are not required at install time — the server connects from the conversation.
|
|
56
57
|
|
|
57
|
-
1.
|
|
58
|
-
2.
|
|
58
|
+
1. Add the server to your AI app.
|
|
59
|
+
2. Say "connect Google Sheets": the assistant walks you through [creating the OAuth client and approving access](#getting-access) without editing config files.
|
|
59
60
|
3. Ask the read-only question above.
|
|
60
61
|
|
|
61
62
|
<details open>
|
|
@@ -63,15 +64,12 @@ You need Node.js 20+, a Google account and OAuth credentials from a Google Cloud
|
|
|
63
64
|
|
|
64
65
|
<br>
|
|
65
66
|
|
|
66
|
-
**In the app:** open **Settings →
|
|
67
|
+
**In the app:** open **Settings → MCP servers**, select **Add server**, choose **STDIO**, enter the command `npx -y @a1-x-tech/mcp-google-sheets@latest` and environment variables `GOOGLE_SHEETS_CLIENT_ID`, `GOOGLE_SHEETS_CLIENT_SECRET`, `GOOGLE_SHEETS_REFRESH_TOKEN`, then select **Save** and **Restart**.
|
|
67
68
|
|
|
68
69
|
**From the command line:**
|
|
69
70
|
|
|
70
71
|
```bash
|
|
71
72
|
codex mcp add google-sheets \
|
|
72
|
-
--env GOOGLE_SHEETS_CLIENT_ID=your_client_id \
|
|
73
|
-
--env GOOGLE_SHEETS_CLIENT_SECRET=your_client_secret \
|
|
74
|
-
--env GOOGLE_SHEETS_REFRESH_TOKEN=your_refresh_token \
|
|
75
73
|
-- npx -y @a1-x-tech/mcp-google-sheets@latest
|
|
76
74
|
```
|
|
77
75
|
|
|
@@ -90,9 +88,6 @@ codex mcp list
|
|
|
90
88
|
|
|
91
89
|
```bash
|
|
92
90
|
claude mcp add \
|
|
93
|
-
--env GOOGLE_SHEETS_CLIENT_ID=your_client_id \
|
|
94
|
-
--env GOOGLE_SHEETS_CLIENT_SECRET=your_client_secret \
|
|
95
|
-
--env GOOGLE_SHEETS_REFRESH_TOKEN=your_refresh_token \
|
|
96
91
|
--transport stdio --scope user google-sheets \
|
|
97
92
|
-- npx -y @a1-x-tech/mcp-google-sheets@latest
|
|
98
93
|
```
|
|
@@ -110,25 +105,22 @@ claude mcp list
|
|
|
110
105
|
|
|
111
106
|
<br>
|
|
112
107
|
|
|
113
|
-
|
|
108
|
+
The current official path is **Settings → Extensions**. For a custom desktop extension, open **Advanced settings → Extension Developer → Install Extension…**, select a `.mcpb` file and follow the prompts.
|
|
109
|
+
|
|
110
|
+
This repository currently publishes an npm stdio package and does not contain a `.mcpb` bundle. For Claude Desktop builds that still support local configuration, use the following JSON stdio configuration as a fallback:
|
|
114
111
|
|
|
115
112
|
```json
|
|
116
113
|
{
|
|
117
114
|
"mcpServers": {
|
|
118
115
|
"google-sheets": {
|
|
119
116
|
"command": "npx",
|
|
120
|
-
"args": ["-y", "@a1-x-tech/mcp-google-sheets@latest"]
|
|
121
|
-
"env": {
|
|
122
|
-
"GOOGLE_SHEETS_CLIENT_ID": "your_client_id",
|
|
123
|
-
"GOOGLE_SHEETS_CLIENT_SECRET": "your_client_secret",
|
|
124
|
-
"GOOGLE_SHEETS_REFRESH_TOKEN": "your_refresh_token"
|
|
125
|
-
}
|
|
117
|
+
"args": ["-y", "@a1-x-tech/mcp-google-sheets@latest"]
|
|
126
118
|
}
|
|
127
119
|
}
|
|
128
120
|
}
|
|
129
121
|
```
|
|
130
122
|
|
|
131
|
-
|
|
123
|
+
In those builds, save it to `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS or `%APPDATA%\Claude\claude_desktop_config.json` on Windows.
|
|
132
124
|
|
|
133
125
|
[Claude Desktop MCP documentation](https://support.claude.com/en/articles/10949351-getting-started-with-local-mcp-servers-on-claude-desktop)
|
|
134
126
|
|
|
@@ -147,12 +139,7 @@ Add this to `~/.cursor/mcp.json` on macOS/Linux or `%USERPROFILE%\.cursor\mcp.js
|
|
|
147
139
|
"google-sheets": {
|
|
148
140
|
"type": "stdio",
|
|
149
141
|
"command": "npx",
|
|
150
|
-
"args": ["-y", "@a1-x-tech/mcp-google-sheets@latest"]
|
|
151
|
-
"env": {
|
|
152
|
-
"GOOGLE_SHEETS_CLIENT_ID": "your_client_id",
|
|
153
|
-
"GOOGLE_SHEETS_CLIENT_SECRET": "your_client_secret",
|
|
154
|
-
"GOOGLE_SHEETS_REFRESH_TOKEN": "your_refresh_token"
|
|
155
|
-
}
|
|
142
|
+
"args": ["-y", "@a1-x-tech/mcp-google-sheets@latest"]
|
|
156
143
|
}
|
|
157
144
|
}
|
|
158
145
|
}
|
|
@@ -175,19 +162,9 @@ Run **MCP: Open User Configuration** and add:
|
|
|
175
162
|
"google-sheets": {
|
|
176
163
|
"type": "stdio",
|
|
177
164
|
"command": "npx",
|
|
178
|
-
"args": ["-y", "@a1-x-tech/mcp-google-sheets@latest"]
|
|
179
|
-
"env": {
|
|
180
|
-
"GOOGLE_SHEETS_CLIENT_ID": "${input:sheets_client_id}",
|
|
181
|
-
"GOOGLE_SHEETS_CLIENT_SECRET": "${input:sheets_client_secret}",
|
|
182
|
-
"GOOGLE_SHEETS_REFRESH_TOKEN": "${input:sheets_refresh_token}"
|
|
183
|
-
}
|
|
165
|
+
"args": ["-y", "@a1-x-tech/mcp-google-sheets@latest"]
|
|
184
166
|
}
|
|
185
|
-
}
|
|
186
|
-
"inputs": [
|
|
187
|
-
{ "type": "promptString", "id": "sheets_client_id", "description": "Google OAuth client ID" },
|
|
188
|
-
{ "type": "promptString", "id": "sheets_client_secret", "description": "Google OAuth client secret", "password": true },
|
|
189
|
-
{ "type": "promptString", "id": "sheets_refresh_token", "description": "Google OAuth refresh token", "password": true }
|
|
190
|
-
]
|
|
167
|
+
}
|
|
191
168
|
}
|
|
192
169
|
```
|
|
193
170
|
|
|
@@ -249,7 +226,20 @@ The AI client controls confirmation prompts. The server marks reads, writes and
|
|
|
249
226
|
|
|
250
227
|
## Getting access
|
|
251
228
|
|
|
252
|
-
Google Sheets requires OAuth 2.0
|
|
229
|
+
Google Sheets requires OAuth 2.0; an API key is not enough. There are two ways in, and the first one needs no configuration files.
|
|
230
|
+
|
|
231
|
+
### Connect from the chat (recommended)
|
|
232
|
+
|
|
233
|
+
Say "connect Google Sheets" and the assistant runs the flow with you:
|
|
234
|
+
|
|
235
|
+
1. `setup_instructions` prints the checklist: create or select a Google Cloud project, enable **Google Sheets API**, configure the consent screen and create a **Desktop app** OAuth client.
|
|
236
|
+
2. Download that client's JSON ("Download JSON") and give the assistant its **path** — `set_client` stores it owner-only. The secret never goes through the conversation.
|
|
237
|
+
3. `start_login` returns a Google consent link. Open it **on this machine** and approve; the code comes back to a one-shot listener on `127.0.0.1` (PKCE), never through the chat.
|
|
238
|
+
4. `finish_login` exchanges the code and saves the tokens to `~/.config/mcp-google-sheets/credentials.json` (mode 0600).
|
|
239
|
+
|
|
240
|
+
The tokens are re-read on every call, so the connection works immediately — no restart of the AI app. `auth_status` shows what is connected, `logout` revokes and deletes it.
|
|
241
|
+
|
|
242
|
+
### Environment variables (CI, unattended installs)
|
|
253
243
|
|
|
254
244
|
1. Create or select a Google Cloud project and enable the **Google Sheets API**. Also enable the **Google Drive API** if you want spreadsheet search and sharing.
|
|
255
245
|
2. Configure the OAuth consent screen and create a **Desktop app** OAuth client.
|
|
@@ -266,12 +256,15 @@ Testing-mode OAuth refresh tokens can expire after seven days. Publish the OAuth
|
|
|
266
256
|
|
|
267
257
|
## Configuration
|
|
268
258
|
|
|
259
|
+
Every variable is optional — with none of them the server connects [from the chat](#connect-from-the-chat-recommended).
|
|
260
|
+
|
|
269
261
|
| Variable | Required | Description |
|
|
270
262
|
|---|---|---|
|
|
271
|
-
| `GOOGLE_SHEETS_CLIENT_ID` |
|
|
272
|
-
| `GOOGLE_SHEETS_CLIENT_SECRET` |
|
|
273
|
-
| `GOOGLE_SHEETS_REFRESH_TOKEN` |
|
|
274
|
-
| `GOOGLE_SHEETS_ACCESS_TOKEN` |
|
|
263
|
+
| `GOOGLE_SHEETS_CLIENT_ID` | No* | OAuth client ID. |
|
|
264
|
+
| `GOOGLE_SHEETS_CLIENT_SECRET` | No* | OAuth client secret. |
|
|
265
|
+
| `GOOGLE_SHEETS_REFRESH_TOKEN` | No* | OAuth refresh token. |
|
|
266
|
+
| `GOOGLE_SHEETS_ACCESS_TOKEN` | No* | Short-lived (~1 h) alternative to the OAuth trio. |
|
|
267
|
+
| `GOOGLE_SHEETS_OAUTH_PORT` | No | Fixed loopback port for the in-chat login; useful over SSH port forwarding. |
|
|
275
268
|
| `GOOGLE_SHEETS_API_BASE` | No | Google Sheets API base URL override. |
|
|
276
269
|
| `GOOGLE_SHEETS_TIMEOUT_MS` | No | Per-request timeout; default `60000` ms. |
|
|
277
270
|
| `GOOGLE_SHEETS_MAX_RETRIES` | No | Temporary-error retries; default `3`. |
|
package/README.ru.md
CHANGED
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
|
|
12
12
|
Сервер работает с Google Sheets API через ваш Google-аккаунт. Он разделяет чтение и запись, явно помечает разрушительные операции и честно показывает ограничения Sheets API, а не создаёт впечатление, что с таблицей можно сделать всё.
|
|
13
13
|
|
|
14
|
-
- **
|
|
14
|
+
- **26 инструментов.** Поиск и создание таблиц, чтение и запись диапазонов, управление листами, форматированием, проверкой данных, защищёнными диапазонами, условным форматированием, структурированными таблицами, диаграммами и доступом.
|
|
15
|
+
- **Подключение из диалога.** Скажите «подключи Google Таблицы»: сервер проведёт через создание OAuth-клиента, поймает редирект Google на `127.0.0.1` с PKCE и сам сохранит токены — без конфигов и перезапуска.
|
|
15
16
|
- **Осознанная запись.** Запись никогда не повторяется после неопределённой ошибки — повтор `append` продублировал бы строки, — а разрушительные инструменты помечены, чтобы AI-клиент мог сначала спросить.
|
|
16
17
|
- **Только Sheets.** Drive — внутренняя зависимость лишь для поиска таблиц и управления доступом; отдельного Drive-инструмента нет, и `raw_request` до Drive не дотягивается.
|
|
17
18
|
- **Минимальные scope Google.** `spreadsheets` покрывает каждый Sheets-инструмент; scope Drive нужен только для поиска таблиц и управления доступом.
|
|
@@ -52,10 +53,10 @@
|
|
|
52
53
|
|
|
53
54
|
## Быстрый старт
|
|
54
55
|
|
|
55
|
-
Нужны Node.js 20
|
|
56
|
+
Нужны Node.js 20+ и Google-аккаунт. Учётные данные при установке не нужны: сервер подключается прямо в диалоге.
|
|
56
57
|
|
|
57
|
-
1.
|
|
58
|
-
2.
|
|
58
|
+
1. Добавьте сервер в AI-приложение.
|
|
59
|
+
2. Скажите «подключи Google Таблицы» — ассистент проведёт [создание OAuth-клиента и выдачу доступа](#как-получить-доступ), не трогая конфиги.
|
|
59
60
|
3. Отправьте запрос, который только читает данные.
|
|
60
61
|
|
|
61
62
|
<details open>
|
|
@@ -63,15 +64,12 @@
|
|
|
63
64
|
|
|
64
65
|
<br>
|
|
65
66
|
|
|
66
|
-
**В приложении:** откройте **Settings →
|
|
67
|
+
**В приложении:** откройте **Settings → MCP servers**, нажмите **Add server**, выберите **STDIO**, укажите команду `npx -y @a1-x-tech/mcp-google-sheets@latest` и переменные окружения `GOOGLE_SHEETS_CLIENT_ID`, `GOOGLE_SHEETS_CLIENT_SECRET`, `GOOGLE_SHEETS_REFRESH_TOKEN`, затем нажмите **Save**, потом **Restart**.
|
|
67
68
|
|
|
68
69
|
**В командной строке:**
|
|
69
70
|
|
|
70
71
|
```bash
|
|
71
72
|
codex mcp add google-sheets \
|
|
72
|
-
--env GOOGLE_SHEETS_CLIENT_ID=your_client_id \
|
|
73
|
-
--env GOOGLE_SHEETS_CLIENT_SECRET=your_client_secret \
|
|
74
|
-
--env GOOGLE_SHEETS_REFRESH_TOKEN=your_refresh_token \
|
|
75
73
|
-- npx -y @a1-x-tech/mcp-google-sheets@latest
|
|
76
74
|
```
|
|
77
75
|
|
|
@@ -90,9 +88,6 @@ codex mcp list
|
|
|
90
88
|
|
|
91
89
|
```bash
|
|
92
90
|
claude mcp add \
|
|
93
|
-
--env GOOGLE_SHEETS_CLIENT_ID=your_client_id \
|
|
94
|
-
--env GOOGLE_SHEETS_CLIENT_SECRET=your_client_secret \
|
|
95
|
-
--env GOOGLE_SHEETS_REFRESH_TOKEN=your_refresh_token \
|
|
96
91
|
--transport stdio --scope user google-sheets \
|
|
97
92
|
-- npx -y @a1-x-tech/mcp-google-sheets@latest
|
|
98
93
|
```
|
|
@@ -110,25 +105,22 @@ claude mcp list
|
|
|
110
105
|
|
|
111
106
|
<br>
|
|
112
107
|
|
|
113
|
-
|
|
108
|
+
Актуальный официальный путь — **Settings → Extensions**. Для пользовательского desktop extension откройте **Advanced settings → Extension Developer → Install Extension…**, выберите файл `.mcpb` и следуйте подсказкам.
|
|
109
|
+
|
|
110
|
+
Этот репозиторий сейчас публикует npm-пакет со stdio и пока не содержит `.mcpb`. Поэтому используйте приведённый ниже JSON stdio-конфиг как fallback только в сборках Claude Desktop, где ещё поддерживается локальная конфигурация:
|
|
114
111
|
|
|
115
112
|
```json
|
|
116
113
|
{
|
|
117
114
|
"mcpServers": {
|
|
118
115
|
"google-sheets": {
|
|
119
116
|
"command": "npx",
|
|
120
|
-
"args": ["-y", "@a1-x-tech/mcp-google-sheets@latest"]
|
|
121
|
-
"env": {
|
|
122
|
-
"GOOGLE_SHEETS_CLIENT_ID": "your_client_id",
|
|
123
|
-
"GOOGLE_SHEETS_CLIENT_SECRET": "your_client_secret",
|
|
124
|
-
"GOOGLE_SHEETS_REFRESH_TOKEN": "your_refresh_token"
|
|
125
|
-
}
|
|
117
|
+
"args": ["-y", "@a1-x-tech/mcp-google-sheets@latest"]
|
|
126
118
|
}
|
|
127
119
|
}
|
|
128
120
|
}
|
|
129
121
|
```
|
|
130
122
|
|
|
131
|
-
|
|
123
|
+
В таких сборках сохраните его в `~/Library/Application Support/Claude/claude_desktop_config.json` на macOS или `%APPDATA%\Claude\claude_desktop_config.json` на Windows.
|
|
132
124
|
|
|
133
125
|
[Документация Claude Desktop MCP](https://support.claude.com/en/articles/10949351-getting-started-with-local-mcp-servers-on-claude-desktop)
|
|
134
126
|
|
|
@@ -147,12 +139,7 @@ claude mcp list
|
|
|
147
139
|
"google-sheets": {
|
|
148
140
|
"type": "stdio",
|
|
149
141
|
"command": "npx",
|
|
150
|
-
"args": ["-y", "@a1-x-tech/mcp-google-sheets@latest"]
|
|
151
|
-
"env": {
|
|
152
|
-
"GOOGLE_SHEETS_CLIENT_ID": "your_client_id",
|
|
153
|
-
"GOOGLE_SHEETS_CLIENT_SECRET": "your_client_secret",
|
|
154
|
-
"GOOGLE_SHEETS_REFRESH_TOKEN": "your_refresh_token"
|
|
155
|
-
}
|
|
142
|
+
"args": ["-y", "@a1-x-tech/mcp-google-sheets@latest"]
|
|
156
143
|
}
|
|
157
144
|
}
|
|
158
145
|
}
|
|
@@ -175,19 +162,9 @@ claude mcp list
|
|
|
175
162
|
"google-sheets": {
|
|
176
163
|
"type": "stdio",
|
|
177
164
|
"command": "npx",
|
|
178
|
-
"args": ["-y", "@a1-x-tech/mcp-google-sheets@latest"]
|
|
179
|
-
"env": {
|
|
180
|
-
"GOOGLE_SHEETS_CLIENT_ID": "${input:sheets_client_id}",
|
|
181
|
-
"GOOGLE_SHEETS_CLIENT_SECRET": "${input:sheets_client_secret}",
|
|
182
|
-
"GOOGLE_SHEETS_REFRESH_TOKEN": "${input:sheets_refresh_token}"
|
|
183
|
-
}
|
|
165
|
+
"args": ["-y", "@a1-x-tech/mcp-google-sheets@latest"]
|
|
184
166
|
}
|
|
185
|
-
}
|
|
186
|
-
"inputs": [
|
|
187
|
-
{ "type": "promptString", "id": "sheets_client_id", "description": "Google OAuth client ID" },
|
|
188
|
-
{ "type": "promptString", "id": "sheets_client_secret", "description": "Google OAuth client secret", "password": true },
|
|
189
|
-
{ "type": "promptString", "id": "sheets_refresh_token", "description": "Google OAuth refresh token", "password": true }
|
|
190
|
-
]
|
|
167
|
+
}
|
|
191
168
|
}
|
|
192
169
|
```
|
|
193
170
|
|
|
@@ -249,7 +226,20 @@ claude mcp list
|
|
|
249
226
|
|
|
250
227
|
## Как получить доступ
|
|
251
228
|
|
|
252
|
-
|
|
229
|
+
Google Sheets требует OAuth 2.0: одного API-ключа недостаточно. Путей два, и первый не требует править конфигурационные файлы.
|
|
230
|
+
|
|
231
|
+
### Подключение из диалога (рекомендуемый путь)
|
|
232
|
+
|
|
233
|
+
Скажите «подключи Google Таблицы», и ассистент пройдёт флоу вместе с вами:
|
|
234
|
+
|
|
235
|
+
1. `setup_instructions` выдаёт чек-лист: создать или выбрать проект Google Cloud, включить **Google Sheets API**, настроить consent screen и создать OAuth-клиент типа **Desktop app**.
|
|
236
|
+
2. Скачайте JSON этого клиента («Download JSON») и передайте ассистенту **путь** к файлу — `set_client` сохранит его с правами только для владельца. Секрет через переписку не проходит.
|
|
237
|
+
3. `start_login` возвращает ссылку на согласие Google. Откройте её **на этой же машине** и подтвердите доступ: код возвращается на одноразовый слушатель `127.0.0.1` (PKCE), а не в чат.
|
|
238
|
+
4. `finish_login` меняет код на токены и кладёт их в `~/.config/mcp-google-sheets/credentials.json` (права 0600).
|
|
239
|
+
|
|
240
|
+
Токены перечитываются на каждый вызов, поэтому подключение действует немедленно — перезапускать AI-приложение не нужно. `auth_status` показывает состояние, `logout` отзывает токен и удаляет его.
|
|
241
|
+
|
|
242
|
+
### Переменные окружения (CI и автоматические установки)
|
|
253
243
|
|
|
254
244
|
1. Создайте или выберите проект Google Cloud и включите **Google Sheets API**. Включите также **Google Drive API**, если нужны поиск таблиц и управление доступом.
|
|
255
245
|
2. Настройте OAuth consent screen и создайте OAuth-клиент типа **Desktop app**.
|
|
@@ -266,12 +256,15 @@ Refresh token OAuth-приложения в режиме Testing может ис
|
|
|
266
256
|
|
|
267
257
|
## Конфигурация
|
|
268
258
|
|
|
259
|
+
Все переменные необязательные — без единой из них сервер подключается [из диалога](#подключение-из-диалога-рекомендуемый-путь).
|
|
260
|
+
|
|
269
261
|
| Переменная | Обязательна | Описание |
|
|
270
262
|
|---|---|---|
|
|
271
|
-
| `GOOGLE_SHEETS_CLIENT_ID` |
|
|
272
|
-
| `GOOGLE_SHEETS_CLIENT_SECRET` |
|
|
273
|
-
| `GOOGLE_SHEETS_REFRESH_TOKEN` |
|
|
274
|
-
| `GOOGLE_SHEETS_ACCESS_TOKEN` |
|
|
263
|
+
| `GOOGLE_SHEETS_CLIENT_ID` | Нет* | OAuth client ID. |
|
|
264
|
+
| `GOOGLE_SHEETS_CLIENT_SECRET` | Нет* | OAuth client secret. |
|
|
265
|
+
| `GOOGLE_SHEETS_REFRESH_TOKEN` | Нет* | OAuth refresh token. |
|
|
266
|
+
| `GOOGLE_SHEETS_ACCESS_TOKEN` | Нет* | Короткоживущая (~1 ч) альтернатива OAuth-тройке. |
|
|
267
|
+
| `GOOGLE_SHEETS_OAUTH_PORT` | Нет | Фиксированный порт loopback-слушателя для входа из диалога; нужен при пробросе портов по SSH. |
|
|
275
268
|
| `GOOGLE_SHEETS_API_BASE` | Нет | Переопределяет базовый URL Google Sheets API. |
|
|
276
269
|
| `GOOGLE_SHEETS_TIMEOUT_MS` | Нет | Тайм-аут одного запроса; по умолчанию `60000` мс. |
|
|
277
270
|
| `GOOGLE_SHEETS_MAX_RETRIES` | Нет | Повторы временных ошибок; по умолчанию `3`. |
|
package/dist/client.js
CHANGED
|
@@ -146,6 +146,7 @@ function gridRange(range) {
|
|
|
146
146
|
}
|
|
147
147
|
export class GoogleSheetsClient {
|
|
148
148
|
config;
|
|
149
|
+
tokenProvider;
|
|
149
150
|
base;
|
|
150
151
|
timeoutMs;
|
|
151
152
|
maxRetries;
|
|
@@ -154,8 +155,16 @@ export class GoogleSheetsClient {
|
|
|
154
155
|
cachedToken;
|
|
155
156
|
/** In-flight refresh, deduping concurrent token requests. */
|
|
156
157
|
refreshInFlight;
|
|
157
|
-
constructor(config
|
|
158
|
+
constructor(config,
|
|
159
|
+
/**
|
|
160
|
+
* Fallback token source (the in-chat login of @a1-x-tech/mcp-google-auth).
|
|
161
|
+
* Consulted only when the env-derived config carries no credentials —
|
|
162
|
+
* env wins (component invariant 3), so existing refresh-triple and
|
|
163
|
+
* access-token installs behave exactly as before.
|
|
164
|
+
*/
|
|
165
|
+
tokenProvider) {
|
|
158
166
|
this.config = config;
|
|
167
|
+
this.tokenProvider = tokenProvider;
|
|
159
168
|
this.base = config.apiBase.endsWith("/") ? config.apiBase : config.apiBase + "/";
|
|
160
169
|
this.timeoutMs = config.timeoutMs ?? 60_000;
|
|
161
170
|
this.maxRetries = config.maxRetries ?? 3;
|
|
@@ -164,6 +173,19 @@ export class GoogleSheetsClient {
|
|
|
164
173
|
canRefresh() {
|
|
165
174
|
return Boolean(this.config.refreshToken && this.config.clientId && this.config.clientSecret);
|
|
166
175
|
}
|
|
176
|
+
/**
|
|
177
|
+
* Whether a 401 is worth one re-mint + replay: either the env config can mint
|
|
178
|
+
* from its refresh triple, or the provider holds a refresh token (env or
|
|
179
|
+
* stored login). A static env access token can never be re-minted, so a 401
|
|
180
|
+
* there is final — replaying it would just burn a second request.
|
|
181
|
+
*/
|
|
182
|
+
canReplayOn401() {
|
|
183
|
+
if (this.canRefresh())
|
|
184
|
+
return true;
|
|
185
|
+
if (this.config.accessToken)
|
|
186
|
+
return false;
|
|
187
|
+
return this.tokenProvider?.canRefresh() ?? false;
|
|
188
|
+
}
|
|
167
189
|
/**
|
|
168
190
|
* Returns a valid Bearer token. With the refresh triple configured, mints an
|
|
169
191
|
* access token from the refresh token and caches it until shortly before it
|
|
@@ -175,9 +197,13 @@ export class GoogleSheetsClient {
|
|
|
175
197
|
*/
|
|
176
198
|
async accessToken(forceRefresh = false) {
|
|
177
199
|
if (!this.canRefresh()) {
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
200
|
+
// Env wins over the provider (component invariant 3): a static
|
|
201
|
+
// GOOGLE_SHEETS_ACCESS_TOKEN keeps behaving exactly as before.
|
|
202
|
+
if (this.config.accessToken)
|
|
203
|
+
return this.config.accessToken;
|
|
204
|
+
if (this.tokenProvider)
|
|
205
|
+
return this.tokenProvider.getAccessToken(forceRefresh);
|
|
206
|
+
throw new CredentialsError();
|
|
181
207
|
}
|
|
182
208
|
if (!forceRefresh && this.cachedToken && Date.now() < this.cachedToken.expiresAt) {
|
|
183
209
|
return this.cachedToken.value;
|
|
@@ -309,7 +335,7 @@ export class GoogleSheetsClient {
|
|
|
309
335
|
}
|
|
310
336
|
// An expired/revoked access token: re-mint once and replay. The request
|
|
311
337
|
// never executed, so this is safe for writes too.
|
|
312
|
-
if (res.status === 401 && this.
|
|
338
|
+
if (res.status === 401 && this.canReplayOn401() && !refreshedOn401) {
|
|
313
339
|
refreshedOn401 = true;
|
|
314
340
|
await this.accessToken(true);
|
|
315
341
|
continue;
|
package/dist/index.js
CHANGED
|
@@ -13,6 +13,7 @@ import { registerRuleTools } from "./tools/rules.js";
|
|
|
13
13
|
import { registerObjectTools } from "./tools/objects.js";
|
|
14
14
|
import { registerSharingTools } from "./tools/sharing.js";
|
|
15
15
|
import { registerRawTool } from "./tools/raw.js";
|
|
16
|
+
import { authUnconfiguredPrefix, hasAuthToken, registerAuthTools } from "./tools/auth.js";
|
|
16
17
|
/**
|
|
17
18
|
* Prose handed to the calling model in the `initialize` result — the only place
|
|
18
19
|
* it learns what the tool list cannot say: which Google product this API is,
|
|
@@ -41,11 +42,6 @@ const INSTRUCTIONS = "Google Sheets API v4 reads and edits spreadsheets — not
|
|
|
41
42
|
* rather than with a failed call. There is no in-chat login here: credentials
|
|
42
43
|
* come only from the environment, so the fix is an operator action + restart.
|
|
43
44
|
*/
|
|
44
|
-
const UNCONFIGURED_PREFIX = "ATTENTION: Google Sheets is not connected yet — no credentials are configured, so every " +
|
|
45
|
-
"tool call will fail. The operator must set GOOGLE_SHEETS_CLIENT_ID + " +
|
|
46
|
-
"GOOGLE_SHEETS_CLIENT_SECRET + GOOGLE_SHEETS_REFRESH_TOKEN (recommended), or " +
|
|
47
|
-
"GOOGLE_SHEETS_ACCESS_TOKEN with a short-lived access token, in the MCP client's " +
|
|
48
|
-
"server config and restart this server — the variables are read only at startup. ";
|
|
49
45
|
/** Reads the package version so the server reports its real version to MCP clients. */
|
|
50
46
|
function readVersion() {
|
|
51
47
|
try {
|
|
@@ -86,10 +82,9 @@ async function main() {
|
|
|
86
82
|
// credentials can be reported; wired to the server before tools register.
|
|
87
83
|
const telemetry = new Telemetry(readVersion());
|
|
88
84
|
const { config, problem } = loadConfigOrDegraded(telemetry);
|
|
89
|
-
const client = new GoogleSheetsClient(config);
|
|
90
85
|
// Decided once, at startup: credentials come only from the environment, so
|
|
91
86
|
// "restart after setting the variables" is the accurate advice to give.
|
|
92
|
-
const connected = hasCredentials(config);
|
|
87
|
+
const connected = hasCredentials(config) || hasAuthToken();
|
|
93
88
|
const server = new McpServer({
|
|
94
89
|
name: "mcp-google-sheets",
|
|
95
90
|
version: readVersion(),
|
|
@@ -98,7 +93,7 @@ async function main() {
|
|
|
98
93
|
{
|
|
99
94
|
instructions: connected
|
|
100
95
|
? INSTRUCTIONS
|
|
101
|
-
:
|
|
96
|
+
: authUnconfiguredPrefix() + (problem ? `Configuration problem: ${problem.message} ` : "") + INSTRUCTIONS,
|
|
102
97
|
});
|
|
103
98
|
instrumentToolCalls(server, telemetry);
|
|
104
99
|
server.server.oninitialized = () => {
|
|
@@ -110,6 +105,11 @@ async function main() {
|
|
|
110
105
|
else
|
|
111
106
|
telemetry.send("unconfigured_start", { reason: problem?.reason ?? "missing_credentials" });
|
|
112
107
|
};
|
|
108
|
+
// The auth tools come first so their TokenProvider exists before the client:
|
|
109
|
+
// the client falls back to it whenever the environment carries no
|
|
110
|
+
// credentials (env always wins — component invariant 3).
|
|
111
|
+
const tokenProvider = registerAuthTools(server);
|
|
112
|
+
const client = new GoogleSheetsClient(config, tokenProvider);
|
|
113
113
|
registerSpreadsheetTools(server, client);
|
|
114
114
|
registerValueTools(server, client);
|
|
115
115
|
registerSheetTools(server, client);
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { registerGoogleAuth, TokenProvider, unconfiguredPrefix, } from "@a1-x-tech/mcp-google-auth";
|
|
2
|
+
/**
|
|
3
|
+
* The scopes an in-chat login requests (the per-task table lives in
|
|
4
|
+
* docs/TOOLS.md). The component always adds the identity scopes on top.
|
|
5
|
+
*/
|
|
6
|
+
export const LOGIN_SCOPES = [
|
|
7
|
+
"https://www.googleapis.com/auth/spreadsheets",
|
|
8
|
+
];
|
|
9
|
+
/**
|
|
10
|
+
* The single source of the auth wiring: serverName "sheets" puts the stored
|
|
11
|
+
* login in ~/.config/mcp-google-sheets/credentials.json (the component
|
|
12
|
+
* prefixes "mcp-google-"), envPrefix keeps the provider reading the exact
|
|
13
|
+
* GOOGLE_SHEETS_* variables config.ts documents — which is what preserves the
|
|
14
|
+
* env-beats-stored priority for existing installs.
|
|
15
|
+
*/
|
|
16
|
+
export const AUTH_OPTIONS = {
|
|
17
|
+
serverName: "sheets",
|
|
18
|
+
envPrefix: "GOOGLE_SHEETS",
|
|
19
|
+
scopes: LOGIN_SCOPES,
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Registers the six onboarding tools (auth_status, setup_instructions,
|
|
23
|
+
* set_client, start_login, finish_login, logout) and returns the TokenProvider
|
|
24
|
+
* the client plugs in as its fallback token source — the same instance, so a
|
|
25
|
+
* login finished mid-session is visible to the very next API call without a
|
|
26
|
+
* restart.
|
|
27
|
+
*/
|
|
28
|
+
export function registerAuthTools(server) {
|
|
29
|
+
return registerGoogleAuth(server, AUTH_OPTIONS);
|
|
30
|
+
}
|
|
31
|
+
/** True when any token exists — env variables or a stored in-chat login. */
|
|
32
|
+
export function hasAuthToken() {
|
|
33
|
+
return new TokenProvider(AUTH_OPTIONS).hasToken();
|
|
34
|
+
}
|
|
35
|
+
/** The "NOT CONNECTED" prefix for the initialize instructions (names both fixes). */
|
|
36
|
+
export function authUnconfiguredPrefix() {
|
|
37
|
+
return unconfiguredPrefix(AUTH_OPTIONS);
|
|
38
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@a1-x-tech/mcp-google-sheets",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"description": "MCP server for the Google Sheets API — search spreadsheets, read and write ranges, manage sheets, formatting, validation, protected ranges, tables, charts and sharing. For Claude, Cursor, Codex and other AI clients.",
|
|
5
5
|
"mcpName": "io.github.A1-x-Tech/mcp-google-sheets",
|
|
6
6
|
"type": "module",
|
|
@@ -52,6 +52,7 @@
|
|
|
52
52
|
"url": "https://github.com/A1-x-Tech/mcp-google-sheets/issues"
|
|
53
53
|
},
|
|
54
54
|
"dependencies": {
|
|
55
|
+
"@a1-x-tech/mcp-google-auth": "^0.1.0",
|
|
55
56
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
56
57
|
"zod": "^3.25.0"
|
|
57
58
|
},
|
package/test/dist-smoke.test.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
2
5
|
import test from "node:test";
|
|
3
6
|
import { fileURLToPath } from "node:url";
|
|
4
7
|
|
|
@@ -14,14 +17,23 @@ import { registerRuleTools } from "../dist/tools/rules.js";
|
|
|
14
17
|
import { registerObjectTools } from "../dist/tools/objects.js";
|
|
15
18
|
import { registerSharingTools } from "../dist/tools/sharing.js";
|
|
16
19
|
import { registerRawTool } from "../dist/tools/raw.js";
|
|
20
|
+
import { registerAuthTools } from "../dist/tools/auth.js";
|
|
17
21
|
|
|
22
|
+
/**
|
|
23
|
+
* Sorted, because every assertion compares it against a sorted tool list. The
|
|
24
|
+
* six onboarding tools come from @a1-x-tech/mcp-google-auth, so this list is
|
|
25
|
+
* also the check that the component is wired into the published binary.
|
|
26
|
+
*/
|
|
18
27
|
const ALL_TOOLS = [
|
|
19
28
|
"append_values",
|
|
29
|
+
"auth_status",
|
|
20
30
|
"batch_write_values",
|
|
21
31
|
"clear_values",
|
|
22
32
|
"create_spreadsheet",
|
|
33
|
+
"finish_login",
|
|
23
34
|
"format_cells",
|
|
24
35
|
"get_spreadsheet",
|
|
36
|
+
"logout",
|
|
25
37
|
"manage_charts",
|
|
26
38
|
"manage_conditional_formats",
|
|
27
39
|
"manage_dimensions",
|
|
@@ -33,11 +45,27 @@ const ALL_TOOLS = [
|
|
|
33
45
|
"read_values",
|
|
34
46
|
"search_spreadsheets",
|
|
35
47
|
"set_borders",
|
|
48
|
+
"set_client",
|
|
36
49
|
"set_data_validation",
|
|
37
50
|
"set_frozen",
|
|
51
|
+
"setup_instructions",
|
|
52
|
+
"start_login",
|
|
38
53
|
"write_values",
|
|
39
54
|
];
|
|
40
55
|
|
|
56
|
+
/**
|
|
57
|
+
* A throwaway $XDG_CONFIG_HOME for the spawned server. The auth component
|
|
58
|
+
* re-reads $XDG_CONFIG_HOME/mcp-google-sheets/credentials.json per call, so
|
|
59
|
+
* without this a real login on the developer's machine would make the
|
|
60
|
+
* "unconfigured" case pass for the wrong reason.
|
|
61
|
+
*/
|
|
62
|
+
function isolatedConfigDir(t) {
|
|
63
|
+
const dir = mkdtempSync(join(tmpdir(), "mcp-sheets-dist-smoke-"));
|
|
64
|
+
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
|
65
|
+
return dir;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
41
69
|
test("dist client rejects foreign-origin paths before sending the Bearer token", async () => {
|
|
42
70
|
const original = globalThis.fetch;
|
|
43
71
|
let called = false;
|
|
@@ -91,6 +119,7 @@ test("dist registers the expected tools", () => {
|
|
|
91
119
|
};
|
|
92
120
|
const client = {};
|
|
93
121
|
|
|
122
|
+
registerAuthTools(server, client);
|
|
94
123
|
registerSpreadsheetTools(server, client);
|
|
95
124
|
registerValueTools(server, client);
|
|
96
125
|
registerSheetTools(server, client);
|
|
@@ -103,13 +132,14 @@ test("dist registers the expected tools", () => {
|
|
|
103
132
|
assert.deepEqual(names.sort(), ALL_TOOLS);
|
|
104
133
|
});
|
|
105
134
|
|
|
106
|
-
test("dist binary completes a real MCP handshake over stdio and lists every tool", async () => {
|
|
135
|
+
test("dist binary completes a real MCP handshake over stdio and lists every tool", async (t) => {
|
|
107
136
|
const transport = new StdioClientTransport({
|
|
108
137
|
command: process.execPath,
|
|
109
138
|
args: [fileURLToPath(new URL("../dist/index.js", import.meta.url))],
|
|
110
139
|
env: {
|
|
111
140
|
...process.env,
|
|
112
141
|
GOOGLE_SHEETS_ACCESS_TOKEN: "test-token",
|
|
142
|
+
XDG_CONFIG_HOME: isolatedConfigDir(t),
|
|
113
143
|
ASKADS_TELEMETRY: "0", // keep the suite offline
|
|
114
144
|
},
|
|
115
145
|
stderr: "pipe",
|
|
@@ -145,13 +175,14 @@ test("dist binary completes a real MCP handshake over stdio and lists every tool
|
|
|
145
175
|
* answer a tool call with the actionable error — offline: the CredentialsError
|
|
146
176
|
* fires before any fetch, so this test never touches the network.
|
|
147
177
|
*/
|
|
148
|
-
test("dist binary starts without credentials: handshake, tool list, actionable call error", async () => {
|
|
178
|
+
test("dist binary starts without credentials: handshake, tool list, actionable call error", async (t) => {
|
|
149
179
|
const env = Object.fromEntries(
|
|
150
180
|
Object.entries(process.env).filter(
|
|
151
181
|
([key, value]) => value !== undefined && !key.startsWith("GOOGLE_SHEETS_"),
|
|
152
182
|
),
|
|
153
183
|
);
|
|
154
184
|
env.ASKADS_TELEMETRY = "0"; // keep the suite offline
|
|
185
|
+
env.XDG_CONFIG_HOME = isolatedConfigDir(t); // ignore any real login on this machine
|
|
155
186
|
const transport = new StdioClientTransport({
|
|
156
187
|
command: process.execPath,
|
|
157
188
|
args: [fileURLToPath(new URL("../dist/index.js", import.meta.url))],
|
|
@@ -163,7 +194,8 @@ test("dist binary starts without credentials: handshake, tool list, actionable c
|
|
|
163
194
|
try {
|
|
164
195
|
// The model must read the fix before it picks a tool.
|
|
165
196
|
const instructions = client.getInstructions() ?? "";
|
|
166
|
-
assert.match(instructions, /
|
|
197
|
+
assert.match(instructions, /NOT CONNECTED/);
|
|
198
|
+
assert.match(instructions, /start_login/);
|
|
167
199
|
assert.match(instructions, /GOOGLE_SHEETS_CLIENT_ID/);
|
|
168
200
|
assert.match(instructions, /restart/);
|
|
169
201
|
|
|
@@ -177,7 +209,8 @@ test("dist binary starts without credentials: handshake, tool list, actionable c
|
|
|
177
209
|
});
|
|
178
210
|
assert.equal(result.isError, true);
|
|
179
211
|
const text = result.content.map((c) => c.text ?? "").join(" ");
|
|
180
|
-
assert.match(text, /
|
|
212
|
+
assert.match(text, /not connected/i);
|
|
213
|
+
assert.match(text, /start_login/);
|
|
181
214
|
assert.match(text, /restart the server/);
|
|
182
215
|
} finally {
|
|
183
216
|
await client.close();
|