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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -2
  3. package/README.npm.md +34 -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,3085 @@
1
+ """
2
+ Google Drive MCP Tools
3
+
4
+ This module provides MCP tools for interacting with Google Drive API.
5
+ """
6
+
7
+ import asyncio
8
+ import base64
9
+ import logging
10
+ import io
11
+
12
+ from typing import Optional, List, Dict, Any
13
+ from tempfile import NamedTemporaryFile, SpooledTemporaryFile
14
+ from urllib.parse import quote, urlparse
15
+ from urllib.request import url2pathname
16
+ from pathlib import Path
17
+
18
+ from googleapiclient.errors import HttpError
19
+ from googleapiclient.http import MediaIoBaseUpload
20
+
21
+ from fastmcp.tools import ToolResult
22
+ from mcp.types import (
23
+ BlobResourceContents,
24
+ EmbeddedResource,
25
+ ImageContent,
26
+ TextContent,
27
+ ToolAnnotations,
28
+ )
29
+
30
+ from auth.service_decorator import require_google_service
31
+ from auth.oauth_config import is_stateless_mode
32
+ from core.attachment_storage import get_attachment_storage, get_attachment_url
33
+ from core.file_limits import (
34
+ FileTooLargeError,
35
+ PagedContentCache,
36
+ download_media_bytes,
37
+ ensure_within_file_size_limit,
38
+ get_max_content_chars,
39
+ get_paged_content_cache_bytes,
40
+ get_stateless_inline_max_bytes,
41
+ page_content_text,
42
+ )
43
+ from core.gcs_attachment_storage import gcs_files_enabled
44
+ from core.utils import (
45
+ GOOGLE_API_WRITE_RETRIES,
46
+ IMAGE_MIME_TYPES,
47
+ INLINE_IMAGE_MIME_TYPES,
48
+ SVG_MIME_TYPE,
49
+ hide_local_file_args,
50
+ hide_remote_only_args,
51
+ local_file_access_enabled,
52
+ encode_image_content,
53
+ image_content_from_bytes,
54
+ sniff_inline_image_mime_type,
55
+ svg_content,
56
+ OfficeXmlExtractionError,
57
+ NotARegularFileError,
58
+ OfficeXmlTooLargeError,
59
+ UserInputError,
60
+ extract_office_xml_text,
61
+ extract_pdf_text,
62
+ handle_http_errors,
63
+ open_validated_file,
64
+ )
65
+ from core.server import server
66
+ from core.telemetry import record_degraded_failure
67
+ from core.config import get_transport_mode
68
+ from gdrive.drive_helpers import (
69
+ DRIVE_QUERY_PATTERNS,
70
+ FOLDER_MIME_TYPE,
71
+ GOOGLE_APPS_MIME_PREFIX,
72
+ GOOGLE_DOCS_IMPORT_FORMATS,
73
+ GOOGLE_DOCS_MIME_TYPE,
74
+ GOOGLE_DRAWINGS_MIME_TYPE,
75
+ GOOGLE_SHEETS_IMPORT_FORMATS,
76
+ GOOGLE_SHEETS_MIME_TYPE,
77
+ GOOGLE_SLIDES_IMPORT_FORMATS,
78
+ GOOGLE_SLIDES_MIME_TYPE,
79
+ CONTENT_UPDATE_MODES,
80
+ SHORTCUT_MIME_TYPE,
81
+ UPLOAD_CHUNK_SIZE_BYTES,
82
+ _create_drive_folder_impl,
83
+ _create_drive_shortcut_impl,
84
+ _decode_base64_upload,
85
+ _download_file_bytes,
86
+ _download_file_to_temp,
87
+ _get_content_update_lock,
88
+ _import_with_conversion,
89
+ _list_shared_drives_impl,
90
+ _media_request,
91
+ _resolve_import_media,
92
+ _splice_content,
93
+ _stream_url_with_validation,
94
+ _use_resumable_upload,
95
+ build_drive_list_params,
96
+ check_public_link_permission,
97
+ flag_incomplete_search,
98
+ list_all_permissions,
99
+ derive_shared_state,
100
+ drawing_export_target,
101
+ escape_drive_query_value,
102
+ format_permission_info,
103
+ get_drive_image_url,
104
+ has_explicit_trashed_clause,
105
+ initiate_resumable_upload_session,
106
+ native_replace_format_map,
107
+ normalize_drive_query_v2_compat,
108
+ reject_sources_with_upload_url,
109
+ resolve_drive_item,
110
+ resolve_file_type_mime,
111
+ resolve_folder_id,
112
+ resumable_upload_result,
113
+ upload_url_hint,
114
+ upload_url_not_offered_error,
115
+ validate_expiration_time,
116
+ validate_share_role,
117
+ validate_share_type,
118
+ validate_shortcut_request,
119
+ )
120
+
121
+ logger = logging.getLogger(__name__)
122
+
123
+ _paged_content_cache = PagedContentCache(ttl_seconds=600)
124
+
125
+
126
+ def _stateless_too_large_message(
127
+ file_name: str, file_id: str, size_bytes: int, mime_type: str, limit: int
128
+ ) -> str:
129
+ """Explain why a stateless-mode download was not returned inline."""
130
+ return "\n".join(
131
+ [
132
+ f"File: {file_name}",
133
+ f"File ID: {file_id}",
134
+ f"Size: {size_bytes / 1024:.1f} KB ({size_bytes} bytes)",
135
+ f"MIME Type: {mime_type}",
136
+ "",
137
+ "Not returned: stateless mode has no file storage, and this file "
138
+ f"exceeds the inline limit of {limit} bytes "
139
+ "(WORKSPACE_MCP_STATELESS_INLINE_MAX_BYTES, or "
140
+ "WORKSPACE_MCP_MAX_FILE_BYTES if lower). Use "
141
+ "get_drive_file_content for its text, or raise the limit.",
142
+ ]
143
+ )
144
+
145
+
146
+ def _stateless_inline_disabled_message(
147
+ file_name: str, file_id: str, mime_type: str
148
+ ) -> str:
149
+ """Explain that stateless-mode downloads are not returned inline at all."""
150
+ return "\n".join(
151
+ [
152
+ f"File: {file_name}",
153
+ f"File ID: {file_id}",
154
+ f"MIME Type: {mime_type}",
155
+ "",
156
+ "Not returned: stateless mode has no file storage, and inline "
157
+ "returns are disabled (WORKSPACE_MCP_STATELESS_INLINE_MAX_BYTES=0). "
158
+ "Use get_drive_file_content for its text, or raise the limit.",
159
+ ]
160
+ )
161
+
162
+
163
+ @server.tool(
164
+ title="Search Drive Files",
165
+ annotations=ToolAnnotations(
166
+ readOnlyHint=True,
167
+ destructiveHint=False,
168
+ idempotentHint=True,
169
+ openWorldHint=True,
170
+ ),
171
+ )
172
+ @handle_http_errors("search_drive_files", is_read_only=True, service_type="drive")
173
+ @require_google_service("drive", "drive_read")
174
+ async def search_drive_files(
175
+ service,
176
+ user_google_email: str,
177
+ query: str,
178
+ page_size: int = 10,
179
+ page_token: Optional[str] = None,
180
+ drive_id: Optional[str] = None,
181
+ include_items_from_all_drives: bool = True,
182
+ corpora: Optional[str] = None,
183
+ file_type: Optional[str] = None,
184
+ detailed: bool = True,
185
+ order_by: Optional[str] = None,
186
+ include_trashed: bool = False,
187
+ ) -> str:
188
+ """
189
+ Searches for files and folders within a user's Google Drive, including shared drives.
190
+
191
+ Args:
192
+ user_google_email (str): The user's Google email address. Required.
193
+ query (str): The search query string. Supports Google Drive search operators.
194
+ NOTE: Owner-based queries ('user@example.com' in owners) DO NOT WORK in Shared Drives
195
+ because files are owned by the shared drive itself, not individual users.
196
+ For recent files by a specific user in Shared Drives, search by modifiedTime
197
+ and use order_by='modifiedTime desc' instead.
198
+ page_size (int): The maximum number of files to return. Defaults to 10.
199
+ page_token (Optional[str]): Page token from a previous response's nextPageToken to retrieve the next page of results.
200
+ drive_id (Optional[str]): ID of the shared drive to search. If None, behavior depends on `corpora` and `include_items_from_all_drives`.
201
+ include_items_from_all_drives (bool): Whether shared drive items should be included in results. Defaults to True. This is effective when not specifying a `drive_id`.
202
+ corpora (Optional[str]): Bodies of items to query (e.g., 'user', 'domain', 'drive', 'allDrives').
203
+ If 'drive_id' is specified and 'corpora' is None, it defaults to 'drive'.
204
+ Otherwise it defaults to 'allDrives' when `include_items_from_all_drives` is True.
205
+ Pass 'user' to search only My Drive and files shared with the user.
206
+ file_type (Optional[str]): Restrict results to a specific file type. Accepts a friendly
207
+ name ('folder', 'document'/'doc', 'spreadsheet'/'sheet',
208
+ 'presentation'/'slides', 'form', 'drawing', 'pdf', 'shortcut',
209
+ 'script', 'site', 'jam'/'jamboard') or any raw MIME type
210
+ string (e.g. 'application/pdf'). Defaults to None (all types).
211
+ detailed (bool): Whether to include size, modified time, and link in results. Defaults to True.
212
+ order_by (Optional[str]): Sort order. Comma-separated list of sort keys with optional 'desc' modifier.
213
+ Valid keys: 'createdTime', 'folder', 'modifiedByMeTime', 'modifiedTime',
214
+ 'name', 'name_natural', 'quotaBytesUsed', 'recency', 'sharedWithMeTime',
215
+ 'starred', 'viewedByMeTime'. Example: 'modifiedTime desc' or 'folder,modifiedTime desc,name'.
216
+ Defaults to None (Drive API default ordering).
217
+ include_trashed (bool): Whether to include files in the trash. Defaults to False, matching
218
+ the Drive web UI and `list_drive_items`. Ignored when `query` already
219
+ contains its own `trashed` clause (`=` or `!=`), which always wins.
220
+
221
+ Returns:
222
+ str: A formatted list of found files/folders with their details (ID, name, type, and optionally size, modified time, link).
223
+ Includes a nextPageToken line when more results are available.
224
+ """
225
+ logger.info(
226
+ f"[search_drive_files] Invoked. Email: '{user_google_email}', query_len={len(query)}, "
227
+ f"file_type: '{file_type}', include_trashed: {include_trashed}"
228
+ )
229
+
230
+ # Check if the query looks like a structured Drive query or free text
231
+ # Look for Drive API operators and structured query patterns
232
+ is_structured_query = any(pattern.search(query) for pattern in DRIVE_QUERY_PATTERNS)
233
+
234
+ if is_structured_query:
235
+ final_query = normalize_drive_query_v2_compat(query)
236
+ if final_query != query:
237
+ logger.info(
238
+ "[search_drive_files] Normalized v2 query field names to v3 equivalents"
239
+ )
240
+ logger.debug(f"[search_drive_files] Using structured query: '{final_query}'")
241
+ else:
242
+ # For free text queries, wrap in fullText contains
243
+ escaped_query = escape_drive_query_value(query)
244
+ final_query = f"fullText contains '{escaped_query}'"
245
+ logger.debug(
246
+ f"[search_drive_files] Reformatting free text query '{query}' to '{final_query}'"
247
+ )
248
+
249
+ # Drive's files.list returns trashed items unless told otherwise. Hide them by
250
+ # default so search agrees with list_drive_items and the Drive web UI, but never
251
+ # override an explicit trashed clause the caller wrote themselves.
252
+ if not include_trashed and not has_explicit_trashed_clause(final_query):
253
+ final_query = f"({final_query}) and trashed=false"
254
+ logger.info(
255
+ "[search_drive_files] Excluding trashed items (include_trashed=False)"
256
+ )
257
+
258
+ if file_type is not None:
259
+ mime = resolve_file_type_mime(file_type)
260
+ final_query = f"({final_query}) and mimeType = '{mime}'"
261
+ logger.info(f"[search_drive_files] Added mimeType filter: '{mime}'")
262
+
263
+ list_params = build_drive_list_params(
264
+ query=final_query,
265
+ page_size=page_size,
266
+ drive_id=drive_id,
267
+ include_items_from_all_drives=include_items_from_all_drives,
268
+ corpora=corpora,
269
+ page_token=page_token,
270
+ detailed=detailed,
271
+ include_permissions=detailed,
272
+ order_by=order_by,
273
+ )
274
+
275
+ results = await asyncio.to_thread(service.files().list(**list_params).execute)
276
+ files = results.get("files", [])
277
+ next_token = results.get("nextPageToken")
278
+ if not files and not next_token:
279
+ return flag_incomplete_search(f"No files found for '{query}'.", results)
280
+
281
+ header = f"Found {len(files)} files for {user_google_email} matching '{query}':"
282
+ formatted_files_text_parts = [header]
283
+ for item in files:
284
+ if detailed:
285
+ size_str = f", Size: {item.get('size', 'N/A')}" if "size" in item else ""
286
+ created_str = (
287
+ f", Created: {item['createdTime']}" if item.get("createdTime") else ""
288
+ )
289
+ # Last modifying user (not available for all files)
290
+ lmu = item.get("lastModifyingUser")
291
+ if lmu:
292
+ lmu_name = lmu.get("displayName", "")
293
+ lmu_email = lmu.get("emailAddress", "")
294
+ if lmu_name and lmu_email:
295
+ last_edited_by_str = f", Last Edited By: {lmu_name} <{lmu_email}>"
296
+ elif lmu_name:
297
+ last_edited_by_str = f", Last Edited By: {lmu_name}"
298
+ elif lmu_email:
299
+ last_edited_by_str = f", Last Edited By: {lmu_email}"
300
+ else:
301
+ last_edited_by_str = ""
302
+ else:
303
+ last_edited_by_str = ""
304
+ # Anyone-with-link permission role (reader/commenter/writer)
305
+ anyone_role_str = ""
306
+ for perm in item.get("permissions", []):
307
+ if perm.get("type") == "anyone":
308
+ anyone_role_str = (
309
+ f", Anyone with link: {perm.get('role', 'unknown')}"
310
+ )
311
+ break
312
+ # TODO: "Created By" (original file creator) is not included here.
313
+ # For Shared Drive files the `owners` field is always empty — the drive
314
+ # owns the file. True creator attribution requires fetching revision 1
315
+ # via files/{id}/revisions and reading its lastModifyingUser. That adds
316
+ # one API call per file and should be a separate follow-up.
317
+ formatted_files_text_parts.append(
318
+ f'- Name: "{item["name"]}" (ID: {item["id"]}, Type: {item["mimeType"]}{size_str}'
319
+ f"{created_str}, Modified: {item.get('modifiedTime', 'N/A')}"
320
+ f"{last_edited_by_str}{anyone_role_str})"
321
+ f" Link: {item.get('webViewLink', '#')}"
322
+ )
323
+ else:
324
+ formatted_files_text_parts.append(
325
+ f'- Name: "{item["name"]}" (ID: {item["id"]}, Type: {item["mimeType"]})'
326
+ )
327
+ if next_token:
328
+ formatted_files_text_parts.append(f"nextPageToken: {next_token}")
329
+ return flag_incomplete_search("\n".join(formatted_files_text_parts), results)
330
+
331
+
332
+ async def _read_drive_file_body(
333
+ service,
334
+ file_id: str,
335
+ file_metadata: Dict[str, Any],
336
+ export_mime_type: Optional[str],
337
+ max_chars: Optional[int],
338
+ ) -> tuple[str, List[ImageContent], bool]:
339
+ """Download and extract a Drive file; return its text, attached images, and
340
+ whether the text is pageable. Raises FileTooLargeError over a size limit."""
341
+ mime_type = file_metadata.get("mimeType", "")
342
+ file_name = file_metadata.get("name", "Unknown File")
343
+ web_view_link = file_metadata.get("webViewLink", "#")
344
+
345
+ # Declared Drive size is only meaningful for binary downloads (not exports).
346
+ if not export_mime_type:
347
+ ensure_within_file_size_limit(
348
+ file_metadata.get("size"),
349
+ file_name=file_name,
350
+ file_id=file_id,
351
+ web_view_link=web_view_link,
352
+ )
353
+
354
+ request_obj = _media_request(service, file_id, export_mime_type)
355
+ file_content_bytes = await download_media_bytes(
356
+ request_obj,
357
+ file_name=file_name,
358
+ file_id=file_id,
359
+ web_view_link=web_view_link,
360
+ )
361
+
362
+ # Attempt Office XML extraction only for actual Office XML files
363
+ office_mime_types = {
364
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
365
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
366
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
367
+ }
368
+
369
+ images: List[ImageContent] = []
370
+ paged = True
371
+ if mime_type in office_mime_types:
372
+ # Offload Office XML extraction to a thread to avoid blocking the event loop
373
+ try:
374
+ office_text = await asyncio.to_thread(
375
+ extract_office_xml_text, file_content_bytes, mime_type
376
+ )
377
+ except OfficeXmlTooLargeError as e:
378
+ # Not damaged, and not to be retried as raw text: say what happened.
379
+ office_text = f"[Could not read '{mime_type}' file - {e}]"
380
+ except OfficeXmlExtractionError as e:
381
+ office_text = (
382
+ f"[Could not read '{mime_type}' file - it appears damaged or is "
383
+ f"not a valid Office document: {e}]"
384
+ )
385
+ if office_text:
386
+ body_text = office_text
387
+ else:
388
+ # Fallback: try UTF-8; otherwise flag binary
389
+ try:
390
+ body_text = file_content_bytes.decode("utf-8")
391
+ except UnicodeDecodeError:
392
+ body_text = (
393
+ f"[Binary or unsupported text encoding for mimeType '{mime_type}' - "
394
+ f"{len(file_content_bytes)} bytes]"
395
+ )
396
+ elif mime_type == "application/pdf":
397
+ # Offload PDF text extraction to a thread to avoid blocking the event loop
398
+ pdf_text = await asyncio.to_thread(extract_pdf_text, file_content_bytes)
399
+ if pdf_text:
400
+ body_text = pdf_text
401
+ else:
402
+ body_text = (
403
+ f"[Could not extract text from PDF ({len(file_content_bytes)} bytes) "
404
+ f"- the file may be scanned/image-only. "
405
+ f"Use get_drive_file_download_url to get a direct download link instead.]"
406
+ )
407
+ elif mime_type in INLINE_IMAGE_MIME_TYPES and (
408
+ inline_mime_type := sniff_inline_image_mime_type(file_content_bytes)
409
+ ):
410
+ images.append(image_content_from_bytes(file_content_bytes, inline_mime_type))
411
+ body_text = (
412
+ f"[Image attached as image content - {len(file_content_bytes)} bytes]"
413
+ )
414
+ paged = False
415
+ elif mime_type == SVG_MIME_TYPE:
416
+ svg = svg_content(file_content_bytes)
417
+ if svg is not None:
418
+ body_text = svg.markup
419
+ images.extend(svg.images)
420
+ else:
421
+ body_text = (
422
+ f"[SVG is not UTF-8 text (it may be a compressed .svgz) - "
423
+ f"{len(file_content_bytes)} bytes. "
424
+ f"Use get_drive_file_download_url to get the file instead.]"
425
+ )
426
+ elif mime_type in IMAGE_MIME_TYPES:
427
+ body_text = encode_image_content(file_content_bytes, mime_type)
428
+ paged = False
429
+ if max_chars is not None and len(body_text) > max_chars:
430
+ body_text = (
431
+ f"[Image is {len(file_content_bytes):,} bytes, {len(body_text):,} "
432
+ f"characters as base64, over the default page size of "
433
+ f"{max_chars:,} (set by WORKSPACE_MCP_MAX_CONTENT_CHARS). Pass "
434
+ f"full_content=True to get it anyway, or use "
435
+ f"get_drive_file_download_url to get the file instead.]"
436
+ )
437
+ else:
438
+ # For non-Office files (including Google native files), try UTF-8 decode directly
439
+ try:
440
+ body_text = file_content_bytes.decode("utf-8")
441
+ except UnicodeDecodeError:
442
+ body_text = (
443
+ f"[Binary or unsupported text encoding for mimeType '{mime_type}' - "
444
+ f"{len(file_content_bytes)} bytes]"
445
+ )
446
+
447
+ return body_text, images, paged
448
+
449
+
450
+ @server.tool(
451
+ title="Get Drive File Content",
452
+ annotations=ToolAnnotations(
453
+ readOnlyHint=True,
454
+ destructiveHint=False,
455
+ idempotentHint=True,
456
+ openWorldHint=True,
457
+ ),
458
+ )
459
+ @handle_http_errors("get_drive_file_content", is_read_only=True, service_type="drive")
460
+ @require_google_service("drive", "drive_read")
461
+ async def get_drive_file_content(
462
+ service,
463
+ user_google_email: str,
464
+ file_id: str,
465
+ offset: int = 0,
466
+ full_content: bool = False,
467
+ ) -> str:
468
+ """
469
+ Retrieves the content of a specific Google Drive file by ID, supporting files in shared drives.
470
+
471
+ • Native Google Docs, Sheets, Slides → exported as text / CSV.
472
+ • Office files (.docx, .xlsx, .pptx) → unzipped & parsed with std-lib to
473
+ extract readable text.
474
+ • PDFs → text extracted with pypdf when possible; scanned/image-only PDFs
475
+ fall back to a download hint.
476
+ • Images (PNG, JPEG, GIF, WebP) → returned as MCP image content after the
477
+ metadata header. SVG → returned as its markup; raster images it embeds
478
+ as base64 are attached as image content, numbered to match their place
479
+ in the markup. BMP and TIFF → base64 text, or a download hint when over
480
+ the default page size.
481
+ • Any other file → downloaded; tries UTF-8 decode, else notes binary.
482
+
483
+ Args:
484
+ user_google_email: The user’s Google email address.
485
+ file_id: Drive file ID.
486
+ offset: Character offset to read on from after a truncated result.
487
+ full_content: Return all content from offset onward in one call
488
+ instead of a page of the default size.
489
+
490
+ Returns:
491
+ str: The file content as plain text with a metadata header that carries
492
+ the file's version, so a reader paging by offset can tell when it
493
+ changed and restart from offset=0. For images, a ToolResult with that
494
+ text followed by the image as image content.
495
+ """
496
+ logger.info(f"[get_drive_file_content] Invoked. File ID: '{file_id}'")
497
+ if offset < 0:
498
+ raise UserInputError(f"offset must be >= 0, got {offset}.")
499
+
500
+ resolved_file_id, file_metadata = await resolve_drive_item(
501
+ service,
502
+ file_id,
503
+ extra_fields="name, webViewLink, size, version, capabilities(canDownload)",
504
+ )
505
+ file_id = resolved_file_id
506
+ mime_type = file_metadata.get("mimeType", "")
507
+ file_name = file_metadata.get("name", "Unknown File")
508
+ web_view_link = file_metadata.get("webViewLink", "#")
509
+ export_mime_type = {
510
+ "application/vnd.google-apps.document": "text/plain",
511
+ "application/vnd.google-apps.spreadsheet": "text/csv",
512
+ "application/vnd.google-apps.presentation": "text/plain",
513
+ }.get(mime_type)
514
+
515
+ max_chars = None if full_content else get_max_content_chars()
516
+ version = file_metadata.get("version")
517
+ # Policy and DLP download restrictions can change without a new version.
518
+ can_download = (file_metadata.get("capabilities") or {}).get("canDownload")
519
+ cache_bytes = get_paged_content_cache_bytes()
520
+ cache_key = (
521
+ (user_google_email.lower(), file_id, version, export_mime_type)
522
+ if cache_bytes
523
+ and user_google_email
524
+ and version is not None
525
+ and can_download is True
526
+ and not is_stateless_mode()
527
+ else None
528
+ )
529
+ cached = _paged_content_cache.get(cache_key) if cache_key and offset else None
530
+ if cached is not None:
531
+ logger.debug(
532
+ "[get_drive_file_content] Reading on from kept text of %s", file_id
533
+ )
534
+ body_text, images, paged = cached, [], True
535
+ else:
536
+ try:
537
+ body_text, images, paged = await _read_drive_file_body(
538
+ service, file_id, file_metadata, export_mime_type, max_chars
539
+ )
540
+ except FileTooLargeError as e:
541
+ return str(e)
542
+ truncated = max_chars is not None and len(body_text) > max_chars
543
+ if paged and (truncated or offset) and version is not None:
544
+ current = await asyncio.to_thread(
545
+ service.files()
546
+ .get(fileId=file_id, fields="version", supportsAllDrives=True)
547
+ .execute
548
+ )
549
+ if current.get("version") != version:
550
+ return (
551
+ f'File "{file_name}" (ID: {file_id}) changed while it was '
552
+ f"being read. Call again with offset=0 to read the current "
553
+ f"version from the start."
554
+ )
555
+ if cache_key and paged and truncated:
556
+ _paged_content_cache.put(cache_key, body_text, max_bytes=cache_bytes)
557
+
558
+ if paged:
559
+ body_text = page_content_text(
560
+ body_text,
561
+ offset=offset,
562
+ max_chars=max_chars,
563
+ alternative=", or pass full_content=True for the whole file",
564
+ )
565
+ if offset:
566
+ images = []
567
+
568
+ # Assemble response
569
+ version_text = f", Version: {version}" if version is not None else ""
570
+ header = (
571
+ f'File: "{file_name}" (ID: {file_id}, Type: {mime_type}{version_text})\n'
572
+ f"Link: {web_view_link}\n\n--- CONTENT ---\n"
573
+ )
574
+ if images:
575
+ # structured_content mirrors the plain-string result so clients that
576
+ # validate against the tool's output schema still get a string.
577
+ text = header + body_text
578
+ return ToolResult(
579
+ content=[TextContent(type="text", text=text), *images],
580
+ structured_content={"result": text},
581
+ )
582
+ return header + body_text
583
+
584
+
585
+ @server.tool(
586
+ title="Get Drive File Download URL",
587
+ annotations=ToolAnnotations(
588
+ readOnlyHint=True,
589
+ destructiveHint=False,
590
+ idempotentHint=True,
591
+ openWorldHint=True,
592
+ ),
593
+ )
594
+ @handle_http_errors(
595
+ "get_drive_file_download_url", is_read_only=True, service_type="drive"
596
+ )
597
+ @require_google_service("drive", "drive_read")
598
+ async def get_drive_file_download_url(
599
+ service,
600
+ user_google_email: str,
601
+ file_id: str,
602
+ export_format: Optional[str] = None,
603
+ ) -> str:
604
+ """
605
+ Downloads a Google Drive file and saves it to local disk.
606
+
607
+ In stdio mode, returns the local file path for direct access.
608
+ In HTTP mode, returns a temporary download URL (valid for 1 hour).
609
+ In stateless mode (no file storage), returns the file itself as an embedded
610
+ resource, up to WORKSPACE_MCP_STATELESS_INLINE_MAX_BYTES (default 10 MiB,
611
+ and never more than WORKSPACE_MCP_MAX_FILE_BYTES when that is set).
612
+
613
+ For Google native files (Docs, Sheets, Slides, Drawings), exports to a useful format:
614
+ - Google Docs -> PDF (default) or DOCX if export_format='docx'
615
+ - Google Sheets -> XLSX (default), PDF if export_format='pdf', or CSV if export_format='csv'
616
+ - Google Slides -> PDF (default) or PPTX if export_format='pptx'
617
+ - Google Drawings -> PNG (default), or PDF, JPG or SVG if export_format='pdf', 'jpg' or 'svg'
618
+
619
+ For other files, downloads the original file format.
620
+
621
+ Args:
622
+ user_google_email: The user's Google email address. Required.
623
+ file_id: The Google Drive file ID to download.
624
+ export_format: Optional export format for Google native files.
625
+ Options: 'pdf', 'docx', 'xlsx', 'csv', 'pptx', 'png', 'jpg', 'svg'.
626
+ If not specified, uses sensible defaults (PDF for Docs/Slides, XLSX for Sheets,
627
+ PNG for Drawings).
628
+ For Sheets: supports 'csv', 'pdf', or 'xlsx' (default).
629
+
630
+ Returns:
631
+ str: File metadata with either a local file path or download URL. In
632
+ stateless mode the same text comes back as a ToolResult that also
633
+ embeds the file; the annotation stays str so the advertised output
634
+ schema is unchanged.
635
+ """
636
+ logger.info(
637
+ f"[get_drive_file_download_url] Invoked. File ID: '{file_id}', Export format: {export_format}"
638
+ )
639
+
640
+ # Resolve shortcuts and get file metadata
641
+ resolved_file_id, file_metadata = await resolve_drive_item(
642
+ service,
643
+ file_id,
644
+ extra_fields="name, webViewLink, mimeType, size",
645
+ )
646
+ file_id = resolved_file_id
647
+ mime_type = file_metadata.get("mimeType", "")
648
+ file_name = file_metadata.get("name", "Unknown File")
649
+
650
+ # Determine export format for Google native files
651
+ export_mime_type = None
652
+ output_filename = file_name
653
+ output_mime_type = mime_type
654
+
655
+ if mime_type == "application/vnd.google-apps.document":
656
+ # Google Docs
657
+ if export_format == "docx":
658
+ export_mime_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
659
+ output_mime_type = export_mime_type
660
+ if not output_filename.endswith(".docx"):
661
+ output_filename = f"{Path(output_filename).stem}.docx"
662
+ else:
663
+ # Default to PDF
664
+ export_mime_type = "application/pdf"
665
+ output_mime_type = export_mime_type
666
+ if not output_filename.endswith(".pdf"):
667
+ output_filename = f"{Path(output_filename).stem}.pdf"
668
+
669
+ elif mime_type == "application/vnd.google-apps.spreadsheet":
670
+ # Google Sheets
671
+ if export_format == "csv":
672
+ export_mime_type = "text/csv"
673
+ output_mime_type = export_mime_type
674
+ if not output_filename.endswith(".csv"):
675
+ output_filename = f"{Path(output_filename).stem}.csv"
676
+ elif export_format == "pdf":
677
+ export_mime_type = "application/pdf"
678
+ output_mime_type = export_mime_type
679
+ if not output_filename.endswith(".pdf"):
680
+ output_filename = f"{Path(output_filename).stem}.pdf"
681
+ else:
682
+ # Default to XLSX
683
+ export_mime_type = (
684
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
685
+ )
686
+ output_mime_type = export_mime_type
687
+ if not output_filename.endswith(".xlsx"):
688
+ output_filename = f"{Path(output_filename).stem}.xlsx"
689
+
690
+ elif mime_type == "application/vnd.google-apps.presentation":
691
+ # Google Slides
692
+ if export_format == "pptx":
693
+ export_mime_type = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
694
+ output_mime_type = export_mime_type
695
+ if not output_filename.endswith(".pptx"):
696
+ output_filename = f"{Path(output_filename).stem}.pptx"
697
+ else:
698
+ # Default to PDF
699
+ export_mime_type = "application/pdf"
700
+ output_mime_type = export_mime_type
701
+ if not output_filename.endswith(".pdf"):
702
+ output_filename = f"{Path(output_filename).stem}.pdf"
703
+
704
+ elif mime_type == GOOGLE_DRAWINGS_MIME_TYPE:
705
+ # Google Drawings
706
+ extension, export_mime_type = drawing_export_target(export_format)
707
+ output_mime_type = export_mime_type
708
+ if not output_filename.endswith(f".{extension}"):
709
+ output_filename = f"{output_filename}.{extension}"
710
+
711
+ # Stateless mode has no attachment storage to hand out a URL from, so the
712
+ # file itself goes back as an embedded resource, up to inline_max_bytes.
713
+ # GCS staging supplies that storage, so the file goes there instead.
714
+ inline_max_bytes = (
715
+ get_stateless_inline_max_bytes()
716
+ if is_stateless_mode() and not gcs_files_enabled()
717
+ else None
718
+ )
719
+ if inline_max_bytes == 0:
720
+ return _stateless_inline_disabled_message(file_name, file_id, output_mime_type)
721
+ # Drive's declared size is the download size only for binary files; an
722
+ # export's size is unknown until it has been downloaded.
723
+ declared_size = int(file_metadata.get("size") or 0)
724
+ if (
725
+ inline_max_bytes is not None
726
+ and not export_mime_type
727
+ and declared_size > inline_max_bytes
728
+ ):
729
+ return _stateless_too_large_message(
730
+ file_name, file_id, declared_size, output_mime_type, inline_max_bytes
731
+ )
732
+
733
+ # Stream the download straight to disk. Outside the capped stateless inline
734
+ # return, the payload is never held in memory as a whole.
735
+ tmp_path = await _download_file_to_temp(service, file_id, export_mime_type)
736
+ size_bytes = tmp_path.stat().st_size
737
+ size_kb = size_bytes / 1024 if size_bytes else 0
738
+
739
+ if inline_max_bytes is not None:
740
+ try:
741
+ if size_bytes > inline_max_bytes:
742
+ return _stateless_too_large_message(
743
+ file_name, file_id, size_bytes, output_mime_type, inline_max_bytes
744
+ )
745
+ with tmp_path.open("rb") as fh:
746
+ payload = fh.read()
747
+ finally:
748
+ tmp_path.unlink(missing_ok=True)
749
+ summary = "\n".join(
750
+ [
751
+ "File downloaded successfully!",
752
+ f"File: {file_name}",
753
+ f"File ID: {file_id}",
754
+ f"Size: {size_kb:.1f} KB ({size_bytes} bytes)",
755
+ f"MIME Type: {output_mime_type}",
756
+ "\nStateless mode: the file is attached to this result as an "
757
+ f"embedded resource ({output_filename}).",
758
+ ]
759
+ )
760
+ if export_mime_type:
761
+ summary += (
762
+ f"\n\nNote: Google native file exported to {output_mime_type} format."
763
+ )
764
+ logger.info(
765
+ f"[get_drive_file_download_url] Returned {size_kb:.1f} KB inline (stateless mode)"
766
+ )
767
+ return ToolResult(
768
+ content=[
769
+ TextContent(type="text", text=summary),
770
+ EmbeddedResource(
771
+ type="resource",
772
+ resource=BlobResourceContents(
773
+ uri=f"gdrive://{file_id}/{quote(output_filename)}",
774
+ mimeType=output_mime_type or "application/octet-stream",
775
+ blob=base64.b64encode(payload).decode("ascii"),
776
+ ),
777
+ ),
778
+ ],
779
+ structured_content={"result": summary},
780
+ )
781
+
782
+ # Move the download into attachment storage and return its path/URL
783
+ try:
784
+ storage = get_attachment_storage()
785
+ # shutil.move falls back to a full streamed copy when the temp dir and
786
+ # the storage dir are on different mounts, which for a multi-gigabyte
787
+ # download would block the event loop for the length of that copy.
788
+ result = await asyncio.to_thread(
789
+ storage.save_attachment_from_path,
790
+ src_path=str(tmp_path),
791
+ filename=output_filename,
792
+ mime_type=output_mime_type,
793
+ )
794
+
795
+ result_lines = [
796
+ "File downloaded successfully!",
797
+ f"File: {file_name}",
798
+ f"File ID: {file_id}",
799
+ f"Size: {size_kb:.1f} KB ({size_bytes} bytes)",
800
+ f"MIME Type: {output_mime_type}",
801
+ ]
802
+
803
+ if get_transport_mode() == "stdio":
804
+ result_lines.append(f"\n📎 Saved to: {result.path}")
805
+ result_lines.append(
806
+ "\nThe file has been saved to disk and can be accessed directly via the file path."
807
+ )
808
+ else:
809
+ download_url = await asyncio.to_thread(get_attachment_url, result.file_id)
810
+ result_lines.append(f"\n📎 Download URL: {download_url}")
811
+ result_lines.append("\nThe file will expire after 1 hour.")
812
+
813
+ if export_mime_type:
814
+ result_lines.append(
815
+ f"\nNote: Google native file exported to {output_mime_type} format."
816
+ )
817
+
818
+ logger.info(
819
+ f"[get_drive_file_download_url] Successfully saved {size_kb:.1f} KB file to {result.path}"
820
+ )
821
+ return "\n".join(result_lines)
822
+
823
+ except Exception as e:
824
+ # save_attachment_from_path consumes tmp_path on success only; if it
825
+ # raised before the move completed the temp file is still ours to drop.
826
+ tmp_path.unlink(missing_ok=True)
827
+ logger.error(f"[get_drive_file_download_url] Failed to save file: {e}")
828
+ record_degraded_failure(e)
829
+ return (
830
+ f"Error: Failed to save file for download.\n"
831
+ f"File was downloaded successfully ({size_kb:.1f} KB) but could not be saved.\n\n"
832
+ f"Error details: {str(e)}"
833
+ )
834
+
835
+
836
+ @server.tool(
837
+ title="List Drive Items",
838
+ annotations=ToolAnnotations(
839
+ readOnlyHint=True,
840
+ destructiveHint=False,
841
+ idempotentHint=True,
842
+ openWorldHint=True,
843
+ ),
844
+ )
845
+ @handle_http_errors("list_drive_items", is_read_only=True, service_type="drive")
846
+ @require_google_service("drive", "drive_read")
847
+ async def list_drive_items(
848
+ service,
849
+ user_google_email: str,
850
+ folder_id: str = "root",
851
+ page_size: int = 100,
852
+ page_token: Optional[str] = None,
853
+ drive_id: Optional[str] = None,
854
+ include_items_from_all_drives: bool = True,
855
+ corpora: Optional[str] = None,
856
+ file_type: Optional[str] = None,
857
+ detailed: bool = True,
858
+ order_by: Optional[str] = None,
859
+ resource_type: str = "items",
860
+ query: Optional[str] = None,
861
+ include_organizers: bool = False,
862
+ ) -> str:
863
+ """
864
+ Lists files/folders or shared drive containers, supporting shared drives.
865
+ If `drive_id` is specified, lists items within that shared drive. `folder_id` is then relative to that drive (or use drive_id as folder_id for root).
866
+ If `drive_id` is not specified, lists items from user's "My Drive" and accessible shared drives (if `include_items_from_all_drives` is True).
867
+ Set `resource_type` to "shared_drives" to list shared drive containers instead of folder contents.
868
+
869
+ Args:
870
+ user_google_email (str): The user's Google email address. Required.
871
+ folder_id (str): The ID of the Google Drive folder. Defaults to 'root'. For a shared drive, this can be the shared drive's ID to list its root, or a folder ID within that shared drive.
872
+ page_size (int): The maximum number of items to return. Defaults to 100.
873
+ page_token (Optional[str]): Page token from a previous response's nextPageToken to retrieve the next page of results.
874
+ drive_id (Optional[str]): ID of the shared drive. If provided, the listing is scoped to this drive.
875
+ include_items_from_all_drives (bool): Whether items from all accessible shared drives should be included if `drive_id` is not set. Defaults to True.
876
+ corpora (Optional[str]): Corpus to query ('user', 'drive', 'allDrives'). If `drive_id` is set and `corpora` is None, 'drive' is used. If None and no `drive_id`, 'allDrives' is used when `include_items_from_all_drives` is True.
877
+ file_type (Optional[str]): Restrict results to a specific file type. Accepts a friendly
878
+ name ('folder', 'document'/'doc', 'spreadsheet'/'sheet',
879
+ 'presentation'/'slides', 'form', 'drawing', 'pdf', 'shortcut',
880
+ 'script', 'site', 'jam'/'jamboard') or any raw MIME type
881
+ string (e.g. 'application/pdf'). Defaults to None (all types).
882
+ detailed (bool): Whether to include size, modified time, and link in results. Defaults to True.
883
+ order_by (Optional[str]): Sort order. Comma-separated list of sort keys with optional 'desc' modifier.
884
+ Valid keys: 'createdTime', 'folder', 'modifiedByMeTime', 'modifiedTime',
885
+ 'name', 'name_natural', 'quotaBytesUsed', 'recency', 'sharedWithMeTime',
886
+ 'starred', 'viewedByMeTime'. Example: 'modifiedTime desc' or 'folder,modifiedTime desc,name'.
887
+ Defaults to None (Drive API default ordering).
888
+ resource_type (str): What to list. Use "items" for folder contents or
889
+ "shared_drives" for shared drive containers. Defaults to "items".
890
+ query (Optional[str]): Shared drive query used only when resource_type="shared_drives",
891
+ e.g. "name contains 'Engineering'".
892
+ include_organizers (bool): When resource_type="shared_drives", include principals
893
+ with the organizer role. This costs one extra permissions.list
894
+ API call per shared drive returned. Defaults to False.
895
+
896
+ Returns:
897
+ str: A formatted list of files/folders in the specified folder or shared drives.
898
+ Includes a nextPageToken line when more results are available.
899
+ """
900
+ logger.info(
901
+ f"[list_drive_items] Invoked. Email: '{user_google_email}', Folder ID: '{folder_id}', "
902
+ f"File Type: '{file_type}', Resource Type: '{resource_type}'"
903
+ )
904
+
905
+ normalized_resource_type = resource_type.lower().strip()
906
+ if normalized_resource_type == "shared_drives":
907
+ return await _list_shared_drives_impl(
908
+ service=service,
909
+ user_google_email=user_google_email,
910
+ page_size=page_size,
911
+ page_token=page_token,
912
+ query=query,
913
+ include_organizers=include_organizers,
914
+ )
915
+ if normalized_resource_type != "items":
916
+ raise ValueError("resource_type must be either 'items' or 'shared_drives'")
917
+
918
+ resolved_folder_id = await resolve_folder_id(service, folder_id)
919
+ final_query = f"'{resolved_folder_id}' in parents and trashed=false"
920
+
921
+ if file_type is not None:
922
+ mime = resolve_file_type_mime(file_type)
923
+ final_query = f"({final_query}) and mimeType = '{mime}'"
924
+ logger.info(f"[list_drive_items] Added mimeType filter: '{mime}'")
925
+
926
+ list_params = build_drive_list_params(
927
+ query=final_query,
928
+ page_size=page_size,
929
+ drive_id=drive_id,
930
+ include_items_from_all_drives=include_items_from_all_drives,
931
+ corpora=corpora,
932
+ page_token=page_token,
933
+ detailed=detailed,
934
+ order_by=order_by,
935
+ )
936
+
937
+ results = await asyncio.to_thread(service.files().list(**list_params).execute)
938
+ files = results.get("files", [])
939
+ next_token = results.get("nextPageToken")
940
+ if not files and not next_token:
941
+ return flag_incomplete_search(
942
+ f"No items found in folder '{folder_id}'.", results
943
+ )
944
+
945
+ header = (
946
+ f"Found {len(files)} items in folder '{folder_id}' for {user_google_email}:"
947
+ )
948
+ formatted_items_text_parts = [header]
949
+ for item in files:
950
+ if detailed:
951
+ size_str = f", Size: {item.get('size', 'N/A')}" if "size" in item else ""
952
+ drive_id_str = (
953
+ f", Drive ID: {item['driveId']}" if item.get("driveId") else ""
954
+ )
955
+ created_str = (
956
+ f", Created: {item['createdTime']}" if item.get("createdTime") else ""
957
+ )
958
+ lmu = item.get("lastModifyingUser")
959
+ if lmu:
960
+ lmu_name = lmu.get("displayName", "")
961
+ lmu_email = lmu.get("emailAddress", "")
962
+ if lmu_name and lmu_email:
963
+ last_edited_by_str = f", Last Edited By: {lmu_name} <{lmu_email}>"
964
+ elif lmu_name:
965
+ last_edited_by_str = f", Last Edited By: {lmu_name}"
966
+ elif lmu_email:
967
+ last_edited_by_str = f", Last Edited By: {lmu_email}"
968
+ else:
969
+ last_edited_by_str = ""
970
+ else:
971
+ last_edited_by_str = ""
972
+ formatted_items_text_parts.append(
973
+ f'- Name: "{item["name"]}" (ID: {item["id"]}, Type: {item["mimeType"]}{size_str}'
974
+ f"{created_str}, Modified: {item.get('modifiedTime', 'N/A')}"
975
+ f"{last_edited_by_str}{drive_id_str})"
976
+ f" Link: {item.get('webViewLink', '#')}"
977
+ )
978
+ else:
979
+ formatted_items_text_parts.append(
980
+ f'- Name: "{item["name"]}" (ID: {item["id"]}, Type: {item["mimeType"]})'
981
+ )
982
+ if next_token:
983
+ formatted_items_text_parts.append(f"nextPageToken: {next_token}")
984
+ return flag_incomplete_search("\n".join(formatted_items_text_parts), results)
985
+
986
+
987
+ @server.tool(
988
+ title="Create Drive Folder",
989
+ annotations=ToolAnnotations(
990
+ readOnlyHint=False,
991
+ destructiveHint=False,
992
+ idempotentHint=False,
993
+ openWorldHint=True,
994
+ ),
995
+ )
996
+ @handle_http_errors("create_drive_folder", service_type="drive")
997
+ @require_google_service("drive", "drive_file")
998
+ async def create_drive_folder(
999
+ service,
1000
+ user_google_email: str,
1001
+ folder_name: str,
1002
+ parent_folder_id: str = "root",
1003
+ ) -> str:
1004
+ """
1005
+ Creates a new folder in Google Drive, supporting creation within shared drives.
1006
+
1007
+ Args:
1008
+ user_google_email (str): The user's Google email address. Required.
1009
+ folder_name (str): The name for the new folder.
1010
+ parent_folder_id (str): The ID of the parent folder. Defaults to 'root'.
1011
+ For shared drives, use a folder ID within that shared drive.
1012
+
1013
+ Returns:
1014
+ str: Confirmation message with folder name, ID, and link.
1015
+ """
1016
+ logger.info(
1017
+ f"[create_drive_folder] Invoked. Email: '{user_google_email}', Folder: '{folder_name}', Parent: '{parent_folder_id}'"
1018
+ )
1019
+ return await _create_drive_folder_impl(
1020
+ service, user_google_email, folder_name, parent_folder_id
1021
+ )
1022
+
1023
+
1024
+ @server.tool(
1025
+ title="Create Drive File",
1026
+ annotations=ToolAnnotations(
1027
+ readOnlyHint=False,
1028
+ destructiveHint=False,
1029
+ idempotentHint=False,
1030
+ openWorldHint=True,
1031
+ ),
1032
+ )
1033
+ @hide_remote_only_args("return_upload_url")
1034
+ @handle_http_errors("create_drive_file", service_type="drive")
1035
+ @require_google_service("drive", "drive_file")
1036
+ async def create_drive_file(
1037
+ service,
1038
+ user_google_email: str,
1039
+ file_name: str,
1040
+ content: Optional[str] = None, # Now explicitly Optional
1041
+ folder_id: str = "root",
1042
+ mime_type: Optional[str] = None,
1043
+ fileUrl: Optional[str] = None, # Now explicitly Optional
1044
+ base64_content: Optional[str] = None,
1045
+ content_mime_type: Optional[str] = None,
1046
+ base64_sha256: Optional[str] = None,
1047
+ return_upload_url: bool = False,
1048
+ shortcut_target_id: Optional[str] = None,
1049
+ ) -> str:
1050
+ """
1051
+ Creates a new file in Google Drive, supporting creation within shared drives.
1052
+ Accepts direct text content, inline base64 bytes, or a fileUrl to fetch content from.
1053
+ Where local file access is disabled it can instead return an upload URL for the
1054
+ caller to PUT file bytes to. With shortcut_target_id it creates a Drive shortcut
1055
+ to an existing file or folder instead.
1056
+ This stores the supplied bytes without converting them to Google Docs, Sheets, or
1057
+ Slides. Use the matching import_to_google_* tool for Google-native conversion.
1058
+
1059
+ Args:
1060
+ user_google_email (str): The user's Google email address. Required.
1061
+ file_name (str): The name for the new file.
1062
+ content (Optional[str]): If provided, the content to write to the file.
1063
+ folder_id (str): The ID of the parent folder. Defaults to 'root'. For shared drives, this must be a folder ID within the shared drive.
1064
+ mime_type (Optional[str]): The MIME type of the file. Defaults to 'text/plain'; required with return_upload_url.
1065
+ fileUrl (Optional[str]): If provided, fetches the file content from this URL. Supports http:// and https://; file:// only where local file access is enabled. Where it is disabled, files on the caller's machine go through an upload URL instead (see the upload-URL parameter, if offered).
1066
+ base64_content (Optional[str]): Standard base64-encoded file bytes.
1067
+ content_mime_type (Optional[str]): MIME type for base64_content uploads.
1068
+ base64_sha256 (Optional[str]): Expected SHA-256 of decoded base64_content. Recommended for binary payload integrity checks.
1069
+ return_upload_url (bool): Return a Google resumable-upload session URL for a new file of mime_type instead of creating it from inline content; the caller PUTs the bytes there directly (no Authorization header). Preferred for large or binary files. Not combinable with other content sources. Offered only where local file access is disabled.
1070
+ shortcut_target_id (Optional[str]): ID of an existing file or folder. Creates a shortcut named file_name in folder_id that points to it, so the item shows up in a second folder without being copied. Not combinable with content sources; mime_type may be omitted.
1071
+
1072
+ Returns:
1073
+ str: Confirmation message of the successful file creation with file link,
1074
+ or the resumable upload URL.
1075
+ """
1076
+ logger.info(
1077
+ f"[create_drive_file] Invoked. Email: '{user_google_email}', "
1078
+ f"file_name_len={len(file_name) if file_name else 0}, Folder ID: {folder_id}, "
1079
+ f"has_fileUrl={bool(fileUrl)}, return_upload_url={return_upload_url}, "
1080
+ f"shortcut_target_id={shortcut_target_id}"
1081
+ )
1082
+ logger.debug(f"[create_drive_file] File Name: {file_name}")
1083
+
1084
+ if mime_type is not None:
1085
+ mime_type = mime_type.strip().lower()
1086
+ if content_mime_type is not None:
1087
+ content_mime_type = content_mime_type.strip().lower()
1088
+
1089
+ if shortcut_target_id is not None:
1090
+ validate_shortcut_request(
1091
+ shortcut_target_id,
1092
+ mime_type=mime_type,
1093
+ content=content,
1094
+ fileUrl=fileUrl,
1095
+ base64_content=base64_content,
1096
+ content_mime_type=content_mime_type,
1097
+ base64_sha256=base64_sha256,
1098
+ return_upload_url=return_upload_url,
1099
+ )
1100
+ return await _create_drive_shortcut_impl(
1101
+ service,
1102
+ user_google_email,
1103
+ file_name,
1104
+ shortcut_target_id.strip(),
1105
+ folder_id,
1106
+ )
1107
+
1108
+ if return_upload_url:
1109
+ if local_file_access_enabled():
1110
+ raise upload_url_not_offered_error(("fileUrl", "content", "base64_content"))
1111
+ reject_sources_with_upload_url(
1112
+ "creates the file",
1113
+ content=content,
1114
+ fileUrl=fileUrl,
1115
+ base64_content=base64_content,
1116
+ content_mime_type=content_mime_type,
1117
+ base64_sha256=base64_sha256,
1118
+ )
1119
+ if not mime_type:
1120
+ raise ValueError(
1121
+ "return_upload_url requires mime_type: the MIME type of the bytes "
1122
+ "to be uploaded."
1123
+ )
1124
+ if mime_type == FOLDER_MIME_TYPE:
1125
+ raise ValueError("return_upload_url is not applicable to folders.")
1126
+ if mime_type.startswith(GOOGLE_APPS_MIME_PREFIX):
1127
+ raise ValueError(
1128
+ "Google-native files cannot be created from uploaded bytes with "
1129
+ "create_drive_file. Use import_to_google_doc, "
1130
+ "import_to_google_sheets, or import_to_google_slides so Drive receives "
1131
+ "separate source and target MIME types."
1132
+ )
1133
+ upload_url = await initiate_resumable_upload_session(
1134
+ service,
1135
+ upload_mime_type=mime_type,
1136
+ file_metadata={
1137
+ "name": file_name,
1138
+ "parents": [await resolve_folder_id(service, folder_id)],
1139
+ "mimeType": mime_type,
1140
+ },
1141
+ )
1142
+ logger.info("[create_drive_file] Returned resumable upload URL.")
1143
+ return resumable_upload_result(
1144
+ f"Resumable upload session created for new file '{file_name}' "
1145
+ f"(folder '{folder_id}', for {user_google_email}).",
1146
+ upload_url,
1147
+ mime_type,
1148
+ )
1149
+
1150
+ mime_type = mime_type or "text/plain"
1151
+ if mime_type == SHORTCUT_MIME_TYPE:
1152
+ raise ValueError(
1153
+ "Creating a shortcut requires shortcut_target_id: the ID of the file "
1154
+ "or folder the shortcut points to."
1155
+ )
1156
+ has_existing_content_source = content is not None or bool(fileUrl)
1157
+ if (
1158
+ not has_existing_content_source
1159
+ and base64_content is None
1160
+ and mime_type != FOLDER_MIME_TYPE
1161
+ ):
1162
+ raise ValueError(
1163
+ "You must provide one of 'content', 'fileUrl', or 'base64_content'."
1164
+ )
1165
+ if base64_content is not None and has_existing_content_source:
1166
+ raise ValueError("'base64_content' cannot be used with 'content' or 'fileUrl'.")
1167
+ if content_mime_type is not None and base64_content is None:
1168
+ raise ValueError("'content_mime_type' can only be used with 'base64_content'.")
1169
+ if base64_content is not None and not content_mime_type:
1170
+ raise ValueError("'content_mime_type' is required when using 'base64_content'.")
1171
+ if base64_sha256 is not None and base64_content is None:
1172
+ raise ValueError("'base64_sha256' can only be used with 'base64_content'.")
1173
+ if base64_content is not None and (
1174
+ mime_type.startswith(GOOGLE_APPS_MIME_PREFIX)
1175
+ or content_mime_type.startswith(GOOGLE_APPS_MIME_PREFIX)
1176
+ ):
1177
+ raise ValueError(
1178
+ "Google-native files cannot be created from inline binary bytes with "
1179
+ "create_drive_file. Use import_to_google_doc, import_to_google_sheets, "
1180
+ "or import_to_google_slides so Drive receives separate source and target "
1181
+ "MIME types."
1182
+ )
1183
+
1184
+ if mime_type == FOLDER_MIME_TYPE:
1185
+ if base64_content is not None or content is not None or bool(fileUrl):
1186
+ raise ValueError(
1187
+ "Folders cannot contain file content. Remove 'content', "
1188
+ "'base64_content', and 'fileUrl' when creating a folder, "
1189
+ "or use a different mime_type."
1190
+ )
1191
+ return await _create_drive_folder_impl(
1192
+ service, user_google_email, file_name, folder_id
1193
+ )
1194
+
1195
+ file_data = None
1196
+ if base64_content is not None:
1197
+ file_data = _decode_base64_upload(
1198
+ base64_content,
1199
+ tool_name="create_drive_file",
1200
+ mime_type=content_mime_type,
1201
+ expected_sha256=base64_sha256,
1202
+ )
1203
+
1204
+ resolved_folder_id = await resolve_folder_id(service, folder_id)
1205
+
1206
+ file_metadata = {
1207
+ "name": file_name,
1208
+ "parents": [resolved_folder_id],
1209
+ "mimeType": mime_type,
1210
+ }
1211
+
1212
+ if base64_content is not None:
1213
+ file_metadata["mimeType"] = content_mime_type
1214
+ media = MediaIoBaseUpload(
1215
+ io.BytesIO(file_data),
1216
+ mimetype=content_mime_type,
1217
+ resumable=_use_resumable_upload(len(file_data)),
1218
+ chunksize=UPLOAD_CHUNK_SIZE_BYTES,
1219
+ )
1220
+
1221
+ created_file = await asyncio.to_thread(
1222
+ service.files()
1223
+ .create(
1224
+ body=file_metadata,
1225
+ media_body=media,
1226
+ fields="id, name, webViewLink",
1227
+ supportsAllDrives=True,
1228
+ )
1229
+ .execute,
1230
+ num_retries=GOOGLE_API_WRITE_RETRIES,
1231
+ )
1232
+ # Prefer fileUrl if both legacy sources are provided.
1233
+ elif fileUrl:
1234
+ logger.info("[create_drive_file] Fetching file from provided URL")
1235
+
1236
+ # Check if this is a file:// URL
1237
+ parsed_url = urlparse(fileUrl)
1238
+ if parsed_url.scheme == "file":
1239
+ if not local_file_access_enabled():
1240
+ raise UserInputError(
1241
+ "Local file access is disabled on this server: file paths "
1242
+ "resolve on the server's filesystem, not the caller's. "
1243
+ "Provide the file by http(s) URL or as inline content "
1244
+ f"instead. {upload_url_hint('mime_type')}"
1245
+ )
1246
+
1247
+ # Handle file:// URL - read from local filesystem
1248
+ logger.info(
1249
+ "[create_drive_file] Detected file:// URL, reading from local filesystem"
1250
+ )
1251
+ transport_mode = get_transport_mode()
1252
+ running_streamable = transport_mode == "streamable-http"
1253
+ if running_streamable:
1254
+ logger.warning(
1255
+ "[create_drive_file] file:// URL requested while server runs in streamable-http mode. Ensure the file path is accessible to the server (e.g., Docker volume) or use an HTTP(S) URL."
1256
+ )
1257
+
1258
+ # Convert file:// URL to a cross-platform local path
1259
+ raw_path = parsed_url.path or ""
1260
+ netloc = parsed_url.netloc
1261
+ if netloc and netloc.lower() != "localhost":
1262
+ raw_path = f"//{netloc}{raw_path}"
1263
+ file_path = url2pathname(raw_path)
1264
+
1265
+ # Validate path safety and verify file exists
1266
+ try:
1267
+ handle = open_validated_file(file_path)
1268
+ except NotARegularFileError:
1269
+ extra = (
1270
+ " In streamable-http/Docker deployments, mount the file into the container or provide an HTTP(S) URL."
1271
+ if running_streamable
1272
+ else ""
1273
+ )
1274
+ raise Exception(f"Local path is not a file.{extra}") from None
1275
+ except (OSError, ValueError) as exc:
1276
+ raise ValueError(
1277
+ f"Local file could not be accessed ({type(exc).__name__})."
1278
+ ) from None
1279
+
1280
+ logger.info("[create_drive_file] Reading local file")
1281
+
1282
+ # Read file and upload
1283
+ with handle:
1284
+ try:
1285
+ file_data = await asyncio.to_thread(handle.read)
1286
+ except OSError as exc:
1287
+ raise OSError(
1288
+ f"Failed to read local file ({type(exc).__name__})."
1289
+ ) from None
1290
+ total_bytes = len(file_data)
1291
+ logger.info(f"[create_drive_file] Read {total_bytes} bytes from local file")
1292
+
1293
+ media = MediaIoBaseUpload(
1294
+ io.BytesIO(file_data),
1295
+ mimetype=mime_type,
1296
+ resumable=True,
1297
+ chunksize=UPLOAD_CHUNK_SIZE_BYTES,
1298
+ )
1299
+
1300
+ logger.info("[create_drive_file] Starting upload to Google Drive...")
1301
+ created_file = await asyncio.to_thread(
1302
+ service.files()
1303
+ .create(
1304
+ body=file_metadata,
1305
+ media_body=media,
1306
+ fields="id, name, webViewLink",
1307
+ supportsAllDrives=True,
1308
+ )
1309
+ .execute,
1310
+ num_retries=GOOGLE_API_WRITE_RETRIES,
1311
+ )
1312
+ # Handle HTTP/HTTPS URLs
1313
+ elif parsed_url.scheme in ("http", "https"):
1314
+ # when running in stateless mode, deployment may not have access to local file system
1315
+ if is_stateless_mode():
1316
+ with SpooledTemporaryFile(max_size=UPLOAD_CHUNK_SIZE_BYTES) as spool:
1317
+
1318
+ async def _write_spool(chunk: bytes) -> None:
1319
+ await asyncio.to_thread(spool.write, chunk)
1320
+
1321
+ _total, content_type = await _stream_url_with_validation(
1322
+ fileUrl, _write_spool, upload_type_param="mime_type"
1323
+ )
1324
+ await asyncio.to_thread(spool.seek, 0)
1325
+
1326
+ # Try to get MIME type from Content-Type header
1327
+ if content_type and content_type != "application/octet-stream":
1328
+ mime_type = content_type
1329
+ file_metadata["mimeType"] = content_type
1330
+ logger.info(
1331
+ f"[create_drive_file] Using MIME type from Content-Type header: {content_type}"
1332
+ )
1333
+
1334
+ media = MediaIoBaseUpload(
1335
+ spool,
1336
+ mimetype=mime_type,
1337
+ resumable=True,
1338
+ chunksize=UPLOAD_CHUNK_SIZE_BYTES,
1339
+ )
1340
+
1341
+ created_file = await asyncio.to_thread(
1342
+ service.files()
1343
+ .create(
1344
+ body=file_metadata,
1345
+ media_body=media,
1346
+ fields="id, name, webViewLink",
1347
+ supportsAllDrives=True,
1348
+ )
1349
+ .execute,
1350
+ num_retries=GOOGLE_API_WRITE_RETRIES,
1351
+ )
1352
+ else:
1353
+ # Stream download to temp file with SSRF protection, then upload
1354
+ with NamedTemporaryFile() as temp_file:
1355
+
1356
+ async def _write_chunk(chunk: bytes) -> None:
1357
+ await asyncio.to_thread(temp_file.write, chunk)
1358
+
1359
+ total_bytes, content_type = await _stream_url_with_validation(
1360
+ fileUrl, _write_chunk, upload_type_param="mime_type"
1361
+ )
1362
+
1363
+ logger.info(
1364
+ f"[create_drive_file] Downloaded {total_bytes} bytes "
1365
+ f"from URL before upload."
1366
+ )
1367
+
1368
+ if content_type and content_type != "application/octet-stream":
1369
+ mime_type = content_type
1370
+ file_metadata["mimeType"] = mime_type
1371
+ logger.info(
1372
+ f"[create_drive_file] Using MIME type from "
1373
+ f"Content-Type header: {mime_type}"
1374
+ )
1375
+
1376
+ # Reset file pointer to beginning for upload
1377
+ temp_file.seek(0)
1378
+
1379
+ media = MediaIoBaseUpload(
1380
+ temp_file,
1381
+ mimetype=mime_type,
1382
+ resumable=True,
1383
+ chunksize=UPLOAD_CHUNK_SIZE_BYTES,
1384
+ )
1385
+
1386
+ logger.info(
1387
+ "[create_drive_file] Starting upload to Google Drive..."
1388
+ )
1389
+ created_file = await asyncio.to_thread(
1390
+ service.files()
1391
+ .create(
1392
+ body=file_metadata,
1393
+ media_body=media,
1394
+ fields="id, name, webViewLink",
1395
+ supportsAllDrives=True,
1396
+ )
1397
+ .execute,
1398
+ num_retries=GOOGLE_API_WRITE_RETRIES,
1399
+ )
1400
+ else:
1401
+ if not parsed_url.scheme:
1402
+ raise Exception(
1403
+ "fileUrl is missing a URL scheme. Use file://, http://, or https://."
1404
+ )
1405
+ raise Exception(
1406
+ f"Unsupported URL scheme '{parsed_url.scheme}'. Only file://, http://, and https:// are supported."
1407
+ )
1408
+ elif content is not None:
1409
+ file_data = content.encode("utf-8")
1410
+ media = io.BytesIO(file_data)
1411
+
1412
+ created_file = await asyncio.to_thread(
1413
+ service.files()
1414
+ .create(
1415
+ body=file_metadata,
1416
+ media_body=MediaIoBaseUpload(media, mimetype=mime_type, resumable=True),
1417
+ fields="id, name, webViewLink",
1418
+ supportsAllDrives=True,
1419
+ )
1420
+ .execute,
1421
+ num_retries=GOOGLE_API_WRITE_RETRIES,
1422
+ )
1423
+
1424
+ link = created_file.get("webViewLink", "No link available")
1425
+ confirmation_message = f"Successfully created file '{created_file.get('name', file_name)}' (ID: {created_file.get('id', 'N/A')}) in folder '{folder_id}' for {user_google_email}. Link: {link}"
1426
+ logger.info(f"Successfully created file. Link: {link}")
1427
+ return confirmation_message
1428
+
1429
+
1430
+ @server.tool(
1431
+ title="Import to Google Doc",
1432
+ annotations=ToolAnnotations(
1433
+ readOnlyHint=False,
1434
+ destructiveHint=False,
1435
+ idempotentHint=False,
1436
+ openWorldHint=True,
1437
+ ),
1438
+ )
1439
+ @hide_local_file_args("file_path")
1440
+ @hide_remote_only_args("return_upload_url")
1441
+ @handle_http_errors("import_to_google_doc", service_type="drive")
1442
+ @require_google_service("drive", "drive_file")
1443
+ async def import_to_google_doc(
1444
+ service,
1445
+ user_google_email: str,
1446
+ file_name: str,
1447
+ content: Optional[str] = None,
1448
+ file_path: Optional[str] = None,
1449
+ file_url: Optional[str] = None,
1450
+ source_format: Optional[str] = None,
1451
+ folder_id: str = "root",
1452
+ base64_content: Optional[str] = None,
1453
+ base64_sha256: Optional[str] = None,
1454
+ return_upload_url: bool = False,
1455
+ ) -> str:
1456
+ """
1457
+ Imports a file (Markdown, DOCX, TXT, HTML, RTF, ODT) into Google Docs format with automatic conversion.
1458
+
1459
+ Google Drive automatically converts the source file to native Google Docs format,
1460
+ preserving formatting like headings, lists, bold, italic, etc.
1461
+ Binary sources may be passed directly as base64_content. On a local server a
1462
+ file on disk can also be passed by path (preferred for batch operations, so
1463
+ callers do not need to load full file contents into their context).
1464
+
1465
+ Args:
1466
+ user_google_email (str): The user's Google email address. Required.
1467
+ file_name (str): The name for the new Google Doc; the extension is dropped from the title. Without 'source_format', its extension also sets the format of 'content' or 'base64_content' (e.g. 'Notes.md' so Markdown tables are not imported as plain text).
1468
+ content (Optional[str]): Text content for text-based formats. Use only for short snippets or content already in memory.
1469
+ file_path (Optional[str]): Local file path or file:// URL for any supported format (MD, TXT, HTML, DOCX, ODT, RTF). Appropriate for larger files than content, but file_path may still load the file into memory or perform non-streaming reads. Avoid very large files that could exceed memory or time limits; use streaming/chunked uploads or an alternative API for huge files.
1470
+ file_url (Optional[str]): Remote URL to fetch the file from (http/https).
1471
+ source_format (Optional[str]): Source format hint ('md', 'markdown', 'docx', 'txt', 'html', 'rtf', 'odt').
1472
+ Auto-detected from file_name extension if not provided.
1473
+ folder_id (str): The ID of the parent folder. Defaults to 'root'.
1474
+ base64_content (Optional[str]): Standard base64-encoded bytes for a binary source such as DOCX or ODT.
1475
+ base64_sha256 (Optional[str]): Expected SHA-256 of decoded base64_content. Recommended for binary payload integrity checks.
1476
+ return_upload_url (bool): Return a Google resumable-upload session URL instead of ingesting the source here; the caller PUTs the source bytes there directly (no Authorization header) and Drive converts them. Requires source_format; not combinable with other content sources. Offered only where local file access is disabled.
1477
+
1478
+ Returns:
1479
+ str: Confirmation message with the new Google Doc link, or the resumable upload URL.
1480
+
1481
+ Examples:
1482
+ # Import a markdown file from disk (preferred for batch operations)
1483
+ import_to_google_doc(file_name="My Doc.md", file_path="/path/to/my-doc.md", source_format="md")
1484
+
1485
+ # Import markdown content directly
1486
+ import_to_google_doc(file_name="My Doc.md", content="# Title\\n\\nHello **world**")
1487
+
1488
+ # Import a local DOCX file
1489
+ import_to_google_doc(file_name="Report", file_path="/path/to/report.docx")
1490
+
1491
+ # Import from URL
1492
+ import_to_google_doc(file_name="Remote Doc", file_url="https://example.com/doc.md")
1493
+
1494
+ # Get an upload URL and PUT a DOCX to it directly (hosted servers, large files)
1495
+ import_to_google_doc(file_name="Report", source_format="docx", return_upload_url=True)
1496
+ """
1497
+ return await _import_with_conversion(
1498
+ service,
1499
+ tool_name="import_to_google_doc",
1500
+ target_label="Google Doc",
1501
+ id_label="Document ID",
1502
+ target_mime_type=GOOGLE_DOCS_MIME_TYPE,
1503
+ format_map=GOOGLE_DOCS_IMPORT_FORMATS,
1504
+ user_google_email=user_google_email,
1505
+ file_name=file_name,
1506
+ content=content,
1507
+ file_path=file_path,
1508
+ file_url=file_url,
1509
+ source_format=source_format,
1510
+ folder_id=folder_id,
1511
+ base64_content=base64_content,
1512
+ base64_sha256=base64_sha256,
1513
+ return_upload_url=return_upload_url,
1514
+ )
1515
+
1516
+
1517
+ @server.tool(
1518
+ title="Import to Google Slides",
1519
+ annotations=ToolAnnotations(
1520
+ readOnlyHint=False,
1521
+ destructiveHint=False,
1522
+ idempotentHint=False,
1523
+ openWorldHint=True,
1524
+ ),
1525
+ )
1526
+ @hide_local_file_args("file_path")
1527
+ @hide_remote_only_args("return_upload_url")
1528
+ @handle_http_errors("import_to_google_slides", service_type="drive")
1529
+ @require_google_service("drive", "drive_file")
1530
+ async def import_to_google_slides(
1531
+ service,
1532
+ user_google_email: str,
1533
+ file_name: str,
1534
+ file_path: Optional[str] = None,
1535
+ file_url: Optional[str] = None,
1536
+ source_format: Optional[str] = None,
1537
+ folder_id: str = "root",
1538
+ base64_content: Optional[str] = None,
1539
+ base64_sha256: Optional[str] = None,
1540
+ return_upload_url: bool = False,
1541
+ ) -> str:
1542
+ """
1543
+ Imports a presentation (PPTX, PPT, ODP) into Google Slides format with automatic conversion.
1544
+
1545
+ Google Drive automatically converts the source presentation to native Google Slides format,
1546
+ preserving slides, layouts, text, and images.
1547
+ Binary sources may be passed directly as base64_content. On a local server a
1548
+ file on disk can also be passed by path (preferred for batch operations, so
1549
+ callers do not need to load full file contents into their context).
1550
+
1551
+ Args:
1552
+ user_google_email (str): The user's Google email address. Required.
1553
+ file_name (str): The name for the new Google Slides presentation; the extension is dropped from the title. Without 'source_format', its extension also sets the format of 'base64_content' (e.g. 'Deck.pptx').
1554
+ file_path (Optional[str]): Local file path or file:// URL for any supported format (PPTX, PPT, ODP). Appropriate for larger files than content, but file_path may still load the file into memory or perform non-streaming reads. Avoid very large files that could exceed memory or time limits; use streaming/chunked uploads or an alternative API for huge files.
1555
+ file_url (Optional[str]): Remote URL to fetch the presentation from (http/https).
1556
+ source_format (Optional[str]): Source format hint ('pptx', 'ppt', 'odp').
1557
+ Auto-detected from file_name extension if not provided.
1558
+ folder_id (str): The ID of the parent folder. Defaults to 'root'.
1559
+ base64_content (Optional[str]): Standard base64-encoded bytes for a PPTX or ODP source.
1560
+ base64_sha256 (Optional[str]): Expected SHA-256 of decoded base64_content. Recommended for binary payload integrity checks.
1561
+ return_upload_url (bool): Return a Google resumable-upload session URL instead of ingesting the source here; the caller PUTs the source bytes there directly (no Authorization header) and Drive converts them. Requires source_format; not combinable with other content sources. Offered only where local file access is disabled.
1562
+
1563
+ Returns:
1564
+ str: Confirmation message with the new Google Slides link, or the resumable upload URL.
1565
+
1566
+ Examples:
1567
+ # Import a local PowerPoint file (preferred for batch operations)
1568
+ import_to_google_slides(file_name="Deck", file_path="/path/to/deck.pptx")
1569
+
1570
+ # Import from URL
1571
+ import_to_google_slides(file_name="Remote Deck", file_url="https://example.com/deck.pptx")
1572
+
1573
+ # Get an upload URL and PUT a PPTX to it directly (hosted servers, large files)
1574
+ import_to_google_slides(file_name="Deck", source_format="pptx", return_upload_url=True)
1575
+ """
1576
+ return await _import_with_conversion(
1577
+ service,
1578
+ tool_name="import_to_google_slides",
1579
+ target_label="Google Slides presentation",
1580
+ id_label="Presentation ID",
1581
+ target_mime_type=GOOGLE_SLIDES_MIME_TYPE,
1582
+ format_map=GOOGLE_SLIDES_IMPORT_FORMATS,
1583
+ user_google_email=user_google_email,
1584
+ file_name=file_name,
1585
+ content=None,
1586
+ file_path=file_path,
1587
+ file_url=file_url,
1588
+ source_format=source_format,
1589
+ folder_id=folder_id,
1590
+ base64_content=base64_content,
1591
+ base64_sha256=base64_sha256,
1592
+ inline_params=("base64_content",),
1593
+ return_upload_url=return_upload_url,
1594
+ )
1595
+
1596
+
1597
+ @server.tool(
1598
+ title="Import to Google Sheets",
1599
+ annotations=ToolAnnotations(
1600
+ readOnlyHint=False,
1601
+ destructiveHint=False,
1602
+ idempotentHint=False,
1603
+ openWorldHint=True,
1604
+ ),
1605
+ )
1606
+ @hide_local_file_args("file_path")
1607
+ @hide_remote_only_args("return_upload_url")
1608
+ @handle_http_errors("import_to_google_sheets", service_type="drive")
1609
+ @require_google_service("drive", "drive_file")
1610
+ async def import_to_google_sheets(
1611
+ service,
1612
+ user_google_email: str,
1613
+ file_name: str,
1614
+ content: Optional[str] = None,
1615
+ file_path: Optional[str] = None,
1616
+ file_url: Optional[str] = None,
1617
+ source_format: Optional[str] = None,
1618
+ folder_id: str = "root",
1619
+ base64_content: Optional[str] = None,
1620
+ base64_sha256: Optional[str] = None,
1621
+ return_upload_url: bool = False,
1622
+ ) -> str:
1623
+ """
1624
+ Imports a spreadsheet (XLSX, XLS, ODS, CSV, TSV) into Google Sheets format with automatic conversion.
1625
+
1626
+ Google Drive automatically converts the source spreadsheet to native Google Sheets format,
1627
+ preserving rows, columns, sheets, and values.
1628
+ Binary sources may be passed directly as base64_content. On a local server a
1629
+ file on disk can also be passed by path (preferred for batch operations, so
1630
+ callers do not need to load full file contents into their context).
1631
+
1632
+ Args:
1633
+ user_google_email (str): The user's Google email address. Required.
1634
+ file_name (str): The name for the new Google Sheets spreadsheet; the extension is dropped from the title. Without 'source_format', its extension also sets the format of 'content' or 'base64_content' (e.g. 'Data.csv').
1635
+ content (Optional[str]): Text content for text-based formats (CSV, TSV). Use only for short snippets or content already in memory.
1636
+ file_path (Optional[str]): Local file path or file:// URL for any supported format (XLSX, XLS, ODS, CSV, TSV). Appropriate for larger files than content, but file_path may still load the file into memory or perform non-streaming reads. Avoid very large files that could exceed memory or time limits; use streaming/chunked uploads or an alternative API for huge files.
1637
+ file_url (Optional[str]): Remote URL to fetch the spreadsheet from (http/https).
1638
+ source_format (Optional[str]): Source format hint ('xlsx', 'xls', 'ods', 'csv', 'tsv').
1639
+ Auto-detected from file_name extension if not provided.
1640
+ folder_id (str): The ID of the parent folder. Defaults to 'root'.
1641
+ base64_content (Optional[str]): Standard base64-encoded bytes for an XLSX, XLS, or ODS source.
1642
+ base64_sha256 (Optional[str]): Expected SHA-256 of decoded base64_content. Recommended for binary payload integrity checks.
1643
+ return_upload_url (bool): Return a Google resumable-upload session URL instead of ingesting the source here; the caller PUTs the source bytes there directly (no Authorization header) and Drive converts them. Requires source_format; not combinable with other content sources. Offered only where local file access is disabled.
1644
+
1645
+ Returns:
1646
+ str: Confirmation message with the new Google Sheets link, or the resumable upload URL.
1647
+
1648
+ Examples:
1649
+ # Import a local Excel file (preferred for batch operations)
1650
+ import_to_google_sheets(file_name="Budget", file_path="/path/to/budget.xlsx")
1651
+
1652
+ # Import CSV content directly
1653
+ import_to_google_sheets(file_name="Data.csv", content="a,b,c\\n1,2,3", source_format="csv")
1654
+
1655
+ # Import from URL
1656
+ import_to_google_sheets(file_name="Remote Sheet", file_url="https://example.com/data.xlsx")
1657
+
1658
+ # Get an upload URL and PUT an XLSX to it directly (hosted servers, large files)
1659
+ import_to_google_sheets(file_name="Budget", source_format="xlsx", return_upload_url=True)
1660
+ """
1661
+ return await _import_with_conversion(
1662
+ service,
1663
+ tool_name="import_to_google_sheets",
1664
+ target_label="Google Sheets spreadsheet",
1665
+ id_label="Spreadsheet ID",
1666
+ target_mime_type=GOOGLE_SHEETS_MIME_TYPE,
1667
+ format_map=GOOGLE_SHEETS_IMPORT_FORMATS,
1668
+ user_google_email=user_google_email,
1669
+ file_name=file_name,
1670
+ content=content,
1671
+ file_path=file_path,
1672
+ file_url=file_url,
1673
+ source_format=source_format,
1674
+ folder_id=folder_id,
1675
+ base64_content=base64_content,
1676
+ base64_sha256=base64_sha256,
1677
+ return_upload_url=return_upload_url,
1678
+ )
1679
+
1680
+
1681
+ @server.tool(
1682
+ title="Get Drive File Permissions",
1683
+ annotations=ToolAnnotations(
1684
+ readOnlyHint=True,
1685
+ destructiveHint=False,
1686
+ idempotentHint=True,
1687
+ openWorldHint=True,
1688
+ ),
1689
+ )
1690
+ @handle_http_errors(
1691
+ "get_drive_file_permissions", is_read_only=True, service_type="drive"
1692
+ )
1693
+ @require_google_service("drive", "drive_read")
1694
+ async def get_drive_file_permissions(
1695
+ service,
1696
+ user_google_email: str,
1697
+ file_id: str,
1698
+ ) -> str:
1699
+ """
1700
+ Gets detailed metadata about a Google Drive file including sharing permissions,
1701
+ parent folder IDs, ownership, and lifecycle timestamps.
1702
+
1703
+ Args:
1704
+ user_google_email (str): The user's Google email address. Required.
1705
+ file_id (str): The ID of the file to check permissions for.
1706
+
1707
+ Returns:
1708
+ str: Detailed file metadata including parents, owners, timestamps, sharing status, and URLs.
1709
+ """
1710
+ logger.info(
1711
+ f"[get_drive_file_permissions] Checking file {file_id} for {user_google_email}"
1712
+ )
1713
+
1714
+ resolved_file_id, _ = await resolve_drive_item(service, file_id)
1715
+ file_id = resolved_file_id
1716
+
1717
+ try:
1718
+ # Get comprehensive file metadata including permissions with details
1719
+ file_metadata = await asyncio.to_thread(
1720
+ service.files()
1721
+ .get(
1722
+ fileId=file_id,
1723
+ fields="id, name, mimeType, size, parents, createdTime, modifiedTime, "
1724
+ "trashed, driveId, owners(displayName,emailAddress), "
1725
+ "permissions(id, type, role, emailAddress, domain, expirationTime, permissionDetails), "
1726
+ "webViewLink, webContentLink, shared, sharingUser, viewersCanCopyContent",
1727
+ supportsAllDrives=True,
1728
+ )
1729
+ .execute
1730
+ )
1731
+
1732
+ # Format the response
1733
+ # Resolve permissions up front: Shared Drive items omit inline permissions
1734
+ # (and the `shared` boolean) on files.get(), so fetch via permissions.list().
1735
+ _perms_for_shared = file_metadata.get("permissions", [])
1736
+ if file_metadata.get("driveId"):
1737
+ _perms_for_shared = await asyncio.to_thread(
1738
+ list_all_permissions, service, file_id
1739
+ )
1740
+ parents = file_metadata.get("parents")
1741
+ parent_str = ", ".join(parents) if parents else "None (root or orphaned)"
1742
+ owners = file_metadata.get("owners") or []
1743
+ if owners:
1744
+ owner_str = ", ".join(
1745
+ (
1746
+ f"{owner.get('displayName') or owner.get('name') or 'Unknown'} "
1747
+ f"({owner.get('emailAddress') or owner.get('email')})"
1748
+ )
1749
+ if (owner.get("emailAddress") or owner.get("email"))
1750
+ else owner.get("displayName") or owner.get("name") or "Unknown"
1751
+ for owner in owners
1752
+ )
1753
+ else:
1754
+ owner_str = "None available"
1755
+
1756
+ output_parts = [
1757
+ f"File: {file_metadata.get('name', 'Unknown')}",
1758
+ f"ID: {file_id}",
1759
+ f"Type: {file_metadata.get('mimeType', 'Unknown')}",
1760
+ f"Parents: {parent_str}",
1761
+ f"Owners: {owner_str}",
1762
+ f"Size: {file_metadata.get('size', 'N/A')} bytes",
1763
+ f"Created: {file_metadata.get('createdTime', 'N/A')}",
1764
+ f"Modified: {file_metadata.get('modifiedTime', 'N/A')}",
1765
+ f"Trashed: {file_metadata.get('trashed', False)}",
1766
+ ]
1767
+
1768
+ if file_metadata.get("driveId"):
1769
+ output_parts.append(f"Shared Drive ID: {file_metadata['driveId']}")
1770
+
1771
+ output_parts.extend(
1772
+ [
1773
+ "",
1774
+ "Sharing Status:",
1775
+ f" Shared: {derive_shared_state(file_metadata, _perms_for_shared)}",
1776
+ ]
1777
+ )
1778
+
1779
+ # Add sharing user if available
1780
+ sharing_user = file_metadata.get("sharingUser")
1781
+ if sharing_user:
1782
+ output_parts.append(
1783
+ f" Shared by: {sharing_user.get('displayName', 'Unknown')} ({sharing_user.get('emailAddress', 'Unknown')})"
1784
+ )
1785
+
1786
+ # Process permissions (already resolved above as _perms_for_shared)
1787
+ permissions = _perms_for_shared
1788
+ if permissions:
1789
+ output_parts.append(f" Number of permissions: {len(permissions)}")
1790
+ output_parts.append(" Permissions:")
1791
+ for perm in permissions:
1792
+ output_parts.append(f" - {format_permission_info(perm)}")
1793
+ else:
1794
+ output_parts.append(" No additional permissions (private file)")
1795
+
1796
+ # Add URLs
1797
+ output_parts.extend(
1798
+ [
1799
+ "",
1800
+ "URLs:",
1801
+ f" View Link: {file_metadata.get('webViewLink', 'N/A')}",
1802
+ ]
1803
+ )
1804
+
1805
+ # webContentLink is only available for files that can be downloaded
1806
+ web_content_link = file_metadata.get("webContentLink")
1807
+ if web_content_link:
1808
+ output_parts.append(f" Direct Download Link: {web_content_link}")
1809
+
1810
+ has_public_link = check_public_link_permission(permissions)
1811
+
1812
+ if has_public_link:
1813
+ output_parts.extend(
1814
+ [
1815
+ "",
1816
+ "✅ This file is shared with 'Anyone with the link' - it can be inserted into Google Docs",
1817
+ ]
1818
+ )
1819
+ else:
1820
+ output_parts.extend(
1821
+ [
1822
+ "",
1823
+ "❌ This file is NOT shared with 'Anyone with the link' - it cannot be inserted into Google Docs",
1824
+ " To fix: Right-click the file in Google Drive → Share → Anyone with the link → Viewer",
1825
+ ]
1826
+ )
1827
+
1828
+ return "\n".join(output_parts)
1829
+
1830
+ except Exception as e:
1831
+ logger.error(f"Error getting file permissions: {e}")
1832
+ return f"Error getting file permissions: {e}"
1833
+
1834
+
1835
+ @server.tool(
1836
+ title="Check Drive File Public Access",
1837
+ annotations=ToolAnnotations(
1838
+ readOnlyHint=True,
1839
+ destructiveHint=False,
1840
+ idempotentHint=True,
1841
+ openWorldHint=True,
1842
+ ),
1843
+ )
1844
+ @handle_http_errors(
1845
+ "check_drive_file_public_access", is_read_only=True, service_type="drive"
1846
+ )
1847
+ @require_google_service("drive", "drive_read")
1848
+ async def check_drive_file_public_access(
1849
+ service,
1850
+ user_google_email: str,
1851
+ file_name: str,
1852
+ drive_id: Optional[str] = None,
1853
+ ) -> str:
1854
+ """
1855
+ Searches for a file by name and checks if it has public link sharing enabled.
1856
+
1857
+ Args:
1858
+ user_google_email (str): The user's Google email address. Required.
1859
+ file_name (str): The name of the file to check.
1860
+ drive_id (Optional[str]): ID of the shared drive to scope the search to. When set, the
1861
+ underlying files.list call uses corpora='drive' and the given
1862
+ driveId, which is required to reliably find files that live only
1863
+ in that shared drive. When None, behaviour is unchanged
1864
+ (default API corpora applies).
1865
+
1866
+ Returns:
1867
+ str: Information about the file's sharing status and whether it can be used in Google Docs.
1868
+ """
1869
+ logger.info(
1870
+ f"[check_drive_file_public_access] Invoked. "
1871
+ f"file_name_len={len(file_name) if file_name else 0}"
1872
+ + (f" within drive_id={drive_id}" if drive_id else "")
1873
+ )
1874
+ logger.debug(f"[check_drive_file_public_access] Searching for {file_name}")
1875
+
1876
+ # Search for the file
1877
+ escaped_name = escape_drive_query_value(file_name)
1878
+ query = f"name = '{escaped_name}'"
1879
+
1880
+ list_params: Dict[str, Any] = {
1881
+ "q": query,
1882
+ "pageSize": 10,
1883
+ "fields": "files(id, name, mimeType, webViewLink)",
1884
+ "supportsAllDrives": True,
1885
+ "includeItemsFromAllDrives": True,
1886
+ }
1887
+ if drive_id:
1888
+ list_params["corpora"] = "drive"
1889
+ list_params["driveId"] = drive_id
1890
+
1891
+ results = await asyncio.to_thread(service.files().list(**list_params).execute)
1892
+
1893
+ files = results.get("files", [])
1894
+ if not files:
1895
+ return f"No file found with name '{file_name}'"
1896
+
1897
+ if len(files) > 1:
1898
+ output_parts = [f"Found {len(files)} files with name '{file_name}':"]
1899
+ for f in files:
1900
+ output_parts.append(f" - {f['name']} (ID: {f['id']})")
1901
+ output_parts.append("\nChecking the first file...")
1902
+ output_parts.append("")
1903
+ else:
1904
+ output_parts = []
1905
+
1906
+ # Check permissions for the first file
1907
+ file_id = files[0]["id"]
1908
+ resolved_file_id, _ = await resolve_drive_item(service, file_id)
1909
+ file_id = resolved_file_id
1910
+
1911
+ # Get detailed permissions
1912
+ file_metadata = await asyncio.to_thread(
1913
+ service.files()
1914
+ .get(
1915
+ fileId=file_id,
1916
+ fields="id, name, mimeType, driveId, permissions, webViewLink, webContentLink, shared",
1917
+ supportsAllDrives=True,
1918
+ )
1919
+ .execute
1920
+ )
1921
+
1922
+ permissions = file_metadata.get("permissions", [])
1923
+ # Shared Drive items do not return inline permissions on files.get(); fall
1924
+ # back to permissions.list() so 'anyone with link' surfaces correctly.
1925
+ if file_metadata.get("driveId"):
1926
+ permissions = await asyncio.to_thread(list_all_permissions, service, file_id)
1927
+
1928
+ has_public_link = check_public_link_permission(permissions)
1929
+
1930
+ output_parts.extend(
1931
+ [
1932
+ f"File: {file_metadata['name']}",
1933
+ f"ID: {file_id}",
1934
+ f"Type: {file_metadata['mimeType']}",
1935
+ f"Shared: {derive_shared_state(file_metadata, permissions)}",
1936
+ "",
1937
+ ]
1938
+ )
1939
+
1940
+ if has_public_link:
1941
+ output_parts.extend(
1942
+ [
1943
+ "✅ PUBLIC ACCESS ENABLED - This file can be inserted into Google Docs",
1944
+ f"Use with insert_doc_image_url: {get_drive_image_url(file_id)}",
1945
+ ]
1946
+ )
1947
+ else:
1948
+ output_parts.extend(
1949
+ [
1950
+ "❌ NO PUBLIC ACCESS - Cannot insert into Google Docs",
1951
+ "Fix: Drive → Share → 'Anyone with the link' → 'Viewer'",
1952
+ ]
1953
+ )
1954
+
1955
+ return "\n".join(output_parts)
1956
+
1957
+
1958
+ @server.tool(
1959
+ title="Update Drive File",
1960
+ annotations=ToolAnnotations(
1961
+ readOnlyHint=False,
1962
+ destructiveHint=True,
1963
+ idempotentHint=False,
1964
+ openWorldHint=True,
1965
+ ),
1966
+ )
1967
+ @hide_local_file_args("file_path")
1968
+ @hide_remote_only_args("return_upload_url")
1969
+ @handle_http_errors("update_drive_file", is_read_only=False, service_type="drive")
1970
+ @require_google_service("drive", "drive_file")
1971
+ async def update_drive_file(
1972
+ service,
1973
+ user_google_email: str,
1974
+ file_id: str,
1975
+ # File metadata updates
1976
+ name: Optional[str] = None,
1977
+ description: Optional[str] = None,
1978
+ mime_type: Optional[str] = None,
1979
+ # Folder organization
1980
+ add_parents: Optional[str] = None, # Comma-separated folder IDs to add
1981
+ remove_parents: Optional[str] = None, # Comma-separated folder IDs to remove
1982
+ # File status
1983
+ starred: Optional[bool] = None,
1984
+ trashed: Optional[bool] = None,
1985
+ # Sharing and permissions
1986
+ writers_can_share: Optional[bool] = None,
1987
+ copy_requires_writer_permission: Optional[bool] = None,
1988
+ # Custom properties
1989
+ properties: Optional[dict] = None, # User-visible custom properties
1990
+ # Content replacement (re-import with format conversion, preserving the file ID)
1991
+ content: Optional[str] = None, # Text content (markdown, TXT, HTML)
1992
+ file_path: Optional[str] = None, # Local file path (DOCX, ODT, etc.)
1993
+ file_url: Optional[str] = None, # Remote URL to fetch content from
1994
+ source_format: Optional[str] = None, # Format hint (md, docx, txt, html, rtf, odt)
1995
+ mode: str = "replace", # replace | append | prepend
1996
+ return_upload_url: bool = False,
1997
+ ) -> str:
1998
+ """
1999
+ Updates metadata, properties, and/or content of a Google Drive file.
2000
+
2001
+ Providing new content (inline as ``content``, fetched from ``file_url``, or on a
2002
+ local server read from a file path) replaces the file's content in place,
2003
+ preserving the existing file ID, sharing, comments, and links.
2004
+ For native Google Docs/Sheets/Slides the source is uploaded with its source MIME
2005
+ type so the Drive API applies the same format conversion as import_to_google_doc
2006
+ (markdown headings, tables, bold, etc.). For any other file (.md, .txt, .pdf, ...)
2007
+ there is nothing to convert, so the bytes are written back as-is under the file's
2008
+ own MIME type. Metadata and content can be updated in a single call.
2009
+
2010
+ ``mode='append'``/``'prepend'`` splice ``content`` onto the file's existing text
2011
+ server-side, so only the new text has to be supplied — no need to send the whole
2012
+ file back to rewrite it.
2013
+
2014
+ Drive shortcuts are handled according to the kind of update: supported
2015
+ resource-local metadata changes (rename, move, trash, star, description, and
2016
+ custom properties) apply to the supplied shortcut, while content replacement
2017
+ follows the shortcut and updates its target. To avoid applying metadata to the
2018
+ wrong resource, a shortcut call cannot combine content with resource-local
2019
+ metadata. Update the shortcut metadata and target content in separate calls.
2020
+
2021
+ Args:
2022
+ user_google_email (str): The user's Google email address. Required.
2023
+ file_id (str): The ID of the file to update. Required.
2024
+ name (Optional[str]): New name for the file.
2025
+ description (Optional[str]): New description for the file.
2026
+ mime_type (Optional[str]): New MIME type (note: changing type may require
2027
+ content upload). For a shortcut ID, this must accompany content and applies
2028
+ to the resolved target.
2029
+ add_parents (Optional[str]): Comma-separated folder IDs to add as parents.
2030
+ remove_parents (Optional[str]): Comma-separated folder IDs to remove from parents.
2031
+ starred (Optional[bool]): Whether to star/unstar the file.
2032
+ trashed (Optional[bool]): Whether to move file to/from trash.
2033
+ writers_can_share (Optional[bool]): Whether editors can share the file. Pass the
2034
+ target ID directly; this cannot be changed on a shortcut resource.
2035
+ copy_requires_writer_permission (Optional[bool]): Whether copying requires writer
2036
+ permission. Pass the target ID directly; this cannot be changed on a
2037
+ shortcut resource.
2038
+ properties (Optional[dict]): Custom key-value properties for the file.
2039
+ content (Optional[str]): New text content for text-based formats (markdown, TXT, HTML).
2040
+ file_path (Optional[str]): Local file path for binary formats (DOCX, ODT). Supports file:// URLs.
2041
+ file_url (Optional[str]): Remote http(s) URL to fetch new content from.
2042
+ source_format (Optional[str]): Source format hint for conversion
2043
+ (md, markdown, docx, txt, html, rtf, odt). Auto-detected when omitted, and
2044
+ ignored for non-Google files, which are uploaded without conversion.
2045
+ Provide at most one content source.
2046
+ mode (str): How to apply the new content — 'replace' (default), 'append', or
2047
+ 'prepend'. Append/prepend require 'content' and a UTF-8 text file such as
2048
+ .md or .txt; a newline is inserted at the seam if neither side has one.
2049
+ For native Google Docs use insert_doc_elements, modify_doc_text, or
2050
+ find_and_replace_doc, which edit in place instead of rewriting the file.
2051
+ return_upload_url (bool): Return a Google resumable-upload session URL to
2052
+ PUT the replacement bytes to directly (no Authorization header); any
2053
+ metadata changes take effect with the upload. Only with
2054
+ mode='replace'; not combinable with another content source. Here
2055
+ mime_type names the MIME type of the bytes to be uploaded; on a native
2056
+ Google file it is required, names only that, and leaves the file's type
2057
+ untouched. Offered only where local file access is disabled.
2058
+
2059
+ Returns:
2060
+ str: Confirmation message with details of the updates applied, or the
2061
+ resumable upload URL.
2062
+ """
2063
+ logger.info(f"[update_drive_file] Updating file {file_id} for {user_google_email}")
2064
+
2065
+ if mode not in CONTENT_UPDATE_MODES:
2066
+ raise ValueError(
2067
+ f"Unsupported mode: '{mode}'. Supported: {', '.join(CONTENT_UPDATE_MODES)}."
2068
+ )
2069
+ if return_upload_url:
2070
+ if local_file_access_enabled():
2071
+ raise upload_url_not_offered_error(("file_path", "content"))
2072
+ if mode != "replace":
2073
+ raise ValueError(
2074
+ "return_upload_url replaces the file's whole content; it cannot be "
2075
+ f"combined with mode='{mode}'."
2076
+ )
2077
+ reject_sources_with_upload_url(
2078
+ "replaces the content",
2079
+ content=content,
2080
+ file_path=file_path,
2081
+ file_url=file_url,
2082
+ source_format=source_format,
2083
+ )
2084
+ if mime_type is not None:
2085
+ mime_type = mime_type.strip().lower() or None
2086
+ if mode != "replace" and mime_type is not None:
2087
+ raise ValueError(f"mime_type cannot be set when mode='{mode}'.")
2088
+ if mode != "replace" and content is None:
2089
+ raise ValueError(
2090
+ f"mode='{mode}' requires 'content' (the text to add); other content "
2091
+ "sources are only supported with mode='replace'."
2092
+ )
2093
+
2094
+ replacing_content = return_upload_url or any(
2095
+ x is not None for x in (content, file_path, file_url)
2096
+ )
2097
+ current_file_fields = (
2098
+ "name, description, mimeType, parents, starred, trashed, webViewLink, "
2099
+ "writersCanShare, copyRequiresWriterPermission, properties"
2100
+ )
2101
+ supplied_file_id = file_id
2102
+ resolved_file_id, current_file = await resolve_drive_item(
2103
+ service,
2104
+ supplied_file_id,
2105
+ extra_fields=current_file_fields,
2106
+ # Inspect the supplied resource before deciding whether a content update may
2107
+ # safely follow a shortcut. This prevents metadata in a mixed call from being
2108
+ # silently applied to the shortcut target.
2109
+ follow_shortcuts=False,
2110
+ )
2111
+ supplied_file_is_shortcut = current_file.get("mimeType") == SHORTCUT_MIME_TYPE
2112
+
2113
+ if supplied_file_is_shortcut:
2114
+ resource_local_updates = [
2115
+ field
2116
+ for field, requested in (
2117
+ ("name", name is not None),
2118
+ ("description", description is not None),
2119
+ ("add_parents", bool(add_parents)),
2120
+ ("remove_parents", bool(remove_parents)),
2121
+ ("starred", starred is not None),
2122
+ ("trashed", trashed is not None),
2123
+ ("writers_can_share", writers_can_share is not None),
2124
+ (
2125
+ "copy_requires_writer_permission",
2126
+ copy_requires_writer_permission is not None,
2127
+ ),
2128
+ ("properties", properties is not None),
2129
+ )
2130
+ if requested
2131
+ ]
2132
+ if replacing_content and resource_local_updates:
2133
+ raise ValueError(
2134
+ "Content and shortcut-local metadata cannot be updated in one call "
2135
+ f"({', '.join(resource_local_updates)}). Update the shortcut metadata "
2136
+ "and target content in separate calls."
2137
+ )
2138
+
2139
+ unsupported_shortcut_updates = [
2140
+ field
2141
+ for field, requested in (
2142
+ ("mime_type", mime_type is not None and not replacing_content),
2143
+ ("writers_can_share", writers_can_share is not None),
2144
+ (
2145
+ "copy_requires_writer_permission",
2146
+ copy_requires_writer_permission is not None,
2147
+ ),
2148
+ )
2149
+ if requested
2150
+ ]
2151
+ if unsupported_shortcut_updates:
2152
+ raise ValueError(
2153
+ "These fields cannot be updated on a Drive shortcut: "
2154
+ f"{', '.join(unsupported_shortcut_updates)}. Pass the target file ID "
2155
+ "to change target MIME or permission controls."
2156
+ )
2157
+
2158
+ if replacing_content:
2159
+ resolved_file_id, current_file = await resolve_drive_item(
2160
+ service,
2161
+ supplied_file_id,
2162
+ extra_fields=current_file_fields,
2163
+ follow_shortcuts=True,
2164
+ )
2165
+ file_id = resolved_file_id
2166
+
2167
+ # Build the update body with only specified fields
2168
+ update_body = {}
2169
+ if name is not None:
2170
+ update_body["name"] = name
2171
+ if description is not None:
2172
+ update_body["description"] = description
2173
+ if mime_type is not None:
2174
+ update_body["mimeType"] = mime_type
2175
+ if starred is not None:
2176
+ update_body["starred"] = starred
2177
+ if trashed is not None:
2178
+ update_body["trashed"] = trashed
2179
+ if writers_can_share is not None:
2180
+ update_body["writersCanShare"] = writers_can_share
2181
+ if copy_requires_writer_permission is not None:
2182
+ update_body["copyRequiresWriterPermission"] = copy_requires_writer_permission
2183
+ if properties is not None:
2184
+ update_body["properties"] = properties
2185
+
2186
+ async def _resolve_parent_arguments(parent_arg: Optional[str]) -> Optional[str]:
2187
+ if not parent_arg:
2188
+ return None
2189
+ parent_ids = [part.strip() for part in parent_arg.split(",") if part.strip()]
2190
+ if not parent_ids:
2191
+ return None
2192
+
2193
+ resolved_ids = []
2194
+ for parent in parent_ids:
2195
+ resolved_parent = await resolve_folder_id(service, parent)
2196
+ resolved_ids.append(resolved_parent)
2197
+ return ",".join(resolved_ids)
2198
+
2199
+ resolved_add_parents = await _resolve_parent_arguments(add_parents)
2200
+ resolved_remove_parents = await _resolve_parent_arguments(remove_parents)
2201
+
2202
+ # Build query parameters for parent changes
2203
+ query_params = {
2204
+ "fileId": file_id,
2205
+ "supportsAllDrives": True,
2206
+ "fields": "id, name, description, mimeType, parents, starred, trashed, webViewLink, writersCanShare, copyRequiresWriterPermission, properties",
2207
+ }
2208
+
2209
+ if resolved_add_parents:
2210
+ query_params["addParents"] = resolved_add_parents
2211
+ if resolved_remove_parents:
2212
+ query_params["removeParents"] = resolved_remove_parents
2213
+
2214
+ # Only include body if there are updates
2215
+ if update_body:
2216
+ query_params["body"] = update_body
2217
+
2218
+ if return_upload_url:
2219
+ current_mime = current_file.get("mimeType") or ""
2220
+ format_map = native_replace_format_map(current_mime)
2221
+ if format_map is not None:
2222
+ # mime_type names the uploaded bytes here; Drive rejects a metadata
2223
+ # mimeType change on a native file.
2224
+ update_body.pop("mimeType", None)
2225
+ upload_mime = mime_type or current_mime or "application/octet-stream"
2226
+ if upload_mime.startswith(GOOGLE_APPS_MIME_PREFIX):
2227
+ raise ValueError(
2228
+ f"This file is a native Google type ({upload_mime}); pass mime_type "
2229
+ "with the MIME type of the bytes you will upload (e.g. 'text/markdown') "
2230
+ "so Drive knows what it is converting from."
2231
+ )
2232
+ if format_map is not None and upload_mime not in format_map.values():
2233
+ raise ValueError(
2234
+ f"Unsupported mime_type for a {current_mime} upload: '{upload_mime}'. "
2235
+ f"Supported: {', '.join(dict.fromkeys(format_map.values()))}."
2236
+ )
2237
+ upload_url = await initiate_resumable_upload_session(
2238
+ service,
2239
+ upload_mime_type=upload_mime,
2240
+ file_metadata=update_body,
2241
+ file_id=file_id,
2242
+ query={
2243
+ k: query_params[k]
2244
+ for k in ("addParents", "removeParents")
2245
+ if k in query_params
2246
+ },
2247
+ )
2248
+ logger.info(f"[update_drive_file] Returned resumable upload URL for {file_id}.")
2249
+ return resumable_upload_result(
2250
+ "Resumable upload session created to replace the content of "
2251
+ f"'{current_file.get('name', file_id)}' (ID {file_id}, for {user_google_email}).",
2252
+ upload_url,
2253
+ upload_mime,
2254
+ )
2255
+
2256
+ # Native Google files take replacement content through Drive's import conversion
2257
+ # (the engine import_to_google_doc uses); any other file has nothing to convert,
2258
+ # so its bytes stream back verbatim under the same file ID.
2259
+ remote_file_data = None
2260
+ format_map = None
2261
+ content_update_lock = (
2262
+ _get_content_update_lock(file_id) if replacing_content else None
2263
+ )
2264
+ if content_update_lock is not None:
2265
+ await content_update_lock.acquire()
2266
+ try:
2267
+ if replacing_content:
2268
+ target_mime_type = mime_type or current_file.get("mimeType") or ""
2269
+ format_map = native_replace_format_map(target_mime_type)
2270
+
2271
+ if mode != "replace":
2272
+ if format_map is not None:
2273
+ raise ValueError(
2274
+ f"mode='{mode}' is only supported for non-Google files, because a "
2275
+ f"native {target_mime_type} would have to be exported and re-imported "
2276
+ "to splice text in. Use insert_doc_elements, modify_doc_text, or "
2277
+ "find_and_replace_doc to edit a Google Doc in place."
2278
+ )
2279
+ existing_bytes = await _download_file_bytes(service, file_id)
2280
+ try:
2281
+ existing_text = existing_bytes.decode("utf-8")
2282
+ except UnicodeDecodeError as exc:
2283
+ raise ValueError(
2284
+ f"mode='{mode}' requires a UTF-8 text file, but "
2285
+ f"'{current_file.get('name', file_id)}' ({target_mime_type}) "
2286
+ "could not be decoded as text."
2287
+ ) from exc
2288
+ content = _splice_content(existing_text, content, mode)
2289
+
2290
+ media, _source_mime_type, remote_file_data = await _resolve_import_media(
2291
+ tool_name="update_drive_file",
2292
+ file_name=name or current_file.get("name", ""),
2293
+ content=content,
2294
+ file_path=file_path,
2295
+ file_url=file_url,
2296
+ source_format=source_format,
2297
+ format_map=format_map,
2298
+ passthrough_mime_type=(
2299
+ None
2300
+ if format_map
2301
+ else (target_mime_type or "application/octet-stream")
2302
+ ),
2303
+ upload_type_param="mime_type",
2304
+ )
2305
+ query_params["media_body"] = media
2306
+
2307
+ # Perform the update while append/prepend still hold the file lock.
2308
+ updated_file = await asyncio.to_thread(
2309
+ service.files().update(**query_params).execute,
2310
+ num_retries=GOOGLE_API_WRITE_RETRIES if replacing_content else 0,
2311
+ )
2312
+ finally:
2313
+ if remote_file_data is not None:
2314
+ remote_file_data.close()
2315
+ if content_update_lock is not None:
2316
+ content_update_lock.release()
2317
+
2318
+ # Build response message
2319
+ output_parts = [
2320
+ f"✅ Successfully updated file: {updated_file.get('name', current_file['name'])}"
2321
+ ]
2322
+ output_parts.append(f" File ID: {file_id}")
2323
+
2324
+ # Report what changed
2325
+ changes = []
2326
+ if name is not None and name != current_file.get("name"):
2327
+ changes.append(f" • Name: '{current_file.get('name')}' → '{name}'")
2328
+ if description is not None:
2329
+ old_desc_value = current_file.get("description")
2330
+ new_desc_value = description
2331
+ should_report_change = (old_desc_value or "") != (new_desc_value or "")
2332
+ if should_report_change:
2333
+ old_desc_display = (
2334
+ old_desc_value if old_desc_value not in (None, "") else "(empty)"
2335
+ )
2336
+ new_desc_display = (
2337
+ new_desc_value if new_desc_value not in (None, "") else "(empty)"
2338
+ )
2339
+ changes.append(f" • Description: {old_desc_display} → {new_desc_display}")
2340
+ if add_parents:
2341
+ changes.append(f" • Added to folder(s): {add_parents}")
2342
+ if remove_parents:
2343
+ changes.append(f" • Removed from folder(s): {remove_parents}")
2344
+ current_starred = current_file.get("starred")
2345
+ if starred is not None and starred != current_starred:
2346
+ star_status = "starred" if starred else "unstarred"
2347
+ changes.append(f" • File {star_status}")
2348
+ current_trashed = current_file.get("trashed")
2349
+ if trashed is not None and trashed != current_trashed:
2350
+ trash_status = "moved to trash" if trashed else "restored from trash"
2351
+ changes.append(f" • File {trash_status}")
2352
+ current_writers_can_share = current_file.get("writersCanShare")
2353
+ if writers_can_share is not None and writers_can_share != current_writers_can_share:
2354
+ share_status = "can" if writers_can_share else "cannot"
2355
+ changes.append(f" • Writers {share_status} share the file")
2356
+ current_copy_requires_writer_permission = current_file.get(
2357
+ "copyRequiresWriterPermission"
2358
+ )
2359
+ if (
2360
+ copy_requires_writer_permission is not None
2361
+ and copy_requires_writer_permission != current_copy_requires_writer_permission
2362
+ ):
2363
+ copy_status = (
2364
+ "requires" if copy_requires_writer_permission else "doesn't require"
2365
+ )
2366
+ changes.append(f" • Copying {copy_status} writer permission")
2367
+ if properties:
2368
+ changes.append(f" • Updated custom properties: {properties}")
2369
+ if replacing_content:
2370
+ result_mime_type = updated_file.get(
2371
+ "mimeType", current_file.get("mimeType", "file type")
2372
+ )
2373
+ written_as = "converted to" if format_map else "written as"
2374
+ if mode == "replace":
2375
+ source = "content" if content is not None else (file_path or file_url)
2376
+ detail = f"Replaced content from {source}"
2377
+ else:
2378
+ detail = f"{'Appended' if mode == 'append' else 'Prepended'} text"
2379
+ changes.append(f" • {detail} ({written_as} {result_mime_type})")
2380
+
2381
+ if changes:
2382
+ output_parts.append("")
2383
+ output_parts.append("Changes applied:")
2384
+ output_parts.extend(changes)
2385
+ else:
2386
+ output_parts.append(" (No changes were made)")
2387
+
2388
+ output_parts.append("")
2389
+ output_parts.append(f"View file: {updated_file.get('webViewLink', '#')}")
2390
+
2391
+ return "\n".join(output_parts)
2392
+
2393
+
2394
+ @server.tool(
2395
+ title="Get Drive Shareable Link",
2396
+ annotations=ToolAnnotations(
2397
+ readOnlyHint=True,
2398
+ destructiveHint=False,
2399
+ idempotentHint=True,
2400
+ openWorldHint=True,
2401
+ ),
2402
+ )
2403
+ @handle_http_errors("get_drive_shareable_link", is_read_only=True, service_type="drive")
2404
+ @require_google_service("drive", "drive_read")
2405
+ async def get_drive_shareable_link(
2406
+ service,
2407
+ user_google_email: str,
2408
+ file_id: str,
2409
+ ) -> str:
2410
+ """
2411
+ Gets the shareable link for a Google Drive file or folder.
2412
+
2413
+ Args:
2414
+ user_google_email (str): The user's Google email address. Required.
2415
+ file_id (str): The ID of the file or folder to get the shareable link for. Required.
2416
+
2417
+ Returns:
2418
+ str: The shareable links and current sharing status.
2419
+ """
2420
+ logger.info(
2421
+ f"[get_drive_shareable_link] Invoked. Email: '{user_google_email}', File ID: '{file_id}'"
2422
+ )
2423
+
2424
+ resolved_file_id, _ = await resolve_drive_item(service, file_id)
2425
+ file_id = resolved_file_id
2426
+
2427
+ file_metadata = await asyncio.to_thread(
2428
+ service.files()
2429
+ .get(
2430
+ fileId=file_id,
2431
+ fields="id, name, mimeType, webViewLink, webContentLink, shared, "
2432
+ "permissions(id, type, role, emailAddress, domain, expirationTime)",
2433
+ supportsAllDrives=True,
2434
+ )
2435
+ .execute
2436
+ )
2437
+
2438
+ output_parts = [
2439
+ f"File: {file_metadata.get('name', 'Unknown')}",
2440
+ f"ID: {file_id}",
2441
+ f"Type: {file_metadata.get('mimeType', 'Unknown')}",
2442
+ f"Shared: {file_metadata.get('shared', False)}",
2443
+ "",
2444
+ "Links:",
2445
+ f" View: {file_metadata.get('webViewLink', 'N/A')}",
2446
+ ]
2447
+
2448
+ web_content_link = file_metadata.get("webContentLink")
2449
+ if web_content_link:
2450
+ output_parts.append(f" Download: {web_content_link}")
2451
+
2452
+ permissions = file_metadata.get("permissions", [])
2453
+ if permissions:
2454
+ output_parts.append("")
2455
+ output_parts.append("Current permissions:")
2456
+ for perm in permissions:
2457
+ output_parts.append(f" - {format_permission_info(perm)}")
2458
+
2459
+ return "\n".join(output_parts)
2460
+
2461
+
2462
+ @server.tool(
2463
+ title="Manage Drive Access",
2464
+ annotations=ToolAnnotations(
2465
+ readOnlyHint=False,
2466
+ destructiveHint=True,
2467
+ idempotentHint=False,
2468
+ openWorldHint=True,
2469
+ ),
2470
+ )
2471
+ @handle_http_errors("manage_drive_access", is_read_only=False, service_type="drive")
2472
+ @require_google_service("drive", "drive_file")
2473
+ async def manage_drive_access(
2474
+ service,
2475
+ user_google_email: str,
2476
+ file_id: str,
2477
+ action: str,
2478
+ share_with: Optional[str] = None,
2479
+ role: Optional[str] = None,
2480
+ share_type: str = "user",
2481
+ permission_id: Optional[str] = None,
2482
+ recipients: Optional[List[Dict[str, Any]]] = None,
2483
+ send_notification: bool = True,
2484
+ email_message: Optional[str] = None,
2485
+ expiration_time: Optional[str] = None,
2486
+ allow_file_discovery: Optional[bool] = None,
2487
+ new_owner_email: Optional[str] = None,
2488
+ move_to_new_owners_root: bool = False,
2489
+ ) -> str:
2490
+ """
2491
+ Consolidated tool for managing Google Drive file and folder access permissions.
2492
+
2493
+ Supports granting, batch-granting, updating, revoking permissions, and
2494
+ transferring file ownership -- all through a single entry point.
2495
+
2496
+ Args:
2497
+ user_google_email (str): The user's Google email address. Required.
2498
+ file_id (str): The ID of the file or folder. Required.
2499
+ action (str): The access management action to perform. Required. One of:
2500
+ - "grant": Share with a single user, group, domain, or anyone.
2501
+ - "grant_batch": Share with multiple recipients in one call.
2502
+ - "update": Modify an existing permission (role or expiration).
2503
+ - "revoke": Remove an existing permission.
2504
+ - "transfer_owner": Transfer file ownership to another user.
2505
+ share_with (Optional[str]): Email address (user/group), domain name (domain),
2506
+ or omit for 'anyone'. Used by "grant".
2507
+ role (Optional[str]): Permission role -- 'reader', 'commenter', or 'writer'.
2508
+ Used by "grant" (defaults to 'reader') and "update".
2509
+ share_type (str): Type of sharing -- 'user', 'group', 'domain', or 'anyone'.
2510
+ Used by "grant". Defaults to 'user'.
2511
+ permission_id (Optional[str]): The permission ID to modify or remove.
2512
+ Required for "update" and "revoke" actions.
2513
+ recipients (Optional[List[Dict[str, Any]]]): List of recipient objects for
2514
+ "grant_batch". Each should have: email (str), role (str, optional),
2515
+ share_type (str, optional), expiration_time (str, optional). For domain
2516
+ shares use 'domain' field instead of 'email'.
2517
+ send_notification (bool): Whether to send notification emails. Defaults to True.
2518
+ Used by "grant" and "grant_batch".
2519
+ email_message (Optional[str]): Custom notification email message.
2520
+ Used by "grant" and "grant_batch".
2521
+ expiration_time (Optional[str]): Expiration in RFC 3339 format
2522
+ (e.g., "2025-01-15T00:00:00Z"). Used by "grant" and "update".
2523
+ allow_file_discovery (Optional[bool]): For 'domain'/'anyone' shares, whether
2524
+ the file appears in search. Used by "grant".
2525
+ new_owner_email (Optional[str]): Email of the new owner.
2526
+ Required for "transfer_owner".
2527
+ move_to_new_owners_root (bool): Move file to the new owner's My Drive root.
2528
+ Defaults to False. Used by "transfer_owner".
2529
+
2530
+ Returns:
2531
+ str: Confirmation with details of the permission change applied.
2532
+ """
2533
+ valid_actions = ("grant", "grant_batch", "update", "revoke", "transfer_owner")
2534
+ if action not in valid_actions:
2535
+ raise ValueError(
2536
+ f"Invalid action '{action}'. Must be one of: {', '.join(valid_actions)}"
2537
+ )
2538
+
2539
+ logger.info(
2540
+ f"[manage_drive_access] Invoked. Email: '{user_google_email}', "
2541
+ f"File ID: '{file_id}', Action: '{action}'"
2542
+ )
2543
+
2544
+ # --- grant: share with a single recipient ---
2545
+ if action == "grant":
2546
+ effective_role = role or "reader"
2547
+ validate_share_role(effective_role)
2548
+ validate_share_type(share_type)
2549
+
2550
+ if share_type in ("user", "group") and not share_with:
2551
+ raise ValueError(f"share_with is required for share_type '{share_type}'")
2552
+ if share_type == "domain" and not share_with:
2553
+ raise ValueError(
2554
+ "share_with (domain name) is required for share_type 'domain'"
2555
+ )
2556
+
2557
+ resolved_file_id, file_metadata = await resolve_drive_item(
2558
+ service, file_id, extra_fields="name, webViewLink"
2559
+ )
2560
+ file_id = resolved_file_id
2561
+
2562
+ permission_body: Dict[str, Any] = {
2563
+ "type": share_type,
2564
+ "role": effective_role,
2565
+ }
2566
+ if share_type in ("user", "group"):
2567
+ permission_body["emailAddress"] = share_with
2568
+ elif share_type == "domain":
2569
+ permission_body["domain"] = share_with
2570
+
2571
+ if expiration_time:
2572
+ validate_expiration_time(expiration_time)
2573
+ permission_body["expirationTime"] = expiration_time
2574
+
2575
+ if share_type in ("domain", "anyone") and allow_file_discovery is not None:
2576
+ permission_body["allowFileDiscovery"] = allow_file_discovery
2577
+
2578
+ create_params: Dict[str, Any] = {
2579
+ "fileId": file_id,
2580
+ "body": permission_body,
2581
+ "supportsAllDrives": True,
2582
+ "fields": "id, type, role, emailAddress, domain, expirationTime",
2583
+ }
2584
+ if share_type in ("user", "group"):
2585
+ create_params["sendNotificationEmail"] = send_notification
2586
+ if email_message:
2587
+ create_params["emailMessage"] = email_message
2588
+
2589
+ created_permission = await asyncio.to_thread(
2590
+ service.permissions().create(**create_params).execute
2591
+ )
2592
+
2593
+ return "\n".join(
2594
+ [
2595
+ f"Successfully shared '{file_metadata.get('name', 'Unknown')}'",
2596
+ "",
2597
+ "Permission created:",
2598
+ f" - {format_permission_info(created_permission)}",
2599
+ "",
2600
+ f"View link: {file_metadata.get('webViewLink', 'N/A')}",
2601
+ ]
2602
+ )
2603
+
2604
+ # --- grant_batch: share with multiple recipients ---
2605
+ if action == "grant_batch":
2606
+ if not recipients:
2607
+ raise ValueError("recipients list is required for 'grant_batch' action")
2608
+
2609
+ resolved_file_id, file_metadata = await resolve_drive_item(
2610
+ service, file_id, extra_fields="name, webViewLink"
2611
+ )
2612
+ file_id = resolved_file_id
2613
+
2614
+ results: List[str] = []
2615
+ success_count = 0
2616
+ failure_count = 0
2617
+
2618
+ for recipient in recipients:
2619
+ r_share_type = recipient.get("share_type", "user")
2620
+
2621
+ if r_share_type == "domain":
2622
+ domain = recipient.get("domain")
2623
+ if not domain:
2624
+ results.append(" - Skipped: missing domain for domain share")
2625
+ failure_count += 1
2626
+ continue
2627
+ identifier = domain
2628
+ else:
2629
+ r_email = recipient.get("email")
2630
+ if not r_email:
2631
+ results.append(" - Skipped: missing email address")
2632
+ failure_count += 1
2633
+ continue
2634
+ identifier = r_email
2635
+
2636
+ r_role = recipient.get("role", "reader")
2637
+ try:
2638
+ validate_share_role(r_role)
2639
+ except ValueError as e:
2640
+ results.append(f" - {identifier}: Failed - {e}")
2641
+ failure_count += 1
2642
+ continue
2643
+
2644
+ try:
2645
+ validate_share_type(r_share_type)
2646
+ except ValueError as e:
2647
+ results.append(f" - {identifier}: Failed - {e}")
2648
+ failure_count += 1
2649
+ continue
2650
+
2651
+ r_perm_body: Dict[str, Any] = {
2652
+ "type": r_share_type,
2653
+ "role": r_role,
2654
+ }
2655
+ if r_share_type == "domain":
2656
+ r_perm_body["domain"] = identifier
2657
+ else:
2658
+ r_perm_body["emailAddress"] = identifier
2659
+
2660
+ if recipient.get("expiration_time"):
2661
+ try:
2662
+ validate_expiration_time(recipient["expiration_time"])
2663
+ r_perm_body["expirationTime"] = recipient["expiration_time"]
2664
+ except ValueError as e:
2665
+ results.append(f" - {identifier}: Failed - {e}")
2666
+ failure_count += 1
2667
+ continue
2668
+
2669
+ r_create_params: Dict[str, Any] = {
2670
+ "fileId": file_id,
2671
+ "body": r_perm_body,
2672
+ "supportsAllDrives": True,
2673
+ "fields": "id, type, role, emailAddress, domain, expirationTime",
2674
+ }
2675
+ if r_share_type in ("user", "group"):
2676
+ r_create_params["sendNotificationEmail"] = send_notification
2677
+ if email_message:
2678
+ r_create_params["emailMessage"] = email_message
2679
+
2680
+ try:
2681
+ created_perm = await asyncio.to_thread(
2682
+ service.permissions().create(**r_create_params).execute
2683
+ )
2684
+ results.append(f" - {format_permission_info(created_perm)}")
2685
+ success_count += 1
2686
+ except HttpError as e:
2687
+ results.append(f" - {identifier}: Failed - {str(e)}")
2688
+ failure_count += 1
2689
+
2690
+ output_parts = [
2691
+ f"Batch share results for '{file_metadata.get('name', 'Unknown')}'",
2692
+ "",
2693
+ f"Summary: {success_count} succeeded, {failure_count} failed",
2694
+ "",
2695
+ "Results:",
2696
+ ]
2697
+ output_parts.extend(results)
2698
+ output_parts.extend(
2699
+ [
2700
+ "",
2701
+ f"View link: {file_metadata.get('webViewLink', 'N/A')}",
2702
+ ]
2703
+ )
2704
+ return "\n".join(output_parts)
2705
+
2706
+ # --- update: modify an existing permission ---
2707
+ if action == "update":
2708
+ if not permission_id:
2709
+ raise ValueError("permission_id is required for 'update' action")
2710
+ if not role and not expiration_time:
2711
+ raise ValueError(
2712
+ "Must provide at least one of: role, expiration_time for 'update' action"
2713
+ )
2714
+
2715
+ if role:
2716
+ validate_share_role(role)
2717
+ if expiration_time:
2718
+ validate_expiration_time(expiration_time)
2719
+
2720
+ resolved_file_id, file_metadata = await resolve_drive_item(
2721
+ service, file_id, extra_fields="name"
2722
+ )
2723
+ file_id = resolved_file_id
2724
+
2725
+ effective_role = role
2726
+ if not effective_role:
2727
+ current_permission = await asyncio.to_thread(
2728
+ service.permissions()
2729
+ .get(
2730
+ fileId=file_id,
2731
+ permissionId=permission_id,
2732
+ supportsAllDrives=True,
2733
+ fields="role",
2734
+ )
2735
+ .execute
2736
+ )
2737
+ effective_role = current_permission.get("role")
2738
+
2739
+ update_body: Dict[str, Any] = {"role": effective_role}
2740
+ if expiration_time:
2741
+ update_body["expirationTime"] = expiration_time
2742
+
2743
+ updated_permission = await asyncio.to_thread(
2744
+ service.permissions()
2745
+ .update(
2746
+ fileId=file_id,
2747
+ permissionId=permission_id,
2748
+ body=update_body,
2749
+ supportsAllDrives=True,
2750
+ fields="id, type, role, emailAddress, domain, expirationTime",
2751
+ )
2752
+ .execute
2753
+ )
2754
+
2755
+ return "\n".join(
2756
+ [
2757
+ f"Successfully updated permission on '{file_metadata.get('name', 'Unknown')}'",
2758
+ "",
2759
+ "Updated permission:",
2760
+ f" - {format_permission_info(updated_permission)}",
2761
+ ]
2762
+ )
2763
+
2764
+ # --- revoke: remove an existing permission ---
2765
+ if action == "revoke":
2766
+ if not permission_id:
2767
+ raise ValueError("permission_id is required for 'revoke' action")
2768
+
2769
+ resolved_file_id, file_metadata = await resolve_drive_item(
2770
+ service, file_id, extra_fields="name"
2771
+ )
2772
+ file_id = resolved_file_id
2773
+
2774
+ await asyncio.to_thread(
2775
+ service.permissions()
2776
+ .delete(
2777
+ fileId=file_id,
2778
+ permissionId=permission_id,
2779
+ supportsAllDrives=True,
2780
+ )
2781
+ .execute
2782
+ )
2783
+
2784
+ return "\n".join(
2785
+ [
2786
+ f"Successfully removed permission from '{file_metadata.get('name', 'Unknown')}'",
2787
+ "",
2788
+ f"Permission ID '{permission_id}' has been revoked.",
2789
+ ]
2790
+ )
2791
+
2792
+ # --- transfer_owner: transfer file ownership ---
2793
+ # action == "transfer_owner"
2794
+ if not new_owner_email:
2795
+ raise ValueError("new_owner_email is required for 'transfer_owner' action")
2796
+
2797
+ resolved_file_id, file_metadata = await resolve_drive_item(
2798
+ service, file_id, extra_fields="name, owners"
2799
+ )
2800
+ file_id = resolved_file_id
2801
+
2802
+ current_owners = file_metadata.get("owners", [])
2803
+ current_owner_emails = [o.get("emailAddress", "") for o in current_owners]
2804
+
2805
+ transfer_body: Dict[str, Any] = {
2806
+ "type": "user",
2807
+ "role": "owner",
2808
+ "emailAddress": new_owner_email,
2809
+ }
2810
+
2811
+ await asyncio.to_thread(
2812
+ service.permissions()
2813
+ .create(
2814
+ fileId=file_id,
2815
+ body=transfer_body,
2816
+ transferOwnership=True,
2817
+ moveToNewOwnersRoot=move_to_new_owners_root,
2818
+ supportsAllDrives=True,
2819
+ fields="id, type, role, emailAddress",
2820
+ )
2821
+ .execute
2822
+ )
2823
+
2824
+ output_parts = [
2825
+ f"Successfully transferred ownership of '{file_metadata.get('name', 'Unknown')}'",
2826
+ "",
2827
+ f"New owner: {new_owner_email}",
2828
+ f"Previous owner(s): {', '.join(current_owner_emails) or 'Unknown'}",
2829
+ ]
2830
+ if move_to_new_owners_root:
2831
+ output_parts.append(f"File moved to {new_owner_email}'s My Drive root.")
2832
+ output_parts.extend(["", "Note: Previous owner now has editor access."])
2833
+
2834
+ return "\n".join(output_parts)
2835
+
2836
+
2837
+ @server.tool(
2838
+ title="Copy Drive File",
2839
+ annotations=ToolAnnotations(
2840
+ readOnlyHint=False,
2841
+ destructiveHint=False,
2842
+ idempotentHint=False,
2843
+ openWorldHint=True,
2844
+ ),
2845
+ )
2846
+ @handle_http_errors("copy_drive_file", is_read_only=False, service_type="drive")
2847
+ @require_google_service("drive", "drive_file")
2848
+ async def copy_drive_file(
2849
+ service,
2850
+ user_google_email: str,
2851
+ file_id: str,
2852
+ new_name: Optional[str] = None,
2853
+ parent_folder_id: str = "root",
2854
+ copy_comments: bool = False,
2855
+ ) -> str:
2856
+ """
2857
+ Creates a copy of an existing Google Drive file.
2858
+
2859
+ This tool copies the template document to a new location with an optional new name.
2860
+ The copy maintains all formatting and content from the original file.
2861
+
2862
+ Args:
2863
+ user_google_email (str): The user's Google email address. Required.
2864
+ file_id (str): The ID of the file to copy. Required.
2865
+ new_name (Optional[str]): New name for the copied file. If not provided, uses "Copy of [original name]".
2866
+ parent_folder_id (str): The ID of the folder where the copy should be created. Defaults to 'root' (My Drive).
2867
+ copy_comments (bool): Copy open comments and suggestions (Docs/Sheets/Slides only). Defaults to False.
2868
+
2869
+ Returns:
2870
+ str: Confirmation message with details of the copied file and its link.
2871
+ """
2872
+ logger.info(
2873
+ f"[copy_drive_file] Invoked. Email: '{user_google_email}', File ID: '{file_id}', New name: '{new_name}', Parent folder: '{parent_folder_id}'"
2874
+ )
2875
+
2876
+ resolved_file_id, file_metadata = await resolve_drive_item(
2877
+ service, file_id, extra_fields="name, webViewLink, mimeType"
2878
+ )
2879
+ file_id = resolved_file_id
2880
+ original_name = file_metadata.get("name", "Unknown File")
2881
+
2882
+ resolved_folder_id = await resolve_folder_id(service, parent_folder_id)
2883
+
2884
+ copy_body = {}
2885
+ if new_name:
2886
+ copy_body["name"] = new_name
2887
+ else:
2888
+ copy_body["name"] = f"Copy of {original_name}"
2889
+
2890
+ copy_body["parents"] = [resolved_folder_id]
2891
+
2892
+ copied_file = await asyncio.to_thread(
2893
+ service.files()
2894
+ .copy(
2895
+ fileId=file_id,
2896
+ body=copy_body,
2897
+ supportsAllDrives=True,
2898
+ copyComments=copy_comments,
2899
+ fields="id, name, webViewLink, mimeType, parents",
2900
+ )
2901
+ .execute
2902
+ )
2903
+
2904
+ output_parts = [
2905
+ f"Successfully copied '{original_name}'",
2906
+ "",
2907
+ f"Original file ID: {file_id}",
2908
+ f"New file ID: {copied_file.get('id', 'N/A')}",
2909
+ f"New file name: {copied_file.get('name', 'Unknown')}",
2910
+ f"File type: {copied_file.get('mimeType', 'Unknown')}",
2911
+ f"Location: {parent_folder_id}",
2912
+ "",
2913
+ f"View copied file: {copied_file.get('webViewLink', 'N/A')}",
2914
+ ]
2915
+
2916
+ return "\n".join(output_parts)
2917
+
2918
+
2919
+ @server.tool(
2920
+ title="Set Drive File Permissions",
2921
+ annotations=ToolAnnotations(
2922
+ readOnlyHint=False,
2923
+ destructiveHint=True,
2924
+ idempotentHint=False,
2925
+ openWorldHint=True,
2926
+ ),
2927
+ )
2928
+ @handle_http_errors(
2929
+ "set_drive_file_permissions", is_read_only=False, service_type="drive"
2930
+ )
2931
+ @require_google_service("drive", "drive_file")
2932
+ async def set_drive_file_permissions(
2933
+ service,
2934
+ user_google_email: str,
2935
+ file_id: str,
2936
+ link_sharing: Optional[str] = None,
2937
+ writers_can_share: Optional[bool] = None,
2938
+ copy_requires_writer_permission: Optional[bool] = None,
2939
+ ) -> str:
2940
+ """
2941
+ Sets file-level sharing settings and controls link sharing for a Google Drive file or folder.
2942
+
2943
+ This is a high-level tool for the most common permission changes. Use this to toggle
2944
+ "anyone with the link" access or configure file-level sharing behavior. For managing
2945
+ individual user/group permissions, use share_drive_file or update_drive_permission instead.
2946
+
2947
+ Args:
2948
+ user_google_email (str): The user's Google email address. Required.
2949
+ file_id (str): The ID of the file or folder. Required.
2950
+ link_sharing (Optional[str]): Control "anyone with the link" access for the file.
2951
+ - "off": Disable "anyone with the link" access for this file.
2952
+ - "reader": Anyone with the link can view.
2953
+ - "commenter": Anyone with the link can comment.
2954
+ - "writer": Anyone with the link can edit.
2955
+ writers_can_share (Optional[bool]): Whether editors can change permissions and share.
2956
+ If False, only the owner can share. Defaults to None (no change).
2957
+ copy_requires_writer_permission (Optional[bool]): Whether viewers and commenters
2958
+ are prevented from copying, printing, or downloading. Defaults to None (no change).
2959
+
2960
+ Returns:
2961
+ str: Summary of all permission changes applied to the file.
2962
+ """
2963
+ logger.info(
2964
+ f"[set_drive_file_permissions] Invoked. Email: '{user_google_email}', "
2965
+ f"File ID: '{file_id}', Link sharing: '{link_sharing}', "
2966
+ f"Writers can share: {writers_can_share}, Copy restriction: {copy_requires_writer_permission}"
2967
+ )
2968
+
2969
+ if (
2970
+ link_sharing is None
2971
+ and writers_can_share is None
2972
+ and copy_requires_writer_permission is None
2973
+ ):
2974
+ raise ValueError(
2975
+ "Must provide at least one of: link_sharing, writers_can_share, copy_requires_writer_permission"
2976
+ )
2977
+
2978
+ valid_link_sharing = {"off", "reader", "commenter", "writer"}
2979
+ if link_sharing is not None and link_sharing not in valid_link_sharing:
2980
+ raise ValueError(
2981
+ f"Invalid link_sharing '{link_sharing}'. Must be one of: {', '.join(sorted(valid_link_sharing))}"
2982
+ )
2983
+
2984
+ resolved_file_id, file_metadata = await resolve_drive_item(
2985
+ service, file_id, extra_fields="name, webViewLink"
2986
+ )
2987
+ file_id = resolved_file_id
2988
+ file_name = file_metadata.get("name", "Unknown")
2989
+
2990
+ output_parts = [f"Permission settings updated for '{file_name}'", ""]
2991
+ changes_made = []
2992
+
2993
+ # Handle file-level settings via files().update()
2994
+ file_update_body = {}
2995
+ if writers_can_share is not None:
2996
+ file_update_body["writersCanShare"] = writers_can_share
2997
+ if copy_requires_writer_permission is not None:
2998
+ file_update_body["copyRequiresWriterPermission"] = (
2999
+ copy_requires_writer_permission
3000
+ )
3001
+
3002
+ if file_update_body:
3003
+ await asyncio.to_thread(
3004
+ service.files()
3005
+ .update(
3006
+ fileId=file_id,
3007
+ body=file_update_body,
3008
+ supportsAllDrives=True,
3009
+ fields="id",
3010
+ )
3011
+ .execute
3012
+ )
3013
+ if writers_can_share is not None:
3014
+ state = "allowed" if writers_can_share else "restricted to owner"
3015
+ changes_made.append(f" - Editors sharing: {state}")
3016
+ if copy_requires_writer_permission is not None:
3017
+ state = "restricted" if copy_requires_writer_permission else "allowed"
3018
+ changes_made.append(f" - Viewers copy/print/download: {state}")
3019
+
3020
+ # Handle link sharing via permissions API
3021
+ if link_sharing is not None:
3022
+ current_permissions = await asyncio.to_thread(
3023
+ list_all_permissions, service, file_id
3024
+ )
3025
+ anyone_perms = [p for p in current_permissions if p.get("type") == "anyone"]
3026
+
3027
+ if link_sharing == "off":
3028
+ if anyone_perms:
3029
+ for perm in anyone_perms:
3030
+ await asyncio.to_thread(
3031
+ service.permissions()
3032
+ .delete(
3033
+ fileId=file_id,
3034
+ permissionId=perm["id"],
3035
+ supportsAllDrives=True,
3036
+ )
3037
+ .execute
3038
+ )
3039
+ changes_made.append(
3040
+ " - Link sharing: disabled (restricted to specific people)"
3041
+ )
3042
+ else:
3043
+ changes_made.append(" - Link sharing: already off (no change)")
3044
+ else:
3045
+ if anyone_perms:
3046
+ await asyncio.to_thread(
3047
+ service.permissions()
3048
+ .update(
3049
+ fileId=file_id,
3050
+ permissionId=anyone_perms[0]["id"],
3051
+ body={
3052
+ "role": link_sharing,
3053
+ "allowFileDiscovery": False,
3054
+ },
3055
+ supportsAllDrives=True,
3056
+ fields="id, type, role",
3057
+ )
3058
+ .execute
3059
+ )
3060
+ changes_made.append(f" - Link sharing: updated to '{link_sharing}'")
3061
+ else:
3062
+ await asyncio.to_thread(
3063
+ service.permissions()
3064
+ .create(
3065
+ fileId=file_id,
3066
+ body={
3067
+ "type": "anyone",
3068
+ "role": link_sharing,
3069
+ "allowFileDiscovery": False,
3070
+ },
3071
+ supportsAllDrives=True,
3072
+ fields="id, type, role",
3073
+ )
3074
+ .execute
3075
+ )
3076
+ changes_made.append(f" - Link sharing: enabled as '{link_sharing}'")
3077
+
3078
+ output_parts.append("Changes:")
3079
+ if changes_made:
3080
+ output_parts.extend(changes_made)
3081
+ else:
3082
+ output_parts.append(" - No changes (already configured)")
3083
+ output_parts.extend(["", f"View link: {file_metadata.get('webViewLink', 'N/A')}"])
3084
+
3085
+ return "\n".join(output_parts)