mcp-google-forms 0.1.1 → 1.1.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
@@ -1,96 +1,116 @@
1
- # Google Forms MCP
1
+ # <img src="./assets/a1-logo.svg" alt="A1" width="40"> Google Forms MCP
2
+
3
+ **English** | [Русский](./README.ru.md)
2
4
 
3
5
  [![npm](https://img.shields.io/npm/v/mcp-google-forms)](https://www.npmjs.com/package/mcp-google-forms)
4
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)
5
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)
6
8
  [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
7
9
 
8
- MCP server for the **Google Forms API**: create forms, add and edit questions, publish, read
9
- responses and set up push notifications for new submissions — from Claude, Cursor, Codex and
10
- other AI clients, in natural language.
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
- Ask your assistant to "make a customer-feedback survey with a rating question and publish it",
13
- "show me yesterday's responses", or "close the form for responses" — it drives the Forms API
14
- for you, from a blank form to response analysis.
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.
15
13
 
16
- ## Quick start
14
+ - **13 tools.** Inspect form structure and responses, create and edit forms and questions, manage publishing, and configure Pub/Sub watches.
15
+ - **Publish deliberately.** Forms made through the API start unpublished, so they cannot collect responses until you publish them.
16
+ - **Responses stay intact.** The API can read responses but cannot create or edit them; the server has no tool that submits answers.
17
+ - **Minimal Google scopes.** It uses `forms.body` and `forms.responses.readonly`, without broad Drive access.
17
18
 
18
- 1. [Get OAuth credentials](#getting-credentials) for the Google Forms API.
19
- 2. Add the server — for example, in Claude Code ([other clients](#installation)):
19
+ Start with a read-only question:
20
20
 
21
- ```bash
22
- claude mcp add google-forms \
23
- -e GOOGLE_FORMS_CLIENT_ID=your_client_id \
24
- -e GOOGLE_FORMS_CLIENT_SECRET=your_client_secret \
25
- -e GOOGLE_FORMS_REFRESH_TOKEN=your_refresh_token \
26
- -- npx -y mcp-google-forms@latest
27
- ```
21
+ > Show me yesterday’s responses to the customer feedback form and summarize the free-text answers.
22
+
23
+ [Connect the server](#quick-start) · [Explore use cases](#what-you-can-ask-it-to-do) · [Open technical documentation](#technical-documentation)
24
+
25
+ ---
28
26
 
29
- 3. Ask the assistant: *"Create a form called 'Team lunch survey' with a dropdown of three
30
- restaurants and publish it."*
31
-
32
- ## Tools
33
-
34
- | Tool | Description |
35
- |---|---|
36
- | `create_form` | Create a form (optionally publish it right away — API-created forms start unpublished). |
37
- | `get_form` | Full form structure: info, settings, items with ids, publish state, responder URL. |
38
- | `update_form_info` | Change the title, description or document title. |
39
- | `update_form_settings` | Toggle quiz mode and email collection. |
40
- | `add_question` | Add a question: text, paragraph, radio, checkbox, dropdown, scale, date, time, rating. |
41
- | `update_question` | Update an existing item by index with an explicit update mask. |
42
- | `delete_item` | Delete the item at an index. |
43
- | `move_item` | Reorder items. |
44
- | `set_publish_settings` | Publish/unpublish, open/close response collection. |
45
- | `list_responses` | List submissions, incrementally with `submitted_after`; paginated. |
46
- | `get_response` | Fetch one submission by id. |
47
- | `manage_watches` | Create/list/delete/renew Cloud Pub/Sub push-notification watches. |
48
- | `raw_request` | Escape hatch: any Forms API v1 path (e.g. a custom `batchUpdate` with grids). |
49
-
50
- Plus resilience built in: automatic OAuth token refresh (including on 401), retries with
51
- backoff on 429 (and on 5xx/network errors for reads only — writes are never replayed), a
52
- request timeout, and an SSRF guard so the token can't leak to a foreign host.
53
-
54
- ## Example prompts
55
-
56
- - "Create an RSVP form for the offsite, ask for name, meal preference (veg/meat/fish) and
57
- arrival date, then publish it and give me the link."
58
- - "Turn the 'Onboarding quiz' form into a quiz and make every question required."
59
- - "How many responses came in since Monday? Summarize the free-text feedback."
60
- - "Stop accepting responses on the feedback form."
61
-
62
- ## Limitations (the API's, not the server's)
63
-
64
- - **Responses are read-only.** The Forms API cannot submit or edit responses — there is no
65
- such endpoint, so this server has no submit tool either.
66
- - **API-created forms start unpublished** and don't accept responses until published — use
67
- `publish: true` on `create_form` or `set_publish_settings`. Legacy forms (from before the
68
- publish model) don't support `set_publish_settings` at all.
69
- - **File-upload questions can't be created** via the API (existing ones are readable).
70
- - **Quotas are per minute** (reads 975/project, `list_responses` 450, writes 375); the server
71
- backs off on 429 automatically.
72
-
73
- ## Installation
74
-
75
- Requires Node.js 20+ (runs via `npx`, no separate install).
27
+ ## See it work in a minute
28
+
29
+ > **You:** Show me the questions and response settings of the customer feedback form.
30
+ >
31
+ > **Assistant:** Shows the form, its items, whether it is published and whether it accepts responses. Nothing changes.
32
+ >
33
+ > **You:** Prepare a required 1–5 rating question called “How was your experience?” after the first question.
34
+ >
35
+ > **Assistant:** Shows the target form, position and proposed question, then asks for confirmation before adding it.
36
+ >
37
+ > **You:** Confirm.
38
+ >
39
+ > **Assistant:** Adds the question to the form. It does not publish or close the form unless you ask separately.
40
+
41
+ ## Contents
42
+
43
+ - [Quick start](#quick-start)
44
+ - [What you can ask it to do](#what-you-can-ask-it-to-do)
45
+ - [How a form changes](#how-a-form-changes)
46
+ - [What can change](#what-can-change)
47
+ - [Getting access](#getting-access)
48
+ - [Configuration](#configuration)
49
+ - [Data, limits and background work](#data-limits-and-background-work)
50
+ - [Technical documentation](#technical-documentation)
51
+ - [Support](#support)
52
+
53
+ ## Quick start
54
+
55
+ You need Node.js 20+, a Google account and OAuth credentials from a Google Cloud project with the Google Forms API enabled.
56
+
57
+ 1. [Prepare Google OAuth access](#getting-access).
58
+ 2. Add the server to your AI app.
59
+ 3. Ask the read-only question above.
76
60
 
77
61
  <details open>
78
- <summary><b>Claude Code</b></summary>
62
+ <summary><strong>Codex</strong></summary>
63
+
64
+ <br>
65
+
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
+
68
+ **From the command line:**
79
69
 
80
70
  ```bash
81
- claude mcp add google-forms \
82
- -e GOOGLE_FORMS_CLIENT_ID=your_client_id \
83
- -e GOOGLE_FORMS_CLIENT_SECRET=your_client_secret \
84
- -e GOOGLE_FORMS_REFRESH_TOKEN=your_refresh_token \
71
+ 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 \
85
75
  -- npx -y mcp-google-forms@latest
86
76
  ```
87
77
 
78
+ ```bash
79
+ codex mcp list
80
+ ```
81
+
82
+ [Codex MCP documentation](https://learn.chatgpt.com/docs/extend/mcp?surface=cli)
83
+
84
+ </details>
85
+
86
+ <details>
87
+ <summary><strong>Claude Code</strong></summary>
88
+
89
+ <br>
90
+
91
+ ```bash
92
+ 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
+ --transport stdio --scope user google-forms \
97
+ -- npx -y mcp-google-forms@latest
98
+ ```
99
+
100
+ ```bash
101
+ claude mcp list
102
+ ```
103
+
104
+ [Claude Code MCP documentation](https://code.claude.com/docs/en/mcp)
105
+
88
106
  </details>
89
107
 
90
108
  <details>
91
- <summary><b>Claude Desktop</b></summary>
109
+ <summary><strong>Claude Desktop</strong></summary>
110
+
111
+ <br>
92
112
 
93
- `claude_desktop_config.json` — macOS `~/Library/Application Support/Claude/`, Windows `%APPDATA%\Claude\`
113
+ Open **Settings → Developer → Edit Config** and add:
94
114
 
95
115
  ```json
96
116
  {
@@ -108,17 +128,24 @@ claude mcp add google-forms \
108
128
  }
109
129
  ```
110
130
 
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.
132
+
133
+ [Claude Desktop MCP documentation](https://support.claude.com/en/articles/10949351-getting-started-with-local-mcp-servers-on-claude-desktop)
134
+
111
135
  </details>
112
136
 
113
137
  <details>
114
- <summary><b>Cursor</b></summary>
138
+ <summary><strong>Cursor</strong></summary>
139
+
140
+ <br>
115
141
 
116
- `~/.cursor/mcp.json` (or `.cursor/mcp.json` in the project)
142
+ Add this to `~/.cursor/mcp.json` on macOS/Linux or `%USERPROFILE%\.cursor\mcp.json` on Windows:
117
143
 
118
144
  ```json
119
145
  {
120
146
  "mcpServers": {
121
147
  "google-forms": {
148
+ "type": "stdio",
122
149
  "command": "npx",
123
150
  "args": ["-y", "mcp-google-forms@latest"],
124
151
  "env": {
@@ -131,12 +158,16 @@ claude mcp add google-forms \
131
158
  }
132
159
  ```
133
160
 
161
+ [Cursor MCP documentation](https://cursor.com/docs/mcp)
162
+
134
163
  </details>
135
164
 
136
165
  <details>
137
- <summary><b>VS Code</b></summary>
166
+ <summary><strong>VS Code</strong></summary>
138
167
 
139
- `.vscode/mcp.json` — note the `servers` key (not `mcpServers`)
168
+ <br>
169
+
170
+ Run **MCP: Open User Configuration** and add:
140
171
 
141
172
  ```json
142
173
  {
@@ -146,76 +177,124 @@ claude mcp add google-forms \
146
177
  "command": "npx",
147
178
  "args": ["-y", "mcp-google-forms@latest"],
148
179
  "env": {
149
- "GOOGLE_FORMS_CLIENT_ID": "your_client_id",
150
- "GOOGLE_FORMS_CLIENT_SECRET": "your_client_secret",
151
- "GOOGLE_FORMS_REFRESH_TOKEN": "your_refresh_token"
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}"
152
183
  }
153
184
  }
154
- }
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
+ ]
155
191
  }
156
192
  ```
157
193
 
194
+ Check it with **MCP: List Servers**.
195
+
196
+ [VS Code MCP documentation](https://code.visualstudio.com/docs/agent-customization/mcp-servers)
197
+
158
198
  </details>
159
199
 
160
- ## Getting credentials
161
-
162
- The Forms API has no API-key access — every call needs OAuth 2.0. One-time setup, ~10 minutes:
163
-
164
- 1. **Create a Google Cloud project** (or reuse one) at
165
- [console.cloud.google.com](https://console.cloud.google.com/), then enable the
166
- **Google Forms API**: *APIs & Services → Library → Google Forms API → Enable*.
167
- 2. **Configure the OAuth consent screen** (*APIs & Services → OAuth consent screen*): choose
168
- *External*, fill in the app name and your email, and add your Google account under
169
- **Test users** (in Testing mode only listed users can authorize — no app verification needed).
170
- 3. **Create an OAuth client** (*APIs & Services → Credentials → Create credentials → OAuth
171
- client ID*), application type **Desktop app**. Save the **client ID** and **client secret**.
172
- 4. **Mint a refresh token.** The easiest way is the
173
- [OAuth 2.0 Playground](https://developers.google.com/oauthplayground):
174
- - Click the gear icon → check **Use your own OAuth credentials** → paste your client ID and
175
- secret (add `https://developers.google.com/oauthplayground` as an authorized redirect URI
176
- to the OAuth client first).
177
- - In *Step 1*, enter the scopes
178
- `https://www.googleapis.com/auth/forms.body https://www.googleapis.com/auth/forms.responses.readonly`
179
- and click **Authorize APIs**, signing in with the test-user account.
180
- - In *Step 2*, click **Exchange authorization code for tokens** and copy the
181
- **refresh token**.
182
- 5. Put the three values into `GOOGLE_FORMS_CLIENT_ID`, `GOOGLE_FORMS_CLIENT_SECRET` and
183
- `GOOGLE_FORMS_REFRESH_TOKEN`. The server exchanges the refresh token for short-lived access
184
- tokens automatically.
185
-
186
- Scope notes: `forms.body` + `forms.responses.readonly` is the minimal, recommended pair (no
187
- broad Drive access). While the consent screen stays in Testing mode, refresh tokens expire
188
- after 7 days — publish the app (or keep it Internal in a Workspace domain) for long-lived tokens.
189
-
190
- ⚠️ The credentials are stored **in plain text** in your client's config — treat them like a
191
- password. The refresh token grants access to your forms until revoked at
192
- [myaccount.google.com/permissions](https://myaccount.google.com/permissions).
200
+ ## What you can ask it to do
201
+
202
+ ### Inspect a survey and its answers
203
+
204
+ - Show this form’s questions, response settings and responder link.
205
+ - How many answers arrived since Monday? Summarize the free-text feedback.
206
+ - Show one response by ID.
207
+
208
+ ### Build and improve a form
209
+
210
+ - Create an RSVP form with name, meal preference and arrival date.
211
+ - Add a required rating, dropdown, date, time, choice or text question.
212
+ - Reorder a question or update a title, description, quiz mode or email collection.
213
+
214
+ ### Publish and connect notifications
215
+
216
+ - Publish a prepared form and show its responder URL.
217
+ - Stop accepting new responses without deleting the form.
218
+ - Create, renew or remove a Cloud Pub/Sub watch for new submissions.
219
+
220
+ ## How a form changes
221
+
222
+ 1. `create_form` creates a **form**, which starts unpublished by default.
223
+ 2. Questions are **items**, identified by their position in the form.
224
+ 3. Publishing makes a form available to respondents; closing response collection leaves it published but stops new submissions.
225
+ 4. Responses are a separate read-only record. The API cannot submit, edit or delete a respondent’s answer.
226
+
227
+ File-upload questions cannot be created through the Forms API, although existing file-upload items can be read. Legacy forms created before Google’s publish model may not support publishing settings.
228
+
229
+ ## What can change
230
+
231
+ | Operation | What happens | Confirmation boundary |
232
+ |---|---|---|
233
+ | Read a form and its responses | Reads form structure and submissions | No change |
234
+ | Create a form | Adds an unpublished form | Changes Google Forms |
235
+ | Add or move a question | Changes form items | Changes a form |
236
+ | Update form info, settings or an item | Changes title, settings or a selected question | Changes a form |
237
+ | Publish, unpublish, open or close responses | Changes who can use the form | Changes a form’s public availability |
238
+ | Delete an item | Removes a selected question | Destructive |
239
+ | Manage a Pub/Sub watch | Creates, renews or deletes notification delivery | Potentially destructive |
240
+ | Raw API request | Can call API methods without a dedicated tool | Potentially destructive |
241
+
242
+ The AI client controls confirmation prompts. The server marks reads, writes and destructive tools so the client can distinguish an inspection from a live change.
243
+
244
+ ## Getting access
245
+
246
+ Google Forms requires OAuth 2.0; an API key is not enough.
247
+
248
+ 1. Create or select a Google Cloud project and enable **Google Forms API**.
249
+ 2. Configure the OAuth consent screen and create a **Desktop app** OAuth client.
250
+ 3. Authorize the Google account that owns or can edit the forms. The [OAuth 2.0 Playground](https://developers.google.com/oauthplayground) can obtain the refresh token when **Use your own OAuth credentials** is enabled.
251
+ 4. Request both scopes:
252
+
253
+ ```text
254
+ https://www.googleapis.com/auth/forms.body
255
+ https://www.googleapis.com/auth/forms.responses.readonly
256
+ ```
257
+
258
+ Testing-mode OAuth refresh tokens can expire after seven days. Publish the OAuth app, or use an Internal app in a Workspace domain, when you need long-lived access. Treat the client secret and refresh token as passwords.
193
259
 
194
260
  ## Configuration
195
261
 
196
- | Variable | Required | Default | Description |
197
- |---|---|---|---|
198
- | `GOOGLE_FORMS_CLIENT_ID` | yes* | — | OAuth2 client id (refresh flow). |
199
- | `GOOGLE_FORMS_CLIENT_SECRET` | yes* | — | OAuth2 client secret (refresh flow). |
200
- | `GOOGLE_FORMS_REFRESH_TOKEN` | yes* | — | OAuth2 refresh token (refresh flow). |
201
- | `GOOGLE_FORMS_ACCESS_TOKEN` | yes* | — | Alternative: a static access token (~1 h lifetime), mostly for testing. |
202
- | `GOOGLE_FORMS_API_BASE` | no | `https://forms.googleapis.com` | API root override. |
203
- | `GOOGLE_FORMS_TIMEOUT_MS` | no | `60000` | Per-request timeout, ms. |
204
- | `GOOGLE_FORMS_MAX_RETRIES` | no | `3` | Retries on transient errors. |
262
+ | Variable | Required | Description |
263
+ |---|---|---|
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. |
268
+ | `GOOGLE_FORMS_API_BASE` | No | Google Forms API base URL override. |
269
+ | `GOOGLE_FORMS_TIMEOUT_MS` | No | Per-request timeout; default `60000` ms. |
270
+ | `GOOGLE_FORMS_MAX_RETRIES` | No | Temporary-error retries; default `3`. |
271
+
272
+ \* Provide either the OAuth trio or an access token.
205
273
 
206
- \* Either the three refresh-flow variables together, **or** `GOOGLE_FORMS_ACCESS_TOKEN`.
274
+ ## Data, limits and background work
207
275
 
208
- ## Documentation
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.
277
+ - **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
+ - **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.
209
279
 
210
- - [All tools](https://github.com/A1-x-Tech/mcp-google-forms/blob/main/docs/TOOLS.md) — full reference with parameters and notes.
211
- - [Development](https://github.com/A1-x-Tech/mcp-google-forms/blob/main/docs/DEVELOPMENT.md) — build, tests, smoke check, telemetry.
212
- - [Publishing](https://github.com/A1-x-Tech/mcp-google-forms/blob/main/docs/PUBLISHING.md) — releasing and MCP-catalog listing.
280
+ ## Technical documentation
281
+
282
+ - [MCP capability catalog](./docs/capabilities/index.md) — task-oriented pages for every tool.
283
+ - [All tools and inputs](./docs/TOOLS.md)
284
+ - [Development documentation](./docs/DEVELOPMENT.md)
285
+ - [Publishing documentation](./docs/PUBLISHING.md)
286
+ - [Google Forms API reference](https://developers.google.com/forms/api)
213
287
 
214
288
  ## Support
215
289
 
216
- Questions, ideas, issues — Telegram [@gistrec](http://t.me/gistrec) or
217
- [GitHub issues](https://github.com/A1-x-Tech/mcp-google-forms/issues).
290
+ Found a bug or need a scenario? [Create an issue](https://github.com/A1-x-Tech/mcp-google-forms/issues) or write in [Telegram](https://t.me/a1_mcp).
291
+
292
+ <br>
218
293
 
219
- ## License
294
+ <p align="center">
295
+ <img src="https://github.com/ztemerbekov/a1-yandex-kit-skills/raw/main/assets/images/mona-hifive-yandex-kit-warm.gif" alt="Две Моны дают пять" width="256">
296
+ </p>
220
297
 
221
- MIT — see [LICENSE](./LICENSE).
298
+ <p align="center">
299
+ You made it to the end!
300
+ </p>
package/README.ru.md ADDED
@@ -0,0 +1,300 @@
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
+ - **13 инструментов.** Проверка структуры формы и ответов, создание и редактирование форм и вопросов, управление публикацией и Pub/Sub watches.
15
+ - **Осознанная публикация.** Формы, созданные через API, по умолчанию не опубликованы и не принимают ответы, пока вы их не опубликуете.
16
+ - **Ответы сохраняются как есть.** API умеет читать ответы, но не создавать и не редактировать их; инструмента отправки ответов у сервера нет.
17
+ - **Минимальные scope Google.** Используются `forms.body` и `forms.responses.readonly` без широкого доступа к Drive.
18
+
19
+ Начните с запроса, который только читает данные:
20
+
21
+ > Покажи вчерашние ответы на форму обратной связи и кратко суммируй ответы в свободной форме.
22
+
23
+ [Подключить сервер](#быстрый-старт) · [Посмотреть сценарии](#что-можно-поручить) · [Открыть техническую документацию](#техническая-документация)
24
+
25
+ ---
26
+
27
+ ## Увидеть работу за минуту
28
+
29
+ > **Вы:** Покажи вопросы и настройки приёма ответов в форме обратной связи.
30
+ >
31
+ > **Ассистент:** Показывает форму, её пункты, статус публикации и возможность принимать ответы. Ничего не меняется.
32
+ >
33
+ > **Вы:** Подготовь обязательный вопрос с оценкой от 1 до 5: «Как прошёл ваш опыт?» — после первого вопроса.
34
+ >
35
+ > **Ассистент:** Показывает целевую форму, позицию и предлагаемый вопрос, затем запрашивает подтверждение перед добавлением.
36
+ >
37
+ > **Вы:** Подтверждаю.
38
+ >
39
+ > **Ассистент:** Добавляет вопрос в форму. Он не публикует и не закрывает форму, пока вы не попросите об этом отдельно.
40
+
41
+ ## Содержание
42
+
43
+ - [Быстрый старт](#быстрый-старт)
44
+ - [Что можно поручить](#что-можно-поручить)
45
+ - [Как меняется форма](#как-меняется-форма)
46
+ - [Что может измениться](#что-может-измениться)
47
+ - [Как получить доступ](#как-получить-доступ)
48
+ - [Конфигурация](#конфигурация)
49
+ - [Данные, лимиты и работа в фоне](#данные-лимиты-и-работа-в-фоне)
50
+ - [Техническая документация](#техническая-документация)
51
+ - [Поддержка](#поддержка)
52
+
53
+ ## Быстрый старт
54
+
55
+ Нужны Node.js 20+, Google-аккаунт и OAuth-данные из проекта Google Cloud с включённым Google Forms API.
56
+
57
+ 1. [Подготовьте Google OAuth-доступ](#как-получить-доступ).
58
+ 2. Добавьте сервер в AI-приложение.
59
+ 3. Отправьте запрос, который только читает данные.
60
+
61
+ <details open>
62
+ <summary><strong>Codex</strong></summary>
63
+
64
+ <br>
65
+
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
+
68
+ **В командной строке:**
69
+
70
+ ```bash
71
+ 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
+ -- npx -y mcp-google-forms@latest
76
+ ```
77
+
78
+ ```bash
79
+ codex mcp list
80
+ ```
81
+
82
+ [Документация Codex MCP](https://learn.chatgpt.com/docs/extend/mcp?surface=cli)
83
+
84
+ </details>
85
+
86
+ <details>
87
+ <summary><strong>Claude Code</strong></summary>
88
+
89
+ <br>
90
+
91
+ ```bash
92
+ 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
+ --transport stdio --scope user google-forms \
97
+ -- npx -y mcp-google-forms@latest
98
+ ```
99
+
100
+ ```bash
101
+ claude mcp list
102
+ ```
103
+
104
+ [Документация Claude Code MCP](https://code.claude.com/docs/en/mcp)
105
+
106
+ </details>
107
+
108
+ <details>
109
+ <summary><strong>Claude Desktop</strong></summary>
110
+
111
+ <br>
112
+
113
+ Откройте **Settings → Developer → Edit Config** и добавьте:
114
+
115
+ ```json
116
+ {
117
+ "mcpServers": {
118
+ "google-forms": {
119
+ "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
+ }
126
+ }
127
+ }
128
+ }
129
+ ```
130
+
131
+ Если **Edit Config** недоступна, отредактируйте `~/Library/Application Support/Claude/claude_desktop_config.json` на macOS или `%APPDATA%\Claude\claude_desktop_config.json` на Windows.
132
+
133
+ [Документация Claude Desktop MCP](https://support.claude.com/en/articles/10949351-getting-started-with-local-mcp-servers-on-claude-desktop)
134
+
135
+ </details>
136
+
137
+ <details>
138
+ <summary><strong>Cursor</strong></summary>
139
+
140
+ <br>
141
+
142
+ Добавьте в `~/.cursor/mcp.json` на macOS/Linux или `%USERPROFILE%\.cursor\mcp.json` на Windows:
143
+
144
+ ```json
145
+ {
146
+ "mcpServers": {
147
+ "google-forms": {
148
+ "type": "stdio",
149
+ "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
+ }
156
+ }
157
+ }
158
+ }
159
+ ```
160
+
161
+ [Документация Cursor MCP](https://cursor.com/docs/mcp)
162
+
163
+ </details>
164
+
165
+ <details>
166
+ <summary><strong>VS Code</strong></summary>
167
+
168
+ <br>
169
+
170
+ Запустите **MCP: Open User Configuration** и добавьте:
171
+
172
+ ```json
173
+ {
174
+ "servers": {
175
+ "google-forms": {
176
+ "type": "stdio",
177
+ "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
+ }
184
+ }
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
+ ]
191
+ }
192
+ ```
193
+
194
+ Проверьте сервер командой **MCP: List Servers**.
195
+
196
+ [Документация VS Code MCP](https://code.visualstudio.com/docs/agent-customization/mcp-servers)
197
+
198
+ </details>
199
+
200
+ ## Что можно поручить
201
+
202
+ ### Проверить опрос и ответы
203
+
204
+ - Покажи вопросы, настройки приёма ответов и ссылку для респондентов.
205
+ - Сколько ответов пришло с понедельника? Суммируй обратную связь в свободной форме.
206
+ - Покажи один ответ по его ID.
207
+
208
+ ### Собрать и улучшить форму
209
+
210
+ - Создай RSVP-форму с именем, выбором питания и датой приезда.
211
+ - Добавь обязательный вопрос с оценкой, выпадающий список, дату, время, один или несколько вариантов или текстовое поле.
212
+ - Перемести вопрос или обнови название, описание, quiz mode или сбор email.
213
+
214
+ ### Опубликовать и настроить уведомления
215
+
216
+ - Опубликуй готовую форму и покажи ссылку для респондентов.
217
+ - Останови приём новых ответов, не удаляя форму.
218
+ - Создай, продли или удали Cloud Pub/Sub watch для новых отправок.
219
+
220
+ ## Как меняется форма
221
+
222
+ 1. `create_form` создаёт **форму**, которая по умолчанию не опубликована.
223
+ 2. Вопросы — это **пункты**, которые определяются позицией в форме.
224
+ 3. Публикация открывает форму для респондентов; закрытие приёма ответов оставляет форму опубликованной, но не принимает новые отправки.
225
+ 4. Ответы — отдельная read-only запись. API не может отправить, изменить или удалить ответ респондента.
226
+
227
+ Через Forms API нельзя создать вопрос с загрузкой файла, хотя существующий такой вопрос можно прочитать. Старые формы, созданные до модели публикации Google, могут не поддерживать настройки публикации.
228
+
229
+ ## Что может измениться
230
+
231
+ | Операция | Что происходит | Граница подтверждения |
232
+ |---|---|---|
233
+ | Проверка формы и её ответов | Читает структуру и отправки | Ничего не меняет |
234
+ | Создание формы | Добавляет неопубликованную форму | Меняет Google Forms |
235
+ | Добавление или перемещение вопроса | Меняет пункты формы | Меняет форму |
236
+ | Обновление данных, настроек или вопроса | Меняет название, настройки или выбранный вопрос | Меняет форму |
237
+ | Публикация, снятие с публикации, открытие или закрытие ответов | Меняет доступность формы | Меняет доступ для респондентов |
238
+ | Удаление пункта | Удаляет выбранный вопрос | Разрушительно |
239
+ | Управление Pub/Sub watch | Создаёт, продлевает или удаляет доставку уведомлений | Потенциально разрушительно |
240
+ | Технический запрос API | Может вызвать метод API без отдельного инструмента | Потенциально разрушительно |
241
+
242
+ Как AI-приложение просит подтверждение, определяет само приложение. Сервер помечает операции чтения, записи и удаления, чтобы оно отличило проверку от рабочего изменения.
243
+
244
+ ## Как получить доступ
245
+
246
+ Google Forms требует OAuth 2.0: одного API-ключа недостаточно.
247
+
248
+ 1. Создайте или выберите проект Google Cloud и включите **Google Forms API**.
249
+ 2. Настройте OAuth consent screen и создайте OAuth-клиент типа **Desktop app**.
250
+ 3. Авторизуйте Google-аккаунт, который владеет формами или может их редактировать. [OAuth 2.0 Playground](https://developers.google.com/oauthplayground) поможет получить refresh token, если включить **Use your own OAuth credentials**.
251
+ 4. Запросите оба scope:
252
+
253
+ ```text
254
+ https://www.googleapis.com/auth/forms.body
255
+ https://www.googleapis.com/auth/forms.responses.readonly
256
+ ```
257
+
258
+ Refresh token OAuth-приложения в режиме Testing может истечь через семь дней. Для долгого доступа опубликуйте OAuth-приложение или используйте Internal-приложение в домене Workspace. Храните client secret и refresh token как пароли.
259
+
260
+ ## Конфигурация
261
+
262
+ | Переменная | Обязательна | Описание |
263
+ |---|---|---|
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-тройке. |
268
+ | `GOOGLE_FORMS_API_BASE` | Нет | Переопределяет базовый URL Google Forms API. |
269
+ | `GOOGLE_FORMS_TIMEOUT_MS` | Нет | Тайм-аут одного запроса; по умолчанию `60000` мс. |
270
+ | `GOOGLE_FORMS_MAX_RETRIES` | Нет | Повторы временных ошибок; по умолчанию `3`. |
271
+
272
+ \* Передайте OAuth-тройку или access token.
273
+
274
+ ## Данные, лимиты и работа в фоне
275
+
276
+ - **Запросы идут в Google Forms.** Локальный сервер обновляет OAuth-токены Google и вызывает Forms API. Анонимная телеметрия содержит ID установки, версию пакета, версии AI-клиента и платформы и имена инструментов — но не OAuth-токены, данные формы, аргументы или промпты. Чтобы отключить её, задайте `ASKADS_TELEMETRY=0`.
277
+ - **У Google есть поминутные квоты.** Документированные лимиты: 975 чтений на проект, 450 вызовов `list_responses` и 375 записей. При `429` сервер использует задержку; чтение также повторяется после сетевых и `5xx` ошибок, а запись после неопределённой ошибки не повторяется.
278
+ - **Постоянного опроса нет.** Сервер работает только при вызове. Pub/Sub watch может уведомить вашу инфраструктуру о новых ответах; если AI-приложение поддерживает задания по расписанию, оно также может периодически проверять ответы.
279
+
280
+ ## Техническая документация
281
+
282
+ - [Каталог MCP-возможностей](./docs/capabilities/index.md) — страницы по пользовательским задачам для каждого инструмента.
283
+ - [Все инструменты и параметры](./docs/TOOLS.md)
284
+ - [Документация по разработке](./docs/DEVELOPMENT.md)
285
+ - [Документация по публикации](./docs/PUBLISHING.md)
286
+ - [Справочник Google Forms API](https://developers.google.com/forms/api)
287
+
288
+ ## Поддержка
289
+
290
+ Нашли ошибку или не хватает сценария? [Создайте issue](https://github.com/A1-x-Tech/mcp-google-forms/issues) или напишите в [Telegram](https://t.me/a1_mcp).
291
+
292
+ <br>
293
+
294
+ <p align="center">
295
+ <img src="https://github.com/ztemerbekov/a1-yandex-kit-skills/raw/main/assets/images/mona-hifive-yandex-kit-warm.gif" alt="Две Моны дают пять" width="256">
296
+ </p>
297
+
298
+ <p align="center">
299
+ Вы дочитали до конца!
300
+ </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. */
@@ -89,11 +90,15 @@ export class GoogleFormsClient {
89
90
  * Returns a valid Bearer token. With the refresh triple configured, mints an
90
91
  * access token from the refresh token and caches it until shortly before it
91
92
  * expires (concurrent callers share one in-flight refresh); otherwise the
92
- * static GOOGLE_FORMS_ACCESS_TOKEN is used as-is.
93
+ * static GOOGLE_FORMS_ACCESS_TOKEN is used as-is. With neither configured,
94
+ * throws {@link CredentialsError} BEFORE any fetch — a missing setup must
95
+ * never enter the retry/backoff loop or trigger the 401 re-mint, because no
96
+ * amount of retrying mints credentials.
93
97
  */
94
98
  async accessToken(forceRefresh = false) {
95
99
  if (!this.canRefresh()) {
96
- // loadConfig guarantees accessToken is set when the refresh triple is absent.
100
+ if (!this.config.accessToken)
101
+ throw new CredentialsError();
97
102
  return this.config.accessToken;
98
103
  }
99
104
  if (!forceRefresh && this.cachedToken && Date.now() < this.cachedToken.expiresAt) {
@@ -260,12 +265,25 @@ export class GoogleFormsClient {
260
265
  info: compact({ title: p.title, documentTitle: p.documentTitle }),
261
266
  });
262
267
  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 };
268
+ // The form already exists here; the Forms API has no list endpoint, so a
269
+ // thrown publish error would lose the only copy of the formId and push
270
+ // the caller into re-creating (duplicating) the form.
271
+ try {
272
+ const published = await this.setPublishSettings({
273
+ formId: form.formId,
274
+ isPublished: true,
275
+ isAcceptingResponses: true,
276
+ });
277
+ return { ...form, publishSettings: published.publishSettings };
278
+ }
279
+ catch (err) {
280
+ return {
281
+ ...form,
282
+ published: false,
283
+ publish_error: err instanceof Error ? err.message : String(err),
284
+ next_step: "The form was created but publishing failed — call set_publish_settings with this formId; do not call create_form again.",
285
+ };
286
+ }
269
287
  }
270
288
  return form;
271
289
  }
@@ -281,12 +299,16 @@ export class GoogleFormsClient {
281
299
  writeControl: opts.requiredRevisionId ? { requiredRevisionId: opts.requiredRevisionId } : undefined,
282
300
  }));
283
301
  }
284
- /** Updates title / description / documentTitle with a computed updateMask. */
302
+ /**
303
+ * Updates title / description with a computed updateMask. Info.documentTitle
304
+ * is output-only in batchUpdate: the Drive file name is set at creation and
305
+ * renamed only through the Drive API, which this server does not cover.
306
+ */
285
307
  async updateFormInfo(p) {
286
- const info = compact({ title: p.title, description: p.description, documentTitle: p.documentTitle });
308
+ const info = compact({ title: p.title, description: p.description });
287
309
  const mask = Object.keys(info).join(",");
288
310
  if (!mask)
289
- throw new Error("At least one of title, description or document_title is required.");
311
+ throw new Error("At least one of title or description is required.");
290
312
  return this.batchUpdate(p.formId, [{ updateFormInfo: { info, updateMask: mask } }]);
291
313
  }
292
314
  /** 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,44 @@ 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
+ /**
14
+ * Prose handed to the calling model in the `initialize` result — the only place
15
+ * it learns what the tool list cannot say: which Google product this API is,
16
+ * what the API refuses to do, and the behaviours that make a naive loop
17
+ * expensive, lossy or duplicating.
18
+ */
19
+ const INSTRUCTIONS = "Google Forms API v1 builds and reads Google Forms — not Sheets, Docs or Drive: the linked " +
20
+ "responses spreadsheet (linkedSheetId), and deleting, sharing or renaming the Drive file, are " +
21
+ "out of reach. Responses are read-only: no endpoint submits or edits one. File-upload questions " +
22
+ "cannot be created; grids need raw_request. New forms take only a title/documentTitle (the Drive " +
23
+ "file name — settable only at creation) and start UNPUBLISHED until published; legacy forms " +
24
+ "reject set_publish_settings. Items are addressed by 0-based position, not itemId, and each " +
25
+ "delete or move shifts the rest — re-read get_form between mutations; update_question clears " +
26
+ "any masked field it omits. Quiz mode alone grades nothing: add_question cannot set points — " +
27
+ "write questionItem.question.grading per question via update_question. Per-minute project quotas: 975 " +
28
+ "reads, 375 writes, 450 list_responses — poll with submitted_after (the only filter; sort " +
29
+ "client-side), don't re-list. Absent respondentEmail/totalScore means email collection or grading " +
30
+ "is off, not lost data; auth that suddenly breaks usually means the consent screen is still in " +
31
+ "Testing, where refresh tokens die after 7 days. Writes hit a live form and are never retried " +
32
+ "after a 5xx or timeout: check with get_form before re-sending; delete_item is final.";
33
+ /**
34
+ * Prepended to INSTRUCTIONS when no credentials are configured. The model reads
35
+ * this before it picks a tool, so an unconfigured session opens with the fix
36
+ * rather than with a failed call. There is no in-chat login here: credentials
37
+ * come only from the environment, so the fix is an operator action + restart.
38
+ */
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. ";
13
44
  /** Reads the package version so the server reports its real version to MCP clients. */
14
45
  function readVersion() {
15
46
  try {
@@ -21,21 +52,27 @@ function readVersion() {
21
52
  }
22
53
  }
23
54
  /**
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.
55
+ * Loads the config without dying on a bad value. A server that exits here never
56
+ * completes the MCP handshake, so the user sees a dead server and no reason.
57
+ * Instead the problem is carried into the session, where the model can read it
58
+ * and relay it: the config degrades to "no credentials" and every tool call
59
+ * fails with the actionable message.
28
60
  */
29
- async function loadConfigOrExit(telemetry) {
61
+ function loadConfigOrDegraded(telemetry) {
30
62
  try {
31
- return loadConfig();
63
+ return { config: loadConfig() };
32
64
  }
33
65
  catch (err) {
34
66
  if (!(err instanceof ConfigError))
35
67
  throw err;
36
68
  console.error(`Error: ${err.message}`);
37
- await telemetry.sendBlocking("startup_failed", { reason: err.reason });
38
- process.exit(1);
69
+ // Fire-and-forget now that the process survives: the historical
70
+ // `startup_failed` funnel stays comparable, but nothing blocks startup.
71
+ telemetry.send("startup_failed", { reason: err.reason });
72
+ return {
73
+ config: { apiBase: process.env.GOOGLE_FORMS_API_BASE || DEFAULT_BASE },
74
+ problem: err,
75
+ };
39
76
  }
40
77
  }
41
78
  async function main() {
@@ -43,16 +80,30 @@ async function main() {
43
80
  // opt out with ASKADS_TELEMETRY=0. Built before the config so missing
44
81
  // credentials can be reported; wired to the server before tools register.
45
82
  const telemetry = new Telemetry(readVersion());
46
- const config = await loadConfigOrExit(telemetry);
83
+ const { config, problem } = loadConfigOrDegraded(telemetry);
47
84
  const client = new GoogleFormsClient(config);
85
+ // Decided once, at startup: credentials come only from the environment, so
86
+ // "restart after setting the variables" is the accurate advice to give.
87
+ const connected = hasCredentials(config);
48
88
  const server = new McpServer({
49
89
  name: "mcp-google-forms",
50
90
  version: readVersion(),
91
+ },
92
+ // Surfaces in the initialize result, before the client sees a single tool.
93
+ {
94
+ instructions: connected
95
+ ? INSTRUCTIONS
96
+ : UNCONFIGURED_PREFIX + (problem ? `Configuration problem: ${problem.message} ` : "") + INSTRUCTIONS,
51
97
  });
52
98
  instrumentToolCalls(server, telemetry);
53
99
  server.server.oninitialized = () => {
54
100
  telemetry.setClientInfo(server.server.getClientVersion());
55
- telemetry.send("server_start");
101
+ // Split on purpose: `server_start` keeps meaning "a usable install started",
102
+ // so the unconfigured case gets its own event instead of inflating that number.
103
+ if (connected)
104
+ telemetry.send("server_start");
105
+ else
106
+ telemetry.send("unconfigured_start", { reason: problem?.reason ?? "missing_credentials" });
56
107
  };
57
108
  registerFormTools(server, client);
58
109
  registerItemTools(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);
@@ -4,7 +4,7 @@ export function registerFormTools(server, client) {
4
4
  server.registerTool("create_form", {
5
5
  title: "Create a form",
6
6
  annotations: WRITE,
7
- description: "Creates a new Google Form and returns it (formId, revisionId, responderUri, publishSettings). The API only accepts a title and an optional document title at creation — add questions with add_question and change settings with update_form_settings afterwards. IMPORTANT: API-created forms are UNPUBLISHED by default and do not accept responses; pass publish=true to publish immediately, or call set_publish_settings later. Share the responderUri with respondents once published.",
7
+ description: "Creates a new Google Form and returns it (formId, revisionId, responderUri, publishSettings). The API only accepts a title and an optional document title at creation (the Drive file name — it cannot be changed later through this API) — add questions with add_question and change settings with update_form_settings afterwards. IMPORTANT: API-created forms are UNPUBLISHED by default and do not accept responses; pass publish=true to publish immediately, or call set_publish_settings later. If the chained publish step fails, the form still exists: the result carries formId with published:false and publish_error — finish with set_publish_settings, never create_form again. Share the responderUri with respondents once published.",
8
8
  inputSchema: {
9
9
  title: z.string().min(1).describe("The form title shown to respondents."),
10
10
  document_title: z
@@ -40,16 +40,15 @@ export function registerFormTools(server, client) {
40
40
  server.registerTool("update_form_info", {
41
41
  title: "Update form info",
42
42
  annotations: UPDATE,
43
- description: "Changes the form's title, description and/or document title (the Drive file name). Only the provided fields are touched (the updateMask is computed automatically); at least one field is required. Returns the batchUpdate replies with the new revisionId.",
43
+ description: "Changes the form's title and/or description. Only the provided fields are touched (the updateMask is computed automatically); at least one field is required. The document title (the Drive file name) is set once at create_form and cannot be changed through the Forms API — renaming the file needs the Drive API, which this server does not cover. Returns the batchUpdate replies with the new revisionId.",
44
44
  inputSchema: {
45
45
  form_id: formIdSchema(),
46
46
  title: z.string().optional().describe("New form title shown to respondents."),
47
47
  description: z.string().optional().describe("New form description shown under the title."),
48
- document_title: z.string().optional().describe("New document name in Google Drive."),
49
48
  },
50
- }, async ({ form_id, title, description, document_title }) => {
49
+ }, async ({ form_id, title, description }) => {
51
50
  try {
52
- return ok(await client.updateFormInfo({ formId: form_id, title, description, documentTitle: document_title }));
51
+ return ok(await client.updateFormInfo({ formId: form_id, title, description }));
53
52
  }
54
53
  catch (e) {
55
54
  return fail(e);
@@ -58,7 +57,7 @@ export function registerFormTools(server, client) {
58
57
  server.registerTool("update_form_settings", {
59
58
  title: "Update form settings",
60
59
  annotations: UPDATE,
61
- description: "Toggles quiz mode (grading with points) and/or the email collection mode. email_collection_type: DO_NOT_COLLECT, VERIFIED (respondent must be signed in; email verified) or RESPONDER_INPUT (respondent types an email). At least one field is required; only the provided fields are touched.",
60
+ description: "Toggles quiz mode (grading with points) and/or the email collection mode. Quiz mode only enables grading — points, correct answers and feedback are set per question afterwards via update_question with the questionItem.question.grading mask (add_question cannot set them). email_collection_type: DO_NOT_COLLECT, VERIFIED (respondent must be signed in; email verified) or RESPONDER_INPUT (respondent types an email). At least one field is required; only the provided fields are touched.",
62
61
  inputSchema: {
63
62
  form_id: formIdSchema(),
64
63
  is_quiz: z.boolean().optional().describe("Turn quiz mode on/off (enables per-question grading)."),
@@ -4,7 +4,7 @@ export function registerItemTools(server, client) {
4
4
  server.registerTool("add_question", {
5
5
  title: "Add a question",
6
6
  annotations: WRITE,
7
- description: "Adds a question to the form (a convenience wrapper over batchUpdate createItem). Types: text (short answer), paragraph (long answer), radio (single choice), checkbox (multiple choice), dropdown, scale (linear scale low..high), date, time, rating (stars/hearts/thumbs). Choice types require options[]. Returns the created itemId and questionId from the batchUpdate replies. index inserts at that 0-based position; omit it to append at the end (costs one extra read to count items). File-upload questions cannot be created via the API, and question grids (questionGroupItem) need raw_request with a batchUpdate body.",
7
+ description: "Adds a question to the form (a convenience wrapper over batchUpdate createItem). Types: text (short answer), paragraph (long answer), radio (single choice), checkbox (multiple choice), dropdown, scale (linear scale low..high), date, time, rating (stars/hearts/thumbs). Choice types require options[]. Returns the created itemId and questionId from the batchUpdate replies. index inserts at that 0-based position; omit it to append at the end (costs one extra read to count items). Quiz grading (points, correct answers, feedback) cannot be set here — after adding, use update_question with the questionItem.question.grading mask. File-upload questions cannot be created via the API, and question grids (questionGroupItem) need raw_request with a batchUpdate body.",
8
8
  inputSchema: {
9
9
  form_id: formIdSchema(),
10
10
  title: z.string().min(1).describe("The question text shown to respondents."),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-google-forms",
3
- "version": "0.1.1",
3
+ "version": "1.1.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",
@@ -108,6 +108,12 @@ test("dist binary completes a real MCP handshake over stdio and lists every tool
108
108
  assert.equal(server?.name, "mcp-google-forms");
109
109
  assert.match(String(server?.version), /^\d+\.\d+\.\d+$/);
110
110
 
111
+ // The instructions the calling model reads before it picks any tool.
112
+ const instructions = client.getInstructions();
113
+ assert.equal(typeof instructions, "string");
114
+ assert.ok(instructions.trim().length > 0, "initialize result carries no instructions");
115
+ assert.match(instructions, /Google Forms API v1/);
116
+
111
117
  const { tools } = await client.listTools();
112
118
  assert.deepEqual(tools.map((t) => t.name).sort(), ALL_TOOLS);
113
119
 
@@ -118,3 +124,46 @@ test("dist binary completes a real MCP handshake over stdio and lists every tool
118
124
  await client.close();
119
125
  }
120
126
  });
127
+
128
+ /**
129
+ * The degraded-start contract: without any credentials the binary used to
130
+ * exit(1) before the handshake, leaving the client a dead server and no reason.
131
+ * It must now start, list every tool, open the instructions with the fix, and
132
+ * answer a tool call with the actionable error — offline: the CredentialsError
133
+ * fires before any fetch, so this test never touches the network.
134
+ */
135
+ test("dist binary starts without credentials: handshake, tool list, actionable call error", async () => {
136
+ const env = Object.fromEntries(
137
+ Object.entries(process.env).filter(
138
+ ([key, value]) => value !== undefined && !key.startsWith("GOOGLE_FORMS_"),
139
+ ),
140
+ );
141
+ env.ASKADS_TELEMETRY = "0"; // keep the suite offline
142
+ const transport = new StdioClientTransport({
143
+ command: process.execPath,
144
+ args: [fileURLToPath(new URL("../dist/index.js", import.meta.url))],
145
+ env,
146
+ stderr: "pipe",
147
+ });
148
+ const client = new Client({ name: "dist-smoke-unconfigured", version: "0.0.0" });
149
+ await client.connect(transport);
150
+ try {
151
+ // The model must read the fix before it picks a tool.
152
+ const instructions = client.getInstructions() ?? "";
153
+ assert.match(instructions, /not connected/);
154
+ assert.match(instructions, /GOOGLE_FORMS_CLIENT_ID/);
155
+ assert.match(instructions, /restart/);
156
+
157
+ const { tools } = await client.listTools();
158
+ assert.deepEqual(tools.map((t) => t.name).sort(), ALL_TOOLS);
159
+
160
+ // A tool call fails with the exact message instead of killing the server.
161
+ const result = await client.callTool({ name: "get_form", arguments: { form_id: "smoke-form" } });
162
+ assert.equal(result.isError, true);
163
+ const text = result.content.map((c) => c.text ?? "").join(" ");
164
+ assert.match(text, /Google OAuth credentials are required: set GOOGLE_FORMS_CLIENT_ID/);
165
+ assert.match(text, /restart the server/);
166
+ } finally {
167
+ await client.close();
168
+ }
169
+ });