apps-script-mcp 0.1.0__tar.gz

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.
@@ -0,0 +1,38 @@
1
+ name: Publish to PyPI
2
+
3
+ # Runs when a GitHub release is published. Uses PyPI trusted publishing,
4
+ # so no API token is stored in this repository.
5
+ on:
6
+ release:
7
+ types: [published]
8
+
9
+ jobs:
10
+ publish:
11
+ runs-on: ubuntu-latest
12
+ environment: pypi
13
+ permissions:
14
+ id-token: write # required for trusted publishing
15
+ contents: read
16
+ steps:
17
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
18
+
19
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
20
+
21
+ - name: Check that the release tag matches the package version
22
+ env:
23
+ TAG: ${{ github.event.release.tag_name }}
24
+ run: |
25
+ version="$(uv version --short)"
26
+ if [ "${TAG#v}" != "$version" ]; then
27
+ echo "Release tag $TAG does not match pyproject.toml version $version" >&2
28
+ exit 1
29
+ fi
30
+
31
+ - name: Run tests
32
+ run: uv run pytest
33
+
34
+ - name: Build
35
+ run: uv build
36
+
37
+ - name: Publish
38
+ run: uv publish
@@ -0,0 +1,7 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ .pytest_cache/
5
+ dist/
6
+ .env
7
+ .mcp.json
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Phuc To
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.
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.5
2
+ Name: apps-script-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server for Google Apps Script that needs no Google Cloud Console setup
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.10
8
+ Requires-Dist: fastmcp>=2.3
9
+ Requires-Dist: httpx>=0.27
10
+ Description-Content-Type: text/markdown
11
+
12
+ # apps-script-mcp
13
+
14
+ An MCP server that lets Claude write and run Google Apps Script in your Google account, with no Google Cloud Console setup.
15
+
16
+ It works through a small "bridge" script that you deploy once as a web app in your own account. The local server calls it with a secret key, and the bridge runs as you.
17
+
18
+ ## Setup
19
+
20
+ Requires [uv](https://docs.astral.sh/uv/).
21
+
22
+ 1. Create a new project at <https://script.google.com> and paste in [bridge/Code.gs](bridge/Code.gs).
23
+ 2. Click **+** next to **Services** and add **Drive API**.
24
+ 3. In **Project Settings**, tick **Show "appsscript.json" manifest file in editor**, then paste in [bridge/appsscript.json](bridge/appsscript.json).
25
+ 4. Run the `setup` function, approve all permissions, and copy the key from the execution log.
26
+ 5. Click **Deploy > New deployment > Web app**, with **Execute as: Me** and **Who has access: Anyone**. Copy the `/exec` URL.
27
+ 6. Add the server to your MCP client:
28
+
29
+ ```json
30
+ {
31
+ "mcpServers": {
32
+ "apps-script": {
33
+ "command": "uv",
34
+ "args": ["run", "--directory", "/path/to/apps-script-mcp", "apps-script-mcp"],
35
+ "env": {
36
+ "APPS_SCRIPT_BRIDGE_URL": "https://script.google.com/macros/s/.../exec",
37
+ "APPS_SCRIPT_BRIDGE_KEY": "your key"
38
+ }
39
+ }
40
+ }
41
+ }
42
+ ```
43
+
44
+ Ask Claude to call `bridge_status` to check that it works.
45
+
46
+ ## Tools
47
+
48
+ | Tool | What it does |
49
+ |---|---|
50
+ | `bridge_status` | Checks the bridge and the account it runs as |
51
+ | `run_code` | Runs a snippet as you and returns its result and logs |
52
+ | `list_projects` | Lists standalone script projects in your Drive |
53
+ | `create_project` | Creates a standalone project |
54
+ | `get_project` | Reads all files of a project |
55
+ | `write_file` | Creates or replaces one file |
56
+ | `delete_file` | Deletes one file |
57
+ | `run_function` | Runs a function from a project's saved code |
58
+
59
+ ## Security
60
+
61
+ Anyone with both the URL and the key can do everything the manifest scopes allow, including reading your mail and files. Treat the key like a password.
62
+
63
+ - Remove scopes you do not need from `appsscript.json`.
64
+ - Run `rotateKey` in the bridge editor to replace the key.
65
+ - Archive the deployment to turn the bridge off.
66
+
67
+ ## Limits
68
+
69
+ - Only standalone projects can be edited, not scripts bound to a Sheet, Doc or Form.
70
+ - `run_function` runs inside the bridge, so there is no active document and the project's own libraries, properties and triggers are unavailable.
71
+ - There is no deploy tool; publish from the Apps Script editor.
72
+ - Each call stops after 6 minutes.
73
+
74
+ ## Development
75
+
76
+ ```sh
77
+ uv sync
78
+ uv run pytest
79
+ ```
80
+
81
+ ## License
82
+
83
+ [MIT](LICENSE)
@@ -0,0 +1,72 @@
1
+ # apps-script-mcp
2
+
3
+ An MCP server that lets Claude write and run Google Apps Script in your Google account, with no Google Cloud Console setup.
4
+
5
+ It works through a small "bridge" script that you deploy once as a web app in your own account. The local server calls it with a secret key, and the bridge runs as you.
6
+
7
+ ## Setup
8
+
9
+ Requires [uv](https://docs.astral.sh/uv/).
10
+
11
+ 1. Create a new project at <https://script.google.com> and paste in [bridge/Code.gs](bridge/Code.gs).
12
+ 2. Click **+** next to **Services** and add **Drive API**.
13
+ 3. In **Project Settings**, tick **Show "appsscript.json" manifest file in editor**, then paste in [bridge/appsscript.json](bridge/appsscript.json).
14
+ 4. Run the `setup` function, approve all permissions, and copy the key from the execution log.
15
+ 5. Click **Deploy > New deployment > Web app**, with **Execute as: Me** and **Who has access: Anyone**. Copy the `/exec` URL.
16
+ 6. Add the server to your MCP client:
17
+
18
+ ```json
19
+ {
20
+ "mcpServers": {
21
+ "apps-script": {
22
+ "command": "uv",
23
+ "args": ["run", "--directory", "/path/to/apps-script-mcp", "apps-script-mcp"],
24
+ "env": {
25
+ "APPS_SCRIPT_BRIDGE_URL": "https://script.google.com/macros/s/.../exec",
26
+ "APPS_SCRIPT_BRIDGE_KEY": "your key"
27
+ }
28
+ }
29
+ }
30
+ }
31
+ ```
32
+
33
+ Ask Claude to call `bridge_status` to check that it works.
34
+
35
+ ## Tools
36
+
37
+ | Tool | What it does |
38
+ |---|---|
39
+ | `bridge_status` | Checks the bridge and the account it runs as |
40
+ | `run_code` | Runs a snippet as you and returns its result and logs |
41
+ | `list_projects` | Lists standalone script projects in your Drive |
42
+ | `create_project` | Creates a standalone project |
43
+ | `get_project` | Reads all files of a project |
44
+ | `write_file` | Creates or replaces one file |
45
+ | `delete_file` | Deletes one file |
46
+ | `run_function` | Runs a function from a project's saved code |
47
+
48
+ ## Security
49
+
50
+ Anyone with both the URL and the key can do everything the manifest scopes allow, including reading your mail and files. Treat the key like a password.
51
+
52
+ - Remove scopes you do not need from `appsscript.json`.
53
+ - Run `rotateKey` in the bridge editor to replace the key.
54
+ - Archive the deployment to turn the bridge off.
55
+
56
+ ## Limits
57
+
58
+ - Only standalone projects can be edited, not scripts bound to a Sheet, Doc or Form.
59
+ - `run_function` runs inside the bridge, so there is no active document and the project's own libraries, properties and triggers are unavailable.
60
+ - There is no deploy tool; publish from the Apps Script editor.
61
+ - Each call stops after 6 minutes.
62
+
63
+ ## Development
64
+
65
+ ```sh
66
+ uv sync
67
+ uv run pytest
68
+ ```
69
+
70
+ ## License
71
+
72
+ [MIT](LICENSE)
@@ -0,0 +1,283 @@
1
+ /**
2
+ * apps-script-mcp bridge.
3
+ *
4
+ * Paste this file into a new project at script.google.com, add the "Drive API"
5
+ * service (Services > +), run setup() once,
6
+ * then deploy as a web app (Execute as: Me, Who has access: Anyone).
7
+ * The local MCP server calls the web app URL with the key that setup() prints.
8
+ */
9
+
10
+ const BRIDGE_VERSION = '1.1.2';
11
+ const SCRIPT_MIME = 'application/vnd.google-apps.script';
12
+ const SCRIPT_JSON_MIME = 'application/vnd.google-apps.script+json';
13
+ const KEY_PROPERTY = 'BRIDGE_KEY';
14
+
15
+ /**
16
+ * Run from the editor. Grants permissions and prints the secret key, creating
17
+ * one on first run. Safe to run again after changing scopes; the key is kept.
18
+ */
19
+ function setup() {
20
+ // Google only prompts for the scopes a function uses itself, so ask for
21
+ // every manifest scope explicitly; run_code needs all of them later.
22
+ if (ScriptApp.requireAllScopes) ScriptApp.requireAllScopes(ScriptApp.AuthMode.FULL);
23
+ const props = PropertiesService.getScriptProperties();
24
+ let key = props.getProperty(KEY_PROPERTY);
25
+ if (!key) {
26
+ key = (Utilities.getUuid() + Utilities.getUuid()).replace(/-/g, '');
27
+ props.setProperty(KEY_PROPERTY, key);
28
+ }
29
+ console.log('APPS_SCRIPT_BRIDGE_KEY (keep it secret): ' + key);
30
+ }
31
+
32
+ /** Replaces the secret key. The old key stops working immediately. */
33
+ function rotateKey() {
34
+ PropertiesService.getScriptProperties().deleteProperty(KEY_PROPERTY);
35
+ setup();
36
+ }
37
+
38
+ function doPost(e) {
39
+ let out;
40
+ try {
41
+ const req = JSON.parse(e.postData.contents);
42
+ checkKey_(req.key);
43
+ const handler = ACTIONS[req.action];
44
+ if (!handler) throw new Error('Unknown action: ' + req.action);
45
+ out = { ok: true, data: handler(req.params || {}) };
46
+ } catch (err) {
47
+ out = { ok: false, error: String((err && err.message) || err) };
48
+ }
49
+ return ContentService.createTextOutput(JSON.stringify(out)).setMimeType(
50
+ ContentService.MimeType.JSON
51
+ );
52
+ }
53
+
54
+ function doGet() {
55
+ return ContentService.createTextOutput('apps-script-mcp bridge ' + BRIDGE_VERSION);
56
+ }
57
+
58
+ function checkKey_(given) {
59
+ const expected = PropertiesService.getScriptProperties().getProperty(KEY_PROPERTY);
60
+ if (!expected) throw new Error('Bridge has no key yet. Run setup() in the Apps Script editor.');
61
+ given = String(given || '');
62
+ let diff = given.length ^ expected.length;
63
+ for (let i = 0; i < expected.length; i++) {
64
+ diff |= expected.charCodeAt(i) ^ (given.charCodeAt(i) || 0);
65
+ }
66
+ if (diff !== 0) throw new Error('Invalid bridge key.');
67
+ }
68
+
69
+ const ACTIONS = {
70
+ status: function () {
71
+ return {
72
+ version: BRIDGE_VERSION,
73
+ email: Session.getEffectiveUser().getEmail(),
74
+ bridgeScriptId: ScriptApp.getScriptId(),
75
+ driveService: typeof Drive !== 'undefined',
76
+ };
77
+ },
78
+
79
+ run_code: function (p) {
80
+ return execute_(String(p.code || ''), []);
81
+ },
82
+
83
+ run_function: function (p) {
84
+ const name = String(p.function_name || '');
85
+ if (!/^[A-Za-z_$][\w$]*$/.test(name)) throw new Error('Invalid function name: ' + name);
86
+ const files = getFiles_(p.script_id).filter(function (f) {
87
+ return f.type === 'SERVER_JS';
88
+ });
89
+ const source = files
90
+ .map(function (f) {
91
+ return '// ---- ' + f.name + '.gs ----\n' + f.source;
92
+ })
93
+ .join('\n');
94
+ return execute_(source + '\nreturn ' + name + '.apply(null, __args);', p.args || []);
95
+ },
96
+
97
+ list_projects: function (p) {
98
+ let q = "mimeType = 'application/vnd.google-apps.script' and trashed = false";
99
+ if (p.query) {
100
+ q += " and title contains '" + String(p.query).replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'";
101
+ }
102
+ const it = DriveApp.searchFiles(q);
103
+ const limit = Math.min(Number(p.limit) || 50, 200);
104
+ const out = [];
105
+ while (it.hasNext() && out.length < limit) {
106
+ const f = it.next();
107
+ out.push({
108
+ scriptId: f.getId(),
109
+ title: f.getName(),
110
+ updated: f.getLastUpdated().toISOString(),
111
+ url: 'https://script.google.com/d/' + f.getId() + '/edit',
112
+ });
113
+ }
114
+ return out;
115
+ },
116
+
117
+ create_project: function (p) {
118
+ const title = String(p.title || 'Untitled project');
119
+ const blob = scriptBlob_([{ name: 'Code', type: 'server_js', source: 'function myFunction() {\n\n}\n' }]);
120
+ const drive = drive_();
121
+ const file = drive.Files.create
122
+ ? drive.Files.create({ name: title, mimeType: SCRIPT_MIME }, blob)
123
+ : drive.Files.insert({ title: title, mimeType: SCRIPT_MIME }, blob, { convert: true });
124
+ return {
125
+ scriptId: file.id,
126
+ title: title,
127
+ url: 'https://script.google.com/d/' + file.id + '/edit',
128
+ };
129
+ },
130
+
131
+ get_project: function (p) {
132
+ const file = DriveApp.getFileById(String(p.script_id || ''));
133
+ return {
134
+ scriptId: file.getId(),
135
+ title: file.getName(),
136
+ files: getFiles_(p.script_id).map(publicFile_),
137
+ };
138
+ },
139
+
140
+ write_file: function (p) {
141
+ const name = String(p.name || '');
142
+ if (!name) throw new Error('File name is required.');
143
+ const type = p.type || (name === 'appsscript' ? 'JSON' : 'SERVER_JS');
144
+ if (['SERVER_JS', 'HTML', 'JSON'].indexOf(type) < 0) throw new Error('Invalid file type: ' + type);
145
+ const files = getFiles_(p.script_id);
146
+ const existing = files.filter(function (f) {
147
+ return f.name === name;
148
+ })[0];
149
+ if (existing) {
150
+ existing.type = type;
151
+ existing.source = String(p.source);
152
+ } else {
153
+ files.push({ name: name, type: type, source: String(p.source) });
154
+ }
155
+ putFiles_(p.script_id, files);
156
+ return { scriptId: p.script_id, name: name, type: type, created: !existing, fileCount: files.length };
157
+ },
158
+
159
+ delete_file: function (p) {
160
+ const name = String(p.name || '');
161
+ if (name === 'appsscript') throw new Error('The appsscript manifest cannot be deleted.');
162
+ const files = getFiles_(p.script_id);
163
+ const kept = files.filter(function (f) {
164
+ return f.name !== name;
165
+ });
166
+ if (kept.length === files.length) throw new Error('No file named "' + name + '" in this project.');
167
+ putFiles_(p.script_id, kept);
168
+ return { scriptId: p.script_id, deleted: name, fileCount: kept.length };
169
+ },
170
+ };
171
+
172
+ /** Runs a function body with captured logging. Never throws for user code errors. */
173
+ function execute_(body, args) {
174
+ const logs = [];
175
+ const write = function () {
176
+ logs.push(Array.prototype.map.call(arguments, show_).join(' '));
177
+ };
178
+ const fakeConsole = { log: write, info: write, warn: write, error: write, debug: write };
179
+ const fakeLogger = {
180
+ log: function () {
181
+ write.apply(null, arguments);
182
+ return fakeLogger;
183
+ },
184
+ getLog: function () {
185
+ return logs.join('\n');
186
+ },
187
+ clear: function () {
188
+ logs.length = 0;
189
+ },
190
+ };
191
+ try {
192
+ const fn = new Function('console', 'Logger', '__args', body);
193
+ const result = fn(fakeConsole, fakeLogger, args);
194
+ return { success: true, result: serialize_(result), logs: logs };
195
+ } catch (err) {
196
+ return {
197
+ success: false,
198
+ error: String((err && err.message) || err),
199
+ stack: (err && err.stack) || null,
200
+ logs: logs,
201
+ };
202
+ }
203
+ }
204
+
205
+ function show_(v) {
206
+ if (typeof v === 'string') return v;
207
+ try {
208
+ const s = JSON.stringify(v);
209
+ return s === undefined ? String(v) : s;
210
+ } catch (err) {
211
+ return String(v);
212
+ }
213
+ }
214
+
215
+ function serialize_(v) {
216
+ if (v === undefined) return null;
217
+ try {
218
+ const s = JSON.stringify(v);
219
+ return s === undefined ? String(v) : JSON.parse(s);
220
+ } catch (err) {
221
+ return String(v);
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Reads a standalone script's files through the Drive export endpoint.
227
+ * Each file keeps its internal `id`, which putFiles_ needs to update it in place.
228
+ */
229
+ function getFiles_(scriptId) {
230
+ if (!scriptId) throw new Error('script_id is required.');
231
+ const url =
232
+ 'https://script.google.com/feeds/download/export?format=json&id=' +
233
+ encodeURIComponent(String(scriptId));
234
+ const res = UrlFetchApp.fetch(url, {
235
+ headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() },
236
+ muteHttpExceptions: true,
237
+ });
238
+ const code = res.getResponseCode();
239
+ const text = res.getContentText();
240
+ let json = null;
241
+ try {
242
+ json = JSON.parse(text);
243
+ } catch (err) {
244
+ // handled below
245
+ }
246
+ if (code >= 300 || !json || !json.files) {
247
+ throw new Error(
248
+ 'Could not read script ' + scriptId + ' (HTTP ' + code + '). ' +
249
+ 'Only standalone script projects you can access are supported, not scripts bound to a Sheet, Doc or Form.'
250
+ );
251
+ }
252
+ return json.files.map(function (f) {
253
+ return { id: f.id, name: f.name, type: String(f.type).toUpperCase(), source: f.source || '' };
254
+ });
255
+ }
256
+
257
+ /** Replaces all files of a script. Files without an `id` are created; missing ones are deleted. */
258
+ function putFiles_(scriptId, files) {
259
+ drive_().Files.update({}, String(scriptId), scriptBlob_(files));
260
+ }
261
+
262
+ function scriptBlob_(files) {
263
+ const payload = files.map(function (f) {
264
+ const out = { name: f.name, type: String(f.type).toLowerCase(), source: f.source };
265
+ if (f.id) out.id = f.id;
266
+ return out;
267
+ });
268
+ return Utilities.newBlob(JSON.stringify({ files: payload }), SCRIPT_JSON_MIME);
269
+ }
270
+
271
+ function publicFile_(f) {
272
+ return { name: f.name, type: f.type, source: f.source };
273
+ }
274
+
275
+ function drive_() {
276
+ if (typeof Drive === 'undefined') {
277
+ throw new Error(
278
+ 'The Drive service is not enabled in the bridge. In the bridge editor click Services > + > ' +
279
+ 'Drive API > Add, then Deploy > Manage deployments > Edit > Version: New version.'
280
+ );
281
+ }
282
+ return Drive;
283
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "timeZone": "Etc/UTC",
3
+ "exceptionLogging": "STACKDRIVER",
4
+ "runtimeVersion": "V8",
5
+ "dependencies": {
6
+ "enabledAdvancedServices": [
7
+ { "userSymbol": "Drive", "version": "v3", "serviceId": "drive" }
8
+ ]
9
+ },
10
+ "webapp": {
11
+ "executeAs": "USER_DEPLOYING",
12
+ "access": "ANYONE_ANONYMOUS"
13
+ },
14
+ "oauthScopes": [
15
+ "https://www.googleapis.com/auth/userinfo.email",
16
+ "https://www.googleapis.com/auth/script.external_request",
17
+ "https://www.googleapis.com/auth/drive",
18
+ "https://www.googleapis.com/auth/drive.scripts",
19
+ "https://www.googleapis.com/auth/spreadsheets",
20
+ "https://www.googleapis.com/auth/documents",
21
+ "https://www.googleapis.com/auth/presentations",
22
+ "https://www.googleapis.com/auth/forms",
23
+ "https://www.googleapis.com/auth/calendar",
24
+ "https://mail.google.com/"
25
+ ]
26
+ }
@@ -0,0 +1,28 @@
1
+ [project]
2
+ name = "apps-script-mcp"
3
+ version = "0.1.0"
4
+ description = "MCP server for Google Apps Script that needs no Google Cloud Console setup"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.10"
9
+ dependencies = [
10
+ "fastmcp>=2.3",
11
+ "httpx>=0.27",
12
+ ]
13
+
14
+ [project.scripts]
15
+ apps-script-mcp = "apps_script_mcp.server:main"
16
+
17
+ [dependency-groups]
18
+ dev = ["pytest>=8"]
19
+
20
+ [build-system]
21
+ requires = ["hatchling"]
22
+ build-backend = "hatchling.build"
23
+
24
+ [tool.hatch.build.targets.wheel]
25
+ packages = ["src/apps_script_mcp"]
26
+
27
+ [tool.pytest.ini_options]
28
+ testpaths = ["tests"]
File without changes
@@ -0,0 +1,64 @@
1
+ """HTTP client for the Apps Script web app bridge."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import httpx
8
+
9
+ # Apps Script allows 6 minutes per execution; leave a little headroom.
10
+ DEFAULT_TIMEOUT = 370.0
11
+
12
+
13
+ class BridgeError(Exception):
14
+ pass
15
+
16
+
17
+ class BridgeClient:
18
+ def __init__(
19
+ self,
20
+ url: str,
21
+ key: str,
22
+ *,
23
+ transport: httpx.AsyncBaseTransport | None = None,
24
+ timeout: float = DEFAULT_TIMEOUT,
25
+ ) -> None:
26
+ self._url = url
27
+ self._key = key
28
+ self._transport = transport
29
+ self._timeout = timeout
30
+
31
+ async def call(self, action: str, **params: Any) -> Any:
32
+ """Call one bridge action and return its data, or raise BridgeError."""
33
+ payload = {
34
+ "key": self._key,
35
+ "action": action,
36
+ "params": {k: v for k, v in params.items() if v is not None},
37
+ }
38
+ try:
39
+ # The web app answers with a 302 to script.googleusercontent.com,
40
+ # which must be followed with a GET.
41
+ async with httpx.AsyncClient(
42
+ follow_redirects=True, timeout=self._timeout, transport=self._transport
43
+ ) as client:
44
+ response = await client.post(self._url, json=payload)
45
+ except httpx.TimeoutException as exc:
46
+ raise BridgeError(
47
+ "The bridge did not answer in time (Apps Script stops after 6 minutes)."
48
+ ) from exc
49
+ except httpx.HTTPError as exc:
50
+ raise BridgeError(f"Could not reach the bridge: {exc}") from exc
51
+
52
+ try:
53
+ body = response.json()
54
+ except ValueError:
55
+ body = None
56
+ if not isinstance(body, dict) or "ok" not in body:
57
+ raise BridgeError(
58
+ f"The bridge returned HTTP {response.status_code} without a JSON result. "
59
+ "Check that the URL ends in /exec, that the web app is deployed with "
60
+ "'Who has access: Anyone', and that the latest code is deployed as a new version."
61
+ )
62
+ if not body["ok"]:
63
+ raise BridgeError(str(body.get("error") or "Unknown bridge error"))
64
+ return body.get("data")
@@ -0,0 +1,37 @@
1
+ """Bridge connection settings, read from the environment."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass
7
+
8
+ URL_VAR = "APPS_SCRIPT_BRIDGE_URL"
9
+ KEY_VAR = "APPS_SCRIPT_BRIDGE_KEY"
10
+
11
+
12
+ class ConfigError(Exception):
13
+ pass
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class Config:
18
+ url: str
19
+ key: str
20
+
21
+
22
+ def load_config(env: dict[str, str] | None = None) -> Config:
23
+ env = os.environ if env is None else env
24
+ url = (env.get(URL_VAR) or "").strip()
25
+ key = (env.get(KEY_VAR) or "").strip()
26
+ missing = [name for name, value in ((URL_VAR, url), (KEY_VAR, key)) if not value]
27
+ if missing:
28
+ raise ConfigError(
29
+ f"Missing environment variable(s): {', '.join(missing)}. "
30
+ "See README.md for the one-time bridge setup."
31
+ )
32
+ if not url.startswith("https://script.google.com/") or not url.endswith("/exec"):
33
+ raise ConfigError(
34
+ f"{URL_VAR} must be the web app URL, in the form "
35
+ "https://script.google.com/macros/s/<id>/exec"
36
+ )
37
+ return Config(url=url, key=key)