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

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 +28 -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,2252 @@
1
+ """
2
+ Google Calendar MCP Tools
3
+
4
+ This module provides MCP tools for interacting with Google Calendar API.
5
+ """
6
+
7
+ import datetime
8
+ import logging
9
+ import asyncio
10
+ import uuid
11
+ from typing import List, Optional, Dict, Any, Union
12
+
13
+ import pytz
14
+ from googleapiclient.errors import HttpError
15
+
16
+ from auth.service_decorator import require_google_service
17
+ from core.utils import handle_http_errors, StringList, StringOrDictList, UserInputError
18
+ from gcalendar.calendar_helpers import (
19
+ _apply_transparency_if_valid,
20
+ _apply_visibility_if_valid,
21
+ _build_attachment_entries,
22
+ _build_time_boundary,
23
+ _correct_time_format_for_api,
24
+ _create_calendar,
25
+ _format_event_detail_lines,
26
+ _format_event_time,
27
+ _get_meeting_link,
28
+ _manage_calendar_acl,
29
+ _move_event,
30
+ _normalize_attendees,
31
+ _parse_reminders_json,
32
+ _preserve_existing_fields,
33
+ _resolve_color_id,
34
+ _resolve_conference_data,
35
+ _saved_event_times,
36
+ _split_recurring_event,
37
+ _status_event_time_entry,
38
+ _validate_auto_decline_mode,
39
+ _validate_chat_status,
40
+ )
41
+
42
+ from mcp.types import ToolAnnotations
43
+
44
+ from core.server import server
45
+
46
+
47
+ # Configure module logger
48
+ logger = logging.getLogger(__name__)
49
+
50
+
51
+ @server.tool(
52
+ title="List Calendars",
53
+ annotations=ToolAnnotations(
54
+ readOnlyHint=True,
55
+ destructiveHint=False,
56
+ idempotentHint=True,
57
+ openWorldHint=True,
58
+ ),
59
+ )
60
+ @handle_http_errors("list_calendars", is_read_only=True, service_type="calendar")
61
+ @require_google_service("calendar", "calendar_read")
62
+ async def list_calendars(
63
+ service,
64
+ user_google_email: str,
65
+ max_results: Optional[int] = None,
66
+ page_token: Optional[str] = None,
67
+ ) -> str:
68
+ """
69
+ Retrieves a list of calendars accessible to the authenticated user.
70
+
71
+ Args:
72
+ user_google_email (str): The user's Google email address. Required.
73
+ max_results (Optional[int]): Maximum calendars to return in one page. Omit to use the API default.
74
+ page_token (Optional[str]): Token for the next page, taken from a previous response.
75
+
76
+ Returns:
77
+ str: A formatted list of the user's calendars (summary, ID, primary status, time zone).
78
+ When more calendars remain, a "Next page token" line is appended.
79
+ """
80
+ logger.info(f"[list_calendars] Invoked. Email: '{user_google_email}'")
81
+
82
+ params: Dict[str, Any] = {}
83
+ if max_results is not None:
84
+ params["maxResults"] = max_results
85
+ if page_token:
86
+ params["pageToken"] = page_token
87
+
88
+ calendar_list_response = await asyncio.to_thread(
89
+ lambda: service.calendarList().list(**params).execute()
90
+ )
91
+ items = calendar_list_response.get("items", [])
92
+ next_page_token = calendar_list_response.get("nextPageToken")
93
+ if not items:
94
+ if next_page_token:
95
+ return (
96
+ f"No calendars on this page for {user_google_email}, and more pages remain."
97
+ f"\nNext page token: {next_page_token}"
98
+ )
99
+ return f"No calendars found for {user_google_email}."
100
+
101
+ calendars_summary_list = []
102
+ for cal in items:
103
+ line = f'- "{cal.get("summary", "No Summary")}"{" (Primary)" if cal.get("primary") else ""} (ID: {cal["id"]})'
104
+ if cal.get("timeZone"):
105
+ line += f" (Time zone: {cal['timeZone']})"
106
+ calendars_summary_list.append(line)
107
+ text_output = (
108
+ f"Successfully listed {len(items)} calendars for {user_google_email}:\n"
109
+ + "\n".join(calendars_summary_list)
110
+ )
111
+ if next_page_token:
112
+ text_output += f"\n\nNext page token: {next_page_token}"
113
+ logger.info(f"Successfully listed {len(items)} calendars for {user_google_email}.")
114
+ return text_output
115
+
116
+
117
+ @server.tool(
118
+ title="Get Events",
119
+ annotations=ToolAnnotations(
120
+ readOnlyHint=True,
121
+ destructiveHint=False,
122
+ idempotentHint=True,
123
+ openWorldHint=True,
124
+ ),
125
+ )
126
+ @handle_http_errors("get_events", is_read_only=True, service_type="calendar")
127
+ @require_google_service("calendar", "calendar_read")
128
+ async def get_events(
129
+ service,
130
+ user_google_email: str,
131
+ calendar_id: str = "primary",
132
+ event_id: Optional[str] = None,
133
+ time_min: Optional[str] = None,
134
+ time_max: Optional[str] = None,
135
+ max_results: int = 25,
136
+ query: Optional[str] = None,
137
+ detailed: bool = False,
138
+ include_attachments: bool = False,
139
+ single_events: bool = True,
140
+ page_token: Optional[str] = None,
141
+ ) -> str:
142
+ """
143
+ Retrieves events from a specified Google Calendar. Can retrieve a single event by ID or multiple events within a time range.
144
+ You can also search for events by keyword by supplying the optional "query" param.
145
+
146
+ Args:
147
+ user_google_email (str): The user's Google email address. Required.
148
+ calendar_id (str): The ID of the calendar to query. Use 'primary' for the user's primary calendar. Defaults to 'primary'. Calendar IDs can be obtained using `list_calendars`.
149
+ event_id (Optional[str]): The ID of a specific event to retrieve. If provided, retrieves only this event and ignores time filtering parameters.
150
+ time_min (Optional[str]): The start of the time range (inclusive) in RFC3339 format (e.g., '2024-05-12T10:00:00Z' or '2024-05-12'). If omitted, defaults to the current time when single_events=True. It is omitted from unexpanded queries so recurring masters that began in the past but still have future occurrences remain discoverable. Ignored if event_id is provided.
151
+ time_max (Optional[str]): The end of the time range (exclusive) in RFC3339 format. If omitted, events starting from `time_min` onwards are considered (up to `max_results`). Ignored if event_id is provided.
152
+ max_results (int): The maximum number of events to return in one page. Defaults to 25. Ignored if event_id is provided.
153
+ page_token (Optional[str]): Token for the next page, taken from a previous response. When single_events=True, also pass the response's Pagination time_min as time_min, even if omitted on the first call. Keep all other query parameters unchanged. Ignored if event_id is provided.
154
+ query (Optional[str]): A keyword to search for within event fields (summary, description, location). Ignored if event_id is provided.
155
+ detailed (bool): Whether to return detailed event information including description, location, colour (colorId), attendees, and attendee details (response status, organizer, optional flags). Recurring instances also report the parent series ID needed to edit the whole series; recurring masters report their raw RFC5545 recurrence rules; and events that are not ordinary confirmed meetings report their event type (outOfOffice, workingLocation, focusTime) and status. Custom reminders (an empty list means none), non-default visibility and transparency are reported too; events using the calendar's default reminders omit the Reminders line. Defaults to False.
156
+ include_attachments (bool): Whether to include attachment information in detailed event output. When True, shows attachment details (fileId, fileUrl, mimeType, title) for events that have attachments. Only applies when detailed=True. Set this to True when you need to view or access files that have been attached to calendar events, such as meeting documents, presentations, or other shared files. Defaults to False.
157
+ single_events (bool): Whether to expand recurring series into individual instances. Defaults to True for backwards compatibility. Set to False with detailed=True to retrieve recurring master events and their exact RFC5545 recurrence rules instead of inferring cadence from expanded instances.
158
+
159
+ Returns:
160
+ str: A formatted list of events (summary, start and end times, link) within the specified range, or detailed information for a single event if event_id is provided. When more events remain beyond max_results, a "Next page token" line is appended.
161
+ """
162
+ logger.info(
163
+ f"[get_events] Raw parameters - event_id: '{event_id}', time_min: '{time_min}', time_max: '{time_max}', query_len={len(query) if query else 0}, detailed: {detailed}, include_attachments: {include_attachments}, single_events: {single_events}"
164
+ )
165
+
166
+ next_page_token: Optional[str] = None
167
+ pagination_info = ""
168
+
169
+ # Handle single event retrieval
170
+ if event_id:
171
+ logger.info(f"[get_events] Retrieving single event with ID: {event_id}")
172
+ event = await asyncio.to_thread(
173
+ lambda: (
174
+ service.events().get(calendarId=calendar_id, eventId=event_id).execute()
175
+ )
176
+ )
177
+ items = [event]
178
+ else:
179
+ # Handle multiple events retrieval with time filtering
180
+ # Normalize before validating: blank and null-like strings also default
181
+ # to "now", which would change the query between pages.
182
+ formatted_time_min = _correct_time_format_for_api(time_min, "time_min", None)
183
+ if page_token and formatted_time_min is None and single_events:
184
+ raise UserInputError(
185
+ "[get_events] page_token requires time_min. Pass the Pagination "
186
+ "time_min from the previous response to preserve the original range."
187
+ )
188
+
189
+ if formatted_time_min:
190
+ effective_time_min = formatted_time_min
191
+ elif single_events:
192
+ utc_now = datetime.datetime.now(datetime.timezone.utc)
193
+ effective_time_min = utc_now.isoformat().replace("+00:00", "Z")
194
+ else:
195
+ effective_time_min = None
196
+ if time_min is None:
197
+ if single_events:
198
+ logger.info(
199
+ f"time_min not provided, defaulting to current UTC time: {effective_time_min}"
200
+ )
201
+ else:
202
+ logger.info(
203
+ "time_min not provided for unexpanded events; omitting it so older recurring masters remain discoverable"
204
+ )
205
+ else:
206
+ logger.info(
207
+ f"time_min processing: original='{time_min}', formatted='{formatted_time_min}', effective='{effective_time_min}'"
208
+ )
209
+
210
+ effective_time_max = _correct_time_format_for_api(time_max, "time_max", None)
211
+ if time_max:
212
+ logger.info(
213
+ f"time_max processing: original='{time_max}', formatted='{effective_time_max}'"
214
+ )
215
+
216
+ logger.info(
217
+ f"[get_events] Final API parameters - calendarId: '{calendar_id}', timeMin: '{effective_time_min}', timeMax: '{effective_time_max}', maxResults: {max_results}, query_len={len(query) if query else 0}"
218
+ )
219
+
220
+ # Build the request parameters dynamically
221
+ request_params = {
222
+ "calendarId": calendar_id,
223
+ "timeMax": effective_time_max,
224
+ "maxResults": max_results,
225
+ "singleEvents": single_events,
226
+ }
227
+
228
+ if effective_time_min:
229
+ request_params["timeMin"] = effective_time_min
230
+
231
+ # The Calendar API only permits start-time ordering when recurring
232
+ # series are expanded. Unexpanded results retain the API's stable
233
+ # default ordering and expose the master event's recurrence array.
234
+ if single_events:
235
+ request_params["orderBy"] = "startTime"
236
+
237
+ if query:
238
+ request_params["q"] = query
239
+
240
+ if page_token:
241
+ request_params["pageToken"] = page_token
242
+
243
+ events_result = await asyncio.to_thread(
244
+ lambda: service.events().list(**request_params).execute()
245
+ )
246
+ items = events_result.get("items", [])
247
+ next_page_token = events_result.get("nextPageToken")
248
+ if next_page_token:
249
+ pagination_info = f"Next page token: {next_page_token}"
250
+ if effective_time_min:
251
+ pagination_info += f"\nPagination time_min: {effective_time_min}"
252
+ if not items:
253
+ if event_id:
254
+ return f"Event with ID '{event_id}' not found in calendar '{calendar_id}' for {user_google_email}."
255
+ elif next_page_token:
256
+ # The API can return an empty page with more pages behind it, so
257
+ # "no events" would be untrue here.
258
+ return (
259
+ f"No events on this page in calendar '{calendar_id}' for {user_google_email}"
260
+ f" for the specified time range, and more pages remain."
261
+ f"\n{pagination_info}"
262
+ )
263
+ else:
264
+ return f"No events found in calendar '{calendar_id}' for {user_google_email} for the specified time range."
265
+
266
+ # Handle returning detailed output for a single event when requested
267
+ if event_id and detailed:
268
+ item = items[0]
269
+ summary = item.get("summary", "No Title")
270
+ start = _format_event_time(item, "start")
271
+ end = _format_event_time(item, "end")
272
+ link = item.get("htmlLink", "No Link")
273
+
274
+ event_details = (
275
+ f"Event Details:\n- Title: {summary}\n- Starts: {start}\n- Ends: {end}\n"
276
+ )
277
+ event_details += _format_event_detail_lines(
278
+ item,
279
+ prefix="- ",
280
+ indent=" ",
281
+ include_attachments=include_attachments,
282
+ )
283
+ event_details += f"- Event ID: {event_id}\n- Link: {link}"
284
+ logger.info(
285
+ f"[get_events] Successfully retrieved detailed event {event_id} for {user_google_email}."
286
+ )
287
+ return event_details
288
+
289
+ # Handle multiple events or single event with basic output
290
+ event_details_list = []
291
+ for item in items:
292
+ summary = item.get("summary", "No Title")
293
+ start_time = _format_event_time(item, "start")
294
+ end_time = _format_event_time(item, "end")
295
+ link = item.get("htmlLink", "No Link")
296
+ item_event_id = item.get("id", "No ID")
297
+
298
+ if detailed:
299
+ # Add detailed information for multiple events
300
+ event_detail_parts = (
301
+ f'- "{summary}" (Starts: {start_time}, Ends: {end_time})\n'
302
+ + _format_event_detail_lines(
303
+ item,
304
+ prefix=" ",
305
+ indent=" ",
306
+ include_attachments=include_attachments,
307
+ )
308
+ + f" ID: {item_event_id} | Link: {link}"
309
+ )
310
+ event_details_list.append(event_detail_parts)
311
+ else:
312
+ # Basic output format
313
+ meeting_link = _get_meeting_link(item)
314
+ basic_line = f'- "{summary}" (Starts: {start_time}, Ends: {end_time})'
315
+ if item.get("status") == "cancelled":
316
+ basic_line += " Status: cancelled"
317
+ if meeting_link:
318
+ basic_line += f" Meeting: {meeting_link}"
319
+ basic_line += f" ID: {item_event_id} | Link: {link}"
320
+ event_details_list.append(basic_line)
321
+
322
+ if event_id:
323
+ # Single event basic output
324
+ text_output = (
325
+ f"Successfully retrieved event from calendar '{calendar_id}' for {user_google_email}:\n"
326
+ + "\n".join(event_details_list)
327
+ )
328
+ else:
329
+ # Multiple events output
330
+ text_output = (
331
+ f"Successfully retrieved {len(items)} events from calendar '{calendar_id}' for {user_google_email}:\n"
332
+ + "\n".join(event_details_list)
333
+ )
334
+ if next_page_token:
335
+ text_output += f"\n\n{pagination_info}"
336
+
337
+ logger.info(f"Successfully retrieved {len(items)} events for {user_google_email}.")
338
+ return text_output
339
+
340
+
341
+ # ---------------------------------------------------------------------------
342
+ # Internal implementation functions for event create/modify/delete.
343
+ # These are called by both the consolidated ``manage_event`` tool and the
344
+ # legacy single-action tools.
345
+ # ---------------------------------------------------------------------------
346
+
347
+
348
+ async def _create_event_impl(
349
+ service,
350
+ user_google_email: str,
351
+ summary: str,
352
+ start_time: str,
353
+ end_time: str,
354
+ calendar_id: str = "primary",
355
+ description: Optional[str] = None,
356
+ location: Optional[str] = None,
357
+ attendees: Optional[List[Union[str, Dict[str, Any]]]] = None,
358
+ timezone: Optional[str] = None,
359
+ attachments: Optional[List[str]] = None,
360
+ add_google_meet: bool = False,
361
+ conference_data: Optional[Dict[str, Any]] = None,
362
+ reminders: Optional[Union[str, List[Dict[str, Any]]]] = None,
363
+ use_default_reminders: bool = True,
364
+ transparency: Optional[str] = None,
365
+ visibility: Optional[str] = None,
366
+ color_id: Optional[str] = None,
367
+ recurrence: Optional[List[str]] = None,
368
+ guests_can_modify: Optional[bool] = None,
369
+ guests_can_invite_others: Optional[bool] = None,
370
+ guests_can_see_other_guests: Optional[bool] = None,
371
+ send_updates: str = "all",
372
+ *,
373
+ start_timezone: Optional[str] = None,
374
+ end_timezone: Optional[str] = None,
375
+ ) -> str:
376
+ """Internal implementation for creating a calendar event."""
377
+ logger.info(
378
+ f"[create_event] Invoked. Email: '{user_google_email}', summary_len={len(summary) if summary else 0}"
379
+ )
380
+ logger.debug(f"[create_event] Incoming attachments param: {attachments}")
381
+ # If attachments value is a string, split by comma and strip whitespace
382
+ if attachments and isinstance(attachments, str):
383
+ attachments = [a.strip() for a in attachments.split(",") if a.strip()]
384
+ logger.debug(
385
+ f"[create_event] Parsed attachments list from string: {attachments}"
386
+ )
387
+ # Each boundary resolves its own zone, falling back to the event-wide timezone.
388
+ event_body: Dict[str, Any] = {
389
+ "summary": summary,
390
+ "start": _build_time_boundary(
391
+ start_time, start_timezone if start_timezone is not None else timezone
392
+ ),
393
+ "end": _build_time_boundary(
394
+ end_time, end_timezone if end_timezone is not None else timezone
395
+ ),
396
+ }
397
+ if recurrence:
398
+ event_body["recurrence"] = recurrence
399
+ if location:
400
+ event_body["location"] = location
401
+ if description:
402
+ event_body["description"] = description
403
+ normalized_attendees = _normalize_attendees(attendees)
404
+ if normalized_attendees is not None:
405
+ event_body["attendees"] = normalized_attendees
406
+ if color_id is not None:
407
+ event_body["colorId"] = color_id
408
+
409
+ # Handle reminders
410
+ if reminders is not None or not use_default_reminders:
411
+ # If custom reminders are provided, automatically disable default reminders
412
+ effective_use_default = use_default_reminders and reminders is None
413
+
414
+ reminder_data = {"useDefault": effective_use_default}
415
+ if reminders is not None:
416
+ validated_reminders = _parse_reminders_json(reminders, "create_event")
417
+ if validated_reminders:
418
+ reminder_data["overrides"] = validated_reminders
419
+ logger.info(
420
+ f"[create_event] Added {len(validated_reminders)} custom reminders"
421
+ )
422
+ if use_default_reminders:
423
+ logger.info(
424
+ "[create_event] Custom reminders provided - disabling default reminders"
425
+ )
426
+
427
+ event_body["reminders"] = reminder_data
428
+
429
+ # Handle transparency validation
430
+ _apply_transparency_if_valid(event_body, transparency, "create_event")
431
+
432
+ # Handle visibility validation
433
+ _apply_visibility_if_valid(event_body, visibility, "create_event")
434
+
435
+ # Handle guest permissions
436
+ if guests_can_modify is not None:
437
+ event_body["guestsCanModify"] = guests_can_modify
438
+ logger.info(f"[create_event] Set guestsCanModify to {guests_can_modify}")
439
+ if guests_can_invite_others is not None:
440
+ event_body["guestsCanInviteOthers"] = guests_can_invite_others
441
+ logger.info(
442
+ f"[create_event] Set guestsCanInviteOthers to {guests_can_invite_others}"
443
+ )
444
+ if guests_can_see_other_guests is not None:
445
+ event_body["guestsCanSeeOtherGuests"] = guests_can_see_other_guests
446
+ logger.info(
447
+ f"[create_event] Set guestsCanSeeOtherGuests to {guests_can_see_other_guests}"
448
+ )
449
+
450
+ if add_google_meet:
451
+ request_id = str(uuid.uuid4())
452
+ event_body["conferenceData"] = {
453
+ "createRequest": {
454
+ "requestId": request_id,
455
+ "conferenceSolutionKey": {"type": "hangoutsMeet"},
456
+ }
457
+ }
458
+ logger.info(
459
+ f"[create_event] Adding Google Meet conference with request ID: {request_id}"
460
+ )
461
+ elif conference_data is not None:
462
+ event_body["conferenceData"] = conference_data
463
+ logger.info("[create_event] Attaching pre-generated conference data")
464
+
465
+ # conferenceDataVersion=1 is required whenever conferenceData is present,
466
+ # whether it's a native Meet create request or a pre-generated add-on payload.
467
+ conference_data_version = (
468
+ 1 if (add_google_meet or conference_data is not None) else 0
469
+ )
470
+
471
+ if attachments:
472
+ event_body["attachments"] = await _build_attachment_entries(
473
+ service, attachments, "create_event"
474
+ )
475
+ created_event = await asyncio.to_thread(
476
+ lambda: (
477
+ service.events()
478
+ .insert(
479
+ calendarId=calendar_id,
480
+ body=event_body,
481
+ supportsAttachments=True,
482
+ conferenceDataVersion=conference_data_version,
483
+ sendUpdates=send_updates,
484
+ )
485
+ .execute()
486
+ )
487
+ )
488
+ else:
489
+ created_event = await asyncio.to_thread(
490
+ lambda: (
491
+ service.events()
492
+ .insert(
493
+ calendarId=calendar_id,
494
+ body=event_body,
495
+ conferenceDataVersion=conference_data_version,
496
+ sendUpdates=send_updates,
497
+ )
498
+ .execute()
499
+ )
500
+ )
501
+ link = created_event.get("htmlLink", "No link available")
502
+ confirmation_message = f"Successfully created event '{created_event.get('summary', summary)}' for {user_google_email}. Link: {link}"
503
+
504
+ confirmation_message += _saved_event_times(created_event)
505
+
506
+ # Surface the conferencing link (native Meet or third-party add-on) if present
507
+ if add_google_meet or conference_data is not None:
508
+ meeting_link = _get_meeting_link(created_event)
509
+ if meeting_link:
510
+ label = "Google Meet" if add_google_meet else "Conference"
511
+ confirmation_message += f" {label}: {meeting_link}"
512
+
513
+ logger.info(
514
+ f"Event created successfully for {user_google_email}. ID: {created_event.get('id')}, Link: {link}"
515
+ )
516
+ return confirmation_message
517
+
518
+
519
+ async def _modify_event_impl(
520
+ service,
521
+ user_google_email: str,
522
+ event_id: str,
523
+ calendar_id: str = "primary",
524
+ summary: Optional[str] = None,
525
+ start_time: Optional[str] = None,
526
+ end_time: Optional[str] = None,
527
+ description: Optional[str] = None,
528
+ location: Optional[str] = None,
529
+ attendees: Optional[List[Union[str, Dict[str, Any]]]] = None,
530
+ timezone: Optional[str] = None,
531
+ add_google_meet: Optional[bool] = None,
532
+ conference_data: Optional[Dict[str, Any]] = None,
533
+ reminders: Optional[Union[str, List[Dict[str, Any]]]] = None,
534
+ use_default_reminders: Optional[bool] = None,
535
+ transparency: Optional[str] = None,
536
+ visibility: Optional[str] = None,
537
+ color_id: Optional[str] = None,
538
+ recurrence: Optional[List[str]] = None,
539
+ guests_can_modify: Optional[bool] = None,
540
+ guests_can_invite_others: Optional[bool] = None,
541
+ guests_can_see_other_guests: Optional[bool] = None,
542
+ attachments: Optional[Union[str, List[str]]] = None,
543
+ send_updates: str = "all",
544
+ *,
545
+ start_timezone: Optional[str] = None,
546
+ end_timezone: Optional[str] = None,
547
+ this_and_following: bool = False,
548
+ ) -> str:
549
+ """Internal implementation for modifying a calendar event."""
550
+ logger.info(
551
+ f"[modify_event] Invoked. Email: '{user_google_email}', Event ID: {event_id}"
552
+ )
553
+
554
+ # Build the event body with only the fields that are provided
555
+ event_body: Dict[str, Any] = {}
556
+ if summary is not None:
557
+ event_body["summary"] = summary
558
+ if start_time is not None:
559
+ event_body["start"] = _build_time_boundary(
560
+ start_time, start_timezone if start_timezone is not None else timezone
561
+ )
562
+ if end_time is not None:
563
+ event_body["end"] = _build_time_boundary(
564
+ end_time, end_timezone if end_timezone is not None else timezone
565
+ )
566
+ if description is not None:
567
+ event_body["description"] = description
568
+ if location is not None:
569
+ event_body["location"] = location
570
+
571
+ # Normalize attendees - accepts both email strings and full attendee objects
572
+ normalized_attendees = _normalize_attendees(attendees)
573
+ if normalized_attendees is not None:
574
+ event_body["attendees"] = normalized_attendees
575
+
576
+ if color_id is not None:
577
+ event_body["colorId"] = color_id
578
+ if recurrence is not None:
579
+ event_body["recurrence"] = recurrence
580
+
581
+ # Handle reminders
582
+ if reminders is not None or use_default_reminders is not None:
583
+ reminder_data = {}
584
+ if use_default_reminders is not None:
585
+ reminder_data["useDefault"] = use_default_reminders
586
+ else:
587
+ # Preserve existing event's useDefault value if not explicitly specified
588
+ try:
589
+ existing_event = await asyncio.to_thread(
590
+ service.events()
591
+ .get(calendarId=calendar_id, eventId=event_id)
592
+ .execute
593
+ )
594
+ reminder_data["useDefault"] = existing_event.get("reminders", {}).get(
595
+ "useDefault", True
596
+ )
597
+ except Exception as e:
598
+ logger.warning(
599
+ f"[modify_event] Could not fetch existing event for reminders: {e}"
600
+ )
601
+ reminder_data["useDefault"] = (
602
+ True # Fallback to True if unable to fetch
603
+ )
604
+
605
+ # If custom reminders are provided, automatically disable default reminders
606
+ if reminders is not None:
607
+ if reminder_data.get("useDefault", False):
608
+ reminder_data["useDefault"] = False
609
+ logger.info(
610
+ "[modify_event] Custom reminders provided - disabling default reminders"
611
+ )
612
+
613
+ validated_reminders = _parse_reminders_json(reminders, "modify_event")
614
+ if reminders and not validated_reminders:
615
+ logger.warning(
616
+ "[modify_event] Reminders provided but failed validation. No custom reminders will be set."
617
+ )
618
+ elif validated_reminders:
619
+ reminder_data["overrides"] = validated_reminders
620
+ logger.info(
621
+ f"[modify_event] Updated reminders with {len(validated_reminders)} custom reminders"
622
+ )
623
+
624
+ event_body["reminders"] = reminder_data
625
+
626
+ # Handle transparency validation
627
+ _apply_transparency_if_valid(event_body, transparency, "modify_event")
628
+
629
+ # Handle visibility validation
630
+ _apply_visibility_if_valid(event_body, visibility, "modify_event")
631
+
632
+ # Handle guest permissions
633
+ if guests_can_modify is not None:
634
+ event_body["guestsCanModify"] = guests_can_modify
635
+ logger.info(f"[modify_event] Set guestsCanModify to {guests_can_modify}")
636
+ if guests_can_invite_others is not None:
637
+ event_body["guestsCanInviteOthers"] = guests_can_invite_others
638
+ logger.info(
639
+ f"[modify_event] Set guestsCanInviteOthers to {guests_can_invite_others}"
640
+ )
641
+ if guests_can_see_other_guests is not None:
642
+ event_body["guestsCanSeeOtherGuests"] = guests_can_see_other_guests
643
+ logger.info(
644
+ f"[modify_event] Set guestsCanSeeOtherGuests to {guests_can_see_other_guests}"
645
+ )
646
+
647
+ # Handle conference data
648
+ if conference_data is not None:
649
+ # Attach a pre-generated third-party conference (Zoom/Webex/Teams add-on)
650
+ event_body["conferenceData"] = conference_data
651
+ logger.info("[modify_event] Attaching pre-generated conference data")
652
+ elif add_google_meet is not None:
653
+ if add_google_meet:
654
+ request_id = str(uuid.uuid4())
655
+ event_body["conferenceData"] = {
656
+ "createRequest": {
657
+ "requestId": request_id,
658
+ "conferenceSolutionKey": {"type": "hangoutsMeet"},
659
+ }
660
+ }
661
+ logger.info(
662
+ f"[modify_event] Adding Google Meet conference with request ID: {request_id}"
663
+ )
664
+ else:
665
+ # Remove Google Meet by setting conferenceData to JSON null.
666
+ event_body["conferenceData"] = None
667
+ logger.info("[modify_event] Removing Google Meet conference")
668
+
669
+ if timezone is not None and "start" not in event_body and "end" not in event_body:
670
+ # If timezone is provided but start/end times are not, we need to fetch the existing event
671
+ # to apply the timezone correctly. This is a simplification; a full implementation
672
+ # might handle this more robustly or require start/end with timezone.
673
+ # For now, we'll log a warning and skip applying timezone if start/end are missing.
674
+ logger.warning(
675
+ "[modify_event] Timezone provided but start_time and end_time are missing. Timezone will not be applied unless start/end times are also provided."
676
+ )
677
+
678
+ if attachments is not None:
679
+ # patch replaces the array wholesale, so the list passed in is the final list.
680
+ event_body["attachments"] = await _build_attachment_entries(
681
+ service, attachments, "modify_event"
682
+ )
683
+
684
+ if not event_body:
685
+ message = "No fields provided to modify the event."
686
+ logger.warning(f"[modify_event] {message}")
687
+ raise Exception(message)
688
+
689
+ if this_and_following:
690
+ new_series = await _split_recurring_event(
691
+ service, calendar_id, event_id, event_body, send_updates
692
+ )
693
+ return (
694
+ f"Successfully modified '{new_series.get('summary', summary)}' from "
695
+ f"instance {event_id} onward for {user_google_email}. Earlier instances "
696
+ "keep the original series; this and following instances are now series "
697
+ f"ID {new_series.get('id')}. "
698
+ f"Link: {new_series.get('htmlLink', 'No link available')}"
699
+ + _saved_event_times(new_series)
700
+ )
701
+
702
+ # Log the event ID for debugging
703
+ logger.info(
704
+ f"[modify_event] Attempting to update event with ID: '{event_id}' in calendar '{calendar_id}'"
705
+ )
706
+
707
+ # Get the existing event to preserve fields that aren't being updated
708
+ try:
709
+ existing_event = await asyncio.to_thread(
710
+ lambda: (
711
+ service.events().get(calendarId=calendar_id, eventId=event_id).execute()
712
+ )
713
+ )
714
+ logger.info(
715
+ "[modify_event] Successfully retrieved existing event before update"
716
+ )
717
+
718
+ # Preserve existing fields if not provided in the update
719
+ _preserve_existing_fields(
720
+ event_body,
721
+ existing_event,
722
+ {
723
+ "summary": summary,
724
+ "description": description,
725
+ "location": location,
726
+ # Use the already-normalized attendee objects (if provided); otherwise preserve existing
727
+ "attendees": event_body.get("attendees"),
728
+ "colorId": event_body.get("colorId"),
729
+ "recurrence": recurrence,
730
+ },
731
+ )
732
+
733
+ if add_google_meet is None and "conferenceData" in existing_event:
734
+ logger.info(
735
+ "[modify_event] Existing conference data preserved via patch (not copied)"
736
+ )
737
+
738
+ except HttpError as get_error:
739
+ if get_error.resp.status == 404:
740
+ logger.error(
741
+ f"[modify_event] Event not found during pre-update verification: {get_error}"
742
+ )
743
+ message = f"Event not found during verification. The event with ID '{event_id}' could not be found in calendar '{calendar_id}'. This may be due to incorrect ID format or the event no longer exists."
744
+ raise Exception(message)
745
+ else:
746
+ logger.warning(
747
+ f"[modify_event] Error during pre-update verification, but proceeding with update: {get_error}"
748
+ )
749
+
750
+ updated_event = await asyncio.to_thread(
751
+ lambda: (
752
+ service.events()
753
+ .patch(
754
+ calendarId=calendar_id,
755
+ eventId=event_id,
756
+ body=event_body,
757
+ supportsAttachments=True,
758
+ conferenceDataVersion=1,
759
+ sendUpdates=send_updates,
760
+ )
761
+ .execute()
762
+ )
763
+ )
764
+
765
+ link = updated_event.get("htmlLink", "No link available")
766
+ confirmation_message = f"Successfully modified event '{updated_event.get('summary', summary)}' (ID: {event_id}) for {user_google_email}. Link: {link}"
767
+
768
+ confirmation_message += _saved_event_times(updated_event)
769
+
770
+ # Surface the conferencing link (native Meet or third-party add-on) if present
771
+ if conference_data is not None:
772
+ meeting_link = _get_meeting_link(updated_event)
773
+ if meeting_link:
774
+ confirmation_message += f" Conference: {meeting_link}"
775
+ elif add_google_meet is True:
776
+ meeting_link = _get_meeting_link(updated_event)
777
+ if meeting_link:
778
+ confirmation_message += f" Google Meet: {meeting_link}"
779
+ elif add_google_meet is False:
780
+ confirmation_message += " (Google Meet removed)"
781
+
782
+ logger.info(
783
+ f"Event modified successfully for {user_google_email}. ID: {updated_event.get('id')}, Link: {link}"
784
+ )
785
+ return confirmation_message
786
+
787
+
788
+ async def _delete_event_impl(
789
+ service,
790
+ user_google_email: str,
791
+ event_id: str,
792
+ calendar_id: str = "primary",
793
+ send_updates: str = "all",
794
+ only_if_no_attendees: bool = False,
795
+ ) -> str:
796
+ """Internal implementation for deleting a calendar event."""
797
+ logger.info(
798
+ f"[delete_event] Invoked. Email: '{user_google_email}', Event ID: {event_id}"
799
+ )
800
+
801
+ # Log the event ID for debugging
802
+ logger.info(
803
+ f"[delete_event] Attempting to delete event with ID: '{event_id}' in calendar '{calendar_id}'"
804
+ )
805
+
806
+ # Try to get the event first to verify it exists
807
+ try:
808
+ existing_event = await asyncio.to_thread(
809
+ lambda: (
810
+ service.events().get(calendarId=calendar_id, eventId=event_id).execute()
811
+ )
812
+ )
813
+ logger.info("[delete_event] Successfully verified event exists before deletion")
814
+ except HttpError as get_error:
815
+ if get_error.resp.status == 404:
816
+ logger.error(
817
+ f"[delete_event] Event not found during pre-delete verification: {get_error}"
818
+ )
819
+ message = f"Event not found during verification. The event with ID '{event_id}' could not be found in calendar '{calendar_id}'. This may be due to incorrect ID format or the event no longer exists."
820
+ raise Exception(message)
821
+ if only_if_no_attendees:
822
+ raise
823
+ logger.warning(
824
+ f"[delete_event] Error during pre-delete verification, but proceeding with deletion: {get_error}"
825
+ )
826
+
827
+ delete_request = service.events().delete(
828
+ calendarId=calendar_id,
829
+ eventId=event_id,
830
+ sendUpdates=send_updates,
831
+ )
832
+ if only_if_no_attendees:
833
+ if existing_event.get("recurrence"):
834
+ raise UserInputError(
835
+ "only_if_no_attendees cannot check every instance of a recurring series; "
836
+ "delete instances individually or omit the guard."
837
+ )
838
+ guests = sum(
839
+ a.get("additionalGuests", 0) + (0 if a.get("self") else 1)
840
+ for a in existing_event.get("attendees", [])
841
+ )
842
+ if guests:
843
+ raise UserInputError(
844
+ f"Event has {guests} attendee(s) besides the calendar owner; "
845
+ "refusing to delete."
846
+ )
847
+ delete_request.headers["If-Match"] = existing_event["etag"]
848
+ await asyncio.to_thread(delete_request.execute)
849
+
850
+ confirmation_message = f"Successfully deleted event (ID: {event_id}) from calendar '{calendar_id}' for {user_google_email}."
851
+ logger.info(f"Event deleted successfully for {user_google_email}. ID: {event_id}")
852
+ return confirmation_message
853
+
854
+
855
+ async def _rsvp_event_impl(
856
+ service,
857
+ user_google_email: str,
858
+ event_id: str,
859
+ response: str,
860
+ calendar_id: str = "primary",
861
+ comment: Optional[str] = None,
862
+ send_updates: str = "all",
863
+ ) -> str:
864
+ """Internal implementation for responding to a calendar event invitation."""
865
+ valid_responses = {"accepted", "declined", "tentative", "needsAction"}
866
+ if response not in valid_responses:
867
+ raise UserInputError(
868
+ f"Invalid response '{response}'. Must be one of: {sorted(valid_responses)}"
869
+ )
870
+
871
+ existing_event = await asyncio.to_thread(
872
+ lambda: service.events().get(calendarId=calendar_id, eventId=event_id).execute()
873
+ )
874
+
875
+ attendees = existing_event.get("attendees")
876
+ if not attendees:
877
+ raise Exception("This event has no attendee list; cannot update RSVP.")
878
+
879
+ if existing_event.get("organizer", {}).get("self"):
880
+ raise Exception(
881
+ "You are the organizer of this event. Organizers cannot respond to their own invitations."
882
+ )
883
+
884
+ user_index = next((i for i, a in enumerate(attendees) if a.get("self")), None)
885
+ if user_index is None:
886
+ raise Exception(
887
+ f"{user_google_email} was not found in the event's attendee list."
888
+ )
889
+
890
+ updated_attendees = [dict(a) for a in attendees]
891
+ updated_attendees[user_index]["responseStatus"] = response
892
+ if comment is not None:
893
+ updated_attendees[user_index]["comment"] = comment
894
+
895
+ updated_event = await asyncio.to_thread(
896
+ lambda: (
897
+ service.events()
898
+ .patch(
899
+ calendarId=calendar_id,
900
+ eventId=event_id,
901
+ body={"attendees": updated_attendees},
902
+ sendUpdates=send_updates,
903
+ )
904
+ .execute()
905
+ )
906
+ )
907
+
908
+ summary = updated_event.get("summary", "Unknown event")
909
+ logger.info(
910
+ f"[rsvp_event] RSVP for event {event_id} set to '{response}' for {user_google_email}."
911
+ )
912
+ return f"Successfully updated RSVP for '{summary}' (ID: {event_id}) to '{response}' for {user_google_email}."
913
+
914
+
915
+ # ---------------------------------------------------------------------------
916
+ # Consolidated event management tool
917
+ # ---------------------------------------------------------------------------
918
+
919
+
920
+ @server.tool(
921
+ title="Manage Event",
922
+ annotations=ToolAnnotations(
923
+ readOnlyHint=False,
924
+ destructiveHint=True,
925
+ idempotentHint=False,
926
+ openWorldHint=True,
927
+ ),
928
+ )
929
+ @handle_http_errors("manage_event", service_type="calendar")
930
+ @require_google_service("calendar", "calendar_events")
931
+ async def manage_event(
932
+ service,
933
+ user_google_email: str,
934
+ action: str,
935
+ summary: Optional[str] = None,
936
+ start_time: Optional[str] = None,
937
+ end_time: Optional[str] = None,
938
+ event_id: Optional[str] = None,
939
+ calendar_id: str = "primary",
940
+ description: Optional[str] = None,
941
+ location: Optional[str] = None,
942
+ attendees: Optional[StringOrDictList] = None,
943
+ timezone: Optional[str] = None,
944
+ attachments: Optional[StringList] = None,
945
+ add_google_meet: Optional[bool] = None,
946
+ conference_data: Optional[Dict[str, Any]] = None,
947
+ conference_provider: Optional[str] = None,
948
+ conference_uri: Optional[str] = None,
949
+ conference_passcode: Optional[str] = None,
950
+ conference_id: Optional[str] = None,
951
+ reminders: Optional[Union[str, List[Dict[str, Any]]]] = None,
952
+ use_default_reminders: Optional[bool] = None,
953
+ transparency: Optional[str] = None,
954
+ visibility: Optional[str] = None,
955
+ color_id: Optional[str] = None,
956
+ recurrence: Optional[StringList] = None,
957
+ guests_can_modify: Optional[bool] = None,
958
+ guests_can_invite_others: Optional[bool] = None,
959
+ guests_can_see_other_guests: Optional[bool] = None,
960
+ response: Optional[str] = None,
961
+ rsvp_comment: Optional[str] = None,
962
+ send_updates: Optional[str] = None,
963
+ *,
964
+ start_timezone: Optional[str] = None,
965
+ end_timezone: Optional[str] = None,
966
+ this_and_following: bool = False,
967
+ destination_calendar_id: Optional[str] = None,
968
+ only_if_no_attendees: bool = False,
969
+ ) -> str:
970
+ """
971
+ Manages calendar events. Supports creating, updating, deleting, moving, and RSVP.
972
+
973
+ Args:
974
+ user_google_email (str): The user's Google email address. Required.
975
+ action (str): Action to perform - "create", "update", "delete", "move", or "rsvp".
976
+ summary (Optional[str]): Event title (required for create).
977
+ start_time (Optional[str]): Start time (required for create). An RFC3339 UTC offset identifies the exact instant and is preserved. Without an offset, supply start_timezone or timezone. For a local wall-clock time, omit the offset and pass the zone so Google resolves daylight saving; a wrong offset moves the event. Date-only values create all-day events.
978
+ end_time (Optional[str]): End time (required for create). An RFC3339 UTC offset identifies the exact instant and is preserved. Without an offset, supply end_timezone or timezone. All-day end dates are exclusive.
979
+ event_id (Optional[str]): Event ID (required for update, delete, move, and rsvp).
980
+ calendar_id (str): Calendar ID (default: 'primary'). For move, this is the source.
981
+ destination_calendar_id (Optional[str]): Calendar to move the event to, which becomes its organizer (required for move). Only default events can be moved, and the user needs access to both calendars.
982
+ description (Optional[str]): Event description.
983
+ location (Optional[str]): Event location.
984
+ attendees (Optional[List[Union[str, Dict[str, Any]]]]): Attendee email addresses, attendee objects (e.g. {"email": ..., "responseStatus": "accepted"}), or a mix of both.
985
+ timezone (Optional[str]): IANA timezone applied to both boundaries (e.g.,
986
+ "America/New_York"). Converts offset-bearing timestamps without changing their
987
+ instant; interprets offset-free timestamps as local times in this zone.
988
+ Overridden per boundary by start_timezone/end_timezone.
989
+ start_timezone (Optional[str]): IANA timezone for the start boundary only,
990
+ overriding timezone. Use for events whose two ends sit in different zones -
991
+ a flight departing 13:45 "Asia/Jerusalem" and landing 17:50
992
+ "Europe/Amsterdam" is one event authored in two zones. Explicit timestamp
993
+ offsets always preserve the instant, even when the zone differs.
994
+ end_timezone (Optional[str]): IANA timezone for the end boundary only,
995
+ overriding timezone. See start_timezone.
996
+ attachments (Optional[List[str]]): List of Google Drive file URLs or IDs to attach.
997
+ On action="update" this replaces the event's existing attachments rather than
998
+ appending to them, matching the Calendar API's patch semantics.
999
+ add_google_meet (Optional[bool]): Whether to add/remove native Google Meet.
1000
+ conference_data (Optional[Dict[str, Any]]): Raw Google Calendar `conferenceData`
1001
+ payload to attach a third-party conference (Zoom/Webex/Teams add-on). Use this
1002
+ for full control; mutually exclusive with the conference_provider helper params
1003
+ and with add_google_meet. (create/update only)
1004
+ conference_provider (Optional[str]): Higher-level helper: third-party provider name
1005
+ (e.g. "zoom", "webex", "teams"). Requires conference_uri. The MCP builds the
1006
+ addOn `conferenceData` block internally. (create/update only)
1007
+ conference_uri (Optional[str]): Join URL for the third-party conference (e.g.
1008
+ "https://zoom.us/j/123456789"). Required when conference_provider is set.
1009
+ conference_passcode (Optional[str]): Optional passcode for the third-party conference.
1010
+ conference_id (Optional[str]): Optional provider-side conference/meeting ID.
1011
+ reminders (Optional[Union[str, List[Dict[str, Any]]]]): Custom reminder objects.
1012
+ use_default_reminders (Optional[bool]): Whether to use default reminders.
1013
+ transparency (Optional[str]): "opaque" (busy) or "transparent" (free).
1014
+ visibility (Optional[str]): "default", "public", "private", or "confidential".
1015
+ color_id (Optional[str]): Event color, by name or ID: lavender (1), sage (2),
1016
+ grape (3), flamingo (4), banana (5), tangerine (6), peacock (7),
1017
+ graphite (8), blueberry (9), basil (10), tomato (11).
1018
+ recurrence (Optional[List[str]]): RFC5545 recurrence rules for a recurring event, e.g. ["RRULE:FREQ=WEEKLY;COUNT=10"].
1019
+ guests_can_modify (Optional[bool]): Whether attendees can modify.
1020
+ guests_can_invite_others (Optional[bool]): Whether attendees can invite others.
1021
+ guests_can_see_other_guests (Optional[bool]): Whether attendees can see other guests.
1022
+ response (Optional[str]): RSVP response — "accepted", "declined", "tentative", or "needsAction" (rsvp action only).
1023
+ rsvp_comment (Optional[str]): Optional message to include with the RSVP response (rsvp action only).
1024
+ send_updates (Optional[str]): Notification behavior: "all", "externalOnly", or "none".
1025
+ Defaults to "none" for move and "all" for other actions.
1026
+ this_and_following (bool): Update only. With event_id set to a recurring instance ID,
1027
+ applies the change to that instance and every later one by ending the original
1028
+ series before it and starting a new series there; earlier instances are kept.
1029
+ Updating the series ID instead changes every instance, and moving its start or
1030
+ recurrence drops past instances that no longer match. Defaults to False.
1031
+ only_if_no_attendees (bool): Delete only. Refuses the delete unless the event lists
1032
+ no attendees besides the calendar it is deleted from, checked server-side
1033
+ against the current event. Recurring series are refused; delete their
1034
+ instances individually. Defaults to False.
1035
+
1036
+ Returns:
1037
+ str: Confirmation message with event details.
1038
+ """
1039
+ action_lower = action.lower().strip()
1040
+
1041
+ if send_updates is not None:
1042
+ valid_send_updates = {"all", "externalOnly", "none"}
1043
+ if send_updates not in valid_send_updates:
1044
+ raise UserInputError(
1045
+ f"Invalid send_updates '{send_updates}'. Must be one of: {sorted(valid_send_updates)}"
1046
+ )
1047
+
1048
+ if this_and_following and action_lower != "update":
1049
+ raise UserInputError("this_and_following applies only to the update action.")
1050
+
1051
+ if only_if_no_attendees and action_lower != "delete":
1052
+ raise UserInputError("only_if_no_attendees applies only to the delete action.")
1053
+
1054
+ # Resolve the conferencing inputs (raw payload or helper params) once for the
1055
+ # actions that build an event body.
1056
+ resolved_conference_data = None
1057
+ if action_lower in ("create", "update"):
1058
+ resolved_conference_data = _resolve_conference_data(
1059
+ conference_data,
1060
+ conference_provider,
1061
+ conference_uri,
1062
+ conference_passcode,
1063
+ conference_id,
1064
+ add_google_meet,
1065
+ )
1066
+ color_id = _resolve_color_id(color_id)
1067
+
1068
+ if action_lower == "create":
1069
+ if not summary or not start_time or not end_time:
1070
+ raise UserInputError(
1071
+ "summary, start_time, and end_time are required for create action"
1072
+ )
1073
+ return await _create_event_impl(
1074
+ service=service,
1075
+ user_google_email=user_google_email,
1076
+ summary=summary,
1077
+ start_time=start_time,
1078
+ end_time=end_time,
1079
+ calendar_id=calendar_id,
1080
+ description=description,
1081
+ location=location,
1082
+ attendees=attendees,
1083
+ timezone=timezone,
1084
+ start_timezone=start_timezone,
1085
+ end_timezone=end_timezone,
1086
+ attachments=attachments,
1087
+ add_google_meet=add_google_meet or False,
1088
+ conference_data=resolved_conference_data,
1089
+ reminders=reminders,
1090
+ use_default_reminders=use_default_reminders
1091
+ if use_default_reminders is not None
1092
+ else True,
1093
+ transparency=transparency,
1094
+ visibility=visibility,
1095
+ color_id=color_id,
1096
+ guests_can_modify=guests_can_modify,
1097
+ guests_can_invite_others=guests_can_invite_others,
1098
+ guests_can_see_other_guests=guests_can_see_other_guests,
1099
+ recurrence=recurrence,
1100
+ send_updates=send_updates or "all",
1101
+ )
1102
+ elif action_lower == "update":
1103
+ if not event_id:
1104
+ raise UserInputError("event_id is required for update action")
1105
+ return await _modify_event_impl(
1106
+ service=service,
1107
+ user_google_email=user_google_email,
1108
+ event_id=event_id,
1109
+ calendar_id=calendar_id,
1110
+ summary=summary,
1111
+ start_time=start_time,
1112
+ end_time=end_time,
1113
+ description=description,
1114
+ location=location,
1115
+ attendees=attendees,
1116
+ timezone=timezone,
1117
+ start_timezone=start_timezone,
1118
+ end_timezone=end_timezone,
1119
+ add_google_meet=add_google_meet,
1120
+ conference_data=resolved_conference_data,
1121
+ reminders=reminders,
1122
+ use_default_reminders=use_default_reminders,
1123
+ transparency=transparency,
1124
+ visibility=visibility,
1125
+ color_id=color_id,
1126
+ recurrence=recurrence,
1127
+ guests_can_modify=guests_can_modify,
1128
+ guests_can_invite_others=guests_can_invite_others,
1129
+ guests_can_see_other_guests=guests_can_see_other_guests,
1130
+ attachments=attachments,
1131
+ send_updates=send_updates or "all",
1132
+ this_and_following=this_and_following,
1133
+ )
1134
+ elif action_lower == "delete":
1135
+ if not event_id:
1136
+ raise UserInputError("event_id is required for delete action")
1137
+ return await _delete_event_impl(
1138
+ service=service,
1139
+ user_google_email=user_google_email,
1140
+ event_id=event_id,
1141
+ calendar_id=calendar_id,
1142
+ send_updates=send_updates or "all",
1143
+ only_if_no_attendees=only_if_no_attendees,
1144
+ )
1145
+ elif action_lower == "move":
1146
+ if not event_id or not destination_calendar_id:
1147
+ raise UserInputError(
1148
+ "event_id and destination_calendar_id are required for move action"
1149
+ )
1150
+ return await _move_event(
1151
+ service=service,
1152
+ calendar_id=calendar_id,
1153
+ event_id=event_id,
1154
+ destination_calendar_id=destination_calendar_id,
1155
+ send_updates=send_updates or "none",
1156
+ )
1157
+ elif action_lower == "rsvp":
1158
+ if not event_id:
1159
+ raise UserInputError("event_id is required for rsvp action")
1160
+ if not response:
1161
+ raise UserInputError("response is required for rsvp action")
1162
+ return await _rsvp_event_impl(
1163
+ service=service,
1164
+ user_google_email=user_google_email,
1165
+ event_id=event_id,
1166
+ response=response,
1167
+ calendar_id=calendar_id,
1168
+ comment=rsvp_comment,
1169
+ send_updates=send_updates or "all",
1170
+ )
1171
+ else:
1172
+ raise UserInputError(
1173
+ f"Invalid action '{action_lower}'. Must be 'create', 'update', 'delete', 'move', or 'rsvp'."
1174
+ )
1175
+
1176
+
1177
+ # ---------------------------------------------------------------------------
1178
+ # Out of Office event management
1179
+ # ---------------------------------------------------------------------------
1180
+
1181
+
1182
+ async def _create_ooo_event_impl(
1183
+ service,
1184
+ user_google_email: str,
1185
+ start_time: str,
1186
+ end_time: str,
1187
+ calendar_id: str = "primary",
1188
+ summary: Optional[str] = None,
1189
+ auto_decline_mode: Optional[str] = None,
1190
+ decline_message: Optional[str] = None,
1191
+ recurrence: Optional[List[str]] = None,
1192
+ timezone: Optional[str] = None,
1193
+ ) -> str:
1194
+ """Internal implementation for creating an Out of Office calendar event."""
1195
+ logger.info(
1196
+ f"[create_ooo_event] Invoked. Email: '{user_google_email}', Start: {start_time}, End: {end_time}"
1197
+ )
1198
+
1199
+ effective_summary = summary or "Out of Office"
1200
+ effective_decline_mode = _validate_auto_decline_mode(
1201
+ auto_decline_mode, "create_ooo_event"
1202
+ )
1203
+
1204
+ event_body: Dict[str, Any] = {
1205
+ "eventType": "outOfOffice",
1206
+ "summary": effective_summary,
1207
+ "start": _status_event_time_entry(start_time, "Out of Office", timezone),
1208
+ "end": _status_event_time_entry(end_time, "Out of Office", timezone),
1209
+ "outOfOfficeProperties": {
1210
+ "autoDeclineMode": effective_decline_mode,
1211
+ "declineMessage": decline_message or "",
1212
+ },
1213
+ "transparency": "opaque",
1214
+ }
1215
+ if recurrence:
1216
+ event_body["recurrence"] = recurrence
1217
+
1218
+ created_event = await asyncio.to_thread(
1219
+ lambda: (
1220
+ service.events().insert(calendarId=calendar_id, body=event_body).execute()
1221
+ )
1222
+ )
1223
+
1224
+ event_id = created_event.get("id", "N/A")
1225
+ link = created_event.get("htmlLink", "N/A")
1226
+
1227
+ start_display = created_event.get("start", {}).get(
1228
+ "date", created_event.get("start", {}).get("dateTime", "N/A")
1229
+ )
1230
+ end_display = created_event.get("end", {}).get(
1231
+ "date", created_event.get("end", {}).get("dateTime", "N/A")
1232
+ )
1233
+
1234
+ confirmation = (
1235
+ f"Successfully created Out of Office event for {user_google_email}.\n"
1236
+ f"- Summary: {effective_summary}\n"
1237
+ f"- Start: {start_display}\n"
1238
+ f"- End: {end_display}\n"
1239
+ f"- Auto-decline: {effective_decline_mode}\n"
1240
+ f"- Decline message: {decline_message or '(none)'}\n"
1241
+ f"- Event ID: {event_id}\n"
1242
+ f"- Link: {link}"
1243
+ )
1244
+
1245
+ logger.info(
1246
+ f"OOO event created successfully for {user_google_email}. ID: {event_id}"
1247
+ )
1248
+ return confirmation
1249
+
1250
+
1251
+ async def _list_ooo_events_impl(
1252
+ service,
1253
+ user_google_email: str,
1254
+ calendar_id: str = "primary",
1255
+ time_min: Optional[str] = None,
1256
+ time_max: Optional[str] = None,
1257
+ max_results: int = 10,
1258
+ timezone: Optional[str] = None,
1259
+ page_token: Optional[str] = None,
1260
+ ) -> str:
1261
+ """Internal implementation for listing Out of Office calendar events."""
1262
+ logger.info(
1263
+ f"[list_ooo_events] Invoked. Email: '{user_google_email}', time_min: {time_min}, time_max: {time_max}, timezone: {timezone}"
1264
+ )
1265
+
1266
+ formatted_time_min = _correct_time_format_for_api(time_min, "time_min", timezone)
1267
+ if page_token and formatted_time_min is None:
1268
+ raise UserInputError(
1269
+ "[list_ooo_events] page_token requires time_min. Pass the Pagination "
1270
+ "time_min from the previous response to preserve the original range."
1271
+ )
1272
+ if formatted_time_min:
1273
+ effective_time_min = formatted_time_min
1274
+ else:
1275
+ if timezone:
1276
+ try:
1277
+ tz = pytz.timezone(timezone)
1278
+ now = datetime.datetime.now(tz)
1279
+ effective_time_min = (
1280
+ now.astimezone(datetime.timezone.utc)
1281
+ .isoformat()
1282
+ .replace("+00:00", "Z")
1283
+ )
1284
+ except pytz.exceptions.UnknownTimeZoneError:
1285
+ logger.warning(
1286
+ f"Could not apply timezone '{timezone}', falling back to UTC"
1287
+ )
1288
+ utc_now = datetime.datetime.now(datetime.timezone.utc)
1289
+ effective_time_min = utc_now.isoformat().replace("+00:00", "Z")
1290
+ else:
1291
+ utc_now = datetime.datetime.now(datetime.timezone.utc)
1292
+ effective_time_min = utc_now.isoformat().replace("+00:00", "Z")
1293
+
1294
+ effective_time_max = _correct_time_format_for_api(time_max, "time_max", timezone)
1295
+
1296
+ request_params: Dict[str, Any] = {
1297
+ "calendarId": calendar_id,
1298
+ "timeMin": effective_time_min,
1299
+ "maxResults": max_results,
1300
+ "singleEvents": True,
1301
+ "orderBy": "startTime",
1302
+ "eventTypes": ["outOfOffice"],
1303
+ }
1304
+ if effective_time_max:
1305
+ request_params["timeMax"] = effective_time_max
1306
+ if page_token:
1307
+ request_params["pageToken"] = page_token
1308
+
1309
+ events_result = await asyncio.to_thread(
1310
+ lambda: service.events().list(**request_params).execute()
1311
+ )
1312
+ items = events_result.get("items", [])
1313
+ next_page_token = events_result.get("nextPageToken")
1314
+ pagination_info = ""
1315
+ if next_page_token:
1316
+ pagination_info = (
1317
+ f"Next page token: {next_page_token}"
1318
+ f"\nPagination time_min: {effective_time_min}"
1319
+ )
1320
+
1321
+ if not items:
1322
+ if next_page_token:
1323
+ return (
1324
+ f"No out-of-office events on this page for {user_google_email}, and more pages remain."
1325
+ f"\n{pagination_info}"
1326
+ )
1327
+ return f"No out-of-office events found for {user_google_email}."
1328
+
1329
+ lines = [f"Found {len(items)} out-of-office event(s) for {user_google_email}:\n"]
1330
+ for i, item in enumerate(items, 1):
1331
+ summary = item.get("summary", "Out of Office")
1332
+ start = item.get("start", {}).get(
1333
+ "date", item.get("start", {}).get("dateTime", "N/A")
1334
+ )
1335
+ end = item.get("end", {}).get(
1336
+ "date", item.get("end", {}).get("dateTime", "N/A")
1337
+ )
1338
+ event_id = item.get("id", "N/A")
1339
+ ooo_props = item.get("outOfOfficeProperties", {})
1340
+ decline_mode = ooo_props.get("autoDeclineMode", "N/A")
1341
+ decline_msg = ooo_props.get("declineMessage", "")
1342
+
1343
+ lines.append(f'{i}. "{summary}" ({start} to {end})')
1344
+ lines.append(f" Auto-decline: {decline_mode}")
1345
+ if decline_msg:
1346
+ lines.append(f" Decline message: {decline_msg}")
1347
+ lines.append(f" Event ID: {event_id}")
1348
+ lines.append("")
1349
+
1350
+ if next_page_token:
1351
+ lines.append(pagination_info)
1352
+ return "\n".join(lines).rstrip()
1353
+
1354
+
1355
+ async def _update_ooo_event_impl(
1356
+ service,
1357
+ user_google_email: str,
1358
+ event_id: str,
1359
+ calendar_id: str = "primary",
1360
+ start_time: Optional[str] = None,
1361
+ end_time: Optional[str] = None,
1362
+ summary: Optional[str] = None,
1363
+ auto_decline_mode: Optional[str] = None,
1364
+ decline_message: Optional[str] = None,
1365
+ recurrence: Optional[List[str]] = None,
1366
+ timezone: Optional[str] = None,
1367
+ ) -> str:
1368
+ """Internal implementation for updating an Out of Office calendar event."""
1369
+ logger.info(
1370
+ f"[update_ooo_event] Invoked. Email: '{user_google_email}', Event ID: {event_id}"
1371
+ )
1372
+
1373
+ existing_event = await asyncio.to_thread(
1374
+ lambda: service.events().get(calendarId=calendar_id, eventId=event_id).execute()
1375
+ )
1376
+
1377
+ if existing_event.get("eventType") != "outOfOffice":
1378
+ raise UserInputError(
1379
+ f"Event '{event_id}' is not an Out of Office event (type: '{existing_event.get('eventType', 'default')}'). "
1380
+ f"Use manage_event to update regular events."
1381
+ )
1382
+
1383
+ patch_body: Dict[str, Any] = {}
1384
+
1385
+ if summary is not None:
1386
+ patch_body["summary"] = summary
1387
+ if start_time is not None:
1388
+ patch_body["start"] = _status_event_time_entry(
1389
+ start_time, "Out of Office", timezone
1390
+ )
1391
+ if end_time is not None:
1392
+ patch_body["end"] = _status_event_time_entry(
1393
+ end_time, "Out of Office", timezone
1394
+ )
1395
+ if recurrence is not None:
1396
+ patch_body["recurrence"] = recurrence
1397
+
1398
+ if auto_decline_mode is not None or decline_message is not None:
1399
+ existing_ooo_props = existing_event.get("outOfOfficeProperties", {})
1400
+ patch_body["outOfOfficeProperties"] = {
1401
+ "autoDeclineMode": _validate_auto_decline_mode(
1402
+ auto_decline_mode, "update_ooo_event"
1403
+ )
1404
+ if auto_decline_mode is not None
1405
+ else existing_ooo_props.get(
1406
+ "autoDeclineMode", "declineAllConflictingInvitations"
1407
+ ),
1408
+ "declineMessage": decline_message
1409
+ if decline_message is not None
1410
+ else existing_ooo_props.get("declineMessage", ""),
1411
+ }
1412
+
1413
+ if not patch_body:
1414
+ return f"No changes specified for Out of Office event '{event_id}'."
1415
+
1416
+ updated_event = await asyncio.to_thread(
1417
+ lambda: (
1418
+ service.events()
1419
+ .patch(calendarId=calendar_id, eventId=event_id, body=patch_body)
1420
+ .execute()
1421
+ )
1422
+ )
1423
+
1424
+ link = updated_event.get("htmlLink", "N/A")
1425
+ start_display = updated_event.get("start", {}).get(
1426
+ "date", updated_event.get("start", {}).get("dateTime", "N/A")
1427
+ )
1428
+ end_display = updated_event.get("end", {}).get(
1429
+ "date", updated_event.get("end", {}).get("dateTime", "N/A")
1430
+ )
1431
+
1432
+ confirmation = (
1433
+ f"Successfully updated Out of Office event (ID: {event_id}) for {user_google_email}.\n"
1434
+ f"- Summary: {updated_event.get('summary', 'Out of Office')}\n"
1435
+ f"- Start: {start_display}\n"
1436
+ f"- End: {end_display}\n"
1437
+ f"- Link: {link}"
1438
+ )
1439
+
1440
+ logger.info(
1441
+ f"OOO event updated successfully for {user_google_email}. ID: {event_id}"
1442
+ )
1443
+ return confirmation
1444
+
1445
+
1446
+ async def _delete_ooo_event_impl(
1447
+ service,
1448
+ user_google_email: str,
1449
+ event_id: str,
1450
+ calendar_id: str = "primary",
1451
+ ) -> str:
1452
+ """Internal implementation for deleting an Out of Office calendar event."""
1453
+ logger.info(
1454
+ f"[delete_ooo_event] Invoked. Email: '{user_google_email}', Event ID: {event_id}"
1455
+ )
1456
+
1457
+ try:
1458
+ existing_event = await asyncio.to_thread(
1459
+ lambda: (
1460
+ service.events().get(calendarId=calendar_id, eventId=event_id).execute()
1461
+ )
1462
+ )
1463
+ if existing_event.get("eventType") != "outOfOffice":
1464
+ raise UserInputError(
1465
+ f"Event '{event_id}' is not an Out of Office event (type: '{existing_event.get('eventType', 'default')}'). "
1466
+ f"Use manage_event to delete regular events."
1467
+ )
1468
+ except HttpError as get_error:
1469
+ if get_error.resp.status == 404:
1470
+ raise Exception(
1471
+ f"Event not found. The event with ID '{event_id}' could not be found in calendar '{calendar_id}'."
1472
+ )
1473
+ else:
1474
+ raise
1475
+
1476
+ await asyncio.to_thread(
1477
+ lambda: (
1478
+ service.events().delete(calendarId=calendar_id, eventId=event_id).execute()
1479
+ )
1480
+ )
1481
+
1482
+ confirmation = f"Successfully deleted Out of Office event (ID: {event_id}) from calendar '{calendar_id}' for {user_google_email}."
1483
+ logger.info(
1484
+ f"OOO event deleted successfully for {user_google_email}. ID: {event_id}"
1485
+ )
1486
+ return confirmation
1487
+
1488
+
1489
+ @server.tool(
1490
+ title="Manage Out of Office",
1491
+ annotations=ToolAnnotations(
1492
+ readOnlyHint=False,
1493
+ destructiveHint=True,
1494
+ idempotentHint=False,
1495
+ openWorldHint=True,
1496
+ ),
1497
+ )
1498
+ @handle_http_errors("manage_out_of_office", service_type="calendar")
1499
+ @require_google_service("calendar", "calendar_events")
1500
+ async def manage_out_of_office(
1501
+ service,
1502
+ user_google_email: str,
1503
+ action: str,
1504
+ start_time: Optional[str] = None,
1505
+ end_time: Optional[str] = None,
1506
+ summary: Optional[str] = None,
1507
+ auto_decline_mode: Optional[str] = None,
1508
+ decline_message: Optional[str] = None,
1509
+ recurrence: Optional[StringList] = None,
1510
+ timezone: Optional[str] = None,
1511
+ time_min: Optional[str] = None,
1512
+ time_max: Optional[str] = None,
1513
+ max_results: int = 10,
1514
+ event_id: Optional[str] = None,
1515
+ calendar_id: str = "primary",
1516
+ page_token: Optional[str] = None,
1517
+ ) -> str:
1518
+ """
1519
+ Manages Out of Office events on Google Calendar. These special events auto-decline
1520
+ meeting invitations and set the user's status to "Out of office" across Google Workspace.
1521
+
1522
+ Args:
1523
+ user_google_email (str): The user's Google email address. Required.
1524
+ action (str): Action to perform - "create", "list", "update", or "delete".
1525
+ start_time (Optional[str]): Start date/time. Use 'YYYY-MM-DD' for full-day or RFC3339 for partial-day (e.g., '2024-04-05T09:00:00Z'). Date-only values are auto-converted to dateTime (midnight-to-midnight). Required for create.
1526
+ end_time (Optional[str]): End date/time (exclusive). Same format as start_time. For a single full day on April 5, use start_time='2026-04-05' and end_time='2026-04-06'. Required for create.
1527
+ summary (Optional[str]): Display text on the calendar. Defaults to "Out of Office".
1528
+ auto_decline_mode (Optional[str]): How to handle conflicting invitations. One of: "declineAllConflictingInvitations" (default), "declineOnlyNewConflictingInvitations", "declineNone".
1529
+ decline_message (Optional[str]): Message included when auto-declining invitations.
1530
+ recurrence (Optional[List[str]]): RFC5545 recurrence rules for a recurring Out of Office series, e.g. ["RRULE:FREQ=WEEKLY;COUNT=10"].
1531
+ timezone (Optional[str]): Timezone for the event (e.g., "America/New_York", "Europe/London"). Required when using date-only values or dateTime values without an explicit UTC offset.
1532
+ time_min (Optional[str]): For "list" action: start of time range. Defaults to current time. Recurring series are expanded into individual instances in the requested range.
1533
+ time_max (Optional[str]): For "list" action: end of time range.
1534
+ max_results (int): For "list" action: maximum events to return in one page. Defaults to 10.
1535
+ event_id (Optional[str]): Event ID. Required for "update" and "delete" actions.
1536
+ calendar_id (str): Calendar ID. Defaults to 'primary'. Out of Office status events live on primary calendars, so use 'primary' or a user's primary calendar ID/email rather than a secondary calendar ID.
1537
+ page_token (Optional[str]): For "list" action: token for the next page, taken from a previous response. Also pass the response's Pagination time_min as time_min, even if omitted on the first call. Keep all other query parameters unchanged.
1538
+
1539
+ Returns:
1540
+ str: Confirmation message with event details, or a formatted list of OOO events.
1541
+ """
1542
+ action_lower = action.lower().strip()
1543
+ if action_lower == "create":
1544
+ if not start_time or not end_time:
1545
+ raise UserInputError(
1546
+ "start_time and end_time are required for create action"
1547
+ )
1548
+ return await _create_ooo_event_impl(
1549
+ service=service,
1550
+ user_google_email=user_google_email,
1551
+ start_time=start_time,
1552
+ end_time=end_time,
1553
+ calendar_id=calendar_id,
1554
+ summary=summary,
1555
+ auto_decline_mode=auto_decline_mode,
1556
+ decline_message=decline_message,
1557
+ recurrence=recurrence,
1558
+ timezone=timezone,
1559
+ )
1560
+ elif action_lower == "list":
1561
+ return await _list_ooo_events_impl(
1562
+ service=service,
1563
+ user_google_email=user_google_email,
1564
+ calendar_id=calendar_id,
1565
+ time_min=time_min,
1566
+ time_max=time_max,
1567
+ max_results=max_results,
1568
+ timezone=timezone,
1569
+ page_token=page_token,
1570
+ )
1571
+ elif action_lower == "update":
1572
+ if not event_id:
1573
+ raise UserInputError("event_id is required for update action")
1574
+ return await _update_ooo_event_impl(
1575
+ service=service,
1576
+ user_google_email=user_google_email,
1577
+ event_id=event_id,
1578
+ calendar_id=calendar_id,
1579
+ start_time=start_time,
1580
+ end_time=end_time,
1581
+ summary=summary,
1582
+ auto_decline_mode=auto_decline_mode,
1583
+ decline_message=decline_message,
1584
+ recurrence=recurrence,
1585
+ timezone=timezone,
1586
+ )
1587
+ elif action_lower == "delete":
1588
+ if not event_id:
1589
+ raise UserInputError("event_id is required for delete action")
1590
+ return await _delete_ooo_event_impl(
1591
+ service=service,
1592
+ user_google_email=user_google_email,
1593
+ event_id=event_id,
1594
+ calendar_id=calendar_id,
1595
+ )
1596
+ else:
1597
+ raise UserInputError(
1598
+ f"Invalid action '{action_lower}'. Must be 'create', 'list', 'update', or 'delete'."
1599
+ )
1600
+
1601
+
1602
+ # ---------------------------------------------------------------------------
1603
+ # Focus Time event management
1604
+ # ---------------------------------------------------------------------------
1605
+
1606
+
1607
+ async def _create_focus_time_event_impl(
1608
+ service,
1609
+ user_google_email: str,
1610
+ start_time: str,
1611
+ end_time: str,
1612
+ calendar_id: str = "primary",
1613
+ summary: Optional[str] = None,
1614
+ description: Optional[str] = None,
1615
+ auto_decline_mode: Optional[str] = None,
1616
+ decline_message: Optional[str] = None,
1617
+ chat_status: Optional[str] = None,
1618
+ recurrence: Optional[List[str]] = None,
1619
+ timezone: Optional[str] = None,
1620
+ ) -> str:
1621
+ """Internal implementation for creating a Focus Time calendar event."""
1622
+ logger.info(
1623
+ f"[create_focus_time_event] Invoked. Email: '{user_google_email}', Start: {start_time}, End: {end_time}"
1624
+ )
1625
+
1626
+ effective_summary = summary or "Focus Time"
1627
+ effective_decline_mode = _validate_auto_decline_mode(
1628
+ auto_decline_mode, "create_focus_time_event"
1629
+ )
1630
+ validated_chat_status = _validate_chat_status(
1631
+ chat_status or "doNotDisturb", "create_focus_time_event"
1632
+ )
1633
+
1634
+ focus_time_props: Dict[str, str] = {
1635
+ "autoDeclineMode": effective_decline_mode,
1636
+ "declineMessage": decline_message or "",
1637
+ }
1638
+ if validated_chat_status:
1639
+ focus_time_props["chatStatus"] = validated_chat_status
1640
+
1641
+ event_body: Dict[str, Any] = {
1642
+ "eventType": "focusTime",
1643
+ "summary": effective_summary,
1644
+ "start": _status_event_time_entry(start_time, "Focus Time", timezone),
1645
+ "end": _status_event_time_entry(end_time, "Focus Time", timezone),
1646
+ "focusTimeProperties": focus_time_props,
1647
+ "transparency": "opaque",
1648
+ }
1649
+ if description:
1650
+ event_body["description"] = description
1651
+ if recurrence:
1652
+ event_body["recurrence"] = recurrence
1653
+
1654
+ created_event = await asyncio.to_thread(
1655
+ lambda: (
1656
+ service.events().insert(calendarId=calendar_id, body=event_body).execute()
1657
+ )
1658
+ )
1659
+
1660
+ event_id = created_event.get("id", "N/A")
1661
+ link = created_event.get("htmlLink", "N/A")
1662
+
1663
+ start_display = created_event.get("start", {}).get(
1664
+ "date", created_event.get("start", {}).get("dateTime", "N/A")
1665
+ )
1666
+ end_display = created_event.get("end", {}).get(
1667
+ "date", created_event.get("end", {}).get("dateTime", "N/A")
1668
+ )
1669
+
1670
+ confirmation = (
1671
+ f"Successfully created Focus Time event for {user_google_email}.\n"
1672
+ f"- Summary: {effective_summary}\n"
1673
+ f"- Start: {start_display}\n"
1674
+ f"- End: {end_display}\n"
1675
+ f"- Auto-decline: {effective_decline_mode}\n"
1676
+ f"- Decline message: {decline_message or '(none)'}\n"
1677
+ f"- Chat status: {validated_chat_status or '(default)'}\n"
1678
+ f"- Event ID: {event_id}\n"
1679
+ f"- Link: {link}"
1680
+ )
1681
+
1682
+ logger.info(
1683
+ f"Focus Time event created successfully for {user_google_email}. ID: {event_id}"
1684
+ )
1685
+ return confirmation
1686
+
1687
+
1688
+ async def _list_focus_time_events_impl(
1689
+ service,
1690
+ user_google_email: str,
1691
+ calendar_id: str = "primary",
1692
+ time_min: Optional[str] = None,
1693
+ time_max: Optional[str] = None,
1694
+ max_results: int = 10,
1695
+ timezone: Optional[str] = None,
1696
+ page_token: Optional[str] = None,
1697
+ ) -> str:
1698
+ """Internal implementation for listing Focus Time calendar events."""
1699
+ logger.info(
1700
+ f"[list_focus_time_events] Invoked. Email: '{user_google_email}', time_min: {time_min}, time_max: {time_max}, timezone: {timezone}"
1701
+ )
1702
+
1703
+ formatted_time_min = _correct_time_format_for_api(time_min, "time_min", timezone)
1704
+ if page_token and formatted_time_min is None:
1705
+ raise UserInputError(
1706
+ "[list_focus_time_events] page_token requires time_min. Pass the Pagination "
1707
+ "time_min from the previous response to preserve the original range."
1708
+ )
1709
+ if formatted_time_min:
1710
+ effective_time_min = formatted_time_min
1711
+ else:
1712
+ if timezone:
1713
+ try:
1714
+ tz = pytz.timezone(timezone)
1715
+ now = datetime.datetime.now(tz)
1716
+ effective_time_min = (
1717
+ now.astimezone(datetime.timezone.utc)
1718
+ .isoformat()
1719
+ .replace("+00:00", "Z")
1720
+ )
1721
+ except pytz.exceptions.UnknownTimeZoneError:
1722
+ logger.warning(
1723
+ f"Could not apply timezone '{timezone}', falling back to UTC"
1724
+ )
1725
+ utc_now = datetime.datetime.now(datetime.timezone.utc)
1726
+ effective_time_min = utc_now.isoformat().replace("+00:00", "Z")
1727
+ else:
1728
+ utc_now = datetime.datetime.now(datetime.timezone.utc)
1729
+ effective_time_min = utc_now.isoformat().replace("+00:00", "Z")
1730
+
1731
+ effective_time_max = _correct_time_format_for_api(time_max, "time_max", timezone)
1732
+
1733
+ request_params: Dict[str, Any] = {
1734
+ "calendarId": calendar_id,
1735
+ "timeMin": effective_time_min,
1736
+ "maxResults": max_results,
1737
+ "singleEvents": True,
1738
+ "orderBy": "startTime",
1739
+ "eventTypes": ["focusTime"],
1740
+ }
1741
+ if effective_time_max:
1742
+ request_params["timeMax"] = effective_time_max
1743
+ if page_token:
1744
+ request_params["pageToken"] = page_token
1745
+
1746
+ events_result = await asyncio.to_thread(
1747
+ lambda: service.events().list(**request_params).execute()
1748
+ )
1749
+ items = events_result.get("items", [])
1750
+ next_page_token = events_result.get("nextPageToken")
1751
+ pagination_info = ""
1752
+ if next_page_token:
1753
+ pagination_info = (
1754
+ f"Next page token: {next_page_token}"
1755
+ f"\nPagination time_min: {effective_time_min}"
1756
+ )
1757
+
1758
+ if not items:
1759
+ if next_page_token:
1760
+ return (
1761
+ f"No Focus Time events on this page for {user_google_email}, and more pages remain."
1762
+ f"\n{pagination_info}"
1763
+ )
1764
+ return f"No Focus Time events found for {user_google_email}."
1765
+
1766
+ lines = [f"Found {len(items)} Focus Time event(s) for {user_google_email}:\n"]
1767
+ for i, item in enumerate(items, 1):
1768
+ summary = item.get("summary", "Focus Time")
1769
+ start = item.get("start", {}).get(
1770
+ "date", item.get("start", {}).get("dateTime", "N/A")
1771
+ )
1772
+ end = item.get("end", {}).get(
1773
+ "date", item.get("end", {}).get("dateTime", "N/A")
1774
+ )
1775
+ event_id = item.get("id", "N/A")
1776
+ ft_props = item.get("focusTimeProperties", {})
1777
+ decline_mode = ft_props.get("autoDeclineMode", "N/A")
1778
+ decline_msg = ft_props.get("declineMessage", "")
1779
+ chat_st = ft_props.get("chatStatus", "")
1780
+
1781
+ lines.append(f'{i}. "{summary}" ({start} to {end})')
1782
+ lines.append(f" Auto-decline: {decline_mode}")
1783
+ if decline_msg:
1784
+ lines.append(f" Decline message: {decline_msg}")
1785
+ if chat_st:
1786
+ lines.append(f" Chat status: {chat_st}")
1787
+ lines.append(f" Event ID: {event_id}")
1788
+ lines.append("")
1789
+
1790
+ if next_page_token:
1791
+ lines.append(pagination_info)
1792
+ return "\n".join(lines).rstrip()
1793
+
1794
+
1795
+ async def _update_focus_time_event_impl(
1796
+ service,
1797
+ user_google_email: str,
1798
+ event_id: str,
1799
+ calendar_id: str = "primary",
1800
+ start_time: Optional[str] = None,
1801
+ end_time: Optional[str] = None,
1802
+ summary: Optional[str] = None,
1803
+ description: Optional[str] = None,
1804
+ auto_decline_mode: Optional[str] = None,
1805
+ decline_message: Optional[str] = None,
1806
+ chat_status: Optional[str] = None,
1807
+ recurrence: Optional[List[str]] = None,
1808
+ timezone: Optional[str] = None,
1809
+ ) -> str:
1810
+ """Internal implementation for updating a Focus Time calendar event."""
1811
+ logger.info(
1812
+ f"[update_focus_time_event] Invoked. Email: '{user_google_email}', Event ID: {event_id}"
1813
+ )
1814
+
1815
+ existing_event = await asyncio.to_thread(
1816
+ lambda: service.events().get(calendarId=calendar_id, eventId=event_id).execute()
1817
+ )
1818
+
1819
+ if existing_event.get("eventType") != "focusTime":
1820
+ raise UserInputError(
1821
+ f"Event '{event_id}' is not a Focus Time event (type: '{existing_event.get('eventType', 'default')}'). "
1822
+ f"Use manage_event to update regular events."
1823
+ )
1824
+
1825
+ patch_body: Dict[str, Any] = {}
1826
+
1827
+ if summary is not None:
1828
+ patch_body["summary"] = summary
1829
+ if description is not None:
1830
+ patch_body["description"] = description
1831
+ if start_time is not None:
1832
+ patch_body["start"] = _status_event_time_entry(
1833
+ start_time, "Focus Time", timezone
1834
+ )
1835
+ if end_time is not None:
1836
+ patch_body["end"] = _status_event_time_entry(end_time, "Focus Time", timezone)
1837
+ if recurrence is not None:
1838
+ patch_body["recurrence"] = recurrence
1839
+
1840
+ if (
1841
+ auto_decline_mode is not None
1842
+ or decline_message is not None
1843
+ or chat_status is not None
1844
+ ):
1845
+ existing_ft_props = existing_event.get("focusTimeProperties", {})
1846
+ updated_ft_props: Dict[str, str] = {
1847
+ "autoDeclineMode": _validate_auto_decline_mode(
1848
+ auto_decline_mode, "update_focus_time_event"
1849
+ )
1850
+ if auto_decline_mode is not None
1851
+ else existing_ft_props.get(
1852
+ "autoDeclineMode", "declineAllConflictingInvitations"
1853
+ ),
1854
+ "declineMessage": decline_message
1855
+ if decline_message is not None
1856
+ else existing_ft_props.get("declineMessage", ""),
1857
+ }
1858
+ if chat_status is not None:
1859
+ validated = _validate_chat_status(chat_status, "update_focus_time_event")
1860
+ updated_ft_props["chatStatus"] = validated
1861
+ elif existing_ft_props.get("chatStatus"):
1862
+ updated_ft_props["chatStatus"] = existing_ft_props["chatStatus"]
1863
+ patch_body["focusTimeProperties"] = updated_ft_props
1864
+
1865
+ if not patch_body:
1866
+ return f"No changes specified for Focus Time event '{event_id}'."
1867
+
1868
+ updated_event = await asyncio.to_thread(
1869
+ lambda: (
1870
+ service.events()
1871
+ .patch(calendarId=calendar_id, eventId=event_id, body=patch_body)
1872
+ .execute()
1873
+ )
1874
+ )
1875
+
1876
+ link = updated_event.get("htmlLink", "N/A")
1877
+ start_display = updated_event.get("start", {}).get(
1878
+ "date", updated_event.get("start", {}).get("dateTime", "N/A")
1879
+ )
1880
+ end_display = updated_event.get("end", {}).get(
1881
+ "date", updated_event.get("end", {}).get("dateTime", "N/A")
1882
+ )
1883
+
1884
+ confirmation = (
1885
+ f"Successfully updated Focus Time event (ID: {event_id}) for {user_google_email}.\n"
1886
+ f"- Summary: {updated_event.get('summary', 'Focus Time')}\n"
1887
+ f"- Start: {start_display}\n"
1888
+ f"- End: {end_display}\n"
1889
+ f"- Link: {link}"
1890
+ )
1891
+
1892
+ logger.info(
1893
+ f"Focus Time event updated successfully for {user_google_email}. ID: {event_id}"
1894
+ )
1895
+ return confirmation
1896
+
1897
+
1898
+ async def _delete_focus_time_event_impl(
1899
+ service,
1900
+ user_google_email: str,
1901
+ event_id: str,
1902
+ calendar_id: str = "primary",
1903
+ ) -> str:
1904
+ """Internal implementation for deleting a Focus Time calendar event."""
1905
+ logger.info(
1906
+ f"[delete_focus_time_event] Invoked. Email: '{user_google_email}', Event ID: {event_id}"
1907
+ )
1908
+
1909
+ try:
1910
+ existing_event = await asyncio.to_thread(
1911
+ lambda: (
1912
+ service.events().get(calendarId=calendar_id, eventId=event_id).execute()
1913
+ )
1914
+ )
1915
+ if existing_event.get("eventType") != "focusTime":
1916
+ raise UserInputError(
1917
+ f"Event '{event_id}' is not a Focus Time event (type: '{existing_event.get('eventType', 'default')}'). "
1918
+ f"Use manage_event to delete regular events."
1919
+ )
1920
+ except HttpError as get_error:
1921
+ if get_error.resp.status == 404:
1922
+ raise Exception(
1923
+ f"Event not found. The event with ID '{event_id}' could not be found in calendar '{calendar_id}'."
1924
+ )
1925
+ else:
1926
+ raise
1927
+
1928
+ await asyncio.to_thread(
1929
+ lambda: (
1930
+ service.events().delete(calendarId=calendar_id, eventId=event_id).execute()
1931
+ )
1932
+ )
1933
+
1934
+ confirmation = f"Successfully deleted Focus Time event (ID: {event_id}) from calendar '{calendar_id}' for {user_google_email}."
1935
+ logger.info(
1936
+ f"Focus Time event deleted successfully for {user_google_email}. ID: {event_id}"
1937
+ )
1938
+ return confirmation
1939
+
1940
+
1941
+ @server.tool(
1942
+ title="Manage Focus Time",
1943
+ annotations=ToolAnnotations(
1944
+ readOnlyHint=False,
1945
+ destructiveHint=True,
1946
+ idempotentHint=False,
1947
+ openWorldHint=True,
1948
+ ),
1949
+ )
1950
+ @handle_http_errors("manage_focus_time", service_type="calendar")
1951
+ @require_google_service("calendar", "calendar_events")
1952
+ async def manage_focus_time(
1953
+ service,
1954
+ user_google_email: str,
1955
+ action: str,
1956
+ start_time: Optional[str] = None,
1957
+ end_time: Optional[str] = None,
1958
+ summary: Optional[str] = None,
1959
+ description: Optional[str] = None,
1960
+ auto_decline_mode: Optional[str] = None,
1961
+ decline_message: Optional[str] = None,
1962
+ chat_status: Optional[str] = None,
1963
+ recurrence: Optional[StringList] = None,
1964
+ timezone: Optional[str] = None,
1965
+ time_min: Optional[str] = None,
1966
+ time_max: Optional[str] = None,
1967
+ max_results: int = 10,
1968
+ event_id: Optional[str] = None,
1969
+ calendar_id: str = "primary",
1970
+ page_token: Optional[str] = None,
1971
+ ) -> str:
1972
+ """
1973
+ Manages Focus Time events on Google Calendar. These special events auto-decline
1974
+ meeting invitations and, by default, set the user's chat status to Do Not
1975
+ Disturb, helping protect blocks of uninterrupted work time.
1976
+
1977
+ Args:
1978
+ user_google_email (str): The user's Google email address. Required.
1979
+ action (str): Action to perform - "create", "list", "update", or "delete".
1980
+ start_time (Optional[str]): Start date/time. Use 'YYYY-MM-DD' for full-day or RFC3339 for partial-day (e.g., '2024-04-05T09:00:00Z'). Date-only values are auto-converted to dateTime (midnight-to-midnight). Required for create.
1981
+ end_time (Optional[str]): End date/time (exclusive). Same format as start_time. For a single full day on April 5, use start_time='2026-04-05' and end_time='2026-04-06'. Required for create.
1982
+ summary (Optional[str]): Display text on the calendar. Defaults to "Focus Time".
1983
+ description (Optional[str]): Event description. Useful for adding context about what the focus time is for.
1984
+ auto_decline_mode (Optional[str]): How to handle conflicting invitations. One of: "declineAllConflictingInvitations" (default), "declineOnlyNewConflictingInvitations", "declineNone".
1985
+ decline_message (Optional[str]): Message included when auto-declining invitations.
1986
+ chat_status (Optional[str]): Google Chat status during the focus time. Supports "doNotDisturb" (default) and "available".
1987
+ recurrence (Optional[List[str]]): RFC5545 recurrence rules for a recurring Focus Time series, e.g. ["RRULE:FREQ=WEEKLY;COUNT=10"].
1988
+ timezone (Optional[str]): Timezone for the event (e.g., "America/New_York", "Europe/London"). Required when using date-only values or dateTime values without an explicit UTC offset.
1989
+ time_min (Optional[str]): For "list" action: start of time range. Defaults to current time. Recurring series are expanded into individual instances in the requested range.
1990
+ time_max (Optional[str]): For "list" action: end of time range.
1991
+ max_results (int): For "list" action: maximum events to return in one page. Defaults to 10.
1992
+ event_id (Optional[str]): Event ID. Required for "update" and "delete" actions.
1993
+ calendar_id (str): Calendar ID. Defaults to 'primary'. Focus Time status events live on primary calendars, so use 'primary' or a user's primary calendar ID/email rather than a secondary calendar ID.
1994
+ page_token (Optional[str]): For "list" action: token for the next page, taken from a previous response. Also pass the response's Pagination time_min as time_min, even if omitted on the first call. Keep all other query parameters unchanged.
1995
+
1996
+ Returns:
1997
+ str: Confirmation message with event details, or a formatted list of Focus Time events.
1998
+ """
1999
+ action_lower = action.lower().strip()
2000
+ if action_lower == "create":
2001
+ if not start_time or not end_time:
2002
+ raise UserInputError(
2003
+ "start_time and end_time are required for create action"
2004
+ )
2005
+ return await _create_focus_time_event_impl(
2006
+ service=service,
2007
+ user_google_email=user_google_email,
2008
+ start_time=start_time,
2009
+ end_time=end_time,
2010
+ calendar_id=calendar_id,
2011
+ summary=summary,
2012
+ description=description,
2013
+ auto_decline_mode=auto_decline_mode,
2014
+ decline_message=decline_message,
2015
+ chat_status=chat_status,
2016
+ recurrence=recurrence,
2017
+ timezone=timezone,
2018
+ )
2019
+ elif action_lower == "list":
2020
+ return await _list_focus_time_events_impl(
2021
+ service=service,
2022
+ user_google_email=user_google_email,
2023
+ calendar_id=calendar_id,
2024
+ time_min=time_min,
2025
+ time_max=time_max,
2026
+ max_results=max_results,
2027
+ timezone=timezone,
2028
+ page_token=page_token,
2029
+ )
2030
+ elif action_lower == "update":
2031
+ if not event_id:
2032
+ raise UserInputError("event_id is required for update action")
2033
+ return await _update_focus_time_event_impl(
2034
+ service=service,
2035
+ user_google_email=user_google_email,
2036
+ event_id=event_id,
2037
+ calendar_id=calendar_id,
2038
+ start_time=start_time,
2039
+ end_time=end_time,
2040
+ summary=summary,
2041
+ description=description,
2042
+ auto_decline_mode=auto_decline_mode,
2043
+ decline_message=decline_message,
2044
+ chat_status=chat_status,
2045
+ recurrence=recurrence,
2046
+ timezone=timezone,
2047
+ )
2048
+ elif action_lower == "delete":
2049
+ if not event_id:
2050
+ raise UserInputError("event_id is required for delete action")
2051
+ return await _delete_focus_time_event_impl(
2052
+ service=service,
2053
+ user_google_email=user_google_email,
2054
+ event_id=event_id,
2055
+ calendar_id=calendar_id,
2056
+ )
2057
+ else:
2058
+ raise UserInputError(
2059
+ f"Invalid action '{action_lower}'. Must be 'create', 'list', 'update', or 'delete'."
2060
+ )
2061
+
2062
+
2063
+ # ---------------------------------------------------------------------------
2064
+ # Legacy single-action tools (deprecated -- prefer ``manage_event``)
2065
+ # ---------------------------------------------------------------------------
2066
+
2067
+
2068
+ @server.tool(
2069
+ title="Query Freebusy",
2070
+ annotations=ToolAnnotations(
2071
+ readOnlyHint=True,
2072
+ destructiveHint=False,
2073
+ idempotentHint=True,
2074
+ openWorldHint=True,
2075
+ ),
2076
+ )
2077
+ @handle_http_errors("query_freebusy", is_read_only=True, service_type="calendar")
2078
+ @require_google_service("calendar", "calendar_read")
2079
+ async def query_freebusy(
2080
+ service,
2081
+ user_google_email: str,
2082
+ time_min: str,
2083
+ time_max: str,
2084
+ calendar_ids: Optional[StringList] = None,
2085
+ group_expansion_max: Optional[int] = None,
2086
+ calendar_expansion_max: Optional[int] = None,
2087
+ ) -> str:
2088
+ """
2089
+ Returns free/busy information for a set of calendars.
2090
+
2091
+ Args:
2092
+ user_google_email (str): The user's Google email address. Required.
2093
+ time_min (str): The start of the interval for the query in RFC3339 format (e.g., '2024-05-12T10:00:00Z' or '2024-05-12').
2094
+ time_max (str): The end of the interval for the query in RFC3339 format (e.g., '2024-05-12T18:00:00Z' or '2024-05-12').
2095
+ calendar_ids (Optional[List[str]]): List of calendar identifiers to query. If not provided, queries the primary calendar. Use 'primary' for the user's primary calendar or specific calendar IDs obtained from `list_calendars`.
2096
+ group_expansion_max (Optional[int]): Maximum number of calendar identifiers to be provided for a single group. Optional. An error is returned for a group with more members than this value. Maximum value is 100.
2097
+ calendar_expansion_max (Optional[int]): Maximum number of calendars for which FreeBusy information is to be provided. Optional. Maximum value is 50.
2098
+
2099
+ Returns:
2100
+ str: A formatted response showing free/busy information for each requested calendar, including busy time periods.
2101
+ """
2102
+ logger.info(
2103
+ f"[query_freebusy] Invoked. Email: '{user_google_email}', time_min: '{time_min}', time_max: '{time_max}'"
2104
+ )
2105
+
2106
+ # Format time parameters
2107
+ formatted_time_min = _correct_time_format_for_api(time_min, "time_min", None)
2108
+ formatted_time_max = _correct_time_format_for_api(time_max, "time_max", None)
2109
+
2110
+ # Default to primary calendar if no calendar IDs provided
2111
+ if not calendar_ids:
2112
+ calendar_ids = ["primary"]
2113
+
2114
+ # Build the request body
2115
+ request_body: Dict[str, Any] = {
2116
+ "timeMin": formatted_time_min,
2117
+ "timeMax": formatted_time_max,
2118
+ "items": [{"id": cal_id} for cal_id in calendar_ids],
2119
+ }
2120
+
2121
+ if group_expansion_max is not None:
2122
+ request_body["groupExpansionMax"] = group_expansion_max
2123
+ if calendar_expansion_max is not None:
2124
+ request_body["calendarExpansionMax"] = calendar_expansion_max
2125
+
2126
+ logger.info(
2127
+ f"[query_freebusy] Request body: timeMin={formatted_time_min}, timeMax={formatted_time_max}, calendar_count={len(calendar_ids)}"
2128
+ )
2129
+
2130
+ # Execute the freebusy query
2131
+ freebusy_result = await asyncio.to_thread(
2132
+ lambda: service.freebusy().query(body=request_body).execute()
2133
+ )
2134
+
2135
+ # Parse the response
2136
+ calendars = freebusy_result.get("calendars", {})
2137
+ time_min_result = freebusy_result.get("timeMin", formatted_time_min)
2138
+ time_max_result = freebusy_result.get("timeMax", formatted_time_max)
2139
+
2140
+ if not calendars:
2141
+ return f"No free/busy information found for the requested calendars for {user_google_email}."
2142
+
2143
+ # Format the output
2144
+ output_lines = [
2145
+ f"Free/Busy information for {user_google_email}:",
2146
+ f"Time range: {time_min_result} to {time_max_result}",
2147
+ "",
2148
+ ]
2149
+
2150
+ for cal_id, cal_data in calendars.items():
2151
+ output_lines.append(f"Calendar: {cal_id}")
2152
+
2153
+ # Check for errors
2154
+ errors = cal_data.get("errors", [])
2155
+ if errors:
2156
+ output_lines.append(" Errors:")
2157
+ for error in errors:
2158
+ domain = error.get("domain", "unknown")
2159
+ reason = error.get("reason", "unknown")
2160
+ output_lines.append(f" - {domain}: {reason}")
2161
+ output_lines.append("")
2162
+ continue
2163
+
2164
+ # Get busy periods
2165
+ busy_periods = cal_data.get("busy", [])
2166
+ if not busy_periods:
2167
+ output_lines.append(" Status: Free (no busy periods)")
2168
+ else:
2169
+ output_lines.append(f" Busy periods: {len(busy_periods)}")
2170
+ for period in busy_periods:
2171
+ start = period.get("start", "Unknown")
2172
+ end = period.get("end", "Unknown")
2173
+ output_lines.append(f" - {start} to {end}")
2174
+
2175
+ output_lines.append("")
2176
+
2177
+ result_text = "\n".join(output_lines)
2178
+ logger.info(
2179
+ f"[query_freebusy] Successfully retrieved free/busy information for {len(calendars)} calendar(s)"
2180
+ )
2181
+ return result_text
2182
+
2183
+
2184
+ @server.tool(
2185
+ title="Manage Calendar",
2186
+ annotations=ToolAnnotations(
2187
+ readOnlyHint=False,
2188
+ destructiveHint=True,
2189
+ idempotentHint=False,
2190
+ openWorldHint=True,
2191
+ ),
2192
+ )
2193
+ @handle_http_errors("manage_calendar", service_type="calendar")
2194
+ @require_google_service("calendar", "calendar")
2195
+ async def manage_calendar(
2196
+ service,
2197
+ user_google_email: str,
2198
+ action: str,
2199
+ summary: Optional[str] = None,
2200
+ description: Optional[str] = None,
2201
+ timezone: Optional[str] = None,
2202
+ calendar_id: str = "primary",
2203
+ role: Optional[str] = None,
2204
+ scope_type: str = "user",
2205
+ scope_value: Optional[str] = None,
2206
+ rule_id: Optional[str] = None,
2207
+ send_notifications: bool = True,
2208
+ page_token: Optional[str] = None,
2209
+ ) -> str:
2210
+ """
2211
+ Creates secondary Google Calendars and manages who a calendar is shared with (its access control rules).
2212
+
2213
+ Args:
2214
+ user_google_email (str): The user's Google email address. Required.
2215
+ action (str): Action to perform. One of:
2216
+ - "create": Create a new secondary calendar. Uses summary, description, timezone.
2217
+ - "list_sharing": List the calendar's sharing rules. Uses calendar_id, page_token.
2218
+ - "share": Grant access to the calendar. Uses calendar_id, role, scope_type, scope_value, send_notifications.
2219
+ - "update_sharing": Change the role of an existing rule. Uses calendar_id, rule_id, role, send_notifications.
2220
+ - "unshare": Remove an existing rule. Uses calendar_id, rule_id.
2221
+ summary (Optional[str]): The title/name of the new calendar. Required for "create".
2222
+ description (Optional[str]): An optional description for the new calendar. Used by "create".
2223
+ timezone (Optional[str]): IANA timezone for the new calendar (e.g. 'America/New_York'). Used by "create".
2224
+ calendar_id (str): Calendar ID for the sharing actions. Defaults to 'primary'.
2225
+ role (Optional[str]): Access level for "share" and "update_sharing". One of: "freeBusyReader", "reader", "writerWithoutPrivateAccess", "writer", "owner", "none".
2226
+ scope_type (str): Who "share" grants access to: "user", "group", "domain", or "default" (public). Defaults to "user".
2227
+ scope_value (Optional[str]): Email address for "user"/"group" or domain name for "domain". Required for "share" unless scope_type is "default".
2228
+ rule_id (Optional[str]): Rule ID from "list_sharing" (e.g. "user:alice@example.com"). Required for "update_sharing" and "unshare".
2229
+ send_notifications (bool): Whether to email the grantee on "share" and "update_sharing". Defaults to True.
2230
+ page_token (Optional[str]): For "list_sharing" action: token for the next page, taken from a previous response.
2231
+
2232
+ Returns:
2233
+ str: The new calendar's summary and ID, the calendar's sharing rules, or a confirmation of the rule that changed.
2234
+ """
2235
+ logger.info(
2236
+ f"[manage_calendar] Invoked. Email: '{user_google_email}', Action: '{action}'"
2237
+ )
2238
+ action = action.lower().strip()
2239
+ if action == "create":
2240
+ return await _create_calendar(service, summary, description, timezone)
2241
+ return await _manage_calendar_acl(
2242
+ service,
2243
+ user_google_email=user_google_email,
2244
+ action=action,
2245
+ calendar_id=calendar_id,
2246
+ role=role,
2247
+ scope_type=scope_type,
2248
+ scope_value=scope_value,
2249
+ rule_id=rule_id,
2250
+ send_notifications=send_notifications,
2251
+ page_token=page_token,
2252
+ )