@mutallip/google-workspace-mcp 0.0.0-stage → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -2
  3. package/README.npm.md +28 -0
  4. package/auth/__init__.py +1 -0
  5. package/auth/auth_info_middleware.py +419 -0
  6. package/auth/client_secrets.py +76 -0
  7. package/auth/credential_store.py +598 -0
  8. package/auth/external_oauth_provider.py +369 -0
  9. package/auth/gateway_identity.py +164 -0
  10. package/auth/google_auth.py +1550 -0
  11. package/auth/google_oauth_provider.py +20 -0
  12. package/auth/mcp_session_middleware.py +95 -0
  13. package/auth/oauth21_session_store.py +1332 -0
  14. package/auth/oauth_callback_server.py +466 -0
  15. package/auth/oauth_config.py +693 -0
  16. package/auth/oauth_proxy_config.py +122 -0
  17. package/auth/oauth_responses.py +230 -0
  18. package/auth/oauth_types.py +92 -0
  19. package/auth/permissions.py +330 -0
  20. package/auth/port_resolver.py +153 -0
  21. package/auth/request_identity.py +89 -0
  22. package/auth/scopes.py +369 -0
  23. package/auth/service_decorator.py +1109 -0
  24. package/bin/google-workspace-mcp.cjs +123 -0
  25. package/core/__init__.py +1 -0
  26. package/core/api_enablement.py +108 -0
  27. package/core/attachment_storage.py +496 -0
  28. package/core/camel_case_middleware.py +98 -0
  29. package/core/cli.py +161 -0
  30. package/core/comments.py +609 -0
  31. package/core/config.py +57 -0
  32. package/core/context.py +43 -0
  33. package/core/file_limits.py +632 -0
  34. package/core/gcs_attachment_storage.py +253 -0
  35. package/core/http_utils.py +339 -0
  36. package/core/log_formatter.py +270 -0
  37. package/core/portable_schema_middleware.py +67 -0
  38. package/core/server.py +1192 -0
  39. package/core/startup_ui.py +239 -0
  40. package/core/storage.py +23 -0
  41. package/core/telemetry.py +194 -0
  42. package/core/tool_descriptions.py +19 -0
  43. package/core/tool_registry.py +311 -0
  44. package/core/tool_tier_loader.py +197 -0
  45. package/core/tool_tiers.yaml +179 -0
  46. package/core/toolset_header_middleware.py +67 -0
  47. package/core/utils.py +1537 -0
  48. package/core/valkey_storage.py +271 -0
  49. package/core/warning_filters.py +19 -0
  50. package/fastmcp_server.py +198 -0
  51. package/gappsscript/README.md +512 -0
  52. package/gappsscript/TESTING.md +254 -0
  53. package/gappsscript/__init__.py +0 -0
  54. package/gappsscript/apps_script_tools.py +1940 -0
  55. package/gcalendar/__init__.py +1 -0
  56. package/gcalendar/calendar_helpers.py +1323 -0
  57. package/gcalendar/calendar_tools.py +2252 -0
  58. package/gchat/__init__.py +7 -0
  59. package/gchat/chat_helpers.py +410 -0
  60. package/gchat/chat_tools.py +798 -0
  61. package/gcontacts/__init__.py +1 -0
  62. package/gcontacts/contacts_helpers.py +765 -0
  63. package/gcontacts/contacts_tools.py +1685 -0
  64. package/gdocs/__init__.py +0 -0
  65. package/gdocs/docs_anchors.py +163 -0
  66. package/gdocs/docs_comments.py +89 -0
  67. package/gdocs/docs_helpers.py +2201 -0
  68. package/gdocs/docs_links.py +87 -0
  69. package/gdocs/docs_markdown.py +828 -0
  70. package/gdocs/docs_markdown_writer.py +592 -0
  71. package/gdocs/docs_plain_text.py +463 -0
  72. package/gdocs/docs_structure.py +621 -0
  73. package/gdocs/docs_tables.py +425 -0
  74. package/gdocs/docs_tools.py +3300 -0
  75. package/gdocs/managers/__init__.py +18 -0
  76. package/gdocs/managers/batch_operation_manager.py +1694 -0
  77. package/gdocs/managers/header_footer_manager.py +526 -0
  78. package/gdocs/managers/table_operation_manager.py +488 -0
  79. package/gdocs/managers/validation_manager.py +1504 -0
  80. package/gdocs/operation_schemas.py +594 -0
  81. package/gdrive/__init__.py +0 -0
  82. package/gdrive/drive_helpers.py +1738 -0
  83. package/gdrive/drive_tools.py +3085 -0
  84. package/gforms/__init__.py +3 -0
  85. package/gforms/forms_tools.py +575 -0
  86. package/gmail/__init__.py +1 -0
  87. package/gmail/gmail_helpers.py +2107 -0
  88. package/gmail/gmail_tools.py +4895 -0
  89. package/gmail/gmail_web_mime.py +441 -0
  90. package/gsearch/__init__.py +0 -0
  91. package/gsearch/search_tools.py +253 -0
  92. package/gsheets/__init__.py +31 -0
  93. package/gsheets/sheets_helpers.py +2236 -0
  94. package/gsheets/sheets_tools.py +3280 -0
  95. package/gslides/__init__.py +0 -0
  96. package/gslides/slides_digest.py +390 -0
  97. package/gslides/slides_helpers.py +392 -0
  98. package/gslides/slides_markup.py +770 -0
  99. package/gslides/slides_tools.py +376 -0
  100. package/gtasks/__init__.py +5 -0
  101. package/gtasks/tasks_tools.py +936 -0
  102. package/main.py +1170 -0
  103. package/package.json +43 -4
  104. package/pyproject.toml +173 -0
  105. package/uv.lock +2504 -0
