mcp-google-forms 1.1.0 → 1.3.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 CHANGED
@@ -3,15 +3,16 @@
3
3
  **English** | [Русский](./README.ru.md)
4
4
 
5
5
  [![npm](https://img.shields.io/npm/v/mcp-google-forms)](https://www.npmjs.com/package/mcp-google-forms)
6
- [![CI](https://github.com/A1-x-Tech/mcp-google-forms/actions/workflows/ci.yml/badge.svg)](https://github.com/A1-x-Tech/mcp-google-forms/actions/workflows/ci.yml)
7
6
  [![Glama](https://glama.ai/mcp/servers/A1-x-Tech/mcp-google-forms/badges/score.svg)](https://glama.ai/mcp/servers/A1-x-Tech/mcp-google-forms)
7
+ [![CI](https://github.com/A1-x-Tech/mcp-google-forms/actions/workflows/ci.yml/badge.svg)](https://github.com/A1-x-Tech/mcp-google-forms/actions/workflows/ci.yml)
8
8
  [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
9
9
 
10
10
  **A1 Google Forms MCP** lets an AI app build and manage Google Forms in plain language. Create a survey, choose its questions, publish it when ready, read answers and use notifications for new submissions.
11
11
 
12
12
  It uses the Google Forms API with your Google account. It distinguishes a draft form from a published form and makes the limits of the Forms API explicit instead of implying that every form task is possible.
13
13
 
14
- - **13 tools.** Inspect form structure and responses, create and edit forms and questions, manage publishing, and configure Pub/Sub watches.
14
+ - **19 tools.** Inspect form structure and responses, create and edit forms and questions, manage publishing, and configure Pub/Sub watches.
15
+ - **Connects from the conversation.** Say "connect Google Forms": 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
  - **Publish deliberately.** Forms made through the API start unpublished, so they cannot collect responses until you publish them.
16
17
  - **Responses stay intact.** The API can read responses but cannot create or edit them; the server has no tool that submits answers.
17
18
  - **Minimal Google scopes.** It uses `forms.body` and `forms.responses.readonly`, without broad Drive access.
@@ -52,10 +53,10 @@ Start with a read-only question:
52
53
 
53
54
  ## Quick start
54
55
 
55
- You need Node.js 20+, a Google account and OAuth credentials from a Google Cloud project with the Google Forms API enabled.
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. [Prepare Google OAuth access](#getting-access).
58
- 2. Add the server to your AI app.
58
+ 1. Add the server to your AI app.
59
+ 2. Say "connect Google Forms": 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 → Plugins → MCP servers**, select **Add server**, then add `npx -y mcp-google-forms@latest` with `GOOGLE_FORMS_CLIENT_ID`, `GOOGLE_FORMS_CLIENT_SECRET` and `GOOGLE_FORMS_REFRESH_TOKEN`.
67
+ **In the app:** open **Settings → MCP servers**, select **Add server**, choose **STDIO**, enter the command `npx -y mcp-google-forms@latest` and environment variables `GOOGLE_FORMS_CLIENT_ID`, `GOOGLE_FORMS_CLIENT_SECRET`, `GOOGLE_FORMS_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-forms \
72
- --env GOOGLE_FORMS_CLIENT_ID=your_client_id \
73
- --env GOOGLE_FORMS_CLIENT_SECRET=your_client_secret \
74
- --env GOOGLE_FORMS_REFRESH_TOKEN=your_refresh_token \
75
73
  -- npx -y mcp-google-forms@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_FORMS_CLIENT_ID=your_client_id \
94
- --env GOOGLE_FORMS_CLIENT_SECRET=your_client_secret \
95
- --env GOOGLE_FORMS_REFRESH_TOKEN=your_refresh_token \
96
91
  --transport stdio --scope user google-forms \
97
92
  -- npx -y mcp-google-forms@latest
98
93
  ```
@@ -110,25 +105,22 @@ claude mcp list
110
105
 
111
106
  <br>
112
107
 
113
- Open **Settings → Developer → Edit Config** and add:
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-forms": {
119
116
  "command": "npx",
120
- "args": ["-y", "mcp-google-forms@latest"],
121
- "env": {
122
- "GOOGLE_FORMS_CLIENT_ID": "your_client_id",
123
- "GOOGLE_FORMS_CLIENT_SECRET": "your_client_secret",
124
- "GOOGLE_FORMS_REFRESH_TOKEN": "your_refresh_token"
125
- }
117
+ "args": ["-y", "mcp-google-forms@latest"]
126
118
  }
127
119
  }
128
120
  }
129
121
  ```
130
122
 
131
- If **Edit Config** is unavailable, edit `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS or `%APPDATA%\Claude\claude_desktop_config.json` on Windows.
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-forms": {
148
140
  "type": "stdio",
149
141
  "command": "npx",
150
- "args": ["-y", "mcp-google-forms@latest"],
151
- "env": {
152
- "GOOGLE_FORMS_CLIENT_ID": "your_client_id",
153
- "GOOGLE_FORMS_CLIENT_SECRET": "your_client_secret",
154
- "GOOGLE_FORMS_REFRESH_TOKEN": "your_refresh_token"
155
- }
142
+ "args": ["-y", "mcp-google-forms@latest"]
156
143
  }
157
144
  }
158
145
  }
@@ -175,19 +162,9 @@ Run **MCP: Open User Configuration** and add:
175
162
  "google-forms": {
176
163
  "type": "stdio",
177
164
  "command": "npx",
178
- "args": ["-y", "mcp-google-forms@latest"],
179
- "env": {
180
- "GOOGLE_FORMS_CLIENT_ID": "${input:forms_client_id}",
181
- "GOOGLE_FORMS_CLIENT_SECRET": "${input:forms_client_secret}",
182
- "GOOGLE_FORMS_REFRESH_TOKEN": "${input:forms_refresh_token}"
183
- }
165
+ "args": ["-y", "mcp-google-forms@latest"]
184
166
  }
185
- },
186
- "inputs": [
187
- { "type": "promptString", "id": "forms_client_id", "description": "Google OAuth client ID" },
188
- { "type": "promptString", "id": "forms_client_secret", "description": "Google OAuth client secret", "password": true },
189
- { "type": "promptString", "id": "forms_refresh_token", "description": "Google OAuth refresh token", "password": true }
190
- ]
167
+ }
191
168
  }
192
169
  ```
193
170
 
@@ -243,7 +220,20 @@ The AI client controls confirmation prompts. The server marks reads, writes and
243
220
 
244
221
  ## Getting access
245
222
 
246
- Google Forms requires OAuth 2.0; an API key is not enough.
223
+ Google Forms requires OAuth 2.0; an API key is not enough. There are two ways in, and the first one needs no configuration files.
224
+
225
+ ### Connect from the chat (recommended)
226
+
227
+ Say "connect Google Forms" and the assistant runs the flow with you:
228
+
229
+ 1. `setup_instructions` prints the checklist: create or select a Google Cloud project, enable **Google Forms API**, configure the consent screen and create a **Desktop app** OAuth client.
230
+ 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.
231
+ 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.
232
+ 4. `finish_login` exchanges the code and saves the tokens to `~/.config/mcp-google-forms/credentials.json` (mode 0600).
233
+
234
+ 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.
235
+
236
+ ### Environment variables (CI, unattended installs)
247
237
 
248
238
  1. Create or select a Google Cloud project and enable **Google Forms API**.
249
239
  2. Configure the OAuth consent screen and create a **Desktop app** OAuth client.
@@ -259,12 +249,15 @@ Testing-mode OAuth refresh tokens can expire after seven days. Publish the OAuth
259
249
 
260
250
  ## Configuration
261
251
 
252
+ Every variable is optional — with none of them the server connects [from the chat](#connect-from-the-chat-recommended).
253
+
262
254
  | Variable | Required | Description |
263
255
  |---|---|---|
264
- | `GOOGLE_FORMS_CLIENT_ID` | Yes* | OAuth client ID. |
265
- | `GOOGLE_FORMS_CLIENT_SECRET` | Yes* | OAuth client secret. |
266
- | `GOOGLE_FORMS_REFRESH_TOKEN` | Yes* | OAuth refresh token. |
267
- | `GOOGLE_FORMS_ACCESS_TOKEN` | Yes* | Short-lived alternative to the OAuth trio. |
256
+ | `GOOGLE_FORMS_CLIENT_ID` | No* | OAuth client ID. |
257
+ | `GOOGLE_FORMS_CLIENT_SECRET` | No* | OAuth client secret. |
258
+ | `GOOGLE_FORMS_REFRESH_TOKEN` | No* | OAuth refresh token. |
259
+ | `GOOGLE_FORMS_ACCESS_TOKEN` | No* | Short-lived alternative to the OAuth trio. |
260
+ | `GOOGLE_FORMS_OAUTH_PORT` | No | Fixed loopback port for the in-chat login; useful over SSH port forwarding. |
268
261
  | `GOOGLE_FORMS_API_BASE` | No | Google Forms API base URL override. |
269
262
  | `GOOGLE_FORMS_TIMEOUT_MS` | No | Per-request timeout; default `60000` ms. |
270
263
  | `GOOGLE_FORMS_MAX_RETRIES` | No | Temporary-error retries; default `3`. |
@@ -273,7 +266,7 @@ Testing-mode OAuth refresh tokens can expire after seven days. Publish the OAuth
273
266
 
274
267
  ## Data, limits and background work
275
268
 
276
- - **Requests go to Google Forms.** The local server refreshes Google OAuth tokens and calls the Forms API. Its anonymous telemetry contains an installation ID, package version, AI client and platform versions, and tool names — never OAuth tokens, form data, tool arguments or prompts. Set `ASKADS_TELEMETRY=0` to opt out.
269
+ - **Requests go to Google Forms.** The local server refreshes Google OAuth tokens and calls the Forms API. Its anonymous telemetry contains an installation ID, package version, AI client and platform versions, and tool names — never OAuth tokens, form data, tool arguments or prompts. For each tool call it also sends the outcome and, on failure, an excerpt of the error text with e-mails, addresses, tokens, numbers of 4+ digits and quoted text replaced by `#`; a value from your request can appear in it if the error text contains it. Set `ASKADS_TELEMETRY=0` to opt out.
277
270
  - **Google applies per-minute quotas.** The documented limits are 975 reads per project, 450 `list_responses` calls and 375 writes. On `429`, the server uses backoff; reads also retry after network and `5xx` errors, while writes are not replayed after an uncertain failure.
278
271
  - **There is no background polling.** The server runs only when called. Pub/Sub watches can notify your own infrastructure about new responses; if your AI app supports scheduled tasks, it can also check responses periodically.
279
272
 
package/README.ru.md CHANGED
@@ -11,7 +11,8 @@
11
11
 
12
12
  Сервер работает с Google Forms API через ваш Google-аккаунт. Он отличает черновую форму от опубликованной и явно показывает ограничения API, а не создаёт впечатление, что через форму можно сделать всё.
13
13
 
14
- - **13 инструментов.** Проверка структуры формы и ответов, создание и редактирование форм и вопросов, управление публикацией и Pub/Sub watches.
14
+ - **19 инструментов.** Проверка структуры формы и ответов, создание и редактирование форм и вопросов, управление публикацией и Pub/Sub watches.
15
+ - **Подключение из диалога.** Скажите «подключи Google Формы»: сервер проведёт через создание OAuth-клиента, поймает редирект Google на `127.0.0.1` с PKCE и сам сохранит токены — без конфигов и перезапуска.
15
16
  - **Осознанная публикация.** Формы, созданные через API, по умолчанию не опубликованы и не принимают ответы, пока вы их не опубликуете.
16
17
  - **Ответы сохраняются как есть.** API умеет читать ответы, но не создавать и не редактировать их; инструмента отправки ответов у сервера нет.
17
18
  - **Минимальные scope Google.** Используются `forms.body` и `forms.responses.readonly` без широкого доступа к Drive.
@@ -52,10 +53,10 @@
52
53
 
53
54
  ## Быстрый старт
54
55
 
55
- Нужны Node.js 20+, Google-аккаунт и OAuth-данные из проекта Google Cloud с включённым Google Forms API.
56
+ Нужны Node.js 20+ и Google-аккаунт. Учётные данные при установке не нужны: сервер подключается прямо в диалоге.
56
57
 
57
- 1. [Подготовьте Google OAuth-доступ](#как-получить-доступ).
58
- 2. Добавьте сервер в AI-приложение.
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 → Plugins → MCP servers**, нажмите **Add server**, затем добавьте `npx -y mcp-google-forms@latest` с `GOOGLE_FORMS_CLIENT_ID`, `GOOGLE_FORMS_CLIENT_SECRET` и `GOOGLE_FORMS_REFRESH_TOKEN`.
67
+ **В приложении:** откройте **Settings → MCP servers**, нажмите **Add server**, выберите **STDIO**, укажите команду `npx -y mcp-google-forms@latest` и переменные окружения `GOOGLE_FORMS_CLIENT_ID`, `GOOGLE_FORMS_CLIENT_SECRET`, `GOOGLE_FORMS_REFRESH_TOKEN`, затем нажмите **Save**, потом **Restart**.
67
68
 
68
69
  **В командной строке:**
69
70
 
70
71
  ```bash
71
72
  codex mcp add google-forms \
72
- --env GOOGLE_FORMS_CLIENT_ID=your_client_id \
73
- --env GOOGLE_FORMS_CLIENT_SECRET=your_client_secret \
74
- --env GOOGLE_FORMS_REFRESH_TOKEN=your_refresh_token \
75
73
  -- npx -y mcp-google-forms@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_FORMS_CLIENT_ID=your_client_id \
94
- --env GOOGLE_FORMS_CLIENT_SECRET=your_client_secret \
95
- --env GOOGLE_FORMS_REFRESH_TOKEN=your_refresh_token \
96
91
  --transport stdio --scope user google-forms \
97
92
  -- npx -y mcp-google-forms@latest
98
93
  ```
@@ -110,25 +105,22 @@ claude mcp list
110
105
 
111
106
  <br>
112
107
 
113
- Откройте **Settings → Developer → Edit Config** и добавьте:
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-forms": {
119
116
  "command": "npx",
120
- "args": ["-y", "mcp-google-forms@latest"],
121
- "env": {
122
- "GOOGLE_FORMS_CLIENT_ID": "your_client_id",
123
- "GOOGLE_FORMS_CLIENT_SECRET": "your_client_secret",
124
- "GOOGLE_FORMS_REFRESH_TOKEN": "your_refresh_token"
125
- }
117
+ "args": ["-y", "mcp-google-forms@latest"]
126
118
  }
127
119
  }
