@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,4895 @@
1
+ """
2
+ Google Gmail MCP Tools
3
+
4
+ This module provides MCP tools for interacting with the Gmail API.
5
+ """
6
+
7
+ import logging
8
+ import asyncio
9
+ import base64
10
+ import binascii
11
+ import json
12
+ import re
13
+ import mimetypes
14
+ import html
15
+ from functools import partial
16
+ from html.parser import HTMLParser
17
+ from pathlib import Path
18
+ from typing import Annotated, Optional, List, Dict, Literal, Any, Union
19
+ from urllib.parse import unquote, urlparse, urlunsplit
20
+
21
+ from email.message import EmailMessage
22
+ from email.policy import SMTP
23
+ from email.utils import formataddr
24
+
25
+ import httpx
26
+ from fastmcp.exceptions import ToolError as ToolExecutionError
27
+ from mcp.types import ToolAnnotations
28
+
29
+ from pydantic import Field
30
+ from pydantic.json_schema import SkipJsonSchema
31
+
32
+ from auth.oauth_config import is_stateless_mode
33
+ from auth.service_decorator import require_google_service
34
+ from core.attachment_storage import (
35
+ get_attachment_storage,
36
+ get_attachment_url,
37
+ resolve_local_attachment,
38
+ )
39
+ from core.file_limits import (
40
+ FileTooLargeError,
41
+ ensure_within_file_size_limit,
42
+ get_max_file_bytes,
43
+ )
44
+ from core.gcs_attachment_storage import gcs_files_enabled
45
+ from core.config import get_transport_mode
46
+ from core.http_utils import ssrf_safe_stream
47
+ from core.utils import (
48
+ GOOGLE_API_WRITE_RETRIES,
49
+ handle_http_errors,
50
+ open_validated_file,
51
+ UserInputError,
52
+ StringList,
53
+ JsonDict,
54
+ DictList,
55
+ )
56
+ from core.server import server
57
+ from core.telemetry import record_degraded_failure
58
+ from auth.scopes import (
59
+ GMAIL_SEND_SCOPE,
60
+ GMAIL_COMPOSE_SCOPE,
61
+ GMAIL_MODIFY_SCOPE,
62
+ GMAIL_LABELS_SCOPE,
63
+ has_required_scopes,
64
+ )
65
+ from gmail.gmail_helpers import (
66
+ FILTER_APPLY_DEFAULT_MAX_MESSAGES,
67
+ GMAIL_METADATA_HEADERS,
68
+ PRIORITY_DESCRIPTION,
69
+ RAW_BODY_TRUNCATE_LIMIT,
70
+ THREAD_REPLY_CONTEXT_FIELDS,
71
+ MessagePriority,
72
+ _analyze_thread_ownership_impl,
73
+ _build_forward_content,
74
+ _build_web_compose_raw,
75
+ _derive_reply_all_recipients,
76
+ _derive_reply_headers,
77
+ _derive_web_bodies,
78
+ _fetch_with_retry,
79
+ _format_id_list,
80
+ _generate_gmail_web_url,
81
+ _get_send_as_identity_and_signature,
82
+ _html_signature_separator,
83
+ _http_error_status,
84
+ _inherit_reply_subject,
85
+ _is_email_reaction,
86
+ _new_attachment_id,
87
+ _prepare_gmail_message_web,
88
+ _priority_headers,
89
+ _reject_entity_escaped_html_body,
90
+ _reply_subject,
91
+ _resolve_reply_quote,
92
+ _retryable_result_ids,
93
+ _signature_html_to_text,
94
+ _wrap_signature_html,
95
+ apply_gmail_filter_to_existing,
96
+ build_label_color,
97
+ decode_part_body,
98
+ fetch_attachment_backed_bodies,
99
+ format_filter_apply_result,
100
+ format_html_links,
101
+ format_thread_label_outcomes,
102
+ html_newlines_to_br,
103
+ html_to_text_preserving_breaks,
104
+ modify_gmail_thread_labels,
105
+ read_gmail_message_page,
106
+ send_message_once,
107
+ thread_message_status,
108
+ update_gmail_filter,
109
+ )
110
+ from gmail.gmail_web_mime import TextDirection
111
+
112
+ logger = logging.getLogger(__name__)
113
+
114
+ GMAIL_BATCH_SIZE = 25
115
+ # Smaller chunks for search-result header fetches: the batch endpoint executes
116
+ # every get in a chunk concurrently server-side, and chunks of 25 metadata gets
117
+ # trip Gmail's per-user concurrency limit ("Too many concurrent requests").
118
+ GMAIL_SEARCH_HEADER_BATCH_SIZE = 10
119
+ GMAIL_REQUEST_DELAY = 0.1
120
+ GMAIL_RATE_LIMIT_BACKOFF = 2.0
121
+ HTML_BODY_TRUNCATE_LIMIT = 20000
122
+ DIRECTION_DESCRIPTION = (
123
+ "Base text direction of the body. 'auto' (default) takes it from the first "
124
+ "strong character (a right-to-left script gives 'rtl', anything else 'ltr'); "
125
+ "'ltr'/'rtl' force it. On a forward it orients the note."
126
+ )
127
+ INCLUDE_LINKS_DESCRIPTION = (
128
+ "When True, append a LINKS section listing the http(s) URLs from the HTML "
129
+ "body that the text output omits. Only applies to body_format='text'."
130
+ )
131
+
132
+ # Keep ``None`` valid at runtime without publishing it as an ``anyOf`` branch.
133
+ # Cowork needs a top-level array schema, while Moonshot rejects the previous
134
+ # parent-level array override alongside a nullable ``anyOf``.
135
+ _OptionalLabelIdList = Union[StringList, SkipJsonSchema[None]]
136
+
137
+ LOW_VALUE_TEXT_PLACEHOLDERS = (
138
+ "your client does not support html",
139
+ "view this email in your browser",
140
+ "open this email in your browser",
141
+ )
142
+ LOW_VALUE_TEXT_FOOTER_MARKERS = (
143
+ "mailing list",
144
+ "mailman/listinfo",
145
+ "unsubscribe",
146
+ "list-unsubscribe",
147
+ "manage preferences",
148
+ )
149
+ LOW_VALUE_TEXT_HTML_DIFF_MIN = 80
150
+ CONTENT_ID_SAFE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+\-@]*$")
151
+
152
+
153
+ class _HTMLTextExtractor(HTMLParser):
154
+ """Extract readable text from HTML using stdlib."""
155
+
156
+ def __init__(self):
157
+ super().__init__()
158
+ self._text = []
159
+ self._skip = False
160
+
161
+ def handle_starttag(self, tag, attrs):
162
+ if tag in ("script", "style"):
163
+ self._skip = True
164
+ return
165
+ if tag == "br" and not self._skip:
166
+ self._text.append(" ")
167
+
168
+ def handle_endtag(self, tag):
169
+ if tag in ("script", "style"):
170
+ self._skip = False
171
+
172
+ def handle_data(self, data):
173
+ if not self._skip:
174
+ self._text.append(data)
175
+
176
+ def get_text(self) -> str:
177
+ return " ".join("".join(self._text).split())
178
+
179
+
180
+ def _html_to_text(html: str) -> str:
181
+ """Convert HTML to readable plain text."""
182
+ try:
183
+ parser = _HTMLTextExtractor()
184
+ parser.feed(html)
185
+ return parser.get_text()
186
+ except Exception:
187
+ return html
188
+
189
+
190
+ def _extract_message_body(payload):
191
+ """
192
+ Helper function to extract plain text body from a Gmail message payload.
193
+ (Maintained for backward compatibility)
194
+
195
+ Args:
196
+ payload (dict): The message payload from Gmail API
197
+
198
+ Returns:
199
+ str: The plain text body content, or empty string if not found
200
+ """
201
+ bodies = _extract_message_bodies(payload)
202
+ return bodies.get("text", "")
203
+
204
+
205
+ def _extract_message_bodies(payload):
206
+ """
207
+ Helper function to extract both plain text and HTML bodies from a Gmail message payload.
208
+
209
+ Args:
210
+ payload (dict): The message payload from Gmail API
211
+
212
+ Returns:
213
+ dict: Dictionary with 'text' and 'html' keys containing body content
214
+ """
215
+ text_body = ""
216
+ html_body = ""
217
+ parts = [payload] if "parts" not in payload else payload.get("parts", [])
218
+
219
+ part_queue = list(parts) # Use a queue for BFS traversal of parts
220
+ while part_queue:
221
+ part = part_queue.pop(0)
222
+ mime_type = part.get("mimeType", "")
223
+
224
+ if part.get("body", {}).get("data"):
225
+ try:
226
+ decoded_data = decode_part_body(part)
227
+ if mime_type == "text/plain" and not text_body:
228
+ text_body = decoded_data
229
+ elif mime_type == "text/html" and not html_body:
230
+ html_body = decoded_data
231
+ except Exception as e:
232
+ logger.warning(f"Failed to decode body part: {e}")
233
+
234
+ # Add sub-parts to queue for multipart messages
235
+ if mime_type.startswith("multipart/") and "parts" in part:
236
+ part_queue.extend(part.get("parts", []))
237
+
238
+ # Check the main payload if it has body data directly
239
+ if payload.get("body", {}).get("data"):
240
+ try:
241
+ decoded_data = decode_part_body(payload)
242
+ mime_type = payload.get("mimeType", "")
243
+ if mime_type == "text/plain" and not text_body:
244
+ text_body = decoded_data
245
+ elif mime_type == "text/html" and not html_body:
246
+ html_body = decoded_data
247
+ except Exception as e:
248
+ logger.warning(f"Failed to decode main payload body: {e}")
249
+
250
+ return {"text": text_body, "html": html_body}
251
+
252
+
253
+ def _format_body_content(
254
+ text_body: str,
255
+ html_body: str,
256
+ body_format: Literal["text", "html"] = "text",
257
+ include_links: bool = False,
258
+ truncate_limit: Optional[int] = HTML_BODY_TRUNCATE_LIMIT,
259
+ ) -> str:
260
+ """
261
+ Helper function to format message body content with HTML fallback and truncation.
262
+ Detects useless text/plain fallbacks (e.g., "Your client does not support HTML").
263
+
264
+ Args:
265
+ text_body: Plain text body content
266
+ html_body: HTML body content
267
+ body_format: Output format - "text" converts HTML to plaintext (default),
268
+ "html" returns raw HTML body as-is
269
+ truncate_limit: Maximum HTML-derived body characters; None preserves the complete body.
270
+ include_links: In text mode, append the HTML body's http(s) links missing from the text
271
+
272
+ Returns:
273
+ Formatted body content string
274
+ """
275
+ if body_format == "html":
276
+ html_stripped = html_body.strip()
277
+ if html_stripped:
278
+ if truncate_limit is not None and len(html_stripped) > truncate_limit:
279
+ return html_stripped[:truncate_limit] + "\n\n[Content truncated...]"
280
+ return html_stripped
281
+ # Fall back to text body when no HTML is available
282
+ text_stripped = text_body.strip()
283
+ return text_stripped if text_stripped else "[No readable content found]"
284
+
285
+ text_stripped = text_body.strip()
286
+ html_stripped = html_body.strip()
287
+ html_text = _html_to_text(html_stripped).strip() if html_stripped else ""
288
+
289
+ plain_lower = " ".join(text_stripped.split()).lower()
290
+ html_lower = " ".join(html_text.split()).lower()
291
+ plain_is_low_value = plain_lower and (
292
+ any(marker in plain_lower for marker in LOW_VALUE_TEXT_PLACEHOLDERS)
293
+ or (
294
+ any(marker in plain_lower for marker in LOW_VALUE_TEXT_FOOTER_MARKERS)
295
+ and len(html_lower) >= len(plain_lower) + LOW_VALUE_TEXT_HTML_DIFF_MIN
296
+ )
297
+ or (
298
+ len(html_lower) >= len(plain_lower) + LOW_VALUE_TEXT_HTML_DIFF_MIN
299
+ and html_lower.endswith(plain_lower)
300
+ )
301
+ )
302
+
303
+ # Prefer plain text, but fall back to HTML when plain text is empty or clearly low-value.
304
+ use_html = html_text and (
305
+ not text_stripped or "<!--" in text_stripped or plain_is_low_value
306
+ )
307
+
308
+ if use_html:
309
+ content = (
310
+ _truncate_content(html_text, truncate_limit)
311
+ if truncate_limit is not None
312
+ else html_text
313
+ )
314
+ elif text_stripped:
315
+ content = text_body
316
+ else:
317
+ content = "[No readable content found]"
318
+ if include_links:
319
+ content += format_html_links(html_stripped, content, truncate_limit)
320
+ return content
321
+
322
+
323
+ def _truncate_content(content: str, limit: int) -> str:
324
+ """Truncate content to a readable length for tool responses."""
325
+ if len(content) <= limit:
326
+ return content
327
+ return content[:limit] + "\n\n[Content truncated...]"
328
+
329
+
330
+ def _decode_raw_mime_content(raw_data: str) -> str:
331
+ """Decode Gmail raw MIME content into readable text."""
332
+ if not raw_data:
333
+ return "[No raw content found]"
334
+
335
+ padded_raw = raw_data + "=" * (-len(raw_data) % 4)
336
+ try:
337
+ decoded_raw = base64.urlsafe_b64decode(padded_raw).decode(
338
+ "utf-8", errors="replace"
339
+ )
340
+ except (binascii.Error, ValueError) as exc:
341
+ return f"[Failed to decode raw MIME: {exc}]"
342
+
343
+ return _truncate_content(decoded_raw, RAW_BODY_TRUNCATE_LIMIT)
344
+
345
+
346
+ def _format_message_header_lines(
347
+ headers: Dict[str, str], message_id: Optional[str] = None
348
+ ) -> List[str]:
349
+ """Format standard Gmail message headers for response output."""
350
+ subject = headers.get("Subject", "(no subject)")
351
+ sender = headers.get("From", "(unknown sender)")
352
+ reply_to = headers.get("Reply-To", "")
353
+ to = headers.get("To", "")
354
+ cc = headers.get("Cc", "")
355
+ rfc822_msg_id = headers.get("Message-ID", "")
356
+ in_reply_to = headers.get("In-Reply-To", "")
357
+ references = headers.get("References", "")
358
+ list_unsub = headers.get("List-Unsubscribe", "")
359
+ precedence = headers.get("Precedence", "")
360
+ list_id = headers.get("List-Id", "")
361
+
362
+ content_lines = []
363
+ if message_id:
364
+ content_lines.append(f"Message ID: {message_id}")
365
+
366
+ content_lines.extend(
367
+ [
368
+ f"Subject: {subject}",
369
+ f"From: {sender}",
370
+ f"Date: {headers.get('Date', '(unknown date)')}",
371
+ ]
372
+ )
373
+ if reply_to:
374
+ content_lines.append(f"Reply-To: {reply_to}")
375
+
376
+ if rfc822_msg_id:
377
+ content_lines.append(f"Message-ID: {rfc822_msg_id}")
378
+ if in_reply_to:
379
+ content_lines.append(f"In-Reply-To: {in_reply_to}")
380
+ if references:
381
+ content_lines.append(f"References: {references}")
382
+ content_lines.append(
383
+ f"To: {to}" if "To" in headers else "To: [not present in Gmail response]"
384
+ )
385
+ content_lines.append(
386
+ f"Cc: {cc}" if "Cc" in headers else "Cc: [not present in Gmail response]"
387
+ )
388
+ if list_unsub:
389
+ content_lines.append(f"List-Unsubscribe: {list_unsub}")
390
+ if precedence:
391
+ content_lines.append(f"Precedence: {precedence}")
392
+ if list_id:
393
+ content_lines.append(f"List-Id: {list_id}")
394
+
395
+ return content_lines
396
+
397
+
398
+ async def _export_full_message(
399
+ service,
400
+ message_id: str,
401
+ headers: Dict[str, str],
402
+ body_format: Literal["text", "html", "raw"],
403
+ declared_size: Optional[int] = None,
404
+ include_headers: bool = True,
405
+ include_links: bool = False,
406
+ ) -> str:
407
+ """
408
+ Return a message's complete, untruncated content: saved to storage and
409
+ referenced by download URL (HTTP transport) or file path (stdio transport), or —
410
+ in stateless mode without GCS staging, where there is no storage — inlined in
411
+ the response. With a GCS bucket configured, stateless mode also gets a signed
412
+ download URL, since the bucket is not instance-local.
413
+
414
+ Whenever a file is written the body is kept out of the returned string, which is
415
+ the point of the export: large messages are handed off out-of-band instead of
416
+ through the model context. Either way no truncation limit applies.
417
+
418
+ Args:
419
+ service: Authenticated Gmail API service.
420
+ message_id: The message to export.
421
+ headers: Already-fetched message headers, used for the summary and filename.
422
+ body_format: "raw" saves the byte-exact RFC 5322 message as .eml,
423
+ "html" saves the raw HTML body, "text" saves the plaintext body.
424
+ include_headers: When False, omit the header summary and name the file
425
+ after the message ID instead of the subject.
426
+
427
+ Returns:
428
+ str: Header summary plus the saved file's URL or path (or the inline body in
429
+ stateless mode), or an "Error:" string.
430
+ """
431
+ file_stem = (headers.get("Subject") if include_headers else message_id) or "message"
432
+ notes: List[str] = []
433
+
434
+ # Gmail's full/raw endpoints return their payload as one JSON response, so
435
+ # use the metadata response's sizeEstimate to fail closed before asking the
436
+ # client library to buffer and decode an oversized message.
437
+ try:
438
+ ensure_within_file_size_limit(
439
+ declared_size,
440
+ file_name=file_stem,
441
+ file_id=message_id,
442
+ kind="message export",
443
+ )
444
+ except FileTooLargeError as exc:
445
+ return str(exc)
446
+
447
+ if body_format == "raw":
448
+ message_raw = await asyncio.to_thread(
449
+ service.users()
450
+ .messages()
451
+ .get(userId="me", id=message_id, format="raw")
452
+ .execute
453
+ )
454
+ raw_data = message_raw.get("raw", "")
455
+ if not raw_data:
456
+ return "Error: message has no raw content to export."
457
+ padded_raw = raw_data + "=" * (-len(raw_data) % 4)
458
+ try:
459
+ content_bytes = base64.urlsafe_b64decode(padded_raw)
460
+ except (binascii.Error, ValueError) as exc:
461
+ return f"Error: failed to decode raw MIME content: {exc}"
462
+ mime_type = "message/rfc822"
463
+ extension = ".eml"
464
+ else:
465
+ message_full = await asyncio.to_thread(
466
+ service.users()
467
+ .messages()
468
+ .get(userId="me", id=message_id, format="full")
469
+ .execute
470
+ )
471
+ await fetch_attachment_backed_bodies(service, [message_full])
472
+ bodies = _extract_message_bodies(message_full.get("payload", {}))
473
+ # Preserve the body exactly — the export must be complete — so use .strip()
474
+ # only to test for emptiness, never to trim the content that gets saved.
475
+ text_body = bodies.get("text", "")
476
+ html_body = bodies.get("html", "")
477
+
478
+ if body_format == "html":
479
+ if html_body.strip():
480
+ content_str = html_body
481
+ mime_type = "text/html"
482
+ extension = ".html"
483
+ elif text_body.strip():
484
+ # No HTML part; fall back to plaintext and label it honestly.
485
+ content_str = text_body
486
+ mime_type = "text/plain"
487
+ extension = ".txt"
488
+ notes.append(
489
+ "No HTML body present; exported the plaintext body instead."
490
+ )
491
+ else:
492
+ content_str = ""
493
+ mime_type = "text/html"
494
+ extension = ".html"
495
+ else: # text
496
+ if text_body.strip():
497
+ content_str = text_body
498
+ elif html_body.strip():
499
+ content_str = _html_to_text(html_body)
500
+ else:
501
+ content_str = ""
502
+ if include_links:
503
+ content_str += format_html_links(html_body, content_str)
504
+ mime_type = "text/plain"
505
+ extension = ".txt"
506
+
507
+ if not content_str.strip():
508
+ return "Error: message has no readable body content to export."
509
+ content_bytes = content_str.encode("utf-8")
510
+
511
+ # sizeEstimate is intentionally approximate. Enforce the exact decoded
512
+ # size too before producing another representation or saving the export.
513
+ try:
514
+ ensure_within_file_size_limit(
515
+ len(content_bytes),
516
+ file_name=file_stem,
517
+ file_id=message_id,
518
+ kind="message export",
519
+ )
520
+ except FileTooLargeError as exc:
521
+ return str(exc)
522
+
523
+ # Stateless deployments have no persistent storage to hand a file reference off
524
+ # from, but the guarantee callers actually want is "complete and untruncated".
525
+ # Inline delivery satisfies that; it only costs model context.
526
+ #
527
+ # GCS staging is the exception: the bucket is not instance-local, so a
528
+ # stateless deployment that configures one can hand back a signed URL after
529
+ # all and keep the body out of the model context. Only fall back to inlining
530
+ # when stateless mode has no staging available.
531
+ stateless = is_stateless_mode() and not gcs_files_enabled()
532
+
533
+ size_bytes = len(content_bytes)
534
+ size_kb = size_bytes / 1024
535
+ result_lines = _format_message_header_lines(headers) if include_headers else []
536
+ result_lines.append(
537
+ "\n--- FULL MESSAGE ---" if stateless else "\n--- FULL MESSAGE EXPORT ---"
538
+ )
539
+ result_lines.append(f"Format: {extension.lstrip('.')}")
540
+ result_lines.append(f"Size: {size_kb:.1f} KB ({size_bytes} bytes)")
541
+
542
+ if stateless:
543
+ for note in notes:
544
+ result_lines.append(f"Note: {note}")
545
+ result_lines.append(
546
+ "\nStateless mode: no file storage available, so the complete message is "
547
+ "included inline below instead of as a download URL. It is NOT truncated."
548
+ )
549
+ result_lines.append(
550
+ "\n--- BODY (COMPLETE, NOT TRUNCATED) ---\n"
551
+ f"{content_bytes.decode('utf-8', errors='replace')}"
552
+ )
553
+ logger.info(
554
+ f"[get_gmail_message_content] Returned {size_kb:.1f} KB "
555
+ f"({extension.lstrip('.')}) inline (stateless mode)"
556
+ )
557
+ return "\n".join(result_lines)
558
+
559
+ # Write on a worker thread so a large export doesn't block the event loop.
560
+ # Cap the sender-controlled subject so a pathologically long Subject can't overflow
561
+ # the filesystem's filename limit, and surface a clean error if the write fails.
562
+ storage = get_attachment_storage()
563
+
564
+ def _save_export():
565
+ return storage.save_attachment_bytes(
566
+ file_bytes=content_bytes,
567
+ filename=f"{file_stem[:80]}{extension}",
568
+ mime_type=mime_type,
569
+ )
570
+
571
+ try:
572
+ saved = await asyncio.to_thread(_save_export)
573
+ except OSError as exc:
574
+ logger.error(f"[get_gmail_message_content] Failed to save message: {exc}")
575
+ record_degraded_failure(exc)
576
+ return f"Error: failed to save message to storage: {exc}"
577
+
578
+ result_lines.append(f"Saved filename: {Path(saved.path).name}")
579
+ for note in notes:
580
+ result_lines.append(f"Note: {note}")
581
+
582
+ if get_transport_mode() == "stdio":
583
+ result_lines.append(f"\n📎 Saved to: {saved.path}")
584
+ result_lines.append(
585
+ "\nThe full message has been written to disk and can be read directly "
586
+ "from the file path (its content is NOT included above)."
587
+ )
588
+ else:
589
+ download_url = await asyncio.to_thread(get_attachment_url, saved.file_id)
590
+ result_lines.append(f"\n📎 Download URL: {download_url}")
591
+ result_lines.append(
592
+ "\nFetch the full message from the URL above (content is NOT included "
593
+ "in this response). The file will expire after 1 hour."
594
+ )
595
+
596
+ logger.info(
597
+ f"[get_gmail_message_content] Exported {size_kb:.1f} KB "
598
+ f"({extension.lstrip('.')}) to {saved.path}"
599
+ )
600
+ return "\n".join(result_lines)
601
+
602
+
603
+ def _build_message_get_request(
604
+ service,
605
+ message_id: str,
606
+ message_format: Literal["metadata", "full", "raw"],
607
+ ):
608
+ """Build a Gmail messages.get request for the requested format."""
609
+ request_kwargs = {"userId": "me", "id": message_id, "format": message_format}
610
+ if message_format == "metadata":
611
+ request_kwargs["metadataHeaders"] = GMAIL_METADATA_HEADERS
612
+ return service.users().messages().get(**request_kwargs)
613
+
614
+
615
+ def _validate_message_format_options(
616
+ response_format: Literal["full", "metadata"],
617
+ body_format: Literal["text", "html", "raw"],
618
+ ) -> None:
619
+ """Reject incompatible output combinations for message reads."""
620
+ if response_format == "metadata" and body_format != "text":
621
+ raise UserInputError(
622
+ "body_format='html' and body_format='raw' require format='full'."
623
+ )
624
+
625
+
626
+ async def _fetch_message_with_retry(
627
+ service,
628
+ message_id: str,
629
+ message_format: Literal["metadata", "full", "raw"],
630
+ log_prefix: str,
631
+ max_retries: int = 3,
632
+ ):
633
+ """Fetch a single Gmail message, retrying transient failures."""
634
+ return await _fetch_with_retry(
635
+ lambda: _build_message_get_request(
636
+ service, message_id=message_id, message_format=message_format
637
+ ),
638
+ item_id=message_id,
639
+ item_label="message",
640
+ log_prefix=log_prefix,
641
+ max_retries=max_retries,
642
+ )
643
+
644
+
645
+ async def _fetch_thread_with_retry(
646
+ service,
647
+ thread_id: str,
648
+ log_prefix: str,
649
+ max_retries: int = 3,
650
+ ):
651
+ """Fetch a single Gmail thread, retrying transient failures."""
652
+ return await _fetch_with_retry(
653
+ lambda: service.users().threads().get(userId="me", id=thread_id, format="full"),
654
+ item_id=thread_id,
655
+ item_label="thread",
656
+ log_prefix=log_prefix,
657
+ max_retries=max_retries,
658
+ )
659
+
660
+
661
+ async def _fetch_raw_message_contents(
662
+ service, message_ids: List[str], log_prefix: str
663
+ ) -> Dict[str, str]:
664
+ """Fetch decoded raw MIME content for a set of Gmail message IDs."""
665
+ raw_contents: Dict[str, str] = {}
666
+ for message_id in message_ids:
667
+ _, raw_message, raw_error = await _fetch_message_with_retry(
668
+ service,
669
+ message_id=message_id,
670
+ message_format="raw",
671
+ log_prefix=log_prefix,
672
+ )
673
+ raw_contents[message_id] = (
674
+ _decode_raw_mime_content(raw_message.get("raw", ""))
675
+ if raw_message
676
+ else f"[Failed to fetch raw MIME: {raw_error}]"
677
+ )
678
+ await asyncio.sleep(GMAIL_REQUEST_DELAY)
679
+
680
+ return raw_contents
681
+
682
+
683
+ def _append_signature_to_body(
684
+ body: str, body_format: Literal["plain", "html"], signature_html: str
685
+ ) -> str:
686
+ """Append a Gmail signature to the outgoing body, preserving body format."""
687
+ if not signature_html or not signature_html.strip():
688
+ return body
689
+
690
+ if body_format == "html":
691
+ separator = _html_signature_separator(body)
692
+ return f"{body}{separator}{_wrap_signature_html(signature_html)}"
693
+
694
+ signature_text = _signature_html_to_text(signature_html).strip()
695
+ if not signature_text:
696
+ return body
697
+ separator = "\n\n" if body.strip() else ""
698
+ return f"{body}{separator}{signature_text}"
699
+
700
+
701
+ def _build_quoted_reply_body(
702
+ reply_body: str,
703
+ body_format: Literal["plain", "html"],
704
+ signature_html: str,
705
+ original: Dict[str, Any],
706
+ ) -> str:
707
+ """Assemble reply body + signature + quoted original message.
708
+
709
+ Used only for replies that carry attachments, which still take the
710
+ EmailMessage path; attachment-free replies use the Gmail-web quote built by
711
+ ``_build_web_reply_bodies``.
712
+
713
+ Layout:
714
+ reply_body
715
+ -- signature --
716
+ On {date}, {sender} wrote:
717
+ > quoted original
718
+ """
719
+ sender = original.get("from") or "unknown"
720
+ if original.get("date"):
721
+ attribution = f"On {original['date']}, {sender} wrote:"
722
+ else:
723
+ attribution = f"{sender} wrote:"
724
+
725
+ if body_format == "html":
726
+ signed_body = _append_signature_to_body(reply_body, "html", signature_html)
727
+
728
+ # Quoted original
729
+ orig_html = original.get("html_body") or ""
730
+ if not orig_html:
731
+ orig_text = original.get("text_body", "")
732
+ orig_html = f"<pre>{html.escape(orig_text)}</pre>"
733
+
734
+ quote_block = (
735
+ '<br><br><div class="gmail_quote">'
736
+ f"<span>{html.escape(attribution)}</span><br>"
737
+ '<blockquote style="margin:0 0 0 .8ex;border-left:1px solid #ccc;padding-left:1ex">'
738
+ f"{orig_html}"
739
+ "</blockquote></div>"
740
+ )
741
+ return f"{signed_body}{quote_block}"
742
+
743
+ # Plain text path
744
+ sig_block = ""
745
+ if signature_html and signature_html.strip():
746
+ sig_text = _signature_html_to_text(signature_html).strip()
747
+ if sig_text:
748
+ sig_block = f"\n\n{sig_text}"
749
+
750
+ orig_text = original.get("text_body") or ""
751
+ if not orig_text and original.get("html_body"):
752
+ orig_text = _html_to_text(original["html_body"])
753
+ quoted_lines = "\n".join(f"> {line}" for line in orig_text.splitlines())
754
+
755
+ return f"{reply_body}{sig_block}\n\n{attribution}\n{quoted_lines}"
756
+
757
+
758
+ def _format_attachment_result(attached_count: int, requested_count: int) -> str:
759
+ """Format attachment result message for user-facing responses."""
760
+ if requested_count <= 0:
761
+ return ""
762
+ if attached_count == requested_count:
763
+ return f" with {attached_count} attachment(s)"
764
+ return f" with {attached_count}/{requested_count} attachment(s) attached"
765
+
766
+
767
+ def _format_attachment_error(
768
+ file_path: Optional[str], filename: Optional[str], error: Exception
769
+ ) -> str:
770
+ """Convert attachment processing failures into user-facing guidance."""
771
+ label = filename or file_path or "attachment"
772
+ detail = str(error)
773
+
774
+ if file_path and isinstance(error, ValueError):
775
+ if "outside permitted directories" in detail:
776
+ detail = (
777
+ "local file access is limited to the server's permitted directories, "
778
+ f"so '{file_path}' could not be read. Files on external mounts such as "
779
+ "/run/media may be blocked; move the file into the managed attachment "
780
+ "directory or another allowed directory, or set ALLOWED_FILE_DIRS."
781
+ )
782
+
783
+ return f"{label}: {detail}"
784
+
785
+
786
+ def _normalize_attachment_content_id(content_id: Any) -> str:
787
+ """Return a header-safe Content-ID value without surrounding brackets."""
788
+ raw = str(content_id)
789
+ if any(ord(ch) < 32 or ord(ch) == 127 for ch in raw):
790
+ raise ValueError("content_id contains invalid control characters")
791
+
792
+ cid_value = raw.strip().strip("<>").strip()
793
+ if not cid_value:
794
+ raise ValueError("content_id must not be empty")
795
+ if not CONTENT_ID_SAFE_RE.fullmatch(cid_value):
796
+ raise ValueError(
797
+ "content_id contains invalid characters; use letters, digits, "
798
+ "'.', '_', '+', '-', or '@'"
799
+ )
800
+ return cid_value
801
+
802
+
803
+ def _format_base64_content_block(urlsafe_b64_data: str) -> List[str]:
804
+ """
805
+ Convert Gmail's URL-safe base64 attachment data to standard base64 and
806
+ format it as a labeled block of result lines.
807
+
808
+ The Gmail API returns attachment bodies in URL-safe base64 (per RFC 4648).
809
+ ``draft_gmail_message`` and most stdlib consumers expect standard base64
810
+ (``base64.b64decode``). Converting here keeps the response self-contained
811
+ so a caller can pass the bytes straight back into the draft flow without
812
+ knowing about the alphabet difference.
813
+
814
+ Args:
815
+ urlsafe_b64_data: URL-safe base64 string as returned by Gmail.
816
+
817
+ Returns:
818
+ A list of strings to extend onto ``result_lines``. On failure to
819
+ decode, returns a single warning line instead of raising.
820
+ """
821
+ try:
822
+ raw_bytes = base64.urlsafe_b64decode(urlsafe_b64_data)
823
+ standard_b64 = base64.b64encode(raw_bytes).decode("ascii")
824
+ return [
825
+ f"\n📦 Base64 content ({len(standard_b64)} chars, standard base64):",
826
+ standard_b64,
827
+ ]
828
+ except (binascii.Error, ValueError) as e:
829
+ logger.warning(
830
+ f"[get_gmail_attachment_content] Failed to convert attachment "
831
+ f"to standard base64: {e}"
832
+ )
833
+ return [f"\n⚠️ Could not include base64 content: {e}"]
834
+
835
+
836
+ def _extract_attachments(payload: dict) -> List[Dict[str, Any]]:
837
+ """
838
+ Extract attachment metadata from a Gmail message payload.
839
+
840
+ Args:
841
+ payload: The message payload from Gmail API
842
+
843
+ Returns:
844
+ List of attachment dictionaries with filename, mimeType, size, and attachmentId
845
+ """
846
+ attachments = []
847
+
848
+ pending = [(payload, False)]
849
+ while pending:
850
+ part, in_attached_message = pending.pop()
851
+ # Check if this part is an attachment
852
+ if part.get("filename") and part.get("body", {}).get("attachmentId"):
853
+ # Files inside a wrapped message (message/rfc822) are fetched with the
854
+ # outer message's ID, so keep them listed but flag their origin.
855
+ attachments.append(
856
+ {
857
+ "filename": part["filename"],
858
+ "mimeType": part.get("mimeType", "application/octet-stream"),
859
+ "size": part.get("body", {}).get("size", 0),
860
+ "attachmentId": part["body"]["attachmentId"],
861
+ "inAttachedMessage": in_attached_message,
862
+ }
863
+ )
864
+
865
+ # Reverse the push order to preserve depth-first attachment ordering.
866
+ if "parts" in part:
867
+ nested = in_attached_message or (
868
+ (part.get("mimeType") or "").lower() == "message/rfc822"
869
+ )
870
+ pending.extend((subpart, nested) for subpart in reversed(part["parts"]))
871
+
872
+ return attachments
873
+
874
+
875
+ ATTACHED_MESSAGE_MAX_DEPTH = 3
876
+ ATTACHED_MESSAGE_MAX_COUNT = 5
877
+ ATTACHED_MESSAGE_HEADER_LIMIT = 1000
878
+
879
+
880
+ def _render_attached_messages(
881
+ payload: dict,
882
+ body_format: Literal["text", "html"] = "text",
883
+ include_headers: bool = True,
884
+ include_links: bool = False,
885
+ ) -> str:
886
+ """Render emails wrapped inside this one (message/rfc822 parts) as text.
887
+
888
+ _extract_message_bodies descends only into multipart/* containers, so a
889
+ wrapped email (forward-as-attachment, moderation notice, bounce, digest) is
890
+ otherwise invisible to the read tools. The wrapped message's MIME tree is
891
+ the child of the message/rfc822 part. Returns "" when there is no such part.
892
+ Wrapped headers are printed as the attachment claims them: unlike the
893
+ wrapper's, they are unverified.
894
+ """
895
+ blocks: List[str] = []
896
+ counts = {"shown": 0, "over_limit": 0, "too_deep": 0}
897
+ names = ["From", "To", "Cc", "Subject", "Date"] if include_headers else []
898
+
899
+ # Depth counts attached messages only; ordinary MIME nesting uses the stack.
900
+ pending = [(child, 1) for child in reversed(payload.get("parts") or [])]
901
+ while pending:
902
+ child, depth = pending.pop()
903
+ mime_type = (child.get("mimeType") or "").lower()
904
+ if mime_type == "message/rfc822" and child.get("parts"):
905
+ if depth > ATTACHED_MESSAGE_MAX_DEPTH:
906
+ counts["too_deep"] += 1
907
+ continue
908
+ if counts["shown"] >= ATTACHED_MESSAGE_MAX_COUNT:
909
+ counts["over_limit"] += 1
910
+ continue
911
+ counts["shown"] += 1
912
+ inner = child["parts"][0]
913
+ # Fall back to the rfc822 part's headers if the inner root lacks them.
914
+ headers = _extract_headers(inner, names) or _extract_headers(child, names)
915
+ bodies = _extract_message_bodies(inner)
916
+ html_body = bodies.get("html", "")
917
+ body = _truncate_content(
918
+ _format_body_content(bodies.get("text", ""), html_body, body_format),
919
+ HTML_BODY_TRUNCATE_LIMIT,
920
+ )
921
+ if include_links and body_format == "text":
922
+ body += format_html_links(html_body, body, HTML_BODY_TRUNCATE_LIMIT)
923
+ lines = [
924
+ f"--- ATTACHED MESSAGE {counts['shown']} (headers as claimed "
925
+ "by the attachment, unverified) ---"
926
+ ]
927
+ for name in names:
928
+ if name in headers:
929
+ value = headers[name]
930
+ if len(value) > ATTACHED_MESSAGE_HEADER_LIMIT:
931
+ value = value[:ATTACHED_MESSAGE_HEADER_LIMIT] + " [truncated]"
932
+ lines.append(f"{name}: {value}")
933
+ lines += ["", body]
934
+ blocks.append("\n".join(lines))
935
+ child = inner
936
+ depth += 1
937
+ # Preserve depth-first rendering and which messages fall within the limit.
938
+ pending.extend((part, depth) for part in reversed(child.get("parts") or []))
939
+
940
+ if counts["over_limit"]:
941
+ blocks.append(
942
+ f"--- {counts['over_limit']} more attached message(s) not shown "
943
+ f"(limit {ATTACHED_MESSAGE_MAX_COUNT}) ---"
944
+ )
945
+ if counts["too_deep"]:
946
+ blocks.append(
947
+ f"--- {counts['too_deep']} attached message(s) nested more than "
948
+ f"{ATTACHED_MESSAGE_MAX_DEPTH} deep not shown ---"
949
+ )
950
+ return "".join(f"\n\n{block}" for block in blocks)
951
+
952
+
953
+ def _find_attachment_metadata(payload: dict, attachment_id: str) -> Optional[dict]:
954
+ """Find one attachment by ID without requiring it to have a filename."""
955
+ body = payload.get("body") or {}
956
+ if body.get("attachmentId") == attachment_id:
957
+ return {
958
+ "filename": payload.get("filename") or None,
959
+ "mimeType": payload.get("mimeType") or "application/octet-stream",
960
+ "size": body.get("size"),
961
+ }
962
+ for part in payload.get("parts") or []:
963
+ match = _find_attachment_metadata(part, attachment_id)
964
+ if match is not None:
965
+ return match
966
+ return None
967
+
968
+
969
+ def _extract_headers(payload: dict, header_names: List[str]) -> Dict[str, str]:
970
+ """
971
+ Extract specified headers from a Gmail message payload.
972
+
973
+ Args:
974
+ payload: The message payload from Gmail API
975
+ header_names: List of header names to extract
976
+
977
+ Returns:
978
+ Dict mapping header names to their values
979
+ """
980
+ headers = {}
981
+ target_headers = {name.lower(): name for name in header_names}
982
+ for header in payload.get("headers", []):
983
+ header_name_lower = header["name"].lower()
984
+ if header_name_lower in target_headers:
985
+ # Store using the original requested casing
986
+ target_name = target_headers[header_name_lower]
987
+ value = header["value"]
988
+ if header_name_lower in {"to", "cc"} and target_name in headers:
989
+ headers[target_name] = ", ".join(
990
+ part for part in (headers[target_name], value) if part
991
+ )
992
+ else:
993
+ headers[target_name] = value
994
+ return headers
995
+
996
+
997
+ async def _fetch_thread_reply_context(
998
+ service,
999
+ thread_id: str,
1000
+ in_reply_to: Optional[str] = None,
1001
+ include_bodies: bool = False,
1002
+ ) -> Optional[Dict[str, Any]]:
1003
+ """Fetch reply metadata for a thread, optionally including message bodies."""
1004
+ header_names = [
1005
+ "Message-ID",
1006
+ "In-Reply-To",
1007
+ "References",
1008
+ "Subject",
1009
+ "From",
1010
+ "Reply-To",
1011
+ "To",
1012
+ "Cc",
1013
+ "Date",
1014
+ ]
1015
+
1016
+ try:
1017
+ request_kwargs = {"userId": "me", "id": thread_id, "format": "full"}
1018
+ if not include_bodies:
1019
+ request_kwargs["fields"] = THREAD_REPLY_CONTEXT_FIELDS
1020
+
1021
+ request = service.users().threads().get(**request_kwargs)
1022
+ thread = await asyncio.to_thread(request.execute)
1023
+ except Exception as e:
1024
+ # 400/404 means the thread_id is wrong, not a transient failure. Falling
1025
+ # through attaches no threadId, silently creating a standalone draft (no
1026
+ # recipient or subject) that still reports success.
1027
+ if _http_error_status(e) in (400, 404):
1028
+ raise UserInputError(
1029
+ f"Thread '{thread_id}' was not found, or is not a valid Gmail API "
1030
+ "thread ID. Use the Thread ID returned by search_gmail_messages or "
1031
+ "get_gmail_thread_content (a hex string such as "
1032
+ "'18c2f3a4b5d6e7f8'). The token in a Gmail web URL is a different "
1033
+ "identifier and cannot be used here."
1034
+ ) from e
1035
+ logger.warning(f"Failed to fetch reply context for thread {thread_id}: {e}")
1036
+ return None
1037
+
1038
+ messages = thread.get("messages", [])
1039
+ if not messages:
1040
+ return None
1041
+
1042
+ message_contexts = []
1043
+ eligible_contexts = []
1044
+ for msg in messages:
1045
+ labels = msg.get("labelIds", [])
1046
+ payload = msg.get("payload", {})
1047
+ headers = _extract_headers(payload, header_names)
1048
+ context = {
1049
+ "message_id": headers.get("Message-ID"),
1050
+ "in_reply_to": headers.get("In-Reply-To"),
1051
+ "references": headers.get("References"),
1052
+ "subject": headers.get("Subject", ""),
1053
+ "from": headers.get("From", ""),
1054
+ "reply_to": headers.get("Reply-To", ""),
1055
+ "to": headers.get("To", ""),
1056
+ "cc": headers.get("Cc", ""),
1057
+ "date": headers.get("Date", ""),
1058
+ }
1059
+ message_contexts.append(context)
1060
+ # Automatic selection only considers actual sent or received messages.
1061
+ # Gmail web renders a reaction as a chip on its parent, so a reply
1062
+ # parented on one is hidden from the conversation view. Keep every
1063
+ # context above so an explicit In-Reply-To can still resolve to the
1064
+ # exact message the caller selected.
1065
+ if (
1066
+ context["message_id"]
1067
+ and "DRAFT" not in labels
1068
+ and "TRASH" not in labels
1069
+ and not _is_email_reaction(payload)
1070
+ ):
1071
+ eligible_contexts.append(context)
1072
+
1073
+ target = None
1074
+ if in_reply_to:
1075
+ for msg in message_contexts:
1076
+ if msg.get("message_id") == in_reply_to:
1077
+ target = msg
1078
+ break
1079
+ elif eligible_contexts:
1080
+ target = eligible_contexts[-1]
1081
+
1082
+ if include_bodies and target:
1083
+ target_msg = next(
1084
+ msg for msg, context in zip(messages, message_contexts) if context is target
1085
+ )
1086
+ body_errors = await fetch_attachment_backed_bodies(service, [target_msg])
1087
+ bodies = _extract_message_bodies(target_msg.get("payload", {}))
1088
+ target["text_body"] = bodies.get("text", "")
1089
+ target["html_body"] = bodies.get("html", "")
1090
+ # A part that failed to load is derived from the other one.
1091
+ if body_errors and not (target["text_body"] or target["html_body"]):
1092
+ target["body_error"] = "; ".join(body_errors)
1093
+
1094
+ return {
1095
+ "messages": eligible_contexts,
1096
+ "message_ids": [
1097
+ msg["message_id"] for msg in eligible_contexts if msg.get("message_id")
1098
+ ],
1099
+ "target": target,
1100
+ }
1101
+
1102
+
1103
+ async def _fetch_thread_message_ids(service, thread_id: str) -> List[str]:
1104
+ """
1105
+ Fetch Message-ID headers from a Gmail thread for reply threading.
1106
+
1107
+ Args:
1108
+ service: Gmail API service instance
1109
+ thread_id: Gmail thread ID
1110
+
1111
+ Returns:
1112
+ Message-IDs in thread order. Returns an empty list on failure.
1113
+ """
1114
+ context = await _fetch_thread_reply_context(service, thread_id)
1115
+ if not context:
1116
+ return []
1117
+ return context.get("message_ids", [])
1118
+
1119
+
1120
+ MAX_EMAIL_ATTACHMENT_BYTES = 25 * 1024 * 1024 # 25 MB Gmail attachment limit
1121
+
1122
+
1123
+ def _redact_url(url: str) -> str:
1124
+ """Remove query/fragment components before surfacing a URL in errors or logs."""
1125
+ parsed = urlparse(url)
1126
+ if not parsed.scheme and not parsed.netloc:
1127
+ return parsed.path or url
1128
+ return urlunsplit((parsed.scheme, parsed.netloc, parsed.path, "", ""))
1129
+
1130
+
1131
+ def _read_attachment_bytes(file_path: Path) -> bytes:
1132
+ """Read a local attachment after enforcing the Gmail size limit."""
1133
+ size_bytes = file_path.stat().st_size
1134
+ if size_bytes > MAX_EMAIL_ATTACHMENT_BYTES:
1135
+ raise ValueError(
1136
+ f"Attachment exceeds {MAX_EMAIL_ATTACHMENT_BYTES} bytes: {file_path.name}"
1137
+ )
1138
+ return file_path.read_bytes()
1139
+
1140
+
1141
+ _ATTACHMENT_TIMEOUT = httpx.Timeout(connect=10, read=30, write=10, pool=10)
1142
+
1143
+
1144
+ async def _download_attachment_bytes(url: str) -> tuple[bytes, httpx.Response]:
1145
+ """Download an attachment with streaming size enforcement."""
1146
+ total_bytes = 0
1147
+ chunks: list[bytes] = []
1148
+ redacted_url = _redact_url(url)
1149
+
1150
+ async with ssrf_safe_stream(url, timeout=_ATTACHMENT_TIMEOUT) as resp:
1151
+ if resp.status_code != 200:
1152
+ raise ValueError(
1153
+ f"Failed to fetch attachment URL {redacted_url} (status {resp.status_code})"
1154
+ )
1155
+
1156
+ async for chunk in resp.aiter_bytes(chunk_size=256 * 1024):
1157
+ total_bytes += len(chunk)
1158
+ if total_bytes > MAX_EMAIL_ATTACHMENT_BYTES:
1159
+ raise ValueError(
1160
+ f"Attachment from {redacted_url} exceeds 25 MB Gmail limit ({total_bytes} bytes)"
1161
+ )
1162
+ chunks.append(chunk)
1163
+
1164
+ return b"".join(chunks), resp
1165
+
1166
+
1167
+ def _build_attachment_error_entry(
1168
+ attachment: Dict[str, Any], exc: Exception
1169
+ ) -> Dict[str, Any]:
1170
+ """Preserve failed attachment context so message creation can continue."""
1171
+ failed_attachment = dict(attachment)
1172
+ if "url" in failed_attachment:
1173
+ failed_attachment["display_url"] = _redact_url(str(failed_attachment["url"]))
1174
+ failed_attachment["error"] = str(exc)
1175
+ failed_attachment["error_type"] = type(exc).__name__
1176
+ return failed_attachment
1177
+
1178
+
1179
+ def _format_resolved_attachment_error(attachment: Dict[str, Any]) -> str:
1180
+ """Render a pre-resolved attachment failure for user-facing reporting."""
1181
+ label = (
1182
+ attachment.get("filename")
1183
+ or attachment.get("display_url")
1184
+ or (
1185
+ _redact_url(str(attachment["url"]))
1186
+ if attachment.get("url")
1187
+ else attachment.get("path")
1188
+ )
1189
+ or "attachment"
1190
+ )
1191
+ detail = attachment.get("error", "attachment could not be resolved")
1192
+ error_type = attachment.get("error_type")
1193
+ if error_type:
1194
+ detail = f"{error_type}: {detail}"
1195
+ return f"{label}: {detail}"
1196
+
1197
+
1198
+ def _try_read_local_attachment(url: str) -> Optional[tuple[bytes, str, Optional[str]]]:
1199
+ """Try to resolve a URL as an MCP attachment stored on local disk.
1200
+
1201
+ Returns (data, filename, mime_type) if the URL points to a local
1202
+ ``/attachments/{file_id}`` resource, otherwise ``None``.
1203
+ """
1204
+ local = resolve_local_attachment(url)
1205
+ if local is None:
1206
+ return None
1207
+ file_path, metadata = local
1208
+ return (
1209
+ _read_attachment_bytes(file_path),
1210
+ metadata["filename"],
1211
+ metadata.get("mime_type"),
1212
+ )
1213
+
1214
+
1215
+ async def _resolve_url_attachments(
1216
+ attachments: Optional[List[Dict[str, Any]]],
1217
+ ) -> Optional[List[Dict[str, Any]]]:
1218
+ """Pre-resolve any URL-based attachments to raw bytes.
1219
+
1220
+ For each attachment dict that carries a ``url`` key:
1221
+ * If the URL matches the MCP's own ``/attachments/{id}`` pattern the file
1222
+ is read directly from :data:`STORAGE_DIR` (avoids HTTP + SSRF blocks on
1223
+ localhost).
1224
+ * Otherwise the URL is fetched via :func:`ssrf_safe_fetch`.
1225
+
1226
+ The resolved entry replaces ``url`` with ``_resolved_bytes`` (raw
1227
+ ``bytes``) so that :func:`_prepare_gmail_message` can attach it without a
1228
+ redundant base64 round-trip.
1229
+ """
1230
+ if not attachments:
1231
+ return attachments
1232
+
1233
+ resolved: List[Dict[str, Any]] = []
1234
+ for att in attachments:
1235
+ if "url" not in att:
1236
+ resolved.append(att)
1237
+ continue
1238
+
1239
+ url = att["url"]
1240
+ filename = att.get("filename")
1241
+ mime_type = att.get("mime_type")
1242
+
1243
+ # Fast path: MCP-local attachment URL.
1244
+ try:
1245
+ local = _try_read_local_attachment(url)
1246
+ except Exception as exc:
1247
+ logger.exception("Failed to read local attachment URL %s", _redact_url(url))
1248
+ resolved.append(_build_attachment_error_entry(att, exc))
1249
+ continue
1250
+ if local is not None:
1251
+ data, local_filename, local_mime = local
1252
+ entry = {
1253
+ "_resolved_bytes": data,
1254
+ "filename": filename or local_filename,
1255
+ "mime_type": mime_type or local_mime,
1256
+ }
1257
+ if "content_id" in att:
1258
+ entry["content_id"] = att["content_id"]
1259
+ resolved.append(entry)
1260
+ continue
1261
+
1262
+ # External URL — SSRF-safe fetch.
1263
+ try:
1264
+ data, resp = await _download_attachment_bytes(url)
1265
+ except Exception as exc:
1266
+ logger.exception("Failed to fetch attachment URL %s", _redact_url(url))
1267
+ resolved.append(_build_attachment_error_entry(att, exc))
1268
+ continue
1269
+
1270
+ # Infer filename from URL path if not provided.
1271
+ if not filename:
1272
+ url_path = urlparse(url).path
1273
+ candidate = unquote(url_path.rsplit("/", 1)[-1]) if url_path else ""
1274
+ filename = candidate if candidate and "." in candidate else "attachment"
1275
+
1276
+ # Infer MIME type from Content-Type header or filename.
1277
+ if not mime_type:
1278
+ ct = resp.headers.get("content-type", "")
1279
+ # Strip parameters (e.g. "text/plain; charset=utf-8")
1280
+ ct_base = ct.split(";", 1)[0].strip()
1281
+ if ct_base and ct_base != "application/octet-stream":
1282
+ mime_type = ct_base
1283
+ elif filename:
1284
+ mime_type, _ = mimetypes.guess_type(filename)
1285
+
1286
+ entry = {
1287
+ "_resolved_bytes": data,
1288
+ "filename": filename,
1289
+ "mime_type": mime_type,
1290
+ }
1291
+ if "content_id" in att:
1292
+ entry["content_id"] = att["content_id"]
1293
+ resolved.append(entry)
1294
+
1295
+ return resolved
1296
+
1297
+
1298
+ def _prepare_gmail_message(
1299
+ subject: str,
1300
+ body: str,
1301
+ to: Optional[str] = None,
1302
+ cc: Optional[str] = None,
1303
+ bcc: Optional[str] = None,
1304
+ thread_id: Optional[str] = None,
1305
+ in_reply_to: Optional[str] = None,
1306
+ references: Optional[str] = None,
1307
+ body_format: Literal["plain", "html"] = "plain",
1308
+ from_email: Optional[str] = None,
1309
+ from_name: Optional[str] = None,
1310
+ attachments: Optional[List[Dict[str, str]]] = None,
1311
+ plain_body: Optional[str] = None,
1312
+ priority: MessagePriority = "normal",
1313
+ direction: TextDirection = "auto",
1314
+ ) -> tuple[str, Optional[str], int, List[str]]:
1315
+ """
1316
+ Prepare a Gmail message with threading and attachment support.
1317
+
1318
+ Args:
1319
+ subject: Email subject
1320
+ body: Email body content
1321
+ to: Optional recipient email address
1322
+ cc: Optional CC email address
1323
+ bcc: Optional BCC email address
1324
+ thread_id: Optional Gmail thread ID to reply within
1325
+ in_reply_to: Optional Message-ID of the message being replied to
1326
+ references: Optional chain of Message-IDs for proper threading
1327
+ body_format: Content type for the email body ('plain' or 'html')
1328
+ from_email: Optional sender email address
1329
+ from_name: Optional sender display name (e.g., "Peter Hartree")
1330
+ attachments: Optional list of attachments. Each can have 'path' (file path) OR 'content' (base64) + 'filename'
1331
+ plain_body: Explicit text alternative for HTML, preserving a forwarded original.
1332
+ priority: Message priority ('high', 'normal' or 'low').
1333
+ direction: Base text direction of the HTML part derived from a plain body.
1334
+
1335
+ Returns:
1336
+ Tuple of (raw_message, thread_id, attached_count, attachment_errors)
1337
+ where raw_message is base64 encoded.
1338
+ """
1339
+ # Prepare the email
1340
+ normalized_format = body_format.lower()
1341
+ if normalized_format not in {"plain", "html"}:
1342
+ raise ValueError("body_format must be either 'plain' or 'html'.")
1343
+
1344
+ attached_count = 0
1345
+ attachment_errors: List[str] = []
1346
+ message = EmailMessage(policy=SMTP)
1347
+
1348
+ message["Subject"] = _reply_subject(subject, in_reply_to)
1349
+
1350
+ # Add sender if provided
1351
+ if from_email:
1352
+ if from_name:
1353
+ # Sanitize from_name to prevent header injection
1354
+ safe_name = (
1355
+ from_name.replace("\r", "").replace("\n", "").replace("\x00", "")
1356
+ )
1357
+ message["From"] = formataddr((safe_name, from_email))
1358
+ else:
1359
+ message["From"] = from_email
1360
+
1361
+ # Add recipients if provided
1362
+ if to:
1363
+ message["To"] = to
1364
+ if cc:
1365
+ message["Cc"] = cc
1366
+ if bcc:
1367
+ message["Bcc"] = bcc
1368
+
1369
+ # Add reply headers for threading
1370
+ if in_reply_to:
1371
+ message["In-Reply-To"] = in_reply_to
1372
+
1373
+ if references:
1374
+ message["References"] = references
1375
+
1376
+ for name, value in _priority_headers(priority):
1377
+ message[name] = value
1378
+
1379
+ if normalized_format == "html":
1380
+ # Include a text/plain fallback so reply drafts and recipients don't
1381
+ # depend on clients successfully parsing HTML-only bodies. This is what
1382
+ # a non-HTML client actually displays, so block boundaries have to
1383
+ # survive -- _html_to_text() flattens them and would run paragraphs
1384
+ # together ("First paragraph.Second paragraph.").
1385
+ if plain_body is None:
1386
+ plain_body = html_to_text_preserving_breaks(body).strip()
1387
+ message.set_content(plain_body)
1388
+ message.add_alternative(body, subtype="html")
1389
+ else:
1390
+ plain_part, html_part = _derive_web_bodies(body, "plain", direction)
1391
+ message.set_content(plain_part)
1392
+ message.add_alternative(html_part, subtype="html")
1393
+
1394
+ seen_content_ids: set[str] = set()
1395
+
1396
+ for attachment in attachments or []:
1397
+ if attachment.get("error"):
1398
+ attachment_errors.append(_format_resolved_attachment_error(attachment))
1399
+ continue
1400
+
1401
+ file_path = attachment.get("path")
1402
+ filename = attachment.get("filename")
1403
+ content_base64 = attachment.get("content")
1404
+ resolved_bytes = attachment.get("_resolved_bytes")
1405
+ mime_type = attachment.get("mime_type")
1406
+ content_id = attachment.get("content_id")
1407
+
1408
+ try:
1409
+ if resolved_bytes is not None:
1410
+ # Pre-resolved from a URL by _resolve_url_attachments.
1411
+ file_data = resolved_bytes
1412
+ if not filename:
1413
+ filename = "attachment"
1414
+ if not mime_type:
1415
+ mime_type = "application/octet-stream"
1416
+ elif file_path:
1417
+ with open_validated_file(file_path) as f:
1418
+ file_data = f.read()
1419
+ path_obj = Path(f.name)
1420
+
1421
+ if not filename:
1422
+ filename = path_obj.name
1423
+
1424
+ if not mime_type:
1425
+ mime_type, _ = mimetypes.guess_type(str(path_obj))
1426
+ if not mime_type:
1427
+ mime_type = "application/octet-stream"
1428
+ elif content_base64:
1429
+ if not filename:
1430
+ logger.warning("Skipping attachment: missing filename")
1431
+ continue
1432
+
1433
+ file_data = base64.b64decode(content_base64)
1434
+ if not mime_type:
1435
+ mime_type = "application/octet-stream"
1436
+ else:
1437
+ logger.warning("Skipping attachment: missing path, content, and url")
1438
+ continue
1439
+
1440
+ safe_filename = (
1441
+ (filename or "attachment")
1442
+ .replace("\r", "")
1443
+ .replace("\n", "")
1444
+ .replace("\x00", "")
1445
+ ) or "attachment"
1446
+
1447
+ main_type, sub_type = (
1448
+ mime_type.split("/", 1)
1449
+ if mime_type and "/" in mime_type
1450
+ else ("application", "octet-stream")
1451
+ )
1452
+ if content_id:
1453
+ cid_value = _normalize_attachment_content_id(content_id)
1454
+ if cid_value in seen_content_ids:
1455
+ logger.warning(
1456
+ "Duplicate content_id on attachment: content_id_len=%d, "
1457
+ "filename_len=%d, path_len=%d; email clients may only "
1458
+ "render one instance",
1459
+ len(cid_value),
1460
+ len(filename) if filename else 0,
1461
+ len(file_path) if file_path else 0,
1462
+ )
1463
+ seen_content_ids.add(cid_value)
1464
+ # Find the right MIME part to attach the inline image to.
1465
+ # First inline image: target text/html (creates multipart/related).
1466
+ # Subsequent inline images: target the existing multipart/related
1467
+ # (appends as sibling). Use walk() for recursive search since
1468
+ # iter_parts() only iterates direct children and html may be nested
1469
+ # inside multipart/related after the first inline image is added.
1470
+ target = None
1471
+ for part in message.walk():
1472
+ if part.get_content_type() == "multipart/related":
1473
+ target = part
1474
+ break
1475
+ if target is None:
1476
+ for part in message.walk():
1477
+ if part.get_content_type() == "text/html":
1478
+ target = part
1479
+ break
1480
+ if target is None:
1481
+ target = message # Plain-text body fallback
1482
+ target.add_related(
1483
+ file_data,
1484
+ maintype=main_type,
1485
+ subtype=sub_type,
1486
+ cid=f"<{cid_value}>",
1487
+ filename=safe_filename,
1488
+ disposition="inline",
1489
+ headers=[f"X-Attachment-Id: {cid_value}"],
1490
+ )
1491
+ logger.info(
1492
+ f"Attached inline: content_id_len={len(cid_value)}, "
1493
+ f"filename_len={len(safe_filename)} ({len(file_data)} bytes)"
1494
+ )
1495
+ else:
1496
+ attachment_id = _new_attachment_id()
1497
+ message.add_attachment(
1498
+ file_data,
1499
+ maintype=main_type,
1500
+ subtype=sub_type,
1501
+ filename=safe_filename,
1502
+ cid=f"<{attachment_id}>",
1503
+ headers=[f"X-Attachment-Id: {attachment_id}"],
1504
+ )
1505
+ logger.info(
1506
+ f"Attached file: filename_len={len(safe_filename)} "
1507
+ f"({len(file_data)} bytes)"
1508
+ )
1509
+ attached_count += 1
1510
+ except (binascii.Error, ValueError) as e:
1511
+ logger.error(
1512
+ f"Failed to decode attachment: "
1513
+ f"filename_len={len(filename) if filename else 0}, "
1514
+ f"path_len={len(file_path) if file_path else 0}, "
1515
+ f"error_type={type(e).__name__}"
1516
+ )
1517
+ attachment_errors.append(_format_attachment_error(file_path, filename, e))
1518
+ continue
1519
+ except Exception as e:
1520
+ logger.error(
1521
+ f"Failed to attach: filename_len={len(filename) if filename else 0}, "
1522
+ f"path_len={len(file_path) if file_path else 0}, "
1523
+ f"error_type={type(e).__name__}"
1524
+ )
1525
+ attachment_errors.append(_format_attachment_error(file_path, filename, e))
1526
+ continue
1527
+
1528
+ # Encode message
1529
+ raw_message = base64.urlsafe_b64encode(message.as_bytes(policy=SMTP)).decode()
1530
+
1531
+ return raw_message, thread_id, attached_count, attachment_errors
1532
+
1533
+
1534
+ async def _fetch_search_result_headers(
1535
+ service, message_ids: List[str]
1536
+ ) -> Dict[str, Optional[Dict[str, str]]]:
1537
+ """Fetch metadata headers for search result message IDs.
1538
+
1539
+ Uses the Gmail batch HTTP endpoint (one request per
1540
+ GMAIL_SEARCH_HEADER_BATCH_SIZE chunk, with a delay between chunks),
1541
+ falling back to sequential fetches with a delay if the batch API fails.
1542
+ Messages that fail inside a batch (typically transient per-user
1543
+ concurrency 429s) are retried sequentially afterwards. A message that
1544
+ still cannot be fetched maps to None so the caller can degrade that row
1545
+ instead of failing the whole search.
1546
+ """
1547
+ headers_by_id: Dict[str, Optional[Dict[str, str]]] = {}
1548
+
1549
+ for chunk_start in range(0, len(message_ids), GMAIL_SEARCH_HEADER_BATCH_SIZE):
1550
+ if chunk_start:
1551
+ await asyncio.sleep(GMAIL_REQUEST_DELAY)
1552
+ chunk_ids = message_ids[
1553
+ chunk_start : chunk_start + GMAIL_SEARCH_HEADER_BATCH_SIZE
1554
+ ]
1555
+ results: Dict[str, Dict] = {}
1556
+
1557
+ def _batch_callback(request_id, response, exception):
1558
+ results[request_id] = {"data": response, "error": exception}
1559
+
1560
+ try:
1561
+ batch = service.new_batch_http_request(callback=_batch_callback)
1562
+ for mid in chunk_ids:
1563
+ batch.add(
1564
+ _build_message_get_request(
1565
+ service, message_id=mid, message_format="metadata"
1566
+ ),
1567
+ request_id=mid,
1568
+ )
1569
+ await asyncio.to_thread(batch.execute)
1570
+ except Exception as batch_error:
1571
+ logger.warning(
1572
+ f"[search_gmail_messages] Batch metadata fetch failed, falling back to sequential processing: {batch_error}"
1573
+ )
1574
+ for mid in chunk_ids:
1575
+ mid_result, msg_data, error = await _fetch_message_with_retry(
1576
+ service,
1577
+ message_id=mid,
1578
+ message_format="metadata",
1579
+ log_prefix="search_gmail_messages",
1580
+ )
1581
+ results[mid_result] = {"data": msg_data, "error": error}
1582
+ await asyncio.sleep(GMAIL_REQUEST_DELAY)
1583
+
1584
+ for mid in chunk_ids:
1585
+ entry = results.get(mid, {"data": None, "error": "No result"})
1586
+ if entry["error"] or not entry["data"]:
1587
+ if entry["error"]:
1588
+ logger.debug(
1589
+ f"[search_gmail_messages] Metadata fetch failed for message {mid}, will retry: {entry['error']}"
1590
+ )
1591
+ headers_by_id[mid] = None
1592
+ else:
1593
+ try:
1594
+ headers_by_id[mid] = _extract_search_metadata(entry["data"])
1595
+ except Exception as exc:
1596
+ logger.warning(
1597
+ f"[search_gmail_messages] Invalid metadata for message {mid}, will retry: {exc}"
1598
+ )
1599
+ headers_by_id[mid] = None
1600
+
1601
+ # Retry failures one at a time. Batch failures are usually Gmail's
1602
+ # per-user concurrency limit (429), which sequential requests don't hit.
1603
+ failed_ids = [mid for mid in message_ids if headers_by_id.get(mid) is None]
1604
+ if failed_ids:
1605
+ logger.info(
1606
+ f"[search_gmail_messages] Retrying {len(failed_ids)} failed metadata fetches sequentially"
1607
+ )
1608
+ for mid in failed_ids:
1609
+ await asyncio.sleep(GMAIL_REQUEST_DELAY)
1610
+ _, msg_data, error = await _fetch_message_with_retry(
1611
+ service,
1612
+ message_id=mid,
1613
+ message_format="metadata",
1614
+ log_prefix="search_gmail_messages",
1615
+ )
1616
+ if msg_data and not error:
1617
+ try:
1618
+ headers_by_id[mid] = _extract_search_metadata(msg_data)
1619
+ except Exception as exc:
1620
+ logger.warning(
1621
+ f"[search_gmail_messages] Invalid metadata for message {mid} after retry: {exc}"
1622
+ )
1623
+ else:
1624
+ logger.warning(
1625
+ f"[search_gmail_messages] Metadata fetch failed for message {mid} after retry: {error}"
1626
+ )
1627
+
1628
+ return headers_by_id
1629
+
1630
+
1631
+ def _extract_search_metadata(message: Dict[str, Any]) -> Dict[str, str]:
1632
+ """Return a metadata fetch's headers, plus its label IDs under ``Labels`` if any."""
1633
+ metadata = _extract_headers(message.get("payload") or {}, GMAIL_METADATA_HEADERS)
1634
+ if label_ids := message.get("labelIds"):
1635
+ metadata["Labels"] = ", ".join(label_ids)
1636
+ return metadata
1637
+
1638
+
1639
+ def _format_gmail_results_plain(
1640
+ messages: list,
1641
+ query: str,
1642
+ next_page_token: Optional[str] = None,
1643
+ headers_by_id: Optional[Dict[str, Optional[Dict[str, str]]]] = None,
1644
+ user_google_email: Optional[str] = None,
1645
+ ) -> str:
1646
+ """Format Gmail search results in clean, LLM-friendly plain text."""
1647
+ if not messages:
1648
+ return f"No messages found for query: '{query}'"
1649
+
1650
+ lines = [
1651
+ f"Found {len(messages)} messages matching '{query}':",
1652
+ "",
1653
+ "📧 MESSAGES:",
1654
+ ]
1655
+
1656
+ for i, msg in enumerate(messages, 1):
1657
+ # Handle potential null/undefined message objects
1658
+ if not msg or not isinstance(msg, dict):
1659
+ lines.extend(
1660
+ [
1661
+ f" {i}. Message: Invalid message data",
1662
+ " Error: Message object is null or malformed",
1663
+ "",
1664
+ ]
1665
+ )
1666
+ continue
1667
+
1668
+ # Handle potential null/undefined values from Gmail API
1669
+ message_id = msg.get("id")
1670
+ thread_id = msg.get("threadId")
1671
+
1672
+ # Convert None, empty string, or missing values to "unknown"
1673
+ if not message_id:
1674
+ message_id = "unknown"
1675
+ if not thread_id:
1676
+ thread_id = "unknown"
1677
+
1678
+ if message_id != "unknown":
1679
+ message_url = _generate_gmail_web_url(
1680
+ message_id, user_google_email=user_google_email
1681
+ )
1682
+ else:
1683
+ message_url = "N/A"
1684
+
1685
+ if thread_id != "unknown":
1686
+ thread_url = _generate_gmail_web_url(
1687
+ thread_id, user_google_email=user_google_email
1688
+ )
1689
+ else:
1690
+ thread_url = "N/A"
1691
+
1692
+ lines.append(f" {i}. Message ID: {message_id}")
1693
+
1694
+ if headers_by_id is not None:
1695
+ headers = headers_by_id.get(message_id)
1696
+ if headers is None:
1697
+ lines.append(" Headers: unavailable (metadata fetch failed)")
1698
+ else:
1699
+ lines.extend(
1700
+ [
1701
+ f" Subject: {headers.get('Subject', '(no subject)')}",
1702
+ f" From: {headers.get('From', '(unknown sender)')}",
1703
+ f" Date: {headers.get('Date', '(unknown date)')}",
1704
+ ]
1705
+ )
1706
+ if headers.get("Labels"):
1707
+ lines.append(f" Labels: {headers['Labels']}")
1708
+
1709
+ lines.extend(
1710
+ [
1711
+ f" Web Link: {message_url}",
1712
+ f" Thread ID: {thread_id}",
1713
+ f" Thread Link: {thread_url}",
1714
+ "",
1715
+ ]
1716
+ )
1717
+
1718
+ lines.extend(
1719
+ [
1720
+ "💡 USAGE:",
1721
+ " • Pass the Message IDs **as a list** to get_gmail_messages_content_batch()",
1722
+ " e.g. get_gmail_messages_content_batch(message_ids=[...])",
1723
+ " • Pass the Thread IDs to get_gmail_thread_content() (single) or get_gmail_threads_content_batch() (batch)",
1724
+ ]
1725
+ )
1726
+
1727
+ # Add pagination info if there's a next page
1728
+ if next_page_token:
1729
+ lines.append("")
1730
+ lines.append(
1731
+ f"📄 PAGINATION: To get the next page, call search_gmail_messages again with page_token='{next_page_token}'"
1732
+ )
1733
+
1734
+ return "\n".join(lines)
1735
+
1736
+
1737
+ @server.tool(
1738
+ title="Search Gmail Messages",
1739
+ annotations=ToolAnnotations(
1740
+ readOnlyHint=True,
1741
+ destructiveHint=False,
1742
+ idempotentHint=True,
1743
+ openWorldHint=True,
1744
+ ),
1745
+ )
1746
+ @handle_http_errors("search_gmail_messages", is_read_only=True, service_type="gmail")
1747
+ @require_google_service("gmail", "gmail_read")
1748
+ async def search_gmail_messages(
1749
+ service,
1750
+ query: str,
1751
+ user_google_email: str,
1752
+ page_size: int = 10,
1753
+ page_token: Optional[str] = None,
1754
+ include_headers: bool = False,
1755
+ ) -> str:
1756
+ """
1757
+ Searches messages in a user's Gmail account based on a query.
1758
+ Returns both Message IDs and Thread IDs for each found message, along with Gmail web interface links for manual verification.
1759
+ Supports pagination via page_token parameter.
1760
+
1761
+ Args:
1762
+ query (str): The search query. Supports standard Gmail search operators.
1763
+ Results include drafts unless the query excludes them (e.g. in:sent or -in:drafts).
1764
+ user_google_email (str): The user's Google email address. Required.
1765
+ page_size (int): The maximum number of messages to return. Defaults to 10.
1766
+ page_token (Optional[str]): Token for retrieving the next page of results. Use the next_page_token from a previous response.
1767
+ include_headers (bool): If True, also fetch each message's metadata and include
1768
+ Subject, From, Date and label IDs (e.g. DRAFT, SENT) per result. Costs one
1769
+ metadata get per result, grouped into HTTP batches of up to 10, plus retries
1770
+ for transient failures.
1771
+ Defaults to False (output unchanged from prior versions).
1772
+
1773
+ Returns:
1774
+ str: LLM-friendly structured results with Message IDs, Thread IDs, and clickable Gmail web interface URLs for each found message.
1775
+ With include_headers=True, each result also includes Subject, From, Date and Labels.
1776
+ Includes pagination token if more results are available.
1777
+ """
1778
+ logger.info(
1779
+ f"[search_gmail_messages] Email: '{user_google_email}', query_len={len(query)}, Page size: {page_size}"
1780
+ )
1781
+ logger.debug(f"[search_gmail_messages] Query: '{query}'")
1782
+
1783
+ # Build the API request parameters
1784
+ request_params = {"userId": "me", "q": query, "maxResults": page_size}
1785
+
1786
+ # Add page token if provided
1787
+ if page_token:
1788
+ request_params["pageToken"] = page_token
1789
+ logger.info("[search_gmail_messages] Using page_token for pagination")
1790
+
1791
+ response = await asyncio.to_thread(
1792
+ service.users().messages().list(**request_params).execute
1793
+ )
1794
+
1795
+ # Handle potential null response (but empty dict {} is valid)
1796
+ if response is None:
1797
+ logger.warning("[search_gmail_messages] Null response from Gmail API")
1798
+ return f"No response received from Gmail API for query: '{query}'"
1799
+
1800
+ messages = response.get("messages", [])
1801
+ # Additional safety check for null messages array
1802
+ if messages is None:
1803
+ messages = []
1804
+
1805
+ # Extract next page token for pagination
1806
+ next_page_token = response.get("nextPageToken")
1807
+
1808
+ headers_by_id: Optional[Dict[str, Optional[Dict[str, str]]]] = None
1809
+ if include_headers and messages:
1810
+ result_ids = [
1811
+ msg["id"]
1812
+ for msg in messages
1813
+ if msg and isinstance(msg, dict) and msg.get("id")
1814
+ ]
1815
+ try:
1816
+ headers_by_id = await _fetch_search_result_headers(service, result_ids)
1817
+ except Exception as exc:
1818
+ logger.exception(
1819
+ "[search_gmail_messages] Header enrichment failed; "
1820
+ "returning search results without headers: %s",
1821
+ exc,
1822
+ )
1823
+ headers_by_id = dict.fromkeys(result_ids)
1824
+
1825
+ formatted_output = _format_gmail_results_plain(
1826
+ messages, query, next_page_token, headers_by_id, user_google_email
1827
+ )
1828
+
1829
+ logger.info(f"[search_gmail_messages] Found {len(messages)} messages")
1830
+ if next_page_token:
1831
+ logger.info(
1832
+ "[search_gmail_messages] More results available (next_page_token present)"
1833
+ )
1834
+ return formatted_output
1835
+
1836
+
1837
+ @server.tool(
1838
+ title="Get Gmail Message Content",
1839
+ annotations=ToolAnnotations(
1840
+ readOnlyHint=True,
1841
+ destructiveHint=False,
1842
+ idempotentHint=True,
1843
+ openWorldHint=True,
1844
+ ),
1845
+ )
1846
+ @handle_http_errors(
1847
+ "get_gmail_message_content", is_read_only=True, service_type="gmail"
1848
+ )
1849
+ @require_google_service("gmail", "gmail_read")
1850
+ async def get_gmail_message_content(
1851
+ service,
1852
+ message_id: str,
1853
+ user_google_email: str,
1854
+ body_format: Annotated[
1855
+ Literal["text", "html", "raw"],
1856
+ Field(
1857
+ description=(
1858
+ "Body output format (only applies when format='full'). "
1859
+ "'text' (default) returns plaintext (HTML converted to text as fallback). "
1860
+ "'html' returns the raw HTML body as-is without conversion. "
1861
+ "'raw' fetches the full raw MIME message and returns the base64url-decoded content."
1862
+ ),
1863
+ ),
1864
+ ] = "text",
1865
+ full: Annotated[
1866
+ bool,
1867
+ Field(
1868
+ description=(
1869
+ "When True, return the COMPLETE untruncated message: saved to "
1870
+ "storage and referenced by download URL/file path instead of the body "
1871
+ "text. In stateless mode without GCS staging, the body is returned "
1872
+ "inline; with GCS staging, a signed download URL is returned. Use for "
1873
+ "messages large enough to hit the truncation limit, or when byte-exact "
1874
+ "fidelity is needed (pair with body_format='raw' for a .eml export)."
1875
+ ),
1876
+ ),
1877
+ ] = False,
1878
+ format: Literal["full", "metadata"] = "full",
1879
+ include_headers: bool = True,
1880
+ include_links: Annotated[
1881
+ bool, Field(description=INCLUDE_LINKS_DESCRIPTION)
1882
+ ] = False,
1883
+ page_offset: Annotated[
1884
+ Optional[int],
1885
+ Field(
1886
+ ge=0,
1887
+ description="Character offset in the complete rendered body. Start at 0 and follow next_offset.",
1888
+ ),
1889
+ ] = None,
1890
+ page_size: Annotated[int, Field(ge=1, le=20000)] = 20000,
1891
+ expected_sha256: Optional[str] = None,
1892
+ ) -> str:
1893
+ """
1894
+ Retrieves the full content (subject, sender, recipients, body) of a specific Gmail message.
1895
+
1896
+ Set page_offset=0 to read the complete rendered body, excluding attachments and
1897
+ attached messages, as JSON pages of at most page_size characters. Follow
1898
+ next_offset until complete=true, passing body_sha256 as expected_sha256 and
1899
+ keeping body_format and include_links unchanged.
1900
+
1901
+ Bodies are returned inline and truncated at 20,000 characters. Set full=True to
1902
+ get the complete, untruncated message instead: it is exported to storage and the
1903
+ response carries a short-lived download URL (HTTP transport) or file path (stdio
1904
+ transport) rather than the body, so large messages never stream through the model
1905
+ context. Stateless deployments without GCS staging have no storage, so there
1906
+ full=True returns the untruncated body inline; with GCS staging configured it
1907
+ returns a signed download URL like any other HTTP deployment.
1908
+
1909
+ Args:
1910
+ message_id (str): The unique ID of the Gmail message to retrieve.
1911
+ user_google_email (str): The user's Google email address. Required.
1912
+ body_format (Literal["text", "html", "raw"]): Body output format (only applies
1913
+ when format='full').
1914
+ "text" (default) returns plaintext (HTML converted to text as fallback).
1915
+ "html" returns the raw HTML body as-is without conversion.
1916
+ "raw" fetches the full raw MIME message and returns the base64url-decoded content.
1917
+ full (bool): When True, write the untruncated message to storage and
1918
+ return its URL/path instead of the body. body_format selects the exported
1919
+ file type: "raw" saves the byte-exact RFC 5322 message as .eml, "html"
1920
+ saves the raw HTML body, "text" saves the plaintext body. The "html"/"text"
1921
+ exports are re-encoded as UTF-8 from the declared charset, so prefer "raw" when
1922
+ byte-exact fidelity matters. In stateless mode without GCS staging there is
1923
+ no storage to write to, so the untruncated content is returned inline
1924
+ instead; with GCS staging it is saved and returned as a signed URL.
1925
+ format (Literal["full", "metadata"]): Message format. "full" (default) includes
1926
+ the body and attachments, "metadata" only headers.
1927
+ include_headers (bool): When False, omit the Subject/From/To/Date header
1928
+ summary (attached messages' too), and with full=True name the export
1929
+ after the message ID. Requires format='full'; body_format='raw' is only
1930
+ allowed when the raw message is exported to a file.
1931
+ include_links (bool): Append the HTML body's http(s) links missing from the text output.
1932
+ page_offset (int): Start position in the complete rendered body. Requires
1933
+ format="full", full=False, and body_format="text" or "html".
1934
+ page_size (int): Maximum body characters per page, between 1 and 20,000.
1935
+ expected_sha256 (str): Optional previous body_sha256; rejects changed content.
1936
+
1937
+ Returns:
1938
+ str: The message details including subject, sender, date, Message-ID, recipients
1939
+ (To, Cc), and body content — or, when full=True, the saved file's download
1940
+ URL or path in place of the body (inline only in stateless mode without
1941
+ GCS staging).
1942
+ """
1943
+ logger.info(
1944
+ f"[get_gmail_message_content] Invoked. Message ID: '{message_id}', "
1945
+ f"Email: '{user_google_email}', format='{format}', "
1946
+ f"body_format='{body_format}', full={full}"
1947
+ )
1948
+ _validate_message_format_options(format, body_format)
1949
+ if page_offset is not None:
1950
+ if full or format != "full" or body_format == "raw":
1951
+ raise UserInputError(
1952
+ "Body pagination requires full=False, format='full', and body_format='text' or 'html'."
1953
+ )
1954
+ elif expected_sha256 is not None or page_size != 20000:
1955
+ raise UserInputError("expected_sha256 and page_size require page_offset.")
1956
+ if format == "metadata" and full:
1957
+ raise UserInputError("full=True requires format='full'.")
1958
+ if format == "metadata" and not include_headers:
1959
+ raise UserInputError("include_headers=False requires format='full'.")
1960
+ if (
1961
+ not include_headers
1962
+ and body_format == "raw"
1963
+ and (not full or (is_stateless_mode() and not gcs_files_enabled()))
1964
+ ):
1965
+ raise UserInputError(
1966
+ "include_headers=False cannot hide the headers in inline raw MIME; "
1967
+ "use body_format='text' or a full=True file export."
1968
+ )
1969
+
1970
+ # Fetch message metadata first to get headers
1971
+ message_metadata = await asyncio.to_thread(
1972
+ service.users()
1973
+ .messages()
1974
+ .get(
1975
+ userId="me",
1976
+ id=message_id,
1977
+ format="metadata",
1978
+ metadataHeaders=GMAIL_METADATA_HEADERS,
1979
+ )
1980
+ .execute
1981
+ )
1982
+
1983
+ headers = _extract_headers(
1984
+ message_metadata.get("payload", {}), GMAIL_METADATA_HEADERS
1985
+ )
1986
+
1987
+ if page_offset is not None:
1988
+ page = await read_gmail_message_page(
1989
+ service,
1990
+ message_id,
1991
+ message_metadata.get("sizeEstimate"),
1992
+ body_format,
1993
+ page_offset,
1994
+ page_size,
1995
+ expected_sha256,
1996
+ partial(_format_body_content, include_links=include_links),
1997
+ account=user_google_email,
1998
+ include_links=include_links,
1999
+ )
2000
+ if include_headers:
2001
+ page["headers"] = headers
2002
+ return json.dumps(page, ensure_ascii=False)
2003
+
2004
+ content_lines = _format_message_header_lines(headers) if include_headers else []
2005
+ if format == "metadata":
2006
+ return "\n".join(content_lines)
2007
+
2008
+ # Full export: hand back a file reference instead of the (truncated) body.
2009
+ if full:
2010
+ return await _export_full_message(
2011
+ service,
2012
+ message_id,
2013
+ headers,
2014
+ body_format,
2015
+ declared_size=message_metadata.get("sizeEstimate"),
2016
+ include_headers=include_headers,
2017
+ include_links=include_links,
2018
+ )
2019
+
2020
+ # Handle raw format separately - fetch with format="raw" and return decoded MIME
2021
+ if body_format == "raw":
2022
+ message_raw = await asyncio.to_thread(
2023
+ service.users()
2024
+ .messages()
2025
+ .get(userId="me", id=message_id, format="raw")
2026
+ .execute
2027
+ )
2028
+ decoded_raw = _decode_raw_mime_content(message_raw.get("raw", ""))
2029
+
2030
+ content_lines.append(f"\n--- RAW MIME ---\n{decoded_raw}")
2031
+ return "\n".join(content_lines)
2032
+
2033
+ # Now fetch the full message to get the body parts
2034
+ message_full = await asyncio.to_thread(
2035
+ service.users()
2036
+ .messages()
2037
+ .get(
2038
+ userId="me",
2039
+ id=message_id,
2040
+ format="full", # Request full payload for body
2041
+ )
2042
+ .execute
2043
+ )
2044
+
2045
+ # Extract both text and HTML bodies using enhanced helper function
2046
+ await fetch_attachment_backed_bodies(service, [message_full])
2047
+ payload = message_full.get("payload", {})
2048
+ bodies = _extract_message_bodies(payload)
2049
+ text_body = bodies.get("text", "")
2050
+ html_body = bodies.get("html", "")
2051
+
2052
+ # Format body content with HTML fallback
2053
+ body_data = _format_body_content(
2054
+ text_body, html_body, body_format=body_format, include_links=include_links
2055
+ )
2056
+
2057
+ # Extract attachment metadata
2058
+ attachments = _extract_attachments(payload)
2059
+
2060
+ attached = _render_attached_messages(
2061
+ payload, body_format, include_headers, include_links
2062
+ )
2063
+ content_lines.append(
2064
+ f"\n--- BODY ---\n{body_data or '[No text/plain body found]'}{attached}"
2065
+ )
2066
+
2067
+ # Add attachment information if present
2068
+ if attachments:
2069
+ content_lines.append("\n--- ATTACHMENTS ---")
2070
+ for attachment_index, att in enumerate(attachments):
2071
+ size_kb = att["size"] / 1024
2072
+ content_lines.append(
2073
+ f"{attachment_index + 1}. {att['filename']} ({att['mimeType']}, {size_kb:.1f} KB){' [in attached message]' if att.get('inAttachedMessage') else ''}\n"
2074
+ f" Attachment ID: {att['attachmentId']}\n"
2075
+ f" Use get_gmail_attachment_content(message_id='{message_id}', "
2076
+ f"attachment_id='{att['attachmentId']}', attachment_index={attachment_index}) to download"
2077
+ )
2078
+
2079
+ return "\n".join(content_lines)
2080
+
2081
+
2082
+ @server.tool(
2083
+ title="Get Gmail Messages Content Batch",
2084
+ annotations=ToolAnnotations(
2085
+ readOnlyHint=True,
2086
+ destructiveHint=False,
2087
+ idempotentHint=True,
2088
+ openWorldHint=True,
2089
+ ),
2090
+ )
2091
+ @handle_http_errors(
2092
+ "get_gmail_messages_content_batch", is_read_only=True, service_type="gmail"
2093
+ )
2094
+ @require_google_service("gmail", "gmail_read")
2095
+ async def get_gmail_messages_content_batch(
2096
+ service,
2097
+ message_ids: StringList,
2098
+ user_google_email: str,
2099
+ format: Literal["full", "metadata"] = "full",
2100
+ body_format: Annotated[
2101
+ Literal["text", "html", "raw"],
2102
+ Field(
2103
+ description=(
2104
+ "Body output format (only applies when format='full'). "
2105
+ "'text' (default) returns plaintext (HTML converted to text as fallback). "
2106
+ "'html' returns the raw HTML body as-is without conversion. "
2107
+ "'raw' fetches the full raw MIME message and returns the base64url-decoded content."
2108
+ ),
2109
+ ),
2110
+ ] = "text",
2111
+ include_links: Annotated[
2112
+ bool, Field(description=INCLUDE_LINKS_DESCRIPTION)
2113
+ ] = False,
2114
+ ) -> str:
2115
+ """
2116
+ Retrieves the content of multiple Gmail messages in a single batch request.
2117
+ Supports up to 25 messages per batch to prevent SSL connection exhaustion.
2118
+
2119
+ Args:
2120
+ message_ids (List[str]): List of Gmail message IDs to retrieve; fetched in batches of 25.
2121
+ user_google_email (str): The user's Google email address. Required.
2122
+ format (Literal["full", "metadata"]): Message format. "full" includes body, "metadata" only headers.
2123
+ body_format (Literal["text", "html", "raw"]): Body output format (only applies when format='full').
2124
+ "text" (default) returns plaintext (HTML converted to text as fallback).
2125
+ "html" returns the raw HTML body as-is without conversion.
2126
+ "raw" fetches the full raw MIME message and returns the base64url-decoded content.
2127
+ include_links (bool): Append the HTML body's http(s) links missing from the text output.
2128
+
2129
+ Returns:
2130
+ str: A formatted list of message contents including subject, sender, date, Message-ID, recipients (To, Cc), and body (if full format).
2131
+ """
2132
+ logger.info(
2133
+ f"[get_gmail_messages_content_batch] Invoked. Message count: {len(message_ids)}, Email: '{user_google_email}'"
2134
+ )
2135
+
2136
+ if not message_ids:
2137
+ raise UserInputError("No message IDs provided")
2138
+ _validate_message_format_options(format, body_format)
2139
+
2140
+ output_messages = []
2141
+ message_format: Literal["metadata", "full"] = (
2142
+ "metadata" if format == "metadata" or body_format == "raw" else "full"
2143
+ )
2144
+
2145
+ # Process in smaller chunks to prevent SSL connection exhaustion
2146
+ for chunk_start in range(0, len(message_ids), GMAIL_BATCH_SIZE):
2147
+ chunk_ids = message_ids[chunk_start : chunk_start + GMAIL_BATCH_SIZE]
2148
+ results: Dict[str, Dict] = {}
2149
+
2150
+ def _batch_callback(request_id, response, exception):
2151
+ """Callback for batch requests"""
2152
+ results[request_id] = {"data": response, "error": exception}
2153
+
2154
+ batch_completed = False
2155
+
2156
+ # Try to use batch API
2157
+ try:
2158
+ batch = service.new_batch_http_request(callback=_batch_callback)
2159
+
2160
+ for mid in chunk_ids:
2161
+ req = _build_message_get_request(
2162
+ service, message_id=mid, message_format=message_format
2163
+ )
2164
+ batch.add(req, request_id=mid)
2165
+
2166
+ # Execute batch request
2167
+ await asyncio.to_thread(batch.execute)
2168
+ batch_completed = True
2169
+
2170
+ except Exception as batch_error:
2171
+ # Fallback to sequential processing instead of parallel to prevent SSL exhaustion
2172
+ logger.warning(
2173
+ f"[get_gmail_messages_content_batch] Batch API failed, falling back to sequential processing: {batch_error}"
2174
+ )
2175
+
2176
+ # Process messages sequentially with small delays to prevent connection exhaustion
2177
+ for mid in chunk_ids:
2178
+ mid_result, msg_data, error = await _fetch_message_with_retry(
2179
+ service,
2180
+ message_id=mid,
2181
+ message_format=message_format,
2182
+ log_prefix="get_gmail_messages_content_batch",
2183
+ )
2184
+ results[mid_result] = {"data": msg_data, "error": error}
2185
+ # Brief delay between requests to allow connection cleanup
2186
+ await asyncio.sleep(GMAIL_REQUEST_DELAY)
2187
+
2188
+ # Sub-requests that failed with a transient error (e.g. 429 rate limit)
2189
+ # inside an otherwise successful batch response: re-fetch only those IDs
2190
+ # and merge. The sequential fallback has already exhausted its retries.
2191
+ retryable_ids = (
2192
+ _retryable_result_ids(results, chunk_ids) if batch_completed else []
2193
+ )
2194
+ if retryable_ids:
2195
+ logger.warning(
2196
+ f"[get_gmail_messages_content_batch] {len(retryable_ids)}/{len(chunk_ids)} "
2197
+ f"messages failed with retryable errors; re-fetching: {retryable_ids}"
2198
+ )
2199
+ # Backoff briefly so the rate limit has time to reset.
2200
+ await asyncio.sleep(GMAIL_RATE_LIMIT_BACKOFF)
2201
+ for mid in retryable_ids:
2202
+ mid_result, msg_data, error = await _fetch_message_with_retry(
2203
+ service,
2204
+ message_id=mid,
2205
+ message_format=message_format,
2206
+ log_prefix="get_gmail_messages_content_batch",
2207
+ )
2208
+ results[mid_result] = {"data": msg_data, "error": error}
2209
+ await asyncio.sleep(GMAIL_REQUEST_DELAY)
2210
+
2211
+ raw_contents: Optional[Dict[str, str]] = None
2212
+ if format != "metadata" and body_format == "raw":
2213
+ raw_message_ids = [
2214
+ mid for mid in chunk_ids if not results.get(mid, {}).get("error")
2215
+ ]
2216
+ raw_contents = await _fetch_raw_message_contents(
2217
+ service,
2218
+ raw_message_ids,
2219
+ log_prefix="get_gmail_messages_content_batch",
2220
+ )
2221
+
2222
+ # Process results for this chunk
2223
+ for mid in chunk_ids:
2224
+ entry = results.get(mid, {"data": None, "error": "No result"})
2225
+
2226
+ if entry["error"]:
2227
+ output_messages.append(f"⚠️ Message {mid}: {entry['error']}\n")
2228
+ else:
2229
+ message = entry["data"]
2230
+ if not message:
2231
+ output_messages.append(f"⚠️ Message {mid}: No data returned\n")
2232
+ continue
2233
+
2234
+ # Extract content based on format
2235
+ payload = message.get("payload", {})
2236
+
2237
+ if format == "metadata":
2238
+ headers = _extract_headers(payload, GMAIL_METADATA_HEADERS)
2239
+ msg_output = "\n".join(
2240
+ _format_message_header_lines(headers, message_id=mid)
2241
+ )
2242
+ msg_output += f"\nWeb Link: {_generate_gmail_web_url(mid, user_google_email=user_google_email)}\n"
2243
+
2244
+ output_messages.append(msg_output)
2245
+ else:
2246
+ headers = _extract_headers(payload, GMAIL_METADATA_HEADERS)
2247
+ if body_format == "raw":
2248
+ body_data = (
2249
+ raw_contents.get(
2250
+ mid, "[Failed to fetch raw MIME: No result]"
2251
+ )
2252
+ if raw_contents
2253
+ else "[Failed to fetch raw MIME: No result]"
2254
+ )
2255
+ body_label = "RAW MIME"
2256
+ else:
2257
+ # Full format - extract body too
2258
+ await fetch_attachment_backed_bodies(service, [message])
2259
+ bodies = _extract_message_bodies(payload)
2260
+ text_body = bodies.get("text", "")
2261
+ html_body = bodies.get("html", "")
2262
+ body_data = _format_body_content(
2263
+ text_body,
2264
+ html_body,
2265
+ body_format=body_format,
2266
+ include_links=include_links,
2267
+ ) + _render_attached_messages(
2268
+ payload, body_format, include_links=include_links
2269
+ )
2270
+ body_label = "BODY"
2271
+
2272
+ attachments = _extract_attachments(payload)
2273
+
2274
+ msg_output = "\n".join(
2275
+ _format_message_header_lines(headers, message_id=mid)
2276
+ )
2277
+ msg_output += f"\nWeb Link: {_generate_gmail_web_url(mid, user_google_email=user_google_email)}\n"
2278
+ msg_output += f"\n--- {body_label} ---\n{body_data}\n"
2279
+
2280
+ if attachments:
2281
+ msg_output += "\n--- ATTACHMENTS ---\n"
2282
+ for attachment_index, att in enumerate(attachments):
2283
+ size_kb = att["size"] / 1024
2284
+ msg_output += (
2285
+ f"{attachment_index + 1}. {att['filename']} ({att['mimeType']}, {size_kb:.1f} KB){' [in attached message]' if att.get('inAttachedMessage') else ''}\n"
2286
+ f" Attachment ID: {att['attachmentId']}\n"
2287
+ f" Use get_gmail_attachment_content(message_id='{mid}', "
2288
+ f"attachment_id='{att['attachmentId']}', attachment_index={attachment_index}) to download\n"
2289
+ )
2290
+
2291
+ output_messages.append(msg_output)
2292
+
2293
+ # Combine all messages with separators
2294
+ final_output = f"Retrieved {len(message_ids)} messages:\n\n"
2295
+ final_output += "\n---\n\n".join(output_messages)
2296
+
2297
+ return final_output
2298
+
2299
+
2300
+ def _attachment_metadata_fields(depth: int) -> str:
2301
+ """Build a metadata-only fields mask for a MIME tree of the given depth."""
2302
+ node = "filename,mimeType,body(attachmentId,size)"
2303
+ for _ in range(depth):
2304
+ node = f"filename,mimeType,body(attachmentId,size),parts({node})"
2305
+ return f"payload({node})"
2306
+
2307
+
2308
+ _ATTACHMENT_METADATA_FIELDS = _attachment_metadata_fields(6)
2309
+
2310
+
2311
+ @server.tool(
2312
+ title="Get Gmail Attachment Content",
2313
+ annotations=ToolAnnotations(
2314
+ readOnlyHint=False,
2315
+ destructiveHint=False,
2316
+ idempotentHint=False,
2317
+ openWorldHint=True,
2318
+ ),
2319
+ )
2320
+ @handle_http_errors(
2321
+ "get_gmail_attachment_content", is_read_only=True, service_type="gmail"
2322
+ )
2323
+ @require_google_service("gmail", "gmail_read")
2324
+ async def get_gmail_attachment_content(
2325
+ service,
2326
+ message_id: str,
2327
+ attachment_id: str,
2328
+ user_google_email: str,
2329
+ return_base64: bool = False,
2330
+ attachment_index: Optional[int] = None,
2331
+ ) -> str:
2332
+ """
2333
+ Downloads an email attachment and saves it to local disk.
2334
+
2335
+ In stdio mode, returns the local file path for direct access.
2336
+ In HTTP mode, returns a temporary download URL (valid for 1 hour).
2337
+ May re-fetch message metadata to resolve filename and MIME type.
2338
+
2339
+ Args:
2340
+ message_id (str): The ID of the Gmail message containing the attachment.
2341
+ attachment_id (str): The ID of the attachment to download.
2342
+ user_google_email (str): The user's Google email address. Required.
2343
+ return_base64 (bool): When True, includes the full attachment as a
2344
+ standard base64 string in the response (in addition to any file
2345
+ path or download URL). Useful for sandboxed clients that cannot
2346
+ reach localhost download URLs or the MCP server's local file
2347
+ paths (e.g. containerized agents with network allowlists). The
2348
+ returned base64 uses the standard alphabet, so it can be passed
2349
+ directly to tools like ``draft_gmail_message`` that expect
2350
+ standard (not URL-safe) base64. Default False preserves the
2351
+ existing behavior and response size.
2352
+ attachment_index (Optional[int]): Zero-based attachment position from
2353
+ the message-content response. Lets the server resolve Gmail's
2354
+ refreshed attachment IDs against current metadata before every
2355
+ download, selecting the current attachment ID, filename and MIME type.
2356
+
2357
+ Returns:
2358
+ str: Attachment metadata with either a local file path or download URL,
2359
+ optionally followed by a base64 content block when
2360
+ ``return_base64=True``.
2361
+ """
2362
+ logger.info(
2363
+ f"[get_gmail_attachment_content] Invoked. Message ID: '{message_id}', Email: '{user_google_email}'"
2364
+ )
2365
+
2366
+ # Resolve attachment size/filename from message metadata before downloading
2367
+ # the binary payload so we can reject oversized attachments before the API
2368
+ # returns the full base64 body in one shot.
2369
+ filename = None
2370
+ mime_type = None
2371
+ declared_size = None
2372
+ download_attachment_id = attachment_id
2373
+ max_file_bytes = get_max_file_bytes()
2374
+ if max_file_bytes is not None or attachment_index is not None:
2375
+ try:
2376
+ message_full = await asyncio.to_thread(
2377
+ service.users()
2378
+ .messages()
2379
+ .get(
2380
+ userId="me",
2381
+ id=message_id,
2382
+ format="full",
2383
+ fields=_ATTACHMENT_METADATA_FIELDS,
2384
+ )
2385
+ .execute
2386
+ )
2387
+ payload = message_full.get("payload", {})
2388
+ attachments = _extract_attachments(payload)
2389
+ matched = _find_attachment_metadata(payload, attachment_id)
2390
+
2391
+ if matched is None and attachment_index is not None:
2392
+ if attachment_index < 0 or attachment_index >= len(attachments):
2393
+ return (
2394
+ f"Error: Invalid attachment_index {attachment_index}. Message "
2395
+ f"has {len(attachments)} downloadable attachment(s)."
2396
+ )
2397
+ # Gmail can refresh attachment IDs between messages.get calls.
2398
+ # The stable ordinal emitted with the original ID selects the
2399
+ # corresponding current attachment safely.
2400
+ matched = attachments[attachment_index]
2401
+ elif matched is None and len(attachments) == 1:
2402
+ # A single attachment is unambiguous even if Gmail refreshed
2403
+ # its ID since the caller fetched the message.
2404
+ matched = attachments[0]
2405
+
2406
+ if matched is not None:
2407
+ filename = matched.get("filename")
2408
+ mime_type = matched.get("mimeType")
2409
+ declared_size = matched.get("size")
2410
+ download_attachment_id = matched.get("attachmentId", attachment_id)
2411
+ except Exception:
2412
+ logger.debug(
2413
+ f"Could not fetch attachment metadata for {attachment_id} before download"
2414
+ )
2415
+
2416
+ # attachments().get() returns the complete base64 payload in one API
2417
+ # response, so there is no opportunity to stop mid-body. If the bounded
2418
+ # metadata projection could not resolve this attachment (for example,
2419
+ # because it is nested deeper than the fields mask), fail closed before
2420
+ # requesting data that may exceed the configured cap.
2421
+ if max_file_bytes is not None and declared_size is None:
2422
+ return (
2423
+ "Error: Could not verify the attachment size before download while "
2424
+ "WORKSPACE_MCP_MAX_FILE_BYTES is configured. Fetch the message again "
2425
+ "and pass both its current attachment ID and attachment_index."
2426
+ )
2427
+
2428
+ try:
2429
+ ensure_within_file_size_limit(
2430
+ declared_size,
2431
+ file_name=filename,
2432
+ file_id=attachment_id,
2433
+ kind="attachment",
2434
+ max_bytes=max_file_bytes,
2435
+ )
2436
+ except FileTooLargeError as e:
2437
+ return str(e)
2438
+
2439
+ try:
2440
+ attachment = await asyncio.to_thread(
2441
+ service.users()
2442
+ .messages()
2443
+ .attachments()
2444
+ .get(userId="me", messageId=message_id, id=download_attachment_id)
2445
+ .execute
2446
+ )
2447
+ except Exception as e:
2448
+ logger.error(
2449
+ f"[get_gmail_attachment_content] Failed to download attachment: {e}"
2450
+ )
2451
+ return (
2452
+ f"Error: Failed to download attachment. The attachment ID may have changed.\n"
2453
+ f"Please fetch the message content again to get an updated attachment ID.\n\n"
2454
+ f"Error details: {str(e)}"
2455
+ )
2456
+
2457
+ # Format response with attachment data
2458
+ size_bytes = attachment.get("size", 0) or declared_size or 0
2459
+ size_kb = size_bytes / 1024 if size_bytes else 0
2460
+ base64_data = attachment.get("data", "")
2461
+
2462
+ # The Gmail API already buffered the full body above; this only prevents
2463
+ # returning oversized data when the pre-download declared_size was absent.
2464
+ try:
2465
+ ensure_within_file_size_limit(
2466
+ size_bytes,
2467
+ file_name=filename,
2468
+ file_id=attachment_id,
2469
+ kind="attachment",
2470
+ max_bytes=max_file_bytes,
2471
+ )
2472
+ except FileTooLargeError as e:
2473
+ if isinstance(attachment, dict):
2474
+ attachment.pop("data", None)
2475
+ base64_data = ""
2476
+ return str(e)
2477
+
2478
+ # Stateless mode has no file storage unless GCS staging is configured.
2479
+ from auth.oauth_config import is_stateless_mode
2480
+
2481
+ if is_stateless_mode() and not gcs_files_enabled():
2482
+ result_lines = [
2483
+ "Attachment downloaded successfully!",
2484
+ f"Message ID: {message_id}",
2485
+ f"Size: {size_kb:.1f} KB ({size_bytes} bytes)",
2486
+ "\n⚠️ Stateless mode: File storage disabled.",
2487
+ "\nBase64-encoded content (first 100 characters shown):",
2488
+ f"{base64_data[:100]}...",
2489
+ "\nNote: Attachment IDs are ephemeral. Always use IDs from the most recent message fetch.",
2490
+ ]
2491
+ if return_base64 and base64_data:
2492
+ result_lines.extend(_format_base64_content_block(base64_data))
2493
+ logger.info(
2494
+ f"[get_gmail_attachment_content] Successfully downloaded {size_kb:.1f} KB attachment (stateless mode)"
2495
+ )
2496
+ return "\n".join(result_lines)
2497
+
2498
+ # Save attachment to local disk and return file path
2499
+ try:
2500
+ from core.attachment_storage import get_attachment_storage, get_attachment_url
2501
+ from core.config import get_transport_mode
2502
+
2503
+ storage = get_attachment_storage()
2504
+
2505
+ # If the pre-download metadata fetch missed the filename, try again
2506
+ # with the full nested MIME tree and size-based fallback heuristics.
2507
+ if not filename:
2508
+ try:
2509
+ message_full = await asyncio.to_thread(
2510
+ service.users()
2511
+ .messages()
2512
+ .get(
2513
+ userId="me",
2514
+ id=message_id,
2515
+ format="full",
2516
+ fields=_ATTACHMENT_METADATA_FIELDS,
2517
+ )
2518
+ .execute
2519
+ )
2520
+ payload = message_full.get("payload", {})
2521
+ attachments = _extract_attachments(payload)
2522
+
2523
+ for att in attachments:
2524
+ if att.get("attachmentId") == attachment_id:
2525
+ filename = att.get("filename")
2526
+ mime_type = att.get("mimeType")
2527
+ break
2528
+
2529
+ if not filename and attachments:
2530
+ size_matches = [
2531
+ att
2532
+ for att in attachments
2533
+ if att.get("size") and abs(att["size"] - size_bytes) < 100
2534
+ ]
2535
+ if len(size_matches) == 1:
2536
+ filename = size_matches[0].get("filename")
2537
+ mime_type = size_matches[0].get("mimeType")
2538
+ logger.warning(
2539
+ f"Attachment {attachment_id} matched by size fallback as '{filename}'"
2540
+ )
2541
+
2542
+ if not filename and len(attachments) == 1:
2543
+ filename = attachments[0].get("filename")
2544
+ mime_type = attachments[0].get("mimeType")
2545
+ except Exception:
2546
+ logger.debug(
2547
+ f"Could not fetch attachment metadata for {attachment_id}, using defaults"
2548
+ )
2549
+
2550
+ # The GCS backend uploads over the network, so keep it off the event loop.
2551
+ result = await asyncio.to_thread(
2552
+ storage.save_attachment,
2553
+ base64_data=base64_data,
2554
+ filename=filename,
2555
+ mime_type=mime_type,
2556
+ )
2557
+ saved_filename = Path(result.path).name
2558
+
2559
+ result_lines = [
2560
+ "Attachment downloaded successfully!",
2561
+ f"Message ID: {message_id}",
2562
+ f"Filename: {filename or 'unknown'}",
2563
+ f"Saved filename: {saved_filename}",
2564
+ f"Size: {size_kb:.1f} KB ({size_bytes} bytes)",
2565
+ ]
2566
+
2567
+ if get_transport_mode() == "stdio":
2568
+ result_lines.append(f"\n📎 Saved to: {result.path}")
2569
+ result_lines.append(
2570
+ "\nThe file has been saved to disk and can be accessed directly via the file path."
2571
+ )
2572
+ else:
2573
+ download_url = await asyncio.to_thread(get_attachment_url, result.file_id)
2574
+ result_lines.append(f"\n📎 Download URL: {download_url}")
2575
+ result_lines.append("\nThe file will expire after 1 hour.")
2576
+
2577
+ result_lines.append(
2578
+ "\nNote: Attachment IDs are ephemeral. Always use IDs from the most recent message fetch."
2579
+ )
2580
+
2581
+ if return_base64 and base64_data:
2582
+ result_lines.extend(_format_base64_content_block(base64_data))
2583
+
2584
+ logger.info(
2585
+ f"[get_gmail_attachment_content] Successfully saved {size_kb:.1f} KB attachment to {result.path}"
2586
+ )
2587
+ return "\n".join(result_lines)
2588
+
2589
+ except Exception as e:
2590
+ logger.error(
2591
+ f"[get_gmail_attachment_content] Failed to save attachment: {e}",
2592
+ exc_info=True,
2593
+ )
2594
+ record_degraded_failure(e)
2595
+ # Fallback to showing base64 preview
2596
+ result_lines = [
2597
+ "Attachment downloaded successfully!",
2598
+ f"Message ID: {message_id}",
2599
+ f"Size: {size_kb:.1f} KB ({size_bytes} bytes)",
2600
+ "\n⚠️ Failed to save attachment file. Showing preview instead.",
2601
+ "\nBase64-encoded content (first 100 characters shown):",
2602
+ f"{base64_data[:100]}...",
2603
+ f"\nError: {str(e)}",
2604
+ "\nNote: Attachment IDs are ephemeral. Always use IDs from the most recent message fetch.",
2605
+ ]
2606
+ if return_base64 and base64_data:
2607
+ result_lines.extend(_format_base64_content_block(base64_data))
2608
+ return "\n".join(result_lines)
2609
+
2610
+
2611
+ @server.tool(
2612
+ title="Send Gmail Message",
2613
+ annotations=ToolAnnotations(
2614
+ readOnlyHint=False,
2615
+ destructiveHint=True,
2616
+ idempotentHint=False,
2617
+ openWorldHint=True,
2618
+ ),
2619
+ )
2620
+ @handle_http_errors("send_gmail_message", service_type="gmail")
2621
+ @require_google_service("gmail", ["gmail_read", GMAIL_SEND_SCOPE])
2622
+ async def send_gmail_message(
2623
+ service,
2624
+ user_google_email: str,
2625
+ to: Annotated[
2626
+ Optional[str],
2627
+ Field(
2628
+ description="Recipient email address. Optional when replying with reply_all=True, which derives it from the thread.",
2629
+ ),
2630
+ ] = None,
2631
+ subject: Annotated[
2632
+ Optional[str],
2633
+ Field(
2634
+ description="Email subject. Required for a new message. Optional when replying with thread_id (inherits the parent message's subject, adding 'Re:' only if absent) or when forwarding (defaults to 'Fwd: <original subject>').",
2635
+ ),
2636
+ ] = None,
2637
+ body: Annotated[
2638
+ Optional[str],
2639
+ Field(
2640
+ description="Email body content (plain text or HTML). Required when sending. When forwarding, this is an optional note prepended above the quoted original.",
2641
+ ),
2642
+ ] = None,
2643
+ body_format: Annotated[
2644
+ Literal["plain", "html"],
2645
+ Field(
2646
+ description="Format of the body content (and of the prepended note when forwarding). Use 'plain' for plaintext or 'html' for HTML content. With 'html', write real markup; an entity-escaped body ('&lt;div&gt;') is rejected.",
2647
+ ),
2648
+ ] = "plain",
2649
+ forward_message_id: Annotated[
2650
+ Optional[str],
2651
+ Field(
2652
+ description="Set to a Gmail message ID to forward that message instead of composing a new one. The original subject, body, and (optionally) attachments are carried over; 'body' becomes an optional note prepended to the forward.",
2653
+ ),
2654
+ ] = None,
2655
+ include_forwarded_attachments: Annotated[
2656
+ bool,
2657
+ Field(
2658
+ description="When forwarding, whether to include the original message's attachments. Ignored unless forward_message_id is set.",
2659
+ ),
2660
+ ] = True,
2661
+ cc: Annotated[
2662
+ Optional[str], Field(description="Optional CC email address.")
2663
+ ] = None,
2664
+ bcc: Annotated[
2665
+ Optional[str], Field(description="Optional BCC email address.")
2666
+ ] = None,
2667
+ from_name: Annotated[
2668
+ Optional[str],
2669
+ Field(
2670
+ description="Optional sender display name (e.g., 'Peter Hartree'). If provided, the From header will be formatted as 'Name <email>'.",
2671
+ ),
2672
+ ] = None,
2673
+ from_email: Annotated[
2674
+ Optional[str],
2675
+ Field(
2676
+ description="Optional 'Send As' alias email address. Must be configured in Gmail settings (Settings > Accounts > Send mail as). If not provided, uses the authenticated user's email.",
2677
+ ),
2678
+ ] = None,
2679
+ thread_id: Annotated[
2680
+ Optional[str],
2681
+ Field(
2682
+ description="Optional Gmail thread ID to reply within. When in_reply_to is omitted, replies to the latest non-draft, non-trash message with an RFC Message-ID.",
2683
+ ),
2684
+ ] = None,
2685
+ in_reply_to: Annotated[
2686
+ Optional[str],
2687
+ Field(
2688
+ description="Optional RFC Message-ID to explicitly reply to a specific message (e.g., '<message123@gmail.com>'). Omit to reply to the latest eligible message in thread_id.",
2689
+ ),
2690
+ ] = None,
2691
+ references: Annotated[
2692
+ Optional[str],
2693
+ Field(
2694
+ description="Optional Message-ID ancestry chain. Normally omit when thread_id is provided; the server derives the chain through the selected reply target.",
2695
+ ),
2696
+ ] = None,
2697
+ attachments: Annotated[
2698
+ Optional[DictList],
2699
+ Field(
2700
+ description='Optional list of attachments. Each can have: "url" (fetch from URL — works with MCP attachment URLs from get_drive_file_download_url / get_gmail_attachment_content), OR "path" (file path, auto-encodes), OR "content" (standard base64, not urlsafe) + "filename". Optional "mime_type". Optional "content_id" (string) makes the attachment inline-rendered: it lands in a multipart/related part with `Content-ID: <content_id>` and `Content-Disposition: inline`, and the HTML body can reference it via `<img src="cid:<content_id>">` (RFC 2392). Without `content_id` the attachment is a regular multipart/mixed attachment. Example: [{"url": "https://host/attachments/abc-123", "filename": "report.pdf"}]',
2701
+ ),
2702
+ ] = None,
2703
+ include_signature: Annotated[
2704
+ bool,
2705
+ Field(
2706
+ description="Whether to append the Gmail signature from Settings > Signature when available. Defaults to true.",
2707
+ ),
2708
+ ] = True,
2709
+ direction: Annotated[
2710
+ TextDirection, Field(description=DIRECTION_DESCRIPTION)
2711
+ ] = "auto",
2712
+ quote_original: Annotated[
2713
+ bool,
2714
+ Field(
2715
+ description="Whether to include the message being replied to as a quoted original, as Gmail web does. Only has an effect when thread_id is provided. Defaults to false; pass true on replies whose recipients should see the earlier message.",
2716
+ ),
2717
+ ] = False,
2718
+ reply_all: Annotated[
2719
+ bool,
2720
+ Field(
2721
+ description="Whether to derive reply-all recipients from the thread: To = the sender being replied to, Cc = the other participants, excluding the authenticated account and from_email. Requires thread_id. Explicit to/cc win; when cc is omitted the sender being replied to is added to the derived Cc if they are not already in To. Defaults to false.",
2722
+ ),
2723
+ ] = False,
2724
+ priority: Annotated[
2725
+ MessagePriority, Field(description=PRIORITY_DESCRIPTION)
2726
+ ] = "normal",
2727
+ ) -> str:
2728
+ """
2729
+ Sends an email using the user's Gmail account. Supports new emails, replies, and
2730
+ forwards, with optional attachments. Supports Gmail's "Send As" feature to send
2731
+ from configured alias addresses.
2732
+
2733
+ To forward an existing message, pass forward_message_id. The original subject,
2734
+ body (quoted with a "Forwarded message" header), and attachments are carried over.
2735
+ In forward mode, body (if any) is prepended as a note and subject is optional.
2736
+ Threading, reply, and signature options do not apply when forwarding.
2737
+
2738
+ THIS TOOL SENDS IMMEDIATELY AND CANNOT SCHEDULE. Gmail's REST API exposes no
2739
+ send-time parameter; Schedule send is a web-UI feature with no API equivalent,
2740
+ so no argument to this tool can defer delivery. Never tell a user a message
2741
+ was scheduled. For "prepare now, deliver later", create a draft with
2742
+ draft_gmail_message. An external scheduler must retain the message data to
2743
+ create and send a new message via send_gmail_message at the chosen time, or
2744
+ call users.drafts.send with the draft ID returned by draft_gmail_message.
2745
+ Alternatively, let the user schedule that draft in the Gmail UI.
2746
+
2747
+ Args:
2748
+ to (str): Recipient email address.
2749
+ subject (str): Email subject. Required for a new message. Optional when replying
2750
+ with thread_id (inherits the parent message's subject) or forwarding (then
2751
+ defaults to 'Fwd: <original subject>').
2752
+ body (str): Email body content. Required unless forwarding (then an optional prepended note).
2753
+ body_format (Literal['plain', 'html']): Body format (and prepended note format when forwarding). Defaults to 'plain'.
2754
+ forward_message_id (Optional[str]): Gmail message ID to forward. When set, the tool forwards that message.
2755
+ include_forwarded_attachments (bool): Whether to carry over the original attachments when forwarding. Defaults to True.
2756
+ attachments (Optional[List[Dict[str, str]]]): Optional list of attachments. Each dict can contain:
2757
+ Option 1 - File path (auto-encodes):
2758
+ - 'path' (required): File path to attach
2759
+ - 'filename' (optional): Override filename
2760
+ - 'mime_type' (optional): Override MIME type (auto-detected if not provided)
2761
+ Option 2 - Base64 content:
2762
+ - 'content' (required): Standard base64-encoded file content (not urlsafe)
2763
+ - 'filename' (required): Name of the file
2764
+ - 'mime_type' (optional): MIME type (defaults to 'application/octet-stream')
2765
+ cc (Optional[str]): Optional CC email address.
2766
+ bcc (Optional[str]): Optional BCC email address.
2767
+ from_name (Optional[str]): Optional sender display name. If provided, the From header will be formatted as 'Name <email>'.
2768
+ from_email (Optional[str]): Optional 'Send As' alias email address. The alias must be
2769
+ configured in Gmail settings (Settings > Accounts > Send mail as). If not provided,
2770
+ the email will be sent from the authenticated user's primary email address.
2771
+ user_google_email (str): The user's Google email address. Required for authentication.
2772
+ thread_id (Optional[str]): Optional Gmail thread ID to reply within. When
2773
+ in_reply_to is omitted, replies to the latest non-draft, non-trash message
2774
+ with an RFC Message-ID.
2775
+ in_reply_to (Optional[str]): Optional RFC Message-ID to explicitly reply to
2776
+ a specific message. Omit to reply to the latest eligible message.
2777
+ references (Optional[str]): Optional RFC Message-ID ancestry chain. Normally
2778
+ omit when thread_id is provided; the chain is derived automatically.
2779
+ include_signature (bool): Whether to append Gmail signature HTML from send-as settings.
2780
+ When include_signature is true and Gmail signature retrieval fails for benign reasons
2781
+ (e.g., missing gmail.settings.basic scope), the send proceeds without a signature.
2782
+ Non-benign failures such as quota/rate-limit or API errors raise ToolError and abort
2783
+ the send.
2784
+ quote_original (bool): Whether to append the message being replied to as a quoted
2785
+ original, as Gmail web does. Only has an effect when thread_id is provided.
2786
+ Defaults to False. When the quote cannot be built, the reply still sends and the
2787
+ result says why it was left out.
2788
+ reply_all (bool): Whether to derive reply-all recipients from the thread: To = the
2789
+ sender being replied to, Cc = the other participants, excluding the authenticated
2790
+ account and from_email. Requires thread_id. Explicit to/cc win over the derived
2791
+ values; when cc is omitted, the sender being replied to is added to the derived Cc
2792
+ unless they are already in To (so an explicit 'to' that redirects the reply still
2793
+ keeps them on it).
2794
+ priority (str): 'high' or 'low' adds priority headers. Defaults to 'normal'.
2795
+
2796
+ Returns:
2797
+ str: Confirmation message with the sent email's message ID.
2798
+
2799
+ Examples:
2800
+ # Send a new email
2801
+ send_gmail_message(to="user@example.com", subject="Hello", body="Hi there!")
2802
+
2803
+ # Send with a custom display name
2804
+ send_gmail_message(to="user@example.com", subject="Hello", body="Hi there!", from_name="John Doe")
2805
+
2806
+ # Send an HTML email
2807
+ send_gmail_message(
2808
+ to="user@example.com",
2809
+ subject="Hello",
2810
+ body="<strong>Hi there!</strong>",
2811
+ body_format="html"
2812
+ )
2813
+
2814
+ # Send from a configured alias (Send As)
2815
+ send_gmail_message(
2816
+ to="user@example.com",
2817
+ subject="Business Inquiry",
2818
+ body="Hello from my business address...",
2819
+ from_email="business@mydomain.com"
2820
+ )
2821
+
2822
+ # Send an email with CC and BCC
2823
+ send_gmail_message(
2824
+ to="user@example.com",
2825
+ cc="manager@example.com",
2826
+ bcc="archive@example.com",
2827
+ subject="Project Update",
2828
+ body="Here's the latest update..."
2829
+ )
2830
+
2831
+ # Send an email with attachments (using file path)
2832
+ send_gmail_message(
2833
+ to="user@example.com",
2834
+ subject="Report",
2835
+ body="Please see attached report.",
2836
+ attachments=[{
2837
+ "path": "/path/to/report.pdf"
2838
+ }]
2839
+ )
2840
+
2841
+ # Send an email with attachments (using base64 content)
2842
+ send_gmail_message(
2843
+ to="user@example.com",
2844
+ subject="Report",
2845
+ body="Please see attached report.",
2846
+ attachments=[{
2847
+ "filename": "report.pdf",
2848
+ "content": "JVBERi0xLjQK...", # base64 encoded PDF
2849
+ "mime_type": "application/pdf"
2850
+ }]
2851
+ )
2852
+
2853
+ # Send a reply
2854
+ send_gmail_message(
2855
+ to="user@example.com",
2856
+ subject="Re: Meeting tomorrow",
2857
+ body="Thanks for the update!",
2858
+ thread_id="thread_123"
2859
+ )
2860
+
2861
+ # Send a reply-all with the original quoted, deriving headers and
2862
+ # recipients from the thread
2863
+ send_gmail_message(
2864
+ subject="Re: Meeting tomorrow",
2865
+ body="Thanks for the update!",
2866
+ thread_id="thread_123",
2867
+ reply_all=True,
2868
+ quote_original=True
2869
+ )
2870
+
2871
+ # Forward a message with a note
2872
+ send_gmail_message(
2873
+ to="user@example.com",
2874
+ forward_message_id="abc123",
2875
+ body="FYI - see below."
2876
+ )
2877
+
2878
+ # Forward without the original attachments
2879
+ send_gmail_message(
2880
+ to="user@example.com",
2881
+ forward_message_id="abc123",
2882
+ include_forwarded_attachments=False
2883
+ )
2884
+ """
2885
+ _reject_entity_escaped_html_body(body, body_format)
2886
+
2887
+ # Forwarding reuses the original message's content, so it follows a dedicated
2888
+ # path that fetches and quotes the source message.
2889
+ if forward_message_id:
2890
+ # 'to' is optional on the signature only so a reply_all send can derive it;
2891
+ # a forward has no thread to derive from, so it still requires one.
2892
+ if not to:
2893
+ raise UserInputError(
2894
+ "'to' is required when forwarding via 'forward_message_id'."
2895
+ )
2896
+ logger.info(
2897
+ f"[send_gmail_message] Forwarding message '{forward_message_id}' for '{user_google_email}'"
2898
+ )
2899
+ # An explicit alias is always validated. Otherwise the Send-As
2900
+ # displayName is only looked up when signatures are enabled, so the
2901
+ # settings endpoint stays optional, as on a regular send.
2902
+ if from_email or (include_signature and not from_name):
2903
+ _, sender_display_name, _ = await _get_send_as_identity_and_signature(
2904
+ service,
2905
+ from_email=from_email or user_google_email,
2906
+ fallback_email=user_google_email,
2907
+ require_match=bool(from_email),
2908
+ )
2909
+ from_name = from_name or sender_display_name or None
2910
+ return await _forward_gmail_message_impl(
2911
+ service=service,
2912
+ message_id=forward_message_id,
2913
+ to=to,
2914
+ subject=subject,
2915
+ forward_message=body,
2916
+ forward_message_format=body_format,
2917
+ include_attachments=include_forwarded_attachments,
2918
+ attachments=attachments,
2919
+ cc=cc,
2920
+ bcc=bcc,
2921
+ from_name=from_name,
2922
+ from_email=from_email,
2923
+ user_google_email=user_google_email,
2924
+ direction=direction,
2925
+ priority=priority,
2926
+ )
2927
+
2928
+ if body is None or (not thread_id and not (subject or "").strip()):
2929
+ raise UserInputError(
2930
+ "'body' is required, and 'subject' is required unless replying with "
2931
+ "thread_id (it is then inherited from the parent message) or "
2932
+ "forwarding via 'forward_message_id'."
2933
+ )
2934
+
2935
+ if reply_all and not thread_id:
2936
+ raise UserInputError(
2937
+ "'reply_all' requires a thread_id: the recipients are derived from "
2938
+ "the message being replied to."
2939
+ )
2940
+
2941
+ if not to and not (thread_id and reply_all):
2942
+ raise UserInputError(
2943
+ "'to' is required unless replying with reply_all=True and a thread_id, "
2944
+ "which derives the recipients from the thread."
2945
+ )
2946
+
2947
+ logger.info(
2948
+ f"[send_gmail_message] Invoked. Email: '{user_google_email}', subject_len={len(subject) if subject else 0}, Attachments: {len(attachments) if attachments else 0}"
2949
+ )
2950
+
2951
+ # The Send-As entry carries both the signature and the displayName Gmail web
2952
+ # renders in the From line. With signatures disabled the settings endpoint
2953
+ # is never touched and From stays the bare address unless from_name is given.
2954
+ sender_email = from_email or user_google_email
2955
+ sender_display_name = signature_html = ""
2956
+ if include_signature:
2957
+ (
2958
+ _,
2959
+ sender_display_name,
2960
+ signature_html,
2961
+ ) = await _get_send_as_identity_and_signature(
2962
+ service,
2963
+ from_email=sender_email,
2964
+ fallback_email=user_google_email,
2965
+ require_match=bool(from_email),
2966
+ )
2967
+ from_name = from_name or sender_display_name or None
2968
+
2969
+ # A reply's headers, recipients and quoted original are all derivable from the
2970
+ # thread, so a caller should not have to assemble them by hand. Mirrors
2971
+ # draft_gmail_message; one thread fetch serves all three.
2972
+ reply_context = None
2973
+ if thread_id and (
2974
+ quote_original
2975
+ or reply_all
2976
+ or not (subject or "").strip()
2977
+ or not in_reply_to
2978
+ or not references
2979
+ ):
2980
+ reply_context = await _fetch_thread_reply_context(
2981
+ service,
2982
+ thread_id,
2983
+ in_reply_to=in_reply_to,
2984
+ include_bodies=quote_original,
2985
+ )
2986
+
2987
+ target_reply = reply_context.get("target") if reply_context else None
2988
+ if thread_id and (not in_reply_to or not references):
2989
+ in_reply_to, references = _derive_reply_headers(
2990
+ reply_context.get("message_ids", []) if reply_context else [],
2991
+ in_reply_to,
2992
+ references,
2993
+ target_reply,
2994
+ )
2995
+
2996
+ if reply_all:
2997
+ if not target_reply:
2998
+ raise UserInputError(
2999
+ f"Could not load the message to reply to in thread '{thread_id}', "
3000
+ "so reply-all recipients cannot be derived. Retry, or pass 'to' "
3001
+ "and 'cc' explicitly without 'reply_all'."
3002
+ )
3003
+ to, cc = _derive_reply_all_recipients(
3004
+ target_reply, {user_google_email, sender_email}, to, cc
3005
+ )
3006
+ if not to:
3007
+ raise UserInputError(
3008
+ f"Could not derive a recipient from thread '{thread_id}'. Pass 'to' explicitly."
3009
+ )
3010
+ if thread_id and not (subject or "").strip():
3011
+ subject = _inherit_reply_subject(thread_id, target_reply)
3012
+
3013
+ if body_format == "html":
3014
+ # Bare newlines between text are invisible to HTML renderers; callers
3015
+ # (LLMs especially) pass them expecting line breaks. Convert only the
3016
+ # caller's body, before any signature or quoted original is attached.
3017
+ body = html_newlines_to_br(body)
3018
+
3019
+ resolved_attachments = await _resolve_url_attachments(attachments)
3020
+ quote_target, quote_note = (
3021
+ _resolve_reply_quote(target_reply, web_path=not resolved_attachments)
3022
+ if thread_id and quote_original
3023
+ else (None, "")
3024
+ )
3025
+ if resolved_attachments:
3026
+ if quote_target:
3027
+ send_body_content = _build_quoted_reply_body(
3028
+ body, body_format, signature_html, quote_target
3029
+ )
3030
+ else:
3031
+ send_body_content = _append_signature_to_body(
3032
+ body, body_format, signature_html
3033
+ )
3034
+ raw_message, thread_id_final, attached_count, attachment_errors = (
3035
+ _prepare_gmail_message(
3036
+ subject=subject,
3037
+ body=send_body_content,
3038
+ direction=direction,
3039
+ to=to,
3040
+ cc=cc,
3041
+ bcc=bcc,
3042
+ thread_id=thread_id,
3043
+ in_reply_to=in_reply_to,
3044
+ references=references,
3045
+ body_format=body_format,
3046
+ from_email=sender_email,
3047
+ from_name=from_name,
3048
+ attachments=resolved_attachments,
3049
+ priority=priority,
3050
+ )
3051
+ )
3052
+ else:
3053
+ # Without attachments the message takes the Gmail-web faithful path.
3054
+ raw_message = _build_web_compose_raw(
3055
+ subject=subject,
3056
+ body=_append_signature_to_body(body, body_format, signature_html),
3057
+ body_format=body_format,
3058
+ to=to,
3059
+ cc=cc,
3060
+ bcc=bcc,
3061
+ from_email=sender_email,
3062
+ from_name=from_name,
3063
+ in_reply_to=in_reply_to,
3064
+ references=references,
3065
+ direction=direction,
3066
+ reply_target=quote_target,
3067
+ priority=priority,
3068
+ )
3069
+ thread_id_final, attached_count, attachment_errors = thread_id, 0, []
3070
+
3071
+ requested_attachment_count = len(attachments or [])
3072
+ if requested_attachment_count > 0 and attached_count == 0:
3073
+ details = (
3074
+ f" Details: {'; '.join(attachment_errors)}" if attachment_errors else ""
3075
+ )
3076
+ raise UserInputError(
3077
+ "No valid attachments were added. Verify each attachment path/content and retry."
3078
+ f"{details}"
3079
+ )
3080
+
3081
+ send_body = {"raw": raw_message}
3082
+
3083
+ # Associate with thread if provided
3084
+ if thread_id_final:
3085
+ send_body["threadId"] = thread_id_final
3086
+
3087
+ # Send the message
3088
+ sent_message = await send_message_once(service, send_body)
3089
+ message_id = sent_message.get("id")
3090
+
3091
+ if requested_attachment_count > 0:
3092
+ attachment_info = _format_attachment_result(
3093
+ attached_count, requested_attachment_count
3094
+ )
3095
+ return f"Email sent{attachment_info}! Message ID: {message_id}{quote_note}"
3096
+ return f"Email sent! Message ID: {message_id}{quote_note}"
3097
+
3098
+
3099
+ # Internal implementation function for testing
3100
+ async def _forward_gmail_message_impl(
3101
+ service,
3102
+ message_id: str,
3103
+ to: Optional[str],
3104
+ subject: Optional[str] = None,
3105
+ forward_message: Optional[str] = None,
3106
+ forward_message_format: Literal["plain", "html"] = "plain",
3107
+ include_attachments: bool = True,
3108
+ cc: Optional[str] = None,
3109
+ bcc: Optional[str] = None,
3110
+ from_name: Optional[str] = None,
3111
+ from_email: Optional[str] = None,
3112
+ user_google_email: str = "",
3113
+ direction: TextDirection = "auto",
3114
+ as_draft: bool = False,
3115
+ attachments: Optional[List[Dict[str, Any]]] = None,
3116
+ priority: MessagePriority = "normal",
3117
+ ) -> str:
3118
+ """Build a forward of an existing Gmail message and send it or save it as a draft.
3119
+
3120
+ Shared by the forward paths of send_gmail_message and draft_gmail_message. An
3121
+ explicit ``subject`` overrides the auto-derived 'Fwd: <original subject>'.
3122
+ ``direction`` sets the base text direction of the prepended note ('auto'
3123
+ detects it from the note text).
3124
+ """
3125
+ # Fetch the original message with full payload
3126
+ original_message = await asyncio.to_thread(
3127
+ service.users()
3128
+ .messages()
3129
+ .get(userId="me", id=message_id, format="full")
3130
+ .execute
3131
+ )
3132
+ body_errors = await fetch_attachment_backed_bodies(service, [original_message])
3133
+ if body_errors:
3134
+ raise ToolExecutionError(
3135
+ "Failed to include the original message body: " + "; ".join(body_errors)
3136
+ )
3137
+
3138
+ payload = original_message.get("payload", {})
3139
+
3140
+ # Handle attachments
3141
+ attachments_to_send = []
3142
+ if include_attachments:
3143
+ attachment_metadata = _extract_attachments(payload)
3144
+ failed_attachments = []
3145
+ for att in attachment_metadata:
3146
+ try:
3147
+ ensure_within_file_size_limit(
3148
+ att.get("size"),
3149
+ file_name=att.get("filename"),
3150
+ file_id=att.get("attachmentId"),
3151
+ kind="attachment",
3152
+ )
3153
+ except FileTooLargeError as exc:
3154
+ # Do not let the broad per-attachment download handler turn a
3155
+ # configured safety rejection into a generic partial-forward
3156
+ # failure, and never send the message without requested files.
3157
+ raise UserInputError(str(exc)) from exc
3158
+ try:
3159
+ # Download attachment content
3160
+ attachment_data = await asyncio.to_thread(
3161
+ service.users()
3162
+ .messages()
3163
+ .attachments()
3164
+ .get(userId="me", messageId=message_id, id=att["attachmentId"])
3165
+ .execute
3166
+ )
3167
+ # Gmail normally repeats the decoded byte size in this
3168
+ # response. Re-check it before making padded/decoded/re-encoded
3169
+ # copies in case it differs from the message metadata.
3170
+ ensure_within_file_size_limit(
3171
+ attachment_data.get("size"),
3172
+ file_name=att.get("filename"),
3173
+ file_id=att.get("attachmentId"),
3174
+ kind="attachment",
3175
+ )
3176
+ # Gmail returns URL-safe base64 (often unpadded). Decode it
3177
+ # tolerantly and re-encode as standard, padded base64 so the
3178
+ # downstream base64.b64decode() in _prepare_gmail_message succeeds.
3179
+ urlsafe_data = attachment_data.get("data", "")
3180
+ padded = urlsafe_data + "=" * (-len(urlsafe_data) % 4)
3181
+ standard_b64 = base64.b64encode(
3182
+ base64.urlsafe_b64decode(padded)
3183
+ ).decode()
3184
+ attachments_to_send.append(
3185
+ {
3186
+ "content": standard_b64,
3187
+ "filename": att["filename"],
3188
+ "mime_type": att["mimeType"],
3189
+ }
3190
+ )
3191
+ logger.info(
3192
+ f"[forward_gmail_message] Downloaded attachment: {att['filename']}"
3193
+ )
3194
+ except FileTooLargeError as exc:
3195
+ raise UserInputError(str(exc)) from exc
3196
+ except Exception as e:
3197
+ logger.warning(
3198
+ f"[forward_gmail_message] Failed to download attachment {att['filename']}: {e}"
3199
+ )
3200
+ failed_attachments.append(att["filename"])
3201
+
3202
+ # Fail loudly rather than silently delivering an incomplete forward when
3203
+ # the caller asked for the original attachments to be preserved.
3204
+ if failed_attachments:
3205
+ raise Exception(
3206
+ "Failed to include requested attachment(s): "
3207
+ + ", ".join(failed_attachments)
3208
+ )
3209
+
3210
+ attachments_to_send.extend(await _resolve_url_attachments(attachments) or [])
3211
+
3212
+ forward_subject, forward_plain, forward_html = _build_forward_content(
3213
+ _extract_headers(payload, ["Subject", "From", "Date", "To"]),
3214
+ _extract_message_bodies(payload),
3215
+ forward_message,
3216
+ forward_message_format,
3217
+ subject,
3218
+ direction,
3219
+ )
3220
+
3221
+ # --- Prepare and send the message ---
3222
+ sender_email = from_email or user_google_email
3223
+ if attachments_to_send:
3224
+ # The web assembler does not carry attachments yet; send the same HTML
3225
+ # body through the EmailMessage path so the files are preserved.
3226
+ raw_message, _, attached_count, attachment_errors = _prepare_gmail_message(
3227
+ subject=forward_subject,
3228
+ body=forward_html,
3229
+ plain_body=forward_plain,
3230
+ to=to,
3231
+ cc=cc,
3232
+ bcc=bcc,
3233
+ body_format="html",
3234
+ from_email=sender_email,
3235
+ from_name=from_name,
3236
+ attachments=attachments_to_send,
3237
+ priority=priority,
3238
+ )
3239
+ else:
3240
+ raw_message = _prepare_gmail_message_web(
3241
+ subject=forward_subject,
3242
+ plain_body=forward_plain,
3243
+ html_body=forward_html,
3244
+ to=to,
3245
+ cc=cc,
3246
+ bcc=bcc,
3247
+ from_email=sender_email,
3248
+ from_name=from_name,
3249
+ priority=priority,
3250
+ )
3251
+ attached_count, attachment_errors = 0, []
3252
+ if attachments_to_send and attached_count != len(attachments_to_send):
3253
+ details = (
3254
+ f" Details: {'; '.join(attachment_errors)}" if attachment_errors else ""
3255
+ )
3256
+ raise UserInputError(
3257
+ "Failed to include requested attachment(s): "
3258
+ f"{attached_count}/{len(attachments_to_send)} attached.{details}"
3259
+ )
3260
+
3261
+ attachment_info = (
3262
+ _format_attachment_result(attached_count, len(attachments_to_send))
3263
+ if attachments_to_send
3264
+ else ""
3265
+ )
3266
+ send_body = {"raw": raw_message}
3267
+
3268
+ if as_draft:
3269
+ created_draft = await asyncio.to_thread(
3270
+ service.users()
3271
+ .drafts()
3272
+ .create(userId="me", body={"message": send_body})
3273
+ .execute,
3274
+ num_retries=GOOGLE_API_WRITE_RETRIES,
3275
+ )
3276
+ draft_id = created_draft.get("id")
3277
+ return f"Forward draft created{attachment_info}! Draft ID: {draft_id}"
3278
+
3279
+ # Send the message
3280
+ sent_message = await send_message_once(service, send_body)
3281
+ sent_message_id = sent_message.get("id")
3282
+ return f"Email forwarded{attachment_info}! Message ID: {sent_message_id}"
3283
+
3284
+
3285
+ @server.tool(
3286
+ title="Draft Gmail Message",
3287
+ annotations=ToolAnnotations(
3288
+ readOnlyHint=False,
3289
+ destructiveHint=False,
3290
+ idempotentHint=False,
3291
+ openWorldHint=True,
3292
+ ),
3293
+ )
3294
+ @handle_http_errors("draft_gmail_message", service_type="gmail")
3295
+ @require_google_service("gmail", GMAIL_COMPOSE_SCOPE)
3296
+ async def draft_gmail_message(
3297
+ service,
3298
+ user_google_email: str,
3299
+ subject: Annotated[
3300
+ Optional[str],
3301
+ Field(
3302
+ description="Email subject. Required for a new draft. Optional when replying with thread_id (inherits the parent message's subject, adding 'Re:' only if absent) or when forwarding (then defaults to 'Fwd: <original subject>').",
3303
+ ),
3304
+ ] = None,
3305
+ body: Annotated[
3306
+ Optional[str],
3307
+ Field(
3308
+ description="Email body. Required unless forwarding, where it becomes an optional note prepended above the quoted original.",
3309
+ ),
3310
+ ] = None,
3311
+ body_format: Annotated[
3312
+ Literal["plain", "html"],
3313
+ Field(
3314
+ description="Email body format. Use 'plain' for plaintext or 'html' for HTML content. With 'html', write real markup; an entity-escaped body ('&lt;div&gt;') is rejected.",
3315
+ ),
3316
+ ] = "plain",
3317
+ forward_message_id: Annotated[
3318
+ Optional[str],
3319
+ Field(
3320
+ description="Set to a Gmail message ID to save a forward of that message as a draft for review. The original subject, body, and (optionally) attachments are carried over; 'body' becomes an optional note prepended to the forward.",
3321
+ ),
3322
+ ] = None,
3323
+ include_forwarded_attachments: Annotated[
3324
+ bool,
3325
+ Field(
3326
+ description="When forwarding, whether to include the original message's attachments. Ignored unless forward_message_id is set.",
3327
+ ),
3328
+ ] = True,
3329
+ to: Annotated[
3330
+ Optional[str],
3331
+ Field(
3332
+ description="Optional recipient email address.",
3333
+ ),
3334
+ ] = None,
3335
+ cc: Annotated[
3336
+ Optional[str], Field(description="Optional CC email address.")
3337
+ ] = None,
3338
+ bcc: Annotated[
3339
+ Optional[str], Field(description="Optional BCC email address.")
3340
+ ] = None,
3341
+ from_name: Annotated[
3342
+ Optional[str],
3343
+ Field(
3344
+ description="Optional sender display name (e.g., 'Peter Hartree'). If provided, the From header will be formatted as 'Name <email>'.",
3345
+ ),
3346
+ ] = None,
3347
+ from_email: Annotated[
3348
+ Optional[str],
3349
+ Field(
3350
+ description="Optional 'Send As' alias email address. Must be configured in Gmail settings (Settings > Accounts > Send mail as). If not provided, uses the account's default Send As address, falling back to the authenticated user's email when Gmail returns no usable Send-As entry or settings access is not authorized.",
3351
+ ),
3352
+ ] = None,
3353
+ thread_id: Annotated[
3354
+ Optional[str],
3355
+ Field(
3356
+ description="Optional Gmail thread ID to reply within. When in_reply_to is omitted, replies to the latest non-draft, non-trash message with an RFC Message-ID.",
3357
+ ),
3358
+ ] = None,
3359
+ in_reply_to: Annotated[
3360
+ Optional[str],
3361
+ Field(
3362
+ description="Optional RFC Message-ID to explicitly reply to a specific message (e.g., '<message123@gmail.com>'). Omit to reply to the latest eligible message in thread_id.",
3363
+ ),
3364
+ ] = None,
3365
+ references: Annotated[
3366
+ Optional[str],
3367
+ Field(
3368
+ description="Optional Message-ID ancestry chain. Normally omit when thread_id is provided; the server derives the chain through the selected reply target.",
3369
+ ),
3370
+ ] = None,
3371
+ attachments: Annotated[
3372
+ Optional[DictList],
3373
+ Field(
3374
+ description="Optional list of attachments. Each can have: 'url' (fetch from URL — works with MCP attachment URLs from get_drive_file_download_url / get_gmail_attachment_content), OR 'path' (file path, auto-encodes), OR 'content' (standard base64, not urlsafe) + 'filename'. Optional 'mime_type'. Optional 'content_id' (string) makes the attachment inline-rendered: it lands in a multipart/related part with `Content-ID: <content_id>` and `Content-Disposition: inline`, and the HTML body can reference it via `<img src=\"cid:<content_id>\">` (RFC 2392). Without `content_id` the attachment is a regular multipart/mixed attachment.",
3375
+ ),
3376
+ ] = None,
3377
+ include_signature: Annotated[
3378
+ bool,
3379
+ Field(
3380
+ description="Whether to append the Gmail signature from Settings > Signature when available. Defaults to true.",
3381
+ ),
3382
+ ] = True,
3383
+ direction: Annotated[
3384
+ TextDirection, Field(description=DIRECTION_DESCRIPTION)
3385
+ ] = "auto",
3386
+ quote_original: Annotated[
3387
+ bool,
3388
+ Field(
3389
+ description="Whether to include the original message as a quoted reply, as Gmail web does. Only has an effect when thread_id is provided. Defaults to false; pass true on replies whose recipients should see the earlier message.",
3390
+ ),
3391
+ ] = False,
3392
+ reply_all: Annotated[
3393
+ bool,
3394
+ Field(
3395
+ description="Whether to derive reply-all recipients from the thread: To = the sender being replied to, Cc = the other participants, excluding the authenticated account and from_email. Requires thread_id. Explicit to/cc win; when cc is omitted the sender being replied to is added to the derived Cc if they are not already in To. Defaults to false.",
3396
+ ),
3397
+ ] = False,
3398
+ priority: Annotated[
3399
+ MessagePriority, Field(description=PRIORITY_DESCRIPTION)
3400
+ ] = "normal",
3401
+ ) -> str:
3402
+ """
3403
+ Creates a draft email in the user's Gmail account. Supports new, reply, and forward
3404
+ drafts with optional attachments. Supports Gmail's "Send As" feature to draft from
3405
+ configured alias addresses.
3406
+
3407
+ To save a forward as a draft for review, pass forward_message_id. The original
3408
+ subject, body (quoted with a "Forwarded message" header), and attachments are
3409
+ carried over. In forward mode, body (if any) is prepended as a note, subject is
3410
+ optional, and threading, reply, and signature options do not apply.
3411
+
3412
+ SCHEDULED SEND IS NOT AVAILABLE. Gmail's REST API exposes no send-time
3413
+ parameter; the Schedule send feature is web-UI only, and a message cannot be
3414
+ placed in the Scheduled folder through the API. Do not claim a message was
3415
+ scheduled. To deliver at a chosen time, create a draft with
3416
+ draft_gmail_message. An external scheduler must retain the message data to
3417
+ create and send a new message via send_gmail_message then, or call
3418
+ users.drafts.send with the draft ID returned by draft_gmail_message.
3419
+ Alternatively, let the user schedule the draft in the Gmail UI.
3420
+
3421
+ Args:
3422
+ user_google_email (str): The user's Google email address. Required for authentication.
3423
+ subject (Optional[str]): Email subject. Required for a new draft. Optional when
3424
+ replying with thread_id (inherits the parent message's subject) or forwarding
3425
+ (then defaults to 'Fwd: <original subject>').
3426
+ body (Optional[str]): Email body. Required unless forwarding (then an optional prepended note).
3427
+ body_format (Literal['plain', 'html']): Email body format. Defaults to 'plain'.
3428
+ forward_message_id (Optional[str]): Gmail message ID to forward. When set, the draft is a forward of that message.
3429
+ include_forwarded_attachments (bool): Whether to carry over the original attachments when forwarding. Defaults to True.
3430
+ to (Optional[str]): Optional recipient email address. Can be left empty for drafts.
3431
+ cc (Optional[str]): Optional CC email address.
3432
+ bcc (Optional[str]): Optional BCC email address.
3433
+ from_name (Optional[str]): Optional sender display name. If provided, the From header will be formatted as 'Name <email>'.
3434
+ from_email (Optional[str]): Optional 'Send As' alias email address. The alias must be
3435
+ configured in Gmail settings (Settings > Accounts > Send mail as). If not provided,
3436
+ the draft uses the account's default Send As address, then the primary or first
3437
+ usable Send-As entry, falling back to the authenticated user's email when Gmail
3438
+ returns no usable entry or settings access is not authorized.
3439
+ thread_id (Optional[str]): Optional Gmail thread ID to reply within. When
3440
+ in_reply_to is omitted, replies to the latest non-draft, non-trash message
3441
+ with an RFC Message-ID.
3442
+ in_reply_to (Optional[str]): Optional RFC Message-ID to explicitly reply to
3443
+ a specific message. Omit to reply to the latest eligible message.
3444
+ references (Optional[str]): Optional RFC Message-ID ancestry chain. Normally
3445
+ omit when thread_id is provided; the chain is derived automatically.
3446
+ attachments (List[Dict[str, str]]): Optional list of attachments. Each dict can contain:
3447
+ Option 1 - File path (auto-encodes):
3448
+ - 'path' (required): File path to attach
3449
+ - 'filename' (optional): Override filename
3450
+ - 'mime_type' (optional): Override MIME type (auto-detected if not provided)
3451
+ Option 2 - Base64 content:
3452
+ - 'content' (required): Standard base64-encoded file content (not urlsafe)
3453
+ - 'filename' (required): Name of the file
3454
+ - 'mime_type' (optional): MIME type (defaults to 'application/octet-stream')
3455
+ include_signature (bool): Whether to append Gmail signature HTML from send-as settings.
3456
+ When include_signature is true and Gmail signature retrieval fails for benign reasons
3457
+ (e.g., missing settings authorization), the draft proceeds with the requested or
3458
+ authenticated sender and without a signature.
3459
+ Non-benign failures such as quota/rate-limit or API errors raise ToolError and abort
3460
+ the draft.
3461
+ quote_original (bool): Whether to include the original message as a quoted reply, as
3462
+ Gmail web does. Only has an effect when thread_id is provided. Defaults to False.
3463
+ When enabled, fetches the original message and appends it below the signature.
3464
+ When the quote cannot be built, the draft is still created and the result says
3465
+ why it was left out.
3466
+ reply_all (bool): Whether to derive reply-all recipients from the thread: To = the
3467
+ sender being replied to, Cc = the other participants, excluding the authenticated
3468
+ account and from_email. Requires thread_id. Explicit to/cc win over the derived
3469
+ values; when cc is omitted, the sender being replied to is added to the derived Cc
3470
+ unless they are already in To.
3471
+ priority (str): 'high' or 'low' adds priority headers. Defaults to 'normal'.
3472
+
3473
+ Returns:
3474
+ str: Confirmation message with the created draft's ID.
3475
+
3476
+ Examples:
3477
+ # Create a new draft
3478
+ draft_gmail_message(subject="Hello", body="Hi there!", to="user@example.com")
3479
+
3480
+ # Create a draft from a configured alias (Send As)
3481
+ draft_gmail_message(
3482
+ subject="Business Inquiry",
3483
+ body="Hello from my business address...",
3484
+ to="user@example.com",
3485
+ from_email="business@mydomain.com"
3486
+ )
3487
+
3488
+ # Create a plaintext draft with CC and BCC
3489
+ draft_gmail_message(
3490
+ subject="Project Update",
3491
+ body="Here's the latest update...",
3492
+ to="user@example.com",
3493
+ cc="manager@example.com",
3494
+ bcc="archive@example.com"
3495
+ )
3496
+
3497
+ # Create a HTML draft with CC and BCC
3498
+ draft_gmail_message(
3499
+ subject="Project Update",
3500
+ body="<strong>Hi there!</strong>",
3501
+ body_format="html",
3502
+ to="user@example.com",
3503
+ cc="manager@example.com",
3504
+ bcc="archive@example.com"
3505
+ )
3506
+
3507
+ # Create a reply draft in plaintext
3508
+ draft_gmail_message(
3509
+ subject="Re: Meeting tomorrow",
3510
+ body="Thanks for the update!",
3511
+ to="user@example.com",
3512
+ thread_id="thread_123"
3513
+ )
3514
+
3515
+ # Create a reply draft in HTML
3516
+ draft_gmail_message(
3517
+ subject="Re: Meeting tomorrow",
3518
+ body="<strong>Thanks for the update!</strong>",
3519
+ body_format="html",
3520
+ to="user@example.com",
3521
+ thread_id="thread_123"
3522
+ )
3523
+
3524
+ # Save a forward (with the original attachments) as a draft for review
3525
+ draft_gmail_message(
3526
+ to="user@example.com",
3527
+ forward_message_id="abc123",
3528
+ body="FYI - see below."
3529
+ )
3530
+ """
3531
+ _reject_entity_escaped_html_body(body, body_format)
3532
+
3533
+ if forward_message_id:
3534
+ # Resolve and validate the identity, and take its Gmail-web From
3535
+ # displayName, the same way as a regular draft below.
3536
+ (
3537
+ sender_email,
3538
+ sender_display_name,
3539
+ _,
3540
+ ) = await _get_send_as_identity_and_signature(
3541
+ service, from_email=from_email, fallback_email=user_google_email
3542
+ )
3543
+ from_name = from_name or sender_display_name or None
3544
+ logger.info(
3545
+ f"[draft_gmail_message] Drafting forward of message '{forward_message_id}' for '{user_google_email}'"
3546
+ )
3547
+ return await _forward_gmail_message_impl(
3548
+ service=service,
3549
+ message_id=forward_message_id,
3550
+ to=to,
3551
+ subject=subject,
3552
+ forward_message=body,
3553
+ forward_message_format=body_format,
3554
+ include_attachments=include_forwarded_attachments,
3555
+ attachments=attachments,
3556
+ cc=cc,
3557
+ bcc=bcc,
3558
+ from_name=from_name,
3559
+ from_email=sender_email,
3560
+ user_google_email=user_google_email,
3561
+ direction=direction,
3562
+ as_draft=True,
3563
+ priority=priority,
3564
+ )
3565
+
3566
+ if body is None or (not thread_id and not (subject or "").strip()):
3567
+ raise UserInputError(
3568
+ "Both 'subject' and 'body' are required when drafting a message. "
3569
+ "'subject' may be omitted when replying with thread_id, where it is "
3570
+ "inherited from the parent message; both are optional only when "
3571
+ "forwarding via 'forward_message_id'."
3572
+ )
3573
+
3574
+ if reply_all and not thread_id:
3575
+ raise UserInputError(
3576
+ "'reply_all' requires a thread_id: the recipients are derived from "
3577
+ "the message being replied to."
3578
+ )
3579
+
3580
+ logger.info(
3581
+ f"[draft_gmail_message] Invoked. Email: '{user_google_email}', subject_len={len(subject) if subject else 0}"
3582
+ )
3583
+
3584
+ # Prepare the email message. An explicit alias needs no settings lookup when
3585
+ # its signature is disabled. Otherwise resolve the identity, signature and
3586
+ # Gmail-web From displayName together so Gmail's default sender and its
3587
+ # signature stay aligned.
3588
+ if from_email and not include_signature:
3589
+ sender_email, sender_display_name, resolved_signature_html = from_email, "", ""
3590
+ else:
3591
+ (
3592
+ sender_email,
3593
+ sender_display_name,
3594
+ resolved_signature_html,
3595
+ ) = await _get_send_as_identity_and_signature(
3596
+ service,
3597
+ from_email=from_email,
3598
+ fallback_email=user_google_email,
3599
+ )
3600
+ from_name = from_name or sender_display_name or None
3601
+ # Convert only the caller's body, before any signature or quoted original
3602
+ # is attached; see send_gmail_message.
3603
+ draft_body = html_newlines_to_br(body) if body_format == "html" else body
3604
+ signature_html = resolved_signature_html if include_signature else ""
3605
+
3606
+ reply_context = None
3607
+ if thread_id and (
3608
+ quote_original
3609
+ or reply_all
3610
+ or not (subject or "").strip()
3611
+ or not in_reply_to
3612
+ or not references
3613
+ or not to
3614
+ ):
3615
+ reply_context = await _fetch_thread_reply_context(
3616
+ service,
3617
+ thread_id,
3618
+ in_reply_to=in_reply_to,
3619
+ include_bodies=quote_original,
3620
+ )
3621
+
3622
+ target_reply = reply_context.get("target") if reply_context else None
3623
+ if thread_id and (not in_reply_to or not references):
3624
+ thread_message_ids = (
3625
+ reply_context.get("message_ids", []) if reply_context else []
3626
+ )
3627
+ in_reply_to, references = _derive_reply_headers(
3628
+ thread_message_ids, in_reply_to, references, target_reply
3629
+ )
3630
+
3631
+ if reply_all:
3632
+ if not target_reply:
3633
+ raise UserInputError(
3634
+ f"Could not load the message to reply to in thread '{thread_id}', "
3635
+ "so reply-all recipients cannot be derived. Retry, or pass 'to' "
3636
+ "and 'cc' explicitly without 'reply_all'."
3637
+ )
3638
+ to, cc = _derive_reply_all_recipients(
3639
+ target_reply, {user_google_email, sender_email}, to, cc
3640
+ )
3641
+ elif thread_id and not to and target_reply:
3642
+ to = target_reply.get("reply_to") or target_reply.get("from") or to
3643
+ if thread_id and not (subject or "").strip():
3644
+ subject = _inherit_reply_subject(thread_id, target_reply)
3645
+
3646
+ resolved_attachments = await _resolve_url_attachments(attachments)
3647
+ quote_target, quote_note = (
3648
+ _resolve_reply_quote(target_reply, web_path=not resolved_attachments)
3649
+ if thread_id and quote_original
3650
+ else (None, "")
3651
+ )
3652
+ if resolved_attachments:
3653
+ if quote_target:
3654
+ draft_body = _build_quoted_reply_body(
3655
+ draft_body, body_format, signature_html, quote_target
3656
+ )
3657
+ else:
3658
+ draft_body = _append_signature_to_body(
3659
+ draft_body, body_format, signature_html
3660
+ )
3661
+ raw_message, _thread_id_final, attached_count, attachment_errors = (
3662
+ _prepare_gmail_message(
3663
+ subject=subject,
3664
+ body=draft_body,
3665
+ body_format=body_format,
3666
+ direction=direction,
3667
+ to=to,
3668
+ cc=cc,
3669
+ bcc=bcc,
3670
+ thread_id=thread_id,
3671
+ in_reply_to=in_reply_to,
3672
+ references=references,
3673
+ from_email=sender_email,
3674
+ from_name=from_name,
3675
+ attachments=resolved_attachments,
3676
+ priority=priority,
3677
+ )
3678
+ )
3679
+ else:
3680
+ # Without attachments the draft takes the Gmail-web faithful path.
3681
+ raw_message = _build_web_compose_raw(
3682
+ subject=subject,
3683
+ body=_append_signature_to_body(draft_body, body_format, signature_html),
3684
+ body_format=body_format,
3685
+ to=to,
3686
+ cc=cc,
3687
+ bcc=bcc,
3688
+ from_email=sender_email,
3689
+ from_name=from_name,
3690
+ in_reply_to=in_reply_to,
3691
+ references=references,
3692
+ direction=direction,
3693
+ reply_target=quote_target,
3694
+ priority=priority,
3695
+ )
3696
+ attached_count, attachment_errors = 0, []
3697
+
3698
+ requested_attachment_count = len(attachments or [])
3699
+ if requested_attachment_count > 0 and attached_count == 0:
3700
+ details = (
3701
+ f" Details: {'; '.join(attachment_errors)}" if attachment_errors else ""
3702
+ )
3703
+ raise UserInputError(
3704
+ "No valid attachments were added. Verify each attachment path/content and retry."
3705
+ f"{details}"
3706
+ )
3707
+
3708
+ # Create a draft instead of sending. Gmail requires message.threadId plus
3709
+ # RFC-compliant In-Reply-To/References headers to add a draft to a thread.
3710
+ # If we could not derive the headers, fall back to an unthreaded draft
3711
+ # instead of sending an invalid thread request.
3712
+ draft_body = {"message": {"raw": raw_message}}
3713
+ if thread_id and in_reply_to and references:
3714
+ draft_body["message"]["threadId"] = thread_id
3715
+
3716
+ # Create the draft
3717
+ created_draft = await asyncio.to_thread(
3718
+ service.users().drafts().create(userId="me", body=draft_body).execute,
3719
+ num_retries=GOOGLE_API_WRITE_RETRIES,
3720
+ )
3721
+ draft_id = created_draft.get("id")
3722
+ attachment_info = _format_attachment_result(
3723
+ attached_count, requested_attachment_count
3724
+ )
3725
+ return f"Draft created{attachment_info}! Draft ID: {draft_id}{quote_note}"
3726
+
3727
+
3728
+ def _format_thread_content(
3729
+ thread_data: dict,
3730
+ thread_id: str,
3731
+ body_format: Literal["text", "html", "raw"] = "text",
3732
+ raw_contents: Optional[Dict[str, str]] = None,
3733
+ include_links: bool = False,
3734
+ ) -> str:
3735
+ """
3736
+ Helper function to format thread content from Gmail API response.
3737
+
3738
+ Args:
3739
+ thread_data (dict): Thread data from Gmail API
3740
+ thread_id (str): Thread ID for display
3741
+ body_format: Output format - "text" (default), "html", or "raw"
3742
+ raw_contents: Optional mapping of message IDs to decoded raw MIME content
3743
+ include_links: In text mode, append each body's http(s) links missing from the text
3744
+
3745
+ Returns:
3746
+ str: Formatted thread content
3747
+ """
3748
+ messages = thread_data.get("messages", [])
3749
+ if not messages:
3750
+ return f"No messages found in thread '{thread_id}'."
3751
+
3752
+ # Extract thread subject from the first message
3753
+ first_message = messages[0]
3754
+ first_headers = _extract_headers(first_message.get("payload", {}), ["Subject"])
3755
+ thread_subject = first_headers.get("Subject", "(no subject)")
3756
+
3757
+ # Build the thread content
3758
+ content_lines = [
3759
+ f"Thread ID: {thread_id}",
3760
+ f"Subject: {thread_subject}",
3761
+ f"Messages: {len(messages)}",
3762
+ "",
3763
+ ]
3764
+
3765
+ # Process each message in the thread
3766
+ for i, message in enumerate(messages, 1):
3767
+ payload = message.get("payload", {})
3768
+ # Extract headers
3769
+ headers = _extract_headers(payload, GMAIL_METADATA_HEADERS)
3770
+
3771
+ sender = headers.get("From", "(unknown sender)")
3772
+ date = headers.get("Date", "(unknown date)")
3773
+ subject = headers.get("Subject", "(no subject)")
3774
+ reply_to = headers.get("Reply-To", "")
3775
+ to = headers.get("To", "")
3776
+ cc = headers.get("Cc", "")
3777
+ rfc822_message_id = headers.get("Message-ID", "")
3778
+ in_reply_to = headers.get("In-Reply-To", "")
3779
+ references = headers.get("References", "")
3780
+
3781
+ if body_format == "raw":
3782
+ body_data = (raw_contents or {}).get(
3783
+ message.get("id", ""), "[No raw content found]"
3784
+ )
3785
+ body_label = "RAW MIME"
3786
+ else:
3787
+ # Extract both text and HTML bodies
3788
+ bodies = _extract_message_bodies(payload)
3789
+ text_body = bodies.get("text", "")
3790
+ html_body = bodies.get("html", "")
3791
+
3792
+ # Format body content with HTML fallback
3793
+ body_data = _format_body_content(
3794
+ text_body,
3795
+ html_body,
3796
+ body_format=body_format,
3797
+ include_links=include_links,
3798
+ ) + _render_attached_messages(
3799
+ payload, body_format, include_links=include_links
3800
+ )
3801
+ body_label = "BODY"
3802
+
3803
+ # Extract attachment metadata for this message
3804
+ attachments = _extract_attachments(payload)
3805
+ message_id = message.get("id", "")
3806
+
3807
+ # Add message to content
3808
+ content_lines.extend(
3809
+ [
3810
+ f"=== Message {i}{thread_message_status(message)} ===",
3811
+ f"From: {sender}",
3812
+ f"Date: {date}",
3813
+ ]
3814
+ )
3815
+ if reply_to:
3816
+ content_lines.append(f"Reply-To: {reply_to}")
3817
+ content_lines.append(
3818
+ f"To: {to}" if "To" in headers else "To: [not present in Gmail response]"
3819
+ )
3820
+ content_lines.append(
3821
+ f"Cc: {cc}" if "Cc" in headers else "Cc: [not present in Gmail response]"
3822
+ )
3823
+
3824
+ if rfc822_message_id:
3825
+ content_lines.append(f"Message-ID: {rfc822_message_id}")
3826
+ if in_reply_to:
3827
+ content_lines.append(f"In-Reply-To: {in_reply_to}")
3828
+ if references:
3829
+ content_lines.append(f"References: {references}")
3830
+
3831
+ # Only show subject if it's different from thread subject
3832
+ if subject != thread_subject:
3833
+ content_lines.append(f"Subject: {subject}")
3834
+
3835
+ if body_format == "raw":
3836
+ content_lines.extend(
3837
+ [
3838
+ "",
3839
+ f"--- {body_label} ---",
3840
+ body_data,
3841
+ "",
3842
+ ]
3843
+ )
3844
+ else:
3845
+ content_lines.extend(["", body_data, ""])
3846
+
3847
+ if attachments:
3848
+ content_lines.append("--- ATTACHMENTS ---")
3849
+ for attachment_index, att in enumerate(attachments):
3850
+ size_kb = att["size"] / 1024
3851
+ content_lines.append(
3852
+ f"{attachment_index + 1}. {att['filename']} ({att['mimeType']}, {size_kb:.1f} KB){' [in attached message]' if att.get('inAttachedMessage') else ''}\n"
3853
+ f" Attachment ID: {att['attachmentId']}\n"
3854
+ f" Use get_gmail_attachment_content(message_id='{message_id}', "
3855
+ f"attachment_id='{att['attachmentId']}', attachment_index={attachment_index}) to download"
3856
+ )
3857
+ content_lines.append("")
3858
+
3859
+ return "\n".join(content_lines)
3860
+
3861
+
3862
+ @server.tool(
3863
+ title="Get Gmail Thread Content",
3864
+ annotations=ToolAnnotations(
3865
+ readOnlyHint=True,
3866
+ destructiveHint=False,
3867
+ idempotentHint=True,
3868
+ openWorldHint=True,
3869
+ ),
3870
+ )
3871
+ @require_google_service("gmail", "gmail_read")
3872
+ @handle_http_errors("get_gmail_thread_content", is_read_only=True, service_type="gmail")
3873
+ async def get_gmail_thread_content(
3874
+ service,
3875
+ thread_id: str,
3876
+ user_google_email: str,
3877
+ body_format: Annotated[
3878
+ Literal["text", "html", "raw"],
3879
+ Field(
3880
+ description=(
3881
+ "Body output format. "
3882
+ "'text' (default) returns plaintext (HTML converted to text as fallback). "
3883
+ "'html' returns the raw HTML body as-is without conversion. "
3884
+ "'raw' fetches each message's full raw MIME content and returns the base64url-decoded body."
3885
+ ),
3886
+ ),
3887
+ ] = "text",
3888
+ include_analysis: Annotated[
3889
+ bool,
3890
+ Field(
3891
+ description=(
3892
+ "When True, the return value is a dict with both the formatted "
3893
+ "thread content AND structured ownership analysis (last sender, "
3894
+ "ball-in-court verdict, per-sender message counts, participants). "
3895
+ "Defaults to False, in which case the existing string return shape "
3896
+ "is preserved."
3897
+ ),
3898
+ ),
3899
+ ] = False,
3900
+ include_links: Annotated[
3901
+ bool, Field(description=INCLUDE_LINKS_DESCRIPTION)
3902
+ ] = False,
3903
+ ) -> "str | Dict[str, Any]":
3904
+ """
3905
+ Retrieves the complete content of a Gmail conversation thread, including all messages.
3906
+
3907
+ Optionally also returns structured ownership analysis so a caller can
3908
+ determine who sent the last message and who owes whom a response without
3909
+ re-parsing the formatted string or making a second tool call.
3910
+
3911
+ Args:
3912
+ thread_id (str): The unique ID of the Gmail thread to retrieve.
3913
+ user_google_email (str): The user's Google email address. Required.
3914
+ body_format (Literal["text", "html", "raw"]): Body output format.
3915
+ "text" (default) returns plaintext (HTML converted to text as fallback).
3916
+ "html" returns the raw HTML body as-is without conversion.
3917
+ "raw" fetches each message's full raw MIME content and returns the base64url-decoded body.
3918
+ include_analysis (bool): When True, returns a dict containing both the
3919
+ formatted thread content and structured ownership analysis. When
3920
+ False (default), returns the formatted content string (existing
3921
+ behavior, unchanged).
3922
+ include_links (bool): Append the HTML body's http(s) links missing from the text output.
3923
+
3924
+ Returns:
3925
+ str: When `include_analysis=False` (default). The complete thread
3926
+ content with all messages formatted for reading.
3927
+
3928
+ Dict[str, Any]: When `include_analysis=True`. A dict with keys
3929
+ "content" (str) and "analysis" (dict). See
3930
+ `_analyze_thread_ownership_impl` for the analysis schema.
3931
+ """
3932
+ logger.info(
3933
+ f"[get_gmail_thread_content] Invoked. Thread ID: '{thread_id}', "
3934
+ f"Email: '{user_google_email}', include_analysis={include_analysis}"
3935
+ )
3936
+
3937
+ # Fetch the complete thread with all messages
3938
+ thread_response = await asyncio.to_thread(
3939
+ service.users().threads().get(userId="me", id=thread_id, format="full").execute
3940
+ )
3941
+
3942
+ raw_contents = None
3943
+ if body_format == "raw":
3944
+ message_ids = [
3945
+ message["id"]
3946
+ for message in thread_response.get("messages", [])
3947
+ if message.get("id")
3948
+ ]
3949
+ raw_contents = await _fetch_raw_message_contents(
3950
+ service, message_ids, log_prefix="get_gmail_thread_content"
3951
+ )
3952
+ else:
3953
+ await fetch_attachment_backed_bodies(
3954
+ service, thread_response.get("messages", [])
3955
+ )
3956
+
3957
+ content = _format_thread_content(
3958
+ thread_response,
3959
+ thread_id,
3960
+ body_format=body_format,
3961
+ raw_contents=raw_contents,
3962
+ include_links=include_links,
3963
+ )
3964
+
3965
+ if not include_analysis:
3966
+ return content
3967
+
3968
+ analysis = _analyze_thread_ownership_impl(thread_response, user_google_email)
3969
+ return {"content": content, "analysis": analysis}
3970
+
3971
+
3972
+ @server.tool(
3973
+ title="Get Gmail Threads Content Batch",
3974
+ annotations=ToolAnnotations(
3975
+ readOnlyHint=True,
3976
+ destructiveHint=False,
3977
+ idempotentHint=True,
3978
+ openWorldHint=True,
3979
+ ),
3980
+ )
3981
+ @require_google_service("gmail", "gmail_read")
3982
+ @handle_http_errors(
3983
+ "get_gmail_threads_content_batch", is_read_only=True, service_type="gmail"
3984
+ )
3985
+ async def get_gmail_threads_content_batch(
3986
+ service,
3987
+ thread_ids: StringList,
3988
+ user_google_email: str,
3989
+ body_format: Annotated[
3990
+ Literal["text", "html", "raw"],
3991
+ Field(
3992
+ description=(
3993
+ "Body output format. "
3994
+ "'text' (default) returns plaintext (HTML converted to text as fallback). "
3995
+ "'html' returns the raw HTML body as-is without conversion. "
3996
+ "'raw' fetches each message's full raw MIME content and returns the base64url-decoded body."
3997
+ ),
3998
+ ),
3999
+ ] = "text",
4000
+ include_links: Annotated[
4001
+ bool, Field(description=INCLUDE_LINKS_DESCRIPTION)
4002
+ ] = False,
4003
+ ) -> str:
4004
+ """
4005
+ Retrieves the content of multiple Gmail threads in a single batch request.
4006
+ Supports up to 25 threads per batch to prevent SSL connection exhaustion.
4007
+
4008
+ Args:
4009
+ thread_ids (List[str]): A list of Gmail thread IDs to retrieve. The function will automatically batch requests in chunks of 25.
4010
+ user_google_email (str): The user's Google email address. Required.
4011
+ body_format (Literal["text", "html", "raw"]): Body output format.
4012
+ "text" (default) returns plaintext (HTML converted to text as fallback).
4013
+ "html" returns the raw HTML body as-is without conversion.
4014
+ "raw" fetches each message's full raw MIME content and returns the base64url-decoded body.
4015
+ include_links (bool): Append the HTML body's http(s) links missing from the text output.
4016
+
4017
+ Returns:
4018
+ str: A formatted list of thread contents with separators.
4019
+ """
4020
+ logger.info(
4021
+ f"[get_gmail_threads_content_batch] Invoked. Thread count: {len(thread_ids)}, Email: '{user_google_email}'"
4022
+ )
4023
+
4024
+ if not thread_ids:
4025
+ raise ValueError("No thread IDs provided")
4026
+
4027
+ output_threads = []
4028
+
4029
+ def _batch_callback(request_id, response, exception):
4030
+ """Callback for batch requests"""
4031
+ results[request_id] = {"data": response, "error": exception}
4032
+
4033
+ # Process in smaller chunks to prevent SSL connection exhaustion
4034
+ for chunk_start in range(0, len(thread_ids), GMAIL_BATCH_SIZE):
4035
+ chunk_ids = thread_ids[chunk_start : chunk_start + GMAIL_BATCH_SIZE]
4036
+ results: Dict[str, Dict] = {}
4037
+
4038
+ batch_completed = False
4039
+
4040
+ # Try to use batch API
4041
+ try:
4042
+ batch = service.new_batch_http_request(callback=_batch_callback)
4043
+
4044
+ for tid in chunk_ids:
4045
+ req = service.users().threads().get(userId="me", id=tid, format="full")
4046
+ batch.add(req, request_id=tid)
4047
+
4048
+ # Execute batch request
4049
+ await asyncio.to_thread(batch.execute)
4050
+ batch_completed = True
4051
+
4052
+ except Exception as batch_error:
4053
+ # Fallback to sequential processing instead of parallel to prevent SSL exhaustion
4054
+ logger.warning(
4055
+ f"[get_gmail_threads_content_batch] Batch API failed, falling back to sequential processing: {batch_error}"
4056
+ )
4057
+
4058
+ # Process threads sequentially with small delays to prevent connection exhaustion
4059
+ for tid in chunk_ids:
4060
+ tid_result, thread_data, error = await _fetch_thread_with_retry(
4061
+ service,
4062
+ thread_id=tid,
4063
+ log_prefix="get_gmail_threads_content_batch",
4064
+ )
4065
+ results[tid_result] = {"data": thread_data, "error": error}
4066
+ # Brief delay between requests to allow connection cleanup
4067
+ await asyncio.sleep(GMAIL_REQUEST_DELAY)
4068
+
4069
+ # Sub-requests that failed with a transient error (e.g. 429 rate limit)
4070
+ # inside an otherwise successful batch response: re-fetch only those IDs
4071
+ # and merge. The sequential fallback has already exhausted its retries.
4072
+ retryable_ids = (
4073
+ _retryable_result_ids(results, chunk_ids) if batch_completed else []
4074
+ )
4075
+ if retryable_ids:
4076
+ logger.warning(
4077
+ f"[get_gmail_threads_content_batch] {len(retryable_ids)}/{len(chunk_ids)} "
4078
+ f"threads failed with retryable errors; re-fetching: {retryable_ids}"
4079
+ )
4080
+ await asyncio.sleep(GMAIL_RATE_LIMIT_BACKOFF)
4081
+ for tid in retryable_ids:
4082
+ tid_result, thread_data, error = await _fetch_thread_with_retry(
4083
+ service,
4084
+ thread_id=tid,
4085
+ log_prefix="get_gmail_threads_content_batch",
4086
+ )
4087
+ results[tid_result] = {"data": thread_data, "error": error}
4088
+ await asyncio.sleep(GMAIL_REQUEST_DELAY)
4089
+
4090
+ # Process results for this chunk
4091
+ for tid in chunk_ids:
4092
+ entry = results.get(tid, {"data": None, "error": "No result"})
4093
+
4094
+ if entry["error"]:
4095
+ output_threads.append(f"⚠️ Thread {tid}: {entry['error']}\n")
4096
+ else:
4097
+ thread = entry["data"]
4098
+ if not thread:
4099
+ output_threads.append(f"⚠️ Thread {tid}: No data returned\n")
4100
+ continue
4101
+
4102
+ raw_contents = None
4103
+ if body_format == "raw":
4104
+ message_ids = [
4105
+ message["id"]
4106
+ for message in thread.get("messages", [])
4107
+ if message.get("id")
4108
+ ]
4109
+ raw_contents = await _fetch_raw_message_contents(
4110
+ service,
4111
+ message_ids,
4112
+ log_prefix="get_gmail_threads_content_batch",
4113
+ )
4114
+ else:
4115
+ await fetch_attachment_backed_bodies(
4116
+ service, thread.get("messages", [])
4117
+ )
4118
+
4119
+ output_threads.append(
4120
+ _format_thread_content(
4121
+ thread,
4122
+ tid,
4123
+ body_format=body_format,
4124
+ raw_contents=raw_contents,
4125
+ include_links=include_links,
4126
+ )
4127
+ )
4128
+
4129
+ # Combine all threads with separators
4130
+ header = f"Retrieved {len(thread_ids)} threads:"
4131
+ return header + "\n\n" + "\n---\n\n".join(output_threads)
4132
+
4133
+
4134
+ @server.tool(
4135
+ title="List Gmail Labels",
4136
+ annotations=ToolAnnotations(
4137
+ readOnlyHint=True,
4138
+ destructiveHint=False,
4139
+ idempotentHint=True,
4140
+ openWorldHint=True,
4141
+ ),
4142
+ )
4143
+ @handle_http_errors("list_gmail_labels", is_read_only=True, service_type="gmail")
4144
+ @require_google_service("gmail", "gmail_read")
4145
+ async def list_gmail_labels(
4146
+ service,
4147
+ user_google_email: str,
4148
+ prefix: Optional[str] = None,
4149
+ compact: bool = False,
4150
+ include_system: bool = True,
4151
+ ) -> str:
4152
+ """
4153
+ Lists labels in the user's Gmail account.
4154
+
4155
+ Args:
4156
+ user_google_email (str): The user's Google email address. Required.
4157
+ prefix (Optional[str]): Return only labels whose name starts with this
4158
+ exact (case-sensitive) string. users.labels.list accepts no filter,
4159
+ so the full list is fetched and narrowed here: this shrinks what the
4160
+ caller receives, not the API call.
4161
+ compact (bool): Return minimal JSON {"count", "labels": [{"id", "name"}]}
4162
+ sorted by name, instead of the formatted text list. For callers
4163
+ that parse the result, e.g. a label cache refresh.
4164
+ include_system (bool): Include Gmail system labels (INBOX, SENT, ...).
4165
+ Set False to return user labels only.
4166
+
4167
+ Returns:
4168
+ str: A formatted list of labels, or minimal JSON when compact=True.
4169
+ """
4170
+ logger.info(f"[list_gmail_labels] Invoked. Email: '{user_google_email}'")
4171
+
4172
+ response = await asyncio.to_thread(
4173
+ service.users().labels().list(userId="me").execute
4174
+ )
4175
+ labels = response.get("labels", [])
4176
+
4177
+ if not include_system:
4178
+ labels = [lab for lab in labels if lab.get("type") != "system"]
4179
+ if prefix is not None:
4180
+ labels = [lab for lab in labels if lab.get("name", "").startswith(prefix)]
4181
+
4182
+ if compact:
4183
+ return json.dumps(
4184
+ {
4185
+ "count": len(labels),
4186
+ "labels": sorted(
4187
+ ({"id": lab["id"], "name": lab["name"]} for lab in labels),
4188
+ key=lambda lab: lab["name"],
4189
+ ),
4190
+ },
4191
+ ensure_ascii=False,
4192
+ )
4193
+
4194
+ if not labels:
4195
+ parts = ["No"]
4196
+ parts.append("user" if not include_system else "")
4197
+ parts.append("labels found")
4198
+ if prefix is not None:
4199
+ parts.append(f"with prefix {prefix!r}")
4200
+ msg = " ".join(p for p in parts if p) + "."
4201
+ return msg
4202
+
4203
+ lines = [f"Found {len(labels)} labels:", ""]
4204
+
4205
+ system_labels = []
4206
+ user_labels = []
4207
+
4208
+ for label in labels:
4209
+ if label.get("type") == "system":
4210
+ system_labels.append(label)
4211
+ else:
4212
+ user_labels.append(label)
4213
+
4214
+ if system_labels:
4215
+ lines.append("📂 SYSTEM LABELS:")
4216
+ for label in system_labels:
4217
+ lines.append(f" • {label['name']} (ID: {label['id']})")
4218
+ lines.append("")
4219
+
4220
+ if user_labels:
4221
+ lines.append("🏷️ USER LABELS:")
4222
+ for label in user_labels:
4223
+ lines.append(f" • {label['name']} (ID: {label['id']})")
4224
+
4225
+ return "\n".join(lines)
4226
+
4227
+
4228
+ @server.tool(
4229
+ title="Manage Gmail Label",
4230
+ annotations=ToolAnnotations(
4231
+ readOnlyHint=False,
4232
+ destructiveHint=True,
4233
+ idempotentHint=False,
4234
+ openWorldHint=True,
4235
+ ),
4236
+ )
4237
+ @handle_http_errors("manage_gmail_label", service_type="gmail")
4238
+ @require_google_service("gmail", GMAIL_LABELS_SCOPE)
4239
+ async def manage_gmail_label(
4240
+ service,
4241
+ user_google_email: str,
4242
+ action: Literal["create", "update", "delete"],
4243
+ name: Optional[str] = None,
4244
+ label_id: Optional[str] = None,
4245
+ label_list_visibility: Optional[
4246
+ Literal["labelShow", "labelShowIfUnread", "labelHide"]
4247
+ ] = None,
4248
+ message_list_visibility: Optional[Literal["show", "hide"]] = None,
4249
+ background_color: Optional[str] = None,
4250
+ text_color: Optional[str] = None,
4251
+ clear_color: bool = False,
4252
+ ) -> str:
4253
+ """
4254
+ Manages Gmail labels: create, update, or delete labels.
4255
+
4256
+ Args:
4257
+ user_google_email (str): The user's Google email address. Required.
4258
+ action (Literal["create", "update", "delete"]): Action to perform on the label.
4259
+ name (Optional[str]): Label name. Required for create, optional for update.
4260
+ label_id (Optional[str]): Label ID. Required for update and delete operations.
4261
+ label_list_visibility (Optional[Literal["labelShow", "labelShowIfUnread", "labelHide"]]): Whether the label is shown in the label list. Defaults to "labelShow" on create. On update, omitting it keeps the label's current setting.
4262
+ message_list_visibility (Optional[Literal["show", "hide"]]): Whether the label's messages are shown in the message list. Defaults to "show" on create. On update, omitting it keeps the label's current setting.
4263
+ background_color (Optional[str]): Label background color as a hex string, e.g. "#fb4c2f". Set together with text_color; Gmail requires both. Gmail accepts only its own palette, and an unsupported value is rejected before the request. Colors apply to user labels, not system labels.
4264
+ text_color (Optional[str]): Label text color as a hex string, e.g. "#ffffff". Set together with background_color. Same palette. On update, omitting both keeps the label's current color.
4265
+ clear_color (bool): On update, remove the label's current color. Cannot be combined with background_color or text_color.
4266
+
4267
+ Returns:
4268
+ str: Confirmation message of the label operation.
4269
+ """
4270
+ logger.info(
4271
+ f"[manage_gmail_label] Invoked. Email: '{user_google_email}', Action: '{action}'"
4272
+ )
4273
+
4274
+ if action == "create" and not name:
4275
+ raise UserInputError("Label name is required for create action.")
4276
+
4277
+ if action in ["update", "delete"] and not label_id:
4278
+ raise UserInputError("Label ID is required for update and delete actions.")
4279
+
4280
+ color = None
4281
+ if action in ["create", "update"]:
4282
+ if clear_color:
4283
+ if action == "create":
4284
+ raise ToolExecutionError(
4285
+ "clear_color is only valid for update actions."
4286
+ )
4287
+ if background_color is not None or text_color is not None:
4288
+ raise ToolExecutionError(
4289
+ "clear_color cannot be combined with background_color or text_color."
4290
+ )
4291
+ else:
4292
+ # Validated before any request so a bad color costs no API call.
4293
+ color = build_label_color(background_color, text_color)
4294
+
4295
+ if action == "create":
4296
+ label_object = {
4297
+ "name": name,
4298
+ "labelListVisibility": label_list_visibility or "labelShow",
4299
+ "messageListVisibility": message_list_visibility or "show",
4300
+ }
4301
+ if color:
4302
+ label_object["color"] = color
4303
+ created_label = await asyncio.to_thread(
4304
+ service.users().labels().create(userId="me", body=label_object).execute
4305
+ )
4306
+ return f"Label created successfully!\nName: {created_label['name']}\nID: {created_label['id']}"
4307
+
4308
+ elif action == "update":
4309
+ current_label = await asyncio.to_thread(
4310
+ service.users().labels().get(userId="me", id=label_id).execute
4311
+ )
4312
+
4313
+ label_object = {
4314
+ "id": label_id,
4315
+ "name": name if name is not None else current_label["name"],
4316
+ # A PUT replaces the label outright, so every field the caller left
4317
+ # out is carried over from the fetched label rather than defaulted.
4318
+ "labelListVisibility": label_list_visibility
4319
+ or current_label.get("labelListVisibility")
4320
+ or "labelShow",
4321
+ "messageListVisibility": message_list_visibility
4322
+ or current_label.get("messageListVisibility")
4323
+ or "show",
4324
+ }
4325
+ label_color = None if clear_color else color or current_label.get("color")
4326
+ if label_color:
4327
+ label_object["color"] = label_color
4328
+
4329
+ updated_label = await asyncio.to_thread(
4330
+ service.users()
4331
+ .labels()
4332
+ .update(userId="me", id=label_id, body=label_object)
4333
+ .execute
4334
+ )
4335
+ return f"Label updated successfully!\nName: {updated_label['name']}\nID: {updated_label['id']}"
4336
+
4337
+ elif action == "delete":
4338
+ label = await asyncio.to_thread(
4339
+ service.users().labels().get(userId="me", id=label_id).execute
4340
+ )
4341
+ label_name = label["name"]
4342
+
4343
+ await asyncio.to_thread(
4344
+ service.users().labels().delete(userId="me", id=label_id).execute
4345
+ )
4346
+ return f"Label '{label_name}' (ID: {label_id}) deleted successfully!"
4347
+
4348
+
4349
+ @server.tool(
4350
+ title="List Gmail Filters",
4351
+ annotations=ToolAnnotations(
4352
+ readOnlyHint=True,
4353
+ destructiveHint=False,
4354
+ idempotentHint=True,
4355
+ openWorldHint=True,
4356
+ ),
4357
+ )
4358
+ @handle_http_errors("list_gmail_filters", is_read_only=True, service_type="gmail")
4359
+ @require_google_service("gmail", "gmail_settings_basic")
4360
+ async def list_gmail_filters(service, user_google_email: str) -> str:
4361
+ """
4362
+ Lists all Gmail filters configured in the user's mailbox.
4363
+
4364
+ Args:
4365
+ user_google_email (str): The user's Google email address. Required.
4366
+
4367
+ Returns:
4368
+ str: A formatted list of filters with their criteria and actions.
4369
+ """
4370
+ logger.info(f"[list_gmail_filters] Invoked. Email: '{user_google_email}'")
4371
+
4372
+ response = await asyncio.to_thread(
4373
+ service.users().settings().filters().list(userId="me").execute
4374
+ )
4375
+
4376
+ filters = response.get("filter") or response.get("filters") or []
4377
+
4378
+ if not filters:
4379
+ return "No filters found."
4380
+
4381
+ lines = [f"Found {len(filters)} filters:", ""]
4382
+
4383
+ for filter_obj in filters:
4384
+ filter_id = filter_obj.get("id", "(no id)")
4385
+ criteria = filter_obj.get("criteria", {})
4386
+ action = filter_obj.get("action", {})
4387
+
4388
+ lines.append(f"🔹 Filter ID: {filter_id}")
4389
+ lines.append(" Criteria:")
4390
+
4391
+ criteria_lines = []
4392
+ if criteria.get("from"):
4393
+ criteria_lines.append(f"From: {criteria['from']}")
4394
+ if criteria.get("to"):
4395
+ criteria_lines.append(f"To: {criteria['to']}")
4396
+ if criteria.get("subject"):
4397
+ criteria_lines.append(f"Subject: {criteria['subject']}")
4398
+ if criteria.get("query"):
4399
+ criteria_lines.append(f"Query: {criteria['query']}")
4400
+ if criteria.get("negatedQuery"):
4401
+ criteria_lines.append(f"Exclude Query: {criteria['negatedQuery']}")
4402
+ if criteria.get("hasAttachment"):
4403
+ criteria_lines.append("Has attachment")
4404
+ if criteria.get("excludeChats"):
4405
+ criteria_lines.append("Exclude chats")
4406
+ if criteria.get("size"):
4407
+ comparison = criteria.get("sizeComparison", "")
4408
+ criteria_lines.append(
4409
+ f"Size {comparison or ''} {criteria['size']} bytes".strip()
4410
+ )
4411
+
4412
+ if not criteria_lines:
4413
+ criteria_lines.append("(none)")
4414
+
4415
+ lines.extend([f" • {line}" for line in criteria_lines])
4416
+
4417
+ lines.append(" Actions:")
4418
+ action_lines = []
4419
+ if action.get("forward"):
4420
+ action_lines.append(f"Forward to: {action['forward']}")
4421
+ if action.get("removeLabelIds"):
4422
+ action_lines.append(f"Remove labels: {', '.join(action['removeLabelIds'])}")
4423
+ if action.get("addLabelIds"):
4424
+ action_lines.append(f"Add labels: {', '.join(action['addLabelIds'])}")
4425
+
4426
+ if not action_lines:
4427
+ action_lines.append("(none)")
4428
+
4429
+ lines.extend([f" • {line}" for line in action_lines])
4430
+ lines.append("")
4431
+
4432
+ return "\n".join(lines).rstrip()
4433
+
4434
+
4435
+ @server.tool(
4436
+ title="Manage Gmail Filter",
4437
+ annotations=ToolAnnotations(
4438
+ readOnlyHint=False,
4439
+ destructiveHint=True,
4440
+ idempotentHint=False,
4441
+ openWorldHint=True,
4442
+ ),
4443
+ )
4444
+ @handle_http_errors("manage_gmail_filter", service_type="gmail")
4445
+ @require_google_service("gmail", "gmail_settings_basic")
4446
+ async def manage_gmail_filter(
4447
+ service,
4448
+ user_google_email: str,
4449
+ action: str,
4450
+ criteria: Optional[JsonDict] = None,
4451
+ filter_action: Optional[JsonDict] = None,
4452
+ filter_id: Optional[str] = None,
4453
+ dry_run: bool = False,
4454
+ max_messages: int = FILTER_APPLY_DEFAULT_MAX_MESSAGES,
4455
+ ) -> str:
4456
+ """
4457
+ Manages Gmail filters: create, delete, update, and apply to existing mail.
4458
+
4459
+ - update: Gmail has no filter update API, so the filter is recreated (new
4460
+ one first, then the old one is deleted) and its ID changes. A passed
4461
+ criteria or filter_action replaces that whole object; omit one to keep
4462
+ the old filter's.
4463
+ - apply: runs a filter's label actions on mail ALREADY in the mailbox
4464
+ (Gmail filters only act on new mail). Only matching messages change,
4465
+ not whole conversations as in the web UI. Use filter_id, or criteria +
4466
+ filter_action for an ad-hoc run. Forwarding is never applied. Use
4467
+ dry_run=true first to see the search query and the match count.
4468
+ Needs the gmail.modify scope in addition to gmail.settings.basic.
4469
+
4470
+ Args:
4471
+ user_google_email (str): The user's Google email address. Required.
4472
+ action (str): "create", "delete", "update" or "apply".
4473
+ criteria (Optional[Dict[str, Any]]): Filter criteria object (required for create; optional for update/apply).
4474
+ filter_action (Optional[Dict[str, Any]]): Filter action object (required for create; optional for update/apply). Named 'filter_action' to avoid shadowing the 'action' parameter.
4475
+ filter_id (Optional[str]): ID of the filter (required for delete and update; optional for apply).
4476
+ dry_run (bool): apply only: count matches without changing anything.
4477
+ max_messages (int): apply only: safety cap on messages changed (default 5000).
4478
+
4479
+ Returns:
4480
+ str: Confirmation message with filter details.
4481
+ """
4482
+ action_lower = action.lower().strip()
4483
+ if action_lower == "create":
4484
+ if not criteria or not filter_action:
4485
+ raise ValueError(
4486
+ "criteria and filter_action are required for create action"
4487
+ )
4488
+ logger.info("[manage_gmail_filter] Creating filter")
4489
+ filter_body = {"criteria": criteria, "action": filter_action}
4490
+ created_filter = await asyncio.to_thread(
4491
+ service.users()
4492
+ .settings()
4493
+ .filters()
4494
+ .create(userId="me", body=filter_body)
4495
+ .execute
4496
+ )
4497
+ fid = created_filter.get("id", "(unknown)")
4498
+ return f"Filter created successfully!\nFilter ID: {fid}"
4499
+ elif action_lower == "delete":
4500
+ if not filter_id:
4501
+ raise ValueError("filter_id is required for delete action")
4502
+ logger.info(f"[manage_gmail_filter] Deleting filter {filter_id}")
4503
+ filter_details = await asyncio.to_thread(
4504
+ service.users().settings().filters().get(userId="me", id=filter_id).execute
4505
+ )
4506
+ await asyncio.to_thread(
4507
+ service.users()
4508
+ .settings()
4509
+ .filters()
4510
+ .delete(userId="me", id=filter_id)
4511
+ .execute
4512
+ )
4513
+ criteria_info = filter_details.get("criteria", {})
4514
+ action_info = filter_details.get("action", {})
4515
+ return (
4516
+ "Filter deleted successfully!\n"
4517
+ f"Filter ID: {filter_id}\n"
4518
+ f"Criteria: {criteria_info or '(none)'}\n"
4519
+ f"Action: {action_info or '(none)'}"
4520
+ )
4521
+ elif action_lower == "update":
4522
+ if not filter_id:
4523
+ raise ValueError("filter_id is required for update action")
4524
+ if not criteria and not filter_action:
4525
+ raise ValueError(
4526
+ "criteria and/or filter_action are required for update action"
4527
+ )
4528
+ logger.info(f"[manage_gmail_filter] Updating filter {filter_id}")
4529
+ created = await update_gmail_filter(
4530
+ service, filter_id, criteria=criteria, filter_action=filter_action
4531
+ )
4532
+ return (
4533
+ "Filter updated successfully (Gmail recreates filters on update).\n"
4534
+ f"Old filter ID: {filter_id} (deleted)\n"
4535
+ f"New filter ID: {created.get('id', '(unknown)')}\n"
4536
+ f"Criteria: {created.get('criteria') or '(none)'}\n"
4537
+ f"Action: {created.get('action') or '(none)'}"
4538
+ )
4539
+ elif action_lower == "apply":
4540
+ # Checked here, not in the decorator, so the other actions work with
4541
+ # only gmail.settings.basic.
4542
+ credentials = getattr(getattr(service, "_http", None), "credentials", None)
4543
+ granted = getattr(credentials, "scopes", None)
4544
+ if isinstance(granted, (list, tuple, set, frozenset)) and not (
4545
+ has_required_scopes(granted, [GMAIL_MODIFY_SCOPE])
4546
+ ):
4547
+ raise ToolExecutionError(
4548
+ "apply needs the gmail.modify scope to change existing messages; "
4549
+ "re-authenticate with Gmail modify access."
4550
+ )
4551
+ if max_messages < 1:
4552
+ raise ValueError("max_messages must be at least 1")
4553
+ if filter_id:
4554
+ existing = await asyncio.to_thread(
4555
+ service.users()
4556
+ .settings()
4557
+ .filters()
4558
+ .get(userId="me", id=filter_id)
4559
+ .execute
4560
+ )
4561
+ criteria = existing.get("criteria", {})
4562
+ filter_action = existing.get("action", {})
4563
+ if not criteria or not filter_action:
4564
+ raise ValueError(
4565
+ "apply needs filter_id, or both criteria and filter_action"
4566
+ )
4567
+ logger.info(
4568
+ f"[manage_gmail_filter] Applying filter to existing mail (dry_run={dry_run})"
4569
+ )
4570
+ result = await apply_gmail_filter_to_existing(
4571
+ service,
4572
+ criteria,
4573
+ filter_action,
4574
+ dry_run=dry_run,
4575
+ max_messages=max_messages,
4576
+ )
4577
+ return format_filter_apply_result(result, dry_run)
4578
+ else:
4579
+ raise ValueError(
4580
+ f"Invalid action '{action_lower}'. Must be 'create', 'delete', "
4581
+ "'update' or 'apply'."
4582
+ )
4583
+
4584
+
4585
+ @server.tool(
4586
+ title="Modify Gmail Message Labels",
4587
+ annotations=ToolAnnotations(
4588
+ readOnlyHint=False,
4589
+ destructiveHint=True,
4590
+ idempotentHint=False,
4591
+ openWorldHint=True,
4592
+ ),
4593
+ )
4594
+ @handle_http_errors("modify_gmail_message_labels", service_type="gmail")
4595
+ @require_google_service("gmail", GMAIL_MODIFY_SCOPE)
4596
+ async def modify_gmail_message_labels(
4597
+ service,
4598
+ user_google_email: str,
4599
+ message_id: str,
4600
+ add_label_ids: _OptionalLabelIdList = None,
4601
+ remove_label_ids: _OptionalLabelIdList = None,
4602
+ ) -> str:
4603
+ """
4604
+ Adds or removes labels from a Gmail message.
4605
+ To archive an email, remove the INBOX label.
4606
+ To delete an email, add the TRASH label.
4607
+
4608
+ Args:
4609
+ user_google_email (str): The user's Google email address. Required.
4610
+ message_id (str): The ID of the message to modify.
4611
+ add_label_ids (Optional[List[str]]): List of label IDs to add to the message.
4612
+ remove_label_ids (Optional[List[str]]): List of label IDs to remove from the message.
4613
+
4614
+ Returns:
4615
+ str: Confirmation message of the label changes applied to the message.
4616
+ """
4617
+ logger.info(
4618
+ f"[modify_gmail_message_labels] Invoked. Email: '{user_google_email}', Message ID: '{message_id}'"
4619
+ )
4620
+
4621
+ if not add_label_ids and not remove_label_ids:
4622
+ raise UserInputError(
4623
+ "At least one of add_label_ids or remove_label_ids must be provided."
4624
+ )
4625
+
4626
+ body = {}
4627
+ if add_label_ids:
4628
+ body["addLabelIds"] = add_label_ids
4629
+ if remove_label_ids:
4630
+ body["removeLabelIds"] = remove_label_ids
4631
+
4632
+ await asyncio.to_thread(
4633
+ service.users().messages().modify(userId="me", id=message_id, body=body).execute
4634
+ )
4635
+
4636
+ actions = []
4637
+ if add_label_ids:
4638
+ actions.append(f"Added labels: {', '.join(add_label_ids)}")
4639
+ if remove_label_ids:
4640
+ actions.append(f"Removed labels: {', '.join(remove_label_ids)}")
4641
+
4642
+ return f"Message labels updated successfully!\nMessage ID: {message_id}\n{'; '.join(actions)}"
4643
+
4644
+
4645
+ async def _verify_batch_label_changes(
4646
+ service,
4647
+ message_ids: List[str],
4648
+ add_label_ids: Optional[List[str]],
4649
+ remove_label_ids: Optional[List[str]],
4650
+ ) -> Dict[str, str]:
4651
+ """Read the messages back to see which requested label changes actually landed.
4652
+
4653
+ ``users.messages.batchModify`` answers ``204 No Content`` and silently
4654
+ ignores IDs it does not recognise, so its own response cannot distinguish a
4655
+ sweep that changed everything from one that changed nothing. This re-reads
4656
+ each message with ``format="minimal"`` (``labelIds`` only) and classifies it.
4657
+
4658
+ Returns a per-ID status: ``applied`` (end state matches the request),
4659
+ ``not_applied`` (message exists, labels do not match), ``unresolved``
4660
+ (the ID does not currently resolve to a message), or ``unverified`` (the
4661
+ read-back itself failed, so nothing can be claimed either way).
4662
+ """
4663
+ wanted = set(add_label_ids or ())
4664
+ unwanted = set(remove_label_ids or ())
4665
+ statuses: Dict[str, str] = {}
4666
+
4667
+ for chunk_start in range(0, len(message_ids), GMAIL_BATCH_SIZE):
4668
+ chunk_ids = message_ids[chunk_start : chunk_start + GMAIL_BATCH_SIZE]
4669
+ results: Dict[str, Dict] = {}
4670
+ batch_completed = False
4671
+
4672
+ def _batch_callback(request_id, response, exception):
4673
+ results[request_id] = {"data": response, "error": exception}
4674
+
4675
+ try:
4676
+ batch = service.new_batch_http_request(callback=_batch_callback)
4677
+ for mid in chunk_ids:
4678
+ batch.add(
4679
+ service.users()
4680
+ .messages()
4681
+ .get(userId="me", id=mid, format="minimal"),
4682
+ request_id=mid,
4683
+ )
4684
+ await asyncio.to_thread(batch.execute)
4685
+ batch_completed = True
4686
+ except Exception as batch_error:
4687
+ # Same fallback the read tools use: sequential reads with a small
4688
+ # delay, to avoid exhausting connections when the batch endpoint is
4689
+ # unavailable.
4690
+ logger.warning(
4691
+ f"[batch_modify_gmail_message_labels] Verification batch failed, "
4692
+ f"falling back to sequential reads: {batch_error}"
4693
+ )
4694
+ for mid in chunk_ids:
4695
+ mid_result, data, error = await _fetch_with_retry(
4696
+ build_request=lambda mid=mid: (
4697
+ service.users()
4698
+ .messages()
4699
+ .get(userId="me", id=mid, format="minimal")
4700
+ ),
4701
+ item_id=mid,
4702
+ item_label="message",
4703
+ log_prefix="batch_modify_gmail_message_labels",
4704
+ )
4705
+ results[mid_result] = {"data": data, "error": error}
4706
+ await asyncio.sleep(GMAIL_REQUEST_DELAY)
4707
+
4708
+ retryable_ids = (
4709
+ _retryable_result_ids(results, chunk_ids) if batch_completed else []
4710
+ )
4711
+ if retryable_ids:
4712
+ logger.warning(
4713
+ f"[batch_modify_gmail_message_labels] "
4714
+ f"{len(retryable_ids)}/{len(chunk_ids)} verification reads failed "
4715
+ f"with retryable errors; re-fetching: {retryable_ids}"
4716
+ )
4717
+ await asyncio.sleep(GMAIL_RATE_LIMIT_BACKOFF)
4718
+ for mid in retryable_ids:
4719
+ mid_result, data, error = await _fetch_with_retry(
4720
+ build_request=lambda mid=mid: (
4721
+ service.users()
4722
+ .messages()
4723
+ .get(userId="me", id=mid, format="minimal")
4724
+ ),
4725
+ item_id=mid,
4726
+ item_label="message",
4727
+ log_prefix="batch_modify_gmail_message_labels",
4728
+ )
4729
+ results[mid_result] = {"data": data, "error": error}
4730
+ await asyncio.sleep(GMAIL_REQUEST_DELAY)
4731
+
4732
+ for mid in chunk_ids:
4733
+ entry = results.get(mid)
4734
+ if not entry or (entry.get("data") is None and entry.get("error") is None):
4735
+ statuses[mid] = "unverified"
4736
+ continue
4737
+ error = entry.get("error")
4738
+ if error is not None:
4739
+ statuses[mid] = (
4740
+ "unresolved" if _http_error_status(error) == 404 else "unverified"
4741
+ )
4742
+ continue
4743
+ labels = set((entry.get("data") or {}).get("labelIds") or ())
4744
+ statuses[mid] = (
4745
+ "applied"
4746
+ if wanted <= labels and not (unwanted & labels)
4747
+ else "not_applied"
4748
+ )
4749
+
4750
+ return statuses
4751
+
4752
+
4753
+ @server.tool(
4754
+ title="Batch Modify Gmail Message Labels",
4755
+ annotations=ToolAnnotations(
4756
+ readOnlyHint=False,
4757
+ destructiveHint=True,
4758
+ idempotentHint=False,
4759
+ openWorldHint=True,
4760
+ ),
4761
+ )
4762
+ @handle_http_errors("batch_modify_gmail_message_labels", service_type="gmail")
4763
+ @require_google_service("gmail", GMAIL_MODIFY_SCOPE)
4764
+ async def batch_modify_gmail_message_labels(
4765
+ service,
4766
+ user_google_email: str,
4767
+ message_ids: _OptionalLabelIdList = None,
4768
+ add_label_ids: _OptionalLabelIdList = None,
4769
+ remove_label_ids: _OptionalLabelIdList = None,
4770
+ verify: bool = True,
4771
+ thread_ids: _OptionalLabelIdList = None,
4772
+ ) -> str:
4773
+ """
4774
+ Adds or removes labels on many Gmail messages, or on every message of whole
4775
+ conversations via thread_ids.
4776
+
4777
+ message_ids are sent in one users.messages.batchModify call (Gmail accepts
4778
+ up to 1000 ids per call). That endpoint returns no per-message result and
4779
+ silently ignores ids it does not recognise, so by default the messages are
4780
+ read back afterwards to report which ids actually changed.
4781
+
4782
+ thread_ids are modified one at a time with users.threads.modify, e.g.
4783
+ archive a conversation with remove_label_ids=["INBOX"] or mark it read with
4784
+ remove_label_ids=["UNREAD"]. Each thread reports its own outcome.
4785
+ message_ids and thread_ids can be combined; at least one is required, as is
4786
+ at least one of add_label_ids or remove_label_ids.
4787
+
4788
+ Args:
4789
+ user_google_email (str): The user's Google email address. Required.
4790
+ message_ids (Optional[List[str]]): Message IDs to modify.
4791
+ add_label_ids (Optional[List[str]]): Label IDs to add.
4792
+ remove_label_ids (Optional[List[str]]): Label IDs to remove.
4793
+ verify (bool): Read message_ids back and report per-id outcomes, at the
4794
+ cost of one extra read per id (batched 25 at a time). Set False for
4795
+ very large sweeps where an unverified result is acceptable. Has no
4796
+ effect on thread_ids, which always report per thread.
4797
+ thread_ids (Optional[List[str]]): Thread (conversation) IDs to modify.
4798
+
4799
+ Returns:
4800
+ str: Per-id outcomes for message_ids (applied, unchanged, not found, or
4801
+ unverified) and per-thread outcomes for thread_ids.
4802
+ """
4803
+ logger.info(
4804
+ f"[batch_modify_gmail_message_labels] Invoked. Email: '{user_google_email}', Message IDs: '{message_ids}', Thread IDs: '{thread_ids}'"
4805
+ )
4806
+
4807
+ if not add_label_ids and not remove_label_ids:
4808
+ raise UserInputError(
4809
+ "At least one of add_label_ids or remove_label_ids must be provided."
4810
+ )
4811
+ if not message_ids and not thread_ids:
4812
+ raise UserInputError(
4813
+ "At least one of message_ids or thread_ids must be provided."
4814
+ )
4815
+
4816
+ actions = []
4817
+ if add_label_ids:
4818
+ actions.append(f"Added labels: {', '.join(add_label_ids)}")
4819
+ if remove_label_ids:
4820
+ actions.append(f"Removed labels: {', '.join(remove_label_ids)}")
4821
+ action_summary = "; ".join(actions)
4822
+
4823
+ thread_report = ""
4824
+ if thread_ids:
4825
+ outcomes = await modify_gmail_thread_labels(
4826
+ service, thread_ids, add_label_ids, remove_label_ids
4827
+ )
4828
+ thread_report = format_thread_label_outcomes(
4829
+ thread_ids, outcomes, action_summary
4830
+ )
4831
+ if not message_ids:
4832
+ return thread_report
4833
+
4834
+ body = {"ids": message_ids}
4835
+ if add_label_ids:
4836
+ body["addLabelIds"] = add_label_ids
4837
+ if remove_label_ids:
4838
+ body["removeLabelIds"] = remove_label_ids
4839
+
4840
+ try:
4841
+ await asyncio.to_thread(
4842
+ service.users().messages().batchModify(userId="me", body=body).execute
4843
+ )
4844
+ except Exception as error:
4845
+ if not thread_report:
4846
+ raise
4847
+ raise ToolExecutionError(
4848
+ f"Label change for message_ids failed: {error}\n\n"
4849
+ f"The thread_ids part was already processed:\n{thread_report}"
4850
+ ) from error
4851
+
4852
+ total = len(message_ids)
4853
+
4854
+ if not verify:
4855
+ return (
4856
+ f"Requested label changes for {total} message ID(s): {action_summary}\n"
4857
+ "NOT VERIFIED: Gmail's batchModify returns no per-message result and "
4858
+ "silently ignores IDs it does not recognise, so this records what was "
4859
+ "asked for, not what changed. Re-run with verify=True to confirm."
4860
+ ) + (f"\n\n{thread_report}" if thread_report else "")
4861
+
4862
+ statuses = await _verify_batch_label_changes(
4863
+ service, message_ids, add_label_ids, remove_label_ids
4864
+ )
4865
+ applied = [mid for mid in message_ids if statuses.get(mid) == "applied"]
4866
+ not_applied = [mid for mid in message_ids if statuses.get(mid) == "not_applied"]
4867
+ unresolved = [mid for mid in message_ids if statuses.get(mid) == "unresolved"]
4868
+ unverified = [mid for mid in message_ids if statuses.get(mid) == "unverified"]
4869
+
4870
+ lines = [
4871
+ f"Label changes for {total} message ID(s): {action_summary}",
4872
+ f"Applied: {len(applied)}/{total}",
4873
+ ]
4874
+ if unresolved:
4875
+ lines.append(
4876
+ f"No such message ({len(unresolved)}): {_format_id_list(unresolved)}\n"
4877
+ " These IDs do not currently resolve to messages in this mailbox, "
4878
+ "so the requested change could not be verified. One possible cause "
4879
+ "is passing a THREAD id where a MESSAGE id is required."
4880
+ )
4881
+ if not_applied:
4882
+ lines.append(
4883
+ f"Unchanged ({len(not_applied)}): {_format_id_list(not_applied)}\n"
4884
+ " These messages exist but their labels do not match the request."
4885
+ )
4886
+ if unverified:
4887
+ lines.append(
4888
+ f"Could not verify ({len(unverified)}): {_format_id_list(unverified)}\n"
4889
+ " The read-back failed; the change may or may not have been applied."
4890
+ )
4891
+
4892
+ if thread_report:
4893
+ lines.append("")
4894
+ lines.append(thread_report)
4895
+ return "\n".join(lines)