@@ -0,0 +1,1738 @@
1
+ """
2
+ Google Drive Helper Functions
3
+
4
+ Shared utilities for Google Drive operations including permission checking,
5
+ remote content download, and import-time format conversion.
6
+ """
7
+
8
+ import asyncio
9
+ import base64
10
+ import binascii
11
+ import hashlib
12
+ import io
13
+ import json
14
+ import logging
15
+ import re
16
+ import zipfile
17
+ import zlib
18
+ from pathlib import Path
19
+ from tempfile import NamedTemporaryFile, SpooledTemporaryFile
20
+ from typing import List, Dict, Any, Awaitable, BinaryIO, Callable, Optional, Tuple
21
+ from urllib.parse import urlencode, urlparse
22
+ from urllib.request import url2pathname
23
+ from weakref import WeakValueDictionary
24
+
25
+ import httpx
26
+ from googleapiclient.errors import HttpError
27
+ from googleapiclient.http import HttpRequest, MediaIoBaseDownload, MediaIoBaseUpload
28
+
29
+ from auth.service_decorator import require_google_service
30
+ from core.attachment_storage import resolve_local_attachment
31
+ from core.file_limits import download_media_bytes
32
+ from core.http_utils import (
33
+ PrivateHostError,
34
+ redact_url as _redact_url,
35
+ ssrf_safe_stream as _ssrf_safe_stream,
36
+ )
37
+ from core.utils import (
38
+ GOOGLE_API_WRITE_RETRIES,
39
+ NotARegularFileError,
40
+ UserInputError,
41
+ local_file_access_enabled,
42
+ open_validated_file,
43
+ )
44
+
45
+ logger = logging.getLogger(__name__)
46
+
47
+ VALID_SHARE_ROLES = {"reader", "commenter", "writer"}
48
+ VALID_SHARE_TYPES = {"user", "group", "domain", "anyone"}
49
+
50
+
51
+ def check_public_link_permission(permissions: List[Dict[str, Any]]) -> bool:
52
+ """
53
+ Check if file has 'anyone with the link' permission.
54
+
55
+ Args:
56
+ permissions: List of permission objects from Google Drive API
57
+
58
+ Returns:
59
+ bool: True if file has public link sharing enabled
60
+ """
61
+ return any(
62
+ p.get("type") == "anyone" and p.get("role") in ["reader", "writer", "commenter"]
63
+ for p in permissions
64
+ )
65
+
66
+
67
+ def list_all_permissions(service, file_id: str) -> List[Dict[str, Any]]:
68
+ """
69
+ Return the complete permission set for a file, including Shared Drive items.
70
+
71
+ files.get() does NOT populate the inline `permissions` field (nor the `shared`
72
+ boolean) for items that live in a Shared Drive, even when supportsAllDrives=True
73
+ is passed. permissions.list() is the only reliable source in that case. This
74
+ helper paginates and always sets supportsAllDrives=True.
75
+ """
76
+ permissions: List[Dict[str, Any]] = []
77
+ page_token = None
78
+ while True:
79
+ resp = (
80
+ service.permissions()
81
+ .list(
82
+ fileId=file_id,
83
+ supportsAllDrives=True,
84
+ pageSize=100,
85
+ pageToken=page_token,
86
+ fields=(
87
+ "nextPageToken, permissions(id, type, role, emailAddress, "
88
+ "domain, expirationTime, permissionDetails, allowFileDiscovery)"
89
+ ),
90
+ )
91
+ .execute()
92
+ )
93
+ permissions.extend(resp.get("permissions", []))
94
+ page_token = resp.get("nextPageToken")
95
+ if not page_token:
96
+ break
97
+ return permissions
98
+
99
+
100
+ def derive_shared_state(
101
+ file_metadata: Dict[str, Any], permissions: List[Dict[str, Any]]
102
+ ) -> bool:
103
+ """
104
+ Determine whether a file is shared.
105
+
106
+ The Drive API omits the `shared` boolean for Shared Drive items, so derive it
107
+ from the driveId and the resolved permission set instead of trusting `shared`.
108
+ """
109
+ if file_metadata.get("shared"):
110
+ return True
111
+ if file_metadata.get("driveId"):
112
+ return True
113
+ if any(p.get("type") in ("anyone", "domain") for p in permissions):
114
+ return True
115
+ return len([p for p in permissions if p.get("type") in ("user", "group")]) > 1
116
+
117
+
118
+ def format_public_sharing_error(file_name: str, file_id: str) -> str:
119
+ """
120
+ Format error message for files without public sharing.
121
+
122
+ Args:
123
+ file_name: Name of the file
124
+ file_id: Google Drive file ID
125
+
126
+ Returns:
127
+ str: Formatted error message
128
+ """
129
+ return (
130
+ f"❌ Permission Error: '{file_name}' not shared publicly. "
131
+ f"Set 'Anyone with the link' → 'Viewer' in Google Drive sharing. "
132
+ f"File: https://drive.google.com/file/d/{file_id}/view"
133
+ )
134
+
135
+
136
+ def get_drive_image_url(file_id: str) -> str:
137
+ """
138
+ Get the correct Drive URL format for publicly shared images.
139
+
140
+ Args:
141
+ file_id: Google Drive file ID
142
+
143
+ Returns:
144
+ str: URL for embedding Drive images
145
+ """
146
+ return f"https://drive.google.com/uc?export=view&id={file_id}"
147
+
148
+
149
+ def validate_share_role(role: str) -> None:
150
+ """
151
+ Validate that the role is valid for sharing.
152
+
153
+ Args:
154
+ role: The permission role to validate
155
+
156
+ Raises:
157
+ ValueError: If role is not reader, commenter, or writer
158
+ """
159
+ if role not in VALID_SHARE_ROLES:
160
+ raise ValueError(
161
+ f"Invalid role '{role}'. Must be one of: {', '.join(sorted(VALID_SHARE_ROLES))}"
162
+ )
163
+
164
+
165
+ def validate_share_type(share_type: str) -> None:
166
+ """
167
+ Validate that the share type is valid.
168
+
169
+ Args:
170
+ share_type: The type of sharing to validate
171
+
172
+ Raises:
173
+ ValueError: If share_type is not user, group, domain, or anyone
174
+ """
175
+ if share_type not in VALID_SHARE_TYPES:
176
+ raise ValueError(
177
+ f"Invalid share_type '{share_type}'. Must be one of: {', '.join(sorted(VALID_SHARE_TYPES))}"
178
+ )
179
+
180
+
181
+ RFC3339_PATTERN = re.compile(
182
+ r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$"
183
+ )
184
+
185
+
186
+ def validate_expiration_time(expiration_time: str) -> None:
187
+ """
188
+ Validate that expiration_time is in RFC 3339 format.
189
+
190
+ Args:
191
+ expiration_time: The expiration time string to validate
192
+
193
+ Raises:
194
+ ValueError: If expiration_time is not valid RFC 3339 format
195
+ """
196
+ if not RFC3339_PATTERN.fullmatch(expiration_time):
197
+ raise ValueError(
198
+ f"Invalid expiration_time '{expiration_time}'. "
199
+ "Must be RFC 3339 format (e.g., '2025-01-15T00:00:00Z')"
200
+ )
201
+
202
+
203
+ def format_permission_info(permission: Dict[str, Any]) -> str:
204
+ """
205
+ Format a permission object for display.
206
+
207
+ Args:
208
+ permission: Permission object from Google Drive API
209
+
210
+ Returns:
211
+ str: Human-readable permission description with ID
212
+ """
213
+ perm_type = permission.get("type", "unknown")
214
+ role = permission.get("role", "unknown")
215
+ perm_id = permission.get("id", "")
216
+
217
+ if perm_type == "anyone":
218
+ base = f"Anyone with the link ({role}) [id: {perm_id}]"
219
+ elif perm_type == "user":
220
+ email = permission.get("emailAddress", "unknown")
221
+ base = f"User: {email} ({role}) [id: {perm_id}]"
222
+ elif perm_type == "group":
223
+ email = permission.get("emailAddress", "unknown")
224
+ base = f"Group: {email} ({role}) [id: {perm_id}]"
225
+ elif perm_type == "domain":
226
+ domain = permission.get("domain", "unknown")
227
+ base = f"Domain: {domain} ({role}) [id: {perm_id}]"
228
+ else:
229
+ base = f"{perm_type} ({role}) [id: {perm_id}]"
230
+
231
+ extras = []
232
+ if permission.get("expirationTime"):
233
+ extras.append(f"expires: {permission['expirationTime']}")
234
+
235
+ perm_details = permission.get("permissionDetails", [])
236
+ if perm_details:
237
+ for detail in perm_details:
238
+ if detail.get("inherited") and detail.get("inheritedFrom"):
239
+ extras.append(f"inherited from: {detail['inheritedFrom']}")
240
+ break
241
+
242
+ if extras:
243
+ return f"{base} | {', '.join(extras)}"
244
+ return base
245
+
246
+
247
+ # Matches an explicit trashed clause anywhere in a Drive query, e.g. "trashed = true".
248
+ # Drive accepts both = and != on boolean fields, so `trashed != false` is just as much
249
+ # a caller-supplied filter as `trashed = true`. Used both for structured-query detection
250
+ # and to avoid double-adding a trashed filter.
251
+ TRASHED_CLAUSE_PATTERN = re.compile(r"\btrashed\s*!?=\s*(true|false)\b", re.IGNORECASE)
252
+
253
+ # Matches a Drive query string literal, including backslash escapes, in either quote
254
+ # style: 'a\'b' or "a\"b". Used to blank out literals before looking for operators, so
255
+ # text that merely *looks* like a predicate inside a value is not mistaken for one.
256
+ QUERY_STRING_LITERAL_PATTERN = re.compile(r"'(?:\\.|[^'\\])*'|\"(?:\\.|[^\"\\])*\"")
257
+
258
+
259
+ def escape_drive_query_value(value: str) -> str:
260
+ """Escape a value for use inside a single-quoted Drive query string literal."""
261
+ return value.replace("\\", "\\\\").replace("'", "\\'")
262
+
263
+
264
+ def has_explicit_trashed_clause(query: str) -> bool:
265
+ """Return True when `query` contains a real `trashed =`/`!=` `true/false` predicate.
266
+
267
+ Quoted values are blanked out first, so a search for a filename that happens to
268
+ contain the text (``name contains 'trashed=false'``) is not read as the caller
269
+ having already filtered by trash state.
270
+ """
271
+ without_literals = QUERY_STRING_LITERAL_PATTERN.sub("''", query)
272
+ return bool(TRASHED_CLAUSE_PATTERN.search(without_literals))
273
+
274
+
275
+ # Drive API v2 query field names and their v3 replacements, see
276
+ # https://developers.google.com/drive/api/guides/v2-to-v3-reference
277
+ DRIVE_V2_TO_V3_QUERY_FIELD_MAP = {
278
+ "title": "name",
279
+ "createddate": "createdTime",
280
+ "modifieddate": "modifiedTime",
281
+ "lastviewedbymedate": "viewedByMeTime",
282
+ }
283
+
284
+ # Literals are matched first so field names inside quoted values are left alone.
285
+ _DRIVE_V2_FIELD_OR_LITERAL_PATTERN = re.compile(
286
+ rf"({QUERY_STRING_LITERAL_PATTERN.pattern})"
287
+ rf"|\b({'|'.join(DRIVE_V2_TO_V3_QUERY_FIELD_MAP)})\b",
288
+ re.IGNORECASE,
289
+ )
290
+
291
+
292
+ def normalize_drive_query_v2_compat(query: str) -> str:
293
+ """Rewrite Drive API v2 field names outside string literals to their v3 names.
294
+
295
+ ``title contains 'title'`` becomes ``name contains 'title'``.
296
+ """
297
+ return _DRIVE_V2_FIELD_OR_LITERAL_PATTERN.sub(
298
+ lambda m: m.group(1) or DRIVE_V2_TO_V3_QUERY_FIELD_MAP[m.group(2).lower()],
299
+ query,
300
+ )
301
+
302
+
303
+ # Precompiled regex patterns for Drive query detection
304
+ DRIVE_QUERY_PATTERNS = [
305
+ re.compile(r'\b\w+\s*(=|!=|>|<)\s*[\'"].*?[\'"]', re.IGNORECASE), # field = 'value'
306
+ re.compile(r"\b\w+\s*(=|!=|>|<)\s*\d+", re.IGNORECASE), # field = number
307
+ re.compile(r"\bcontains\b", re.IGNORECASE), # contains operator
308
+ re.compile(r"\bin\s+parents\b", re.IGNORECASE), # in parents
309
+ re.compile(r"\bhas\s*\{", re.IGNORECASE), # has {properties}
310
+ TRASHED_CLAUSE_PATTERN, # trashed =/!= true/false
311
+ re.compile(r"\bstarred\s*=\s*(true|false)\b", re.IGNORECASE), # starred=true/false
312
+ re.compile(
313
+ r'[\'"][^\'"]+[\'"]\s+in\s+parents', re.IGNORECASE
314
+ ), # 'parentId' in parents
315
+ re.compile(r"\bfullText\s+contains\b", re.IGNORECASE), # fullText contains
316
+ re.compile(r"\bname\s*(=|contains)\b", re.IGNORECASE), # name = or name contains
317
+ re.compile(r"\bmimeType\s*(=|!=)\b", re.IGNORECASE), # mimeType operators
318
+ ]
319
+
320
+
321
+ def build_drive_list_params(
322
+ query: str,
323
+ page_size: int,
324
+ drive_id: Optional[str] = None,
325
+ include_items_from_all_drives: bool = True,
326
+ corpora: Optional[str] = None,
327
+ page_token: Optional[str] = None,
328
+ detailed: bool = True,
329
+ include_permissions: bool = False,
330
+ order_by: Optional[str] = None,
331
+ ) -> Dict[str, Any]:
332
+ """
333
+ Helper function to build common list parameters for Drive API calls.
334
+
335
+ Args:
336
+ query: The search query string
337
+ page_size: Maximum number of items to return
338
+ drive_id: Optional shared drive ID
339
+ include_items_from_all_drives: Whether to include items from all drives
340
+ corpora: Optional corpus specification. Defaults to 'drive' when drive_id
341
+ is set, otherwise 'allDrives' when include_items_from_all_drives is True.
342
+ page_token: Optional page token for pagination (from a previous nextPageToken)
343
+ detailed: Whether to request size, modifiedTime, and webViewLink fields.
344
+ Defaults to True to preserve existing behavior.
345
+ include_permissions: Whether detailed results should include file ACL fields.
346
+ order_by: Optional sort order. Comma-separated list of sort keys.
347
+ Valid keys: 'createdTime', 'folder', 'modifiedByMeTime', 'modifiedTime',
348
+ 'name', 'name_natural', 'quotaBytesUsed', 'recency', 'sharedWithMeTime',
349
+ 'starred', 'viewedByMeTime'. Add 'desc' modifier to reverse (e.g., 'modifiedTime desc').
350
+ Example: 'folder,modifiedTime desc,name'
351
+
352
+ Returns:
353
+ Dictionary of parameters for Drive API list calls
354
+ """
355
+ if detailed:
356
+ permission_fields = (
357
+ ", permissions(id, type, role)" if include_permissions else ""
358
+ )
359
+ fields = (
360
+ "nextPageToken, incompleteSearch, files(id, name, mimeType, webViewLink, iconLink,"
361
+ " modifiedTime, createdTime, size, driveId,"
362
+ " lastModifyingUser(displayName, emailAddress)"
363
+ f"{permission_fields})"
364
+ )
365
+ else:
366
+ fields = "nextPageToken, incompleteSearch, files(id, name, mimeType)"
367
+ list_params = {
368
+ "q": query,
369
+ "pageSize": page_size,
370
+ "fields": fields,
371
+ "supportsAllDrives": True,
372
+ "includeItemsFromAllDrives": include_items_from_all_drives,
373
+ }
374
+
375
+ if page_token:
376
+ list_params["pageToken"] = page_token
377
+
378
+ if order_by is not None:
379
+ normalized_order_by = order_by.strip()
380
+ if normalized_order_by:
381
+ list_params["orderBy"] = normalized_order_by
382
+
383
+ if drive_id:
384
+ list_params["driveId"] = drive_id
385
+ list_params["corpora"] = corpora or "drive"
386
+ elif corpora:
387
+ list_params["corpora"] = corpora
388
+ elif include_items_from_all_drives:
389
+ # The API's default 'user' corpus skips shared drives the user belongs to
390
+ # even when includeItemsFromAllDrives is set.
391
+ list_params["corpora"] = "allDrives"
392
+
393
+ return list_params
394
+
395
+
396
+ INCOMPLETE_SEARCH_WARNING = (
397
+ "WARNING: Google Drive did not search every corpus (incompleteSearch), so these "
398
+ "results may be incomplete. Narrow the search (e.g. a specific shared drive or "
399
+ "the 'user' corpus) to find the rest."
400
+ )
401
+
402
+
403
+ def flag_incomplete_search(text: str, response: Dict[str, Any]) -> str:
404
+ """Append a warning when a files.list response reports incompleteSearch.
405
+
406
+ Searching the 'allDrives' corpus can skip some shared drives; without this the
407
+ caller would present a partial result set as complete.
408
+ """
409
+ if response.get("incompleteSearch"):
410
+ return f"{text}\n{INCOMPLETE_SEARCH_WARNING}"
411
+ return text
412
+
413
+
414
+ GOOGLE_APPS_MIME_PREFIX = "application/vnd.google-apps."
415
+ SHORTCUT_MIME_TYPE = "application/vnd.google-apps.shortcut"
416
+ FOLDER_MIME_TYPE = "application/vnd.google-apps.folder"
417
+
418
+ # RFC 6838 token-style MIME type validation (safe for Drive query interpolation).
419
+ MIME_TYPE_PATTERN = re.compile(r"^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+$")
420
+
421
+ # Mapping from friendly type names to Google Drive MIME types.
422
+ # Raw MIME type strings (containing '/') are always accepted as-is.
423
+ FILE_TYPE_MIME_MAP: Dict[str, str] = {
424
+ "folder": "application/vnd.google-apps.folder",
425
+ "folders": "application/vnd.google-apps.folder",
426
+ "document": "application/vnd.google-apps.document",
427
+ "doc": "application/vnd.google-apps.document",
428
+ "documents": "application/vnd.google-apps.document",
429
+ "docs": "application/vnd.google-apps.document",
430
+ "spreadsheet": "application/vnd.google-apps.spreadsheet",
431
+ "sheet": "application/vnd.google-apps.spreadsheet",
432
+ "spreadsheets": "application/vnd.google-apps.spreadsheet",
433
+ "sheets": "application/vnd.google-apps.spreadsheet",
434
+ "presentation": "application/vnd.google-apps.presentation",
435
+ "presentations": "application/vnd.google-apps.presentation",
436
+ "slide": "application/vnd.google-apps.presentation",
437
+ "slides": "application/vnd.google-apps.presentation",
438
+ "form": "application/vnd.google-apps.form",
439
+ "forms": "application/vnd.google-apps.form",
440
+ "drawing": "application/vnd.google-apps.drawing",
441
+ "drawings": "application/vnd.google-apps.drawing",
442
+ "pdf": "application/pdf",
443
+ "pdfs": "application/pdf",
444
+ "shortcut": "application/vnd.google-apps.shortcut",
445
+ "shortcuts": "application/vnd.google-apps.shortcut",
446
+ "script": "application/vnd.google-apps.script",
447
+ "scripts": "application/vnd.google-apps.script",
448
+ "site": "application/vnd.google-apps.site",
449
+ "sites": "application/vnd.google-apps.site",
450
+ "jam": "application/vnd.google-apps.jam",
451
+ "jamboard": "application/vnd.google-apps.jam",
452
+ "jamboards": "application/vnd.google-apps.jam",
453
+ }
454
+
455
+
456
+ def resolve_file_type_mime(file_type: str) -> str:
457
+ """
458
+ Resolve a friendly file type name or raw MIME type string to a Drive MIME type.
459
+
460
+ If `file_type` contains '/' it is returned as-is (treated as a raw MIME type).
461
+ Otherwise it is looked up in FILE_TYPE_MIME_MAP.
462
+
463
+ Args:
464
+ file_type: A friendly name ('folder', 'document', 'pdf', …) or a raw MIME
465
+ type string ('application/vnd.google-apps.document', …).
466
+
467
+ Returns:
468
+ str: The resolved MIME type string.
469
+
470
+ Raises:
471
+ ValueError: If the value is not a recognised friendly name and contains no '/'.
472
+ """
473
+ normalized = file_type.strip()
474
+ if not normalized:
475
+ raise ValueError("file_type cannot be empty.")
476
+
477
+ if "/" in normalized:
478
+ normalized_mime = normalized.lower()
479
+ if not MIME_TYPE_PATTERN.fullmatch(normalized_mime):
480
+ raise ValueError(
481
+ f"Invalid MIME type '{file_type}'. Expected format like 'application/pdf'."
482
+ )
483
+ return normalized_mime
484
+ lower = normalized.lower()
485
+ if lower not in FILE_TYPE_MIME_MAP:
486
+ valid = ", ".join(sorted(FILE_TYPE_MIME_MAP.keys()))
487
+ raise ValueError(
488
+ f"Unknown file_type '{file_type}'. Pass a MIME type directly (e.g. "
489
+ f"'application/pdf') or use one of the friendly names: {valid}"
490
+ )
491
+ return FILE_TYPE_MIME_MAP[lower]
492
+
493
+
494
+ BASE_SHORTCUT_FIELDS = (
495
+ "id, mimeType, parents, shortcutDetails(targetId, targetMimeType)"
496
+ )
497
+
498
+
499
+ async def resolve_drive_item(
500
+ service,
501
+ file_id: str,
502
+ *,
503
+ extra_fields: Optional[str] = None,
504
+ max_depth: int = 5,
505
+ follow_shortcuts: bool = True,
506
+ ) -> Tuple[str, Dict[str, Any]]:
507
+ """
508
+ Fetch Drive item metadata and optionally resolve shortcuts to their targets.
509
+
510
+ By default shortcuts are followed so content-oriented callers operate on the real
511
+ item. Set ``follow_shortcuts=False`` for resource-local metadata mutations (rename,
512
+ move, trash, star, description, etc.) that must act on the shortcut itself.
513
+
514
+ Returns the selected file ID and its metadata. Raises if shortcut targets loop
515
+ or exceed max_depth to avoid infinite recursion.
516
+ """
517
+ current_id = file_id
518
+ depth = 0
519
+ fields = BASE_SHORTCUT_FIELDS
520
+ if extra_fields:
521
+ fields = f"{fields}, {extra_fields}"
522
+
523
+ while True:
524
+ metadata = await asyncio.to_thread(
525
+ service.files()
526
+ .get(fileId=current_id, fields=fields, supportsAllDrives=True)
527
+ .execute
528
+ )
529
+ mime_type = metadata.get("mimeType")
530
+ if not follow_shortcuts or mime_type != SHORTCUT_MIME_TYPE:
531
+ return current_id, metadata
532
+
533
+ shortcut_details = metadata.get("shortcutDetails") or {}
534
+ target_id = shortcut_details.get("targetId")
535
+ if not target_id:
536
+ raise Exception(f"Shortcut '{current_id}' is missing target details.")
537
+
538
+ depth += 1
539
+ if depth > max_depth:
540
+ raise Exception(
541
+ f"Shortcut resolution exceeded {max_depth} hops starting from '{file_id}'."
542
+ )
543
+ current_id = target_id
544
+
545
+
546
+ async def resolve_folder_id(
547
+ service,
548
+ folder_id: str,
549
+ *,
550
+ max_depth: int = 5,
551
+ ) -> str:
552
+ """
553
+ Resolve a folder ID that might be a shortcut and ensure the final target is a folder.
554
+ """
555
+ resolved_id, metadata = await resolve_drive_item(
556
+ service,
557
+ folder_id,
558
+ max_depth=max_depth,
559
+ )
560
+ mime_type = metadata.get("mimeType")
561
+ if mime_type != FOLDER_MIME_TYPE:
562
+ raise Exception(
563
+ f"Resolved ID '{resolved_id}' (from '{folder_id}') is not a folder; mimeType={mime_type}."
564
+ )
565
+ return resolved_id
566
+
567
+
568
+ async def place_file_in_folder(
569
+ drive_service: Any,
570
+ file_id: str,
571
+ folder_id: str,
572
+ *,
573
+ tool_name: str = "place_file_in_folder",
574
+ ) -> str:
575
+ """
576
+ Move ``file_id`` into ``folder_id`` (ID or shortcut), removing its other parents.
577
+
578
+ The Docs and Sheets create endpoints accept no parent, so new files land in
579
+ My Drive root and must be re-parented afterwards. Returns the resolved folder ID.
580
+ """
581
+ resolved_folder_id = await resolve_folder_id(drive_service, folder_id)
582
+ existing = await asyncio.to_thread(
583
+ drive_service.files()
584
+ .get(fileId=file_id, fields="parents", supportsAllDrives=True)
585
+ .execute
586
+ )
587
+ # Skip the destination so a file already there is not both added and removed.
588
+ remove_parents = ",".join(
589
+ parent for parent in existing.get("parents", []) if parent != resolved_folder_id
590
+ )
591
+ await asyncio.to_thread(
592
+ drive_service.files()
593
+ .update(
594
+ fileId=file_id,
595
+ addParents=resolved_folder_id,
596
+ removeParents=remove_parents,
597
+ fields="id, parents",
598
+ supportsAllDrives=True,
599
+ )
600
+ .execute
601
+ )
602
+ logger.info(
603
+ f"[{tool_name}] Moved file {file_id} into folder {resolved_folder_id} "
604
+ f"(removed parents: '{remove_parents}')"
605
+ )
606
+ return resolved_folder_id
607
+
608
+
609
+ @require_google_service("drive", "drive_file")
610
+ async def place_created_file_in_folder(
611
+ service,
612
+ user_google_email: str,
613
+ file_id: str,
614
+ folder_id: str,
615
+ tool_name: str = "place_created_file_in_folder",
616
+ ) -> str:
617
+ """
618
+ Authenticate Drive on demand, then run ``place_file_in_folder``.
619
+
620
+ Kept off the calling tool's decorator so the ``folder_id="root"`` default
621
+ needs no Drive scope (and no full-Drive scope under domain-wide delegation).
622
+ """
623
+ return await place_file_in_folder(service, file_id, folder_id, tool_name=tool_name)
624
+
625
+
626
+ async def move_new_file_to_folder(
627
+ user_google_email: str,
628
+ file_id: str,
629
+ folder_id: Optional[str],
630
+ tool_name: str,
631
+ ) -> str:
632
+ """
633
+ Move a just-created file into ``folder_id`` and return a note for the reply.
634
+
635
+ A failed move is reported, not raised: the file already exists in My Drive
636
+ root, so the caller still needs its ID.
637
+ """
638
+ if not folder_id or folder_id == "root":
639
+ return ""
640
+ try:
641
+ await place_created_file_in_folder(
642
+ user_google_email=user_google_email,
643
+ file_id=file_id,
644
+ folder_id=folder_id,
645
+ tool_name=tool_name,
646
+ )
647
+ except Exception as e:
648
+ logger.warning(
649
+ f"[{tool_name}] Created file {file_id} but could not move it into "
650
+ f"folder '{folder_id}': {e}"
651
+ )
652
+ return (
653
+ f" WARNING: left in My Drive root - could not move it into folder "
654
+ f"'{folder_id}': {e}"
655
+ )
656
+ return f" Placed in folder '{folder_id}'."
657
+
658
+
659
+ async def _create_drive_folder_impl(
660
+ service,
661
+ user_google_email: str,
662
+ folder_name: str,
663
+ parent_folder_id: str = "root",
664
+ ) -> str:
665
+ """Internal implementation for create_drive_folder. Used by tests."""
666
+ resolved_folder_id = await resolve_folder_id(service, parent_folder_id)
667
+ file_metadata = {
668
+ "name": folder_name,
669
+ "parents": [resolved_folder_id],
670
+ "mimeType": FOLDER_MIME_TYPE,
671
+ }
672
+ created_file = await asyncio.to_thread(
673
+ service.files()
674
+ .create(
675
+ body=file_metadata,
676
+ fields="id, name, webViewLink",
677
+ supportsAllDrives=True,
678
+ )
679
+ .execute
680
+ )
681
+ link = created_file.get("webViewLink", "")
682
+ return (
683
+ f"Successfully created folder '{created_file.get('name', folder_name)}' (ID: {created_file.get('id', 'N/A')}) "
684
+ f"in folder '{parent_folder_id}' for {user_google_email}. Link: {link}"
685
+ )
686
+
687
+
688
+ async def _create_drive_shortcut_impl(
689
+ service,
690
+ user_google_email: str,
691
+ shortcut_name: str,
692
+ target_id: str,
693
+ parent_folder_id: str = "root",
694
+ ) -> str:
695
+ """Create a metadata-only shortcut to target_id inside parent_folder_id."""
696
+ resolved_folder_id = await resolve_folder_id(service, parent_folder_id)
697
+ file_metadata = {
698
+ "name": shortcut_name,
699
+ "parents": [resolved_folder_id],
700
+ "mimeType": SHORTCUT_MIME_TYPE,
701
+ "shortcutDetails": {"targetId": target_id},
702
+ }
703
+ created_file = await asyncio.to_thread(
704
+ service.files()
705
+ .create(
706
+ body=file_metadata,
707
+ fields="id, name, webViewLink, shortcutDetails(targetId, targetMimeType)",
708
+ supportsAllDrives=True,
709
+ )
710
+ .execute
711
+ )
712
+ link = created_file.get("webViewLink", "No link available")
713
+ target = created_file.get("shortcutDetails") or {}
714
+ target_mime_type = target.get("targetMimeType")
715
+ target_note = f" ({target_mime_type})" if target_mime_type else ""
716
+ return (
717
+ f"Successfully created shortcut '{created_file.get('name', shortcut_name)}' "
718
+ f"(ID: {created_file.get('id', 'N/A')}) to '{target.get('targetId', target_id)}'"
719
+ f"{target_note} in folder '{parent_folder_id}' for {user_google_email}. "
720
+ f"Link: {link}"
721
+ )
722
+
723
+
724
+ DOWNLOAD_CHUNK_SIZE_BYTES = 256 * 1024 # 256 KB
725
+ UPLOAD_CHUNK_SIZE_BYTES = 5 * 1024 * 1024 # 5 MB (Google recommended minimum)
726
+ MAX_DOWNLOAD_BYTES = 2 * 1024 * 1024 * 1024 # 2 GB safety limit for URL downloads
727
+
728
+ MAX_INLINE_BASE64_BYTES = 100 * 1024 * 1024 # 100 MB decoded payload ceiling
729
+ MAX_ZIP_MEMBER_COUNT = 10_000
730
+ MAX_ZIP_UNCOMPRESSED_BYTES = 500 * 1024 * 1024 # 500 MB total uncompressed
731
+ MAX_ZIP_COMPRESSION_RATIO = 100
732
+
733
+ # Office Open XML and OpenDocument payloads are ZIP containers. Drive accepts
734
+ # malformed bytes at upload time and may only surface the corruption minutes later
735
+ # when its Docs/Sheets/Slides importer opens the file, so validate inline payloads
736
+ # before making a write request.
737
+ ZIP_CONTAINER_REQUIRED_MEMBERS = {
738
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": {
739
+ "[Content_Types].xml",
740
+ "word/document.xml",
741
+ },
742
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
743
+ "[Content_Types].xml",
744
+ "xl/workbook.xml",
745
+ },
746
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": {
747
+ "[Content_Types].xml",
748
+ "ppt/presentation.xml",
749
+ },
750
+ "application/vnd.oasis.opendocument.text": {
751
+ "mimetype",
752
+ "META-INF/manifest.xml",
753
+ },
754
+ "application/vnd.oasis.opendocument.spreadsheet": {
755
+ "mimetype",
756
+ "META-INF/manifest.xml",
757
+ },
758
+ "application/vnd.oasis.opendocument.presentation": {
759
+ "mimetype",
760
+ "META-INF/manifest.xml",
761
+ },
762
+ }
763
+
764
+
765
+ def _decode_base64_upload(
766
+ base64_content: str,
767
+ *,
768
+ tool_name: str,
769
+ mime_type: str,
770
+ expected_sha256: Optional[str] = None,
771
+ ) -> bytes:
772
+ """Decode and validate an inline binary upload before sending it to Drive."""
773
+ max_encoded_len = ((MAX_INLINE_BASE64_BYTES + 2) // 3) * 4
774
+ if len(base64_content) > max_encoded_len:
775
+ estimated_decoded_size = len(base64_content) * 3 // 4
776
+ raise ValueError(
777
+ f"[{tool_name}] Inline payload exceeds the "
778
+ f"{MAX_INLINE_BASE64_BYTES // (1024 * 1024)} MB limit "
779
+ f"(estimated {estimated_decoded_size // (1024 * 1024)} MB). "
780
+ "Upload via 'fileUrl' instead."
781
+ )
782
+
783
+ try:
784
+ file_data = base64.b64decode(base64_content, validate=True)
785
+ except (binascii.Error, ValueError) as exc:
786
+ raise ValueError("'base64_content' must be valid standard base64.") from exc
787
+
788
+ if len(file_data) > MAX_INLINE_BASE64_BYTES:
789
+ raise ValueError(
790
+ f"[{tool_name}] Inline payload exceeds the "
791
+ f"{MAX_INLINE_BASE64_BYTES // (1024 * 1024)} MB limit "
792
+ f"({len(file_data) // (1024 * 1024)} MB). "
793
+ "Upload via 'fileUrl' instead."
794
+ )
795
+
796
+ if expected_sha256 is not None:
797
+ normalized_sha256 = expected_sha256.strip().lower()
798
+ if not re.fullmatch(r"[0-9a-f]{64}", normalized_sha256):
799
+ raise ValueError(
800
+ "'base64_sha256' must be a 64-character hexadecimal SHA-256."
801
+ )
802
+ actual_sha256 = hashlib.sha256(file_data).hexdigest()
803
+ if actual_sha256 != normalized_sha256:
804
+ raise ValueError(
805
+ f"[{tool_name}] Inline binary payload failed its SHA-256 integrity check. "
806
+ "The base64 content was altered or truncated before reaching the server."
807
+ )
808
+
809
+ required_members = ZIP_CONTAINER_REQUIRED_MEMBERS.get(mime_type)
810
+ if required_members is not None:
811
+ try:
812
+ with zipfile.ZipFile(io.BytesIO(file_data)) as archive:
813
+ members = archive.infolist()
814
+ if len(members) > MAX_ZIP_MEMBER_COUNT:
815
+ raise ValueError(
816
+ f"[{tool_name}] Inline {mime_type} archive contains "
817
+ f"{len(members)} members (limit {MAX_ZIP_MEMBER_COUNT})."
818
+ )
819
+ total_uncompressed = sum(m.file_size for m in members)
820
+ if total_uncompressed > MAX_ZIP_UNCOMPRESSED_BYTES:
821
+ raise ValueError(
822
+ f"[{tool_name}] Inline {mime_type} archive uncompressed size "
823
+ f"({total_uncompressed // (1024 * 1024)} MB) exceeds the "
824
+ f"{MAX_ZIP_UNCOMPRESSED_BYTES // (1024 * 1024)} MB limit."
825
+ )
826
+ if (
827
+ len(file_data) > 0
828
+ and total_uncompressed // max(len(file_data), 1)
829
+ > MAX_ZIP_COMPRESSION_RATIO
830
+ ):
831
+ raise ValueError(
832
+ f"[{tool_name}] Inline {mime_type} archive compression ratio "
833
+ f"exceeds {MAX_ZIP_COMPRESSION_RATIO}x."
834
+ )
835
+ names = set(archive.namelist())
836
+ missing = required_members - names
837
+ if missing:
838
+ raise ValueError(
839
+ f"[{tool_name}] Inline {mime_type} payload is missing required "
840
+ f"archive members: {', '.join(sorted(missing))}."
841
+ )
842
+ corrupt_member = archive.testzip()
843
+ if corrupt_member is not None:
844
+ raise ValueError(
845
+ f"[{tool_name}] Inline {mime_type} payload contains a corrupt "
846
+ f"archive member: {corrupt_member}."
847
+ )
848
+ except ValueError:
849
+ raise
850
+ except (zipfile.BadZipFile, EOFError, RuntimeError, zlib.error) as exc:
851
+ raise ValueError(
852
+ f"[{tool_name}] Inline {mime_type} payload is not a valid, intact archive."
853
+ ) from exc
854
+
855
+ return file_data
856
+
857
+
858
+ def _use_resumable_upload(size: int) -> bool:
859
+ """Use Drive's resumable protocol only when a simple upload is too large."""
860
+ return size > UPLOAD_CHUNK_SIZE_BYTES
861
+
862
+
863
+ RESUMABLE_UPLOAD_BASE = "https://www.googleapis.com/upload/drive/v3/files"
864
+
865
+
866
+ async def initiate_resumable_upload_session(
867
+ service,
868
+ *,
869
+ upload_mime_type: str,
870
+ file_metadata: Optional[Dict[str, Any]] = None,
871
+ file_id: Optional[str] = None,
872
+ query: Optional[Dict[str, str]] = None,
873
+ ) -> str:
874
+ """Open a Drive resumable upload session and return its pre-authorized URL.
875
+
876
+ ``file_id`` absent: POST creates a new file; present: PATCH replaces that
877
+ file's content. ``file_metadata`` and ``query`` (e.g. ``addParents``) take
878
+ effect only when the upload completes. The caller PUTs the bytes to the
879
+ returned URL with no Authorization header, so the payload never passes
880
+ through this server; only this initiation call uses the user's authorized
881
+ transport.
882
+ """
883
+ path = f"/{file_id}" if file_id else ""
884
+ params = {"uploadType": "resumable", "supportsAllDrives": "true", **(query or {})}
885
+ url = f"{RESUMABLE_UPLOAD_BASE}{path}?{urlencode(params)}"
886
+ # service._http is the discovery Resource's private handle on the user's
887
+ # AuthorizedHttp. Use HttpRequest for the same bounded retry policy as other
888
+ # uploads, keeping the response headers because initiation has an empty body.
889
+ # Retrying only opens another session; no file is written until the client PUT.
890
+ request = HttpRequest(
891
+ service._http,
892
+ postproc=lambda response, content: (response, content),
893
+ uri=url,
894
+ method="PATCH" if file_id else "POST",
895
+ body=json.dumps(file_metadata or {}),
896
+ headers={
897
+ "Content-Type": "application/json; charset=UTF-8",
898
+ "X-Upload-Content-Type": upload_mime_type,
899
+ },
900
+ )
901
+ response, content = await asyncio.to_thread(
902
+ request.execute, num_retries=GOOGLE_API_WRITE_RETRIES
903
+ )
904
+ status = int(response.status)
905
+ if status not in (200, 201):
906
+ # HttpError so handle_http_errors reports it like any other Drive failure.
907
+ raise HttpError(response, content, uri=url)
908
+ upload_url = response.get("location")
909
+ if not upload_url:
910
+ raise Exception(
911
+ "Resumable upload session was created but Google returned no session URL."
912
+ )
913
+ return upload_url
914
+
915
+
916
+ def reject_sources_with_upload_url(verb: str, **sources: Any) -> None:
917
+ """Refuse return_upload_url alongside any inline or server-side source."""
918
+ given = [f"'{name}'" for name, value in sources.items() if value is not None]
919
+ if given:
920
+ raise ValueError(
921
+ f"return_upload_url {verb} via a resumable PUT; do not also pass "
922
+ f"{', '.join(given)}."
923
+ )
924
+
925
+
926
+ def validate_shortcut_request(
927
+ target_id: str, mime_type: Optional[str], **sources: Any
928
+ ) -> None:
929
+ """Refuse a shortcut create that also carries content or a non-shortcut type."""
930
+ if not target_id.strip():
931
+ raise ValueError("shortcut_target_id must be a non-empty Drive file ID.")
932
+ given = [
933
+ f"'{name}'" for name, value in sources.items() if value not in (None, False)
934
+ ]
935
+ if given:
936
+ raise ValueError(
937
+ "A shortcut has no content of its own; do not pass "
938
+ f"{', '.join(given)} with shortcut_target_id."
939
+ )
940
+ if mime_type is not None and mime_type != SHORTCUT_MIME_TYPE:
941
+ raise ValueError(
942
+ f"shortcut_target_id creates a '{SHORTCUT_MIME_TYPE}' file; omit "
943
+ f"mime_type or set it to that value, not '{mime_type}'."
944
+ )
945
+
946
+
947
+ def upload_url_not_offered_error(routes: tuple[str, ...]) -> UserInputError:
948
+ """Refuse ``return_upload_url`` while local file access is enabled.
949
+
950
+ FastMCP already rejects the hidden parameter, so this reaches only direct
951
+ callers. ``routes`` are the source parameters the calling tool has.
952
+ """
953
+ named = ", ".join(f"'{name}'" for name in routes[:-1]) + f" or '{routes[-1]}'"
954
+ return UserInputError(
955
+ "Upload URLs are offered only when local file access is disabled on this "
956
+ "server (WORKSPACE_MCP_DISABLE_LOCAL_FILES=true); pass the file via "
957
+ f"{named}."
958
+ )
959
+
960
+
961
+ def upload_url_hint(type_param: str) -> str:
962
+ """Point a refusal at ``return_upload_url``, naming the tool's ``type_param``."""
963
+ return (
964
+ "If the file is on the caller's machine, call this tool again with "
965
+ f"return_upload_url=true and {type_param}, then PUT the bytes to the URL it "
966
+ "returns."
967
+ )
968
+
969
+
970
+ def resumable_upload_result(summary: str, upload_url: str, mime_type: str) -> str:
971
+ return (
972
+ f"{summary}\n\n"
973
+ f"Upload URL (no Authorization header required):\n{upload_url}\n\n"
974
+ "Send the bytes with a single PUT, e.g.:\n"
975
+ f" curl -H 'Content-Type: {mime_type}' --upload-file \"/path/to/file\" '{upload_url}'\n\n"
976
+ "The session takes one upload; an interrupted PUT can be resumed with "
977
+ "Content-Range until Google expires the session (about a week). The file "
978
+ "is created or updated only when the upload completes, and "
979
+ "the final PUT's response body is the file's metadata (including its id)."
980
+ )
981
+
982
+
983
+ async def _stream_url_with_validation(
984
+ url: str,
985
+ write_chunk: Optional[Callable[[bytes], Awaitable[None]]] = None,
986
+ *,
987
+ upload_type_param: str,
988
+ ) -> Tuple[int, Optional[str]]:
989
+ """Stream a URL, hinting at the upload URL on a private-host refusal.
990
+
991
+ This server's own /attachments/{id} links are read from attachment storage.
992
+ """
993
+ local = resolve_local_attachment(url)
994
+ if local is not None:
995
+ file_path, metadata = local
996
+ return await _stream_file(file_path, write_chunk), metadata.get("mime_type")
997
+ try:
998
+ return await _stream_url(url, write_chunk)
999
+ except PrivateHostError as exc:
1000
+ if local_file_access_enabled():
1001
+ raise
1002
+ raise ValueError(f"{exc}. {upload_url_hint(upload_type_param)}") from exc
1003
+
1004
+
1005
+ async def _stream_file(
1006
+ path: Path, write_chunk: Optional[Callable[[bytes], Awaitable[None]]]
1007
+ ) -> int:
1008
+ """Stream a local file in download-sized chunks and return its size."""
1009
+ size_bytes = path.stat().st_size
1010
+ if size_bytes > MAX_DOWNLOAD_BYTES:
1011
+ raise ValueError(
1012
+ f"Attachment {path.name} exceeds the {MAX_DOWNLOAD_BYTES} byte limit "
1013
+ f"({size_bytes} bytes)"
1014
+ )
1015
+ total_bytes = 0
1016
+ with path.open("rb") as source:
1017
+ while chunk := await asyncio.to_thread(source.read, DOWNLOAD_CHUNK_SIZE_BYTES):
1018
+ total_bytes += len(chunk)
1019
+ if write_chunk is not None:
1020
+ await write_chunk(chunk)
1021
+ return total_bytes
1022
+
1023
+
1024
+ async def _stream_url(
1025
+ url: str, write_chunk: Optional[Callable[[bytes], Awaitable[None]]]
1026
+ ) -> Tuple[int, Optional[str]]:
1027
+ """Stream a remote file with shared status and size validation."""
1028
+ total_bytes = 0
1029
+ redacted_url = _redact_url(url)
1030
+
1031
+ async with _ssrf_safe_stream(url) as resp:
1032
+ if resp.status_code != 200:
1033
+ request = getattr(resp, "request", None)
1034
+ if request is None:
1035
+ parsed_url = urlparse(url)
1036
+ request = httpx.Request("GET", f"{parsed_url.scheme}://{redacted_url}")
1037
+ raise httpx.HTTPStatusError(
1038
+ f"Failed to fetch file from URL: {redacted_url} (status {resp.status_code})",
1039
+ request=request,
1040
+ response=resp,
1041
+ )
1042
+
1043
+ content_type = resp.headers.get("Content-Type")
1044
+ async for chunk in resp.aiter_bytes(chunk_size=DOWNLOAD_CHUNK_SIZE_BYTES):
1045
+ total_bytes += len(chunk)
1046
+ if total_bytes > MAX_DOWNLOAD_BYTES:
1047
+ raise ValueError(
1048
+ f"Download from {redacted_url} exceeded {MAX_DOWNLOAD_BYTES} byte limit "
1049
+ f"({total_bytes} bytes)"
1050
+ )
1051
+ if write_chunk is not None:
1052
+ await write_chunk(chunk)
1053
+
1054
+ return total_bytes, content_type
1055
+
1056
+
1057
+ async def _download_url_to_bytes(
1058
+ url: str, *, upload_type_param: str
1059
+ ) -> Tuple[BinaryIO, Optional[str]]:
1060
+ """Download a remote file into a spooled temporary file with bounded streaming."""
1061
+ spool = SpooledTemporaryFile(max_size=UPLOAD_CHUNK_SIZE_BYTES)
1062
+ try:
1063
+
1064
+ async def _collect(chunk: bytes) -> None:
1065
+ await asyncio.to_thread(spool.write, chunk)
1066
+
1067
+ _total_bytes, content_type = await _stream_url_with_validation(
1068
+ url, _collect, upload_type_param=upload_type_param
1069
+ )
1070
+ await asyncio.to_thread(spool.seek, 0)
1071
+ return spool, content_type
1072
+ except Exception:
1073
+ spool.close()
1074
+ raise
1075
+
1076
+
1077
+ # Bytes held in memory per streamed download chunk.
1078
+ STREAMED_DOWNLOAD_CHUNK_SIZE_BYTES = 8 * 1024 * 1024
1079
+
1080
+
1081
+ def _media_request(service, file_id: str, export_mime_type: Optional[str]):
1082
+ """Build the media request, exporting native Google types when requested."""
1083
+ return (
1084
+ service.files().export_media(fileId=file_id, mimeType=export_mime_type)
1085
+ if export_mime_type
1086
+ else service.files().get_media(fileId=file_id, supportsAllDrives=True)
1087
+ )
1088
+
1089
+
1090
+ async def _download_file_bytes(
1091
+ service, file_id: str, export_mime_type: Optional[str] = None
1092
+ ) -> bytes:
1093
+ """Download a Drive file's bytes, exporting native Google types when requested.
1094
+
1095
+ Buffers the whole file in memory. Only use this for payloads that are about
1096
+ to be parsed as text anyway; anything that ends up on disk should go through
1097
+ _download_file_to_temp instead.
1098
+ """
1099
+ return await download_media_bytes(
1100
+ _media_request(service, file_id, export_mime_type)
1101
+ )
1102
+
1103
+
1104
+ async def _download_file_to_temp(
1105
+ service, file_id: str, export_mime_type: Optional[str] = None
1106
+ ) -> Path:
1107
+ """Stream a Drive file to a temporary file and return its path.
1108
+
1109
+ Peak memory is one chunk rather than one copy of the file, so downloading a
1110
+ multi-gigabyte file no longer exhausts RAM (see #994). The caller owns the
1111
+ returned path and must move or delete it.
1112
+ """
1113
+ tmp_file = NamedTemporaryFile(prefix="wsmcp_dl_", delete=False)
1114
+ tmp_path = Path(tmp_file.name)
1115
+ loop = asyncio.get_event_loop()
1116
+ try:
1117
+ with tmp_file:
1118
+ downloader = MediaIoBaseDownload(
1119
+ tmp_file,
1120
+ _media_request(service, file_id, export_mime_type),
1121
+ chunksize=STREAMED_DOWNLOAD_CHUNK_SIZE_BYTES,
1122
+ )
1123
+ done = False
1124
+ while not done:
1125
+ _status, done = await loop.run_in_executor(None, downloader.next_chunk)
1126
+ except BaseException:
1127
+ tmp_path.unlink(missing_ok=True)
1128
+ raise
1129
+ return tmp_path
1130
+
1131
+
1132
+ # Mapping of file extensions to source MIME types for Google Docs conversion
1133
+ GOOGLE_DOCS_IMPORT_FORMATS = {
1134
+ ".md": "text/markdown",
1135
+ ".markdown": "text/markdown",
1136
+ ".txt": "text/plain",
1137
+ ".text": "text/plain",
1138
+ ".html": "text/html",
1139
+ ".htm": "text/html",
1140
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1141
+ ".doc": "application/msword",
1142
+ ".rtf": "application/rtf",
1143
+ ".odt": "application/vnd.oasis.opendocument.text",
1144
+ }
1145
+
1146
+ # Mapping of file extensions to source MIME types for Google Slides conversion
1147
+ GOOGLE_SLIDES_IMPORT_FORMATS = {
1148
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
1149
+ ".ppt": "application/vnd.ms-powerpoint",
1150
+ ".odp": "application/vnd.oasis.opendocument.presentation",
1151
+ }
1152
+
1153
+ # Mapping of file extensions to source MIME types for Google Sheets conversion
1154
+ GOOGLE_SHEETS_IMPORT_FORMATS = {
1155
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1156
+ ".xls": "application/vnd.ms-excel",
1157
+ ".ods": "application/vnd.oasis.opendocument.spreadsheet",
1158
+ ".csv": "text/csv",
1159
+ ".tsv": "text/tab-separated-values",
1160
+ }
1161
+
1162
+ GOOGLE_DOCS_MIME_TYPE = "application/vnd.google-apps.document"
1163
+ GOOGLE_SLIDES_MIME_TYPE = "application/vnd.google-apps.presentation"
1164
+ GOOGLE_SHEETS_MIME_TYPE = "application/vnd.google-apps.spreadsheet"
1165
+ GOOGLE_DRAWINGS_MIME_TYPE = "application/vnd.google-apps.drawing"
1166
+
1167
+ # Export targets for Google Drawings, keyed by export_format; PNG is the default.
1168
+ DRAWING_EXPORT_FORMATS = {
1169
+ "png": ("png", "image/png"),
1170
+ "pdf": ("pdf", "application/pdf"),
1171
+ "jpg": ("jpg", "image/jpeg"),
1172
+ "jpeg": ("jpg", "image/jpeg"),
1173
+ "svg": ("svg", "image/svg+xml"),
1174
+ }
1175
+
1176
+
1177
+ def drawing_export_target(export_format: Optional[str]) -> Tuple[str, str]:
1178
+ """(file extension, export MIME type) for a Google Drawing.
1179
+
1180
+ PNG unless export_format names another supported format.
1181
+ """
1182
+ return DRAWING_EXPORT_FORMATS.get(
1183
+ (export_format or "").lower(), DRAWING_EXPORT_FORMATS["png"]
1184
+ )
1185
+
1186
+
1187
+ IMPORT_FORMATS_BY_GOOGLE_MIME_TYPE = {
1188
+ GOOGLE_DOCS_MIME_TYPE: GOOGLE_DOCS_IMPORT_FORMATS,
1189
+ GOOGLE_SHEETS_MIME_TYPE: GOOGLE_SHEETS_IMPORT_FORMATS,
1190
+ GOOGLE_SLIDES_MIME_TYPE: GOOGLE_SLIDES_IMPORT_FORMATS,
1191
+ }
1192
+
1193
+
1194
+ def native_replace_format_map(target_mime_type: str) -> Optional[Dict[str, str]]:
1195
+ """Import allowlist for replacing a native file's content; None if not native.
1196
+
1197
+ Raises for a native Google type Drive cannot import content into.
1198
+ """
1199
+ format_map = IMPORT_FORMATS_BY_GOOGLE_MIME_TYPE.get(target_mime_type)
1200
+ if format_map is None and target_mime_type.startswith(GOOGLE_APPS_MIME_PREFIX):
1201
+ supported_targets = ", ".join(IMPORT_FORMATS_BY_GOOGLE_MIME_TYPE)
1202
+ raise ValueError(
1203
+ "Content replacement is not supported for this Google Apps type "
1204
+ f"({target_mime_type}). Editable Google types: {supported_targets}."
1205
+ )
1206
+ return format_map
1207
+
1208
+
1209
+ # Source MIME types safe to build from an in-memory `content` string. Binary
1210
+ # Office/OpenDocument formats must come from file_path/file_url; UTF-8 encoding
1211
+ # their bytes from a string would corrupt the upload and its conversion.
1212
+ TEXT_BASED_IMPORT_MIME_TYPES = {
1213
+ "text/plain",
1214
+ "text/markdown",
1215
+ "text/html",
1216
+ "text/csv",
1217
+ "text/tab-separated-values",
1218
+ "application/rtf",
1219
+ }
1220
+
1221
+
1222
+ def _is_text_like_mime_type(mime_type: str) -> bool:
1223
+ """Whether an in-memory `content` string can safely be uploaded as this MIME type."""
1224
+ return (
1225
+ mime_type.startswith("text/")
1226
+ or mime_type in TEXT_BASED_IMPORT_MIME_TYPES
1227
+ or mime_type.endswith(("+json", "+xml"))
1228
+ or mime_type in {"application/json", "application/xml"}
1229
+ )
1230
+
1231
+
1232
+ def _detect_source_format(
1233
+ file_name: str,
1234
+ content: Optional[str] = None,
1235
+ format_map: Optional[Dict[str, str]] = None,
1236
+ ) -> str:
1237
+ """
1238
+ Detect the source MIME type from a file extension.
1239
+
1240
+ Uses ``format_map`` (defaults to the Google Docs format map) and falls back to
1241
+ text/markdown for markdown-looking content, else text/plain.
1242
+ """
1243
+ if format_map is None:
1244
+ format_map = GOOGLE_DOCS_IMPORT_FORMATS
1245
+
1246
+ ext = Path(file_name).suffix.lower()
1247
+ if ext in format_map:
1248
+ return format_map[ext]
1249
+
1250
+ if content and (content.startswith("#") or "```" in content or "**" in content):
1251
+ return "text/markdown"
1252
+
1253
+ return "text/plain"
1254
+
1255
+
1256
+ async def _resolve_import_media(
1257
+ *,
1258
+ tool_name: str,
1259
+ file_name: str,
1260
+ content: Optional[str],
1261
+ file_path: Optional[str],
1262
+ file_url: Optional[str],
1263
+ source_format: Optional[str],
1264
+ base64_content: Optional[str] = None,
1265
+ base64_sha256: Optional[str] = None,
1266
+ format_map: Optional[Dict[str, str]] = None,
1267
+ passthrough_mime_type: Optional[str] = None,
1268
+ upload_type_param: str,
1269
+ ) -> Tuple[MediaIoBaseUpload, str, Optional[BinaryIO]]:
1270
+ """
1271
+ Resolve a content source into an upload ``MediaIoBaseUpload`` and source MIME type.
1272
+
1273
+ Exactly one of ``content``, ``file_path``, ``file_url``, or
1274
+ ``base64_content`` must be provided.
1275
+ The source bytes are uploaded with their *source* MIME type so the Drive API can
1276
+ convert them into the destination Google Apps format. ``format_map`` is the
1277
+ extension → source MIME allowlist used for detection and validation.
1278
+
1279
+ Pass ``passthrough_mime_type`` instead of ``format_map`` for non-Google targets
1280
+ (a raw .md, .txt, .pdf, ...): there is nothing to convert, so the bytes upload
1281
+ verbatim under that MIME type and no source allowlist applies.
1282
+
1283
+ Returns ``(media, source_mime_type, closeable)``; when the source is a remote URL,
1284
+ ``closeable`` is the download stream the caller must close after upload (else None).
1285
+ ``upload_type_param`` is the type parameter the upload-URL hint names.
1286
+ """
1287
+ # Name file_path only where the tool schema advertises it.
1288
+ path_source = "'file_path', " if local_file_access_enabled() else ""
1289
+ source_count = sum(
1290
+ 1 for x in (content, file_path, file_url, base64_content) if x is not None
1291
+ )
1292
+ if source_count == 0:
1293
+ raise ValueError(
1294
+ f"You must provide one of: 'content', {path_source}'file_url', or "
1295
+ "'base64_content'."
1296
+ )
1297
+ if source_count > 1:
1298
+ raise ValueError(
1299
+ f"Provide only one of: 'content', {path_source}'file_url', or "
1300
+ "'base64_content'."
1301
+ )
1302
+ if base64_sha256 is not None and base64_content is None:
1303
+ raise ValueError("'base64_sha256' can only be used with 'base64_content'.")
1304
+
1305
+ # Determine source MIME type from the explicit hint or auto-detection.
1306
+ if passthrough_mime_type:
1307
+ source_mime_type = passthrough_mime_type
1308
+ elif source_format:
1309
+ format_key = f".{source_format.lower().lstrip('.')}"
1310
+ if format_key not in format_map:
1311
+ raise ValueError(
1312
+ f"Unsupported source_format: '{source_format}'. "
1313
+ f"Supported: {', '.join(ext.lstrip('.') for ext in format_map.keys())}"
1314
+ )
1315
+ source_mime_type = format_map[format_key]
1316
+ else:
1317
+ detection_name = file_path or file_name
1318
+ if file_url is not None:
1319
+ detection_name = urlparse(file_url).path or file_url
1320
+ source_mime_type = _detect_source_format(detection_name, content, format_map)
1321
+
1322
+ logger.info(f"[{tool_name}] Detected source MIME type: {source_mime_type}")
1323
+
1324
+ file_data: bytes
1325
+ remote_file_data: Optional[BinaryIO] = None
1326
+
1327
+ if content is not None:
1328
+ if not _is_text_like_mime_type(source_mime_type):
1329
+ binary_sources = (
1330
+ "'file_path' or 'file_url'" if path_source else "'file_url'"
1331
+ )
1332
+ raise ValueError(
1333
+ f"[{tool_name}] 'content' is only valid for text-based source formats, "
1334
+ f"but the source resolves to '{source_mime_type}' (a binary format). "
1335
+ f"Provide {binary_sources} for binary formats instead."
1336
+ )
1337
+ file_data = content.encode("utf-8")
1338
+ logger.info(f"[{tool_name}] Using content: {len(file_data)} bytes")
1339
+
1340
+ elif base64_content is not None:
1341
+ file_data = _decode_base64_upload(
1342
+ base64_content,
1343
+ tool_name=tool_name,
1344
+ mime_type=source_mime_type,
1345
+ expected_sha256=base64_sha256,
1346
+ )
1347
+ logger.info(
1348
+ f"[{tool_name}] Decoded inline binary content: {len(file_data)} bytes"
1349
+ )
1350
+
1351
+ elif file_path is not None:
1352
+ parsed_url = urlparse(file_path)
1353
+ if parsed_url.scheme == "file":
1354
+ raw_path = parsed_url.path or ""
1355
+ netloc = parsed_url.netloc
1356
+ if netloc and netloc.lower() != "localhost":
1357
+ raw_path = f"//{netloc}{raw_path}"
1358
+ actual_path = url2pathname(raw_path)
1359
+ elif parsed_url.scheme == "":
1360
+ actual_path = file_path
1361
+ else:
1362
+ raise ValueError(
1363
+ f"file_path should be a local path or file:// URL, got: {file_path}"
1364
+ )
1365
+
1366
+ try:
1367
+ with open_validated_file(actual_path) as handle:
1368
+ file_data = await asyncio.to_thread(handle.read)
1369
+ except NotARegularFileError:
1370
+ raise ValueError(f"Path is not a file: {actual_path}") from None
1371
+ logger.info(f"[{tool_name}] Read local file: {len(file_data)} bytes")
1372
+
1373
+ # Re-detect from the real file extension when no explicit hint was given.
1374
+ if not source_format and not passthrough_mime_type:
1375
+ source_mime_type = _detect_source_format(actual_path, None, format_map)
1376
+
1377
+ else: # file_url is not None
1378
+ parsed_url = urlparse(file_url)
1379
+ if parsed_url.scheme not in ("http", "https"):
1380
+ message = f"file_url must be http:// or https://, got: {file_url}"
1381
+ if not local_file_access_enabled():
1382
+ message = f"{message}. {upload_url_hint(upload_type_param)}"
1383
+ raise ValueError(message)
1384
+
1385
+ remote_file_data, remote_content_type = await _download_url_to_bytes(
1386
+ file_url, upload_type_param=upload_type_param
1387
+ )
1388
+
1389
+ # Prefer the response Content-Type, falling back to URL-based detection.
1390
+ if not source_format and not passthrough_mime_type:
1391
+ ct_base = (remote_content_type or "").split(";", 1)[0].strip()
1392
+ if ct_base and ct_base in format_map.values():
1393
+ source_mime_type = ct_base
1394
+ else:
1395
+ source_mime_type = _detect_source_format(
1396
+ parsed_url.path or file_url, None, format_map
1397
+ )
1398
+
1399
+ # Enforce the allowlist on the final resolved MIME type so auto-detection can't
1400
+ # upload an unsupported source (e.g. text/plain from an unknown extension).
1401
+ # Passthrough uploads have no conversion target, so nothing to enforce.
1402
+ if not passthrough_mime_type and source_mime_type not in format_map.values():
1403
+ if remote_file_data is not None:
1404
+ remote_file_data.close()
1405
+ raise ValueError(
1406
+ f"[{tool_name}] Detected source MIME type '{source_mime_type}' is not "
1407
+ f"supported by this tool. Supported source formats: "
1408
+ f"{', '.join(ext.lstrip('.') for ext in sorted(format_map.keys()))}."
1409
+ )
1410
+
1411
+ upload_stream = (
1412
+ remote_file_data if remote_file_data is not None else io.BytesIO(file_data)
1413
+ )
1414
+ if remote_file_data is not None:
1415
+ current_position = remote_file_data.tell()
1416
+ remote_file_data.seek(0, io.SEEK_END)
1417
+ upload_size = remote_file_data.tell()
1418
+ remote_file_data.seek(current_position)
1419
+ else:
1420
+ upload_size = len(file_data)
1421
+
1422
+ media = MediaIoBaseUpload(
1423
+ upload_stream,
1424
+ mimetype=source_mime_type, # Source format drives Drive's auto-conversion
1425
+ resumable=_use_resumable_upload(upload_size),
1426
+ chunksize=UPLOAD_CHUNK_SIZE_BYTES,
1427
+ )
1428
+ return media, source_mime_type, remote_file_data
1429
+
1430
+
1431
+ CONTENT_UPDATE_MODES = ("replace", "append", "prepend")
1432
+ _CONTENT_UPDATE_LOCKS: WeakValueDictionary[str, asyncio.Lock] = WeakValueDictionary()
1433
+
1434
+
1435
+ def _get_content_update_lock(file_id: str) -> asyncio.Lock:
1436
+ """Return a cached lock for updates within one event loop and process.
1437
+
1438
+ This does not coordinate updates across processes, replicas, or other Drive clients.
1439
+ """
1440
+ lock = _CONTENT_UPDATE_LOCKS.get(file_id)
1441
+ if lock is None:
1442
+ lock = asyncio.Lock()
1443
+ _CONTENT_UPDATE_LOCKS[file_id] = lock
1444
+ return lock
1445
+
1446
+
1447
+ def _splice_content(existing: str, addition: str, mode: str) -> str:
1448
+ """Join new text onto existing text, guaranteeing a newline at the seam."""
1449
+ head, tail = (existing, addition) if mode == "append" else (addition, existing)
1450
+ separator = (
1451
+ "\n" if head and not head.endswith("\n") and not tail.startswith("\n") else ""
1452
+ )
1453
+ return f"{head}{separator}{tail}"
1454
+
1455
+
1456
+ # Organizer lookups share a Google API service; its HTTP transport is not thread-safe.
1457
+ SHARED_DRIVE_ORGANIZER_CONCURRENCY_LIMIT = 1
1458
+
1459
+
1460
+ async def _list_shared_drives_impl(
1461
+ service,
1462
+ user_google_email: str,
1463
+ page_size: int = 100,
1464
+ page_token: Optional[str] = None,
1465
+ query: Optional[str] = None,
1466
+ include_organizers: bool = False,
1467
+ ) -> str:
1468
+ """List shared drives available to the authenticated user."""
1469
+ logger.info(
1470
+ f"[list_shared_drives] Invoked. Email: '{user_google_email}', page_size: {page_size}, "
1471
+ f"include_organizers: {include_organizers}"
1472
+ )
1473
+
1474
+ list_params: Dict[str, Any] = {
1475
+ "pageSize": min(max(page_size, 1), 100),
1476
+ "fields": (
1477
+ "drives(id, name, createdTime, hidden, "
1478
+ "restrictions, capabilities(canManageMembers, canEdit)), "
1479
+ "nextPageToken"
1480
+ ),
1481
+ }
1482
+ if page_token:
1483
+ list_params["pageToken"] = page_token
1484
+ if query:
1485
+ list_params["q"] = query
1486
+
1487
+ results = await asyncio.to_thread(service.drives().list(**list_params).execute)
1488
+ drives = results.get("drives", [])
1489
+ if not drives:
1490
+ return f"No shared drives found for {user_google_email}."
1491
+
1492
+ if include_organizers:
1493
+
1494
+ async def _fetch_organizers(d: Dict[str, Any]) -> None:
1495
+ try:
1496
+ permissions = []
1497
+ next_permission_page_token = None
1498
+
1499
+ while True:
1500
+ list_kwargs: Dict[str, Any] = {
1501
+ "fileId": d["id"],
1502
+ "supportsAllDrives": True,
1503
+ "useDomainAdminAccess": False,
1504
+ "fields": (
1505
+ "nextPageToken, "
1506
+ "permissions(emailAddress, displayName, role, type, domain)"
1507
+ ),
1508
+ "pageSize": 100,
1509
+ }
1510
+ if next_permission_page_token:
1511
+ list_kwargs["pageToken"] = next_permission_page_token
1512
+
1513
+ perms = await asyncio.to_thread(
1514
+ service.permissions().list(**list_kwargs).execute
1515
+ )
1516
+ permissions.extend(perms.get("permissions", []))
1517
+
1518
+ next_permission_page_token = perms.get("nextPageToken")
1519
+ if not next_permission_page_token:
1520
+ break
1521
+
1522
+ d["_organizers"] = [
1523
+ p for p in permissions if p.get("role") == "organizer"
1524
+ ]
1525
+ except HttpError as e:
1526
+ status = getattr(e, "status_code", None)
1527
+ if status is None and getattr(e, "resp", None) is not None:
1528
+ status = getattr(e.resp, "status", None)
1529
+ reason = getattr(e, "reason", None) or str(e)
1530
+ d["_organizers_error"] = f"{status or 'unknown'}: {reason}"
1531
+
1532
+ organizer_fetch_sem = asyncio.Semaphore(
1533
+ SHARED_DRIVE_ORGANIZER_CONCURRENCY_LIMIT
1534
+ )
1535
+
1536
+ async def _bounded_fetch_organizers(d: Dict[str, Any]) -> None:
1537
+ async with organizer_fetch_sem:
1538
+ await _fetch_organizers(d)
1539
+
1540
+ await asyncio.gather(*[_bounded_fetch_organizers(d) for d in drives])
1541
+
1542
+ next_token = results.get("nextPageToken")
1543
+ parts = [f"Found {len(drives)} shared drives for {user_google_email}:"]
1544
+ for d in drives:
1545
+ caps = d.get("capabilities") or {}
1546
+ rest = d.get("restrictions") or {}
1547
+ cap_flags = ", ".join(k for k, v in caps.items() if v) or "none"
1548
+ rest_flags = ", ".join(k for k, v in rest.items() if v) or "none"
1549
+ hidden = " [hidden]" if d.get("hidden") else ""
1550
+ parts.append(
1551
+ f'- Name: "{d["name"]}" (ID: {d["id"]}, Created: {d.get("createdTime", "N/A")}){hidden} '
1552
+ f"Capabilities: {cap_flags}; Restrictions: {rest_flags}"
1553
+ )
1554
+ if include_organizers:
1555
+ err = d.get("_organizers_error")
1556
+ if err:
1557
+ parts.append(f" Organizers: <error: {err}>")
1558
+ else:
1559
+ organizers = d.get("_organizers", [])
1560
+ if not organizers:
1561
+ parts.append(" Organizers: <none returned>")
1562
+ else:
1563
+ for o in organizers:
1564
+ identifier = (
1565
+ o.get("emailAddress")
1566
+ or o.get("domain")
1567
+ or o.get("displayName")
1568
+ or o.get("type", "?")
1569
+ )
1570
+ display = o.get("displayName")
1571
+ kind = o.get("type", "?")
1572
+ suffix = (
1573
+ f' ("{display}")'
1574
+ if display and display != identifier
1575
+ else ""
1576
+ )
1577
+ parts.append(f" Organizer ({kind}): {identifier}{suffix}")
1578
+ if next_token:
1579
+ parts.append(f"nextPageToken: {next_token}")
1580
+ return "\n".join(parts)
1581
+
1582
+
1583
+ async def _import_with_conversion(
1584
+ service,
1585
+ *,
1586
+ tool_name: str,
1587
+ target_label: str,
1588
+ id_label: str,
1589
+ target_mime_type: str,
1590
+ format_map: Dict[str, str],
1591
+ user_google_email: str,
1592
+ file_name: str,
1593
+ content: Optional[str],
1594
+ file_path: Optional[str],
1595
+ file_url: Optional[str],
1596
+ source_format: Optional[str],
1597
+ folder_id: str,
1598
+ base64_content: Optional[str],
1599
+ base64_sha256: Optional[str],
1600
+ inline_params: tuple[str, ...] = ("content", "base64_content"),
1601
+ return_upload_url: bool = False,
1602
+ ) -> str:
1603
+ """
1604
+ Shared implementation for the import_to_google_* tools.
1605
+
1606
+ Uploads source bytes (from content, a local file, or a remote URL) as media
1607
+ while ``body.mimeType`` is the Google Apps ``target_mime_type``, letting Drive
1608
+ auto-convert the Office/OpenDocument/text source into native Google format.
1609
+
1610
+ Args:
1611
+ tool_name: Logging prefix and the tool's registered name (for messages).
1612
+ target_label: Human-readable destination name (e.g. "Google Doc").
1613
+ id_label: Label for the created file's ID in the confirmation message.
1614
+ target_mime_type: The ``application/vnd.google-apps.*`` destination type.
1615
+ format_map: Extension -> source MIME type allowlist for this destination.
1616
+ inline_params: The inline-source parameters the calling tool exposes
1617
+ (Slides takes binary formats only, so it has no ``content``), so the
1618
+ return_upload_url refusal names only routes that exist on that tool.
1619
+ return_upload_url: Open a resumable upload session and return its URL
1620
+ instead of uploading a source from this server.
1621
+ """
1622
+ logger.info(
1623
+ f"[{tool_name}] Invoked. Email: '{user_google_email}', "
1624
+ f"file_name_len={len(file_name) if file_name else 0}, "
1625
+ f"Source Format: '{source_format}', Folder ID: '{folder_id}'"
1626
+ )
1627
+ logger.debug(f"[{tool_name}] File Name: '{file_name}'")
1628
+
1629
+ if return_upload_url:
1630
+ if local_file_access_enabled():
1631
+ raise upload_url_not_offered_error(("file_path", *inline_params))
1632
+ reject_sources_with_upload_url(
1633
+ "uploads the source",
1634
+ content=content,
1635
+ file_path=file_path,
1636
+ file_url=file_url,
1637
+ base64_content=base64_content,
1638
+ base64_sha256=base64_sha256,
1639
+ )
1640
+ supported = ", ".join(ext.lstrip(".") for ext in format_map)
1641
+ if not source_format:
1642
+ raise ValueError(
1643
+ "source_format is required with return_upload_url so the upload's "
1644
+ f"Content-Type is known (one of: {supported})."
1645
+ )
1646
+ source_mime_type = format_map.get(f".{source_format.lower().lstrip('.')}")
1647
+ if source_mime_type is None:
1648
+ raise ValueError(
1649
+ f"Unsupported source_format: '{source_format}'. Supported: {supported}."
1650
+ )
1651
+ doc_name = Path(file_name).stem if Path(file_name).suffix else file_name
1652
+ # body.mimeType is the Google Apps target; the PUT carries the source type,
1653
+ # so Drive converts exactly as it does for an inline import.
1654
+ upload_url = await initiate_resumable_upload_session(
1655
+ service,
1656
+ upload_mime_type=source_mime_type,
1657
+ file_metadata={
1658
+ "name": doc_name,
1659
+ "parents": [await resolve_folder_id(service, folder_id)],
1660
+ "mimeType": target_mime_type,
1661
+ },
1662
+ )
1663
+ logger.info(f"[{tool_name}] Returned resumable upload URL.")
1664
+ return resumable_upload_result(
1665
+ f"Resumable upload session created to import '{doc_name}' as {target_label} "
1666
+ f"({source_mime_type} → {target_mime_type}, folder '{folder_id}', "
1667
+ f"for {user_google_email}).",
1668
+ upload_url,
1669
+ source_mime_type,
1670
+ )
1671
+
1672
+ media, source_mime_type, remote_file_data = await _resolve_import_media(
1673
+ tool_name=tool_name,
1674
+ file_name=file_name,
1675
+ content=content,
1676
+ file_path=file_path,
1677
+ file_url=file_url,
1678
+ source_format=source_format,
1679
+ base64_content=base64_content,
1680
+ base64_sha256=base64_sha256,
1681
+ format_map=format_map,
1682
+ upload_type_param="source_format",
1683
+ )
1684
+
1685
+ # Clean up file name (remove extension since it becomes a Google Apps file)
1686
+ doc_name = Path(file_name).stem if Path(file_name).suffix else file_name
1687
+
1688
+ # Resolve folder
1689
+ resolved_folder_id = await resolve_folder_id(service, folder_id)
1690
+
1691
+ # File metadata - destination is the Google Apps target format
1692
+ file_metadata = {
1693
+ "name": doc_name,
1694
+ "parents": [resolved_folder_id],
1695
+ "mimeType": target_mime_type, # Target format = Google Apps type
1696
+ }
1697
+
1698
+ # Upload with conversion
1699
+ logger.info(
1700
+ f"[{tool_name}] Uploading to Google Drive with conversion: "
1701
+ f"{source_mime_type} → {target_mime_type}"
1702
+ )
1703
+ try:
1704
+ created_file = await asyncio.to_thread(
1705
+ service.files()
1706
+ .create(
1707
+ body=file_metadata,
1708
+ media_body=media,
1709
+ fields="id, name, webViewLink, mimeType",
1710
+ supportsAllDrives=True,
1711
+ )
1712
+ .execute,
1713
+ num_retries=GOOGLE_API_WRITE_RETRIES,
1714
+ )
1715
+ finally:
1716
+ if remote_file_data is not None:
1717
+ remote_file_data.close()
1718
+
1719
+ result_mime = created_file.get("mimeType", "unknown")
1720
+ if result_mime != target_mime_type:
1721
+ logger.warning(
1722
+ f"[{tool_name}] Conversion may have failed. "
1723
+ f"Expected {target_mime_type}, got {result_mime}"
1724
+ )
1725
+
1726
+ link = created_file.get("webViewLink", "No link available")
1727
+ doc_id = created_file.get("id", "N/A")
1728
+
1729
+ confirmation = (
1730
+ f"✅ Successfully imported '{doc_name}' as {target_label}\n"
1731
+ f" {id_label}: {doc_id}\n"
1732
+ f" Source format: {source_mime_type}\n"
1733
+ f" Folder: {folder_id}\n"
1734
+ f" Link: {link}"
1735
+ )
1736
+
1737
+ logger.info(f"[{tool_name}] Success. Link: {link}")
1738
+ return confirmation