@mutallip/google-workspace-mcp 0.0.0-stage → 2.8.1
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 +353 -2
- package/README.npm.md +34 -0
- package/auth/__init__.py +1 -0
- package/auth/auth_info_middleware.py +419 -0
- package/auth/client_secrets.py +76 -0
- package/auth/credential_store.py +598 -0
- package/auth/external_oauth_provider.py +369 -0
- package/auth/gateway_identity.py +164 -0
- package/auth/google_auth.py +1550 -0
- package/auth/google_oauth_provider.py +20 -0
- package/auth/mcp_session_middleware.py +95 -0
- package/auth/oauth21_session_store.py +1332 -0
- package/auth/oauth_callback_server.py +466 -0
- package/auth/oauth_config.py +693 -0
- package/auth/oauth_proxy_config.py +122 -0
- package/auth/oauth_responses.py +230 -0
- package/auth/oauth_types.py +92 -0
- package/auth/permissions.py +330 -0
- package/auth/port_resolver.py +153 -0
- package/auth/request_identity.py +89 -0
- package/auth/scopes.py +369 -0
- package/auth/service_decorator.py +1109 -0
- package/bin/google-workspace-mcp.cjs +123 -0
- package/core/__init__.py +1 -0
- package/core/api_enablement.py +108 -0
- package/core/attachment_storage.py +496 -0
- package/core/camel_case_middleware.py +98 -0
- package/core/cli.py +161 -0
- package/core/comments.py +609 -0
- package/core/config.py +57 -0
- package/core/context.py +43 -0
- package/core/file_limits.py +632 -0
- package/core/gcs_attachment_storage.py +253 -0
- package/core/http_utils.py +339 -0
- package/core/log_formatter.py +270 -0
- package/core/portable_schema_middleware.py +67 -0
- package/core/server.py +1192 -0
- package/core/startup_ui.py +239 -0
- package/core/storage.py +23 -0
- package/core/telemetry.py +194 -0
- package/core/tool_descriptions.py +19 -0
- package/core/tool_registry.py +311 -0
- package/core/tool_tier_loader.py +197 -0
- package/core/tool_tiers.yaml +179 -0
- package/core/toolset_header_middleware.py +67 -0
- package/core/utils.py +1537 -0
- package/core/valkey_storage.py +271 -0
- package/core/warning_filters.py +19 -0
- package/fastmcp_server.py +198 -0
- package/gappsscript/README.md +512 -0
- package/gappsscript/TESTING.md +254 -0
- package/gappsscript/__init__.py +0 -0
- package/gappsscript/apps_script_tools.py +1940 -0
- package/gcalendar/__init__.py +1 -0
- package/gcalendar/calendar_helpers.py +1323 -0
- package/gcalendar/calendar_tools.py +2252 -0
- package/gchat/__init__.py +7 -0
- package/gchat/chat_helpers.py +410 -0
- package/gchat/chat_tools.py +798 -0
- package/gcontacts/__init__.py +1 -0
- package/gcontacts/contacts_helpers.py +765 -0
- package/gcontacts/contacts_tools.py +1685 -0
- package/gdocs/__init__.py +0 -0
- package/gdocs/docs_anchors.py +163 -0
- package/gdocs/docs_comments.py +89 -0
- package/gdocs/docs_helpers.py +2201 -0
- package/gdocs/docs_links.py +87 -0
- package/gdocs/docs_markdown.py +828 -0
- package/gdocs/docs_markdown_writer.py +592 -0
- package/gdocs/docs_plain_text.py +463 -0
- package/gdocs/docs_structure.py +621 -0
- package/gdocs/docs_tables.py +425 -0
- package/gdocs/docs_tools.py +3300 -0
- package/gdocs/managers/__init__.py +18 -0
- package/gdocs/managers/batch_operation_manager.py +1694 -0
- package/gdocs/managers/header_footer_manager.py +526 -0
- package/gdocs/managers/table_operation_manager.py +488 -0
- package/gdocs/managers/validation_manager.py +1504 -0
- package/gdocs/operation_schemas.py +594 -0
- package/gdrive/__init__.py +0 -0
- package/gdrive/drive_helpers.py +1738 -0
- package/gdrive/drive_tools.py +3085 -0
- package/gforms/__init__.py +3 -0
- package/gforms/forms_tools.py +575 -0
- package/gmail/__init__.py +1 -0
- package/gmail/gmail_helpers.py +2107 -0
- package/gmail/gmail_tools.py +4895 -0
- package/gmail/gmail_web_mime.py +441 -0
- package/gsearch/__init__.py +0 -0
- package/gsearch/search_tools.py +253 -0
- package/gsheets/__init__.py +31 -0
- package/gsheets/sheets_helpers.py +2236 -0
- package/gsheets/sheets_tools.py +3280 -0
- package/gslides/__init__.py +0 -0
- package/gslides/slides_digest.py +390 -0
- package/gslides/slides_helpers.py +392 -0
- package/gslides/slides_markup.py +770 -0
- package/gslides/slides_tools.py +376 -0
- package/gtasks/__init__.py +5 -0
- package/gtasks/tasks_tools.py +936 -0
- package/main.py +1170 -0
- package/package.json +43 -4
- package/pyproject.toml +173 -0
- package/uv.lock +2504 -0
|
@@ -0,0 +1,1940 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Google Apps Script MCP Tools
|
|
3
|
+
|
|
4
|
+
This module provides MCP tools for interacting with Google Apps Script API.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
import inspect
|
|
9
|
+
import json
|
|
10
|
+
import logging
|
|
11
|
+
import weakref
|
|
12
|
+
from functools import wraps
|
|
13
|
+
from typing import Any, Dict, List, Optional
|
|
14
|
+
|
|
15
|
+
from mcp.types import ToolAnnotations
|
|
16
|
+
|
|
17
|
+
from auth.service_decorator import require_google_service
|
|
18
|
+
from core.server import server
|
|
19
|
+
from core.utils import ObjectList, UserInputError, handle_http_errors
|
|
20
|
+
from gdrive.drive_helpers import flag_incomplete_search
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
_VALID_SCRIPT_FILE_TYPES = frozenset({"SERVER_JS", "HTML", "JSON"})
|
|
25
|
+
_SCRIPT_MIME_TYPE = "application/vnd.google-apps.script"
|
|
26
|
+
|
|
27
|
+
# These locks serialize updates only within this process. Other worker
|
|
28
|
+
# processes or service instances can still race while merging the same script_id.
|
|
29
|
+
_SCRIPT_UPDATE_LOCKS: weakref.WeakValueDictionary[str, asyncio.Lock] = (
|
|
30
|
+
weakref.WeakValueDictionary()
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _get_script_update_lock(script_id: str) -> asyncio.Lock:
|
|
35
|
+
"""Return the in-process lock that orders updates for one script."""
|
|
36
|
+
return _SCRIPT_UPDATE_LOCKS.setdefault(script_id, asyncio.Lock())
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _normalize_script_file(file: Dict[str, Any]) -> Dict[str, str]:
|
|
40
|
+
"""Return the Script API file fields used for updateContent requests.
|
|
41
|
+
|
|
42
|
+
Output-only fields returned by getContent (createTime, functionSet, ...)
|
|
43
|
+
are dropped. Fields the caller omitted stay omitted so a merge can fall
|
|
44
|
+
back to the existing value instead of blanking it.
|
|
45
|
+
"""
|
|
46
|
+
return {
|
|
47
|
+
key: file[key]
|
|
48
|
+
for key in ("name", "type", "source")
|
|
49
|
+
if key in file and file[key] is not None
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _merge_script_files(
|
|
54
|
+
existing_files: List[Dict[str, Any]],
|
|
55
|
+
updated_files: List[Dict[str, Any]],
|
|
56
|
+
) -> List[Dict[str, str]]:
|
|
57
|
+
"""Overlay updated files onto the current project.
|
|
58
|
+
|
|
59
|
+
Files are keyed by (name, type) because Script API names exclude the
|
|
60
|
+
extension, so one project may hold both Code.gs and Code.html as "Code".
|
|
61
|
+
An update that omits `type` falls back to matching by name, but only when
|
|
62
|
+
exactly one existing file carries that name; otherwise the type cannot be
|
|
63
|
+
inferred and a UserInputError is raised rather than pushing an untyped file.
|
|
64
|
+
"""
|
|
65
|
+
merged = {
|
|
66
|
+
(file["name"], file.get("type")): _normalize_script_file(file)
|
|
67
|
+
for file in existing_files
|
|
68
|
+
if file.get("name")
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
for index, file in enumerate(updated_files):
|
|
72
|
+
name = file.get("name")
|
|
73
|
+
if not name:
|
|
74
|
+
raise UserInputError(
|
|
75
|
+
f"File at index {index} is missing a non-empty 'name'."
|
|
76
|
+
)
|
|
77
|
+
file_type = file.get("type")
|
|
78
|
+
if file_type is not None:
|
|
79
|
+
if file_type not in _VALID_SCRIPT_FILE_TYPES:
|
|
80
|
+
raise UserInputError(
|
|
81
|
+
f"File '{name}' has unsupported type '{file_type}'; it must "
|
|
82
|
+
"be one of SERVER_JS, HTML, or JSON."
|
|
83
|
+
)
|
|
84
|
+
if file_type == "JSON" and name != "appsscript":
|
|
85
|
+
raise UserInputError(
|
|
86
|
+
f"JSON file '{name}' must use the manifest name 'appsscript'."
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
key = (name, file_type)
|
|
90
|
+
if key not in merged and file_type is None:
|
|
91
|
+
same_name = [existing for existing in merged if existing[0] == name]
|
|
92
|
+
if len(same_name) != 1:
|
|
93
|
+
raise UserInputError(
|
|
94
|
+
f"File '{name}' is missing 'type'; it must be one of "
|
|
95
|
+
"SERVER_JS, HTML, or JSON because the existing project "
|
|
96
|
+
"does not identify a single file with that name."
|
|
97
|
+
)
|
|
98
|
+
key = same_name[0]
|
|
99
|
+
merged[key] = {**merged.get(key, {}), **_normalize_script_file(file)}
|
|
100
|
+
|
|
101
|
+
return list(merged.values())
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# Internal implementation functions for testing
|
|
105
|
+
async def _list_script_projects_impl(
|
|
106
|
+
service: Any,
|
|
107
|
+
user_google_email: str,
|
|
108
|
+
page_size: int = 50,
|
|
109
|
+
page_token: Optional[str] = None,
|
|
110
|
+
) -> str:
|
|
111
|
+
"""Internal implementation for list_script_projects.
|
|
112
|
+
|
|
113
|
+
Uses Drive API to find Apps Script files since the Script API
|
|
114
|
+
does not have a projects.list method.
|
|
115
|
+
"""
|
|
116
|
+
logger.info(
|
|
117
|
+
f"[list_script_projects] Email: {user_google_email}, PageSize: {page_size}"
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
# Search for Apps Script files using Drive API
|
|
121
|
+
query = f"mimeType='{_SCRIPT_MIME_TYPE}' and trashed=false"
|
|
122
|
+
request_params = {
|
|
123
|
+
"q": query,
|
|
124
|
+
"pageSize": page_size,
|
|
125
|
+
"fields": "nextPageToken, incompleteSearch, files(id, name, createdTime, modifiedTime)",
|
|
126
|
+
"orderBy": "modifiedTime desc",
|
|
127
|
+
"supportsAllDrives": True,
|
|
128
|
+
"includeItemsFromAllDrives": True,
|
|
129
|
+
"corpora": "allDrives",
|
|
130
|
+
}
|
|
131
|
+
if page_token:
|
|
132
|
+
request_params["pageToken"] = page_token
|
|
133
|
+
|
|
134
|
+
response = await asyncio.to_thread(service.files().list(**request_params).execute)
|
|
135
|
+
|
|
136
|
+
files = response.get("files", [])
|
|
137
|
+
|
|
138
|
+
if not files and "nextPageToken" not in response:
|
|
139
|
+
return flag_incomplete_search("No Apps Script projects found.", response)
|
|
140
|
+
|
|
141
|
+
output = [f"Found {len(files)} Apps Script projects:"]
|
|
142
|
+
for file in files:
|
|
143
|
+
title = file.get("name", "Untitled")
|
|
144
|
+
script_id = file.get("id", "Unknown ID")
|
|
145
|
+
create_time = file.get("createdTime", "Unknown")
|
|
146
|
+
update_time = file.get("modifiedTime", "Unknown")
|
|
147
|
+
|
|
148
|
+
output.append(
|
|
149
|
+
f"- {title} (ID: {script_id}) Created: {create_time} Modified: {update_time}"
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
if "nextPageToken" in response:
|
|
153
|
+
output.append(f"\nNext page token: {response['nextPageToken']}")
|
|
154
|
+
|
|
155
|
+
logger.info(
|
|
156
|
+
f"[list_script_projects] Found {len(files)} projects for {user_google_email}"
|
|
157
|
+
)
|
|
158
|
+
return flag_incomplete_search("\n".join(output), response)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _require_project_action_service(action_services):
|
|
162
|
+
"""Select authentication by action while retaining the named service slots."""
|
|
163
|
+
|
|
164
|
+
def decorator(func):
|
|
165
|
+
original_sig = inspect.signature(func)
|
|
166
|
+
public_params = list(original_sig.parameters.values())[2:]
|
|
167
|
+
dispatch_sig = original_sig.replace(parameters=public_params)
|
|
168
|
+
|
|
169
|
+
@wraps(func)
|
|
170
|
+
async def invoke(service, *args, **kwargs):
|
|
171
|
+
action = (
|
|
172
|
+
dispatch_sig.bind(*args, **kwargs).arguments["action"].lower().strip()
|
|
173
|
+
)
|
|
174
|
+
service_type, _ = action_services[action]
|
|
175
|
+
return await func(
|
|
176
|
+
service if service_type == "drive" else None,
|
|
177
|
+
service if service_type == "script" else None,
|
|
178
|
+
*args,
|
|
179
|
+
**kwargs,
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
invoke.__signature__ = original_sig.replace(
|
|
183
|
+
parameters=[
|
|
184
|
+
inspect.Parameter("service", inspect.Parameter.POSITIONAL_OR_KEYWORD),
|
|
185
|
+
*public_params,
|
|
186
|
+
]
|
|
187
|
+
)
|
|
188
|
+
handlers = {
|
|
189
|
+
action: require_google_service(service_type, scopes)(invoke)
|
|
190
|
+
for action, (service_type, scopes) in action_services.items()
|
|
191
|
+
}
|
|
192
|
+
# Let the existing auth decorator handle the managed-email signature.
|
|
193
|
+
public_sig = inspect.signature(next(iter(handlers.values())))
|
|
194
|
+
|
|
195
|
+
@wraps(func)
|
|
196
|
+
async def wrapper(*args, **kwargs):
|
|
197
|
+
arguments = public_sig.bind(*args, **kwargs).arguments
|
|
198
|
+
action = arguments["action"].lower().strip()
|
|
199
|
+
if action not in handlers:
|
|
200
|
+
choices = " or ".join(repr(value) for value in handlers)
|
|
201
|
+
raise UserInputError(f"Invalid action '{action}'. Must be {choices}.")
|
|
202
|
+
return await handlers[action](**arguments)
|
|
203
|
+
|
|
204
|
+
wrapper.__signature__ = public_sig
|
|
205
|
+
wrapper._required_google_scopes = list(
|
|
206
|
+
dict.fromkeys(
|
|
207
|
+
scope
|
|
208
|
+
for handler in handlers.values()
|
|
209
|
+
for scope in handler._required_google_scopes
|
|
210
|
+
)
|
|
211
|
+
)
|
|
212
|
+
return wrapper
|
|
213
|
+
|
|
214
|
+
return decorator
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
@server.tool(
|
|
218
|
+
title="Get Script Project",
|
|
219
|
+
annotations=ToolAnnotations(
|
|
220
|
+
readOnlyHint=True,
|
|
221
|
+
destructiveHint=False,
|
|
222
|
+
idempotentHint=True,
|
|
223
|
+
openWorldHint=True,
|
|
224
|
+
),
|
|
225
|
+
)
|
|
226
|
+
@_require_project_action_service(
|
|
227
|
+
{"list": ("drive", "drive_read"), "get": ("script", "script_readonly")}
|
|
228
|
+
)
|
|
229
|
+
@handle_http_errors("get_script_project", is_read_only=True, service_type="script")
|
|
230
|
+
async def get_script_project(
|
|
231
|
+
drive_service: Any,
|
|
232
|
+
script_service: Any,
|
|
233
|
+
user_google_email: str,
|
|
234
|
+
action: str,
|
|
235
|
+
script_id: Optional[str] = None,
|
|
236
|
+
file_name: Optional[str] = None,
|
|
237
|
+
page_size: int = 50,
|
|
238
|
+
page_token: Optional[str] = None,
|
|
239
|
+
) -> str:
|
|
240
|
+
"""
|
|
241
|
+
Read Apps Script projects and their source files.
|
|
242
|
+
|
|
243
|
+
Actions:
|
|
244
|
+
- "list": List Apps Script projects accessible to the user (Drive-backed).
|
|
245
|
+
Optional: page_size, page_token.
|
|
246
|
+
- "get": Retrieve one project's metadata and file overview, or one
|
|
247
|
+
complete source file when file_name is provided. Requires script_id.
|
|
248
|
+
|
|
249
|
+
Args:
|
|
250
|
+
drive_service: Injected Drive client (used for list).
|
|
251
|
+
script_service: Injected Script client (used for get).
|
|
252
|
+
user_google_email: User's email address
|
|
253
|
+
action: One of "list", "get".
|
|
254
|
+
script_id: The script project ID (required for get).
|
|
255
|
+
file_name: Optional source file name for get.
|
|
256
|
+
page_size: Number of results per page for list (default: 50).
|
|
257
|
+
page_token: Pagination token for list (optional).
|
|
258
|
+
|
|
259
|
+
Returns:
|
|
260
|
+
str: Formatted result for the requested action.
|
|
261
|
+
"""
|
|
262
|
+
action = action.lower().strip()
|
|
263
|
+
if action == "list":
|
|
264
|
+
return await _list_script_projects_impl(
|
|
265
|
+
drive_service, user_google_email, page_size, page_token
|
|
266
|
+
)
|
|
267
|
+
elif action == "get":
|
|
268
|
+
if not script_id:
|
|
269
|
+
raise UserInputError("script_id is required for get action")
|
|
270
|
+
if file_name:
|
|
271
|
+
return await _get_script_content_impl(
|
|
272
|
+
script_service, user_google_email, script_id, file_name
|
|
273
|
+
)
|
|
274
|
+
return await _get_script_project_impl(
|
|
275
|
+
script_service, user_google_email, script_id
|
|
276
|
+
)
|
|
277
|
+
else:
|
|
278
|
+
raise UserInputError(f"Invalid action '{action}'. Must be 'list' or 'get'.")
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
async def _get_script_project_impl(
|
|
282
|
+
service: Any,
|
|
283
|
+
user_google_email: str,
|
|
284
|
+
script_id: str,
|
|
285
|
+
) -> str:
|
|
286
|
+
"""Internal implementation for get_script_project."""
|
|
287
|
+
logger.info(f"[get_script_project] Email: {user_google_email}, ID: {script_id}")
|
|
288
|
+
|
|
289
|
+
# Get project metadata and content concurrently (independent requests)
|
|
290
|
+
project, content = await asyncio.gather(
|
|
291
|
+
asyncio.to_thread(service.projects().get(scriptId=script_id).execute),
|
|
292
|
+
asyncio.to_thread(service.projects().getContent(scriptId=script_id).execute),
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
title = project.get("title", "Untitled")
|
|
296
|
+
project_script_id = project.get("scriptId", "Unknown")
|
|
297
|
+
creator = project.get("creator", {}).get("email", "Unknown")
|
|
298
|
+
create_time = project.get("createTime", "Unknown")
|
|
299
|
+
update_time = project.get("updateTime", "Unknown")
|
|
300
|
+
|
|
301
|
+
output = [
|
|
302
|
+
f"Project: {title} (ID: {project_script_id})",
|
|
303
|
+
f"Creator: {creator}",
|
|
304
|
+
f"Created: {create_time}",
|
|
305
|
+
f"Modified: {update_time}",
|
|
306
|
+
"",
|
|
307
|
+
"Files:",
|
|
308
|
+
]
|
|
309
|
+
|
|
310
|
+
files = content.get("files", [])
|
|
311
|
+
for i, file in enumerate(files, 1):
|
|
312
|
+
file_name = file.get("name", "Untitled")
|
|
313
|
+
file_type = file.get("type", "Unknown")
|
|
314
|
+
source = file.get("source", "")
|
|
315
|
+
|
|
316
|
+
output.append(f"{i}. {file_name} ({file_type})")
|
|
317
|
+
if source:
|
|
318
|
+
output.append(f" {source[:200]}{'...' if len(source) > 200 else ''}")
|
|
319
|
+
output.append("")
|
|
320
|
+
|
|
321
|
+
logger.info(f"[get_script_project] Retrieved project {script_id}")
|
|
322
|
+
return "\n".join(output)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
async def _get_script_content_impl(
|
|
326
|
+
service: Any,
|
|
327
|
+
user_google_email: str,
|
|
328
|
+
script_id: str,
|
|
329
|
+
file_name: str,
|
|
330
|
+
) -> str:
|
|
331
|
+
"""Internal implementation for get_script_content."""
|
|
332
|
+
logger.info(
|
|
333
|
+
f"[get_script_content] Email: {user_google_email}, ID: {script_id}, File: {file_name}"
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
# Must use getContent() to retrieve files, not get() which only returns metadata
|
|
337
|
+
content = await asyncio.to_thread(
|
|
338
|
+
service.projects().getContent(scriptId=script_id).execute
|
|
339
|
+
)
|
|
340
|
+
|
|
341
|
+
files = content.get("files", [])
|
|
342
|
+
target_file = None
|
|
343
|
+
|
|
344
|
+
for file in files:
|
|
345
|
+
if file.get("name") == file_name:
|
|
346
|
+
target_file = file
|
|
347
|
+
break
|
|
348
|
+
|
|
349
|
+
if not target_file:
|
|
350
|
+
return f"File '{file_name}' not found in project {script_id}"
|
|
351
|
+
|
|
352
|
+
source = target_file.get("source", "")
|
|
353
|
+
file_type = target_file.get("type", "Unknown")
|
|
354
|
+
|
|
355
|
+
output = [f"File: {file_name} ({file_type})", "", source]
|
|
356
|
+
|
|
357
|
+
logger.info(f"[get_script_content] Retrieved file {file_name} from {script_id}")
|
|
358
|
+
return "\n".join(output)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
@server.tool(
|
|
362
|
+
title="Manage Script Content",
|
|
363
|
+
annotations=ToolAnnotations(
|
|
364
|
+
readOnlyHint=False,
|
|
365
|
+
destructiveHint=True,
|
|
366
|
+
idempotentHint=False,
|
|
367
|
+
openWorldHint=True,
|
|
368
|
+
),
|
|
369
|
+
)
|
|
370
|
+
@handle_http_errors("manage_script_content", service_type="script")
|
|
371
|
+
@require_google_service("script", "script_projects")
|
|
372
|
+
async def manage_script_content(
|
|
373
|
+
service: Any,
|
|
374
|
+
user_google_email: str,
|
|
375
|
+
action: str,
|
|
376
|
+
script_id: str,
|
|
377
|
+
files: Optional[List[Dict[str, str]]] = None,
|
|
378
|
+
merge: bool = True,
|
|
379
|
+
) -> str:
|
|
380
|
+
"""
|
|
381
|
+
Update the source files of an Apps Script project.
|
|
382
|
+
|
|
383
|
+
Actions:
|
|
384
|
+
- "update": Create or update files. By default (merge=True) the supplied
|
|
385
|
+
files are overlaid onto the project by (name, type), leaving other
|
|
386
|
+
files untouched. Set merge=False to replace the full project file set;
|
|
387
|
+
any existing file omitted from `files` is permanently deleted.
|
|
388
|
+
|
|
389
|
+
Args:
|
|
390
|
+
service: Injected Google API service client
|
|
391
|
+
user_google_email: User's email address
|
|
392
|
+
action: "update".
|
|
393
|
+
script_id: The script project ID.
|
|
394
|
+
files: File objects with name, type, and source to create or update
|
|
395
|
+
(required for update).
|
|
396
|
+
merge: When True (default), overlay `files` onto the current project.
|
|
397
|
+
When False, replace the full project file set (update only).
|
|
398
|
+
|
|
399
|
+
Returns:
|
|
400
|
+
str: Confirmation with the updated file list.
|
|
401
|
+
"""
|
|
402
|
+
action = action.lower().strip()
|
|
403
|
+
if action == "update":
|
|
404
|
+
if not files:
|
|
405
|
+
raise UserInputError("files is required for update action")
|
|
406
|
+
return await _update_script_content_impl(
|
|
407
|
+
service, user_google_email, script_id, files, merge
|
|
408
|
+
)
|
|
409
|
+
else:
|
|
410
|
+
raise UserInputError(f"Invalid action '{action}'. Must be 'update'.")
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
async def _create_script_project_impl(
|
|
414
|
+
service: Any,
|
|
415
|
+
user_google_email: str,
|
|
416
|
+
title: str,
|
|
417
|
+
parent_id: Optional[str] = None,
|
|
418
|
+
) -> str:
|
|
419
|
+
"""Internal implementation for create_script_project."""
|
|
420
|
+
logger.info(
|
|
421
|
+
f"[create_script_project] Email: {user_google_email}, title_len={len(title)}"
|
|
422
|
+
)
|
|
423
|
+
|
|
424
|
+
request_body = {"title": title}
|
|
425
|
+
|
|
426
|
+
if parent_id:
|
|
427
|
+
request_body["parentId"] = parent_id
|
|
428
|
+
|
|
429
|
+
project = await asyncio.to_thread(
|
|
430
|
+
service.projects().create(body=request_body).execute
|
|
431
|
+
)
|
|
432
|
+
|
|
433
|
+
script_id = project.get("scriptId", "Unknown")
|
|
434
|
+
edit_url = f"https://script.google.com/d/{script_id}/edit"
|
|
435
|
+
|
|
436
|
+
output = [
|
|
437
|
+
f"Created Apps Script project: {title}",
|
|
438
|
+
f"Script ID: {script_id}",
|
|
439
|
+
f"Edit URL: {edit_url}",
|
|
440
|
+
]
|
|
441
|
+
|
|
442
|
+
logger.info(f"[create_script_project] Created project {script_id}")
|
|
443
|
+
return "\n".join(output)
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
async def _update_script_content_impl(
|
|
447
|
+
service: Any,
|
|
448
|
+
user_google_email: str,
|
|
449
|
+
script_id: str,
|
|
450
|
+
files: List[Dict[str, str]],
|
|
451
|
+
merge: bool = True,
|
|
452
|
+
) -> str:
|
|
453
|
+
"""Internal implementation for update_script_content."""
|
|
454
|
+
logger.info(
|
|
455
|
+
f"[update_script_content] Email: {user_google_email}, ID: {script_id}, "
|
|
456
|
+
f"Files: {len(files)}, merge: {merge}"
|
|
457
|
+
)
|
|
458
|
+
|
|
459
|
+
files_to_push = [_normalize_script_file(file) for file in files]
|
|
460
|
+
|
|
461
|
+
async with _get_script_update_lock(script_id):
|
|
462
|
+
if merge:
|
|
463
|
+
current_content = await asyncio.to_thread(
|
|
464
|
+
service.projects().getContent(scriptId=script_id).execute
|
|
465
|
+
)
|
|
466
|
+
files_to_push = _merge_script_files(
|
|
467
|
+
current_content.get("files", []), files_to_push
|
|
468
|
+
)
|
|
469
|
+
|
|
470
|
+
request_body = {"files": files_to_push}
|
|
471
|
+
|
|
472
|
+
updated_content = await asyncio.to_thread(
|
|
473
|
+
service.projects()
|
|
474
|
+
.updateContent(scriptId=script_id, body=request_body)
|
|
475
|
+
.execute
|
|
476
|
+
)
|
|
477
|
+
|
|
478
|
+
mode = "merged into project" if merge else "replaced entire project"
|
|
479
|
+
output = [
|
|
480
|
+
f"Updated script project: {script_id} ({mode})",
|
|
481
|
+
"",
|
|
482
|
+
"Files in project after update:",
|
|
483
|
+
]
|
|
484
|
+
|
|
485
|
+
for file in updated_content.get("files", []):
|
|
486
|
+
file_name = file.get("name", "Untitled")
|
|
487
|
+
file_type = file.get("type", "Unknown")
|
|
488
|
+
output.append(f"- {file_name} ({file_type})")
|
|
489
|
+
|
|
490
|
+
logger.info(
|
|
491
|
+
f"[update_script_content] Pushed {len(files_to_push)} files to {script_id}"
|
|
492
|
+
)
|
|
493
|
+
return "\n".join(output)
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
async def _run_script_function_impl(
|
|
497
|
+
service: Any,
|
|
498
|
+
user_google_email: str,
|
|
499
|
+
script_id: str,
|
|
500
|
+
function_name: str,
|
|
501
|
+
parameters: Optional[list[object]] = None,
|
|
502
|
+
dev_mode: bool = False,
|
|
503
|
+
deployment_id: Optional[str] = None,
|
|
504
|
+
) -> str:
|
|
505
|
+
"""Internal implementation for run_script_function."""
|
|
506
|
+
logger.info(
|
|
507
|
+
f"[run_script_function] Email: {user_google_email}, ID: {script_id}, Function: {function_name}"
|
|
508
|
+
)
|
|
509
|
+
|
|
510
|
+
request_body = {"function": function_name, "devMode": dev_mode}
|
|
511
|
+
|
|
512
|
+
if parameters:
|
|
513
|
+
request_body["parameters"] = parameters
|
|
514
|
+
|
|
515
|
+
if not deployment_id:
|
|
516
|
+
deployment_id = await _resolve_execution_deployment_id(service, script_id)
|
|
517
|
+
if not deployment_id:
|
|
518
|
+
return (
|
|
519
|
+
"Execution failed\n"
|
|
520
|
+
f"Function: {function_name}\n"
|
|
521
|
+
"Error: No versioned API Executable deployment was found. In the "
|
|
522
|
+
"Apps Script editor, use Deploy > New deployment > API Executable. "
|
|
523
|
+
"The script and caller must share a standard Google Cloud project. "
|
|
524
|
+
"manage_deployment(action='create') is sufficient only when the "
|
|
525
|
+
"script manifest already defines executionApi."
|
|
526
|
+
)
|
|
527
|
+
|
|
528
|
+
response = await asyncio.to_thread(
|
|
529
|
+
service.scripts().run(scriptId=deployment_id, body=request_body).execute
|
|
530
|
+
)
|
|
531
|
+
|
|
532
|
+
if "error" in response:
|
|
533
|
+
error_details = response["error"]
|
|
534
|
+
error_message = error_details.get("message", "Unknown error")
|
|
535
|
+
return f"Execution failed\nFunction: {function_name}\nError: {error_message}"
|
|
536
|
+
|
|
537
|
+
result = response.get("response", {}).get("result")
|
|
538
|
+
output = [
|
|
539
|
+
"Execution successful",
|
|
540
|
+
f"Function: {function_name}",
|
|
541
|
+
f"Result: {result}",
|
|
542
|
+
]
|
|
543
|
+
|
|
544
|
+
logger.info(f"[run_script_function] Successfully executed {function_name}")
|
|
545
|
+
return "\n".join(output)
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
async def _list_all_pages(list_method: Any, script_id: str, key: str) -> List[Any]:
|
|
549
|
+
"""Collect every page of a script-scoped list call (deployments, versions)."""
|
|
550
|
+
items = []
|
|
551
|
+
page_token = None
|
|
552
|
+
while True:
|
|
553
|
+
list_params = {"scriptId": script_id}
|
|
554
|
+
if page_token:
|
|
555
|
+
list_params["pageToken"] = page_token
|
|
556
|
+
|
|
557
|
+
response = await asyncio.to_thread(list_method(**list_params).execute)
|
|
558
|
+
items.extend(response.get(key, []))
|
|
559
|
+
page_token = response.get("nextPageToken")
|
|
560
|
+
if not page_token:
|
|
561
|
+
return items
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
async def _resolve_execution_deployment_id(
|
|
565
|
+
service: Any,
|
|
566
|
+
script_id: str,
|
|
567
|
+
) -> Optional[str]:
|
|
568
|
+
"""Return the newest versioned API Executable deployment for a project."""
|
|
569
|
+
all_deployments = await _list_all_pages(
|
|
570
|
+
service.projects().deployments().list, script_id, "deployments"
|
|
571
|
+
)
|
|
572
|
+
|
|
573
|
+
candidates = [
|
|
574
|
+
deployment
|
|
575
|
+
for deployment in all_deployments
|
|
576
|
+
if deployment.get("deploymentId")
|
|
577
|
+
and deployment.get("deploymentConfig", {}).get("versionNumber") is not None
|
|
578
|
+
and any(
|
|
579
|
+
entry_point.get("entryPointType") == "EXECUTION_API"
|
|
580
|
+
for entry_point in deployment.get("entryPoints", [])
|
|
581
|
+
)
|
|
582
|
+
]
|
|
583
|
+
if not candidates:
|
|
584
|
+
return None
|
|
585
|
+
|
|
586
|
+
latest = max(
|
|
587
|
+
candidates,
|
|
588
|
+
key=lambda deployment: deployment["deploymentConfig"]["versionNumber"],
|
|
589
|
+
)
|
|
590
|
+
return latest["deploymentId"]
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
@server.tool(
|
|
594
|
+
title="Run Script Function",
|
|
595
|
+
annotations=ToolAnnotations(
|
|
596
|
+
readOnlyHint=False,
|
|
597
|
+
destructiveHint=True,
|
|
598
|
+
idempotentHint=False,
|
|
599
|
+
openWorldHint=True,
|
|
600
|
+
),
|
|
601
|
+
)
|
|
602
|
+
@handle_http_errors("run_script_function", service_type="script")
|
|
603
|
+
@require_google_service("script", ["script_run", "script_deployments_readonly"])
|
|
604
|
+
async def run_script_function(
|
|
605
|
+
service: Any,
|
|
606
|
+
user_google_email: str,
|
|
607
|
+
script_id: str,
|
|
608
|
+
function_name: str,
|
|
609
|
+
parameters: Optional[ObjectList] = None,
|
|
610
|
+
dev_mode: bool = False,
|
|
611
|
+
deployment_id: Optional[str] = None,
|
|
612
|
+
) -> str:
|
|
613
|
+
"""
|
|
614
|
+
Executes a function in a deployed script.
|
|
615
|
+
|
|
616
|
+
Args:
|
|
617
|
+
service: Injected Google API service client
|
|
618
|
+
user_google_email: User's email address
|
|
619
|
+
script_id: The script project ID
|
|
620
|
+
function_name: Name of function to execute
|
|
621
|
+
parameters: Optional list of parameters to pass
|
|
622
|
+
dev_mode: Whether to run latest code vs deployed version
|
|
623
|
+
deployment_id: Optional API Executable deployment ID. When supplied,
|
|
624
|
+
skips the automatic deployment lookup. When omitted, the versioned
|
|
625
|
+
API Executable deployment with the highest version number is used.
|
|
626
|
+
|
|
627
|
+
Returns:
|
|
628
|
+
str: Formatted string with execution result or error
|
|
629
|
+
"""
|
|
630
|
+
return await _run_script_function_impl(
|
|
631
|
+
service,
|
|
632
|
+
user_google_email,
|
|
633
|
+
script_id,
|
|
634
|
+
function_name,
|
|
635
|
+
parameters,
|
|
636
|
+
dev_mode,
|
|
637
|
+
deployment_id,
|
|
638
|
+
)
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
async def _create_deployment_impl(
|
|
642
|
+
service: Any,
|
|
643
|
+
user_google_email: str,
|
|
644
|
+
script_id: str,
|
|
645
|
+
description: str,
|
|
646
|
+
version_description: Optional[str] = None,
|
|
647
|
+
) -> str:
|
|
648
|
+
"""Internal implementation for create_deployment.
|
|
649
|
+
|
|
650
|
+
Creates a new version first, then creates a deployment using that version.
|
|
651
|
+
"""
|
|
652
|
+
logger.info(
|
|
653
|
+
f"[create_deployment] Email: {user_google_email}, ID: {script_id}, desc_len={len(description) if description else 0}"
|
|
654
|
+
)
|
|
655
|
+
|
|
656
|
+
# First, create a new version
|
|
657
|
+
version_body = {"description": version_description or description}
|
|
658
|
+
version = await asyncio.to_thread(
|
|
659
|
+
service.projects()
|
|
660
|
+
.versions()
|
|
661
|
+
.create(scriptId=script_id, body=version_body)
|
|
662
|
+
.execute
|
|
663
|
+
)
|
|
664
|
+
version_number = version.get("versionNumber")
|
|
665
|
+
logger.info(f"[create_deployment] Created version {version_number}")
|
|
666
|
+
|
|
667
|
+
# Now create the deployment with the version number
|
|
668
|
+
deployment_body = {
|
|
669
|
+
"versionNumber": version_number,
|
|
670
|
+
"description": description,
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
deployment = await asyncio.to_thread(
|
|
674
|
+
service.projects()
|
|
675
|
+
.deployments()
|
|
676
|
+
.create(scriptId=script_id, body=deployment_body)
|
|
677
|
+
.execute
|
|
678
|
+
)
|
|
679
|
+
|
|
680
|
+
deployment_id = deployment.get("deploymentId", "Unknown")
|
|
681
|
+
|
|
682
|
+
output = [
|
|
683
|
+
f"Created deployment for script: {script_id}",
|
|
684
|
+
f"Deployment ID: {deployment_id}",
|
|
685
|
+
f"Version: {version_number}",
|
|
686
|
+
f"Description: {description}",
|
|
687
|
+
]
|
|
688
|
+
|
|
689
|
+
logger.info(f"[create_deployment] Created deployment {deployment_id}")
|
|
690
|
+
return "\n".join(output)
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
@server.tool(
|
|
694
|
+
title="Manage Deployment",
|
|
695
|
+
annotations=ToolAnnotations(
|
|
696
|
+
readOnlyHint=False,
|
|
697
|
+
destructiveHint=True,
|
|
698
|
+
idempotentHint=False,
|
|
699
|
+
openWorldHint=True,
|
|
700
|
+
),
|
|
701
|
+
)
|
|
702
|
+
@handle_http_errors("manage_deployment", service_type="script")
|
|
703
|
+
@require_google_service("script", "script_deployments")
|
|
704
|
+
async def manage_deployment(
|
|
705
|
+
service: Any,
|
|
706
|
+
user_google_email: str,
|
|
707
|
+
action: str,
|
|
708
|
+
script_id: str,
|
|
709
|
+
deployment_id: Optional[str] = None,
|
|
710
|
+
description: Optional[str] = None,
|
|
711
|
+
version_description: Optional[str] = None,
|
|
712
|
+
version_number: Optional[int] = None,
|
|
713
|
+
) -> str:
|
|
714
|
+
"""
|
|
715
|
+
Create, update, or delete Apps Script deployments.
|
|
716
|
+
|
|
717
|
+
Args:
|
|
718
|
+
service: Injected Google API service client
|
|
719
|
+
user_google_email: User's email address
|
|
720
|
+
action: Action to perform - "create", "update", or "delete"
|
|
721
|
+
script_id: The script project ID
|
|
722
|
+
deployment_id: The deployment ID (required for update and delete)
|
|
723
|
+
description: Deployment description (required for create; optional for update
|
|
724
|
+
when version_number is supplied)
|
|
725
|
+
version_description: Optional version description (for create only)
|
|
726
|
+
version_number: Version number to point the deployment at (for update only).
|
|
727
|
+
Required to roll a deployment forward to a newly created script version.
|
|
728
|
+
|
|
729
|
+
Returns:
|
|
730
|
+
str: Formatted string with deployment details or confirmation
|
|
731
|
+
"""
|
|
732
|
+
action = action.lower().strip()
|
|
733
|
+
if action == "create":
|
|
734
|
+
if description is None or description.strip() == "":
|
|
735
|
+
raise ValueError("description is required for create action")
|
|
736
|
+
return await _create_deployment_impl(
|
|
737
|
+
service, user_google_email, script_id, description, version_description
|
|
738
|
+
)
|
|
739
|
+
elif action == "update":
|
|
740
|
+
if not deployment_id:
|
|
741
|
+
raise ValueError("deployment_id is required for update action")
|
|
742
|
+
has_description = description is not None and description.strip() != ""
|
|
743
|
+
if not has_description and version_number is None:
|
|
744
|
+
raise ValueError(
|
|
745
|
+
"description or version_number is required for update action"
|
|
746
|
+
)
|
|
747
|
+
return await _update_deployment_impl(
|
|
748
|
+
service,
|
|
749
|
+
user_google_email,
|
|
750
|
+
script_id,
|
|
751
|
+
deployment_id,
|
|
752
|
+
description,
|
|
753
|
+
version_number,
|
|
754
|
+
)
|
|
755
|
+
elif action == "delete":
|
|
756
|
+
if not deployment_id:
|
|
757
|
+
raise ValueError("deployment_id is required for delete action")
|
|
758
|
+
return await _delete_deployment_impl(
|
|
759
|
+
service, user_google_email, script_id, deployment_id
|
|
760
|
+
)
|
|
761
|
+
else:
|
|
762
|
+
raise ValueError(
|
|
763
|
+
f"Invalid action '{action}'. Must be 'create', 'update', or 'delete'."
|
|
764
|
+
)
|
|
765
|
+
|
|
766
|
+
|
|
767
|
+
async def _list_deployments_impl(
|
|
768
|
+
service: Any,
|
|
769
|
+
user_google_email: str,
|
|
770
|
+
script_id: str,
|
|
771
|
+
) -> str:
|
|
772
|
+
"""Internal implementation for list_deployments."""
|
|
773
|
+
logger.info(f"[list_deployments] Email: {user_google_email}, ID: {script_id}")
|
|
774
|
+
|
|
775
|
+
deployments = await _list_all_pages(
|
|
776
|
+
service.projects().deployments().list, script_id, "deployments"
|
|
777
|
+
)
|
|
778
|
+
|
|
779
|
+
if not deployments:
|
|
780
|
+
return f"No deployments found for script: {script_id}"
|
|
781
|
+
|
|
782
|
+
output = [f"Deployments for script: {script_id}", ""]
|
|
783
|
+
|
|
784
|
+
for i, deployment in enumerate(deployments, 1):
|
|
785
|
+
deployment_id = deployment.get("deploymentId", "Unknown")
|
|
786
|
+
# description and versionNumber live under deploymentConfig; fall back to
|
|
787
|
+
# any top-level description for forward/backward compatibility.
|
|
788
|
+
config = deployment.get("deploymentConfig", {})
|
|
789
|
+
description = (
|
|
790
|
+
config.get("description")
|
|
791
|
+
or deployment.get("description")
|
|
792
|
+
or "No description"
|
|
793
|
+
)
|
|
794
|
+
update_time = deployment.get("updateTime", "Unknown")
|
|
795
|
+
# A HEAD deployment has no versionNumber — it always serves the latest
|
|
796
|
+
# saved content rather than a pinned version.
|
|
797
|
+
version_number = config.get("versionNumber")
|
|
798
|
+
version_label = (
|
|
799
|
+
str(version_number) if version_number is not None else "HEAD (latest)"
|
|
800
|
+
)
|
|
801
|
+
|
|
802
|
+
output.append(f"{i}. {description} ({deployment_id})")
|
|
803
|
+
output.append(f" Version: {version_label}")
|
|
804
|
+
output.append(f" Updated: {update_time}")
|
|
805
|
+
output.append("")
|
|
806
|
+
|
|
807
|
+
logger.info(f"[list_deployments] Found {len(deployments)} deployments")
|
|
808
|
+
return "\n".join(output)
|
|
809
|
+
|
|
810
|
+
|
|
811
|
+
@server.tool(
|
|
812
|
+
title="List Script Deployments",
|
|
813
|
+
annotations=ToolAnnotations(
|
|
814
|
+
readOnlyHint=True,
|
|
815
|
+
destructiveHint=False,
|
|
816
|
+
idempotentHint=True,
|
|
817
|
+
openWorldHint=True,
|
|
818
|
+
),
|
|
819
|
+
)
|
|
820
|
+
@handle_http_errors("list_script_deployments", is_read_only=True, service_type="script")
|
|
821
|
+
@require_google_service("script", "script_deployments_readonly")
|
|
822
|
+
async def list_script_deployments(
|
|
823
|
+
service: Any,
|
|
824
|
+
user_google_email: str,
|
|
825
|
+
script_id: str,
|
|
826
|
+
) -> str:
|
|
827
|
+
"""List deployments for an Apps Script project."""
|
|
828
|
+
return await _list_deployments_impl(service, user_google_email, script_id)
|
|
829
|
+
|
|
830
|
+
|
|
831
|
+
async def _update_deployment_impl(
|
|
832
|
+
service: Any,
|
|
833
|
+
user_google_email: str,
|
|
834
|
+
script_id: str,
|
|
835
|
+
deployment_id: str,
|
|
836
|
+
description: Optional[str] = None,
|
|
837
|
+
version_number: Optional[int] = None,
|
|
838
|
+
) -> str:
|
|
839
|
+
"""Internal implementation for update_deployment.
|
|
840
|
+
|
|
841
|
+
The Apps Script ``projects.deployments.update`` endpoint expects every
|
|
842
|
+
field nested inside a ``deploymentConfig`` object; sending them at the top
|
|
843
|
+
level fails with ``400 Invalid JSON payload``. ``scriptId`` is always part
|
|
844
|
+
of the config, and ``versionNumber`` is required to repoint a deployment at
|
|
845
|
+
a newer script version.
|
|
846
|
+
"""
|
|
847
|
+
logger.info(
|
|
848
|
+
f"[update_deployment] Email: {user_google_email}, Script: {script_id}, Deployment: {deployment_id}"
|
|
849
|
+
)
|
|
850
|
+
|
|
851
|
+
async with _get_script_update_lock(script_id):
|
|
852
|
+
current = await asyncio.to_thread(
|
|
853
|
+
service.projects()
|
|
854
|
+
.deployments()
|
|
855
|
+
.get(scriptId=script_id, deploymentId=deployment_id)
|
|
856
|
+
.execute
|
|
857
|
+
)
|
|
858
|
+
deployment_config: Dict[str, Any] = dict(current.get("deploymentConfig") or {})
|
|
859
|
+
deployment_config["scriptId"] = script_id
|
|
860
|
+
if version_number is not None:
|
|
861
|
+
deployment_config["versionNumber"] = version_number
|
|
862
|
+
if description and description.strip():
|
|
863
|
+
deployment_config["description"] = description
|
|
864
|
+
|
|
865
|
+
request_body = {"deploymentConfig": deployment_config}
|
|
866
|
+
|
|
867
|
+
deployment = await asyncio.to_thread(
|
|
868
|
+
service.projects()
|
|
869
|
+
.deployments()
|
|
870
|
+
.update(scriptId=script_id, deploymentId=deployment_id, body=request_body)
|
|
871
|
+
.execute
|
|
872
|
+
)
|
|
873
|
+
|
|
874
|
+
deployment_config_resp = deployment.get("deploymentConfig", {})
|
|
875
|
+
resolved_version = deployment_config_resp.get("versionNumber", version_number)
|
|
876
|
+
resolved_description = deployment_config_resp.get(
|
|
877
|
+
"description", deployment.get("description", "No description")
|
|
878
|
+
)
|
|
879
|
+
|
|
880
|
+
output = [
|
|
881
|
+
f"Updated deployment: {deployment_id}",
|
|
882
|
+
f"Script: {script_id}",
|
|
883
|
+
f"Version: {resolved_version if resolved_version is not None else 'unchanged'}",
|
|
884
|
+
f"Description: {resolved_description}",
|
|
885
|
+
]
|
|
886
|
+
|
|
887
|
+
logger.info(f"[update_deployment] Updated deployment {deployment_id}")
|
|
888
|
+
return "\n".join(output)
|
|
889
|
+
|
|
890
|
+
|
|
891
|
+
async def _delete_deployment_impl(
|
|
892
|
+
service: Any,
|
|
893
|
+
user_google_email: str,
|
|
894
|
+
script_id: str,
|
|
895
|
+
deployment_id: str,
|
|
896
|
+
) -> str:
|
|
897
|
+
"""Internal implementation for delete_deployment."""
|
|
898
|
+
logger.info(
|
|
899
|
+
f"[delete_deployment] Email: {user_google_email}, Script: {script_id}, Deployment: {deployment_id}"
|
|
900
|
+
)
|
|
901
|
+
|
|
902
|
+
await asyncio.to_thread(
|
|
903
|
+
service.projects()
|
|
904
|
+
.deployments()
|
|
905
|
+
.delete(scriptId=script_id, deploymentId=deployment_id)
|
|
906
|
+
.execute
|
|
907
|
+
)
|
|
908
|
+
|
|
909
|
+
output = f"Deleted deployment: {deployment_id} from script: {script_id}"
|
|
910
|
+
|
|
911
|
+
logger.info(f"[delete_deployment] Deleted deployment {deployment_id}")
|
|
912
|
+
return output
|
|
913
|
+
|
|
914
|
+
|
|
915
|
+
async def _list_script_processes_impl(
|
|
916
|
+
service: Any,
|
|
917
|
+
user_google_email: str,
|
|
918
|
+
page_size: int = 50,
|
|
919
|
+
script_id: Optional[str] = None,
|
|
920
|
+
) -> str:
|
|
921
|
+
"""Internal implementation for list_script_processes."""
|
|
922
|
+
logger.info(
|
|
923
|
+
f"[list_script_processes] Email: {user_google_email}, PageSize: {page_size}"
|
|
924
|
+
)
|
|
925
|
+
|
|
926
|
+
if script_id:
|
|
927
|
+
# processes.list() has no top-level scriptId parameter; the
|
|
928
|
+
# script-scoped endpoint takes it directly.
|
|
929
|
+
response = await asyncio.to_thread(
|
|
930
|
+
service.processes()
|
|
931
|
+
.listScriptProcesses(scriptId=script_id, pageSize=page_size)
|
|
932
|
+
.execute
|
|
933
|
+
)
|
|
934
|
+
else:
|
|
935
|
+
response = await asyncio.to_thread(
|
|
936
|
+
service.processes().list(pageSize=page_size).execute
|
|
937
|
+
)
|
|
938
|
+
|
|
939
|
+
processes = response.get("processes", [])
|
|
940
|
+
|
|
941
|
+
if not processes:
|
|
942
|
+
return "No recent script executions found."
|
|
943
|
+
|
|
944
|
+
output = ["Recent script executions:", ""]
|
|
945
|
+
|
|
946
|
+
for i, process in enumerate(processes, 1):
|
|
947
|
+
function_name = process.get("functionName", "Unknown")
|
|
948
|
+
process_status = process.get("processStatus", "Unknown")
|
|
949
|
+
start_time = process.get("startTime", "Unknown")
|
|
950
|
+
duration = process.get("duration", "Unknown")
|
|
951
|
+
|
|
952
|
+
output.append(f"{i}. {function_name}")
|
|
953
|
+
output.append(f" Status: {process_status}")
|
|
954
|
+
output.append(f" Started: {start_time}")
|
|
955
|
+
output.append(f" Duration: {duration}")
|
|
956
|
+
output.append("")
|
|
957
|
+
|
|
958
|
+
logger.info(f"[list_script_processes] Found {len(processes)} processes")
|
|
959
|
+
return "\n".join(output)
|
|
960
|
+
|
|
961
|
+
|
|
962
|
+
# ============================================================================
|
|
963
|
+
# Delete Script Project
|
|
964
|
+
# ============================================================================
|
|
965
|
+
|
|
966
|
+
|
|
967
|
+
async def _delete_script_project_impl(
|
|
968
|
+
service: Any,
|
|
969
|
+
user_google_email: str,
|
|
970
|
+
script_id: str,
|
|
971
|
+
) -> str:
|
|
972
|
+
"""Internal implementation for delete_script_project."""
|
|
973
|
+
logger.info(
|
|
974
|
+
f"[delete_script_project] Email: {user_google_email}, ScriptID: {script_id}"
|
|
975
|
+
)
|
|
976
|
+
|
|
977
|
+
# Apps Script projects are stored as Drive files
|
|
978
|
+
file_info = await asyncio.to_thread(
|
|
979
|
+
service.files()
|
|
980
|
+
.get(fileId=script_id, fields="mimeType", supportsAllDrives=True)
|
|
981
|
+
.execute
|
|
982
|
+
)
|
|
983
|
+
if file_info.get("mimeType") != _SCRIPT_MIME_TYPE:
|
|
984
|
+
raise UserInputError(
|
|
985
|
+
f"{script_id} is not an Apps Script project, so it was not deleted."
|
|
986
|
+
)
|
|
987
|
+
await asyncio.to_thread(
|
|
988
|
+
service.files().delete(fileId=script_id, supportsAllDrives=True).execute
|
|
989
|
+
)
|
|
990
|
+
|
|
991
|
+
logger.info(f"[delete_script_project] Deleted script {script_id}")
|
|
992
|
+
return f"Deleted Apps Script project: {script_id}"
|
|
993
|
+
|
|
994
|
+
|
|
995
|
+
@server.tool(
|
|
996
|
+
title="Manage Script Project",
|
|
997
|
+
annotations=ToolAnnotations(
|
|
998
|
+
readOnlyHint=False,
|
|
999
|
+
destructiveHint=True,
|
|
1000
|
+
idempotentHint=False,
|
|
1001
|
+
openWorldHint=True,
|
|
1002
|
+
),
|
|
1003
|
+
)
|
|
1004
|
+
@_require_project_action_service(
|
|
1005
|
+
{"create": ("script", "script_projects"), "delete": ("drive", "drive_full")}
|
|
1006
|
+
)
|
|
1007
|
+
@handle_http_errors("manage_script_project", service_type="script")
|
|
1008
|
+
async def manage_script_project(
|
|
1009
|
+
drive_service: Any,
|
|
1010
|
+
script_service: Any,
|
|
1011
|
+
user_google_email: str,
|
|
1012
|
+
action: str,
|
|
1013
|
+
script_id: Optional[str] = None,
|
|
1014
|
+
title: Optional[str] = None,
|
|
1015
|
+
parent_id: Optional[str] = None,
|
|
1016
|
+
) -> str:
|
|
1017
|
+
"""
|
|
1018
|
+
Create or delete an Apps Script project.
|
|
1019
|
+
|
|
1020
|
+
Actions:
|
|
1021
|
+
- "create": Create a project. Requires title; parent_id is optional.
|
|
1022
|
+
- "delete": Permanently delete a project. Requires script_id.
|
|
1023
|
+
"""
|
|
1024
|
+
action = action.lower().strip()
|
|
1025
|
+
if action == "create":
|
|
1026
|
+
if not title or not title.strip():
|
|
1027
|
+
raise UserInputError("title is required for create action")
|
|
1028
|
+
return await _create_script_project_impl(
|
|
1029
|
+
script_service, user_google_email, title, parent_id
|
|
1030
|
+
)
|
|
1031
|
+
elif action == "delete":
|
|
1032
|
+
if not script_id:
|
|
1033
|
+
raise UserInputError("script_id is required for delete action")
|
|
1034
|
+
return await _delete_script_project_impl(
|
|
1035
|
+
drive_service, user_google_email, script_id
|
|
1036
|
+
)
|
|
1037
|
+
else:
|
|
1038
|
+
raise UserInputError(
|
|
1039
|
+
f"Invalid action '{action}'. Must be 'create' or 'delete'."
|
|
1040
|
+
)
|
|
1041
|
+
|
|
1042
|
+
|
|
1043
|
+
# ============================================================================
|
|
1044
|
+
# Version Management
|
|
1045
|
+
# ============================================================================
|
|
1046
|
+
|
|
1047
|
+
|
|
1048
|
+
async def _list_versions_impl(
|
|
1049
|
+
service: Any,
|
|
1050
|
+
user_google_email: str,
|
|
1051
|
+
script_id: str,
|
|
1052
|
+
) -> str:
|
|
1053
|
+
"""Internal implementation for list_versions."""
|
|
1054
|
+
logger.info(f"[list_versions] Email: {user_google_email}, ScriptID: {script_id}")
|
|
1055
|
+
|
|
1056
|
+
versions = await _list_all_pages(
|
|
1057
|
+
service.projects().versions().list, script_id, "versions"
|
|
1058
|
+
)
|
|
1059
|
+
|
|
1060
|
+
if not versions:
|
|
1061
|
+
return f"No versions found for script: {script_id}"
|
|
1062
|
+
|
|
1063
|
+
output = [f"Versions for script: {script_id}", ""]
|
|
1064
|
+
|
|
1065
|
+
for version in versions:
|
|
1066
|
+
version_number = version.get("versionNumber", "Unknown")
|
|
1067
|
+
description = version.get("description", "No description")
|
|
1068
|
+
create_time = version.get("createTime", "Unknown")
|
|
1069
|
+
|
|
1070
|
+
output.append(f"Version {version_number}: {description}")
|
|
1071
|
+
output.append(f" Created: {create_time}")
|
|
1072
|
+
output.append("")
|
|
1073
|
+
|
|
1074
|
+
logger.info(f"[list_versions] Found {len(versions)} versions")
|
|
1075
|
+
return "\n".join(output)
|
|
1076
|
+
|
|
1077
|
+
|
|
1078
|
+
@server.tool(
|
|
1079
|
+
title="Manage Script Version",
|
|
1080
|
+
annotations=ToolAnnotations(
|
|
1081
|
+
readOnlyHint=False,
|
|
1082
|
+
destructiveHint=False,
|
|
1083
|
+
idempotentHint=False,
|
|
1084
|
+
openWorldHint=True,
|
|
1085
|
+
),
|
|
1086
|
+
)
|
|
1087
|
+
@handle_http_errors("manage_script_version", service_type="script")
|
|
1088
|
+
@require_google_service("script", "script_full")
|
|
1089
|
+
async def manage_script_version(
|
|
1090
|
+
service: Any,
|
|
1091
|
+
user_google_email: str,
|
|
1092
|
+
action: str,
|
|
1093
|
+
script_id: str,
|
|
1094
|
+
description: Optional[str] = None,
|
|
1095
|
+
) -> str:
|
|
1096
|
+
"""
|
|
1097
|
+
Create immutable version snapshots of a script project.
|
|
1098
|
+
|
|
1099
|
+
Versions capture a snapshot of the current script code; once created they
|
|
1100
|
+
cannot be modified.
|
|
1101
|
+
|
|
1102
|
+
Actions:
|
|
1103
|
+
- "create": Create a new version from the current code. Optional
|
|
1104
|
+
description.
|
|
1105
|
+
|
|
1106
|
+
Args:
|
|
1107
|
+
service: Injected Google API service client
|
|
1108
|
+
user_google_email: User's email address
|
|
1109
|
+
action: "create".
|
|
1110
|
+
script_id: The script project ID.
|
|
1111
|
+
description: Optional description for the new version (create only).
|
|
1112
|
+
|
|
1113
|
+
Returns:
|
|
1114
|
+
str: Formatted result for the requested action.
|
|
1115
|
+
"""
|
|
1116
|
+
action = action.lower().strip()
|
|
1117
|
+
if action == "create":
|
|
1118
|
+
return await _create_version_impl(
|
|
1119
|
+
service, user_google_email, script_id, description
|
|
1120
|
+
)
|
|
1121
|
+
else:
|
|
1122
|
+
raise UserInputError(f"Invalid action '{action}'. Must be 'create'.")
|
|
1123
|
+
|
|
1124
|
+
|
|
1125
|
+
async def _create_version_impl(
|
|
1126
|
+
service: Any,
|
|
1127
|
+
user_google_email: str,
|
|
1128
|
+
script_id: str,
|
|
1129
|
+
description: Optional[str] = None,
|
|
1130
|
+
) -> str:
|
|
1131
|
+
"""Internal implementation for create_version."""
|
|
1132
|
+
logger.info(f"[create_version] Email: {user_google_email}, ScriptID: {script_id}")
|
|
1133
|
+
|
|
1134
|
+
request_body = {}
|
|
1135
|
+
if description:
|
|
1136
|
+
request_body["description"] = description
|
|
1137
|
+
|
|
1138
|
+
version = await asyncio.to_thread(
|
|
1139
|
+
service.projects()
|
|
1140
|
+
.versions()
|
|
1141
|
+
.create(scriptId=script_id, body=request_body)
|
|
1142
|
+
.execute
|
|
1143
|
+
)
|
|
1144
|
+
|
|
1145
|
+
version_number = version.get("versionNumber", "Unknown")
|
|
1146
|
+
create_time = version.get("createTime", "Unknown")
|
|
1147
|
+
|
|
1148
|
+
output = [
|
|
1149
|
+
f"Created version {version_number} for script: {script_id}",
|
|
1150
|
+
f"Description: {description or 'No description'}",
|
|
1151
|
+
f"Created: {create_time}",
|
|
1152
|
+
]
|
|
1153
|
+
|
|
1154
|
+
logger.info(f"[create_version] Created version {version_number}")
|
|
1155
|
+
return "\n".join(output)
|
|
1156
|
+
|
|
1157
|
+
|
|
1158
|
+
async def _get_version_impl(
|
|
1159
|
+
service: Any,
|
|
1160
|
+
user_google_email: str,
|
|
1161
|
+
script_id: str,
|
|
1162
|
+
version_number: int,
|
|
1163
|
+
) -> str:
|
|
1164
|
+
"""Internal implementation for get_version."""
|
|
1165
|
+
logger.info(
|
|
1166
|
+
f"[get_version] Email: {user_google_email}, ScriptID: {script_id}, Version: {version_number}"
|
|
1167
|
+
)
|
|
1168
|
+
|
|
1169
|
+
version = await asyncio.to_thread(
|
|
1170
|
+
service.projects()
|
|
1171
|
+
.versions()
|
|
1172
|
+
.get(scriptId=script_id, versionNumber=version_number)
|
|
1173
|
+
.execute
|
|
1174
|
+
)
|
|
1175
|
+
|
|
1176
|
+
ver_num = version.get("versionNumber", "Unknown")
|
|
1177
|
+
description = version.get("description", "No description")
|
|
1178
|
+
create_time = version.get("createTime", "Unknown")
|
|
1179
|
+
|
|
1180
|
+
output = [
|
|
1181
|
+
f"Version {ver_num} of script: {script_id}",
|
|
1182
|
+
f"Description: {description}",
|
|
1183
|
+
f"Created: {create_time}",
|
|
1184
|
+
]
|
|
1185
|
+
|
|
1186
|
+
logger.info(f"[get_version] Retrieved version {ver_num}")
|
|
1187
|
+
return "\n".join(output)
|
|
1188
|
+
|
|
1189
|
+
|
|
1190
|
+
@server.tool(
|
|
1191
|
+
title="Get Script Version",
|
|
1192
|
+
annotations=ToolAnnotations(
|
|
1193
|
+
readOnlyHint=True,
|
|
1194
|
+
destructiveHint=False,
|
|
1195
|
+
idempotentHint=True,
|
|
1196
|
+
openWorldHint=True,
|
|
1197
|
+
),
|
|
1198
|
+
)
|
|
1199
|
+
@handle_http_errors("get_script_version", is_read_only=True, service_type="script")
|
|
1200
|
+
@require_google_service("script", "script_readonly")
|
|
1201
|
+
async def get_script_version(
|
|
1202
|
+
service: Any,
|
|
1203
|
+
user_google_email: str,
|
|
1204
|
+
action: str,
|
|
1205
|
+
script_id: str,
|
|
1206
|
+
version_number: Optional[int] = None,
|
|
1207
|
+
) -> str:
|
|
1208
|
+
"""
|
|
1209
|
+
List or retrieve immutable version snapshots of a script project.
|
|
1210
|
+
|
|
1211
|
+
Actions:
|
|
1212
|
+
- "list": List every version of the project.
|
|
1213
|
+
- "get": Retrieve one version. Requires version_number.
|
|
1214
|
+
"""
|
|
1215
|
+
action = action.lower().strip()
|
|
1216
|
+
if action == "list":
|
|
1217
|
+
return await _list_versions_impl(service, user_google_email, script_id)
|
|
1218
|
+
elif action == "get":
|
|
1219
|
+
if version_number is None:
|
|
1220
|
+
raise UserInputError("version_number is required for get action")
|
|
1221
|
+
return await _get_version_impl(
|
|
1222
|
+
service, user_google_email, script_id, version_number
|
|
1223
|
+
)
|
|
1224
|
+
else:
|
|
1225
|
+
raise UserInputError(f"Invalid action '{action}'. Must be 'list' or 'get'.")
|
|
1226
|
+
|
|
1227
|
+
|
|
1228
|
+
# ============================================================================
|
|
1229
|
+
# Activity: processes and metrics
|
|
1230
|
+
# ============================================================================
|
|
1231
|
+
|
|
1232
|
+
|
|
1233
|
+
async def _get_script_metrics_impl(
|
|
1234
|
+
service: Any,
|
|
1235
|
+
user_google_email: str,
|
|
1236
|
+
script_id: str,
|
|
1237
|
+
metrics_granularity: str = "DAILY",
|
|
1238
|
+
) -> str:
|
|
1239
|
+
"""Internal implementation for get_script_metrics."""
|
|
1240
|
+
logger.info(
|
|
1241
|
+
f"[get_script_metrics] Email: {user_google_email}, ScriptID: {script_id}, Granularity: {metrics_granularity}"
|
|
1242
|
+
)
|
|
1243
|
+
|
|
1244
|
+
request_params = {
|
|
1245
|
+
"scriptId": script_id,
|
|
1246
|
+
"metricsGranularity": metrics_granularity,
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
response = await asyncio.to_thread(
|
|
1250
|
+
service.projects().getMetrics(**request_params).execute
|
|
1251
|
+
)
|
|
1252
|
+
|
|
1253
|
+
output = [
|
|
1254
|
+
f"Metrics for script: {script_id}",
|
|
1255
|
+
f"Granularity: {metrics_granularity}",
|
|
1256
|
+
"",
|
|
1257
|
+
]
|
|
1258
|
+
|
|
1259
|
+
# Active users
|
|
1260
|
+
active_users = response.get("activeUsers", [])
|
|
1261
|
+
if active_users:
|
|
1262
|
+
output.append("Active Users:")
|
|
1263
|
+
for metric in active_users:
|
|
1264
|
+
start_time = metric.get("startTime", "Unknown")
|
|
1265
|
+
end_time = metric.get("endTime", "Unknown")
|
|
1266
|
+
value = metric.get("value", "0")
|
|
1267
|
+
output.append(f" {start_time} to {end_time}: {value} users")
|
|
1268
|
+
output.append("")
|
|
1269
|
+
|
|
1270
|
+
# Total executions
|
|
1271
|
+
total_executions = response.get("totalExecutions", [])
|
|
1272
|
+
if total_executions:
|
|
1273
|
+
output.append("Total Executions:")
|
|
1274
|
+
for metric in total_executions:
|
|
1275
|
+
start_time = metric.get("startTime", "Unknown")
|
|
1276
|
+
end_time = metric.get("endTime", "Unknown")
|
|
1277
|
+
value = metric.get("value", "0")
|
|
1278
|
+
output.append(f" {start_time} to {end_time}: {value} executions")
|
|
1279
|
+
output.append("")
|
|
1280
|
+
|
|
1281
|
+
# Failed executions
|
|
1282
|
+
failed_executions = response.get("failedExecutions", [])
|
|
1283
|
+
if failed_executions:
|
|
1284
|
+
output.append("Failed Executions:")
|
|
1285
|
+
for metric in failed_executions:
|
|
1286
|
+
start_time = metric.get("startTime", "Unknown")
|
|
1287
|
+
end_time = metric.get("endTime", "Unknown")
|
|
1288
|
+
value = metric.get("value", "0")
|
|
1289
|
+
output.append(f" {start_time} to {end_time}: {value} failures")
|
|
1290
|
+
output.append("")
|
|
1291
|
+
|
|
1292
|
+
if not active_users and not total_executions and not failed_executions:
|
|
1293
|
+
output.append("No metrics data available for this script.")
|
|
1294
|
+
|
|
1295
|
+
logger.info(f"[get_script_metrics] Retrieved metrics for {script_id}")
|
|
1296
|
+
return "\n".join(output)
|
|
1297
|
+
|
|
1298
|
+
|
|
1299
|
+
@server.tool(
|
|
1300
|
+
title="Get Script Activity",
|
|
1301
|
+
annotations=ToolAnnotations(
|
|
1302
|
+
readOnlyHint=True,
|
|
1303
|
+
destructiveHint=False,
|
|
1304
|
+
idempotentHint=True,
|
|
1305
|
+
openWorldHint=True,
|
|
1306
|
+
),
|
|
1307
|
+
)
|
|
1308
|
+
@handle_http_errors("get_script_activity", is_read_only=True, service_type="script")
|
|
1309
|
+
@require_google_service("script", "script_readonly")
|
|
1310
|
+
async def get_script_activity(
|
|
1311
|
+
service: Any,
|
|
1312
|
+
user_google_email: str,
|
|
1313
|
+
action: str,
|
|
1314
|
+
script_id: Optional[str] = None,
|
|
1315
|
+
page_size: int = 50,
|
|
1316
|
+
metrics_granularity: str = "DAILY",
|
|
1317
|
+
) -> str:
|
|
1318
|
+
"""
|
|
1319
|
+
Read execution activity for scripts: recent processes or aggregate metrics.
|
|
1320
|
+
|
|
1321
|
+
Actions:
|
|
1322
|
+
- "processes": List recent execution processes. Without script_id, lists
|
|
1323
|
+
the user's own recent runs; with script_id, lists all processes for
|
|
1324
|
+
that script visible to the user (including runs by others). Optional
|
|
1325
|
+
page_size.
|
|
1326
|
+
- "metrics": Get aggregate execution metrics (active users, total and
|
|
1327
|
+
failed executions) for one script. Requires script_id; optional
|
|
1328
|
+
metrics_granularity ("DAILY" or "WEEKLY").
|
|
1329
|
+
|
|
1330
|
+
Args:
|
|
1331
|
+
service: Injected Google API service client
|
|
1332
|
+
user_google_email: User's email address
|
|
1333
|
+
action: One of "processes", "metrics".
|
|
1334
|
+
script_id: The script project ID (required for metrics; optional for
|
|
1335
|
+
processes).
|
|
1336
|
+
page_size: Number of results for processes (default: 50).
|
|
1337
|
+
metrics_granularity: Granularity for metrics - "DAILY" or "WEEKLY".
|
|
1338
|
+
|
|
1339
|
+
Returns:
|
|
1340
|
+
str: Formatted process list or metrics data.
|
|
1341
|
+
"""
|
|
1342
|
+
action = action.lower().strip()
|
|
1343
|
+
if action == "processes":
|
|
1344
|
+
return await _list_script_processes_impl(
|
|
1345
|
+
service, user_google_email, page_size, script_id
|
|
1346
|
+
)
|
|
1347
|
+
elif action == "metrics":
|
|
1348
|
+
if not script_id:
|
|
1349
|
+
raise UserInputError("script_id is required for metrics action")
|
|
1350
|
+
return await _get_script_metrics_impl(
|
|
1351
|
+
service, user_google_email, script_id, metrics_granularity
|
|
1352
|
+
)
|
|
1353
|
+
else:
|
|
1354
|
+
raise UserInputError(
|
|
1355
|
+
f"Invalid action '{action}'. Must be 'processes' or 'metrics'."
|
|
1356
|
+
)
|
|
1357
|
+
|
|
1358
|
+
|
|
1359
|
+
# ============================================================================
|
|
1360
|
+
# Trigger Code Generation
|
|
1361
|
+
# ============================================================================
|
|
1362
|
+
|
|
1363
|
+
|
|
1364
|
+
def _generate_trigger_code_impl(
|
|
1365
|
+
trigger_type: str,
|
|
1366
|
+
function_name: str,
|
|
1367
|
+
schedule: str = "",
|
|
1368
|
+
) -> str:
|
|
1369
|
+
"""Internal implementation for generate_trigger_code."""
|
|
1370
|
+
code_lines = []
|
|
1371
|
+
|
|
1372
|
+
if trigger_type == "on_open":
|
|
1373
|
+
code_lines = [
|
|
1374
|
+
"// Simple trigger - just rename your function to 'onOpen'",
|
|
1375
|
+
"// This runs automatically when the document is opened",
|
|
1376
|
+
"function onOpen(e) {",
|
|
1377
|
+
f" {function_name}();",
|
|
1378
|
+
"}",
|
|
1379
|
+
]
|
|
1380
|
+
elif trigger_type == "on_edit":
|
|
1381
|
+
code_lines = [
|
|
1382
|
+
"// Simple trigger - just rename your function to 'onEdit'",
|
|
1383
|
+
"// This runs automatically when a user edits the spreadsheet",
|
|
1384
|
+
"function onEdit(e) {",
|
|
1385
|
+
f" {function_name}();",
|
|
1386
|
+
"}",
|
|
1387
|
+
]
|
|
1388
|
+
elif trigger_type == "time_minutes":
|
|
1389
|
+
interval = schedule or "5"
|
|
1390
|
+
code_lines = [
|
|
1391
|
+
"// Run this function ONCE to install the trigger",
|
|
1392
|
+
f"function createTimeTrigger_{function_name}() {{",
|
|
1393
|
+
" // Delete existing triggers for this function first",
|
|
1394
|
+
" const triggers = ScriptApp.getProjectTriggers();",
|
|
1395
|
+
" triggers.forEach(trigger => {",
|
|
1396
|
+
f" if (trigger.getHandlerFunction() === '{function_name}') {{",
|
|
1397
|
+
" ScriptApp.deleteTrigger(trigger);",
|
|
1398
|
+
" }",
|
|
1399
|
+
" });",
|
|
1400
|
+
"",
|
|
1401
|
+
f" // Create new trigger - runs every {interval} minutes",
|
|
1402
|
+
f" ScriptApp.newTrigger('{function_name}')",
|
|
1403
|
+
" .timeBased()",
|
|
1404
|
+
f" .everyMinutes({interval})",
|
|
1405
|
+
" .create();",
|
|
1406
|
+
"",
|
|
1407
|
+
f" Logger.log('Trigger created: {function_name} will run every {interval} minutes');",
|
|
1408
|
+
"}",
|
|
1409
|
+
]
|
|
1410
|
+
elif trigger_type == "time_hours":
|
|
1411
|
+
interval = schedule or "1"
|
|
1412
|
+
code_lines = [
|
|
1413
|
+
"// Run this function ONCE to install the trigger",
|
|
1414
|
+
f"function createTimeTrigger_{function_name}() {{",
|
|
1415
|
+
" // Delete existing triggers for this function first",
|
|
1416
|
+
" const triggers = ScriptApp.getProjectTriggers();",
|
|
1417
|
+
" triggers.forEach(trigger => {",
|
|
1418
|
+
f" if (trigger.getHandlerFunction() === '{function_name}') {{",
|
|
1419
|
+
" ScriptApp.deleteTrigger(trigger);",
|
|
1420
|
+
" }",
|
|
1421
|
+
" });",
|
|
1422
|
+
"",
|
|
1423
|
+
f" // Create new trigger - runs every {interval} hour(s)",
|
|
1424
|
+
f" ScriptApp.newTrigger('{function_name}')",
|
|
1425
|
+
" .timeBased()",
|
|
1426
|
+
f" .everyHours({interval})",
|
|
1427
|
+
" .create();",
|
|
1428
|
+
"",
|
|
1429
|
+
f" Logger.log('Trigger created: {function_name} will run every {interval} hour(s)');",
|
|
1430
|
+
"}",
|
|
1431
|
+
]
|
|
1432
|
+
elif trigger_type == "time_daily":
|
|
1433
|
+
hour = schedule or "9"
|
|
1434
|
+
code_lines = [
|
|
1435
|
+
"// Run this function ONCE to install the trigger",
|
|
1436
|
+
f"function createDailyTrigger_{function_name}() {{",
|
|
1437
|
+
" // Delete existing triggers for this function first",
|
|
1438
|
+
" const triggers = ScriptApp.getProjectTriggers();",
|
|
1439
|
+
" triggers.forEach(trigger => {",
|
|
1440
|
+
f" if (trigger.getHandlerFunction() === '{function_name}') {{",
|
|
1441
|
+
" ScriptApp.deleteTrigger(trigger);",
|
|
1442
|
+
" }",
|
|
1443
|
+
" });",
|
|
1444
|
+
"",
|
|
1445
|
+
f" // Create new trigger - runs daily at {hour}:00",
|
|
1446
|
+
f" ScriptApp.newTrigger('{function_name}')",
|
|
1447
|
+
" .timeBased()",
|
|
1448
|
+
f" .atHour({hour})",
|
|
1449
|
+
" .everyDays(1)",
|
|
1450
|
+
" .create();",
|
|
1451
|
+
"",
|
|
1452
|
+
f" Logger.log('Trigger created: {function_name} will run daily at {hour}:00');",
|
|
1453
|
+
"}",
|
|
1454
|
+
]
|
|
1455
|
+
elif trigger_type == "time_weekly":
|
|
1456
|
+
day = schedule.upper() if schedule else "MONDAY"
|
|
1457
|
+
code_lines = [
|
|
1458
|
+
"// Run this function ONCE to install the trigger",
|
|
1459
|
+
f"function createWeeklyTrigger_{function_name}() {{",
|
|
1460
|
+
" // Delete existing triggers for this function first",
|
|
1461
|
+
" const triggers = ScriptApp.getProjectTriggers();",
|
|
1462
|
+
" triggers.forEach(trigger => {",
|
|
1463
|
+
f" if (trigger.getHandlerFunction() === '{function_name}') {{",
|
|
1464
|
+
" ScriptApp.deleteTrigger(trigger);",
|
|
1465
|
+
" }",
|
|
1466
|
+
" });",
|
|
1467
|
+
"",
|
|
1468
|
+
f" // Create new trigger - runs weekly on {day}",
|
|
1469
|
+
f" ScriptApp.newTrigger('{function_name}')",
|
|
1470
|
+
" .timeBased()",
|
|
1471
|
+
f" .onWeekDay(ScriptApp.WeekDay.{day})",
|
|
1472
|
+
" .atHour(9)",
|
|
1473
|
+
" .create();",
|
|
1474
|
+
"",
|
|
1475
|
+
f" Logger.log('Trigger created: {function_name} will run every {day} at 9:00');",
|
|
1476
|
+
"}",
|
|
1477
|
+
]
|
|
1478
|
+
elif trigger_type == "on_form_submit":
|
|
1479
|
+
code_lines = [
|
|
1480
|
+
"// Run this function ONCE to install the trigger",
|
|
1481
|
+
"// This must be run from a script BOUND to the Google Form",
|
|
1482
|
+
f"function createFormSubmitTrigger_{function_name}() {{",
|
|
1483
|
+
" // Delete existing triggers for this function first",
|
|
1484
|
+
" const triggers = ScriptApp.getProjectTriggers();",
|
|
1485
|
+
" triggers.forEach(trigger => {",
|
|
1486
|
+
f" if (trigger.getHandlerFunction() === '{function_name}') {{",
|
|
1487
|
+
" ScriptApp.deleteTrigger(trigger);",
|
|
1488
|
+
" }",
|
|
1489
|
+
" });",
|
|
1490
|
+
"",
|
|
1491
|
+
" // Create new trigger - runs when form is submitted",
|
|
1492
|
+
f" ScriptApp.newTrigger('{function_name}')",
|
|
1493
|
+
" .forForm(FormApp.getActiveForm())",
|
|
1494
|
+
" .onFormSubmit()",
|
|
1495
|
+
" .create();",
|
|
1496
|
+
"",
|
|
1497
|
+
f" Logger.log('Trigger created: {function_name} will run on form submit');",
|
|
1498
|
+
"}",
|
|
1499
|
+
]
|
|
1500
|
+
elif trigger_type == "on_change":
|
|
1501
|
+
code_lines = [
|
|
1502
|
+
"// Run this function ONCE to install the trigger",
|
|
1503
|
+
"// This must be run from a script BOUND to a Google Sheet",
|
|
1504
|
+
f"function createChangeTrigger_{function_name}() {{",
|
|
1505
|
+
" // Delete existing triggers for this function first",
|
|
1506
|
+
" const triggers = ScriptApp.getProjectTriggers();",
|
|
1507
|
+
" triggers.forEach(trigger => {",
|
|
1508
|
+
f" if (trigger.getHandlerFunction() === '{function_name}') {{",
|
|
1509
|
+
" ScriptApp.deleteTrigger(trigger);",
|
|
1510
|
+
" }",
|
|
1511
|
+
" });",
|
|
1512
|
+
"",
|
|
1513
|
+
" // Create new trigger - runs when spreadsheet changes",
|
|
1514
|
+
f" ScriptApp.newTrigger('{function_name}')",
|
|
1515
|
+
" .forSpreadsheet(SpreadsheetApp.getActive())",
|
|
1516
|
+
" .onChange()",
|
|
1517
|
+
" .create();",
|
|
1518
|
+
"",
|
|
1519
|
+
f" Logger.log('Trigger created: {function_name} will run on spreadsheet change');",
|
|
1520
|
+
"}",
|
|
1521
|
+
]
|
|
1522
|
+
else:
|
|
1523
|
+
return (
|
|
1524
|
+
f"Unknown trigger type: {trigger_type}\n\n"
|
|
1525
|
+
"Valid types: time_minutes, time_hours, time_daily, time_weekly, "
|
|
1526
|
+
"on_open, on_edit, on_form_submit, on_change"
|
|
1527
|
+
)
|
|
1528
|
+
|
|
1529
|
+
code = "\n".join(code_lines)
|
|
1530
|
+
|
|
1531
|
+
instructions = []
|
|
1532
|
+
if trigger_type.startswith("on_"):
|
|
1533
|
+
if trigger_type in ("on_open", "on_edit"):
|
|
1534
|
+
instructions = [
|
|
1535
|
+
"SIMPLE TRIGGER",
|
|
1536
|
+
"=" * 50,
|
|
1537
|
+
"",
|
|
1538
|
+
"Add this code to your script. Simple triggers run automatically",
|
|
1539
|
+
"when the event occurs - no setup function needed.",
|
|
1540
|
+
"",
|
|
1541
|
+
"Note: Simple triggers have limitations:",
|
|
1542
|
+
"- Cannot access services that require authorization",
|
|
1543
|
+
"- Cannot run longer than 30 seconds",
|
|
1544
|
+
"- Cannot make external HTTP requests",
|
|
1545
|
+
"",
|
|
1546
|
+
"For more capabilities, use an installable trigger instead.",
|
|
1547
|
+
"",
|
|
1548
|
+
"CODE TO ADD:",
|
|
1549
|
+
"-" * 50,
|
|
1550
|
+
]
|
|
1551
|
+
else:
|
|
1552
|
+
instructions = [
|
|
1553
|
+
"INSTALLABLE TRIGGER",
|
|
1554
|
+
"=" * 50,
|
|
1555
|
+
"",
|
|
1556
|
+
"1. Add this code to your script",
|
|
1557
|
+
f"2. Run the setup function once: createFormSubmitTrigger_{function_name}() or similar",
|
|
1558
|
+
"3. The trigger will then run automatically",
|
|
1559
|
+
"",
|
|
1560
|
+
"CODE TO ADD:",
|
|
1561
|
+
"-" * 50,
|
|
1562
|
+
]
|
|
1563
|
+
else:
|
|
1564
|
+
instructions = [
|
|
1565
|
+
"INSTALLABLE TRIGGER",
|
|
1566
|
+
"=" * 50,
|
|
1567
|
+
"",
|
|
1568
|
+
"1. Add this code to your script using manage_script_content(action='update')",
|
|
1569
|
+
"2. Run the setup function ONCE (manually in Apps Script editor or via run_script_function)",
|
|
1570
|
+
"3. The trigger will then run automatically on schedule",
|
|
1571
|
+
"",
|
|
1572
|
+
"To check installed triggers: Apps Script editor > Triggers (clock icon)",
|
|
1573
|
+
"",
|
|
1574
|
+
"CODE TO ADD:",
|
|
1575
|
+
"-" * 50,
|
|
1576
|
+
]
|
|
1577
|
+
|
|
1578
|
+
return "\n".join(instructions) + "\n\n" + code
|
|
1579
|
+
|
|
1580
|
+
|
|
1581
|
+
@server.tool(
|
|
1582
|
+
title="Generate Trigger Code",
|
|
1583
|
+
annotations=ToolAnnotations(
|
|
1584
|
+
readOnlyHint=True,
|
|
1585
|
+
destructiveHint=False,
|
|
1586
|
+
idempotentHint=True,
|
|
1587
|
+
openWorldHint=False,
|
|
1588
|
+
),
|
|
1589
|
+
)
|
|
1590
|
+
async def generate_trigger_code(
|
|
1591
|
+
trigger_type: str,
|
|
1592
|
+
function_name: str,
|
|
1593
|
+
schedule: str = "",
|
|
1594
|
+
) -> str:
|
|
1595
|
+
"""
|
|
1596
|
+
Generates Apps Script code for creating triggers.
|
|
1597
|
+
|
|
1598
|
+
The Apps Script API cannot create triggers directly - they must be created
|
|
1599
|
+
from within Apps Script itself. This tool generates the code you need.
|
|
1600
|
+
To list or remove existing triggers without opening the editor, use
|
|
1601
|
+
`manage_script_trigger` (action="list" / action="delete") instead.
|
|
1602
|
+
|
|
1603
|
+
Args:
|
|
1604
|
+
trigger_type: Type of trigger. One of:
|
|
1605
|
+
- "time_minutes" (run every N minutes: 1, 5, 10, 15, 30)
|
|
1606
|
+
- "time_hours" (run every N hours: 1, 2, 4, 6, 8, 12)
|
|
1607
|
+
- "time_daily" (run daily at a specific hour: 0-23)
|
|
1608
|
+
- "time_weekly" (run weekly on a specific day)
|
|
1609
|
+
- "on_open" (simple trigger - runs when document opens)
|
|
1610
|
+
- "on_edit" (simple trigger - runs when user edits)
|
|
1611
|
+
- "on_form_submit" (runs when form is submitted)
|
|
1612
|
+
- "on_change" (runs when content changes)
|
|
1613
|
+
|
|
1614
|
+
function_name: The function to run when trigger fires (e.g., "sendDailyReport")
|
|
1615
|
+
|
|
1616
|
+
schedule: Schedule details (depends on trigger_type):
|
|
1617
|
+
- For time_minutes: "1", "5", "10", "15", or "30"
|
|
1618
|
+
- For time_hours: "1", "2", "4", "6", "8", or "12"
|
|
1619
|
+
- For time_daily: hour as "0"-"23" (e.g., "9" for 9am)
|
|
1620
|
+
- For time_weekly: "MONDAY", "TUESDAY", etc.
|
|
1621
|
+
- For simple triggers (on_open, on_edit): not needed
|
|
1622
|
+
|
|
1623
|
+
Returns:
|
|
1624
|
+
str: Apps Script code to create the trigger
|
|
1625
|
+
"""
|
|
1626
|
+
return _generate_trigger_code_impl(trigger_type, function_name, schedule)
|
|
1627
|
+
|
|
1628
|
+
|
|
1629
|
+
# ---------------------------------------------------------------------------
|
|
1630
|
+
# Trigger management (list / delete for the current user)
|
|
1631
|
+
#
|
|
1632
|
+
# The Apps Script REST API has no triggers resource; trigger state only exists
|
|
1633
|
+
# inside the Apps Script runtime. A small helper file is merged into the
|
|
1634
|
+
# project and invoked through the Execution API (scripts.run), which requires
|
|
1635
|
+
# the script.scriptapp scope.
|
|
1636
|
+
# ---------------------------------------------------------------------------
|
|
1637
|
+
|
|
1638
|
+
_TRIGGER_ADMIN_FILE_NAME = "McpTriggerAdmin"
|
|
1639
|
+
_TRIGGER_ADMIN_MARKER = (
|
|
1640
|
+
"// Auto-provisioned by the Google Workspace MCP server's "
|
|
1641
|
+
"manage_script_trigger tool."
|
|
1642
|
+
)
|
|
1643
|
+
_TRIGGER_ADMIN_SOURCE = (
|
|
1644
|
+
_TRIGGER_ADMIN_MARKER
|
|
1645
|
+
+ """
|
|
1646
|
+
// Overwritten when the helper changes; safe to delete.
|
|
1647
|
+
|
|
1648
|
+
function __mcpListTriggers() {
|
|
1649
|
+
var triggers = ScriptApp.getProjectTriggers();
|
|
1650
|
+
var out = [];
|
|
1651
|
+
for (var i = 0; i < triggers.length; i++) {
|
|
1652
|
+
var t = triggers[i];
|
|
1653
|
+
out.push({
|
|
1654
|
+
uniqueId: t.getUniqueId(),
|
|
1655
|
+
handlerFunction: t.getHandlerFunction(),
|
|
1656
|
+
eventType: t.getEventType().toString(),
|
|
1657
|
+
triggerSource: t.getTriggerSource().toString()
|
|
1658
|
+
});
|
|
1659
|
+
}
|
|
1660
|
+
return JSON.stringify(out);
|
|
1661
|
+
}
|
|
1662
|
+
|
|
1663
|
+
function __mcpDeleteTrigger(uniqueId, handlerFunction) {
|
|
1664
|
+
if (!uniqueId && !handlerFunction) return "[]";
|
|
1665
|
+
var triggers = ScriptApp.getProjectTriggers();
|
|
1666
|
+
var deleted = [];
|
|
1667
|
+
for (var i = 0; i < triggers.length; i++) {
|
|
1668
|
+
var t = triggers[i];
|
|
1669
|
+
var tId = t.getUniqueId();
|
|
1670
|
+
var tHandler = t.getHandlerFunction();
|
|
1671
|
+
if ((!uniqueId || tId === uniqueId) &&
|
|
1672
|
+
(!handlerFunction || tHandler === handlerFunction)) {
|
|
1673
|
+
ScriptApp.deleteTrigger(t);
|
|
1674
|
+
deleted.push({uniqueId: tId, handlerFunction: tHandler});
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
return JSON.stringify(deleted);
|
|
1678
|
+
}
|
|
1679
|
+
"""
|
|
1680
|
+
)
|
|
1681
|
+
|
|
1682
|
+
|
|
1683
|
+
async def _ensure_trigger_admin_file(service: Any, script_id: str) -> None:
|
|
1684
|
+
"""Install or refresh the trigger helper file without touching other files.
|
|
1685
|
+
|
|
1686
|
+
Holds the per-script update lock so it cannot race manage_script_content.
|
|
1687
|
+
A same-named file is only overwritten when it carries the helper marker.
|
|
1688
|
+
"""
|
|
1689
|
+
admin_file = {
|
|
1690
|
+
"name": _TRIGGER_ADMIN_FILE_NAME,
|
|
1691
|
+
"type": "SERVER_JS",
|
|
1692
|
+
"source": _TRIGGER_ADMIN_SOURCE,
|
|
1693
|
+
}
|
|
1694
|
+
async with _get_script_update_lock(script_id):
|
|
1695
|
+
current_content = await asyncio.to_thread(
|
|
1696
|
+
service.projects().getContent(scriptId=script_id).execute
|
|
1697
|
+
)
|
|
1698
|
+
existing_files = current_content.get("files", [])
|
|
1699
|
+
current_source = next(
|
|
1700
|
+
(
|
|
1701
|
+
f.get("source", "")
|
|
1702
|
+
for f in existing_files
|
|
1703
|
+
if f.get("name") == _TRIGGER_ADMIN_FILE_NAME
|
|
1704
|
+
and f.get("type") == "SERVER_JS"
|
|
1705
|
+
),
|
|
1706
|
+
None,
|
|
1707
|
+
)
|
|
1708
|
+
if current_source == _TRIGGER_ADMIN_SOURCE:
|
|
1709
|
+
return
|
|
1710
|
+
if current_source is not None and not current_source.startswith(
|
|
1711
|
+
_TRIGGER_ADMIN_MARKER
|
|
1712
|
+
):
|
|
1713
|
+
raise UserInputError(
|
|
1714
|
+
f"Cannot install the trigger helper because the project already "
|
|
1715
|
+
f"contains a user-managed {_TRIGGER_ADMIN_FILE_NAME}.gs file. "
|
|
1716
|
+
"Rename that file before managing triggers."
|
|
1717
|
+
)
|
|
1718
|
+
|
|
1719
|
+
merged_files = _merge_script_files(existing_files, [admin_file])
|
|
1720
|
+
await asyncio.to_thread(
|
|
1721
|
+
service.projects()
|
|
1722
|
+
.updateContent(scriptId=script_id, body={"files": merged_files})
|
|
1723
|
+
.execute
|
|
1724
|
+
)
|
|
1725
|
+
|
|
1726
|
+
|
|
1727
|
+
async def _run_trigger_admin(
|
|
1728
|
+
service: Any,
|
|
1729
|
+
script_id: str,
|
|
1730
|
+
function_name: str,
|
|
1731
|
+
parameters: List[Optional[str]],
|
|
1732
|
+
dev_mode: bool,
|
|
1733
|
+
deployment_id: Optional[str],
|
|
1734
|
+
) -> List[Dict[str, Any]]:
|
|
1735
|
+
"""Ensure the executed code has the helper, run it, and parse its JSON result."""
|
|
1736
|
+
if not deployment_id:
|
|
1737
|
+
deployment_id = await _resolve_execution_deployment_id(service, script_id)
|
|
1738
|
+
if not deployment_id:
|
|
1739
|
+
raise UserInputError(
|
|
1740
|
+
"No versioned API Executable deployment was found. In the Apps Script "
|
|
1741
|
+
"editor, use Deploy > New deployment > API Executable."
|
|
1742
|
+
)
|
|
1743
|
+
|
|
1744
|
+
if dev_mode:
|
|
1745
|
+
await _ensure_trigger_admin_file(service, script_id)
|
|
1746
|
+
else:
|
|
1747
|
+
deployment = await asyncio.to_thread(
|
|
1748
|
+
service.projects()
|
|
1749
|
+
.deployments()
|
|
1750
|
+
.get(scriptId=script_id, deploymentId=deployment_id)
|
|
1751
|
+
.execute
|
|
1752
|
+
)
|
|
1753
|
+
version_number = deployment.get("deploymentConfig", {}).get("versionNumber")
|
|
1754
|
+
if version_number is None:
|
|
1755
|
+
raise UserInputError(
|
|
1756
|
+
"The selected deployment must reference a script version."
|
|
1757
|
+
)
|
|
1758
|
+
content = await asyncio.to_thread(
|
|
1759
|
+
service.projects()
|
|
1760
|
+
.getContent(scriptId=script_id, versionNumber=version_number)
|
|
1761
|
+
.execute
|
|
1762
|
+
)
|
|
1763
|
+
if not any(
|
|
1764
|
+
function.get("name") == function_name
|
|
1765
|
+
for file in content.get("files", [])
|
|
1766
|
+
if file.get("type") == "SERVER_JS"
|
|
1767
|
+
for function in file.get("functionSet", {}).get("values", [])
|
|
1768
|
+
):
|
|
1769
|
+
raise UserInputError(
|
|
1770
|
+
f"Deployment '{deployment_id}' (version {version_number}) does not "
|
|
1771
|
+
f"contain {function_name}. Run with dev_mode=True as the project "
|
|
1772
|
+
"owner to provision the helper, then create a new version and "
|
|
1773
|
+
"update the deployment before using dev_mode=False."
|
|
1774
|
+
)
|
|
1775
|
+
|
|
1776
|
+
body: Dict[str, Any] = {"function": function_name, "devMode": dev_mode}
|
|
1777
|
+
if parameters:
|
|
1778
|
+
body["parameters"] = parameters
|
|
1779
|
+
response = await asyncio.to_thread(
|
|
1780
|
+
service.scripts().run(scriptId=deployment_id, body=body).execute
|
|
1781
|
+
)
|
|
1782
|
+
|
|
1783
|
+
if "error" in response:
|
|
1784
|
+
message = response["error"].get("message", "Unknown error")
|
|
1785
|
+
raise RuntimeError(f"{function_name} execution failed: {message}")
|
|
1786
|
+
|
|
1787
|
+
result = response.get("response", {}).get("result")
|
|
1788
|
+
return json.loads(result) if result else []
|
|
1789
|
+
|
|
1790
|
+
|
|
1791
|
+
async def _list_script_triggers_impl(
|
|
1792
|
+
service: Any,
|
|
1793
|
+
user_google_email: str,
|
|
1794
|
+
script_id: str,
|
|
1795
|
+
dev_mode: bool = True,
|
|
1796
|
+
deployment_id: Optional[str] = None,
|
|
1797
|
+
) -> str:
|
|
1798
|
+
"""Internal implementation for manage_script_trigger list."""
|
|
1799
|
+
logger.info(f"[list_script_triggers] Email: {user_google_email}, ID: {script_id}")
|
|
1800
|
+
|
|
1801
|
+
triggers = await _run_trigger_admin(
|
|
1802
|
+
service, script_id, "__mcpListTriggers", [], dev_mode, deployment_id
|
|
1803
|
+
)
|
|
1804
|
+
|
|
1805
|
+
if not triggers:
|
|
1806
|
+
return f"No triggers found for the current user on script: {script_id}"
|
|
1807
|
+
|
|
1808
|
+
output = [f"Triggers owned by the current user for script {script_id}:", ""]
|
|
1809
|
+
for i, trig in enumerate(triggers, 1):
|
|
1810
|
+
output.append(f"{i}. {trig.get('handlerFunction', 'Unknown')}")
|
|
1811
|
+
output.append(f" Unique ID: {trig.get('uniqueId', 'Unknown')}")
|
|
1812
|
+
output.append(f" Event type: {trig.get('eventType', 'Unknown')}")
|
|
1813
|
+
output.append(f" Source: {trig.get('triggerSource', 'Unknown')}")
|
|
1814
|
+
output.append("")
|
|
1815
|
+
|
|
1816
|
+
logger.info(f"[list_script_triggers] Found {len(triggers)} triggers")
|
|
1817
|
+
return "\n".join(output)
|
|
1818
|
+
|
|
1819
|
+
|
|
1820
|
+
@server.tool(
|
|
1821
|
+
title="Manage Script Trigger",
|
|
1822
|
+
annotations=ToolAnnotations(
|
|
1823
|
+
readOnlyHint=False,
|
|
1824
|
+
destructiveHint=True,
|
|
1825
|
+
idempotentHint=False,
|
|
1826
|
+
openWorldHint=True,
|
|
1827
|
+
),
|
|
1828
|
+
)
|
|
1829
|
+
@handle_http_errors("manage_script_trigger", service_type="script")
|
|
1830
|
+
@require_google_service(
|
|
1831
|
+
"script",
|
|
1832
|
+
["script_projects", "script_scriptapp", "script_deployments_readonly"],
|
|
1833
|
+
)
|
|
1834
|
+
async def manage_script_trigger(
|
|
1835
|
+
service: Any,
|
|
1836
|
+
user_google_email: str,
|
|
1837
|
+
action: str,
|
|
1838
|
+
script_id: str,
|
|
1839
|
+
trigger_id: Optional[str] = None,
|
|
1840
|
+
handler_function: Optional[str] = None,
|
|
1841
|
+
dev_mode: bool = True,
|
|
1842
|
+
deployment_id: Optional[str] = None,
|
|
1843
|
+
) -> str:
|
|
1844
|
+
"""
|
|
1845
|
+
List or delete the current user's installable triggers on a script project.
|
|
1846
|
+
|
|
1847
|
+
The Apps Script REST API has no triggers resource, so in dev_mode both actions
|
|
1848
|
+
provision (or refresh) a small helper file and run it via the Execution
|
|
1849
|
+
API - the only way to inspect or change trigger state without opening the
|
|
1850
|
+
editor. Neither action is read-only: the helper file may be written into the
|
|
1851
|
+
project on first use. To create a trigger, use `generate_trigger_code` to
|
|
1852
|
+
produce the setup code, add it with `manage_script_content`, then run it with
|
|
1853
|
+
`run_script_function`.
|
|
1854
|
+
|
|
1855
|
+
Actions:
|
|
1856
|
+
- "list": List the current user's triggers configured on the project.
|
|
1857
|
+
- "delete": Delete triggers matching every supplied selector. trigger_id
|
|
1858
|
+
removes one trigger; handler_function alone removes EVERY trigger
|
|
1859
|
+
calling that function; both together remove the trigger only if its
|
|
1860
|
+
handler also matches. At least one is required; run "list" first to
|
|
1861
|
+
find a trigger's unique ID.
|
|
1862
|
+
|
|
1863
|
+
Args:
|
|
1864
|
+
service: Injected Google API service client
|
|
1865
|
+
user_google_email: User's email address
|
|
1866
|
+
action: One of "list", "delete".
|
|
1867
|
+
script_id: The script project ID.
|
|
1868
|
+
trigger_id: Unique ID of a specific trigger to delete (delete only).
|
|
1869
|
+
handler_function: Delete all triggers calling this function name
|
|
1870
|
+
(delete only).
|
|
1871
|
+
dev_mode: Run against the latest saved code (default; project owner
|
|
1872
|
+
only) vs. the deployed version. False requires the helper to
|
|
1873
|
+
already exist in the deployed version.
|
|
1874
|
+
deployment_id: Optional API Executable deployment ID. When omitted, the
|
|
1875
|
+
highest versioned API Executable deployment is used.
|
|
1876
|
+
|
|
1877
|
+
Returns:
|
|
1878
|
+
str: Formatted list of triggers, or a summary of the trigger(s) deleted.
|
|
1879
|
+
"""
|
|
1880
|
+
action = action.lower().strip()
|
|
1881
|
+
if action == "list":
|
|
1882
|
+
return await _list_script_triggers_impl(
|
|
1883
|
+
service, user_google_email, script_id, dev_mode, deployment_id
|
|
1884
|
+
)
|
|
1885
|
+
elif action == "delete":
|
|
1886
|
+
return await _delete_script_trigger_impl(
|
|
1887
|
+
service,
|
|
1888
|
+
user_google_email,
|
|
1889
|
+
script_id,
|
|
1890
|
+
trigger_id,
|
|
1891
|
+
handler_function,
|
|
1892
|
+
dev_mode,
|
|
1893
|
+
deployment_id,
|
|
1894
|
+
)
|
|
1895
|
+
else:
|
|
1896
|
+
raise UserInputError(f"Invalid action '{action}'. Must be 'list' or 'delete'.")
|
|
1897
|
+
|
|
1898
|
+
|
|
1899
|
+
async def _delete_script_trigger_impl(
|
|
1900
|
+
service: Any,
|
|
1901
|
+
user_google_email: str,
|
|
1902
|
+
script_id: str,
|
|
1903
|
+
trigger_id: Optional[str] = None,
|
|
1904
|
+
handler_function: Optional[str] = None,
|
|
1905
|
+
dev_mode: bool = True,
|
|
1906
|
+
deployment_id: Optional[str] = None,
|
|
1907
|
+
) -> str:
|
|
1908
|
+
"""Internal implementation for manage_script_trigger delete."""
|
|
1909
|
+
if not trigger_id and not handler_function:
|
|
1910
|
+
raise UserInputError("Provide trigger_id or handler_function (or both).")
|
|
1911
|
+
|
|
1912
|
+
logger.info(
|
|
1913
|
+
f"[delete_script_trigger] Email: {user_google_email}, ID: {script_id}, "
|
|
1914
|
+
f"trigger_id: {trigger_id}, handler_function: {handler_function}"
|
|
1915
|
+
)
|
|
1916
|
+
|
|
1917
|
+
deleted = await _run_trigger_admin(
|
|
1918
|
+
service,
|
|
1919
|
+
script_id,
|
|
1920
|
+
"__mcpDeleteTrigger",
|
|
1921
|
+
[trigger_id, handler_function],
|
|
1922
|
+
dev_mode,
|
|
1923
|
+
deployment_id,
|
|
1924
|
+
)
|
|
1925
|
+
|
|
1926
|
+
if not deleted:
|
|
1927
|
+
return (
|
|
1928
|
+
f"No matching trigger found for script {script_id} "
|
|
1929
|
+
f"(trigger_id={trigger_id}, handler_function={handler_function})."
|
|
1930
|
+
)
|
|
1931
|
+
|
|
1932
|
+
output = [f"Deleted {len(deleted)} trigger(s) from script {script_id}:"]
|
|
1933
|
+
for trig in deleted:
|
|
1934
|
+
output.append(
|
|
1935
|
+
f"- {trig.get('handlerFunction', 'Unknown')} "
|
|
1936
|
+
f"(unique ID: {trig.get('uniqueId', 'Unknown')})"
|
|
1937
|
+
)
|
|
1938
|
+
|
|
1939
|
+
logger.info(f"[delete_script_trigger] Deleted {len(deleted)} trigger(s)")
|
|
1940
|
+
return "\n".join(output)
|