apps-script-mcp 0.1.0__py3-none-any.whl

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.
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)
@@ -0,0 +1,152 @@
1
+ """FastMCP server exposing Google Apps Script through the web app bridge."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any, Literal
7
+
8
+ from fastmcp import FastMCP
9
+ from fastmcp.exceptions import ToolError
10
+
11
+ from .bridge import BridgeClient, BridgeError
12
+ from .config import ConfigError, load_config
13
+
14
+ mcp = FastMCP(
15
+ "apps-script",
16
+ instructions=(
17
+ "Edit and run Google Apps Script as the signed-in Google user through a "
18
+ "personal web app bridge. Use run_code for one-off snippets (Sheets, Docs, "
19
+ "Drive, Gmail, Calendar), and the project tools to read, write and run "
20
+ "standalone script projects. Call bridge_status first if anything fails."
21
+ ),
22
+ )
23
+
24
+ _client: BridgeClient | None = None
25
+
26
+
27
+ def get_client() -> BridgeClient:
28
+ global _client
29
+ if _client is None:
30
+ config = load_config()
31
+ _client = BridgeClient(config.url, config.key)
32
+ return _client
33
+
34
+
35
+ async def _call(action: str, **params: Any) -> Any:
36
+ try:
37
+ return await get_client().call(action, **params)
38
+ except (BridgeError, ConfigError) as exc:
39
+ raise ToolError(str(exc)) from exc
40
+
41
+
42
+ def _run_result(data: dict[str, Any]) -> dict[str, Any]:
43
+ """Turn a bridge execution result into a tool result or a tool error."""
44
+ if data.get("success"):
45
+ return {"result": data.get("result"), "logs": data.get("logs", [])}
46
+ parts = [f"Script error: {data.get('error')}"]
47
+ if data.get("stack"):
48
+ parts.append(f"Stack:\n{data['stack']}")
49
+ if data.get("logs"):
50
+ parts.append("Logs before the error:\n" + "\n".join(data["logs"]))
51
+ raise ToolError("\n\n".join(parts))
52
+
53
+
54
+ @mcp.tool
55
+ async def bridge_status() -> dict[str, Any]:
56
+ """Check the bridge: its version, the Google account it runs as, and whether
57
+ the Drive service is enabled (needed to create and edit projects)."""
58
+ status = await _call("status")
59
+ if not status.get("driveService"):
60
+ status["hint"] = (
61
+ "create_project, write_file and delete_file will fail. In the bridge "
62
+ "editor click Services > + > Drive API > Add, then Deploy > Manage "
63
+ "deployments > Edit > Version: New version."
64
+ )
65
+ return status
66
+
67
+
68
+ @mcp.tool
69
+ async def run_code(code: str) -> dict[str, Any]:
70
+ """Run Apps Script (JavaScript, V8) as the user and return the result and logs.
71
+
72
+ `code` is a function body: use `return` to send back a JSON-serializable
73
+ value. All built-in services are available (SpreadsheetApp, DocumentApp,
74
+ DriveApp, GmailApp, CalendarApp, UrlFetchApp, ...). console.log and
75
+ Logger.log output is returned in `logs`. There is no active document, so
76
+ open files by ID or URL. Executions stop after 6 minutes.
77
+ """
78
+ return _run_result(await _call("run_code", code=code))
79
+
80
+
81
+ @mcp.tool
82
+ async def list_projects(query: str | None = None, limit: int = 50) -> list[dict[str, Any]]:
83
+ """List standalone Apps Script projects in the user's Drive, optionally
84
+ filtered by a title substring. Scripts bound to a Sheet/Doc/Form are not
85
+ listed, but work with the other tools when you pass their script ID."""
86
+ return await _call("list_projects", query=query, limit=limit)
87
+
88
+
89
+ @mcp.tool
90
+ async def create_project(title: str) -> dict[str, Any]:
91
+ """Create a standalone Apps Script project with an empty Code file."""
92
+ return await _call("create_project", title=title)
93
+
94
+
95
+ @mcp.tool
96
+ async def get_project(script_id: str) -> dict[str, Any]:
97
+ """Get a standalone project's title and every file with its full source.
98
+ `script_id` is the ID in the editor URL (script.google.com/d/<id>/edit)."""
99
+ return await _call("get_project", script_id=script_id)
100
+
101
+
102
+ @mcp.tool
103
+ async def write_file(
104
+ script_id: str,
105
+ name: str,
106
+ source: str,
107
+ type: Literal["SERVER_JS", "HTML", "JSON"] | None = None,
108
+ ) -> dict[str, Any]:
109
+ """Create or fully replace one file in a project; other files are kept.
110
+
111
+ `name` has no extension ("Code", not "Code.gs"). `type` defaults to
112
+ SERVER_JS, or JSON for the "appsscript" manifest; use HTML for HtmlService
113
+ templates.
114
+ """
115
+ return await _call("write_file", script_id=script_id, name=name, source=source, type=type)
116
+
117
+
118
+ @mcp.tool
119
+ async def delete_file(script_id: str, name: str) -> dict[str, Any]:
120
+ """Delete one file from a project (the appsscript manifest cannot be deleted)."""
121
+ return await _call("delete_file", script_id=script_id, name=name)
122
+
123
+
124
+ @mcp.tool
125
+ async def run_function(
126
+ script_id: str, function_name: str, args: list[Any] | None = None
127
+ ) -> dict[str, Any]:
128
+ """Run a top-level function from a project's saved code and return its
129
+ result and logs.
130
+
131
+ The project's .gs files are loaded into the bridge and executed there, so
132
+ it runs as the user but outside the real project: there is no active
133
+ document (getActiveSpreadsheet() returns null), and the project's own
134
+ libraries, advanced services, script properties and triggers are not
135
+ available. Only standalone projects can be loaded. `args` must be JSON-serializable.
136
+ """
137
+ try:
138
+ json.dumps(args)
139
+ except (TypeError, ValueError) as exc:
140
+ raise ToolError(f"args must be JSON-serializable: {exc}") from exc
141
+ data = await _call(
142
+ "run_function", script_id=script_id, function_name=function_name, args=args or []
143
+ )
144
+ return _run_result(data)
145
+
146
+
147
+ def main() -> None:
148
+ mcp.run()
149
+
150
+
151
+ if __name__ == "__main__":
152
+ main()
@@ -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,9 @@
1
+ apps_script_mcp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ apps_script_mcp/bridge.py,sha256=v3RSmrbh2c3TyyyMD2bZBPTDOrVvFKrBaXspdsPcAA0,2194
3
+ apps_script_mcp/config.py,sha256=dV2cng7duVC-yB0VraZr5grWpVxOAbYYd4ksJuwjdCs,1065
4
+ apps_script_mcp/server.py,sha256=y5P35Uych4cwQHsR9VcWpLMTJBNtJ3tl6m0dvlSLoi0,5417
5
+ apps_script_mcp-0.1.0.dist-info/METADATA,sha256=zA8y905Vuox2xeQ7peapf6DCBx30hctb8eT9z5N5maw,2882
6
+ apps_script_mcp-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ apps_script_mcp-0.1.0.dist-info/entry_points.txt,sha256=iSZaql8SX7kh07XhIP-9Sr274AJBOtwxUGF-EeYDjHs,64
8
+ apps_script_mcp-0.1.0.dist-info/licenses/LICENSE,sha256=JGUNlQpjA5ZF0nMKwUrT3Su3Ktezg8FSwG5lA3mUUfA,1064
9
+ apps_script_mcp-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ apps-script-mcp = apps_script_mcp.server:main
@@ -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.