-
-
Notifications
You must be signed in to change notification settings - Fork 541
Expand file tree
/
Copy pathdrive_tools.py
More file actions
2383 lines (2065 loc) · 89.8 KB
/
drive_tools.py
File metadata and controls
2383 lines (2065 loc) · 89.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Google Drive MCP Tools
This module provides MCP tools for interacting with Google Drive API.
"""
import asyncio
import logging
import io
import httpx
import base64
import ipaddress
import socket
from contextlib import asynccontextmanager
from typing import AsyncIterator, Optional, List, Dict, Any
from tempfile import NamedTemporaryFile
from urllib.parse import urljoin, urlparse, urlunparse
from urllib.request import url2pathname
from pathlib import Path
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaIoBaseDownload, MediaIoBaseUpload
from auth.service_decorator import require_google_service
from auth.oauth_config import is_stateless_mode
from core.attachment_storage import get_attachment_storage, get_attachment_url
from core.utils import extract_office_xml_text, handle_http_errors, validate_file_path
from core.server import server
from core.config import get_transport_mode
from gdrive.drive_helpers import (
DRIVE_QUERY_PATTERNS,
FOLDER_MIME_TYPE,
build_drive_list_params,
check_public_link_permission,
format_permission_info,
get_drive_image_url,
resolve_drive_item,
resolve_file_type_mime,
resolve_folder_id,
validate_expiration_time,
validate_share_role,
validate_share_type,
)
logger = logging.getLogger(__name__)
DOWNLOAD_CHUNK_SIZE_BYTES = 256 * 1024 # 256 KB
UPLOAD_CHUNK_SIZE_BYTES = 5 * 1024 * 1024 # 5 MB (Google recommended minimum)
MAX_DOWNLOAD_BYTES = 2 * 1024 * 1024 * 1024 # 2 GB safety limit for URL downloads
@server.tool()
@handle_http_errors("search_drive_files", is_read_only=True, service_type="drive")
@require_google_service("drive", "drive_read")
async def search_drive_files(
service,
user_google_email: str,
query: str,
page_size: int = 10,
page_token: Optional[str] = None,
drive_id: Optional[str] = None,
include_items_from_all_drives: bool = True,
corpora: Optional[str] = None,
file_type: Optional[str] = None,
detailed: bool = True,
) -> str:
"""
Searches for files and folders within a user's Google Drive, including shared drives.
Args:
user_google_email (str): The user's Google email address. Required.
query (str): The search query string. Supports Google Drive search operators.
page_size (int): The maximum number of files to return. Defaults to 10.
page_token (Optional[str]): Page token from a previous response's nextPageToken to retrieve the next page of results.
drive_id (Optional[str]): ID of the shared drive to search. If None, behavior depends on `corpora` and `include_items_from_all_drives`.
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`.
corpora (Optional[str]): Bodies of items to query (e.g., 'user', 'domain', 'drive', 'allDrives').
If 'drive_id' is specified and 'corpora' is None, it defaults to 'drive'.
Otherwise, Drive API default behavior applies. Prefer 'user' or 'drive' over 'allDrives' for efficiency.
file_type (Optional[str]): Restrict results to a specific file type. Accepts a friendly
name ('folder', 'document'/'doc', 'spreadsheet'/'sheet',
'presentation'/'slides', 'form', 'drawing', 'pdf', 'shortcut',
'script', 'site', 'jam'/'jamboard') or any raw MIME type
string (e.g. 'application/pdf'). Defaults to None (all types).
detailed (bool): Whether to include size, modified time, and link in results. Defaults to True.
Returns:
str: A formatted list of found files/folders with their details (ID, name, type, and optionally size, modified time, link).
Includes a nextPageToken line when more results are available.
"""
logger.info(
f"[search_drive_files] Invoked. Email: '{user_google_email}', Query: '{query}', file_type: '{file_type}'"
)
# Check if the query looks like a structured Drive query or free text
# Look for Drive API operators and structured query patterns
is_structured_query = any(pattern.search(query) for pattern in DRIVE_QUERY_PATTERNS)
if is_structured_query:
final_query = query
logger.info(
f"[search_drive_files] Using structured query as-is: '{final_query}'"
)
else:
# For free text queries, wrap in fullText contains
escaped_query = query.replace("'", "\\'")
final_query = f"fullText contains '{escaped_query}'"
logger.info(
f"[search_drive_files] Reformatting free text query '{query}' to '{final_query}'"
)
if file_type is not None:
mime = resolve_file_type_mime(file_type)
final_query = f"({final_query}) and mimeType = '{mime}'"
logger.info(f"[search_drive_files] Added mimeType filter: '{mime}'")
list_params = build_drive_list_params(
query=final_query,
page_size=page_size,
drive_id=drive_id,
include_items_from_all_drives=include_items_from_all_drives,
corpora=corpora,
page_token=page_token,
detailed=detailed,
)
results = await asyncio.to_thread(service.files().list(**list_params).execute)
files = results.get("files", [])
if not files:
return f"No files found for '{query}'."
next_token = results.get("nextPageToken")
header = f"Found {len(files)} files for {user_google_email} matching '{query}':"
formatted_files_text_parts = [header]
for item in files:
if detailed:
size_str = f", Size: {item.get('size', 'N/A')}" if "size" in item else ""
formatted_files_text_parts.append(
f'- Name: "{item["name"]}" (ID: {item["id"]}, Type: {item["mimeType"]}{size_str}, Modified: {item.get("modifiedTime", "N/A")}) Link: {item.get("webViewLink", "#")}'
)
else:
formatted_files_text_parts.append(
f'- Name: "{item["name"]}" (ID: {item["id"]}, Type: {item["mimeType"]})'
)
if next_token:
formatted_files_text_parts.append(f"nextPageToken: {next_token}")
text_output = "\n".join(formatted_files_text_parts)
return text_output
@server.tool()
@handle_http_errors("get_drive_file_content", is_read_only=True, service_type="drive")
@require_google_service("drive", "drive_read")
async def get_drive_file_content(
service,
user_google_email: str,
file_id: str,
) -> str:
"""
Retrieves the content of a specific Google Drive file by ID, supporting files in shared drives.
• Native Google Docs, Sheets, Slides → exported as text / CSV.
• Office files (.docx, .xlsx, .pptx) → unzipped & parsed with std-lib to
extract readable text.
• Any other file → downloaded; tries UTF-8 decode, else notes binary.
Args:
user_google_email: The user’s Google email address.
file_id: Drive file ID.
Returns:
str: The file content as plain text with metadata header.
"""
logger.info(f"[get_drive_file_content] Invoked. File ID: '{file_id}'")
resolved_file_id, file_metadata = await resolve_drive_item(
service,
file_id,
extra_fields="name, webViewLink",
)
file_id = resolved_file_id
mime_type = file_metadata.get("mimeType", "")
file_name = file_metadata.get("name", "Unknown File")
export_mime_type = {
"application/vnd.google-apps.document": "text/plain",
"application/vnd.google-apps.spreadsheet": "text/csv",
"application/vnd.google-apps.presentation": "text/plain",
}.get(mime_type)
request_obj = (
service.files().export_media(fileId=file_id, mimeType=export_mime_type)
if export_mime_type
else service.files().get_media(fileId=file_id)
)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request_obj)
loop = asyncio.get_event_loop()
done = False
while not done:
status, done = await loop.run_in_executor(None, downloader.next_chunk)
file_content_bytes = fh.getvalue()
# Attempt Office XML extraction only for actual Office XML files
office_mime_types = {
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
}
if mime_type in office_mime_types:
office_text = extract_office_xml_text(file_content_bytes, mime_type)
if office_text:
body_text = office_text
else:
# Fallback: try UTF-8; otherwise flag binary
try:
body_text = file_content_bytes.decode("utf-8")
except UnicodeDecodeError:
body_text = (
f"[Binary or unsupported text encoding for mimeType '{mime_type}' - "
f"{len(file_content_bytes)} bytes]"
)
else:
# For non-Office files (including Google native files), try UTF-8 decode directly
try:
body_text = file_content_bytes.decode("utf-8")
except UnicodeDecodeError:
body_text = (
f"[Binary or unsupported text encoding for mimeType '{mime_type}' - "
f"{len(file_content_bytes)} bytes]"
)
# Assemble response
header = (
f'File: "{file_name}" (ID: {file_id}, Type: {mime_type})\n'
f"Link: {file_metadata.get('webViewLink', '#')}\n\n--- CONTENT ---\n"
)
return header + body_text
@server.tool()
@handle_http_errors(
"get_drive_file_download_url", is_read_only=True, service_type="drive"
)
@require_google_service("drive", "drive_read")
async def get_drive_file_download_url(
service,
user_google_email: str,
file_id: str,
export_format: Optional[str] = None,
) -> str:
"""
Downloads a Google Drive file and saves it to local disk.
In stdio mode, returns the local file path for direct access.
In HTTP mode, returns a temporary download URL (valid for 1 hour).
For Google native files (Docs, Sheets, Slides), exports to a useful format:
- Google Docs -> PDF (default) or DOCX if export_format='docx'
- Google Sheets -> XLSX (default), PDF if export_format='pdf', or CSV if export_format='csv'
- Google Slides -> PDF (default) or PPTX if export_format='pptx'
For other files, downloads the original file format.
Args:
user_google_email: The user's Google email address. Required.
file_id: The Google Drive file ID to download.
export_format: Optional export format for Google native files.
Options: 'pdf', 'docx', 'xlsx', 'csv', 'pptx'.
If not specified, uses sensible defaults (PDF for Docs/Slides, XLSX for Sheets).
For Sheets: supports 'csv', 'pdf', or 'xlsx' (default).
Returns:
str: File metadata with either a local file path or download URL.
"""
logger.info(
f"[get_drive_file_download_url] Invoked. File ID: '{file_id}', Export format: {export_format}"
)
# Resolve shortcuts and get file metadata
resolved_file_id, file_metadata = await resolve_drive_item(
service,
file_id,
extra_fields="name, webViewLink, mimeType",
)
file_id = resolved_file_id
mime_type = file_metadata.get("mimeType", "")
file_name = file_metadata.get("name", "Unknown File")
# Determine export format for Google native files
export_mime_type = None
output_filename = file_name
output_mime_type = mime_type
if mime_type == "application/vnd.google-apps.document":
# Google Docs
if export_format == "docx":
export_mime_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
output_mime_type = export_mime_type
if not output_filename.endswith(".docx"):
output_filename = f"{Path(output_filename).stem}.docx"
else:
# Default to PDF
export_mime_type = "application/pdf"
output_mime_type = export_mime_type
if not output_filename.endswith(".pdf"):
output_filename = f"{Path(output_filename).stem}.pdf"
elif mime_type == "application/vnd.google-apps.spreadsheet":
# Google Sheets
if export_format == "csv":
export_mime_type = "text/csv"
output_mime_type = export_mime_type
if not output_filename.endswith(".csv"):
output_filename = f"{Path(output_filename).stem}.csv"
elif export_format == "pdf":
export_mime_type = "application/pdf"
output_mime_type = export_mime_type
if not output_filename.endswith(".pdf"):
output_filename = f"{Path(output_filename).stem}.pdf"
else:
# Default to XLSX
export_mime_type = (
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
output_mime_type = export_mime_type
if not output_filename.endswith(".xlsx"):
output_filename = f"{Path(output_filename).stem}.xlsx"
elif mime_type == "application/vnd.google-apps.presentation":
# Google Slides
if export_format == "pptx":
export_mime_type = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
output_mime_type = export_mime_type
if not output_filename.endswith(".pptx"):
output_filename = f"{Path(output_filename).stem}.pptx"
else:
# Default to PDF
export_mime_type = "application/pdf"
output_mime_type = export_mime_type
if not output_filename.endswith(".pdf"):
output_filename = f"{Path(output_filename).stem}.pdf"
# Download the file
request_obj = (
service.files().export_media(fileId=file_id, mimeType=export_mime_type)
if export_mime_type
else service.files().get_media(fileId=file_id)
)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request_obj)
loop = asyncio.get_event_loop()
done = False
while not done:
status, done = await loop.run_in_executor(None, downloader.next_chunk)
file_content_bytes = fh.getvalue()
size_bytes = len(file_content_bytes)
size_kb = size_bytes / 1024 if size_bytes else 0
# Check if we're in stateless mode (can't save files)
if is_stateless_mode():
result_lines = [
"File downloaded successfully!",
f"File: {file_name}",
f"File ID: {file_id}",
f"Size: {size_kb:.1f} KB ({size_bytes} bytes)",
f"MIME Type: {output_mime_type}",
"\n⚠️ Stateless mode: File storage disabled.",
"\nBase64-encoded content (first 100 characters shown):",
f"{base64.b64encode(file_content_bytes[:100]).decode('utf-8')}...",
]
logger.info(
f"[get_drive_file_download_url] Successfully downloaded {size_kb:.1f} KB file (stateless mode)"
)
return "\n".join(result_lines)
# Save file to local disk and return file path
try:
storage = get_attachment_storage()
# Encode bytes to base64 (as expected by AttachmentStorage)
base64_data = base64.urlsafe_b64encode(file_content_bytes).decode("utf-8")
# Save attachment to local disk
result = storage.save_attachment(
base64_data=base64_data,
filename=output_filename,
mime_type=output_mime_type,
)
result_lines = [
"File downloaded successfully!",
f"File: {file_name}",
f"File ID: {file_id}",
f"Size: {size_kb:.1f} KB ({size_bytes} bytes)",
f"MIME Type: {output_mime_type}",
]
if get_transport_mode() == "stdio":
result_lines.append(f"\n📎 Saved to: {result.path}")
result_lines.append(
"\nThe file has been saved to disk and can be accessed directly via the file path."
)
else:
download_url = get_attachment_url(result.file_id)
result_lines.append(f"\n📎 Download URL: {download_url}")
result_lines.append("\nThe file will expire after 1 hour.")
if export_mime_type:
result_lines.append(
f"\nNote: Google native file exported to {output_mime_type} format."
)
logger.info(
f"[get_drive_file_download_url] Successfully saved {size_kb:.1f} KB file to {result.path}"
)
return "\n".join(result_lines)
except Exception as e:
logger.error(f"[get_drive_file_download_url] Failed to save file: {e}")
return (
f"Error: Failed to save file for download.\n"
f"File was downloaded successfully ({size_kb:.1f} KB) but could not be saved.\n\n"
f"Error details: {str(e)}"
)
@server.tool()
@handle_http_errors("list_drive_items", is_read_only=True, service_type="drive")
@require_google_service("drive", "drive_read")
async def list_drive_items(
service,
user_google_email: str,
folder_id: str = "root",
page_size: int = 100,
page_token: Optional[str] = None,
drive_id: Optional[str] = None,
include_items_from_all_drives: bool = True,
corpora: Optional[str] = None,
file_type: Optional[str] = None,
detailed: bool = True,
) -> str:
"""
Lists files and folders, supporting shared drives.
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).
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).
Args:
user_google_email (str): The user's Google email address. Required.
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.
page_size (int): The maximum number of items to return. Defaults to 100.
page_token (Optional[str]): Page token from a previous response's nextPageToken to retrieve the next page of results.
drive_id (Optional[str]): ID of the shared drive. If provided, the listing is scoped to this drive.
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.
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`, API defaults apply.
file_type (Optional[str]): Restrict results to a specific file type. Accepts a friendly
name ('folder', 'document'/'doc', 'spreadsheet'/'sheet',
'presentation'/'slides', 'form', 'drawing', 'pdf', 'shortcut',
'script', 'site', 'jam'/'jamboard') or any raw MIME type
string (e.g. 'application/pdf'). Defaults to None (all types).
detailed (bool): Whether to include size, modified time, and link in results. Defaults to True.
Returns:
str: A formatted list of files/folders in the specified folder.
Includes a nextPageToken line when more results are available.
"""
logger.info(
f"[list_drive_items] Invoked. Email: '{user_google_email}', Folder ID: '{folder_id}', File Type: '{file_type}'"
)
resolved_folder_id = await resolve_folder_id(service, folder_id)
final_query = f"'{resolved_folder_id}' in parents and trashed=false"
if file_type is not None:
mime = resolve_file_type_mime(file_type)
final_query = f"({final_query}) and mimeType = '{mime}'"
logger.info(f"[list_drive_items] Added mimeType filter: '{mime}'")
list_params = build_drive_list_params(
query=final_query,
page_size=page_size,
drive_id=drive_id,
include_items_from_all_drives=include_items_from_all_drives,
corpora=corpora,
page_token=page_token,
detailed=detailed,
)
results = await asyncio.to_thread(service.files().list(**list_params).execute)
files = results.get("files", [])
if not files:
return f"No items found in folder '{folder_id}'."
next_token = results.get("nextPageToken")
header = (
f"Found {len(files)} items in folder '{folder_id}' for {user_google_email}:"
)
formatted_items_text_parts = [header]
for item in files:
if detailed:
size_str = f", Size: {item.get('size', 'N/A')}" if "size" in item else ""
formatted_items_text_parts.append(
f'- Name: "{item["name"]}" (ID: {item["id"]}, Type: {item["mimeType"]}{size_str}, Modified: {item.get("modifiedTime", "N/A")}) Link: {item.get("webViewLink", "#")}'
)
else:
formatted_items_text_parts.append(
f'- Name: "{item["name"]}" (ID: {item["id"]}, Type: {item["mimeType"]})'
)
if next_token:
formatted_items_text_parts.append(f"nextPageToken: {next_token}")
text_output = "\n".join(formatted_items_text_parts)
return text_output
async def _create_drive_folder_impl(
service,
user_google_email: str,
folder_name: str,
parent_folder_id: str = "root",
) -> str:
"""Internal implementation for create_drive_folder. Used by tests."""
resolved_folder_id = await resolve_folder_id(service, parent_folder_id)
file_metadata = {
"name": folder_name,
"parents": [resolved_folder_id],
"mimeType": FOLDER_MIME_TYPE,
}
created_file = await asyncio.to_thread(
service.files()
.create(
body=file_metadata,
fields="id, name, webViewLink",
supportsAllDrives=True,
)
.execute
)
link = created_file.get("webViewLink", "")
return (
f"Successfully created folder '{created_file.get('name', folder_name)}' (ID: {created_file.get('id', 'N/A')}) "
f"in folder '{parent_folder_id}' for {user_google_email}. Link: {link}"
)
@server.tool()
@handle_http_errors("create_drive_folder", service_type="drive")
@require_google_service("drive", "drive_file")
async def create_drive_folder(
service,
user_google_email: str,
folder_name: str,
parent_folder_id: str = "root",
) -> str:
"""
Creates a new folder in Google Drive, supporting creation within shared drives.
Args:
user_google_email (str): The user's Google email address. Required.
folder_name (str): The name for the new folder.
parent_folder_id (str): The ID of the parent folder. Defaults to 'root'.
For shared drives, use a folder ID within that shared drive.
Returns:
str: Confirmation message with folder name, ID, and link.
"""
logger.info(
f"[create_drive_folder] Invoked. Email: '{user_google_email}', Folder: '{folder_name}', Parent: '{parent_folder_id}'"
)
return await _create_drive_folder_impl(
service, user_google_email, folder_name, parent_folder_id
)
@server.tool()
@handle_http_errors("create_drive_file", service_type="drive")
@require_google_service("drive", "drive_file")
async def create_drive_file(
service,
user_google_email: str,
file_name: str,
content: Optional[str] = None, # Now explicitly Optional
folder_id: str = "root",
mime_type: str = "text/plain",
fileUrl: Optional[str] = None, # Now explicitly Optional
) -> str:
"""
Creates a new file in Google Drive, supporting creation within shared drives.
Accepts either direct content or a fileUrl to fetch the content from.
Args:
user_google_email (str): The user's Google email address. Required.
file_name (str): The name for the new file.
content (Optional[str]): If provided, the content to write to the file.
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.
mime_type (str): The MIME type of the file. Defaults to 'text/plain'.
fileUrl (Optional[str]): If provided, fetches the file content from this URL. Supports file://, http://, and https:// protocols.
Returns:
str: Confirmation message of the successful file creation with file link.
"""
logger.info(
f"[create_drive_file] Invoked. Email: '{user_google_email}', File Name: {file_name}, Folder ID: {folder_id}, fileUrl: {fileUrl}"
)
if content is None and fileUrl is None and mime_type != FOLDER_MIME_TYPE:
raise Exception("You must provide either 'content' or 'fileUrl'.")
# Create folder (no content or media_body). Prefer create_drive_folder for new code.
if mime_type == FOLDER_MIME_TYPE:
return await _create_drive_folder_impl(
service, user_google_email, file_name, folder_id
)
file_data = None
resolved_folder_id = await resolve_folder_id(service, folder_id)
file_metadata = {
"name": file_name,
"parents": [resolved_folder_id],
"mimeType": mime_type,
}
# Prefer fileUrl if both are provided
if fileUrl:
logger.info(f"[create_drive_file] Fetching file from URL: {fileUrl}")
# Check if this is a file:// URL
parsed_url = urlparse(fileUrl)
if parsed_url.scheme == "file":
# Handle file:// URL - read from local filesystem
logger.info(
"[create_drive_file] Detected file:// URL, reading from local filesystem"
)
transport_mode = get_transport_mode()
running_streamable = transport_mode == "streamable-http"
if running_streamable:
logger.warning(
"[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."
)
# Convert file:// URL to a cross-platform local path
raw_path = parsed_url.path or ""
netloc = parsed_url.netloc
if netloc and netloc.lower() != "localhost":
raw_path = f"//{netloc}{raw_path}"
file_path = url2pathname(raw_path)
# Validate path safety and verify file exists
path_obj = validate_file_path(file_path)
if not path_obj.exists():
extra = (
" The server is running via streamable-http, so file:// URLs must point to files inside the container or remote host."
if running_streamable
else ""
)
raise Exception(f"Local file does not exist: {file_path}.{extra}")
if not path_obj.is_file():
extra = (
" In streamable-http/Docker deployments, mount the file into the container or provide an HTTP(S) URL."
if running_streamable
else ""
)
raise Exception(f"Path is not a file: {file_path}.{extra}")
logger.info(f"[create_drive_file] Reading local file: {file_path}")
# Read file and upload
file_data = await asyncio.to_thread(path_obj.read_bytes)
total_bytes = len(file_data)
logger.info(f"[create_drive_file] Read {total_bytes} bytes from local file")
media = MediaIoBaseUpload(
io.BytesIO(file_data),
mimetype=mime_type,
resumable=True,
chunksize=UPLOAD_CHUNK_SIZE_BYTES,
)
logger.info("[create_drive_file] Starting upload to Google Drive...")
created_file = await asyncio.to_thread(
service.files()
.create(
body=file_metadata,
media_body=media,
fields="id, name, webViewLink",
supportsAllDrives=True,
)
.execute
)
# Handle HTTP/HTTPS URLs
elif parsed_url.scheme in ("http", "https"):
# when running in stateless mode, deployment may not have access to local file system
if is_stateless_mode():
resp = await _ssrf_safe_fetch(fileUrl)
if resp.status_code != 200:
raise Exception(
f"Failed to fetch file from URL: {fileUrl} (status {resp.status_code})"
)
file_data = resp.content
# Try to get MIME type from Content-Type header
content_type = resp.headers.get("Content-Type")
if content_type and content_type != "application/octet-stream":
mime_type = content_type
file_metadata["mimeType"] = content_type
logger.info(
f"[create_drive_file] Using MIME type from Content-Type header: {content_type}"
)
media = MediaIoBaseUpload(
io.BytesIO(file_data),
mimetype=mime_type,
resumable=True,
chunksize=UPLOAD_CHUNK_SIZE_BYTES,
)
created_file = await asyncio.to_thread(
service.files()
.create(
body=file_metadata,
media_body=media,
fields="id, name, webViewLink",
supportsAllDrives=True,
)
.execute
)
else:
# Stream download to temp file with SSRF protection, then upload
with NamedTemporaryFile() as temp_file:
total_bytes = 0
content_type = None
async with _ssrf_safe_stream(fileUrl) as resp:
if resp.status_code != 200:
raise Exception(
f"Failed to fetch file from URL: {fileUrl} "
f"(status {resp.status_code})"
)
content_type = resp.headers.get("Content-Type")
async for chunk in resp.aiter_bytes(
chunk_size=DOWNLOAD_CHUNK_SIZE_BYTES
):
total_bytes += len(chunk)
if total_bytes > MAX_DOWNLOAD_BYTES:
raise Exception(
f"Download exceeded {MAX_DOWNLOAD_BYTES} byte limit"
)
await asyncio.to_thread(temp_file.write, chunk)
logger.info(
f"[create_drive_file] Downloaded {total_bytes} bytes "
f"from URL before upload."
)
if content_type and content_type != "application/octet-stream":
mime_type = content_type
file_metadata["mimeType"] = mime_type
logger.info(
f"[create_drive_file] Using MIME type from "
f"Content-Type header: {mime_type}"
)
# Reset file pointer to beginning for upload
temp_file.seek(0)
media = MediaIoBaseUpload(
temp_file,
mimetype=mime_type,
resumable=True,
chunksize=UPLOAD_CHUNK_SIZE_BYTES,
)
logger.info(
"[create_drive_file] Starting upload to Google Drive..."
)
created_file = await asyncio.to_thread(
service.files()
.create(
body=file_metadata,
media_body=media,
fields="id, name, webViewLink",
supportsAllDrives=True,
)
.execute
)
else:
if not parsed_url.scheme:
raise Exception(
"fileUrl is missing a URL scheme. Use file://, http://, or https://."
)
raise Exception(
f"Unsupported URL scheme '{parsed_url.scheme}'. Only file://, http://, and https:// are supported."
)
elif content is not None:
file_data = content.encode("utf-8")
media = io.BytesIO(file_data)
created_file = await asyncio.to_thread(
service.files()
.create(
body=file_metadata,
media_body=MediaIoBaseUpload(media, mimetype=mime_type, resumable=True),
fields="id, name, webViewLink",
supportsAllDrives=True,
)
.execute
)
link = created_file.get("webViewLink", "No link available")
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}"
logger.info(f"Successfully created file. Link: {link}")
return confirmation_message
# Mapping of file extensions to source MIME types for Google Docs conversion
GOOGLE_DOCS_IMPORT_FORMATS = {
".md": "text/markdown",
".markdown": "text/markdown",
".txt": "text/plain",
".text": "text/plain",
".html": "text/html",
".htm": "text/html",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".doc": "application/msword",
".rtf": "application/rtf",
".odt": "application/vnd.oasis.opendocument.text",
}
GOOGLE_DOCS_MIME_TYPE = "application/vnd.google-apps.document"
def _resolve_and_validate_host(hostname: str) -> list[str]:
"""
Resolve a hostname to IP addresses and validate none are private/internal.
Uses getaddrinfo to handle both IPv4 and IPv6. Fails closed on DNS errors.
Returns:
list[str]: Validated resolved IP address strings.
Raises:
ValueError: If hostname resolves to private/internal IPs or DNS fails.
"""
if not hostname:
raise ValueError("Invalid URL: no hostname")
# Block localhost variants
if hostname.lower() in ("localhost", "127.0.0.1", "::1", "0.0.0.0"):
raise ValueError("URLs pointing to localhost are not allowed")
# Resolve hostname using getaddrinfo (handles both IPv4 and IPv6)
try:
addr_infos = socket.getaddrinfo(hostname, None)
except socket.gaierror as e:
raise ValueError(
f"Cannot resolve hostname '{hostname}': {e}. "
"Refusing request (fail-closed)."
)
if not addr_infos:
raise ValueError(f"No addresses found for hostname: {hostname}")
resolved_ips: list[str] = []
seen_ips: set[str] = set()
for _family, _type, _proto, _canonname, sockaddr in addr_infos:
ip_str = sockaddr[0]
ip = ipaddress.ip_address(ip_str)
if not ip.is_global:
raise ValueError(
f"URLs pointing to private/internal networks are not allowed: "
f"{hostname} resolves to {ip_str}"
)
if ip_str not in seen_ips:
seen_ips.add(ip_str)
resolved_ips.append(ip_str)
return resolved_ips
def _validate_url_not_internal(url: str) -> list[str]:
"""
Validate that a URL doesn't point to internal/private networks (SSRF protection).
Returns:
list[str]: Validated resolved IP addresses for the hostname.
Raises:
ValueError: If URL points to localhost or private IP ranges.
"""
parsed = urlparse(url)
return _resolve_and_validate_host(parsed.hostname)
def _format_host_header(hostname: str, scheme: str, port: Optional[int]) -> str:
"""Format the Host header value for IPv4/IPv6 hostnames."""
host_value = hostname
if ":" in host_value and not host_value.startswith("["):
host_value = f"[{host_value}]"
is_default_port = (scheme == "http" and (port is None or port == 80)) or (
scheme == "https" and (port is None or port == 443)
)
if not is_default_port and port is not None:
host_value = f"{host_value}:{port}"
return host_value
def _build_pinned_url(parsed_url, ip_address_str: str) -> str:
"""Build a URL that targets a resolved IP while preserving path/query."""
pinned_host = ip_address_str
if ":" in pinned_host and not pinned_host.startswith("["):
pinned_host = f"[{pinned_host}]"
userinfo = ""
if parsed_url.username is not None:
userinfo = parsed_url.username
if parsed_url.password is not None:
userinfo += f":{parsed_url.password}"
userinfo += "@"
port_part = f":{parsed_url.port}" if parsed_url.port is not None else ""
netloc = f"{userinfo}{pinned_host}{port_part}"
path = parsed_url.path or "/"
return urlunparse(
(
parsed_url.scheme,
netloc,
path,
parsed_url.params,
parsed_url.query,
parsed_url.fragment,
)
)
async def _fetch_url_with_pinned_ip(url: str) -> httpx.Response:
"""
Fetch URL content by connecting to a validated, pre-resolved IP address.
This prevents DNS rebinding between validation and the outbound connection.
"""
parsed_url = urlparse(url)
if parsed_url.scheme not in ("http", "https"):
raise ValueError(f"Only http:// and https:// are supported: {url}")
if not parsed_url.hostname:
raise ValueError(f"Invalid URL: missing hostname ({url})")
resolved_ips = _validate_url_not_internal(url)
host_header = _format_host_header(
parsed_url.hostname, parsed_url.scheme, parsed_url.port
)
last_error: Optional[Exception] = None
for resolved_ip in resolved_ips:
pinned_url = _build_pinned_url(parsed_url, resolved_ip)
try:
async with httpx.AsyncClient(
follow_redirects=False, trust_env=False
) as client:
request = client.build_request(
"GET",
pinned_url,
headers={"Host": host_header},
extensions={"sni_hostname": parsed_url.hostname},
)
return await client.send(request)
except httpx.HTTPError as exc:
last_error = exc
logger.warning(
f"[ssrf_safe_fetch] Failed request via resolved IP {resolved_ip} for host "
f"{parsed_url.hostname}: {exc}"
)
raise Exception(
f"Failed to fetch URL after trying {len(resolved_ips)} validated IP(s): {url}"
) from last_error
async def _ssrf_safe_fetch(url: str, *, stream: bool = False) -> httpx.Response:
"""
Fetch a URL with SSRF protection that covers redirects and DNS rebinding.
Validates the initial URL and every redirect target against private/internal
networks. Disables automatic redirect following and handles redirects manually.
Args:
url: The URL to fetch.
stream: If True, returns a streaming response (caller must manage context).
Returns:
httpx.Response with the final response content.
Raises:
ValueError: If any URL in the redirect chain points to a private network.
Exception: If the HTTP request fails.