@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,1323 @@
1
+ """
2
+ Google Calendar Helper Functions
3
+
4
+ This module provides utility functions for validating Google Calendar tool
5
+ inputs, building event request payloads, and formatting event data for display.
6
+ """
7
+
8
+ import asyncio
9
+ import contextlib
10
+ import datetime
11
+ import json
12
+ import logging
13
+ import re
14
+ import uuid
15
+ from dataclasses import dataclass
16
+ from typing import Any, Dict, List, Optional, Union
17
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
18
+
19
+ import pytz
20
+ from googleapiclient.discovery import Resource, build
21
+ from googleapiclient.errors import HttpError
22
+
23
+ from core.utils import UserInputError
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+ _WEEKDAYS = (
28
+ "Monday",
29
+ "Tuesday",
30
+ "Wednesday",
31
+ "Thursday",
32
+ "Friday",
33
+ "Saturday",
34
+ "Sunday",
35
+ )
36
+
37
+ _RFC3339_DATETIME = re.compile(
38
+ r"\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d"
39
+ r"(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)"
40
+ )
41
+ _GOOGLE_ALL_DAY_DATE = re.compile(r"\d{4}-\d{2}-\d{2}")
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class EventBoundary:
46
+ """One resolved start/end boundary of a Google Calendar event.
47
+
48
+ Google returns each boundary as ``{"dateTime": ..., "timeZone": ...}`` (or
49
+ ``{"date": ...}`` for all-day events), and those two fields do NOT agree by
50
+ default. ``events.list`` / ``events.get`` normalize every ``dateTime`` in the
51
+ response into ONE zone -- the ``timeZone`` request parameter, defaulting to the
52
+ calendar's own -- while leaving each boundary's IANA ``timeZone`` untouched. An
53
+ arrival authored as 17:50 Europe/Amsterdam therefore comes back as
54
+ ``2026-08-21T18:50:00+03:00`` on an Asia/Jerusalem calendar: the correct instant,
55
+ rendered in a zone the author never chose.
56
+
57
+ This type resolves the pair into a single tz-aware moment expressed in the
58
+ boundary's OWN zone, so cross-timezone events (flights, above all) report the
59
+ wall-clock and offset that were actually authored. The instant is unchanged;
60
+ only its presentation is corrected.
61
+ """
62
+
63
+ raw: str
64
+ """The dateTime/date string exactly as Google returned it."""
65
+
66
+ local_date: datetime.date
67
+ """Calendar date at this boundary, in its own zone when that zone was resolved."""
68
+
69
+ moment: Optional[datetime.datetime] = None
70
+ """Timezone-aware instant, converted when :attr:`timezone_resolved` is true."""
71
+
72
+ timezone: Optional[str] = None
73
+ """IANA zone name exactly as Google supplied it, even if locally unresolvable."""
74
+
75
+ timezone_resolved: bool = False
76
+ """Whether :attr:`moment` was converted into :attr:`timezone`."""
77
+
78
+ is_all_day: bool = False
79
+ is_exclusive_end: bool = False
80
+
81
+ @property
82
+ def iso_weekday(self) -> int:
83
+ return self.local_date.isoweekday()
84
+
85
+ def isoformat(self) -> str:
86
+ """RFC3339 stamp in this boundary's own zone.
87
+
88
+ Falls back to :attr:`raw` verbatim when no IANA zone was resolved. Without a
89
+ resolved zone there is no reliable wall-clock conversion to make, so the value
90
+ Google returned is the best timestamp -- and echoing it unchanged preserves its
91
+ exact spelling (``Z`` rather than ``+00:00``, offset-less values untouched).
92
+ """
93
+ if self.moment is None or not self.timezone_resolved:
94
+ return self.raw
95
+ return self.moment.isoformat()
96
+
97
+ def render(self) -> str:
98
+ """Human-readable boundary: local stamp plus zone and weekday evidence."""
99
+ evidence: List[str] = []
100
+ if self.timezone:
101
+ evidence.append(self.timezone)
102
+ evidence.append(f"weekday: {_WEEKDAYS[self.iso_weekday - 1]}")
103
+ evidence.append(f"ISO weekday: {self.iso_weekday}")
104
+ if self.is_exclusive_end:
105
+ evidence.append("exclusive all-day end")
106
+ return f"{self.isoformat()} [{'; '.join(evidence)}]"
107
+
108
+
109
+ def _resolve_zone(boundary: Dict[str, Any]) -> Optional[ZoneInfo]:
110
+ """Return the boundary's IANA zone, or None when absent or unrecognized."""
111
+ tz_name = boundary.get("timeZone")
112
+ if not isinstance(tz_name, str) or not tz_name:
113
+ return None
114
+ try:
115
+ return ZoneInfo(tz_name)
116
+ except (ZoneInfoNotFoundError, ValueError):
117
+ logger.debug(
118
+ "Unrecognized event timeZone %r; keeping returned offset.", tz_name
119
+ )
120
+ return None
121
+
122
+
123
+ def parse_event_boundary(item: Dict[str, Any], field: str) -> Optional[EventBoundary]:
124
+ """Parse one raw Google event boundary into an :class:`EventBoundary`.
125
+
126
+ Returns None when the payload is malformed or shaped unexpectedly, so callers
127
+ can fall back to echoing the raw value rather than guessing at a time.
128
+ """
129
+ boundary = item.get(field)
130
+ if not isinstance(boundary, dict):
131
+ return None
132
+ value = boundary.get("dateTime", boundary.get("date"))
133
+ if not isinstance(value, str):
134
+ return None
135
+
136
+ if "dateTime" in boundary:
137
+ if _RFC3339_DATETIME.fullmatch(value) is None:
138
+ return None
139
+ try:
140
+ normalized = f"{value[:-1]}+00:00" if value.endswith("Z") else value
141
+ moment = datetime.datetime.fromisoformat(normalized)
142
+ except ValueError:
143
+ return None
144
+ if moment.tzinfo is None:
145
+ return None
146
+ zone = _resolve_zone(boundary)
147
+ if zone is not None:
148
+ moment = moment.astimezone(zone)
149
+ tz_name = boundary.get("timeZone")
150
+ timezone = tz_name if isinstance(tz_name, str) and tz_name else None
151
+ return EventBoundary(
152
+ raw=value,
153
+ local_date=moment.date(),
154
+ moment=moment,
155
+ timezone=timezone,
156
+ timezone_resolved=zone is not None,
157
+ )
158
+
159
+ if _GOOGLE_ALL_DAY_DATE.fullmatch(value) is None:
160
+ return None
161
+ try:
162
+ local_date = datetime.date.fromisoformat(value)
163
+ except ValueError:
164
+ return None
165
+ return EventBoundary(
166
+ raw=value,
167
+ local_date=local_date,
168
+ is_all_day=True,
169
+ is_exclusive_end=(field == "end"),
170
+ )
171
+
172
+
173
+ def _format_event_time(item: Dict[str, Any], field: str) -> str:
174
+ """Format one event boundary, including sparse cancelled exceptions.
175
+
176
+ Google may return cancelled instances of an unexpanded recurring series as
177
+ tombstones with no ``start`` or ``end``. Their ``originalStartTime`` is the
178
+ occurrence they exclude, so use it as the start boundary instead of
179
+ failing or presenting an unexplained ``None``.
180
+ """
181
+ boundary_field = field
182
+ if (
183
+ not isinstance(item.get(field), dict)
184
+ and field == "start"
185
+ and item.get("status") == "cancelled"
186
+ ):
187
+ boundary_field = "originalStartTime"
188
+
189
+ parsed = parse_event_boundary(item, boundary_field)
190
+ if parsed is None:
191
+ boundary = item.get(boundary_field)
192
+ if isinstance(boundary, dict):
193
+ value = boundary.get("dateTime", boundary.get("date"))
194
+ return value if isinstance(value, str) else "Unavailable"
195
+ return "Unavailable"
196
+ return parsed.render()
197
+
198
+
199
+ def _get_meeting_link(item: Dict[str, Any]) -> str:
200
+ """Extract video meeting link from event conference data or hangoutLink."""
201
+ conference_data = item.get("conferenceData")
202
+ if conference_data and "entryPoints" in conference_data:
203
+ for entry_point in conference_data["entryPoints"]:
204
+ if entry_point.get("entryPointType") == "video":
205
+ uri = entry_point.get("uri", "")
206
+ if uri:
207
+ return uri
208
+ hangout_link = item.get("hangoutLink", "")
209
+ if hangout_link:
210
+ return hangout_link
211
+ return ""
212
+
213
+
214
+ def _format_attendee_details(
215
+ attendees: List[Dict[str, Any]], indent: str = " "
216
+ ) -> str:
217
+ """
218
+ Format attendee details including response status, organizer and optional
219
+ flags, and the attendee's RSVP note (the API's "comment" field).
220
+
221
+ Example output format:
222
+ " user@example.com: accepted
223
+ manager@example.com: declined (organizer)
224
+ optional-person@example.com: tentative (optional)
225
+ guest@example.com: declined (note: "Can't make it")"
226
+
227
+ Args:
228
+ attendees: List of attendee dictionaries from Google Calendar API
229
+ indent: Indentation to use for newline-separated attendees (default: " ")
230
+
231
+ Returns:
232
+ Formatted string with attendee details, or "None" if no attendees
233
+ """
234
+ if not attendees:
235
+ return "None"
236
+
237
+ attendee_details_list = []
238
+ for a in attendees:
239
+ email = a.get("email", "unknown")
240
+ response_status = a.get("responseStatus", "unknown")
241
+ optional = a.get("optional", False)
242
+ organizer = a.get("organizer", False)
243
+
244
+ detail_parts = [f"{email}: {response_status}"]
245
+ if organizer:
246
+ detail_parts.append("(organizer)")
247
+ if optional:
248
+ detail_parts.append("(optional)")
249
+ note = " ".join((a.get("comment") or "").split())
250
+ if note:
251
+ detail_parts.append(f"(note: {json.dumps(note, ensure_ascii=False)})")
252
+
253
+ attendee_details_list.append(" ".join(detail_parts))
254
+
255
+ return f"\n{indent}".join(attendee_details_list)
256
+
257
+
258
+ def _format_attachment_details(
259
+ attachments: List[Dict[str, Any]], indent: str = " "
260
+ ) -> str:
261
+ """
262
+ Format attachment details including file information.
263
+
264
+
265
+ Args:
266
+ attachments: List of attachment dictionaries from Google Calendar API
267
+ indent: Indentation to use for newline-separated attachments (default: " ")
268
+
269
+ Returns:
270
+ Formatted string with attachment details, or "None" if no attachments
271
+ """
272
+ if not attachments:
273
+ return "None"
274
+
275
+ attachment_details_list = []
276
+ for att in attachments:
277
+ title = att.get("title", "Untitled")
278
+ file_url = att.get("fileUrl", "No URL")
279
+ file_id = att.get("fileId", "No ID")
280
+ mime_type = att.get("mimeType", "Unknown")
281
+
282
+ attachment_info = (
283
+ f"{title}\n"
284
+ f"{indent}File URL: {file_url}\n"
285
+ f"{indent}File ID: {file_id}\n"
286
+ f"{indent}MIME Type: {mime_type}"
287
+ )
288
+ attachment_details_list.append(attachment_info)
289
+
290
+ return f"\n{indent}".join(attachment_details_list)
291
+
292
+
293
+ def _format_person(person: Optional[Dict[str, Any]]) -> Optional[str]:
294
+ """Format a Google Calendar person dict (creator or organizer) for display."""
295
+ if not person:
296
+ return None
297
+ name = (person.get("displayName") or "").strip()
298
+ email = (person.get("email") or "").strip()
299
+ if name and email:
300
+ return f"{name} <{email}>"
301
+ if name:
302
+ return name
303
+ if email:
304
+ return f"<{email}>"
305
+ return None
306
+
307
+
308
+ def _format_event_detail_lines(
309
+ item: Dict[str, Any],
310
+ prefix: str,
311
+ indent: str,
312
+ include_attachments: bool = False,
313
+ ) -> str:
314
+ """
315
+ Format the shared body of a detailed event, one field per line.
316
+
317
+ Both detailed output paths in `get_events` — the single-event lookup and the
318
+ ranged listing — emit the same fields and differ only in line prefix and
319
+ continuation indent. Formatting them here is what keeps the two in step.
320
+
321
+ Args:
322
+ item: Event resource from the Google Calendar API
323
+ prefix: Prefix for each field line (e.g. "- " or " ")
324
+ indent: Continuation indent for multi-line values (attendees, attachments)
325
+ include_attachments: Whether to append attachment details
326
+
327
+ Returns:
328
+ Newline-terminated block of detail lines
329
+ """
330
+ lines = [
331
+ f"{prefix}Description: {item.get('description', 'No Description')}",
332
+ f"{prefix}Location: {item.get('location', 'No Location')}",
333
+ f"{prefix}Color ID: {item.get('colorId', 'None')}",
334
+ ]
335
+
336
+ recurring_event_id = item.get("recurringEventId")
337
+ if recurring_event_id:
338
+ lines.append(f"{prefix}Recurring Event ID: {recurring_event_id}")
339
+
340
+ original_start_time = item.get("originalStartTime")
341
+ is_exception = item.get("status") != "confirmed" or not item.get("start")
342
+ if original_start_time and is_exception:
343
+ lines.append(f"{prefix}Original Start Time: {json.dumps(original_start_time)}")
344
+
345
+ recurrence = item.get("recurrence")
346
+ if recurrence:
347
+ # Keep the individual RFC5545 lines lossless and machine-readable. A
348
+ # recurring master may carry RRULE plus RDATE/EXDATE entries whose
349
+ # commas and semicolons make a hand-joined string ambiguous.
350
+ lines.append(f"{prefix}Recurrence: {json.dumps(recurrence)}")
351
+
352
+ # eventType and status are omitted at their API defaults, so an ordinary
353
+ # one-off meeting stays as compact as it was before these fields existed.
354
+ event_type = item.get("eventType")
355
+ if event_type and event_type != "default":
356
+ lines.append(f"{prefix}Event Type: {event_type}")
357
+
358
+ status = item.get("status")
359
+ if status and status != "confirmed":
360
+ lines.append(f"{prefix}Status: {status}")
361
+
362
+ reminders = item.get("reminders") or {}
363
+ if not reminders.get("useDefault", True):
364
+ lines.append(f"{prefix}Reminders: {json.dumps(reminders.get('overrides', []))}")
365
+
366
+ visibility = item.get("visibility")
367
+ if visibility and visibility != "default":
368
+ lines.append(f"{prefix}Visibility: {visibility}")
369
+
370
+ transparency = item.get("transparency")
371
+ if transparency and transparency != "opaque":
372
+ lines.append(f"{prefix}Transparency: {transparency}")
373
+
374
+ creator_str = _format_person(item.get("creator"))
375
+ if creator_str:
376
+ lines.append(f"{prefix}Creator: {creator_str}")
377
+
378
+ organizer_str = _format_person(item.get("organizer"))
379
+ if organizer_str:
380
+ lines.append(f"{prefix}Organizer: {organizer_str}")
381
+
382
+ meeting_link = _get_meeting_link(item)
383
+ if meeting_link:
384
+ lines.append(f"{prefix}Meeting Link: {meeting_link}")
385
+
386
+ attendees = item.get("attendees", [])
387
+ attendee_emails = (
388
+ ", ".join([a.get("email", "") for a in attendees]) if attendees else "None"
389
+ )
390
+ lines.append(f"{prefix}Attendees: {attendee_emails}")
391
+ lines.append(
392
+ f"{prefix}Attendee Details: {_format_attendee_details(attendees, indent=indent)}"
393
+ )
394
+
395
+ if include_attachments:
396
+ attachment_details = _format_attachment_details(
397
+ item.get("attachments", []), indent=indent
398
+ )
399
+ lines.append(f"{prefix}Attachments: {attachment_details}")
400
+
401
+ return "".join(f"{line}\n" for line in lines)
402
+
403
+
404
+ def _parse_reminders_json(
405
+ reminders_input: Optional[Union[str, List[Dict[str, Any]]]], function_name: str
406
+ ) -> List[Dict[str, Any]]:
407
+ """
408
+ Parse reminders from JSON string or list object and validate them.
409
+
410
+ Args:
411
+ reminders_input: JSON string containing reminder objects or list of reminder objects
412
+ function_name: Name of calling function for logging
413
+
414
+ Returns:
415
+ List of validated reminder objects
416
+ """
417
+ if not reminders_input:
418
+ return []
419
+
420
+ # Handle both string (JSON) and list inputs
421
+ if isinstance(reminders_input, str):
422
+ try:
423
+ reminders = json.loads(reminders_input)
424
+ if not isinstance(reminders, list):
425
+ logger.warning(
426
+ f"[{function_name}] Reminders must be a JSON array, got {type(reminders).__name__}"
427
+ )
428
+ return []
429
+ except json.JSONDecodeError as e:
430
+ logger.warning(f"[{function_name}] Invalid JSON for reminders: {e}")
431
+ return []
432
+ elif isinstance(reminders_input, list):
433
+ reminders = reminders_input
434
+ else:
435
+ logger.warning(
436
+ f"[{function_name}] Reminders must be a JSON string or list, got {type(reminders_input).__name__}"
437
+ )
438
+ return []
439
+
440
+ # Validate reminders
441
+ if len(reminders) > 5:
442
+ logger.warning(
443
+ f"[{function_name}] More than 5 reminders provided, truncating to first 5"
444
+ )
445
+ reminders = reminders[:5]
446
+
447
+ validated_reminders = []
448
+ for reminder in reminders:
449
+ if (
450
+ not isinstance(reminder, dict)
451
+ or "method" not in reminder
452
+ or "minutes" not in reminder
453
+ ):
454
+ logger.warning(
455
+ f"[{function_name}] Invalid reminder format: {reminder}, skipping"
456
+ )
457
+ continue
458
+
459
+ method = reminder["method"].lower()
460
+ if method not in ["popup", "email"]:
461
+ logger.warning(
462
+ f"[{function_name}] Invalid reminder method '{method}', must be 'popup' or 'email', skipping"
463
+ )
464
+ continue
465
+
466
+ minutes = reminder["minutes"]
467
+ if not isinstance(minutes, int) or minutes < 0 or minutes > 40320:
468
+ logger.warning(
469
+ f"[{function_name}] Invalid reminder minutes '{minutes}', must be integer 0-40320, skipping"
470
+ )
471
+ continue
472
+
473
+ validated_reminders.append({"method": method, "minutes": minutes})
474
+
475
+ return validated_reminders
476
+
477
+
478
+ def _apply_transparency_if_valid(
479
+ event_body: Dict[str, Any],
480
+ transparency: Optional[str],
481
+ function_name: str,
482
+ ) -> None:
483
+ """
484
+ Apply transparency to the event body if the provided value is valid.
485
+
486
+ Args:
487
+ event_body: Event payload being constructed.
488
+ transparency: Provided transparency value.
489
+ function_name: Name of the calling function for logging context.
490
+ """
491
+ if transparency is None:
492
+ return
493
+
494
+ valid_transparency_values = ["opaque", "transparent"]
495
+ if transparency in valid_transparency_values:
496
+ event_body["transparency"] = transparency
497
+ logger.info(f"[{function_name}] Set transparency to '{transparency}'")
498
+ else:
499
+ logger.warning(
500
+ f"[{function_name}] Invalid transparency value '{transparency}', must be 'opaque' or 'transparent', skipping"
501
+ )
502
+
503
+
504
+ def _apply_visibility_if_valid(
505
+ event_body: Dict[str, Any],
506
+ visibility: Optional[str],
507
+ function_name: str,
508
+ ) -> None:
509
+ """
510
+ Apply visibility to the event body if the provided value is valid.
511
+
512
+ Args:
513
+ event_body: Event payload being constructed.
514
+ visibility: Provided visibility value.
515
+ function_name: Name of the calling function for logging context.
516
+ """
517
+ if visibility is None:
518
+ return
519
+
520
+ valid_visibility_values = ["default", "public", "private", "confidential"]
521
+ if visibility in valid_visibility_values:
522
+ event_body["visibility"] = visibility
523
+ logger.info(f"[{function_name}] Set visibility to '{visibility}'")
524
+ else:
525
+ logger.warning(
526
+ f"[{function_name}] Invalid visibility value '{visibility}', must be 'default', 'public', 'private', or 'confidential', skipping"
527
+ )
528
+
529
+
530
+ _EVENT_COLOR_IDS = {
531
+ "lavender": "1",
532
+ "sage": "2",
533
+ "grape": "3",
534
+ "flamingo": "4",
535
+ "banana": "5",
536
+ "tangerine": "6",
537
+ "peacock": "7",
538
+ "graphite": "8",
539
+ "blueberry": "9",
540
+ "basil": "10",
541
+ "tomato": "11",
542
+ }
543
+
544
+
545
+ def _resolve_color_id(color: Optional[str]) -> Optional[str]:
546
+ """Resolve an event color name (e.g. "tomato") or ID ("1"-"11") to its colorId."""
547
+ if color is None:
548
+ return None
549
+ normalized = color.strip().lower()
550
+ color_id = _EVENT_COLOR_IDS.get(normalized, normalized)
551
+ if color_id not in _EVENT_COLOR_IDS.values():
552
+ options = ", ".join(f"{name} ({cid})" for name, cid in _EVENT_COLOR_IDS.items())
553
+ raise UserInputError(f"Invalid color_id '{color}'. Must be one of: {options}")
554
+ return color_id
555
+
556
+
557
+ _VALID_AUTO_DECLINE_MODES = {
558
+ "declineAllConflictingInvitations",
559
+ "declineOnlyNewConflictingInvitations",
560
+ "declineNone",
561
+ }
562
+
563
+ _VALID_FOCUS_TIME_CHAT_STATUSES = {
564
+ "available",
565
+ "doNotDisturb",
566
+ }
567
+
568
+
569
+ def _validate_auto_decline_mode(mode: Optional[str], function_name: str) -> str:
570
+ """Validate and return auto decline mode, defaulting to declineAllConflictingInvitations.
571
+
572
+ Args:
573
+ mode: The auto decline mode to validate.
574
+ function_name: Name of the calling function for error context.
575
+
576
+ Returns:
577
+ A valid auto decline mode string.
578
+ """
579
+ if mode is None:
580
+ return "declineAllConflictingInvitations"
581
+ if mode not in _VALID_AUTO_DECLINE_MODES:
582
+ raise UserInputError(
583
+ f"[{function_name}] Invalid auto_decline_mode '{mode}'. "
584
+ f"Must be one of: {', '.join(sorted(_VALID_AUTO_DECLINE_MODES))}"
585
+ )
586
+ return mode
587
+
588
+
589
+ def _preserve_existing_fields(
590
+ event_body: Dict[str, Any],
591
+ existing_event: Dict[str, Any],
592
+ field_mappings: Dict[str, Any],
593
+ ) -> None:
594
+ """
595
+ Helper function to preserve existing event fields when not explicitly provided.
596
+
597
+ Args:
598
+ event_body: The event body being built for the API call
599
+ existing_event: The existing event data from the API
600
+ field_mappings: Dict mapping field names to their new values (None means preserve existing)
601
+ """
602
+ for field_name, new_value in field_mappings.items():
603
+ if new_value is None and field_name in existing_event:
604
+ event_body[field_name] = existing_event[field_name]
605
+ logger.info(f"[modify_event] Preserving existing {field_name}")
606
+ elif new_value is not None:
607
+ event_body[field_name] = new_value
608
+
609
+
610
+ def _naive_to_utc_rfc3339(
611
+ naive: datetime.datetime, param_name: str, timezone: Optional[str]
612
+ ) -> str:
613
+ """Read a naive datetime as wall time in ``timezone`` (UTC if unset) as RFC3339 UTC."""
614
+ tz = pytz.utc
615
+ if timezone:
616
+ try:
617
+ tz = pytz.timezone(timezone)
618
+ except pytz.exceptions.UnknownTimeZoneError:
619
+ logger.warning(
620
+ f"Could not apply timezone '{timezone}', falling back to UTC for {param_name}"
621
+ )
622
+ try:
623
+ aware = tz.localize(naive).astimezone(datetime.timezone.utc)
624
+ except OverflowError:
625
+ logger.warning(
626
+ f"Could not apply timezone '{timezone}' to {param_name} '{naive.isoformat()}', falling back to UTC"
627
+ )
628
+ aware = naive.replace(tzinfo=datetime.timezone.utc)
629
+ return aware.isoformat().replace("+00:00", "Z")
630
+
631
+
632
+ def _correct_time_format_for_api(
633
+ time_str: Optional[str], param_name: str, timezone: Optional[str] = None
634
+ ) -> Optional[str]:
635
+ """Normalize a time string into RFC3339 format suitable for the Google Calendar API."""
636
+ if not time_str:
637
+ return None
638
+
639
+ # Defensive normalization: some LLM-driven MCP clients double-encode JSON
640
+ # string arguments, passing values like '"2026-05-15T00:00:00Z"'
641
+ time_str = time_str.strip().strip('"').strip("'").strip()
642
+ if not time_str or time_str.lower() in ("null", "none"):
643
+ return None
644
+
645
+ logger.info(
646
+ f"_correct_time_format_for_api: Processing {param_name} with value '{time_str}', timezone: '{timezone}'"
647
+ )
648
+
649
+ # Handle date-only format (YYYY-MM-DD)
650
+ if len(time_str) == 10 and time_str.count("-") == 2:
651
+ try:
652
+ naive = datetime.datetime.strptime(time_str, "%Y-%m-%d")
653
+ except ValueError:
654
+ logger.warning(
655
+ f"{param_name} '{time_str}' looks like a date but is not valid YYYY-MM-DD. Using as is."
656
+ )
657
+ return time_str
658
+ formatted = _naive_to_utc_rfc3339(naive, param_name, timezone)
659
+ logger.info(
660
+ f"Formatting date-only {param_name} '{time_str}' to RFC3339: '{formatted}'"
661
+ )
662
+ return formatted
663
+
664
+ # Handle offset-free date-time format (YYYY-MM-DDTHH:MM:SS)
665
+ if (
666
+ len(time_str) == 19
667
+ and time_str[10] == "T"
668
+ and time_str.count(":") == 2
669
+ and not (
670
+ time_str.endswith("Z") or ("+" in time_str[10:]) or ("-" in time_str[10:])
671
+ )
672
+ ):
673
+ try:
674
+ naive = datetime.datetime.strptime(time_str, "%Y-%m-%dT%H:%M:%S")
675
+ except ValueError:
676
+ logger.warning(
677
+ f"{param_name} '{time_str}' looks like it needs 'Z' but is not valid YYYY-MM-DDTHH:MM:SS. Using as is."
678
+ )
679
+ return time_str
680
+ formatted = _naive_to_utc_rfc3339(naive, param_name, timezone)
681
+ logger.info(f"Formatting {param_name} '{time_str}' to RFC3339: '{formatted}'")
682
+ return formatted
683
+
684
+ # If it already has timezone info or doesn't match our patterns, return as is
685
+ logger.info(f"{param_name} '{time_str}' doesn't need formatting, using as is.")
686
+ return time_str
687
+
688
+
689
+ def _build_time_boundary(time_value: str, timezone: Optional[str]) -> Dict[str, str]:
690
+ """Build one Google ``start``/``end`` boundary from a time string and its zone.
691
+
692
+ Each boundary carries its OWN ``timeZone``, which is what makes a cross-timezone
693
+ event expressible: a flight departing 13:45 Asia/Jerusalem and landing 17:50
694
+ Europe/Amsterdam is one event whose two ends are authored in different zones.
695
+ Forcing a single zone on both ends silently rewrites one of them -- the arrival
696
+ above becomes 17:50 Israel time, an hour off, with no error raised.
697
+ """
698
+ if "T" not in time_value:
699
+ try:
700
+ if _GOOGLE_ALL_DAY_DATE.fullmatch(time_value) is None:
701
+ raise ValueError(time_value)
702
+ datetime.date.fromisoformat(time_value)
703
+ except ValueError as exc:
704
+ raise UserInputError(
705
+ f"Invalid all-day date {time_value!r}. Use YYYY-MM-DD, for example "
706
+ "'2026-11-10'."
707
+ ) from exc
708
+ return {"date": time_value}
709
+ try:
710
+ parsed = datetime.datetime.fromisoformat(re.sub(r"[zZ]$", "+00:00", time_value))
711
+ except ValueError as exc:
712
+ raise UserInputError(
713
+ f"Invalid RFC3339 timestamp {time_value!r}. Use a value such as "
714
+ "'2026-09-17T11:35:00' or '2026-09-17T11:35:00-07:00'."
715
+ ) from exc
716
+ # `is None` rather than falsy: an explicitly empty zone is an invalid value, not
717
+ # an omitted one, and must reach validation below instead of being treated as
718
+ # "no zone given".
719
+ if timezone is None:
720
+ return {"dateTime": time_value}
721
+ # Reject an unresolvable zone here rather than stripping the caller's offset and
722
+ # forwarding a name Google will refuse. Falling back to the offset instead would
723
+ # be worse than erroring: it silently discards the zone the caller asked for and
724
+ # books the event somewhere else.
725
+ try:
726
+ zone = ZoneInfo(timezone)
727
+ except (ZoneInfoNotFoundError, ValueError) as exc:
728
+ raise UserInputError(
729
+ f"Unrecognized IANA timezone {timezone!r}. Use a zone name such as "
730
+ "'America/New_York' or 'Europe/Amsterdam'."
731
+ ) from exc
732
+ if parsed.tzinfo is not None:
733
+ time_value = parsed.astimezone(zone).isoformat()
734
+ return {"dateTime": time_value, "timeZone": timezone}
735
+
736
+
737
+ def _saved_event_times(event: Dict[str, Any]) -> str:
738
+ start = parse_event_boundary(event, "start")
739
+ end = parse_event_boundary(event, "end")
740
+ lines = [
741
+ f"Saved start: {_format_event_time(event, 'start')}",
742
+ f"Saved end: {_format_event_time(event, 'end')}",
743
+ ]
744
+ if start and end:
745
+ if start.moment and end.moment:
746
+ # Subtraction in a shared ZoneInfo uses wall time across DST changes.
747
+ utc = datetime.timezone.utc
748
+ seconds = round(
749
+ (
750
+ end.moment.astimezone(utc) - start.moment.astimezone(utc)
751
+ ).total_seconds()
752
+ )
753
+ lines.append(
754
+ f"Elapsed duration: {seconds / 60:.15g} minutes ({seconds} seconds)"
755
+ )
756
+ elif start.is_all_day and end.is_all_day:
757
+ days = (end.local_date - start.local_date).days
758
+ unit = "day" if days == 1 else "days"
759
+ lines.append(f"All-day span: {days} {unit} (end date exclusive)")
760
+ return "\n" + "\n".join(lines)
761
+
762
+
763
+ # Friendly provider name -> conferenceSolution display name for the addOn block.
764
+ _CONFERENCE_SOLUTION_NAMES = {
765
+ "zoom": "Zoom Meeting",
766
+ "webex": "Webex",
767
+ "teams": "Microsoft Teams",
768
+ "microsoft teams": "Microsoft Teams",
769
+ }
770
+
771
+
772
+ def _build_addon_conference_data(
773
+ provider: str,
774
+ uri: str,
775
+ passcode: Optional[str] = None,
776
+ conference_id: Optional[str] = None,
777
+ ) -> Dict[str, Any]:
778
+ """Build a Google Calendar ``conferenceData`` block for a third-party add-on.
779
+
780
+ Used for providers (Zoom, Webex, Teams, ...) attached via the
781
+ ``conferenceSolution.key.type = "addOn"`` mechanism rather than the native
782
+ ``hangoutsMeet`` create request.
783
+ """
784
+ provider = provider.strip()
785
+ uri = uri.strip()
786
+ name = _CONFERENCE_SOLUTION_NAMES.get(provider.lower(), provider)
787
+ entry_point: Dict[str, Any] = {
788
+ "entryPointType": "video",
789
+ "uri": uri,
790
+ "label": name,
791
+ }
792
+ if passcode:
793
+ entry_point["passcode"] = passcode
794
+ conference_data: Dict[str, Any] = {
795
+ "conferenceSolution": {"key": {"type": "addOn"}, "name": name},
796
+ "entryPoints": [entry_point],
797
+ }
798
+ if conference_id:
799
+ conference_data["conferenceId"] = conference_id
800
+ return conference_data
801
+
802
+
803
+ def _resolve_conference_data(
804
+ conference_data: Optional[Dict[str, Any]],
805
+ conference_provider: Optional[str],
806
+ conference_uri: Optional[str],
807
+ conference_passcode: Optional[str],
808
+ conference_id: Optional[str],
809
+ add_google_meet: Optional[bool],
810
+ ) -> Optional[Dict[str, Any]]:
811
+ """Resolve the conferencing inputs into a single ``conferenceData`` dict.
812
+
813
+ Accepts either a raw ``conference_data`` pass-through payload or the
814
+ higher-level ``conference_provider``/``conference_uri`` helper params, and
815
+ validates that they are not combined with each other or with
816
+ ``add_google_meet``. Returns the resolved payload, or ``None`` if no
817
+ third-party conference was requested.
818
+ """
819
+ helper_used = any(
820
+ [conference_provider, conference_uri, conference_passcode, conference_id]
821
+ )
822
+ if conference_data is not None and helper_used:
823
+ raise UserInputError(
824
+ "Provide either conference_data (raw payload) or the "
825
+ "conference_provider/conference_uri helper params, not both."
826
+ )
827
+
828
+ resolved = conference_data
829
+ if helper_used:
830
+ provider = (conference_provider or "").strip()
831
+ uri = (conference_uri or "").strip()
832
+ if not (provider and uri):
833
+ raise UserInputError(
834
+ "conference_provider and conference_uri are both required to "
835
+ "attach a third-party conference."
836
+ )
837
+ resolved = _build_addon_conference_data(
838
+ provider, uri, conference_passcode, conference_id
839
+ )
840
+
841
+ if resolved is not None and add_google_meet:
842
+ raise UserInputError(
843
+ "Cannot attach a third-party conference and add_google_meet on the "
844
+ "same event; choose one."
845
+ )
846
+ return resolved
847
+
848
+
849
+ async def _build_attachment_entries(
850
+ service,
851
+ attachments: Union[str, List[str]],
852
+ log_prefix: str,
853
+ ) -> List[Dict[str, str]]:
854
+ """
855
+ Resolve Drive file IDs or URLs into Calendar attachment objects.
856
+
857
+ Falls back to a generic title and MIME type when Drive metadata cannot be
858
+ read, which happens when the calendar credentials carry no Drive scope.
859
+ """
860
+ if isinstance(attachments, str):
861
+ attachments = [a.strip() for a in attachments.split(",") if a.strip()]
862
+
863
+ entries: List[Dict[str, str]] = []
864
+ drive_service = None
865
+ try:
866
+ try:
867
+ drive_service = service._http and build("drive", "v3", http=service._http)
868
+ except Exception as e:
869
+ logger.warning(f"Could not build Drive service for MIME type lookup: {e}")
870
+
871
+ for att in attachments:
872
+ if att.startswith("https://"):
873
+ # Match /d/<id>, /file/d/<id>, ?id=<id>
874
+ match = re.search(r"(?:/d/|/file/d/|id=)([\w-]+)", att)
875
+ file_id = match.group(1) if match else None
876
+ logger.info(
877
+ f"[{log_prefix}] Extracted file_id '{file_id}' from attachment URL"
878
+ )
879
+ else:
880
+ file_id = att
881
+ logger.info(
882
+ f"[{log_prefix}] Using direct file_id '{file_id}' for attachment"
883
+ )
884
+ if not file_id:
885
+ continue
886
+
887
+ mime_type = "application/vnd.google-apps.drive-sdk"
888
+ title = "Drive Attachment"
889
+ # Try to get the actual MIME type and filename from Drive
890
+ if drive_service:
891
+ try:
892
+ file_metadata = await asyncio.to_thread(
893
+ lambda: (
894
+ drive_service.files()
895
+ .get(
896
+ fileId=file_id,
897
+ fields="mimeType,name",
898
+ supportsAllDrives=True,
899
+ )
900
+ .execute()
901
+ )
902
+ )
903
+ mime_type = file_metadata.get("mimeType", mime_type)
904
+ filename = file_metadata.get("name")
905
+ if filename:
906
+ title = filename
907
+ logger.info(
908
+ f"[{log_prefix}] Using filename '{filename}' as attachment title"
909
+ )
910
+ else:
911
+ logger.info(
912
+ f"[{log_prefix}] No filename found, using generic title"
913
+ )
914
+ except Exception as e:
915
+ logger.warning(f"Could not fetch metadata for file {file_id}: {e}")
916
+
917
+ entries.append(
918
+ {
919
+ "fileUrl": f"https://drive.google.com/open?id={file_id}",
920
+ "title": title,
921
+ "mimeType": mime_type,
922
+ }
923
+ )
924
+ finally:
925
+ if drive_service:
926
+ drive_service.close()
927
+ return entries
928
+
929
+
930
+ _SERIES_SERVER_FIELDS = frozenset(
931
+ {
932
+ "created",
933
+ "creator",
934
+ "etag",
935
+ "hangoutLink",
936
+ "htmlLink",
937
+ "iCalUID",
938
+ "id",
939
+ "organizer",
940
+ "sequence",
941
+ "updated",
942
+ }
943
+ )
944
+
945
+
946
+ def _truncate_recurrence(recurrence: List[str], split_at: EventBoundary) -> List[str]:
947
+ """Return ``recurrence`` with every RRULE ending just before ``split_at``."""
948
+ if split_at.is_all_day:
949
+ until = (split_at.local_date - datetime.timedelta(days=1)).strftime("%Y%m%d")
950
+ else:
951
+ last_kept = split_at.moment - datetime.timedelta(seconds=1)
952
+ until = last_kept.astimezone(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
953
+ truncated = []
954
+ for line in recurrence:
955
+ if line.upper().startswith("RRULE:"):
956
+ parts = [
957
+ part
958
+ for part in line[len("RRULE:") :].split(";")
959
+ if not part.upper().startswith(("COUNT=", "UNTIL="))
960
+ ]
961
+ line = f"RRULE:{';'.join(parts + [f'UNTIL={until}'])}"
962
+ truncated.append(line)
963
+ return truncated
964
+
965
+
966
+ async def _split_recurring_event(
967
+ service,
968
+ calendar_id: str,
969
+ instance_id: str,
970
+ changes: Dict[str, Any],
971
+ send_updates: str,
972
+ ) -> Dict[str, Any]:
973
+ """Apply ``changes`` to a recurring instance and all later ones; return the new series.
974
+
975
+ Ends the original series before the instance, then inserts a copy starting at it,
976
+ restoring the original recurrence if the insert fails.
977
+ """
978
+ events = service.events()
979
+ instance = await asyncio.to_thread(
980
+ lambda: events.get(calendarId=calendar_id, eventId=instance_id).execute()
981
+ )
982
+ series_id = instance.get("recurringEventId")
983
+ split_at = parse_event_boundary(instance, "originalStartTime")
984
+ if not series_id or split_at is None or instance.get("status") == "cancelled":
985
+ raise UserInputError(
986
+ f"Event '{instance_id}' is not an active instance of a recurring series. "
987
+ "Pass a recurring instance ID from get_events."
988
+ )
989
+ series = await asyncio.to_thread(
990
+ lambda: events.get(calendarId=calendar_id, eventId=series_id).execute()
991
+ )
992
+ first = parse_event_boundary(series, "start")
993
+ last = parse_event_boundary(series, "end")
994
+ if first is None or last is None:
995
+ raise Exception(f"Series '{series_id}' has no readable start or end.")
996
+ if (first.moment or first.local_date) == (split_at.moment or split_at.local_date):
997
+ raise UserInputError(
998
+ f"Event '{instance_id}' is the first instance of its series. Update the "
999
+ f"series '{series_id}' directly instead."
1000
+ )
1001
+ recurrence = series.get("recurrence", [])
1002
+ upper_rules = [r.upper() for r in recurrence]
1003
+ if any(r.startswith("RDATE") for r in upper_rules):
1004
+ raise UserInputError(
1005
+ "This series has RDATE entries, which cannot be split. Update the series "
1006
+ "directly instead."
1007
+ )
1008
+ if "recurrence" not in changes and any("COUNT=" in r for r in upper_rules):
1009
+ raise UserInputError(
1010
+ "This series ends after a fixed COUNT. Pass recurrence for the new series."
1011
+ )
1012
+
1013
+ if split_at.is_all_day:
1014
+ span = last.local_date - first.local_date
1015
+ end = {"date": (split_at.local_date + span).isoformat()}
1016
+ else:
1017
+ span = last.moment - first.moment
1018
+ end = {**series["end"], "dateTime": (split_at.moment + span).isoformat()}
1019
+ new_series = {k: v for k, v in series.items() if k not in _SERIES_SERVER_FIELDS}
1020
+ new_series.update(
1021
+ {
1022
+ "id": uuid.uuid4().hex,
1023
+ "start": instance["originalStartTime"],
1024
+ "end": end,
1025
+ **changes,
1026
+ }
1027
+ )
1028
+ for key in ("start", "end"):
1029
+ zone = series[key].get("timeZone")
1030
+ if zone and "dateTime" in new_series[key]:
1031
+ new_series[key] = {"timeZone": zone, **new_series[key]}
1032
+
1033
+ def set_recurrence(rules: List[str]) -> None:
1034
+ events.patch(
1035
+ calendarId=calendar_id,
1036
+ eventId=series_id,
1037
+ body={"recurrence": rules},
1038
+ sendUpdates=send_updates,
1039
+ ).execute()
1040
+
1041
+ await asyncio.to_thread(set_recurrence, _truncate_recurrence(recurrence, split_at))
1042
+ try:
1043
+ return await asyncio.to_thread(
1044
+ lambda: events.insert(
1045
+ calendarId=calendar_id,
1046
+ body=new_series,
1047
+ supportsAttachments=True,
1048
+ conferenceDataVersion=1,
1049
+ sendUpdates=send_updates,
1050
+ ).execute()
1051
+ )
1052
+ except Exception:
1053
+ with contextlib.suppress(Exception):
1054
+ return await asyncio.to_thread(
1055
+ lambda: events.get(
1056
+ calendarId=calendar_id, eventId=new_series["id"]
1057
+ ).execute()
1058
+ )
1059
+ try:
1060
+ await asyncio.to_thread(set_recurrence, recurrence)
1061
+ except Exception as restore_error:
1062
+ raise Exception(
1063
+ f"Could not create the new series or restore series '{series_id}', "
1064
+ f"which now ends before instance '{instance_id}'. Restore its "
1065
+ f"recurrence to {recurrence}."
1066
+ ) from restore_error
1067
+ raise
1068
+
1069
+
1070
+ def _normalize_attendees(
1071
+ attendees: Optional[List[Union[str, Dict[str, Any]]]],
1072
+ ) -> Optional[List[Dict[str, Any]]]:
1073
+ """
1074
+ Normalize attendees input to list of attendee objects.
1075
+
1076
+ Accepts either:
1077
+ - List of email strings: ["user@example.com", "other@example.com"]
1078
+ - List of attendee objects: [{"email": "user@example.com", "responseStatus": "accepted"}]
1079
+ - Mixed list of both formats
1080
+
1081
+ Returns list of attendee dicts with at minimum 'email' key.
1082
+
1083
+ Raises:
1084
+ UserInputError: If an attendee is neither an email string nor a
1085
+ dict with an 'email' key, so it is never silently left off the event.
1086
+ """
1087
+ if attendees is None:
1088
+ return None
1089
+
1090
+ normalized = []
1091
+ for att in attendees:
1092
+ if isinstance(att, str):
1093
+ normalized.append({"email": att})
1094
+ elif isinstance(att, dict) and "email" in att:
1095
+ normalized.append(att)
1096
+ else:
1097
+ raise UserInputError(
1098
+ "Each attendee must be an email string or an object with an "
1099
+ f"'email' key; got {type(att).__name__}"
1100
+ )
1101
+ return normalized if normalized else None
1102
+
1103
+
1104
+ def _status_event_time_entry(
1105
+ time_str: str, event_label: str, timezone: Optional[str] = None
1106
+ ) -> Dict[str, str]:
1107
+ """Build a start/end dict for an Out of Office or Focus Time event.
1108
+
1109
+ Google Calendar API requires dateTime (not date) for these event types, so a
1110
+ date-only string (YYYY-MM-DD) converts to midnight on that day. Callers pass
1111
+ an exclusive end date, so the same conversion serves both boundaries.
1112
+ """
1113
+ if "T" not in time_str:
1114
+ time_str = f"{time_str}T00:00:00"
1115
+ logger.info(
1116
+ f"[status_event_time_entry] Converted date-only to dateTime: {time_str}"
1117
+ )
1118
+
1119
+ has_explicit_offset = time_str.endswith("Z") or bool(
1120
+ re.search(r"[+-]\d{2}:\d{2}$", time_str)
1121
+ )
1122
+ if not has_explicit_offset and not timezone:
1123
+ raise UserInputError(
1124
+ f"{event_label} events require either a timezone parameter or a "
1125
+ "start/end timestamp with an explicit UTC offset."
1126
+ )
1127
+
1128
+ entry: Dict[str, str] = {"dateTime": time_str}
1129
+ if timezone:
1130
+ entry["timeZone"] = timezone
1131
+ return entry
1132
+
1133
+
1134
+ def _validate_chat_status(
1135
+ chat_status: Optional[str], function_name: str
1136
+ ) -> Optional[str]:
1137
+ """Validate chat status for Focus Time events."""
1138
+ if chat_status is None:
1139
+ return None
1140
+ if chat_status not in _VALID_FOCUS_TIME_CHAT_STATUSES:
1141
+ raise UserInputError(
1142
+ f"[{function_name}] Invalid chat_status '{chat_status}'. "
1143
+ f"Must be one of: {', '.join(sorted(_VALID_FOCUS_TIME_CHAT_STATUSES))}"
1144
+ )
1145
+ return chat_status
1146
+
1147
+
1148
+ _ACL_ROLES = {
1149
+ role.lower(): role
1150
+ for role in (
1151
+ "none",
1152
+ "freeBusyReader",
1153
+ "reader",
1154
+ "writerWithoutPrivateAccess",
1155
+ "writer",
1156
+ "owner",
1157
+ )
1158
+ }
1159
+ _ACL_SCOPE_TYPES = ("default", "user", "group", "domain")
1160
+
1161
+
1162
+ def _resolve_acl_role(role: Optional[str], action: str) -> str:
1163
+ """Return the canonical Calendar ACL role for a case-insensitive role name."""
1164
+ if not role or not role.strip():
1165
+ raise UserInputError(f"role is required for {action} action")
1166
+ canonical = _ACL_ROLES.get(role.strip().lower())
1167
+ if canonical is None:
1168
+ raise UserInputError(
1169
+ f"Invalid role '{role}'. Must be one of: {', '.join(_ACL_ROLES.values())}"
1170
+ )
1171
+ return canonical
1172
+
1173
+
1174
+ def _build_acl_scope(scope_type: str, scope_value: Optional[str]) -> Dict[str, str]:
1175
+ """Build the ACL scope for a user, group, domain or public (default) grant."""
1176
+ scope_type = scope_type.strip().lower()
1177
+ if scope_type not in _ACL_SCOPE_TYPES:
1178
+ raise UserInputError(
1179
+ f"Invalid scope_type '{scope_type}'. Must be one of: {', '.join(_ACL_SCOPE_TYPES)}"
1180
+ )
1181
+ value = (scope_value or "").strip()
1182
+ if scope_type == "default":
1183
+ if value:
1184
+ raise UserInputError("scope_value must be omitted for scope_type 'default'")
1185
+ return {"type": "default"}
1186
+ if not value:
1187
+ raise UserInputError(f"scope_value is required for scope_type '{scope_type}'")
1188
+ return {"type": scope_type, "value": value}
1189
+
1190
+
1191
+ def _format_acl_rule(rule: Dict[str, Any]) -> str:
1192
+ """Format one ACL rule as a single readable line."""
1193
+ scope = rule.get("scope", {})
1194
+ target = " ".join(filter(None, (scope.get("type"), scope.get("value"))))
1195
+ return f"- {rule.get('role')}: {target} (Rule ID: {rule.get('id')})"
1196
+
1197
+
1198
+ async def _move_event(
1199
+ service: Resource,
1200
+ calendar_id: str,
1201
+ event_id: str,
1202
+ destination_calendar_id: str,
1203
+ send_updates: str,
1204
+ ) -> str:
1205
+ """Move an event to another calendar and summarize the result."""
1206
+ event = await asyncio.to_thread(
1207
+ lambda: (
1208
+ service.events()
1209
+ .move(
1210
+ calendarId=calendar_id,
1211
+ eventId=event_id,
1212
+ destination=destination_calendar_id,
1213
+ sendUpdates=send_updates,
1214
+ )
1215
+ .execute()
1216
+ )
1217
+ )
1218
+ organizer = event.get("organizer", {}).get("email", destination_calendar_id)
1219
+ return (
1220
+ f"Moved event '{event.get('summary', 'No Title')}' (ID: {event.get('id', event_id)}) "
1221
+ f"from calendar '{calendar_id}' to '{organizer}'. "
1222
+ f"Link: {event.get('htmlLink', 'No link available')}"
1223
+ )
1224
+
1225
+
1226
+ async def _create_calendar(
1227
+ service,
1228
+ summary: Optional[str],
1229
+ description: Optional[str],
1230
+ timezone: Optional[str],
1231
+ ) -> str:
1232
+ """Create a secondary calendar and return its summary and ID."""
1233
+ if not summary:
1234
+ raise UserInputError("summary is required for create action")
1235
+ body: Dict[str, Any] = {"summary": summary}
1236
+ if description:
1237
+ body["description"] = description
1238
+ if timezone:
1239
+ body["timeZone"] = timezone
1240
+ result = await asyncio.to_thread(
1241
+ lambda: service.calendars().insert(body=body).execute()
1242
+ )
1243
+ return f"Created calendar '{result.get('summary', summary)}' (ID: {result['id']})"
1244
+
1245
+
1246
+ async def _manage_calendar_acl(
1247
+ service,
1248
+ user_google_email: str,
1249
+ action: str,
1250
+ calendar_id: str,
1251
+ role: Optional[str],
1252
+ scope_type: str,
1253
+ scope_value: Optional[str],
1254
+ rule_id: Optional[str],
1255
+ send_notifications: bool,
1256
+ page_token: Optional[str],
1257
+ ) -> str:
1258
+ """List, share, update or remove a calendar's sharing rules and summarize the result."""
1259
+ acl = service.acl()
1260
+
1261
+ if action == "list_sharing":
1262
+ params: Dict[str, Any] = {"calendarId": calendar_id}
1263
+ if page_token:
1264
+ params["pageToken"] = page_token
1265
+ response = await asyncio.to_thread(lambda: acl.list(**params).execute())
1266
+ rules = response.get("items", [])
1267
+ lines = [f"Found {len(rules)} sharing rules for calendar '{calendar_id}':"]
1268
+ lines.extend(_format_acl_rule(rule) for rule in rules)
1269
+ if response.get("nextPageToken"):
1270
+ lines.append(f"\nNext page token: {response['nextPageToken']}")
1271
+ return "\n".join(lines)
1272
+
1273
+ if action == "share":
1274
+ body = {
1275
+ "role": _resolve_acl_role(role, action),
1276
+ "scope": _build_acl_scope(scope_type, scope_value),
1277
+ }
1278
+ rule = await asyncio.to_thread(
1279
+ lambda: acl.insert(
1280
+ calendarId=calendar_id,
1281
+ body=body,
1282
+ sendNotifications=send_notifications,
1283
+ ).execute()
1284
+ )
1285
+ return f"Shared calendar '{calendar_id}':\n{_format_acl_rule(rule)}"
1286
+
1287
+ if action not in ("update_sharing", "unshare"):
1288
+ raise UserInputError(
1289
+ f"Invalid action '{action}'. Must be 'create', 'list_sharing', 'share', "
1290
+ "'update_sharing', or 'unshare'."
1291
+ )
1292
+ if not rule_id or not rule_id.strip():
1293
+ raise UserInputError(
1294
+ f"rule_id is required for {action} action. Use action 'list_sharing' to find it."
1295
+ )
1296
+ rule_id = rule_id.strip()
1297
+ owner = user_google_email.lower()
1298
+ if calendar_id.lower() in ("primary", owner) and rule_id.lower() == f"user:{owner}":
1299
+ raise UserInputError(
1300
+ f"Rule '{rule_id}' is the owner's access to their primary calendar and "
1301
+ "cannot be changed or removed."
1302
+ )
1303
+ if action == "update_sharing":
1304
+ request = acl.patch(
1305
+ calendarId=calendar_id,
1306
+ ruleId=rule_id,
1307
+ body={"role": _resolve_acl_role(role, action)},
1308
+ sendNotifications=send_notifications,
1309
+ )
1310
+ else:
1311
+ request = acl.delete(calendarId=calendar_id, ruleId=rule_id)
1312
+ try:
1313
+ rule = await asyncio.to_thread(request.execute)
1314
+ except HttpError as error:
1315
+ if error.resp.status == 404:
1316
+ raise UserInputError(
1317
+ f"No sharing rule '{rule_id}' found on calendar '{calendar_id}'. "
1318
+ "Use action 'list_sharing' to see rule IDs."
1319
+ ) from error
1320
+ raise
1321
+ if action == "update_sharing":
1322
+ return f"Updated sharing on calendar '{calendar_id}':\n{_format_acl_rule(rule)}"
1323
+ return f"Removed sharing rule '{rule_id}' from calendar '{calendar_id}'."