128
120
  }
129
121
  ```
130
122
 
131
- Если **Edit Config** недоступна, отредактируйте `~/Library/Application Support/Claude/claude_desktop_config.json` на macOS или `%APPDATA%\Claude\claude_desktop_config.json` на Windows.
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-forms": {
148
140
  "type": "stdio",
149
141
  "command": "npx",
150
- "args": ["-y", "mcp-google-forms@latest"],
151
- "env": {
152
- "GOOGLE_FORMS_CLIENT_ID": "your_client_id",
153
- "GOOGLE_FORMS_CLIENT_SECRET": "your_client_secret",
154
- "GOOGLE_FORMS_REFRESH_TOKEN": "your_refresh_token"
155
- }
142
+ "args": ["-y", "mcp-google-forms@latest"]
156
143
  }
157
144
  }
158
145
  }
@@ -175,19 +162,9 @@ claude mcp list
175
162
  "google-forms": {
176
163
  "type": "stdio",
177
164
  "command": "npx",
178
- "args": ["-y", "mcp-google-forms@latest"],
179
- "env": {
180
- "GOOGLE_FORMS_CLIENT_ID": "${input:forms_client_id}",
181
- "GOOGLE_FORMS_CLIENT_SECRET": "${input:forms_client_secret}",
182
- "GOOGLE_FORMS_REFRESH_TOKEN": "${input:forms_refresh_token}"
183
- }
165
+ "args": ["-y", "mcp-google-forms@latest"]
184
166
  }
185
- },
186
- "inputs": [
187
- { "type": "promptString", "id": "forms_client_id", "description": "Google OAuth client ID" },
188
- { "type": "promptString", "id": "forms_client_secret", "description": "Google OAuth client secret", "password": true },
189
- { "type": "promptString", "id": "forms_refresh_token", "description": "Google OAuth refresh token", "password": true }
190
- ]
167
+ }
191
168
  }
192
169
  ```
