forked from taylorwilsdon/google_workspace_mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapps_script_tools.py
More file actions
1312 lines (1091 loc) · 41.6 KB
/
apps_script_tools.py
File metadata and controls
1312 lines (1091 loc) · 41.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Google Apps Script MCP Tools
This module provides MCP tools for interacting with Google Apps Script API.
"""
import logging
import asyncio
from typing import List, Dict, Any, Optional
from auth.service_decorator import require_google_service
from core.server import server
from core.utils import handle_http_errors
logger = logging.getLogger(__name__)
# Internal implementation functions for testing
async def _list_script_projects_impl(
service: Any,
user_google_email: str,
page_size: int = 50,
page_token: Optional[str] = None,
) -> str:
"""Internal implementation for list_script_projects.
Uses Drive API to find Apps Script files since the Script API
does not have a projects.list method.
"""
logger.info(
f"[list_script_projects] Email: {user_google_email}, PageSize: {page_size}"
)
# Search for Apps Script files using Drive API
query = "mimeType='application/vnd.google-apps.script' and trashed=false"
request_params = {
"q": query,
"pageSize": page_size,
"fields": "nextPageToken, files(id, name, createdTime, modifiedTime)",
"orderBy": "modifiedTime desc",
}
if page_token:
request_params["pageToken"] = page_token
response = await asyncio.to_thread(service.files().list(**request_params).execute)
files = response.get("files", [])
if not files:
return "No Apps Script projects found."
output = [f"Found {len(files)} Apps Script projects:"]
for file in files:
title = file.get("name", "Untitled")
script_id = file.get("id", "Unknown ID")
create_time = file.get("createdTime", "Unknown")
update_time = file.get("modifiedTime", "Unknown")
output.append(
f"- {title} (ID: {script_id}) Created: {create_time} Modified: {update_time}"
)
if "nextPageToken" in response:
output.append(f"\nNext page token: {response['nextPageToken']}")
logger.info(
f"[list_script_projects] Found {len(files)} projects for {user_google_email}"
)
return "\n".join(output)
@server.tool()
@handle_http_errors("list_script_projects", is_read_only=True, service_type="drive")
@require_google_service("drive", "drive_read")
async def list_script_projects(
service: Any,
user_google_email: str,
page_size: int = 50,
page_token: Optional[str] = None,
) -> str:
"""
Lists Google Apps Script projects accessible to the user.
Uses Drive API to find Apps Script files.
Args:
service: Injected Google API service client
user_google_email: User's email address
page_size: Number of results per page (default: 50)
page_token: Token for pagination (optional)
Returns:
str: Formatted list of script projects
"""
return await _list_script_projects_impl(
service, user_google_email, page_size, page_token
)
async def _get_script_project_impl(
service: Any,
user_google_email: str,
script_id: str,
) -> str:
"""Internal implementation for get_script_project."""
logger.info(f"[get_script_project] Email: {user_google_email}, ID: {script_id}")
# Get project metadata and content concurrently (independent requests)
project, content = await asyncio.gather(
asyncio.to_thread(service.projects().get(scriptId=script_id).execute),
asyncio.to_thread(service.projects().getContent(scriptId=script_id).execute),
)
title = project.get("title", "Untitled")
project_script_id = project.get("scriptId", "Unknown")
creator = project.get("creator", {}).get("email", "Unknown")
create_time = project.get("createTime", "Unknown")
update_time = project.get("updateTime", "Unknown")
output = [
f"Project: {title} (ID: {project_script_id})",
f"Creator: {creator}",
f"Created: {create_time}",
f"Modified: {update_time}",
"",
"Files:",
]
files = content.get("files", [])
for i, file in enumerate(files, 1):
file_name = file.get("name", "Untitled")
file_type = file.get("type", "Unknown")
source = file.get("source", "")
output.append(f"{i}. {file_name} ({file_type})")
if source:
output.append(f" {source[:200]}{'...' if len(source) > 200 else ''}")
output.append("")
logger.info(f"[get_script_project] Retrieved project {script_id}")
return "\n".join(output)
@server.tool()
@handle_http_errors("get_script_project", is_read_only=True, service_type="script")
@require_google_service("script", "script_readonly")
async def get_script_project(
service: Any,
user_google_email: str,
script_id: str,
) -> str:
"""
Retrieves complete project details including all source files.
Args:
service: Injected Google API service client
user_google_email: User's email address
script_id: The script project ID
Returns:
str: Formatted project details with all file contents
"""
return await _get_script_project_impl(service, user_google_email, script_id)
async def _get_script_content_impl(
service: Any,
user_google_email: str,
script_id: str,
file_name: str,
) -> str:
"""Internal implementation for get_script_content."""
logger.info(
f"[get_script_content] Email: {user_google_email}, ID: {script_id}, File: {file_name}"
)
# Must use getContent() to retrieve files, not get() which only returns metadata
content = await asyncio.to_thread(
service.projects().getContent(scriptId=script_id).execute
)
files = content.get("files", [])
target_file = None
for file in files:
if file.get("name") == file_name:
target_file = file
break
if not target_file:
return f"File '{file_name}' not found in project {script_id}"
source = target_file.get("source", "")
file_type = target_file.get("type", "Unknown")
output = [f"File: {file_name} ({file_type})", "", source]
logger.info(f"[get_script_content] Retrieved file {file_name} from {script_id}")
return "\n".join(output)
@server.tool()
@handle_http_errors("get_script_content", is_read_only=True, service_type="script")
@require_google_service("script", "script_readonly")
async def get_script_content(
service: Any,
user_google_email: str,
script_id: str,
file_name: str,
) -> str:
"""
Retrieves content of a specific file within a project.
Args:
service: Injected Google API service client
user_google_email: User's email address
script_id: The script project ID
file_name: Name of the file to retrieve
Returns:
str: File content as string
"""
return await _get_script_content_impl(
service, user_google_email, script_id, file_name
)
async def _create_script_project_impl(
service: Any,
user_google_email: str,
title: str,
parent_id: Optional[str] = None,
) -> str:
"""Internal implementation for create_script_project."""
logger.info(f"[create_script_project] Email: {user_google_email}, Title: {title}")
request_body = {"title": title}
if parent_id:
request_body["parentId"] = parent_id
project = await asyncio.to_thread(
service.projects().create(body=request_body).execute
)
script_id = project.get("scriptId", "Unknown")
edit_url = f"https://script.google.com/d/{script_id}/edit"
output = [
f"Created Apps Script project: {title}",
f"Script ID: {script_id}",
f"Edit URL: {edit_url}",
]
logger.info(f"[create_script_project] Created project {script_id}")
return "\n".join(output)
@server.tool()
@handle_http_errors("create_script_project", service_type="script")
@require_google_service("script", "script_projects")
async def create_script_project(
service: Any,
user_google_email: str,
title: str,
parent_id: Optional[str] = None,
) -> str:
"""
Creates a new Apps Script project.
Args:
service: Injected Google API service client
user_google_email: User's email address
title: Project title
parent_id: Optional Drive folder ID or bound container ID
Returns:
str: Formatted string with new project details
"""
return await _create_script_project_impl(
service, user_google_email, title, parent_id
)
async def _update_script_content_impl(
service: Any,
user_google_email: str,
script_id: str,
files: List[Dict[str, str]],
) -> str:
"""Internal implementation for update_script_content."""
logger.info(
f"[update_script_content] Email: {user_google_email}, ID: {script_id}, Files: {len(files)}"
)
request_body = {"files": files}
updated_content = await asyncio.to_thread(
service.projects().updateContent(scriptId=script_id, body=request_body).execute
)
output = [f"Updated script project: {script_id}", "", "Modified files:"]
for file in updated_content.get("files", []):
file_name = file.get("name", "Untitled")
file_type = file.get("type", "Unknown")
output.append(f"- {file_name} ({file_type})")
logger.info(f"[update_script_content] Updated {len(files)} files in {script_id}")
return "\n".join(output)
@server.tool()
@handle_http_errors("update_script_content", service_type="script")
@require_google_service("script", "script_projects")
async def update_script_content(
service: Any,
user_google_email: str,
script_id: str,
files: List[Dict[str, str]],
) -> str:
"""
Updates or creates files in a script project.
Args:
service: Injected Google API service client
user_google_email: User's email address
script_id: The script project ID
files: List of file objects with name, type, and source
Returns:
str: Formatted string confirming update with file list
"""
return await _update_script_content_impl(
service, user_google_email, script_id, files
)
async def _run_script_function_impl(
service: Any,
user_google_email: str,
script_id: str,
function_name: str,
parameters: Optional[list[object]] = None,
dev_mode: bool = False,
) -> str:
"""Internal implementation for run_script_function."""
logger.info(
f"[run_script_function] Email: {user_google_email}, ID: {script_id}, Function: {function_name}"
)
request_body = {"function": function_name, "devMode": dev_mode}
if parameters:
request_body["parameters"] = parameters
try:
response = await asyncio.to_thread(
service.scripts().run(scriptId=script_id, body=request_body).execute
)
if "error" in response:
error_details = response["error"]
error_message = error_details.get("message", "Unknown error")
return (
f"Execution failed\nFunction: {function_name}\nError: {error_message}"
)
result = response.get("response", {}).get("result")
output = [
"Execution successful",
f"Function: {function_name}",
f"Result: {result}",
]
logger.info(f"[run_script_function] Successfully executed {function_name}")
return "\n".join(output)
except Exception as e:
logger.error(f"[run_script_function] Execution error: {str(e)}")
return f"Execution failed\nFunction: {function_name}\nError: {str(e)}"
@server.tool()
@handle_http_errors("run_script_function", service_type="script")
@require_google_service("script", "script_projects")
async def run_script_function(
service: Any,
user_google_email: str,
script_id: str,
function_name: str,
parameters: Optional[list[object]] = None,
dev_mode: bool = False,
) -> str:
"""
Executes a function in a deployed script.
Args:
service: Injected Google API service client
user_google_email: User's email address
script_id: The script project ID
function_name: Name of function to execute
parameters: Optional list of parameters to pass
dev_mode: Whether to run latest code vs deployed version
Returns:
str: Formatted string with execution result or error
"""
return await _run_script_function_impl(
service, user_google_email, script_id, function_name, parameters, dev_mode
)
async def _create_deployment_impl(
service: Any,
user_google_email: str,
script_id: str,
description: str,
version_description: Optional[str] = None,
) -> str:
"""Internal implementation for create_deployment.
Creates a new version first, then creates a deployment using that version.
"""
logger.info(
f"[create_deployment] Email: {user_google_email}, ID: {script_id}, Desc: {description}"
)
# First, create a new version
version_body = {"description": version_description or description}
version = await asyncio.to_thread(
service.projects()
.versions()
.create(scriptId=script_id, body=version_body)
.execute
)
version_number = version.get("versionNumber")
logger.info(f"[create_deployment] Created version {version_number}")
# Now create the deployment with the version number
deployment_body = {
"versionNumber": version_number,
"description": description,
}
deployment = await asyncio.to_thread(
service.projects()
.deployments()
.create(scriptId=script_id, body=deployment_body)
.execute
)
deployment_id = deployment.get("deploymentId", "Unknown")
output = [
f"Created deployment for script: {script_id}",
f"Deployment ID: {deployment_id}",
f"Version: {version_number}",
f"Description: {description}",
]
logger.info(f"[create_deployment] Created deployment {deployment_id}")
return "\n".join(output)
@server.tool()
@handle_http_errors("create_deployment", service_type="script")
@require_google_service("script", "script_deployments")
async def create_deployment(
service: Any,
user_google_email: str,
script_id: str,
description: str,
version_description: Optional[str] = None,
) -> str:
"""
Creates a new deployment of the script.
Args:
service: Injected Google API service client
user_google_email: User's email address
script_id: The script project ID
description: Deployment description
version_description: Optional version description
Returns:
str: Formatted string with deployment details
"""
return await _create_deployment_impl(
service, user_google_email, script_id, description, version_description
)
async def _list_deployments_impl(
service: Any,
user_google_email: str,
script_id: str,
) -> str:
"""Internal implementation for list_deployments."""
logger.info(f"[list_deployments] Email: {user_google_email}, ID: {script_id}")
response = await asyncio.to_thread(
service.projects().deployments().list(scriptId=script_id).execute
)
deployments = response.get("deployments", [])
if not deployments:
return f"No deployments found for script: {script_id}"
output = [f"Deployments for script: {script_id}", ""]
for i, deployment in enumerate(deployments, 1):
deployment_id = deployment.get("deploymentId", "Unknown")
description = deployment.get("description", "No description")
update_time = deployment.get("updateTime", "Unknown")
output.append(f"{i}. {description} ({deployment_id})")
output.append(f" Updated: {update_time}")
output.append("")
logger.info(f"[list_deployments] Found {len(deployments)} deployments")
return "\n".join(output)
@server.tool()
@handle_http_errors("list_deployments", is_read_only=True, service_type="script")
@require_google_service("script", "script_deployments_readonly")
async def list_deployments(
service: Any,
user_google_email: str,
script_id: str,
) -> str:
"""
Lists all deployments for a script project.
Args:
service: Injected Google API service client
user_google_email: User's email address
script_id: The script project ID
Returns:
str: Formatted string with deployment list
"""
return await _list_deployments_impl(service, user_google_email, script_id)
async def _update_deployment_impl(
service: Any,
user_google_email: str,
script_id: str,
deployment_id: str,
description: Optional[str] = None,
) -> str:
"""Internal implementation for update_deployment."""
logger.info(
f"[update_deployment] Email: {user_google_email}, Script: {script_id}, Deployment: {deployment_id}"
)
request_body = {}
if description:
request_body["description"] = description
deployment = await asyncio.to_thread(
service.projects()
.deployments()
.update(scriptId=script_id, deploymentId=deployment_id, body=request_body)
.execute
)
output = [
f"Updated deployment: {deployment_id}",
f"Script: {script_id}",
f"Description: {deployment.get('description', 'No description')}",
]
logger.info(f"[update_deployment] Updated deployment {deployment_id}")
return "\n".join(output)
@server.tool()
@handle_http_errors("update_deployment", service_type="script")
@require_google_service("script", "script_deployments")
async def update_deployment(
service: Any,
user_google_email: str,
script_id: str,
deployment_id: str,
description: Optional[str] = None,
) -> str:
"""
Updates an existing deployment configuration.
Args:
service: Injected Google API service client
user_google_email: User's email address
script_id: The script project ID
deployment_id: The deployment ID to update
description: Optional new description
Returns:
str: Formatted string confirming update
"""
return await _update_deployment_impl(
service, user_google_email, script_id, deployment_id, description
)
async def _delete_deployment_impl(
service: Any,
user_google_email: str,
script_id: str,
deployment_id: str,
) -> str:
"""Internal implementation for delete_deployment."""
logger.info(
f"[delete_deployment] Email: {user_google_email}, Script: {script_id}, Deployment: {deployment_id}"
)
await asyncio.to_thread(
service.projects()
.deployments()
.delete(scriptId=script_id, deploymentId=deployment_id)
.execute
)
output = f"Deleted deployment: {deployment_id} from script: {script_id}"
logger.info(f"[delete_deployment] Deleted deployment {deployment_id}")
return output
@server.tool()
@handle_http_errors("delete_deployment", service_type="script")
@require_google_service("script", "script_deployments")
async def delete_deployment(
service: Any,
user_google_email: str,
script_id: str,
deployment_id: str,
) -> str:
"""
Deletes a deployment.
Args:
service: Injected Google API service client
user_google_email: User's email address
script_id: The script project ID
deployment_id: The deployment ID to delete
Returns:
str: Confirmation message
"""
return await _delete_deployment_impl(
service, user_google_email, script_id, deployment_id
)
async def _list_script_processes_impl(
service: Any,
user_google_email: str,
page_size: int = 50,
script_id: Optional[str] = None,
) -> str:
"""Internal implementation for list_script_processes."""
logger.info(
f"[list_script_processes] Email: {user_google_email}, PageSize: {page_size}"
)
request_params = {"pageSize": page_size}
if script_id:
request_params["scriptId"] = script_id
response = await asyncio.to_thread(
service.processes().list(**request_params).execute
)
processes = response.get("processes", [])
if not processes:
return "No recent script executions found."
output = ["Recent script executions:", ""]
for i, process in enumerate(processes, 1):
function_name = process.get("functionName", "Unknown")
process_status = process.get("processStatus", "Unknown")
start_time = process.get("startTime", "Unknown")
duration = process.get("duration", "Unknown")
output.append(f"{i}. {function_name}")
output.append(f" Status: {process_status}")
output.append(f" Started: {start_time}")
output.append(f" Duration: {duration}")
output.append("")
logger.info(f"[list_script_processes] Found {len(processes)} processes")
return "\n".join(output)
@server.tool()
@handle_http_errors("list_script_processes", is_read_only=True, service_type="script")
@require_google_service("script", "script_readonly")
async def list_script_processes(
service: Any,
user_google_email: str,
page_size: int = 50,
script_id: Optional[str] = None,
) -> str:
"""
Lists recent execution processes for user's scripts.
Args:
service: Injected Google API service client
user_google_email: User's email address
page_size: Number of results (default: 50)
script_id: Optional filter by script ID
Returns:
str: Formatted string with process list
"""
return await _list_script_processes_impl(
service, user_google_email, page_size, script_id
)
# ============================================================================
# Delete Script Project
# ============================================================================
async def _delete_script_project_impl(
service: Any,
user_google_email: str,
script_id: str,
) -> str:
"""Internal implementation for delete_script_project."""
logger.info(
f"[delete_script_project] Email: {user_google_email}, ScriptID: {script_id}"
)
# Apps Script projects are stored as Drive files
await asyncio.to_thread(service.files().delete(fileId=script_id).execute)
logger.info(f"[delete_script_project] Deleted script {script_id}")
return f"Deleted Apps Script project: {script_id}"
@server.tool()
@handle_http_errors("delete_script_project", is_read_only=False, service_type="drive")
@require_google_service("drive", "drive_full")
async def delete_script_project(
service: Any,
user_google_email: str,
script_id: str,
) -> str:
"""
Deletes an Apps Script project.
This permanently deletes the script project. The action cannot be undone.
Args:
service: Injected Google API service client
user_google_email: User's email address
script_id: The script project ID to delete
Returns:
str: Confirmation message
"""
return await _delete_script_project_impl(service, user_google_email, script_id)
# ============================================================================
# Version Management
# ============================================================================
async def _list_versions_impl(
service: Any,
user_google_email: str,
script_id: str,
) -> str:
"""Internal implementation for list_versions."""
logger.info(f"[list_versions] Email: {user_google_email}, ScriptID: {script_id}")
response = await asyncio.to_thread(
service.projects().versions().list(scriptId=script_id).execute
)
versions = response.get("versions", [])
if not versions:
return f"No versions found for script: {script_id}"
output = [f"Versions for script: {script_id}", ""]
for version in versions:
version_number = version.get("versionNumber", "Unknown")
description = version.get("description", "No description")
create_time = version.get("createTime", "Unknown")
output.append(f"Version {version_number}: {description}")
output.append(f" Created: {create_time}")
output.append("")
logger.info(f"[list_versions] Found {len(versions)} versions")
return "\n".join(output)
@server.tool()
@handle_http_errors("list_versions", is_read_only=True, service_type="script")
@require_google_service("script", "script_readonly")
async def list_versions(
service: Any,
user_google_email: str,
script_id: str,
) -> str:
"""
Lists all versions of a script project.
Versions are immutable snapshots of your script code.
They are created when you deploy or explicitly create a version.
Args:
service: Injected Google API service client
user_google_email: User's email address
script_id: The script project ID
Returns:
str: Formatted string with version list
"""
return await _list_versions_impl(service, user_google_email, script_id)
async def _create_version_impl(
service: Any,
user_google_email: str,
script_id: str,
description: Optional[str] = None,
) -> str:
"""Internal implementation for create_version."""
logger.info(f"[create_version] Email: {user_google_email}, ScriptID: {script_id}")
request_body = {}
if description:
request_body["description"] = description
version = await asyncio.to_thread(
service.projects()
.versions()
.create(scriptId=script_id, body=request_body)
.execute
)
version_number = version.get("versionNumber", "Unknown")
create_time = version.get("createTime", "Unknown")
output = [
f"Created version {version_number} for script: {script_id}",
f"Description: {description or 'No description'}",
f"Created: {create_time}",
]
logger.info(f"[create_version] Created version {version_number}")
return "\n".join(output)
@server.tool()
@handle_http_errors("create_version", is_read_only=False, service_type="script")
@require_google_service("script", "script_full")
async def create_version(
service: Any,
user_google_email: str,
script_id: str,
description: Optional[str] = None,
) -> str:
"""
Creates a new immutable version of a script project.
Versions capture a snapshot of the current script code.
Once created, versions cannot be modified.
Args:
service: Injected Google API service client
user_google_email: User's email address
script_id: The script project ID
description: Optional description for this version
Returns:
str: Formatted string with new version details
"""
return await _create_version_impl(
service, user_google_email, script_id, description
)
async def _get_version_impl(
service: Any,
user_google_email: str,
script_id: str,
version_number: int,
) -> str:
"""Internal implementation for get_version."""
logger.info(
f"[get_version] Email: {user_google_email}, ScriptID: {script_id}, Version: {version_number}"
)
version = await asyncio.to_thread(
service.projects()
.versions()
.get(scriptId=script_id, versionNumber=version_number)
.execute
)
ver_num = version.get("versionNumber", "Unknown")
description = version.get("description", "No description")
create_time = version.get("createTime", "Unknown")
output = [
f"Version {ver_num} of script: {script_id}",
f"Description: {description}",
f"Created: {create_time}",
]
logger.info(f"[get_version] Retrieved version {ver_num}")
return "\n".join(output)
@server.tool()
@handle_http_errors("get_version", is_read_only=True, service_type="script")
@require_google_service("script", "script_readonly")
async def get_version(
service: Any,
user_google_email: str,
script_id: str,
version_number: int,
) -> str:
"""
Gets details of a specific version.
Args:
service: Injected Google API service client
user_google_email: User's email address
script_id: The script project ID
version_number: The version number to retrieve (1, 2, 3, etc.)
Returns:
str: Formatted string with version details
"""
return await _get_version_impl(
service, user_google_email, script_id, version_number
)
# ============================================================================
# Metrics
# ============================================================================
async def _get_script_metrics_impl(
service: Any,
user_google_email: str,
script_id: str,
metrics_granularity: str = "DAILY",
) -> str:
"""Internal implementation for get_script_metrics."""
logger.info(
f"[get_script_metrics] Email: {user_google_email}, ScriptID: {script_id}, Granularity: {metrics_granularity}"
)
request_params = {
"scriptId": script_id,
"metricsGranularity": metrics_granularity,
}
response = await asyncio.to_thread(
service.projects().getMetrics(**request_params).execute
)
output = [
f"Metrics for script: {script_id}",
f"Granularity: {metrics_granularity}",
"",
]
# Active users
active_users = response.get("activeUsers", [])
if active_users:
output.append("Active Users:")
for metric in active_users:
start_time = metric.get("startTime", "Unknown")
end_time = metric.get("endTime", "Unknown")
value = metric.get("value", "0")
output.append(f" {start_time} to {end_time}: {value} users")
output.append("")
# Total executions
total_executions = response.get("totalExecutions", [])
if total_executions:
output.append("Total Executions:")