mcp-google-forms 1.0.0 → 1.2.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.ru.md ADDED
@@ -0,0 +1,293 @@
1
+ # <img src="./assets/a1-logo.svg" alt="A1" width="40"> Google Forms MCP
2
+
3
+ [English](./README.md) | **Русский**
4
+
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
+ [![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)
8
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
9
+
10
+ **A1 Google Forms MCP** позволяет AI-приложению создавать и настраивать Google Forms на естественном языке. Можно подготовить опрос, выбрать вопросы, опубликовать его в нужный момент, прочитать ответы и настроить уведомления о новых отправках.
11
+
12
+ Сервер работает с Google Forms API через ваш Google-аккаунт. Он отличает черновую форму от опубликованной и явно показывает ограничения API, а не создаёт впечатление, что через форму можно сделать всё.
13
+
14
+ - **19 инструментов.** Проверка структуры формы и ответов, создание и редактирование форм и вопросов, управление публикацией и Pub/Sub watches.
15
+ - **Подключение из диалога.** Скажите «подключи Google Формы»: сервер проведёт через создание OAuth-клиента, поймает редирект Google на `127.0.0.1` с PKCE и сам сохранит токены — без конфигов и перезапуска.
16
+ - **Осознанная публикация.** Формы, созданные через API, по умолчанию не опубликованы и не принимают ответы, пока вы их не опубликуете.
17
+ - **Ответы сохраняются как есть.** API умеет читать ответы, но не создавать и не редактировать их; инструмента отправки ответов у сервера нет.
18
+ - **Минимальные scope Google.** Используются `forms.body` и `forms.responses.readonly` без широкого доступа к Drive.
19
+
20
+ Начните с запроса, который только читает данные:
21
+
22
+ > Покажи вчерашние ответы на форму обратной связи и кратко суммируй ответы в свободной форме.
23
+
24
+ [Подключить сервер](#быстрый-старт) · [Посмотреть сценарии](#что-можно-поручить) · [Открыть техническую документацию](#техническая-документация)
25
+
26
+ ---
27
+
28
+ ## Увидеть работу за минуту
29
+
30
+ > **Вы:** Покажи вопросы и настройки приёма ответов в форме обратной связи.
31
+ >
32
+ > **Ассистент:** Показывает форму, её пункты, статус публикации и возможность принимать ответы. Ничего не меняется.
33
+ >
34
+ > **Вы:** Подготовь обязательный вопрос с оценкой от 1 до 5: «Как прошёл ваш опыт?» — после первого вопроса.
35
+ >
36
+ > **Ассистент:** Показывает целевую форму, позицию и предлагаемый вопрос, затем запрашивает подтверждение перед добавлением.
37
+ >
38
+ > **Вы:** Подтверждаю.
39
+ >
40
+ > **Ассистент:** Добавляет вопрос в форму. Он не публикует и не закрывает форму, пока вы не попросите об этом отдельно.
41
+
42
+ ## Содержание
43
+
44
+ - [Быстрый старт](#быстрый-старт)
45
+ - [Что можно поручить](#что-можно-поручить)
46
+ - [Как меняется форма](#как-меняется-форма)
47
+ - [Что может измениться](#что-может-измениться)
48
+ - [Как получить доступ](#как-получить-доступ)
49
+ - [Конфигурация](#конфигурация)
50
+ - [Данные, лимиты и работа в фоне](#данные-лимиты-и-работа-в-фоне)
51
+ - [Техническая документация](#техническая-документация)
52
+ - [Поддержка](#поддержка)
53
+
54
+ ## Быстрый старт
55
+
56
+ Нужны Node.js 20+ и Google-аккаунт. Учётные данные при установке не нужны: сервер подключается прямо в диалоге.
57
+
58
+ 1. Добавьте сервер в AI-приложение.
59
+ 2. Скажите «подключи Google Формы» — ассистент проведёт [создание OAuth-клиента и выдачу доступа](#как-получить-доступ), не трогая конфиги.
60
+ 3. Отправьте запрос, который только читает данные.
61
+
62
+ <details open>
63
+ <summary><strong>Codex</strong></summary>
64
+
65
+ <br>
66
+
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**.
68
+
69
+ **В командной строке:**
70
+
71
+ ```bash
72
+ codex mcp add google-forms \
73
+ -- npx -y mcp-google-forms@latest
74
+ ```
75
+
76
+ ```bash
77
+ codex mcp list
78
+ ```
79
+
80
+ [Документация Codex MCP](https://learn.chatgpt.com/docs/extend/mcp?surface=cli)
81
+
82
+ </details>
83
+
84
+ <details>
85
+ <summary><strong>Claude Code</strong></summary>
86
+
87
+ <br>
88
+
89
+ ```bash
90
+ claude mcp add \
91
+ --transport stdio --scope user google-forms \
92
+ -- npx -y mcp-google-forms@latest
93
+ ```
94
+
95
+ ```bash
96
+ claude mcp list
97
+ ```
98
+
99
+ [Документация Claude Code MCP](https://code.claude.com/docs/en/mcp)
100
+
101
+ </details>
102
+
103
+ <details>
104
+ <summary><strong>Claude Desktop</strong></summary>
105
+
106
+ <br>
107
+
108
+ Актуальный официальный путь — **Settings → Extensions**. Для пользовательского desktop extension откройте **Advanced settings → Extension Developer → Install Extension…**, выберите файл `.mcpb` и следуйте подсказкам.
109
+
110
+ Этот репозиторий сейчас публикует npm-пакет со stdio и пока не содержит `.mcpb`. Поэтому используйте приведённый ниже JSON stdio-конфиг как fallback только в сборках Claude Desktop, где ещё поддерживается локальная конфигурация:
111
+
112
+ ```json
113
+ {
114
+ "mcpServers": {
115
+ "google-forms": {
116
+ "command": "npx",
117
+ "args": ["-y", "mcp-google-forms@latest"]
118
+ }
119
+ }
120
+ }
121
+ ```
122
+
123
+ В таких сборках сохраните его в `~/Library/Application Support/Claude/claude_desktop_config.json` на macOS или `%APPDATA%\Claude\claude_desktop_config.json` на Windows.
124
+
125
+ [Документация Claude Desktop MCP](https://support.claude.com/en/articles/10949351-getting-started-with-local-mcp-servers-on-claude-desktop)
126
+
127
+ </details>
128
+
129
+ <details>
130
+ <summary><strong>Cursor</strong></summary>
131
+
132
+ <br>
133
+
134
+ Добавьте в `~/.cursor/mcp.json` на macOS/Linux или `%USERPROFILE%\.cursor\mcp.json` на Windows:
135
+
136
+ ```json
137
+ {
138
+ "mcpServers": {
139
+ "google-forms": {
140
+ "type": "stdio",
141
+ "command": "npx",
142
+ "args": ["-y", "mcp-google-forms@latest"]
143
+ }
144
+ }
145
+ }
146
+ ```
147
+
148
+ [Документация Cursor MCP](https://cursor.com/docs/mcp)
149
+
150
+ </details>
151
+
152
+ <details>
153
+ <summary><strong>VS Code</strong></summary>
154
+
155
+ <br>
156
+
157
+ Запустите **MCP: Open User Configuration** и добавьте:
158
+
159
+ ```json
160
+ {
161
+ "servers": {
162
+ "google-forms": {
163
+ "type": "stdio",
164
+ "command": "npx",
165
+ "args": ["-y", "mcp-google-forms@latest"]
166
+ }
167
+ }
168
+ }
169
+ ```
170
+
171
+ Проверьте сервер командой **MCP: List Servers**.
172
+
173
+ [Документация VS Code MCP](https://code.visualstudio.com/docs/agent-customization/mcp-servers)
174
+
175
+ </details>
176
+
177
+ ## Что можно поручить
178
+
179
+ ### Проверить опрос и ответы
180
+
181
+ - Покажи вопросы, настройки приёма ответов и ссылку для респондентов.
182
+ - Сколько ответов пришло с понедельника? Суммируй обратную связь в свободной форме.
183
+ - Покажи один ответ по его ID.
184
+
185
+ ### Собрать и улучшить форму
186
+
187
+ - Создай RSVP-форму с именем, выбором питания и датой приезда.
188
+ - Добавь обязательный вопрос с оценкой, выпадающий список, дату, время, один или несколько вариантов или текстовое поле.
189
+ - Перемести вопрос или обнови название, описание, quiz mode или сбор email.
190
+
191
+ ### Опубликовать и настроить уведомления
192
+
193
+ - Опубликуй готовую форму и покажи ссылку для респондентов.
194
+ - Останови приём новых ответов, не удаляя форму.
195
+ - Создай, продли или удали Cloud Pub/Sub watch для новых отправок.
196
+
197
+ ## Как меняется форма
198
+
199
+ 1. `create_form` создаёт **форму**, которая по умолчанию не опубликована.
200
+ 2. Вопросы — это **пункты**, которые определяются позицией в форме.
201
+ 3. Публикация открывает форму для респондентов; закрытие приёма ответов оставляет форму опубликованной, но не принимает новые отправки.
202
+ 4. Ответы — отдельная read-only запись. API не может отправить, изменить или удалить ответ респондента.
203
+
204
+ Через Forms API нельзя создать вопрос с загрузкой файла, хотя существующий такой вопрос можно прочитать. Старые формы, созданные до модели публикации Google, могут не поддерживать настройки публикации.
205
+
206
+ ## Что может измениться
207
+
208
+ | Операция | Что происходит | Граница подтверждения |
209
+ |---|---|---|
210
+ | Проверка формы и её ответов | Читает структуру и отправки | Ничего не меняет |
211
+ | Создание формы | Добавляет неопубликованную форму | Меняет Google Forms |
212
+ | Добавление или перемещение вопроса | Меняет пункты формы | Меняет форму |
213
+ | Обновление данных, настроек или вопроса | Меняет название, настройки или выбранный вопрос | Меняет форму |
214
+ | Публикация, снятие с публикации, открытие или закрытие ответов | Меняет доступность формы | Меняет доступ для респондентов |
215
+ | Удаление пункта | Удаляет выбранный вопрос | Разрушительно |
216
+ | Управление Pub/Sub watch | Создаёт, продлевает или удаляет доставку уведомлений | Потенциально разрушительно |
217
+ | Технический запрос API | Может вызвать метод API без отдельного инструмента | Потенциально разрушительно |
218
+
219
+ Как AI-приложение просит подтверждение, определяет само приложение. Сервер помечает операции чтения, записи и удаления, чтобы оно отличило проверку от рабочего изменения.
220
+
221
+ ## Как получить доступ
222
+
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 и автоматические установки)
237
+
238
+ 1. Создайте или выберите проект Google Cloud и включите **Google Forms API**.
239
+ 2. Настройте OAuth consent screen и создайте OAuth-клиент типа **Desktop app**.
240
+ 3. Авторизуйте Google-аккаунт, который владеет формами или может их редактировать. [OAuth 2.0 Playground](https://developers.google.com/oauthplayground) поможет получить refresh token, если включить **Use your own OAuth credentials**.
241
+ 4. Запросите оба scope:
242
+
243
+ ```text
244
+ https://www.googleapis.com/auth/forms.body
245
+ https://www.googleapis.com/auth/forms.responses.readonly
246
+ ```
247
+
248
+ Refresh token OAuth-приложения в режиме Testing может истечь через семь дней. Для долгого доступа опубликуйте OAuth-приложение или используйте Internal-приложение в домене Workspace. Храните client secret и refresh token как пароли.
249
+
250
+ ## Конфигурация
251
+
252
+ Все переменные необязательные — без единой из них сервер подключается [из диалога](#подключение-из-диалога-рекомендуемый-путь).
253
+
254
+ | Переменная | Обязательна | Описание |
255
+ |---|---|---|
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. |
261
+ | `GOOGLE_FORMS_API_BASE` | Нет | Переопределяет базовый URL Google Forms API. |
262
+ | `GOOGLE_FORMS_TIMEOUT_MS` | Нет | Тайм-аут одного запроса; по умолчанию `60000` мс. |
263
+ | `GOOGLE_FORMS_MAX_RETRIES` | Нет | Повторы временных ошибок; по умолчанию `3`. |
264
+
265
+ \* Передайте OAuth-тройку или access token.
266
+
267
+ ## Данные, лимиты и работа в фоне
268
+
269
+ - **Запросы идут в Google Forms.** Локальный сервер обновляет OAuth-токены Google и вызывает Forms API. Анонимная телеметрия содержит ID установки, версию пакета, версии AI-клиента и платформы и имена инструментов — но не OAuth-токены, данные формы, аргументы или промпты. Чтобы отключить её, задайте `ASKADS_TELEMETRY=0`.
270
+ - **У Google есть поминутные квоты.** Документированные лимиты: 975 чтений на проект, 450 вызовов `list_responses` и 375 записей. При `429` сервер использует задержку; чтение также повторяется после сетевых и `5xx` ошибок, а запись после неопределённой ошибки не повторяется.
271
+ - **Постоянного опроса нет.** Сервер работает только при вызове. Pub/Sub watch может уведомить вашу инфраструктуру о новых ответах; если AI-приложение поддерживает задания по расписанию, оно также может периодически проверять ответы.
272
+
273
+ ## Техническая документация
274
+
275
+ - [Каталог MCP-возможностей](./docs/capabilities/index.md) — страницы по пользовательским задачам для каждого инструмента.
276
+ - [Все инструменты и параметры](./docs/TOOLS.md)
277
+ - [Документация по разработке](./docs/DEVELOPMENT.md)
278
+ - [Документация по публикации](./docs/PUBLISHING.md)
279
+ - [Справочник Google Forms API](https://developers.google.com/forms/api)
280
+
281
+ ## Поддержка
282
+
283
+ Нашли ошибку или не хватает сценария? [Создайте issue](https://github.com/A1-x-Tech/mcp-google-forms/issues) или напишите в [Telegram](https://t.me/a1_mcp).
284
+
285
+ <br>
286
+
287
+ <p align="center">
288
+ <img src="https://github.com/ztemerbekov/a1-yandex-kit-skills/raw/main/assets/images/mona-hifive-yandex-kit-warm.gif" alt="Две Моны дают пять" width="256">
289
+ </p>
290
+
291
+ <p align="center">
292
+ Вы дочитали до конца!
293
+ </p>
package/dist/client.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { GoogleFormsError } from "./types.js";
2
+ import { CredentialsError } from "./config.js";
2
3
  /** Google's OAuth2 token endpoint — refresh tokens are exchanged here. */
3
4
  const TOKEN_URL = "https://oauth2.googleapis.com/token";
4
5
  /** Maps a normalized rating icon to the API's wire value. */
@@ -67,6 +68,7 @@ function buildQuestion(p) {
67
68
  }
68
69
  export class GoogleFormsClient {
69
70
  config;
71
+ tokenProvider;
70
72
  base;
71
73
  timeoutMs;
72
74
  maxRetries;
@@ -75,8 +77,16 @@ export class GoogleFormsClient {
75
77
  cachedToken;
76
78
  /** In-flight refresh, deduping concurrent token requests. */
77
79
  refreshInFlight;
78
- 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) {
79
88
  this.config = config;
89
+ this.tokenProvider = tokenProvider;
80
90
  this.base = config.apiBase.endsWith("/") ? config.apiBase : config.apiBase + "/";
81
91
  this.timeoutMs = config.timeoutMs ?? 60_000;
82
92
  this.maxRetries = config.maxRetries ?? 3;
@@ -85,16 +95,37 @@ export class GoogleFormsClient {
85
95
  canRefresh() {
86
96
  return Boolean(this.config.refreshToken && this.config.clientId && this.config.clientSecret);
87
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
+ }
88
111
  /**
89
112
  * Returns a valid Bearer token. With the refresh triple configured, mints an
90
113
  * access token from the refresh token and caches it until shortly before it
91
114
  * expires (concurrent callers share one in-flight refresh); otherwise the
92
- * static GOOGLE_FORMS_ACCESS_TOKEN is used as-is.
115
+ * static GOOGLE_FORMS_ACCESS_TOKEN is used as-is. With neither configured,
116
+ * throws {@link CredentialsError} BEFORE any fetch — a missing setup must
117
+ * never enter the retry/backoff loop or trigger the 401 re-mint, because no
118
+ * amount of retrying mints credentials.
93
119
  */
94
120
  async accessToken(forceRefresh = false) {
95
121
  if (!this.canRefresh()) {
96
- // loadConfig guarantees accessToken is set when the refresh triple is absent.
97
- 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();
98
129
  }
99
130
  if (!forceRefresh && this.cachedToken && Date.now() < this.cachedToken.expiresAt) {
100
131
  return this.cachedToken.value;
@@ -221,7 +252,7 @@ export class GoogleFormsClient {
221
252
  }
222
253
  // An expired/revoked access token: re-mint once and replay. The request
223
254
  // never executed, so this is safe for writes too.
224
- if (res.status === 401 && this.canRefresh() && !refreshedOn401) {
255
+ if (res.status === 401 && this.canReplayOn401() && !refreshedOn401) {
225
256
  refreshedOn401 = true;
226
257
  await this.accessToken(true);
227
258
  continue;
@@ -260,12 +291,25 @@ export class GoogleFormsClient {
260
291
  info: compact({ title: p.title, documentTitle: p.documentTitle }),
261
292
  });
262
293
  if (p.publish && typeof form.formId === "string") {
263
- const published = await this.setPublishSettings({
264
- formId: form.formId,
265
- isPublished: true,
266
- isAcceptingResponses: true,
267
- });
268
- return { ...form, publishSettings: published.publishSettings };
294
+ // The form already exists here; the Forms API has no list endpoint, so a
295
+ // thrown publish error would lose the only copy of the formId and push
296
+ // the caller into re-creating (duplicating) the form.
297
+ try {
298
+ const published = await this.setPublishSettings({
299
+ formId: form.formId,
300
+ isPublished: true,
301
+ isAcceptingResponses: true,
302
+ });
303
+ return { ...form, publishSettings: published.publishSettings };
304
+ }
305
+ catch (err) {
306
+ return {
307
+ ...form,
308
+ published: false,
309
+ publish_error: err instanceof Error ? err.message : String(err),
310
+ next_step: "The form was created but publishing failed — call set_publish_settings with this formId; do not call create_form again.",
311
+ };
312
+ }
269
313
  }
270
314
  return form;
271
315
  }
@@ -281,12 +325,16 @@ export class GoogleFormsClient {
281
325
  writeControl: opts.requiredRevisionId ? { requiredRevisionId: opts.requiredRevisionId } : undefined,
282
326
  }));
283
327
  }
284
- /** Updates title / description / documentTitle with a computed updateMask. */
328
+ /**
329
+ * Updates title / description with a computed updateMask. Info.documentTitle
330
+ * is output-only in batchUpdate: the Drive file name is set at creation and
331
+ * renamed only through the Drive API, which this server does not cover.
332
+ */
285
333
  async updateFormInfo(p) {
286
- const info = compact({ title: p.title, description: p.description, documentTitle: p.documentTitle });
334
+ const info = compact({ title: p.title, description: p.description });
287
335
  const mask = Object.keys(info).join(",");
288
336
  if (!mask)
289
- throw new Error("At least one of title, description or document_title is required.");
337
+ throw new Error("At least one of title or description is required.");
290
338
  return this.batchUpdate(p.formId, [{ updateFormInfo: { info, updateMask: mask } }]);
291
339
  }
292
340
  /** Toggles quiz mode / email collection with a computed updateMask. */
package/dist/config.js CHANGED
@@ -1,9 +1,10 @@
1
1
  /** Default Google Forms API host. */
2
- const DEFAULT_BASE = "https://forms.googleapis.com";
2
+ export const DEFAULT_BASE = "https://forms.googleapis.com";
3
3
  /**
4
- * A missing or malformed environment variable. Thrown instead of exiting on the
5
- * spot so index.ts can report the drop-off before the process dies; `reason` is
6
- * the machine-readable code that ships with that ping (never a variable's value).
4
+ * A malformed environment variable. Thrown instead of exiting on the spot so
5
+ * index.ts can catch it, report the drop-off and start degraded instead of
6
+ * dying; `reason` is the machine-readable code that ships with that ping
7
+ * (never a variable's value).
7
8
  */
8
9
  export class ConfigError extends Error {
9
10
  reason;
@@ -13,12 +14,43 @@ export class ConfigError extends Error {
13
14
  this.reason = reason;
14
15
  }
15
16
  }
16
- function die(message, reason) {
17
- throw new ConfigError(message, reason);
17
+ /**
18
+ * What a tool call without credentials reads. The first sentence is the
19
+ * historical startup error, verbatim — the rest exists because credentials come
20
+ * only from the environment, so the fix is an operator action plus a restart,
21
+ * never a retry.
22
+ */
23
+ export const MISSING_CREDENTIALS_MESSAGE = "Google OAuth credentials are required: set GOOGLE_FORMS_CLIENT_ID + " +
24
+ "GOOGLE_FORMS_CLIENT_SECRET + GOOGLE_FORMS_REFRESH_TOKEN (recommended), or " +
25
+ "GOOGLE_FORMS_ACCESS_TOKEN with a short-lived access token. " +
26
+ "This is not a network failure and retrying will not help: the operator must set these " +
27
+ "environment variables in the MCP client's server config and restart the server — they are " +
28
+ "read only at startup.";
29
+ /**
30
+ * Raised when a tool call needs credentials and none were configured. The
31
+ * message is the whole point of the class: it is the only text the calling
32
+ * model reads about the missing setup, so it names the fix (which variables,
33
+ * and that a restart is needed) instead of the failure.
34
+ */
35
+ export class CredentialsError extends Error {
36
+ constructor(message = MISSING_CREDENTIALS_MESSAGE) {
37
+ super(message);
38
+ this.name = "CredentialsError";
39
+ }
40
+ }
41
+ /** True when the config carries usable credentials (the full refresh triple or a static token). */
42
+ export function hasCredentials(config) {
43
+ return Boolean(config.accessToken || (config.clientId && config.clientSecret && config.refreshToken));
18
44
  }
19
45
  /**
20
- * Builds the client config from environment variables, throwing ConfigError if
21
- * the credentials are missing or incomplete.
46
+ * Builds the client config from environment variables.
47
+ *
48
+ * Missing credentials are NOT an error here: the server starts anyway and the
49
+ * client raises {@link CredentialsError} on the first tool call, so an
50
+ * unconfigured install completes the MCP handshake and carries the fix into
51
+ * the session instead of dying before it with nothing to read. A malformed
52
+ * setup — the refresh triple set only partially — still throws, because
53
+ * guessing what the user meant is worse.
22
54
  *
23
55
  * GOOGLE_FORMS_CLIENT_ID OAuth2 client id (refresh flow, recommended)
24
56
  * GOOGLE_FORMS_CLIENT_SECRET OAuth2 client secret (refresh flow)
@@ -35,10 +67,7 @@ export function loadConfig() {
35
67
  const accessToken = process.env.GOOGLE_FORMS_ACCESS_TOKEN;
36
68
  const oauthProvided = [clientId, clientSecret, refreshToken].filter(Boolean).length;
37
69
  if (oauthProvided > 0 && oauthProvided < 3) {
38
- die("GOOGLE_FORMS_CLIENT_ID, GOOGLE_FORMS_CLIENT_SECRET and GOOGLE_FORMS_REFRESH_TOKEN must be set together (OAuth2 refresh flow).", "incomplete_oauth_config");
39
- }
40
- if (oauthProvided === 0 && !accessToken) {
41
- die("Google OAuth credentials are required: set GOOGLE_FORMS_CLIENT_ID + GOOGLE_FORMS_CLIENT_SECRET + GOOGLE_FORMS_REFRESH_TOKEN (recommended), or GOOGLE_FORMS_ACCESS_TOKEN with a short-lived access token.", "missing_credentials");
70
+ throw new ConfigError("GOOGLE_FORMS_CLIENT_ID, GOOGLE_FORMS_CLIENT_SECRET and GOOGLE_FORMS_REFRESH_TOKEN must be set together (OAuth2 refresh flow).", "incomplete_oauth_config");
42
71
  }
43
72
  const timeoutMs = Number(process.env.GOOGLE_FORMS_TIMEOUT_MS);
44
73
  const maxRetries = Number(process.env.GOOGLE_FORMS_MAX_RETRIES);
package/dist/index.js CHANGED
@@ -3,13 +3,40 @@ import { readFileSync } from "node:fs";
3
3
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
4
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
5
  import { GoogleFormsClient } from "./client.js";
6
- import { ConfigError, loadConfig } from "./config.js";
6
+ import { ConfigError, DEFAULT_BASE, hasCredentials, loadConfig } from "./config.js";
7
7
  import { instrumentToolCalls, Telemetry } from "./telemetry.js";
8
8
  import { registerFormTools } from "./tools/forms.js";
9
9
  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";
14
+ /**
15
+ * Prose handed to the calling model in the `initialize` result — the only place
16
+ * it learns what the tool list cannot say: which Google product this API is,
17
+ * what the API refuses to do, and the behaviours that make a naive loop
18
+ * expensive, lossy or duplicating.
19
+ */
20
+ const INSTRUCTIONS = "Google Forms API v1 builds and reads Google Forms — not Sheets, Docs or Drive: the linked " +
21
+ "responses spreadsheet (linkedSheetId), and deleting, sharing or renaming the Drive file, are " +
22
+ "out of reach. Responses are read-only: no endpoint submits or edits one. File-upload questions " +
23
+ "cannot be created; grids need raw_request. New forms take only a title/documentTitle (the Drive " +
24
+ "file name — settable only at creation) and start UNPUBLISHED until published; legacy forms " +
25
+ "reject set_publish_settings. Items are addressed by 0-based position, not itemId, and each " +
26
+ "delete or move shifts the rest — re-read get_form between mutations; update_question clears " +
27
+ "any masked field it omits. Quiz mode alone grades nothing: add_question cannot set points — " +
28
+ "write questionItem.question.grading per question via update_question. Per-minute project quotas: 975 " +
29
+ "reads, 375 writes, 450 list_responses — poll with submitted_after (the only filter; sort " +
30
+ "client-side), don't re-list. Absent respondentEmail/totalScore means email collection or grading " +
31
+ "is off, not lost data; auth that suddenly breaks usually means the consent screen is still in " +
32
+ "Testing, where refresh tokens die after 7 days. Writes hit a live form and are never retried " +
33
+ "after a 5xx or timeout: check with get_form before re-sending; delete_item is final.";
34
+ /**
35
+ * Prepended to INSTRUCTIONS when no credentials are configured. The model reads
36
+ * this before it picks a tool, so an unconfigured session opens with the fix
37
+ * rather than with a failed call. There is no in-chat login here: credentials
38
+ * come only from the environment, so the fix is an operator action + restart.
39
+ */
13
40
  /** Reads the package version so the server reports its real version to MCP clients. */
14
41
  function readVersion() {
15
42
  try {
@@ -21,21 +48,27 @@ function readVersion() {
21
48
  }
22
49
  }
23
50
  /**
24
- * Loads the config, reporting the drop-off if it is missing. An unconfigured
25
- * server dies before the MCP handshake, so this ping is the only trace such an
26
- * install ever leaves — and it has to be awaited, or process.exit() below would
27
- * kill the request in flight.
51
+ * Loads the config without dying on a bad value. A server that exits here never
52
+ * completes the MCP handshake, so the user sees a dead server and no reason.
53
+ * Instead the problem is carried into the session, where the model can read it
54
+ * and relay it: the config degrades to "no credentials" and every tool call
55
+ * fails with the actionable message.
28
56
  */
29
- async function loadConfigOrExit(telemetry) {
57
+ function loadConfigOrDegraded(telemetry) {
30
58
  try {
31
- return loadConfig();
59
+ return { config: loadConfig() };
32
60
  }
33
61
  catch (err) {
34
62
  if (!(err instanceof ConfigError))
35
63
  throw err;
36
64
  console.error(`Error: ${err.message}`);
37
- await telemetry.sendBlocking("startup_failed", { reason: err.reason });
38
- process.exit(1);
65
+ // Fire-and-forget now that the process survives: the historical
66
+ // `startup_failed` funnel stays comparable, but nothing blocks startup.
67
+ telemetry.send("startup_failed", { reason: err.reason });
68
+ return {
69
+ config: { apiBase: process.env.GOOGLE_FORMS_API_BASE || DEFAULT_BASE },
70
+ problem: err,
71
+ };
39
72
  }
40
73
  }
41
74
  async function main() {
@@ -43,17 +76,35 @@ async function main() {
43
76
  // opt out with ASKADS_TELEMETRY=0. Built before the config so missing
44
77
  // credentials can be reported; wired to the server before tools register.
45
78
  const telemetry = new Telemetry(readVersion());
46
- const config = await loadConfigOrExit(telemetry);
47
- const client = new GoogleFormsClient(config);
79
+ const { config, problem } = loadConfigOrDegraded(telemetry);
80
+ // Decided once, at startup: credentials come only from the environment, so
81
+ // "restart after setting the variables" is the accurate advice to give.
82
+ const connected = hasCredentials(config) || hasAuthToken();
48
83
  const server = new McpServer({
49
84
  name: "mcp-google-forms",
50
85
  version: readVersion(),
86
+ },
87
+ // Surfaces in the initialize result, before the client sees a single tool.
88
+ {
89
+ instructions: connected
90
+ ? INSTRUCTIONS
91
+ : authUnconfiguredPrefix() + (problem ? `Configuration problem: ${problem.message} ` : "") + INSTRUCTIONS,
51
92
  });
52
93
  instrumentToolCalls(server, telemetry);
53
94
  server.server.oninitialized = () => {
54
95
  telemetry.setClientInfo(server.server.getClientVersion());
55
- telemetry.send("server_start");
96
+ // Split on purpose: `server_start` keeps meaning "a usable install started",
97
+ // so the unconfigured case gets its own event instead of inflating that number.
98
+ if (connected)
99
+ telemetry.send("server_start");
100
+ else
101
+ telemetry.send("unconfigured_start", { reason: problem?.reason ?? "missing_credentials" });
56
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);
57
108
  registerFormTools(server, client);
58
109
  registerItemTools(server, client);
59
110
  registerResponseTools(server, client);
@@ -61,7 +112,7 @@ async function main() {
61
112
  registerRawTool(server, client);
62
113
  const transport = new StdioServerTransport();
63
114
  await server.connect(transport);
64
- console.error("mcp-google-forms running on stdio");
115
+ console.error(`mcp-google-forms running on stdio${connected ? "" : " (no credentials — set the environment variables and restart)"}`);
65
116
  }
66
117
  main().catch((err) => {
67
118
  console.error("Fatal error starting mcp-google-forms:", err);
package/dist/telemetry.js CHANGED
@@ -69,9 +69,9 @@ export class Telemetry {
69
69
  void this.post(event, fields);
70
70
  }
71
71
  /**
72
- * The same ping, awaited. Only for the startup_failed path: that caller
73
- * calls process.exit() immediately after, which would kill an in-flight
74
- * fire-and-forget request before it ever left the machine.
72
+ * The same ping, awaited. Only for a caller that exits right after — a
73
+ * fire-and-forget request would die in flight with the process. No startup
74
+ * path needs it anymore (a config problem degrades instead of exiting).
75
75
  */
76
76
  async sendBlocking(event, fields = {}) {
77
77
  await this.post(event, fields);