193
170
 
@@ -243,7 +220,20 @@ claude mcp list
243
220
 
244
221
  ## Как получить доступ
245
222
 
246
- Google Forms требует OAuth 2.0: одного API-ключа недостаточно.
223
+ Google Forms требует OAuth 2.0: одного API-ключа недостаточно. Путей два, и первый не требует править конфигурационные файлы.
224
+
225
+ ### Подключение из диалога (рекомендуемый путь)
226
+
227
+ Скажите «подключи Google Формы», и ассистент пройдёт флоу вместе с вами:
228
+
229
+ 1. `setup_instructions` выдаёт чек-лист: создать или выбрать проект Google Cloud, включить **Google Forms API**, настроить consent screen и создать OAuth-клиент типа **Desktop app**.
230
+ 2. Скачайте JSON этого клиента («Download JSON») и передайте ассистенту **путь** к файлу — `set_client` сохранит его с правами только для владельца. Секрет через переписку не проходит.
231
+ 3. `start_login` возвращает ссылку на согласие Google. Откройте её **на этой же машине** и подтвердите доступ: код возвращается на одноразовый слушатель `127.0.0.1` (PKCE), а не в чат.
232
+ 4. `finish_login` меняет код на токены и кладёт их в `~/.config/mcp-google-forms/credentials.json` (права 0600).
233
+
234
+ Токены перечитываются на каждый вызов, поэтому подключение действует немедленно — перезапускать AI-приложение не нужно. `auth_status` показывает состояние, `logout` отзывает токен и удаляет его.
235
+
236
+ ### Переменные окружения (CI и автоматические установки)
247
237
 
248
238
  1. Создайте или выберите проект Google Cloud и включите **Google Forms API**.
249
239
  2. Настройте OAuth consent screen и создайте OAuth-клиент типа **Desktop app**.
@@ -259,12 +249,15 @@ Refresh token OAuth-приложения в режиме Testing может ис
259
249
 
260
250
  ## Конфигурация
261
251
 
