forked from taylorwilsdon/google_workspace_mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgmail_tools.py
More file actions
1997 lines (1678 loc) · 72.1 KB
/
gmail_tools.py
File metadata and controls
1997 lines (1678 loc) · 72.1 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 Gmail MCP Tools
This module provides MCP tools for interacting with the Gmail API.
"""
import logging
import asyncio
import base64
import ssl
import mimetypes
from pathlib import Path
from html.parser import HTMLParser
from typing import Optional, List, Dict, Literal, Any
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from email.utils import formataddr
from fastapi import Body
from pydantic import Field
from auth.service_decorator import require_google_service
from core.utils import handle_http_errors
from core.server import server
from fastmcp.tools.tool import ToolResult
from auth.scopes import (
GMAIL_SEND_SCOPE,
GMAIL_COMPOSE_SCOPE,
GMAIL_MODIFY_SCOPE,
GMAIL_LABELS_SCOPE,
)
from core.structured_output import create_tool_result
from gmail.gmail_models import (
GmailMessageSummary,
GmailSearchResult,
GmailMessageContent,
GmailAttachment,
GmailSendResult,
GMAIL_SEARCH_RESULT_SCHEMA,
GMAIL_MESSAGE_CONTENT_SCHEMA,
GMAIL_SEND_RESULT_SCHEMA,
)
logger = logging.getLogger(__name__)
GMAIL_BATCH_SIZE = 25
GMAIL_REQUEST_DELAY = 0.1
HTML_BODY_TRUNCATE_LIMIT = 20000
GMAIL_METADATA_HEADERS = ["Subject", "From", "To", "Cc", "Message-ID", "Date"]
class _HTMLTextExtractor(HTMLParser):
"""Extract readable text from HTML using stdlib."""
def __init__(self):
super().__init__()
self._text = []
self._skip = False
def handle_starttag(self, tag, attrs):
self._skip = tag in ("script", "style")
def handle_endtag(self, tag):
if tag in ("script", "style"):
self._skip = False
def handle_data(self, data):
if not self._skip:
self._text.append(data)
def get_text(self) -> str:
return " ".join("".join(self._text).split())
def _html_to_text(html: str) -> str:
"""Convert HTML to readable plain text."""
try:
parser = _HTMLTextExtractor()
parser.feed(html)
return parser.get_text()
except Exception:
return html
def _extract_message_body(payload):
"""
Helper function to extract plain text body from a Gmail message payload.
(Maintained for backward compatibility)
Args:
payload (dict): The message payload from Gmail API
Returns:
str: The plain text body content, or empty string if not found
"""
bodies = _extract_message_bodies(payload)
return bodies.get("text", "")
def _extract_message_bodies(payload):
"""
Helper function to extract both plain text and HTML bodies from a Gmail message payload.
Args:
payload (dict): The message payload from Gmail API
Returns:
dict: Dictionary with 'text' and 'html' keys containing body content
"""
text_body = ""
html_body = ""
parts = [payload] if "parts" not in payload else payload.get("parts", [])
part_queue = list(parts) # Use a queue for BFS traversal of parts
while part_queue:
part = part_queue.pop(0)
mime_type = part.get("mimeType", "")
body_data = part.get("body", {}).get("data")
if body_data:
try:
decoded_data = base64.urlsafe_b64decode(body_data).decode(
"utf-8", errors="ignore"
)
if mime_type == "text/plain" and not text_body:
text_body = decoded_data
elif mime_type == "text/html" and not html_body:
html_body = decoded_data
except Exception as e:
logger.warning(f"Failed to decode body part: {e}")
# Add sub-parts to queue for multipart messages
if mime_type.startswith("multipart/") and "parts" in part:
part_queue.extend(part.get("parts", []))
# Check the main payload if it has body data directly
if payload.get("body", {}).get("data"):
try:
decoded_data = base64.urlsafe_b64decode(payload["body"]["data"]).decode(
"utf-8", errors="ignore"
)
mime_type = payload.get("mimeType", "")
if mime_type == "text/plain" and not text_body:
text_body = decoded_data
elif mime_type == "text/html" and not html_body:
html_body = decoded_data
except Exception as e:
logger.warning(f"Failed to decode main payload body: {e}")
return {"text": text_body, "html": html_body}
def _format_body_content(text_body: str, html_body: str) -> str:
"""
Helper function to format message body content with HTML fallback and truncation.
Detects useless text/plain fallbacks (e.g., "Your client does not support HTML").
Args:
text_body: Plain text body content
html_body: HTML body content
Returns:
Formatted body content string
"""
text_stripped = text_body.strip()
html_stripped = html_body.strip()
# Detect useless fallback: HTML comments in text, or HTML is 50x+ longer
use_html = html_stripped and (
not text_stripped
or "<!--" in text_stripped
or len(html_stripped) > len(text_stripped) * 50
)
if use_html:
content = _html_to_text(html_stripped)
if len(content) > HTML_BODY_TRUNCATE_LIMIT:
content = content[:HTML_BODY_TRUNCATE_LIMIT] + "\n\n[Content truncated...]"
return content
elif text_stripped:
return text_body
else:
return "[No readable content found]"
def _extract_attachments(payload: dict) -> List[Dict[str, Any]]:
"""
Extract attachment metadata from a Gmail message payload.
Args:
payload: The message payload from Gmail API
Returns:
List of attachment dictionaries with filename, mimeType, size, and attachmentId
"""
attachments = []
def search_parts(part):
"""Recursively search for attachments in message parts"""
# Check if this part is an attachment
if part.get("filename") and part.get("body", {}).get("attachmentId"):
attachments.append(
{
"filename": part["filename"],
"mimeType": part.get("mimeType", "application/octet-stream"),
"size": part.get("body", {}).get("size", 0),
"attachmentId": part["body"]["attachmentId"],
}
)
# Recursively search sub-parts
if "parts" in part:
for subpart in part["parts"]:
search_parts(subpart)
# Start searching from the root payload
search_parts(payload)
return attachments
def _extract_headers(payload: dict, header_names: List[str]) -> Dict[str, str]:
"""
Extract specified headers from a Gmail message payload.
Args:
payload: The message payload from Gmail API
header_names: List of header names to extract
Returns:
Dict mapping header names to their values
"""
headers = {}
target_headers = {name.lower(): name for name in header_names}
for header in payload.get("headers", []):
header_name_lower = header["name"].lower()
if header_name_lower in target_headers:
# Store using the original requested casing
headers[target_headers[header_name_lower]] = header["value"]
return headers
def _prepare_gmail_message(
subject: str,
body: str,
to: Optional[str] = None,
cc: Optional[str] = None,
bcc: Optional[str] = None,
thread_id: Optional[str] = None,
in_reply_to: Optional[str] = None,
references: Optional[str] = None,
body_format: Literal["plain", "html"] = "plain",
from_email: Optional[str] = None,
from_name: Optional[str] = None,
attachments: Optional[List[Dict[str, str]]] = None,
) -> tuple[str, Optional[str]]:
"""
Prepare a Gmail message with threading and attachment support.
Args:
subject: Email subject
body: Email body content
to: Optional recipient email address
cc: Optional CC email address
bcc: Optional BCC email address
thread_id: Optional Gmail thread ID to reply within
in_reply_to: Optional Message-ID of the message being replied to
references: Optional chain of Message-IDs for proper threading
body_format: Content type for the email body ('plain' or 'html')
from_email: Optional sender email address
from_name: Optional sender display name (e.g., "Peter Hartree")
attachments: Optional list of attachments. Each can have 'path' (file path) OR 'content' (base64) + 'filename'
Returns:
Tuple of (raw_message, thread_id) where raw_message is base64 encoded
"""
# Handle reply subject formatting
reply_subject = subject
if in_reply_to and not subject.lower().startswith("re:"):
reply_subject = f"Re: {subject}"
# Prepare the email
normalized_format = body_format.lower()
if normalized_format not in {"plain", "html"}:
raise ValueError("body_format must be either 'plain' or 'html'.")
# Use multipart if attachments are provided
if attachments:
message = MIMEMultipart()
message.attach(MIMEText(body, normalized_format))
# Process attachments
for attachment in attachments:
file_path = attachment.get("path")
filename = attachment.get("filename")
content_base64 = attachment.get("content")
mime_type = attachment.get("mime_type")
try:
# If path is provided, read and encode the file
if file_path:
path_obj = Path(file_path)
if not path_obj.exists():
logger.error(f"File not found: {file_path}")
continue
# Read file content
with open(path_obj, "rb") as f:
file_data = f.read()
# Use provided filename or extract from path
if not filename:
filename = path_obj.name
# Auto-detect MIME type if not provided
if not mime_type:
mime_type, _ = mimetypes.guess_type(str(path_obj))
if not mime_type:
mime_type = "application/octet-stream"
# If content is provided (base64), decode it
elif content_base64:
if not filename:
logger.warning("Skipping attachment: missing filename")
continue
file_data = base64.b64decode(content_base64)
if not mime_type:
mime_type = "application/octet-stream"
else:
logger.warning("Skipping attachment: missing both path and content")
continue
# Create MIME attachment
main_type, sub_type = mime_type.split("/", 1)
part = MIMEBase(main_type, sub_type)
part.set_payload(file_data)
encoders.encode_base64(part)
# Sanitize filename to prevent header injection and ensure valid quoting
safe_filename = (
(filename or "")
.replace("\r", "")
.replace("\n", "")
.replace("\\", "\\\\")
.replace('"', r"\"")
)
part.add_header(
"Content-Disposition", f'attachment; filename="{safe_filename}"'
)
message.attach(part)
logger.info(f"Attached file: {filename} ({len(file_data)} bytes)")
except Exception as e:
logger.error(f"Failed to attach {filename or file_path}: {e}")
continue
else:
message = MIMEText(body, normalized_format)
message["Subject"] = reply_subject
# Add sender if provided
if from_email:
if from_name:
# Sanitize from_name to prevent header injection
safe_name = (
from_name.replace("\r", "").replace("\n", "").replace("\x00", "")
)
message["From"] = formataddr((safe_name, from_email))
else:
message["From"] = from_email
# Add recipients if provided
if to:
message["To"] = to
if cc:
message["Cc"] = cc
if bcc:
message["Bcc"] = bcc
# Add reply headers for threading
if in_reply_to:
message["In-Reply-To"] = in_reply_to
if references:
message["References"] = references
# Encode message
raw_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
return raw_message, thread_id
def _generate_gmail_web_url(item_id: str, account_index: int = 0) -> str:
"""
Generate Gmail web interface URL for a message or thread ID.
Uses #all to access messages from any Gmail folder/label (not just inbox).
Args:
item_id: Gmail message ID or thread ID
account_index: Google account index (default 0 for primary account)
Returns:
Gmail web interface URL that opens the message/thread in Gmail web interface
"""
return f"https://mail.google.com/mail/u/{account_index}/#all/{item_id}"
def _format_gmail_results_plain(
messages: list, query: str, next_page_token: Optional[str] = None
) -> str:
"""Format Gmail search results in clean, LLM-friendly plain text."""
if not messages:
return f"No messages found for query: '{query}'"
lines = [
f"Found {len(messages)} messages matching '{query}':",
"",
"📧 MESSAGES:",
]
for i, msg in enumerate(messages, 1):
# Handle potential null/undefined message objects
if not msg or not isinstance(msg, dict):
lines.extend(
[
f" {i}. Message: Invalid message data",
" Error: Message object is null or malformed",
"",
]
)
continue
# Handle potential null/undefined values from Gmail API
message_id = msg.get("id")
thread_id = msg.get("threadId")
# Convert None, empty string, or missing values to "unknown"
if not message_id:
message_id = "unknown"
if not thread_id:
thread_id = "unknown"
if message_id != "unknown":
message_url = _generate_gmail_web_url(message_id)
else:
message_url = "N/A"
if thread_id != "unknown":
thread_url = _generate_gmail_web_url(thread_id)
else:
thread_url = "N/A"
lines.extend(
[
f" {i}. Message ID: {message_id}",
f" Web Link: {message_url}",
f" Thread ID: {thread_id}",
f" Thread Link: {thread_url}",
"",
]
)
lines.extend(
[
"💡 USAGE:",
" • Pass the Message IDs **as a list** to get_gmail_messages_content_batch()",
" e.g. get_gmail_messages_content_batch(message_ids=[...])",
" • Pass the Thread IDs to get_gmail_thread_content() (single) or get_gmail_threads_content_batch() (batch)",
]
)
# Add pagination info if there's a next page
if next_page_token:
lines.append("")
lines.append(
f"📄 PAGINATION: To get the next page, call search_gmail_messages again with page_token='{next_page_token}'"
)
return "\n".join(lines)
@server.tool(output_schema=GMAIL_SEARCH_RESULT_SCHEMA)
@handle_http_errors("search_gmail_messages", is_read_only=True, service_type="gmail")
@require_google_service("gmail", "gmail_read")
async def search_gmail_messages(
service,
query: str,
page_size: int = 10,
page_token: Optional[str] = None,
) -> ToolResult:
"""
Searches messages in a user's Gmail account based on a query.
Returns both Message IDs and Thread IDs for each found message, along with Gmail web interface links for manual verification.
Supports pagination via page_token parameter.
Args:
query (str): The search query. Supports standard Gmail search operators.
page_size (int): The maximum number of messages to return. Defaults to 10.
page_token (Optional[str]): Token for retrieving the next page of results. Use the next_page_token from a previous response.
Returns:
ToolResult: LLM-friendly structured results with Message IDs, Thread IDs, and clickable Gmail web interface URLs for each found message.
Includes pagination token if more results are available. Also includes structured_content for machine parsing.
"""
logger.info(f"[search_gmail_messages] Query: '{query}', Page size: {page_size}")
# Build the API request parameters
request_params = {"userId": "me", "q": query, "maxResults": page_size}
# Add page token if provided
if page_token:
request_params["pageToken"] = page_token
logger.info("[search_gmail_messages] Using page_token for pagination")
response = await asyncio.to_thread(
service.users().messages().list(**request_params).execute
)
# Handle potential null response (but empty dict {} is valid)
if response is None:
logger.warning("[search_gmail_messages] Null response from Gmail API")
return create_tool_result(
text=f"No response received from Gmail API for query: '{query}'",
data=GmailSearchResult(query=query, total_found=0, messages=[]),
)
messages = response.get("messages", [])
# Additional safety check for null messages array
if messages is None:
messages = []
# Extract next page token for pagination
next_page_token = response.get("nextPageToken")
# Build structured output
message_summaries = []
for msg in messages:
if not msg or not isinstance(msg, dict):
continue
message_id = msg.get("id") or "unknown"
thread_id = msg.get("threadId") or "unknown"
message_summaries.append(
GmailMessageSummary(
message_id=message_id,
thread_id=thread_id,
web_link=_generate_gmail_web_url(message_id)
if message_id != "unknown"
else "N/A",
thread_link=_generate_gmail_web_url(thread_id)
if thread_id != "unknown"
else "N/A",
)
)
structured_result = GmailSearchResult(
query=query,
total_found=len(message_summaries),
messages=message_summaries,
next_page_token=next_page_token,
)
formatted_output = _format_gmail_results_plain(messages, query, next_page_token)
logger.info(f"[search_gmail_messages] Found {len(messages)} messages")
if next_page_token:
logger.info(
"[search_gmail_messages] More results available (next_page_token present)"
)
return create_tool_result(text=formatted_output, data=structured_result)
@server.tool(output_schema=GMAIL_MESSAGE_CONTENT_SCHEMA)
@handle_http_errors(
"get_gmail_message_content", is_read_only=True, service_type="gmail"
)
@require_google_service("gmail", "gmail_read")
async def get_gmail_message_content(service, message_id: str) -> ToolResult:
"""
Retrieves the full content (subject, sender, recipients, plain text body) of a specific Gmail message.
Args:
message_id (str): The unique ID of the Gmail message to retrieve.
Returns:
ToolResult: The message details including subject, sender, date, Message-ID, recipients (To, Cc), and body content.
Also includes structured_content for machine parsing.
"""
logger.info(f"[get_gmail_message_content] Invoked. Message ID: '{message_id}'")
# Fetch message metadata first to get headers
message_metadata = await asyncio.to_thread(
service.users()
.messages()
.get(
userId="me",
id=message_id,
format="metadata",
metadataHeaders=GMAIL_METADATA_HEADERS,
)
.execute
)
headers = _extract_headers(
message_metadata.get("payload", {}), GMAIL_METADATA_HEADERS
)
subject = headers.get("Subject", "(no subject)")
sender = headers.get("From", "(unknown sender)")
to = headers.get("To", "")
cc = headers.get("Cc", "")
date = headers.get("Date", "(unknown date)")
rfc822_msg_id = headers.get("Message-ID", "")
# Now fetch the full message to get the body parts
message_full = await asyncio.to_thread(
service.users()
.messages()
.get(
userId="me",
id=message_id,
format="full", # Request full payload for body
)
.execute
)
# Extract both text and HTML bodies using enhanced helper function
payload = message_full.get("payload", {})
bodies = _extract_message_bodies(payload)
text_body = bodies.get("text", "")
html_body = bodies.get("html", "")
# Format body content with HTML fallback
body_data = _format_body_content(text_body, html_body)
# Extract attachment metadata
attachments = _extract_attachments(payload)
content_lines = [
f"Subject: {subject}",
f"From: {sender}",
f"Date: {date}",
]
if rfc822_msg_id:
content_lines.append(f"Message-ID: {rfc822_msg_id}")
if to:
content_lines.append(f"To: {to}")
if cc:
content_lines.append(f"Cc: {cc}")
content_lines.append(f"\n--- BODY ---\n{body_data or '[No text/plain body found]'}")
# Add attachment information if present
if attachments:
content_lines.append("\n--- ATTACHMENTS ---")
for i, att in enumerate(attachments, 1):
size_kb = att["size"] / 1024
content_lines.append(
f"{i}. {att['filename']} ({att['mimeType']}, {size_kb:.1f} KB)\n"
f" Attachment ID: {att['attachmentId']}\n"
f" Use get_gmail_attachment_content(message_id='{message_id}', attachment_id='{att['attachmentId']}') to download"
)
# Build structured output
structured_attachments = [
GmailAttachment(
filename=att["filename"],
mime_type=att["mimeType"],
size_bytes=att["size"],
attachment_id=att["attachmentId"],
)
for att in attachments
]
structured_result = GmailMessageContent(
message_id=message_id,
subject=subject,
sender=sender,
date=date,
to=to if to else None,
cc=cc if cc else None,
rfc822_message_id=rfc822_msg_id if rfc822_msg_id else None,
body=body_data or "",
attachments=structured_attachments,
)
return create_tool_result(text="\n".join(content_lines), data=structured_result)
@server.tool()
@handle_http_errors(
"get_gmail_messages_content_batch", is_read_only=True, service_type="gmail"
)
@require_google_service("gmail", "gmail_read")
async def get_gmail_messages_content_batch(
service,
message_ids: List[str],
format: Literal["full", "metadata"] = "full",
) -> str:
"""
Retrieves the content of multiple Gmail messages in a single batch request.
Supports up to 25 messages per batch to prevent SSL connection exhaustion.
Args:
message_ids (List[str]): List of Gmail message IDs to retrieve (max 25 per batch).
format (Literal["full", "metadata"]): Message format. "full" includes body, "metadata" only headers.
Returns:
str: A formatted list of message contents including subject, sender, date, Message-ID, recipients (To, Cc), and body (if full format).
"""
logger.info(
f"[get_gmail_messages_content_batch] Invoked. Message count: {len(message_ids)}"
)
if not message_ids:
raise Exception("No message IDs provided")
output_messages = []
# Process in smaller chunks to prevent SSL connection exhaustion
for chunk_start in range(0, len(message_ids), GMAIL_BATCH_SIZE):
chunk_ids = message_ids[chunk_start : chunk_start + GMAIL_BATCH_SIZE]
results: Dict[str, Dict] = {}
def _batch_callback(request_id, response, exception):
"""Callback for batch requests"""
results[request_id] = {"data": response, "error": exception}
# Try to use batch API
try:
batch = service.new_batch_http_request(callback=_batch_callback)
for mid in chunk_ids:
if format == "metadata":
req = (
service.users()
.messages()
.get(
userId="me",
id=mid,
format="metadata",
metadataHeaders=GMAIL_METADATA_HEADERS,
)
)
else:
req = (
service.users()
.messages()
.get(userId="me", id=mid, format="full")
)
batch.add(req, request_id=mid)
# Execute batch request
await asyncio.to_thread(batch.execute)
except Exception as batch_error:
# Fallback to sequential processing instead of parallel to prevent SSL exhaustion
logger.warning(
f"[get_gmail_messages_content_batch] Batch API failed, falling back to sequential processing: {batch_error}"
)
async def fetch_message_with_retry(mid: str, max_retries: int = 3):
"""Fetch a single message with exponential backoff retry for SSL errors"""
for attempt in range(max_retries):
try:
if format == "metadata":
msg = await asyncio.to_thread(
service.users()
.messages()
.get(
userId="me",
id=mid,
format="metadata",
metadataHeaders=GMAIL_METADATA_HEADERS,
)
.execute
)
else:
msg = await asyncio.to_thread(
service.users()
.messages()
.get(userId="me", id=mid, format="full")
.execute
)
return mid, msg, None
except ssl.SSLError as ssl_error:
if attempt < max_retries - 1:
# Exponential backoff: 1s, 2s, 4s
delay = 2**attempt
logger.warning(
f"[get_gmail_messages_content_batch] SSL error for message {mid} on attempt {attempt + 1}: {ssl_error}. Retrying in {delay}s..."
)
await asyncio.sleep(delay)
else:
logger.error(
f"[get_gmail_messages_content_batch] SSL error for message {mid} on final attempt: {ssl_error}"
)
return mid, None, ssl_error
except Exception as e:
return mid, None, e
# Process messages sequentially with small delays to prevent connection exhaustion
for mid in chunk_ids:
mid_result, msg_data, error = await fetch_message_with_retry(mid)
results[mid_result] = {"data": msg_data, "error": error}
# Brief delay between requests to allow connection cleanup
await asyncio.sleep(GMAIL_REQUEST_DELAY)
# Process results for this chunk
for mid in chunk_ids:
entry = results.get(mid, {"data": None, "error": "No result"})
if entry["error"]:
output_messages.append(f"⚠️ Message {mid}: {entry['error']}\n")
else:
message = entry["data"]
if not message:
output_messages.append(f"⚠️ Message {mid}: No data returned\n")
continue
# Extract content based on format
payload = message.get("payload", {})
if format == "metadata":
headers = _extract_headers(payload, GMAIL_METADATA_HEADERS)
subject = headers.get("Subject", "(no subject)")
sender = headers.get("From", "(unknown sender)")
to = headers.get("To", "")
cc = headers.get("Cc", "")
rfc822_msg_id = headers.get("Message-ID", "")
msg_output = (
f"Message ID: {mid}\nSubject: {subject}\nFrom: {sender}\n"
f"Date: {headers.get('Date', '(unknown date)')}\n"
)
if rfc822_msg_id:
msg_output += f"Message-ID: {rfc822_msg_id}\n"
if to:
msg_output += f"To: {to}\n"
if cc:
msg_output += f"Cc: {cc}\n"
msg_output += f"Web Link: {_generate_gmail_web_url(mid)}\n"
output_messages.append(msg_output)
else:
# Full format - extract body too
headers = _extract_headers(payload, GMAIL_METADATA_HEADERS)
subject = headers.get("Subject", "(no subject)")
sender = headers.get("From", "(unknown sender)")
to = headers.get("To", "")
cc = headers.get("Cc", "")
rfc822_msg_id = headers.get("Message-ID", "")
# Extract both text and HTML bodies using enhanced helper function
bodies = _extract_message_bodies(payload)
text_body = bodies.get("text", "")
html_body = bodies.get("html", "")
# Format body content with HTML fallback
body_data = _format_body_content(text_body, html_body)
msg_output = (
f"Message ID: {mid}\nSubject: {subject}\nFrom: {sender}\n"
f"Date: {headers.get('Date', '(unknown date)')}\n"
)
if rfc822_msg_id:
msg_output += f"Message-ID: {rfc822_msg_id}\n"
if to:
msg_output += f"To: {to}\n"
if cc:
msg_output += f"Cc: {cc}\n"
msg_output += (
f"Web Link: {_generate_gmail_web_url(mid)}\n\n{body_data}\n"
)
output_messages.append(msg_output)
# Combine all messages with separators
final_output = f"Retrieved {len(message_ids)} messages:\n\n"
final_output += "\n---\n\n".join(output_messages)
return final_output
@server.tool()
@handle_http_errors(
"get_gmail_attachment_content", is_read_only=True, service_type="gmail"
)
@require_google_service("gmail", "gmail_read")
async def get_gmail_attachment_content(
service,
message_id: str,
attachment_id: str,
) -> str:
"""
Downloads the content of a specific email attachment.
Args:
message_id (str): The ID of the Gmail message containing the attachment.
attachment_id (str): The ID of the attachment to download.
Returns:
str: Attachment metadata and base64-encoded content that can be decoded and saved.
"""
logger.info(f"[get_gmail_attachment_content] Invoked. Message ID: '{message_id}'")
# Download attachment directly without refetching message metadata.
#
# Important: Gmail attachment IDs are ephemeral and change between API calls for the
# same message. If we refetch the message here to get metadata, the new attachment IDs
# won't match the attachment_id parameter provided by the caller, causing the function
# to fail. The attachment download endpoint returns size information, and filename/mime
# type should be obtained from the original message content call that provided this ID.
try:
attachment = await asyncio.to_thread(
service.users()
.messages()
.attachments()
.get(userId="me", messageId=message_id, id=attachment_id)
.execute
)
except Exception as e:
logger.error(
f"[get_gmail_attachment_content] Failed to download attachment: {e}"
)
return (
f"Error: Failed to download attachment. The attachment ID may have changed.\n"
f"Please fetch the message content again to get an updated attachment ID.\n\n"
f"Error details: {str(e)}"
)
# Format response with attachment data
size_bytes = attachment.get("size", 0)
size_kb = size_bytes / 1024 if size_bytes else 0
base64_data = attachment.get("data", "")
# Check if we're in stateless mode (can't save files)
from auth.oauth_config import is_stateless_mode
if is_stateless_mode():
result_lines = [
"Attachment downloaded successfully!",
f"Message ID: {message_id}",
f"Size: {size_kb:.1f} KB ({size_bytes} bytes)",
"\n⚠️ Stateless mode: File storage disabled.",
"\nBase64-encoded content (first 100 characters shown):",
f"{base64_data[:100]}...",
"\nNote: Attachment IDs are ephemeral. Always use IDs from the most recent message fetch.",
]
logger.info(
f"[get_gmail_attachment_content] Successfully downloaded {size_kb:.1f} KB attachment (stateless mode)"
)
return "\n".join(result_lines)
# Save attachment and generate URL
try:
from core.attachment_storage import get_attachment_storage, get_attachment_url
storage = get_attachment_storage()
# Try to get filename and mime type from message (optional - attachment IDs are ephemeral)
filename = None
mime_type = None
try:
# Quick metadata fetch to try to get attachment info
# Note: This might fail if attachment IDs changed, but worth trying
message_metadata = await asyncio.to_thread(
service.users()
.messages()
.get(userId="me", id=message_id, format="metadata")
.execute
)
payload = message_metadata.get("payload", {})
attachments = _extract_attachments(payload)
for att in attachments:
if att.get("attachmentId") == attachment_id:
filename = att.get("filename")
mime_type = att.get("mimeType")
break
except Exception:
# If we can't get metadata, use defaults
logger.debug(
f"Could not fetch attachment metadata for {attachment_id}, using defaults"
)
# Save attachment
file_id = storage.save_attachment(
base64_data=base64_data, filename=filename, mime_type=mime_type
)