mcp-google-forms 0.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/LICENSE +21 -0
- package/README.md +221 -0
- package/dist/client.js +389 -0
- package/dist/config.js +54 -0
- package/dist/index.js +69 -0
- package/dist/telemetry.js +120 -0
- package/dist/tools/forms.js +106 -0
- package/dist/tools/items.js +131 -0
- package/dist/tools/raw.js +30 -0
- package/dist/tools/responses.js +51 -0
- package/dist/tools/util.js +64 -0
- package/dist/tools/watches.js +57 -0
- package/dist/types.js +44 -0
- package/package.json +60 -0
- package/test/dist-smoke.test.js +120 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 A1 x Tech
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
# Google Forms MCP
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/mcp-google-forms)
|
|
4
|
+
[](https://github.com/A1-x-Tech/mcp-google-forms/actions/workflows/ci.yml)
|
|
5
|
+
[](https://glama.ai/mcp/servers/A1-x-Tech/mcp-google-forms)
|
|
6
|
+
[](./LICENSE)
|
|
7
|
+
|
|
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.
|
|
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.
|
|
15
|
+
|
|
16
|
+
## Quick start
|
|
17
|
+
|
|
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)):
|
|
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
|
|
27
|
+
```
|
|
28
|
+
|
|
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).
|
|
76
|
+
|
|
77
|
+
<details open>
|
|
78
|
+
<summary><b>Claude Code</b></summary>
|
|
79
|
+
|
|
80
|
+
```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 \
|
|
85
|
+
-- npx -y mcp-google-forms
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
</details>
|
|
89
|
+
|
|
90
|
+
<details>
|
|
91
|
+
<summary><b>Claude Desktop</b></summary>
|
|
92
|
+
|
|
93
|
+
`claude_desktop_config.json` — macOS `~/Library/Application Support/Claude/`, Windows `%APPDATA%\Claude\`
|
|
94
|
+
|
|
95
|
+
```json
|
|
96
|
+
{
|
|
97
|
+
"mcpServers": {
|
|
98
|
+
"google-forms": {
|
|
99
|
+
"command": "npx",
|
|
100
|
+
"args": ["-y", "mcp-google-forms"],
|
|
101
|
+
"env": {
|
|
102
|
+
"GOOGLE_FORMS_CLIENT_ID": "your_client_id",
|
|
103
|
+
"GOOGLE_FORMS_CLIENT_SECRET": "your_client_secret",
|
|
104
|
+
"GOOGLE_FORMS_REFRESH_TOKEN": "your_refresh_token"
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
</details>
|
|
112
|
+
|
|
113
|
+
<details>
|
|
114
|
+
<summary><b>Cursor</b></summary>
|
|
115
|
+
|
|
116
|
+
`~/.cursor/mcp.json` (or `.cursor/mcp.json` in the project)
|
|
117
|
+
|
|
118
|
+
```json
|
|
119
|
+
{
|
|
120
|
+
"mcpServers": {
|
|
121
|
+
"google-forms": {
|
|
122
|
+
"command": "npx",
|
|
123
|
+
"args": ["-y", "mcp-google-forms"],
|
|
124
|
+
"env": {
|
|
125
|
+
"GOOGLE_FORMS_CLIENT_ID": "your_client_id",
|
|
126
|
+
"GOOGLE_FORMS_CLIENT_SECRET": "your_client_secret",
|
|
127
|
+
"GOOGLE_FORMS_REFRESH_TOKEN": "your_refresh_token"
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
</details>
|
|
135
|
+
|
|
136
|
+
<details>
|
|
137
|
+
<summary><b>VS Code</b></summary>
|
|
138
|
+
|
|
139
|
+
`.vscode/mcp.json` — note the `servers` key (not `mcpServers`)
|
|
140
|
+
|
|
141
|
+
```json
|
|
142
|
+
{
|
|
143
|
+
"servers": {
|
|
144
|
+
"google-forms": {
|
|
145
|
+
"type": "stdio",
|
|
146
|
+
"command": "npx",
|
|
147
|
+
"args": ["-y", "mcp-google-forms"],
|
|
148
|
+
"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"
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
</details>
|
|
159
|
+
|
|
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).
|
|
193
|
+
|
|
194
|
+
## Configuration
|
|
195
|
+
|
|
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. |
|
|
205
|
+
|
|
206
|
+
\* Either the three refresh-flow variables together, **or** `GOOGLE_FORMS_ACCESS_TOKEN`.
|
|
207
|
+
|
|
208
|
+
## Documentation
|
|
209
|
+
|
|
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.
|
|
213
|
+
|
|
214
|
+
## Support
|
|
215
|
+
|
|
216
|
+
Questions, ideas, issues — Telegram [@gistrec](http://t.me/gistrec) or
|
|
217
|
+
[GitHub issues](https://github.com/A1-x-Tech/mcp-google-forms/issues).
|
|
218
|
+
|
|
219
|
+
## License
|
|
220
|
+
|
|
221
|
+
MIT — see [LICENSE](./LICENSE).
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
import { GoogleFormsError } from "./types.js";
|
|
2
|
+
/** Google's OAuth2 token endpoint — refresh tokens are exchanged here. */
|
|
3
|
+
const TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
4
|
+
/** Maps a normalized rating icon to the API's wire value. */
|
|
5
|
+
function mapRatingIcon(icon) {
|
|
6
|
+
return { star: "STAR", heart: "HEART", thumb_up: "THUMB_UP" }[icon];
|
|
7
|
+
}
|
|
8
|
+
/** Maps a normalized choice type to the API's wire value. */
|
|
9
|
+
function mapChoiceType(type) {
|
|
10
|
+
return { radio: "RADIO", checkbox: "CHECKBOX", dropdown: "DROP_DOWN" }[type];
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Builds a Forms API Item (questionItem) from the normalized add_question
|
|
14
|
+
* vocabulary. Pure wire mapping — throws on inputs the API would reject
|
|
15
|
+
* (e.g. a choice question without options).
|
|
16
|
+
*/
|
|
17
|
+
export function buildQuestionItem(p) {
|
|
18
|
+
return compact({
|
|
19
|
+
title: p.title,
|
|
20
|
+
description: p.description,
|
|
21
|
+
questionItem: {
|
|
22
|
+
question: compact({ required: p.required, ...buildQuestion(p) }),
|
|
23
|
+
},
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
function buildQuestion(p) {
|
|
27
|
+
switch (p.type) {
|
|
28
|
+
case "text":
|
|
29
|
+
return { textQuestion: { paragraph: false } };
|
|
30
|
+
case "paragraph":
|
|
31
|
+
return { textQuestion: { paragraph: true } };
|
|
32
|
+
case "radio":
|
|
33
|
+
case "checkbox":
|
|
34
|
+
case "dropdown": {
|
|
35
|
+
if (!p.options || p.options.length === 0) {
|
|
36
|
+
throw new Error(`"options" is required for a ${p.type} question (the list of choices).`);
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
choiceQuestion: compact({
|
|
40
|
+
type: mapChoiceType(p.type),
|
|
41
|
+
options: p.options.map((value) => ({ value })),
|
|
42
|
+
shuffle: p.shuffle,
|
|
43
|
+
}),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
case "scale":
|
|
47
|
+
return {
|
|
48
|
+
scaleQuestion: compact({
|
|
49
|
+
low: p.low ?? 1,
|
|
50
|
+
high: p.high ?? 5,
|
|
51
|
+
lowLabel: p.lowLabel,
|
|
52
|
+
highLabel: p.highLabel,
|
|
53
|
+
}),
|
|
54
|
+
};
|
|
55
|
+
case "date":
|
|
56
|
+
return { dateQuestion: compact({ includeTime: p.includeTime, includeYear: p.includeYear }) };
|
|
57
|
+
case "time":
|
|
58
|
+
return { timeQuestion: compact({ duration: p.duration }) };
|
|
59
|
+
case "rating":
|
|
60
|
+
return {
|
|
61
|
+
ratingQuestion: {
|
|
62
|
+
ratingScaleLevel: p.ratingScaleLevel ?? 5,
|
|
63
|
+
iconType: mapRatingIcon(p.ratingIconType ?? "star"),
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export class GoogleFormsClient {
|
|
69
|
+
config;
|
|
70
|
+
base;
|
|
71
|
+
timeoutMs;
|
|
72
|
+
maxRetries;
|
|
73
|
+
retryBaseMs;
|
|
74
|
+
/** Cached access token from the refresh flow, with its expiry. */
|
|
75
|
+
cachedToken;
|
|
76
|
+
/** In-flight refresh, deduping concurrent token requests. */
|
|
77
|
+
refreshInFlight;
|
|
78
|
+
constructor(config) {
|
|
79
|
+
this.config = config;
|
|
80
|
+
this.base = config.apiBase.endsWith("/") ? config.apiBase : config.apiBase + "/";
|
|
81
|
+
this.timeoutMs = config.timeoutMs ?? 60_000;
|
|
82
|
+
this.maxRetries = config.maxRetries ?? 3;
|
|
83
|
+
this.retryBaseMs = config.retryBaseMs ?? 500;
|
|
84
|
+
}
|
|
85
|
+
canRefresh() {
|
|
86
|
+
return Boolean(this.config.refreshToken && this.config.clientId && this.config.clientSecret);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Returns a valid Bearer token. With the refresh triple configured, mints an
|
|
90
|
+
* access token from the refresh token and caches it until shortly before it
|
|
91
|
+
* expires (concurrent callers share one in-flight refresh); otherwise the
|
|
92
|
+
* static GOOGLE_FORMS_ACCESS_TOKEN is used as-is.
|
|
93
|
+
*/
|
|
94
|
+
async accessToken(forceRefresh = false) {
|
|
95
|
+
if (!this.canRefresh()) {
|
|
96
|
+
// loadConfig guarantees accessToken is set when the refresh triple is absent.
|
|
97
|
+
return this.config.accessToken;
|
|
98
|
+
}
|
|
99
|
+
if (!forceRefresh && this.cachedToken && Date.now() < this.cachedToken.expiresAt) {
|
|
100
|
+
return this.cachedToken.value;
|
|
101
|
+
}
|
|
102
|
+
if (!this.refreshInFlight) {
|
|
103
|
+
this.refreshInFlight = this.refreshAccessToken().finally(() => {
|
|
104
|
+
this.refreshInFlight = undefined;
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
return this.refreshInFlight;
|
|
108
|
+
}
|
|
109
|
+
/** Exchanges the refresh token for a fresh access token at Google's token endpoint. */
|
|
110
|
+
async refreshAccessToken() {
|
|
111
|
+
const body = new URLSearchParams({
|
|
112
|
+
client_id: this.config.clientId,
|
|
113
|
+
client_secret: this.config.clientSecret,
|
|
114
|
+
refresh_token: this.config.refreshToken,
|
|
115
|
+
grant_type: "refresh_token",
|
|
116
|
+
}).toString();
|
|
117
|
+
const { res, text } = await this.fetchWithTimeout(TOKEN_URL, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body }, "oauth2 token refresh");
|
|
118
|
+
let data;
|
|
119
|
+
try {
|
|
120
|
+
data = JSON.parse(text);
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
data = text;
|
|
124
|
+
}
|
|
125
|
+
if (!res.ok)
|
|
126
|
+
throw new GoogleFormsError(res.status, data);
|
|
127
|
+
const token = data.access_token;
|
|
128
|
+
if (typeof token !== "string" || !token) {
|
|
129
|
+
throw new Error("OAuth2 token endpoint returned no access_token.");
|
|
130
|
+
}
|
|
131
|
+
const expiresIn = Number(data.expires_in);
|
|
132
|
+
const ttl = Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : 3600;
|
|
133
|
+
// Refresh 60s ahead of the real expiry so requests never race a dying token.
|
|
134
|
+
this.cachedToken = { value: token, expiresAt: Date.now() + Math.max(ttl - 60, 30) * 1000 };
|
|
135
|
+
return token;
|
|
136
|
+
}
|
|
137
|
+
/** Verifies the OAuth credentials by minting a fresh access token (refresh flow only). */
|
|
138
|
+
async authCheck() {
|
|
139
|
+
if (!this.canRefresh()) {
|
|
140
|
+
throw new Error("authCheck needs the refresh flow (GOOGLE_FORMS_CLIENT_ID / _CLIENT_SECRET / _REFRESH_TOKEN); with a static GOOGLE_FORMS_ACCESS_TOKEN fetch a form instead.");
|
|
141
|
+
}
|
|
142
|
+
await this.accessToken(true);
|
|
143
|
+
return { ok: true, auth: "refresh_token" };
|
|
144
|
+
}
|
|
145
|
+
/** Backoff before a retry: honors Retry-After when present, else exponential (capped at 30s). */
|
|
146
|
+
backoffMs(attempt, res) {
|
|
147
|
+
const retryAfter = res ? Number(res.headers.get("Retry-After")) : NaN;
|
|
148
|
+
if (Number.isFinite(retryAfter) && retryAfter > 0)
|
|
149
|
+
return Math.min(retryAfter, 30) * 1000;
|
|
150
|
+
return Math.min(this.retryBaseMs * 2 ** attempt, 30_000);
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* fetch with an AbortController timeout. Reads the response body inside the
|
|
154
|
+
* guarded zone so the timeout also covers a slow or drip-feeding body, not
|
|
155
|
+
* just the initial headers, and returns the text alongside the response.
|
|
156
|
+
*/
|
|
157
|
+
async fetchWithTimeout(url, init, label) {
|
|
158
|
+
const controller = new AbortController();
|
|
159
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
160
|
+
try {
|
|
161
|
+
const res = await fetch(url, { ...init, signal: controller.signal });
|
|
162
|
+
const text = await res.text();
|
|
163
|
+
return { res, text };
|
|
164
|
+
}
|
|
165
|
+
catch (err) {
|
|
166
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
167
|
+
throw new Error(`Request to "${label}" timed out after ${this.timeoutMs}ms`);
|
|
168
|
+
}
|
|
169
|
+
throw err;
|
|
170
|
+
}
|
|
171
|
+
finally {
|
|
172
|
+
clearTimeout(timer);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Low-level request to a Google Forms API path (e.g. "v1/forms/abc"). Auth is
|
|
177
|
+
* a Bearer token (refreshed transparently; a 401 forces one re-mint + retry).
|
|
178
|
+
* 429 is always retried with backoff; 5xx and network errors/timeouts are
|
|
179
|
+
* retried only for GET — the Forms API has real writes, and retrying a POST
|
|
180
|
+
* after the write committed would duplicate the item/form/watch. Any other
|
|
181
|
+
* non-2xx throws a {@link GoogleFormsError}.
|
|
182
|
+
*/
|
|
183
|
+
async request(method, path, body, query) {
|
|
184
|
+
// Guard method !== "GET" keeps undici from crashing on a GET-with-body.
|
|
185
|
+
const hasBody = body !== undefined && method !== "GET";
|
|
186
|
+
// Resolve the path against the API base, then reject anything that escaped
|
|
187
|
+
// to a foreign origin (an absolute "https://evil/x" or a "\\evil/x" slipped
|
|
188
|
+
// through raw_request) so the Bearer token can never leak to another host.
|
|
189
|
+
const url = new URL(path.replace(/^\//, ""), this.base);
|
|
190
|
+
if (url.origin !== new URL(this.base).origin) {
|
|
191
|
+
throw new Error(`raw_request path must be a relative API path (resolved to foreign origin ${url.origin})`);
|
|
192
|
+
}
|
|
193
|
+
if (query) {
|
|
194
|
+
for (const [key, value] of Object.entries(query)) {
|
|
195
|
+
if (value !== undefined)
|
|
196
|
+
url.searchParams.set(key, String(value));
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
const target = url.toString();
|
|
200
|
+
// Writes must not be replayed on ambiguous failures (see the retry gate below).
|
|
201
|
+
const idempotent = method === "GET";
|
|
202
|
+
let refreshedOn401 = false;
|
|
203
|
+
for (let attempt = 0;; attempt++) {
|
|
204
|
+
const token = await this.accessToken();
|
|
205
|
+
const headers = { Authorization: `Bearer ${token}` };
|
|
206
|
+
if (hasBody)
|
|
207
|
+
headers["Content-Type"] = "application/json";
|
|
208
|
+
let res;
|
|
209
|
+
let text;
|
|
210
|
+
try {
|
|
211
|
+
({ res, text } = await this.fetchWithTimeout(target, { method, headers, body: hasBody ? JSON.stringify(body) : undefined }, path));
|
|
212
|
+
}
|
|
213
|
+
catch (err) {
|
|
214
|
+
// Network error or timeout: the request may or may not have reached the
|
|
215
|
+
// API, so only reads are retried; writes rethrow immediately.
|
|
216
|
+
if (idempotent && attempt < this.maxRetries) {
|
|
217
|
+
await delay(this.backoffMs(attempt));
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
throw err;
|
|
221
|
+
}
|
|
222
|
+
// An expired/revoked access token: re-mint once and replay. The request
|
|
223
|
+
// never executed, so this is safe for writes too.
|
|
224
|
+
if (res.status === 401 && this.canRefresh() && !refreshedOn401) {
|
|
225
|
+
refreshedOn401 = true;
|
|
226
|
+
await this.accessToken(true);
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
// 429 means the request was rejected before executing — safe to retry for
|
|
230
|
+
// any method. 5xx is ambiguous (the write may have committed), so it is
|
|
231
|
+
// gated to idempotent requests.
|
|
232
|
+
const transient = res.status === 429 || (idempotent && res.status >= 500 && res.status < 600);
|
|
233
|
+
if (transient && attempt < this.maxRetries) {
|
|
234
|
+
await delay(this.backoffMs(attempt, res));
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
let data = undefined;
|
|
238
|
+
if (text) {
|
|
239
|
+
try {
|
|
240
|
+
data = JSON.parse(text);
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
data = text;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
if (!res.ok)
|
|
247
|
+
throw new GoogleFormsError(res.status, data);
|
|
248
|
+
return data;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
// ---- Forms ----
|
|
252
|
+
/**
|
|
253
|
+
* Creates a form. forms.create accepts only info.title / info.documentTitle —
|
|
254
|
+
* everything else must go through batchUpdate afterwards. API-created forms
|
|
255
|
+
* default to unpublished; publish=true chains a setPublishSettings call so the
|
|
256
|
+
* form immediately accepts responses.
|
|
257
|
+
*/
|
|
258
|
+
async createForm(p) {
|
|
259
|
+
const form = await this.request("POST", "v1/forms", {
|
|
260
|
+
info: compact({ title: p.title, documentTitle: p.documentTitle }),
|
|
261
|
+
});
|
|
262
|
+
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 };
|
|
269
|
+
}
|
|
270
|
+
return form;
|
|
271
|
+
}
|
|
272
|
+
/** Full form structure: info, settings, items (with itemId/questionId), publishSettings. */
|
|
273
|
+
async getForm(formId) {
|
|
274
|
+
return this.request("GET", `v1/forms/${encodeURIComponent(formId)}`);
|
|
275
|
+
}
|
|
276
|
+
/** Low-level batchUpdate — the write channel for everything except create/publish. */
|
|
277
|
+
async batchUpdate(formId, requests, opts = {}) {
|
|
278
|
+
return this.request("POST", `v1/forms/${encodeURIComponent(formId)}:batchUpdate`, compact({
|
|
279
|
+
requests,
|
|
280
|
+
includeFormInResponse: opts.includeFormInResponse,
|
|
281
|
+
writeControl: opts.requiredRevisionId ? { requiredRevisionId: opts.requiredRevisionId } : undefined,
|
|
282
|
+
}));
|
|
283
|
+
}
|
|
284
|
+
/** Updates title / description / documentTitle with a computed updateMask. */
|
|
285
|
+
async updateFormInfo(p) {
|
|
286
|
+
const info = compact({ title: p.title, description: p.description, documentTitle: p.documentTitle });
|
|
287
|
+
const mask = Object.keys(info).join(",");
|
|
288
|
+
if (!mask)
|
|
289
|
+
throw new Error("At least one of title, description or document_title is required.");
|
|
290
|
+
return this.batchUpdate(p.formId, [{ updateFormInfo: { info, updateMask: mask } }]);
|
|
291
|
+
}
|
|
292
|
+
/** Toggles quiz mode / email collection with a computed updateMask. */
|
|
293
|
+
async updateFormSettings(p) {
|
|
294
|
+
const settings = compact({
|
|
295
|
+
quizSettings: p.isQuiz !== undefined ? { isQuiz: p.isQuiz } : undefined,
|
|
296
|
+
emailCollectionType: p.emailCollectionType,
|
|
297
|
+
});
|
|
298
|
+
const maskParts = [];
|
|
299
|
+
if (p.isQuiz !== undefined)
|
|
300
|
+
maskParts.push("quizSettings.isQuiz");
|
|
301
|
+
if (p.emailCollectionType !== undefined)
|
|
302
|
+
maskParts.push("emailCollectionType");
|
|
303
|
+
if (maskParts.length === 0)
|
|
304
|
+
throw new Error("At least one of is_quiz or email_collection_type is required.");
|
|
305
|
+
return this.batchUpdate(p.formId, [{ updateSettings: { settings, updateMask: maskParts.join(",") } }]);
|
|
306
|
+
}
|
|
307
|
+
/** Publishes/unpublishes the form and opens/closes response collection. */
|
|
308
|
+
async setPublishSettings(p) {
|
|
309
|
+
return this.request("POST", `v1/forms/${encodeURIComponent(p.formId)}:setPublishSettings`, {
|
|
310
|
+
publishSettings: {
|
|
311
|
+
publishState: {
|
|
312
|
+
isPublished: p.isPublished,
|
|
313
|
+
isAcceptingResponses: p.isAcceptingResponses ?? p.isPublished,
|
|
314
|
+
},
|
|
315
|
+
},
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
// ---- Items ----
|
|
319
|
+
/**
|
|
320
|
+
* Adds one question via batchUpdate createItem. When index is omitted the
|
|
321
|
+
* form is fetched first and the question is appended after the last item
|
|
322
|
+
* (createItem requires an explicit location).
|
|
323
|
+
*/
|
|
324
|
+
async addQuestion(p) {
|
|
325
|
+
const item = buildQuestionItem(p);
|
|
326
|
+
let index = p.index;
|
|
327
|
+
if (index === undefined) {
|
|
328
|
+
const form = (await this.getForm(p.formId));
|
|
329
|
+
index = form.items?.length ?? 0;
|
|
330
|
+
}
|
|
331
|
+
return this.batchUpdate(p.formId, [{ createItem: { item, location: { index } } }]);
|
|
332
|
+
}
|
|
333
|
+
/** Replaces the fields named in updateMask on the item at the given index. */
|
|
334
|
+
async updateItem(p) {
|
|
335
|
+
return this.batchUpdate(p.formId, [
|
|
336
|
+
{ updateItem: { item: p.item, location: { index: p.index }, updateMask: p.updateMask } },
|
|
337
|
+
]);
|
|
338
|
+
}
|
|
339
|
+
/** Deletes the item at the given index. */
|
|
340
|
+
async deleteItem(formId, index) {
|
|
341
|
+
return this.batchUpdate(formId, [{ deleteItem: { location: { index } } }]);
|
|
342
|
+
}
|
|
343
|
+
/** Moves the item at fromIndex to toIndex. */
|
|
344
|
+
async moveItem(formId, fromIndex, toIndex) {
|
|
345
|
+
return this.batchUpdate(formId, [
|
|
346
|
+
{ moveItem: { originalLocation: { index: fromIndex }, newLocation: { index: toIndex } } },
|
|
347
|
+
]);
|
|
348
|
+
}
|
|
349
|
+
// ---- Responses (read-only; the API cannot submit responses) ----
|
|
350
|
+
/** Lists submissions, optionally only those after a timestamp (the API's only filter). */
|
|
351
|
+
async listResponses(p) {
|
|
352
|
+
return this.request("GET", `v1/forms/${encodeURIComponent(p.formId)}/responses`, undefined, compact({
|
|
353
|
+
filter: p.submittedAfter ? `timestamp > ${p.submittedAfter}` : undefined,
|
|
354
|
+
pageSize: p.pageSize,
|
|
355
|
+
pageToken: p.pageToken,
|
|
356
|
+
}));
|
|
357
|
+
}
|
|
358
|
+
/** One submission by its responseId. */
|
|
359
|
+
async getResponse(formId, responseId) {
|
|
360
|
+
return this.request("GET", `v1/forms/${encodeURIComponent(formId)}/responses/${encodeURIComponent(responseId)}`);
|
|
361
|
+
}
|
|
362
|
+
// ---- Watches (Pub/Sub push notifications) ----
|
|
363
|
+
/** Creates a watch pushing RESPONSES/SCHEMA events to a Cloud Pub/Sub topic. */
|
|
364
|
+
async createWatch(p) {
|
|
365
|
+
return this.request("POST", `v1/forms/${encodeURIComponent(p.formId)}/watches`, compact({
|
|
366
|
+
watch: { eventType: p.eventType, target: { topic: { topicName: p.topicName } } },
|
|
367
|
+
watchId: p.watchId,
|
|
368
|
+
}));
|
|
369
|
+
}
|
|
370
|
+
/** Lists the caller's watches on a form. */
|
|
371
|
+
async listWatches(formId) {
|
|
372
|
+
return this.request("GET", `v1/forms/${encodeURIComponent(formId)}/watches`);
|
|
373
|
+
}
|
|
374
|
+
/** Deletes a watch. */
|
|
375
|
+
async deleteWatch(formId, watchId) {
|
|
376
|
+
return this.request("DELETE", `v1/forms/${encodeURIComponent(formId)}/watches/${encodeURIComponent(watchId)}`);
|
|
377
|
+
}
|
|
378
|
+
/** Renews a watch for another 7 days (also reactivates a SUSPENDED watch). */
|
|
379
|
+
async renewWatch(formId, watchId) {
|
|
380
|
+
return this.request("POST", `v1/forms/${encodeURIComponent(formId)}/watches/${encodeURIComponent(watchId)}:renew`, {});
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
/** Drops keys whose value is `undefined` so they are not sent to the API. */
|
|
384
|
+
function compact(obj) {
|
|
385
|
+
return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined));
|
|
386
|
+
}
|
|
387
|
+
function delay(ms) {
|
|
388
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
389
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/** Default Google Forms API host. */
|
|
2
|
+
const DEFAULT_BASE = "https://forms.googleapis.com";
|
|
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).
|
|
7
|
+
*/
|
|
8
|
+
export class ConfigError extends Error {
|
|
9
|
+
reason;
|
|
10
|
+
constructor(message, reason) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = "ConfigError";
|
|
13
|
+
this.reason = reason;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function die(message, reason) {
|
|
17
|
+
throw new ConfigError(message, reason);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Builds the client config from environment variables, throwing ConfigError if
|
|
21
|
+
* the credentials are missing or incomplete.
|
|
22
|
+
*
|
|
23
|
+
* GOOGLE_FORMS_CLIENT_ID OAuth2 client id (refresh flow, recommended)
|
|
24
|
+
* GOOGLE_FORMS_CLIENT_SECRET OAuth2 client secret (refresh flow)
|
|
25
|
+
* GOOGLE_FORMS_REFRESH_TOKEN OAuth2 refresh token (refresh flow)
|
|
26
|
+
* GOOGLE_FORMS_ACCESS_TOKEN static access token (alternative; expires in ~1h)
|
|
27
|
+
* GOOGLE_FORMS_API_BASE API root override (default https://forms.googleapis.com)
|
|
28
|
+
* GOOGLE_FORMS_TIMEOUT_MS per-request timeout (default 60000)
|
|
29
|
+
* GOOGLE_FORMS_MAX_RETRIES retries on transient errors (default 3)
|
|
30
|
+
*/
|
|
31
|
+
export function loadConfig() {
|
|
32
|
+
const clientId = process.env.GOOGLE_FORMS_CLIENT_ID;
|
|
33
|
+
const clientSecret = process.env.GOOGLE_FORMS_CLIENT_SECRET;
|
|
34
|
+
const refreshToken = process.env.GOOGLE_FORMS_REFRESH_TOKEN;
|
|
35
|
+
const accessToken = process.env.GOOGLE_FORMS_ACCESS_TOKEN;
|
|
36
|
+
const oauthProvided = [clientId, clientSecret, refreshToken].filter(Boolean).length;
|
|
37
|
+
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");
|
|
42
|
+
}
|
|
43
|
+
const timeoutMs = Number(process.env.GOOGLE_FORMS_TIMEOUT_MS);
|
|
44
|
+
const maxRetries = Number(process.env.GOOGLE_FORMS_MAX_RETRIES);
|
|
45
|
+
return {
|
|
46
|
+
clientId,
|
|
47
|
+
clientSecret,
|
|
48
|
+
refreshToken,
|
|
49
|
+
accessToken,
|
|
50
|
+
apiBase: process.env.GOOGLE_FORMS_API_BASE || DEFAULT_BASE,
|
|
51
|
+
timeoutMs: Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 60_000,
|
|
52
|
+
maxRetries: Number.isFinite(maxRetries) && maxRetries >= 0 ? maxRetries : 3,
|
|
53
|
+
};
|
|
54
|
+
}
|