252
+ Все переменные необязательные — без единой из них сервер подключается [из диалога](#подключение-из-диалога-рекомендуемый-путь).
253
+
262
254
  | Переменная | Обязательна | Описание |
263
255
  |---|---|---|
264
- | `GOOGLE_FORMS_CLIENT_ID` | Да* | OAuth client ID. |
265
- | `GOOGLE_FORMS_CLIENT_SECRET` | Да* | OAuth client secret. |
266
- | `GOOGLE_FORMS_REFRESH_TOKEN` | Да* | OAuth refresh token. |
267
- | `GOOGLE_FORMS_ACCESS_TOKEN` | Да* | Короткоживущая альтернатива OAuth-тройке. |
256
+ | `GOOGLE_FORMS_CLIENT_ID` | Нет* | OAuth client ID. |
257
+ | `GOOGLE_FORMS_CLIENT_SECRET` | Нет* | OAuth client secret. |
258
+ | `GOOGLE_FORMS_REFRESH_TOKEN` | Нет* | OAuth refresh token. |
259
+ | `GOOGLE_FORMS_ACCESS_TOKEN` | Нет* | Короткоживущая альтернатива OAuth-тройке. |
260
+ | `GOOGLE_FORMS_OAUTH_PORT` | Нет | Фиксированный порт loopback-слушателя для входа из диалога; нужен при пробросе портов по SSH. |
268
261
  | `GOOGLE_FORMS_API_BASE` | Нет | Переопределяет базовый URL Google Forms API. |
269
262
  | `GOOGLE_FORMS_TIMEOUT_MS` | Нет | Тайм-аут одного запроса; по умолчанию `60000` мс. |
270
263
  | `GOOGLE_FORMS_MAX_RETRIES` | Нет | Повторы временных ошибок; по умолчанию `3`. |
@@ -273,7 +266,7 @@ Refresh token OAuth-приложения в режиме Testing может ис
273
266
 
274
267
  ## Данные, лимиты и работа в фоне
275
268
 
276
- - **Запросы идут в Google Forms.** Локальный сервер обновляет OAuth-токены Google и вызывает Forms API. Анонимная телеметрия содержит ID установки, версию пакета, версии AI-клиента и платформы и имена инструментов — но не OAuth-токены, данные формы, аргументы или промпты. Чтобы отключить её, задайте `ASKADS_TELEMETRY=0`.
269
+ - **Запросы идут в Google Forms.** Локальный сервер обновляет OAuth-токены Google и вызывает Forms API. Анонимная телеметрия содержит ID установки, версию пакета, версии AI-клиента и платформы и имена инструментов — но не OAuth-токены, данные формы, аргументы или промпты. При вызове инструмента сервер также отправляет его исход, а при ошибке - фрагмент её текста: код и сообщение, в которых e-mail, адреса, токены, числа от 4 цифр и текст в кавычках заменены на «#». Если в тексте ошибки есть значение из запроса, оно тоже может попасть во фрагмент. Чтобы отключить её, задайте `ASKADS_TELEMETRY=0`.
277
270
  - **У Google есть поминутные квоты.** Документированные лимиты: 975 чтений на проект, 450 вызовов `list_responses` и 375 записей. При `429` сервер использует задержку; чтение также повторяется после сетевых и `5xx` ошибок, а запись после неопределённой ошибки не повторяется.
278
271
  - **Постоянного опроса нет.** Сервер работает только при вызове. Pub/Sub watch может уведомить вашу инфраструктуру о новых ответах; если AI-приложение поддерживает задания по расписанию, оно также может периодически проверять ответы.
279
272
 
package/dist/client.js CHANGED
@@ -68,6 +68,7 @@ function buildQuestion(p) {
68
68
  }
69
69
  export class GoogleFormsClient {
70
70
  config;
71
+ tokenProvider;
71
72
  base;
72
73
  timeoutMs;
73
74
  maxRetries;
@@ -76,8 +77,16 @@ export class GoogleFormsClient {
76
77
  cachedToken;
77
78
  /** In-flight refresh, deduping concurrent token requests. */
78
79
  refreshInFlight;
79
- constructor(config) {
80
+ constructor(config,
81
+ /**
82
+ * Fallback token source (the in-chat login of @a1-x-tech/mcp-google-auth).
83
+ * Consulted only when the env-derived config carries no credentials —
84
+ * env wins (component invariant 3), so existing refresh-triple and
85
+ * access-token installs behave exactly as before.
86
+ */
87
+ tokenProvider) {
80
88
  this.config = config;
89
+ this.tokenProvider = tokenProvider;
81
90
  this.base = config.apiBase.endsWith("/") ? config.apiBase : config.apiBase + "/";
82
91
  this.timeoutMs = config.timeoutMs ?? 60_000;
83
92
  this.maxRetries = config.maxRetries ?? 3;
@@ -86,6 +95,19 @@ export class GoogleFormsClient {
86
95
  canRefresh() {
87
96
  return Boolean(this.config.refreshToken && this.config.clientId && this.config.clientSecret);
88
97
  }
98
+ /**
99
+ * Whether a 401 is worth one re-mint + replay: either the env config can mint
100
+ * from its refresh triple, or the provider holds a refresh token (env or
101
+ * stored login). A static env access token can never be re-minted, so a 401
102
+ * there is final — replaying it would just burn a second request.
103
+ */
104
+ canReplayOn401() {
105
+ if (this.canRefresh())
106
+ return true;
107
+ if (this.config.accessToken)
108
+ return false;
109
+ return this.tokenProvider?.canRefresh() ?? false;
110
+ }
89
111
  /**
90
112
  * Returns a valid Bearer token. With the refresh triple configured, mints an
91
113
  * access token from the refresh token and caches it until shortly before it
@@ -97,9 +119,13 @@ export class GoogleFormsClient {
97
119
  */
98
120
  async accessToken(forceRefresh = false) {
99
121
  if (!this.canRefresh()) {
100
- if (!this.config.accessToken)
101
- throw new CredentialsError();
102
- return this.config.accessToken;
122
+ // Env wins over the provider (component invariant 3): a static
123
+ // GOOGLE_FORMS_ACCESS_TOKEN keeps behaving exactly as before.
124
+ if (this.config.accessToken)
125
+ return this.config.accessToken;
126
+ if (this.tokenProvider)
127
+ return this.tokenProvider.getAccessToken(forceRefresh);
128
+ throw new CredentialsError();
103
129
  }
104
130
  if (!forceRefresh && this.cachedToken && Date.now() < this.cachedToken.expiresAt) {
105
131
  return this.cachedToken.value;
@@ -226,7 +252,7 @@ export class GoogleFormsClient {
226
252
  }
227
253
  // An expired/revoked access token: re-mint once and replay. The request
228
254
  // never executed, so this is safe for writes too.
229
- if (res.status === 401 && this.canRefresh() && !refreshedOn401) {
255
+ if (res.status === 401 && this.canReplayOn401() && !refreshedOn401) {
230
256
  refreshedOn401 = true;
231
257
  await this.accessToken(true);
232
258
  continue;
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ import { registerItemTools } from "./tools/items.js";
10
10
  import { registerResponseTools } from "./tools/responses.js";
11
11
  import { registerWatchTools } from "./tools/watches.js";
12
12
  import { registerRawTool } from "./tools/raw.js";
13
+ import { authUnconfiguredPrefix, hasAuthToken, registerAuthTools } from "./tools/auth.js";
13
14
  /**
14
15
  * Prose handed to the calling model in the `initialize` result — the only place
15
16
  * it learns what the tool list cannot say: which Google product this API is,
@@ -36,11 +37,6 @@ const INSTRUCTIONS = "Google Forms API v1 builds and reads Google Forms — not
36
37
  * rather than with a failed call. There is no in-chat login here: credentials
37
38
  * come only from the environment, so the fix is an operator action + restart.
38
39
  */
39
- const UNCONFIGURED_PREFIX = "ATTENTION: Google Forms is not connected yet — no credentials are configured, so every " +
40
- "tool call will fail. The operator must set GOOGLE_FORMS_CLIENT_ID + " +
41
- "GOOGLE_FORMS_CLIENT_SECRET + GOOGLE_FORMS_REFRESH_TOKEN (recommended), or " +
42
- "GOOGLE_FORMS_ACCESS_TOKEN with a short-lived access token, in the MCP client's " +
43
- "server config and restart this server — the variables are read only at startup. ";
44
40
  /** Reads the package version so the server reports its real version to MCP clients. */
45
41
  function readVersion() {
46
42
  try {
@@ -81,10 +77,9 @@ async function main() {
81
77
  // credentials can be reported; wired to the server before tools register.
82
78
  const telemetry = new Telemetry(readVersion());
83
79
  const { config, problem } = loadConfigOrDegraded(telemetry);
84
- const client = new GoogleFormsClient(config);
85
80
  // Decided once, at startup: credentials come only from the environment, so
86
81
  // "restart after setting the variables" is the accurate advice to give.
87
- const connected = hasCredentials(config);
82
+ const connected = hasCredentials(config) || hasAuthToken();
88
83
  const server = new McpServer({
89
84
  name: "mcp-google-forms",
90
85
  version: readVersion(),
@@ -93,7 +88,7 @@ async function main() {
93
88
  {
94
89
  instructions: connected
95
90
  ? INSTRUCTIONS
96
- : UNCONFIGURED_PREFIX + (problem ? `Configuration problem: ${problem.message} ` : "") + INSTRUCTIONS,
91
+ : authUnconfiguredPrefix() + (problem ? `Configuration problem: ${problem.message} ` : "") + INSTRUCTIONS,
97
92
  });
98
93
  instrumentToolCalls(server, telemetry);
99
94
  server.server.oninitialized = () => {
@@ -105,6 +100,11 @@ async function main() {
105
100
  else
106
101
  telemetry.send("unconfigured_start", { reason: problem?.reason ?? "missing_credentials" });
107
102
  };
103
+ // The auth tools come first so their TokenProvider exists before the client:
104
+ // the client falls back to it whenever the environment carries no
105
+ // credentials (env always wins — component invariant 3).
106
+ const tokenProvider = registerAuthTools(server);
107
+ const client = new GoogleFormsClient(config, tokenProvider);
108
108
  registerFormTools(server, client);
109
109
  registerItemTools(server, client);
110
110
  registerResponseTools(server, client);
package/dist/telemetry.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * Anonymous usage telemetry — fire-and-forget pings to usage.gistrec.cloud.
3
3
  *
4
4
  * Privacy contract (mirrored by the receiver): only an anonymous random
5
- * instance id, event/tool names, a fixed-vocabulary failure reason and
5
+ * instance id, event/tool names, a fixed-vocabulary failure reason or tool outcome and
6
6
  * environment versions ever leave the machine. The OAuth credentials, form
7
7
  * data, tool arguments, prompts and the names or values of environment
8
8
  * variables are never read, serialized or sent. Sends are capped at 2 s and
@@ -64,6 +64,10 @@ export class Telemetry {
64
64
  setClientInfo(info) {
65
65
  this.clientInfo = info;
66
66
  }
67
+ /** Whether pings go out at all (ASKADS_TELEMETRY opt-out). */
68
+ isEnabled() {
69
+ return this.enabled;
70
+ }
67
71
  /** Fire-and-forget: the server's own work never waits on a ping. */
68
72
  send(event, fields = {}) {
69
73
  void this.post(event, fields);
@@ -87,7 +91,8 @@ export class Telemetry {
87
91
  client_name: this.clientInfo?.name,
88
92
  client_version: this.clientInfo?.version,
89
93
  tool: fields.tool,
90
- reason: fields.reason,
94
+ reason: wireReason(event, fields.reason),
95
+ error_detail: event === "tool_call" ? fields.error_detail : undefined,
91
96
  node_version: process.version,
92
97
  os: process.platform,
93
98
  });
@@ -104,17 +109,221 @@ export class Telemetry {
104
109
  }
105
110
  }
106
111
  }
112
+ /** How a tool call ended; only these constants leave the machine. */
113
+ export const TOOL_OUTCOMES = [
114
+ "ok",
115
+ "error_auth",
116
+ "error_permission",
117
+ "error_not_found",
118
+ "error_rate_limit",
119
+ "error_invalid_request",
120
+ "error_upstream",
121
+ "error_timeout",
122
+ "error_network",
123
+ "error_internal",
124
+ "error_other",
125
+ ];
126
+ /** Drops a tool_call reason that is not in TOOL_OUTCOMES. */
127
+ function wireReason(event, reason) {
128
+ if (event !== "tool_call" || reason === undefined)
129
+ return reason;
130
+ return TOOL_OUTCOMES.includes(reason) ? reason : undefined;
131
+ }
132
+ // First match wins. Direct answers "no access to this client" with auth code 53, so that
133
+ // permission line goes before auth.
134
+ const OUTCOME_PATTERNS = [
135
+ ["error_timeout", /timed?[ _-]?out|таймаут|ETIMEDOUT|AbortError|не был готов|not ready/i],
136
+ ["error_network", /ECONNRESET|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EPIPE|fetch failed|socket hang up/i],
137
+ ["error_rate_limit", /\b429\b|rate[ _-]?limit|too many requests|quota|квот|лимит|\[(?:56|152|506|9000)\]/i],
138
+ ["error_permission", /нет доступа к кабинету|не подключ[её]н к аккаунту/i],
139
+ [
140
+ "error_auth",
141
+ /\b401\b|unauthori[sz]ed|unauthenticated|invalid[ _-]?(?:token|grant|credentials)|token (?:expired|revoked)|login required|AuthRequired|авториз|не подключ|\[53\]/i,
142
+ ],
143
+ ["error_permission", /\b403\b|forbidden|access[ _-]?denied|permission|insufficient[ _-]?scope|нет доступа|\[(?:54|3228)\]/i],
144
+ ["error_not_found", /\b404\b|not[ _-]?found|не найден|не существует|\[8800\]/i],
145
+ ["error_upstream", /\b5\d\d\b|\b204\b|unavailable|недоступ|internal server error|bad gateway|\[(?:52|1000|1001|1002)\]/i],
146
+ ["error_invalid_request", /\b400\b|\b422\b|bad request|invalid|syntax|некоррект|неверн|недопустим|required|обязател|expected|must (?:be|contain|have)|\[(?:4000|4001|4003|5000|8000)\]/i],
147
+ ];
148
+ // An API code at the head of the message wins over the text, which may quote field names
149
+ // ("ForbiddenPlatform" in a [8000] list of allowed values). 53 is absent: the text tells a
150
+ // dead token from no access to a client.
151
+ const CODE_OUTCOMES = new Map([
152
+ ...["56", "152", "506", "9000"].map((c) => [c, "error_rate_limit"]),
153
+ ...["54", "3228"].map((c) => [c, "error_permission"]),
154
+ ["8800", "error_not_found"],
155
+ ...["52", "1000", "1001", "1002"].map((c) => [c, "error_upstream"]),
156
+ ...["4000", "4001", "4003", "5000", "8000"].map((c) => [c, "error_invalid_request"]),
157
+ ]);
158
+ const LEADING_CODE = /^[^[\n]{0,60}\[(\d{1,5})\]/;
159
+ // Inputs are cut before any regex runs: a long argument echoed in an error must not stall the call.
160
+ const TEXT_MAX = 4000;
161
+ function resultText(value) {
162
+ if (value instanceof Error)
163
+ return `${value.name} ${value.message}`.slice(0, TEXT_MAX);
164
+ const content = value?.content;
165
+ if (!Array.isArray(content))
166
+ return "";
167
+ return content
168
+ .map((part) => (part && typeof part === "object" && typeof part.text === "string" ? part.text : ""))
169
+ .join("\n")
170
+ .slice(0, TEXT_MAX);
171
+ }
172
+ /** `toolOutcome(result)` for a returned result, `toolOutcome(undefined, error)` for a thrown one. */
173
+ export function toolOutcome(result, ...thrown) {
174
+ const didThrow = thrown.length > 0;
175
+ if (!didThrow && !result?.isError)
176
+ return "ok";
177
+ const text = resultText(didThrow ? thrown[0] : result);
178
+ const byCode = CODE_OUTCOMES.get(LEADING_CODE.exec(text)?.[1] ?? "");
179
+ if (byCode)
180
+ return byCode;
181
+ for (const [outcome, pattern] of OUTCOME_PATTERNS)
182
+ if (pattern.test(text))
183
+ return outcome;
184
+ return didThrow ? "error_internal" : "error_other";
185
+ }
186
+ /** Error excerpt: allowlisted fragments of the error text, masked (port of the Ask Ads gateway's). */
187
+ export const DETAIL_MAX = 200;
188
+ const PICK = /\bHTTP (?<http>\d{3})\b(?::\s*(?<htext>[^{[]{1,200}))?|^(?:Ошибка: )?\[(?<bcode>\d{1,5})\]\s*(?<btext>[^;(]{1,200})|\[(?<tag>[A-Za-z][A-Za-z_]{2,})\]\s*(?<ttext>[^;(]{0,200})|\berror_code["']?\s*[:=]\s*["']?(?<code>\d{1,5})\b|\b(?<key>error_string|error_detail|error_type|message)["']?\s*[:=]\s*["']?(?<value>[^"'}\]]{1,80})|\b(?<net>ECONNRESET|ECONNREFUSED|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|timed out|fetch failed|socket hang up|connection closed)\b|(?<netru>превысил таймаут)/gi;
189
+ const SCRUB = /(?<key>(?:login|password|secret|token|api[_-]?key|authorization)\s*[:=]\s*["']?|(?:bearer|basic)\s+)(?<val>[^,;]+)|[^\s,;]*(?:@|:\/\/|%3A|\p{L}\.\p{L})[^\s,;]*|(?<key2>\b(?:token|secret|password|api[_-]?key|access_token|refresh_token|client_secret)\s+)(?!(?:expired|invalid|is|was|for|has|not|missing|required|revoked|provided|type)\b)\S+|\b(?:y0_|AQAA|AQVN|t1\.|sk-|vk1\.|vk_|ghp_|ya29\.)\S+|\b(?=[\w-]*\d)(?=[\w-]*[A-Za-z])[\w-]{20,}\b|\+?\d(?:[\s().-]*\d){3,}/giu;
190
+ const QUOTED = /(?<!\p{L})'[^'\n]+(?:'(?!\p{L})|$)|"[^"\n]+(?:"|$)|«[^»]+(?:»|$)/gu;
191
+ function scrub(value, quoted = true) {
192
+ return (quoted ? value.replace(QUOTED, "#") : value)
193
+ .replace(SCRUB, (...args) => {
194
+ const groups = args[args.length - 1];
195
+ return (groups.key ?? groups.key2 ?? "") + "#";
196
+ })
197
+ .replace(/^[ ;:,.]+|[ ;:,.]+$/g, "");
198
+ }
199
+ export function errorDetail(text) {
200
+ const flat = text.slice(0, 2000).split(/\s+/).filter(Boolean).join(" ");
201
+ const parts = [];
202
+ PICK.lastIndex = 0;
203
+ for (let m = PICK.exec(flat); m; m = PICK.exec(flat)) {
204
+ const g = m.groups ?? {};
205
+ let token;
206
+ if (g.http)
207
+ token = `HTTP ${g.http} ${scrub(g.htext ?? "")}`;
208
+ else if (g.bcode)
209
+ token = `code=${g.bcode} ${scrub(g.btext ?? "")}`;
210
+ else if (g.tag) {
211
+ // Tags are upper-case only; the rest of PICK is case-insensitive.
212
+ if (!/^[A-Z][A-Z_]{2,}$/.test(g.tag)) {
213
+ PICK.lastIndex = m.index + 1;
214
+ continue;
215
+ }
216
+ token = `${g.tag} ${scrub(g.ttext ?? "")}`;
217
+ }
218
+ else if (g.code)
219
+ token = `code=${g.code}`;
220
+ else if (g.key)
221
+ token = `${g.key.toLowerCase()}=${scrub(g.value ?? "")}`;
222
+ else
223
+ token = (g.net ?? g.netru ?? "").toLowerCase();
224
+ token = token.trim();
225
+ if (!parts.includes(token))
226
+ parts.push(token);
227
+ }
228
+ return parts.join("; ").slice(0, DETAIL_MAX);
229
+ }
230
+ /** Set by fail(), never serialized: our own refusal ("local"), a bug in our code ("internal") or a failed fetch ("network"). */
231
+ const FAILURE_ORIGIN = new WeakMap();
232
+ const JS_ERRORS = new Set(["TypeError", "ReferenceError", "RangeError", "SyntaxError", "EvalError", "URIError"]);
233
+ function jsBug(err) {
234
+ return err instanceof Error && JS_ERRORS.has(err.name) ? `${err.name}: ${err.message.split("\n")[0]}` : undefined;
235
+ }
236
+ /**
237
+ * Node's fetch rejects a network failure as TypeError("fetch failed") with the socket/DNS/TLS error
238
+ * in `cause`. Only cause.code leaves the machine: cause.message names hosts and addresses.
239
+ */
240
+ function fetchFailure(err) {
241
+ if (!(err instanceof Error) || err.name !== "TypeError" || err.message !== "fetch failed")
242
+ return undefined;
243
+ const cause = err.cause;
244
+ if (!cause || typeof cause !== "object")
245
+ return undefined;
246
+ const raw = cause.code;
247
+ const code = typeof raw === "string" && /^[A-Z][A-Z0-9_]{2,40}$/.test(raw) ? raw : "";
248
+ return {
249
+ reason: /TIMEOUT|TIMEDOUT/.test(code) ? "error_timeout" : "error_network",
250
+ text: code ? `fetch failed; ${code.toLowerCase()}` : "fetch failed",
251
+ };
252
+ }
253
+ export function noteFailure(result, err) {
254
+ try {
255
+ if (result && typeof result === "object") {
256
+ const net = fetchFailure(err);
257
+ if (typeof err === "string")
258
+ FAILURE_ORIGIN.set(result, { origin: "local", text: err });
259
+ else if (net)
260
+ FAILURE_ORIGIN.set(result, { origin: "network", ...net });
261
+ else {
262
+ const bug = jsBug(err);
263
+ if (bug)
264
+ FAILURE_ORIGIN.set(result, { origin: "internal", text: bug });
265
+ }
266
+ }
267
+ }
268
+ catch {
269
+ // never affects the result
270
+ }
271
+ return result;
272
+ }
273
+ /** A JS error quotes identifiers of our code, not user data, so its quotes are kept. */
274
+ function maskedOwnText(prefix, text, quoted = true) {
275
+ return (prefix + scrub(text.slice(0, 2 * DETAIL_MAX).split(/\s+/).filter(Boolean).join(" "), quoted)).slice(0, DETAIL_MAX);
276
+ }
277
+ /** Best effort: classifying or sending must never change what the tool returns or throws. */
278
+ function reportCall(telemetry, tool, value, thrown) {
279
+ if (!telemetry.isEnabled())
280
+ return;
281
+ try {
282
+ let reason = thrown ? toolOutcome(undefined, value) : toolOutcome(value);
283
+ let detail = "";
284
+ if (reason !== "ok") {
285
+ const noted = value && typeof value === "object" ? FAILURE_ORIGIN.get(value) : undefined;
286
+ const net = noted?.origin === "network" ? noted : thrown ? fetchFailure(value) : undefined;
287
+ const bug = noted?.origin === "internal" ? noted.text : thrown ? jsBug(value) : undefined;
288
+ if (net) {
289
+ reason = net.reason;
290
+ detail = net.text;
291
+ }
292
+ else if (bug) {
293
+ reason = "error_internal";
294
+ detail = maskedOwnText("internal: ", bug, false);
295
+ }
296
+ else if (noted?.origin === "local") {
297
+ reason = "error_invalid_request";
298
+ detail = maskedOwnText("local: ", noted.text);
299
+ }
300
+ else
301
+ detail = errorDetail(resultText(value));
302
+ }
303
+ telemetry.send("tool_call", { tool, reason, error_detail: detail || undefined });
304
+ }
305
+ catch {
306
+ // never affects the call
307
+ }
308
+ }
107
309
  /**
108
- * Count every tool invocation by name. Wraps registerTool once, before the
109
- * domain modules register their tools, so no per-tool wiring is needed.
110
- * Only the tool *name* is recorded — arguments never reach telemetry.
310
+ * Counts every tool call by name and outcome. Wraps registerTool once, before the domain
311
+ * modules register their tools. Calls rejected by SDK input validation are not counted.
111
312
  */
112
313
  export function instrumentToolCalls(server, telemetry) {
113
314
  const original = server.registerTool.bind(server);
114
315
  // registerTool's generic signature does not survive a wrapper; the runtime
115
316
  // shape (name, config, callback) is stable per SDK contract.
116
- server.registerTool = ((name, config, callback) => original(name, config, ((...args) => {
117
- telemetry.send("tool_call", { tool: name });
118
- return callback(...args);
317
+ server.registerTool = ((name, config, callback) => original(name, config, (async (...args) => {
318
+ let result;
319
+ try {
320
+ result = await callback(...args);
321
+ }
322
+ catch (e) {
323
+ reportCall(telemetry, name, e, true);
324
+ throw e;
325
+ }
326
+ reportCall(telemetry, name, result, false);
327
+ return result;
119
328
  })));
120
329
  }
@@ -0,0 +1,39 @@
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/forms.body",
8
+ "https://www.googleapis.com/auth/forms.responses.readonly",
9
+ ];
10
+ /**
11
+ * The single source of the auth wiring: serverName "forms" puts the stored
12
+ * login in ~/.config/mcp-google-forms/credentials.json (the component
13
+ * prefixes "mcp-google-"), envPrefix keeps the provider reading the exact
14
+ * GOOGLE_FORMS_* variables config.ts documents — which is what preserves the
15
+ * env-beats-stored priority for existing installs.
16
+ */
17
+ export const AUTH_OPTIONS = {
18
+ serverName: "forms",
19
+ envPrefix: "GOOGLE_FORMS",
20
+ scopes: LOGIN_SCOPES,
21
+ };
22
+ /**
23
+ * Registers the six onboarding tools (auth_status, setup_instructions,
24
+ * set_client, start_login, finish_login, logout) and returns the TokenProvider
25
+ * the client plugs in as its fallback token source — the same instance, so a
26
+ * login finished mid-session is visible to the very next API call without a
27
+ * restart.
28
+ */
29
+ export function registerAuthTools(server) {
30
+ return registerGoogleAuth(server, AUTH_OPTIONS);
31
+ }
32
+ /** True when any token exists — env variables or a stored in-chat login. */
33
+ export function hasAuthToken() {
34
+ return new TokenProvider(AUTH_OPTIONS).hasToken();
35
+ }
36
+ /** The "NOT CONNECTED" prefix for the initialize instructions (names both fixes). */
37
+ export function authUnconfiguredPrefix() {
38
+ return unconfiguredPrefix(AUTH_OPTIONS);
39
+ }
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { noteFailure } from "../telemetry.js";
2
3
  /**
3
4
  * Schema factories, not shared consts: reusing one zod object across two fields
4
5
  * makes zod-to-json-schema dedupe them into a `$ref`, which some tool-schema
@@ -20,7 +21,11 @@ export function ok(data) {
20
21
  const text = typeof data === "string" ? data : JSON.stringify(data);
21
22
  return { content: [{ type: "text", text: text ?? "null" }] };
22
23
  }
24
+ /** The failed result; also notes, off the wire, whether it is our own refusal or a JS bug (telemetry). */
23
25
  export function fail(err) {
26
+ return noteFailure(failText(err), err);
27
+ }
28
+ function failText(err) {
24
29
  let message = err instanceof Error ? err.message : String(err);
25
30
  // Surface the underlying cause (e.g. the network error behind a timeout) — no
26
31
  // secrets live in cause, and it makes failures far easier to diagnose.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-google-forms",
3
- "version": "1.1.0",
3
+ "version": "1.3.0",
4
4
  "description": "MCP server for the Google Forms API — create forms, manage questions, publish, read responses and watch for new submissions. For Claude, Cursor, Codex and other AI clients.",
5
5
  "mcpName": "io.github.A1-x-Tech/mcp-google-forms",
6
6
  "type": "module",
@@ -49,6 +49,7 @@
49
49
  "url": "https://github.com/A1-x-Tech/mcp-google-forms/issues"
50
50
  },
51
51
  "dependencies": {
52
+ "@a1-x-tech/mcp-google-auth": "^0.1.0",
52
53
  "@modelcontextprotocol/sdk": "^1.29.0",
53
54
  "zod": "^3.25.0"
54
55
  },
@@ -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
 
@@ -11,23 +14,48 @@ import { registerItemTools } from "../dist/tools/items.js";
11
14
  import { registerResponseTools } from "../dist/tools/responses.js";
12
15
  import { registerWatchTools } from "../dist/tools/watches.js";
13
16
  import { registerRawTool } from "../dist/tools/raw.js";
17
+ import { registerAuthTools } from "../dist/tools/auth.js";
14
18
 
19
+ /**
20
+ * Sorted, because every assertion compares it against a sorted tool list. The
21
+ * six onboarding tools come from @a1-x-tech/mcp-google-auth, so this list is
22
+ * also the check that the component is wired into the published binary.
23
+ */
15
24
  const ALL_TOOLS = [
16
25
  "add_question",
26
+ "auth_status",
17
27
  "create_form",
18
28
  "delete_item",
29
+ "finish_login",
19
30
  "get_form",
20
31
  "get_response",
21
32
  "list_responses",
33
+ "logout",
22
34
  "manage_watches",
23
35
  "move_item",
24
36
  "raw_request",
37
+ "set_client",
25
38
  "set_publish_settings",
39
+ "setup_instructions",
40
+ "start_login",
26
41
  "update_form_info",
27
42
  "update_form_settings",
28
43
  "update_question",
29
44
  ];
30
45
 
46
+ /**
47
+ * A throwaway $XDG_CONFIG_HOME for the spawned server. The auth component
48
+ * re-reads $XDG_CONFIG_HOME/mcp-google-forms/credentials.json per call, so
49
+ * without this a real login on the developer's machine would make the
50
+ * "unconfigured" case pass for the wrong reason.
51
+ */
52
+ function isolatedConfigDir(t) {
53
+ const dir = mkdtempSync(join(tmpdir(), "mcp-forms-dist-smoke-"));
54
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
55
+ return dir;
56
+ }
57
+
58
+
31
59
  test("dist client rejects foreign-origin paths before sending the Bearer token", async () => {
32
60
  const original = globalThis.fetch;
33
61
  let called = false;
@@ -81,6 +109,7 @@ test("dist registers the expected tools", () => {
81
109
  };
82
110
  const client = {};
83
111
 
112
+ registerAuthTools(server, client);
84
113
  registerFormTools(server, client);
85
114
  registerItemTools(server, client);
86
115
  registerResponseTools(server, client);
@@ -90,13 +119,14 @@ test("dist registers the expected tools", () => {
90
119
  assert.deepEqual(names.sort(), ALL_TOOLS);
91
120
  });
92
121
 
93
- test("dist binary completes a real MCP handshake over stdio and lists every tool", async () => {
122
+ test("dist binary completes a real MCP handshake over stdio and lists every tool", async (t) => {
94
123
  const transport = new StdioClientTransport({
95
124
  command: process.execPath,
96
125
  args: [fileURLToPath(new URL("../dist/index.js", import.meta.url))],
97
126
  env: {
98
127
  ...process.env,
99
128
  GOOGLE_FORMS_ACCESS_TOKEN: "test-token",
129
+ XDG_CONFIG_HOME: isolatedConfigDir(t),
100
130
  ASKADS_TELEMETRY: "0", // keep the suite offline
101
131
  },
102
132
  stderr: "pipe",
@@ -132,13 +162,14 @@ test("dist binary completes a real MCP handshake over stdio and lists every tool
132
162
  * answer a tool call with the actionable error — offline: the CredentialsError
133
163
  * fires before any fetch, so this test never touches the network.
134
164
  */
135
- test("dist binary starts without credentials: handshake, tool list, actionable call error", async () => {
165
+ test("dist binary starts without credentials: handshake, tool list, actionable call error", async (t) => {
136
166
  const env = Object.fromEntries(
137
167
  Object.entries(process.env).filter(
138
168
  ([key, value]) => value !== undefined && !key.startsWith("GOOGLE_FORMS_"),
139
169
  ),
140
170
  );
141
171
  env.ASKADS_TELEMETRY = "0"; // keep the suite offline
172
+ env.XDG_CONFIG_HOME = isolatedConfigDir(t); // ignore any real login on this machine
142
173
  const transport = new StdioClientTransport({
143
174
  command: process.execPath,
144
175
  args: [fileURLToPath(new URL("../dist/index.js", import.meta.url))],
@@ -150,7 +181,8 @@ test("dist binary starts without credentials: handshake, tool list, actionable c
150
181
  try {
151
182
  // The model must read the fix before it picks a tool.
152
183
  const instructions = client.getInstructions() ?? "";
153
- assert.match(instructions, /not connected/);
184
+ assert.match(instructions, /NOT CONNECTED/);
185
+ assert.match(instructions, /start_login/);
154
186
  assert.match(instructions, /GOOGLE_FORMS_CLIENT_ID/);
155
187
  assert.match(instructions, /restart/);
156
188
 
@@ -161,7 +193,8 @@ test("dist binary starts without credentials: handshake, tool list, actionable c
161
193
  const result = await client.callTool({ name: "get_form", arguments: { form_id: "smoke-form" } });
162
194
  assert.equal(result.isError, true);
163
195
  const text = result.content.map((c) => c.text ?? "").join(" ");
164
- assert.match(text, /Google OAuth credentials are required: set GOOGLE_FORMS_CLIENT_ID/);
196
+ assert.match(text, /not connected/i);
197
+ assert.match(text, /start_login/);
165
198
  assert.match(text, /restart the server/);
166
199
  } finally {
167
200
  await client.close();