Repository navigation
Expand file tree
/
Copy pathcalendar_tools.py
More file actions
2215 lines (2002 loc) · 91.2 KB
/
Copy pathcalendar_tools.py
File metadata and controls
2215 lines (2002 loc) · 91.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Google Calendar MCP Tools
This module provides MCP tools for interacting with Google Calendar API.
"""
import datetime
import logging
import asyncio
import uuid
from typing import List, Optional, Dict, Any, Union
import pytz
from googleapiclient.errors import HttpError
from auth.service_decorator import require_google_service
from core.utils import handle_http_errors, StringList, StringOrDictList, UserInputError
from gcalendar.calendar_helpers import (
_apply_transparency_if_valid,
_apply_visibility_if_valid,
_build_attachment_entries,
_build_time_boundary,
_correct_time_format_for_api,
_create_calendar,
_format_event_detail_lines,
_format_event_time,
_get_meeting_link,
_manage_calendar_acl,
_normalize_attendees,
_parse_reminders_json,
_preserve_existing_fields,
_resolve_color_id,
_resolve_conference_data,
_saved_event_times,
_split_recurring_event,
_status_event_time_entry,
_validate_auto_decline_mode,
_validate_chat_status,
)
from mcp.types import ToolAnnotations
from core.server import server
# Configure module logger
logger = logging.getLogger(__name__)
@server.tool(
title="List Calendars",
annotations=ToolAnnotations(
readOnlyHint=True,
destructiveHint=False,
idempotentHint=True,
openWorldHint=True,
),
)
@handle_http_errors("list_calendars", is_read_only=True, service_type="calendar")
@require_google_service("calendar", "calendar_read")
async def list_calendars(
service,
user_google_email: str,
max_results: Optional[int] = None,
page_token: Optional[str] = None,
) -> str:
"""
Retrieves a list of calendars accessible to the authenticated user.
Args:
user_google_email (str): The user's Google email address. Required.
max_results (Optional[int]): Maximum calendars to return in one page. Omit to use the API default.
page_token (Optional[str]): Token for the next page, taken from a previous response.
Returns:
str: A formatted list of the user's calendars (summary, ID, primary status, time zone).
When more calendars remain, a "Next page token" line is appended.
"""
logger.info(f"[list_calendars] Invoked. Email: '{user_google_email}'")
params: Dict[str, Any] = {}
if max_results is not None:
params["maxResults"] = max_results
if page_token:
params["pageToken"] = page_token
calendar_list_response = await asyncio.to_thread(
lambda: service.calendarList().list(**params).execute()
)
items = calendar_list_response.get("items", [])
next_page_token = calendar_list_response.get("nextPageToken")
if not items:
if next_page_token:
return (
f"No calendars on this page for {user_google_email}, and more pages remain."
f"\nNext page token: {next_page_token}"
)
return f"No calendars found for {user_google_email}."
calendars_summary_list = []
for cal in items:
line = f'- "{cal.get("summary", "No Summary")}"{" (Primary)" if cal.get("primary") else ""} (ID: {cal["id"]})'
if cal.get("timeZone"):
line += f" (Time zone: {cal['timeZone']})"
calendars_summary_list.append(line)
text_output = (
f"Successfully listed {len(items)} calendars for {user_google_email}:\n"
+ "\n".join(calendars_summary_list)
)
if next_page_token:
text_output += f"\n\nNext page token: {next_page_token}"
logger.info(f"Successfully listed {len(items)} calendars for {user_google_email}.")
return text_output
@server.tool(
title="Get Events",
annotations=ToolAnnotations(
readOnlyHint=True,
destructiveHint=False,
idempotentHint=True,
openWorldHint=True,
),
)
@handle_http_errors("get_events", is_read_only=True, service_type="calendar")
@require_google_service("calendar", "calendar_read")
async def get_events(
service,
user_google_email: str,
calendar_id: str = "primary",
event_id: Optional[str] = None,
time_min: Optional[str] = None,
time_max: Optional[str] = None,
max_results: int = 25,
query: Optional[str] = None,
detailed: bool = False,
include_attachments: bool = False,
single_events: bool = True,
page_token: Optional[str] = None,
) -> str:
"""
Retrieves events from a specified Google Calendar. Can retrieve a single event by ID or multiple events within a time range.
You can also search for events by keyword by supplying the optional "query" param.
Args:
user_google_email (str): The user's Google email address. Required.
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`.
event_id (Optional[str]): The ID of a specific event to retrieve. If provided, retrieves only this event and ignores time filtering parameters.
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.
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.
max_results (int): The maximum number of events to return in one page. Defaults to 25. Ignored if event_id is provided.
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.
query (Optional[str]): A keyword to search for within event fields (summary, description, location). Ignored if event_id is provided.
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.
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.
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.
Returns:
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.
"""
logger.info(
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}"
)
next_page_token: Optional[str] = None
pagination_info = ""
# Handle single event retrieval
if event_id:
logger.info(f"[get_events] Retrieving single event with ID: {event_id}")
event = await asyncio.to_thread(
lambda: (
service.events().get(calendarId=calendar_id, eventId=event_id).execute()
)
)
items = [event]
else:
# Handle multiple events retrieval with time filtering
# Normalize before validating: blank and null-like strings also default
# to "now", which would change the query between pages.
formatted_time_min = _correct_time_format_for_api(time_min, "time_min", None)
if page_token and formatted_time_min is None and single_events:
raise UserInputError(
"[get_events] page_token requires time_min. Pass the Pagination "
"time_min from the previous response to preserve the original range."
)
if formatted_time_min:
effective_time_min = formatted_time_min
elif single_events:
utc_now = datetime.datetime.now(datetime.timezone.utc)
effective_time_min = utc_now.isoformat().replace("+00:00", "Z")
else:
effective_time_min = None
if time_min is None:
if single_events:
logger.info(
f"time_min not provided, defaulting to current UTC time: {effective_time_min}"
)
else:
logger.info(
"time_min not provided for unexpanded events; omitting it so older recurring masters remain discoverable"
)
else:
logger.info(
f"time_min processing: original='{time_min}', formatted='{formatted_time_min}', effective='{effective_time_min}'"
)
effective_time_max = _correct_time_format_for_api(time_max, "time_max", None)
if time_max:
logger.info(
f"time_max processing: original='{time_max}', formatted='{effective_time_max}'"
)
logger.info(
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}"
)
# Build the request parameters dynamically
request_params = {
"calendarId": calendar_id,
"timeMax": effective_time_max,
"maxResults": max_results,
"singleEvents": single_events,
}
if effective_time_min:
request_params["timeMin"] = effective_time_min
# The Calendar API only permits start-time ordering when recurring
# series are expanded. Unexpanded results retain the API's stable
# default ordering and expose the master event's recurrence array.
if single_events:
request_params["orderBy"] = "startTime"
if query:
request_params["q"] = query
if page_token:
request_params["pageToken"] = page_token
events_result = await asyncio.to_thread(
lambda: service.events().list(**request_params).execute()
)
items = events_result.get("items", [])
next_page_token = events_result.get("nextPageToken")
if next_page_token:
pagination_info = f"Next page token: {next_page_token}"
if effective_time_min:
pagination_info += f"\nPagination time_min: {effective_time_min}"
if not items:
if event_id:
return f"Event with ID '{event_id}' not found in calendar '{calendar_id}' for {user_google_email}."
elif next_page_token:
# The API can return an empty page with more pages behind it, so
# "no events" would be untrue here.
return (
f"No events on this page in calendar '{calendar_id}' for {user_google_email}"
f" for the specified time range, and more pages remain."
f"\n{pagination_info}"
)
else:
return f"No events found in calendar '{calendar_id}' for {user_google_email} for the specified time range."
# Handle returning detailed output for a single event when requested
if event_id and detailed:
item = items[0]
summary = item.get("summary", "No Title")
start = _format_event_time(item, "start")
end = _format_event_time(item, "end")
link = item.get("htmlLink", "No Link")
event_details = (
f"Event Details:\n- Title: {summary}\n- Starts: {start}\n- Ends: {end}\n"
)
event_details += _format_event_detail_lines(
item,
prefix="- ",
indent=" ",
include_attachments=include_attachments,
)
event_details += f"- Event ID: {event_id}\n- Link: {link}"
logger.info(
f"[get_events] Successfully retrieved detailed event {event_id} for {user_google_email}."
)
return event_details
# Handle multiple events or single event with basic output
event_details_list = []
for item in items:
summary = item.get("summary", "No Title")
start_time = _format_event_time(item, "start")
end_time = _format_event_time(item, "end")
link = item.get("htmlLink", "No Link")
item_event_id = item.get("id", "No ID")
if detailed:
# Add detailed information for multiple events
event_detail_parts = (
f'- "{summary}" (Starts: {start_time}, Ends: {end_time})\n'
+ _format_event_detail_lines(
item,
prefix=" ",
indent=" ",
include_attachments=include_attachments,
)
+ f" ID: {item_event_id} | Link: {link}"
)
event_details_list.append(event_detail_parts)
else:
# Basic output format
meeting_link = _get_meeting_link(item)
basic_line = f'- "{summary}" (Starts: {start_time}, Ends: {end_time})'
if item.get("status") == "cancelled":
basic_line += " Status: cancelled"
if meeting_link:
basic_line += f" Meeting: {meeting_link}"
basic_line += f" ID: {item_event_id} | Link: {link}"
event_details_list.append(basic_line)
if event_id:
# Single event basic output
text_output = (
f"Successfully retrieved event from calendar '{calendar_id}' for {user_google_email}:\n"
+ "\n".join(event_details_list)
)
else:
# Multiple events output
text_output = (
f"Successfully retrieved {len(items)} events from calendar '{calendar_id}' for {user_google_email}:\n"
+ "\n".join(event_details_list)
)
if next_page_token:
text_output += f"\n\n{pagination_info}"
logger.info(f"Successfully retrieved {len(items)} events for {user_google_email}.")
return text_output
# ---------------------------------------------------------------------------
# Internal implementation functions for event create/modify/delete.
# These are called by both the consolidated ``manage_event`` tool and the
# legacy single-action tools.
# ---------------------------------------------------------------------------
async def _create_event_impl(
service,
user_google_email: str,
summary: str,
start_time: str,
end_time: str,
calendar_id: str = "primary",
description: Optional[str] = None,
location: Optional[str] = None,
attendees: Optional[List[Union[str, Dict[str, Any]]]] = None,
timezone: Optional[str] = None,
attachments: Optional[List[str]] = None,
add_google_meet: bool = False,
conference_data: Optional[Dict[str, Any]] = None,
reminders: Optional[Union[str, List[Dict[str, Any]]]] = None,
use_default_reminders: bool = True,
transparency: Optional[str] = None,
visibility: Optional[str] = None,
color_id: Optional[str] = None,
recurrence: Optional[List[str]] = None,
guests_can_modify: Optional[bool] = None,
guests_can_invite_others: Optional[bool] = None,
guests_can_see_other_guests: Optional[bool] = None,
send_updates: str = "all",
*,
start_timezone: Optional[str] = None,
end_timezone: Optional[str] = None,
) -> str:
"""Internal implementation for creating a calendar event."""
logger.info(
f"[create_event] Invoked. Email: '{user_google_email}', summary_len={len(summary) if summary else 0}"
)
logger.debug(f"[create_event] Incoming attachments param: {attachments}")
# If attachments value is a string, split by comma and strip whitespace
if attachments and isinstance(attachments, str):
attachments = [a.strip() for a in attachments.split(",") if a.strip()]
logger.debug(
f"[create_event] Parsed attachments list from string: {attachments}"
)
# Each boundary resolves its own zone, falling back to the event-wide timezone.
event_body: Dict[str, Any] = {
"summary": summary,
"start": _build_time_boundary(
start_time, start_timezone if start_timezone is not None else timezone
),
"end": _build_time_boundary(
end_time, end_timezone if end_timezone is not None else timezone
),
}
if recurrence:
event_body["recurrence"] = recurrence
if location:
event_body["location"] = location
if description:
event_body["description"] = description
normalized_attendees = _normalize_attendees(attendees)
if normalized_attendees is not None:
event_body["attendees"] = normalized_attendees
if color_id is not None:
event_body["colorId"] = color_id
# Handle reminders
if reminders is not None or not use_default_reminders:
# If custom reminders are provided, automatically disable default reminders
effective_use_default = use_default_reminders and reminders is None
reminder_data = {"useDefault": effective_use_default}
if reminders is not None:
validated_reminders = _parse_reminders_json(reminders, "create_event")
if validated_reminders:
reminder_data["overrides"] = validated_reminders
logger.info(
f"[create_event] Added {len(validated_reminders)} custom reminders"
)
if use_default_reminders:
logger.info(
"[create_event] Custom reminders provided - disabling default reminders"
)
event_body["reminders"] = reminder_data
# Handle transparency validation
_apply_transparency_if_valid(event_body, transparency, "create_event")
# Handle visibility validation
_apply_visibility_if_valid(event_body, visibility, "create_event")
# Handle guest permissions
if guests_can_modify is not None:
event_body["guestsCanModify"] = guests_can_modify
logger.info(f"[create_event] Set guestsCanModify to {guests_can_modify}")
if guests_can_invite_others is not None:
event_body["guestsCanInviteOthers"] = guests_can_invite_others
logger.info(
f"[create_event] Set guestsCanInviteOthers to {guests_can_invite_others}"
)
if guests_can_see_other_guests is not None:
event_body["guestsCanSeeOtherGuests"] = guests_can_see_other_guests
logger.info(
f"[create_event] Set guestsCanSeeOtherGuests to {guests_can_see_other_guests}"
)
if add_google_meet:
request_id = str(uuid.uuid4())
event_body["conferenceData"] = {
"createRequest": {
"requestId": request_id,
"conferenceSolutionKey": {"type": "hangoutsMeet"},
}
}
logger.info(
f"[create_event] Adding Google Meet conference with request ID: {request_id}"
)
elif conference_data is not None:
event_body["conferenceData"] = conference_data
logger.info("[create_event] Attaching pre-generated conference data")
# conferenceDataVersion=1 is required whenever conferenceData is present,
# whether it's a native Meet create request or a pre-generated add-on payload.
conference_data_version = (
1 if (add_google_meet or conference_data is not None) else 0
)
if attachments:
event_body["attachments"] = await _build_attachment_entries(
service, attachments, "create_event"
)
created_event = await asyncio.to_thread(
lambda: (
service.events()
.insert(
calendarId=calendar_id,
body=event_body,
supportsAttachments=True,
conferenceDataVersion=conference_data_version,
sendUpdates=send_updates,
)
.execute()
)
)
else:
created_event = await asyncio.to_thread(
lambda: (
service.events()
.insert(
calendarId=calendar_id,
body=event_body,
conferenceDataVersion=conference_data_version,
sendUpdates=send_updates,
)
.execute()
)
)
link = created_event.get("htmlLink", "No link available")
confirmation_message = f"Successfully created event '{created_event.get('summary', summary)}' for {user_google_email}. Link: {link}"
confirmation_message += _saved_event_times(created_event)
# Surface the conferencing link (native Meet or third-party add-on) if present
if add_google_meet or conference_data is not None:
meeting_link = _get_meeting_link(created_event)
if meeting_link:
label = "Google Meet" if add_google_meet else "Conference"
confirmation_message += f" {label}: {meeting_link}"
logger.info(
f"Event created successfully for {user_google_email}. ID: {created_event.get('id')}, Link: {link}"
)
return confirmation_message
async def _modify_event_impl(
service,
user_google_email: str,
event_id: str,
calendar_id: str = "primary",
summary: Optional[str] = None,
start_time: Optional[str] = None,
end_time: Optional[str] = None,
description: Optional[str] = None,
location: Optional[str] = None,
attendees: Optional[List[Union[str, Dict[str, Any]]]] = None,
timezone: Optional[str] = None,
add_google_meet: Optional[bool] = None,
conference_data: Optional[Dict[str, Any]] = None,
reminders: Optional[Union[str, List[Dict[str, Any]]]] = None,
use_default_reminders: Optional[bool] = None,
transparency: Optional[str] = None,
visibility: Optional[str] = None,
color_id: Optional[str] = None,
recurrence: Optional[List[str]] = None,
guests_can_modify: Optional[bool] = None,
guests_can_invite_others: Optional[bool] = None,
guests_can_see_other_guests: Optional[bool] = None,
attachments: Optional[Union[str, List[str]]] = None,
send_updates: str = "all",
*,
start_timezone: Optional[str] = None,
end_timezone: Optional[str] = None,
this_and_following: bool = False,
) -> str:
"""Internal implementation for modifying a calendar event."""
logger.info(
f"[modify_event] Invoked. Email: '{user_google_email}', Event ID: {event_id}"
)
# Build the event body with only the fields that are provided
event_body: Dict[str, Any] = {}
if summary is not None:
event_body["summary"] = summary
if start_time is not None:
event_body["start"] = _build_time_boundary(
start_time, start_timezone if start_timezone is not None else timezone
)
if end_time is not None:
event_body["end"] = _build_time_boundary(
end_time, end_timezone if end_timezone is not None else timezone
)
if description is not None:
event_body["description"] = description
if location is not None:
event_body["location"] = location
# Normalize attendees - accepts both email strings and full attendee objects
normalized_attendees = _normalize_attendees(attendees)
if normalized_attendees is not None:
event_body["attendees"] = normalized_attendees
if color_id is not None:
event_body["colorId"] = color_id
if recurrence is not None:
event_body["recurrence"] = recurrence
# Handle reminders
if reminders is not None or use_default_reminders is not None:
reminder_data = {}
if use_default_reminders is not None:
reminder_data["useDefault"] = use_default_reminders
else:
# Preserve existing event's useDefault value if not explicitly specified
try:
existing_event = await asyncio.to_thread(
service.events()
.get(calendarId=calendar_id, eventId=event_id)
.execute
)
reminder_data["useDefault"] = existing_event.get("reminders", {}).get(
"useDefault", True
)
except Exception as e:
logger.warning(
f"[modify_event] Could not fetch existing event for reminders: {e}"
)
reminder_data["useDefault"] = (
True # Fallback to True if unable to fetch
)
# If custom reminders are provided, automatically disable default reminders
if reminders is not None:
if reminder_data.get("useDefault", False):
reminder_data["useDefault"] = False
logger.info(
"[modify_event] Custom reminders provided - disabling default reminders"
)
validated_reminders = _parse_reminders_json(reminders, "modify_event")
if reminders and not validated_reminders:
logger.warning(
"[modify_event] Reminders provided but failed validation. No custom reminders will be set."
)
elif validated_reminders:
reminder_data["overrides"] = validated_reminders
logger.info(
f"[modify_event] Updated reminders with {len(validated_reminders)} custom reminders"
)
event_body["reminders"] = reminder_data
# Handle transparency validation
_apply_transparency_if_valid(event_body, transparency, "modify_event")
# Handle visibility validation
_apply_visibility_if_valid(event_body, visibility, "modify_event")
# Handle guest permissions
if guests_can_modify is not None:
event_body["guestsCanModify"] = guests_can_modify
logger.info(f"[modify_event] Set guestsCanModify to {guests_can_modify}")
if guests_can_invite_others is not None:
event_body["guestsCanInviteOthers"] = guests_can_invite_others
logger.info(
f"[modify_event] Set guestsCanInviteOthers to {guests_can_invite_others}"
)
if guests_can_see_other_guests is not None:
event_body["guestsCanSeeOtherGuests"] = guests_can_see_other_guests
logger.info(
f"[modify_event] Set guestsCanSeeOtherGuests to {guests_can_see_other_guests}"
)
# Handle conference data
if conference_data is not None:
# Attach a pre-generated third-party conference (Zoom/Webex/Teams add-on)
event_body["conferenceData"] = conference_data
logger.info("[modify_event] Attaching pre-generated conference data")
elif add_google_meet is not None:
if add_google_meet:
request_id = str(uuid.uuid4())
event_body["conferenceData"] = {
"createRequest": {
"requestId": request_id,
"conferenceSolutionKey": {"type": "hangoutsMeet"},
}
}
logger.info(
f"[modify_event] Adding Google Meet conference with request ID: {request_id}"
)
else:
# Remove Google Meet by setting conferenceData to JSON null.
event_body["conferenceData"] = None
logger.info("[modify_event] Removing Google Meet conference")
if timezone is not None and "start" not in event_body and "end" not in event_body:
# If timezone is provided but start/end times are not, we need to fetch the existing event
# to apply the timezone correctly. This is a simplification; a full implementation
# might handle this more robustly or require start/end with timezone.
# For now, we'll log a warning and skip applying timezone if start/end are missing.
logger.warning(
"[modify_event] Timezone provided but start_time and end_time are missing. Timezone will not be applied unless start/end times are also provided."
)
if attachments is not None:
# patch replaces the array wholesale, so the list passed in is the final list.
event_body["attachments"] = await _build_attachment_entries(
service, attachments, "modify_event"
)
if not event_body:
message = "No fields provided to modify the event."
logger.warning(f"[modify_event] {message}")
raise Exception(message)
if this_and_following:
new_series = await _split_recurring_event(
service, calendar_id, event_id, event_body, send_updates
)
return (
f"Successfully modified '{new_series.get('summary', summary)}' from "
f"instance {event_id} onward for {user_google_email}. Earlier instances "
"keep the original series; this and following instances are now series "
f"ID {new_series.get('id')}. "
f"Link: {new_series.get('htmlLink', 'No link available')}"
+ _saved_event_times(new_series)
)
# Log the event ID for debugging
logger.info(
f"[modify_event] Attempting to update event with ID: '{event_id}' in calendar '{calendar_id}'"
)
# Get the existing event to preserve fields that aren't being updated
try:
existing_event = await asyncio.to_thread(
lambda: (
service.events().get(calendarId=calendar_id, eventId=event_id).execute()
)
)
logger.info(
"[modify_event] Successfully retrieved existing event before update"
)
# Preserve existing fields if not provided in the update
_preserve_existing_fields(
event_body,
existing_event,
{
"summary": summary,
"description": description,
"location": location,
# Use the already-normalized attendee objects (if provided); otherwise preserve existing
"attendees": event_body.get("attendees"),
"colorId": event_body.get("colorId"),
"recurrence": recurrence,
},
)
if add_google_meet is None and "conferenceData" in existing_event:
logger.info(
"[modify_event] Existing conference data preserved via patch (not copied)"
)
except HttpError as get_error:
if get_error.resp.status == 404:
logger.error(
f"[modify_event] Event not found during pre-update verification: {get_error}"
)
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."
raise Exception(message)
else:
logger.warning(
f"[modify_event] Error during pre-update verification, but proceeding with update: {get_error}"
)
updated_event = await asyncio.to_thread(
lambda: (
service.events()
.patch(
calendarId=calendar_id,
eventId=event_id,
body=event_body,
supportsAttachments=True,
conferenceDataVersion=1,
sendUpdates=send_updates,
)
.execute()
)
)
link = updated_event.get("htmlLink", "No link available")
confirmation_message = f"Successfully modified event '{updated_event.get('summary', summary)}' (ID: {event_id}) for {user_google_email}. Link: {link}"
confirmation_message += _saved_event_times(updated_event)
# Surface the conferencing link (native Meet or third-party add-on) if present
if conference_data is not None:
meeting_link = _get_meeting_link(updated_event)
if meeting_link:
confirmation_message += f" Conference: {meeting_link}"
elif add_google_meet is True:
meeting_link = _get_meeting_link(updated_event)
if meeting_link:
confirmation_message += f" Google Meet: {meeting_link}"
elif add_google_meet is False:
confirmation_message += " (Google Meet removed)"
logger.info(
f"Event modified successfully for {user_google_email}. ID: {updated_event.get('id')}, Link: {link}"
)
return confirmation_message
async def _delete_event_impl(
service,
user_google_email: str,
event_id: str,
calendar_id: str = "primary",
send_updates: str = "all",
) -> str:
"""Internal implementation for deleting a calendar event."""
logger.info(
f"[delete_event] Invoked. Email: '{user_google_email}', Event ID: {event_id}"
)
# Log the event ID for debugging
logger.info(
f"[delete_event] Attempting to delete event with ID: '{event_id}' in calendar '{calendar_id}'"
)
# Try to get the event first to verify it exists
try:
await asyncio.to_thread(
lambda: (
service.events().get(calendarId=calendar_id, eventId=event_id).execute()
)
)
logger.info("[delete_event] Successfully verified event exists before deletion")
except HttpError as get_error:
if get_error.resp.status == 404:
logger.error(
f"[delete_event] Event not found during pre-delete verification: {get_error}"
)
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."
raise Exception(message)
else:
logger.warning(
f"[delete_event] Error during pre-delete verification, but proceeding with deletion: {get_error}"
)
# Proceed with the deletion
await asyncio.to_thread(
lambda: (
service.events()
.delete(
calendarId=calendar_id,
eventId=event_id,
sendUpdates=send_updates,
)
.execute()
)
)
confirmation_message = f"Successfully deleted event (ID: {event_id}) from calendar '{calendar_id}' for {user_google_email}."
logger.info(f"Event deleted successfully for {user_google_email}. ID: {event_id}")
return confirmation_message
async def _rsvp_event_impl(
service,
user_google_email: str,
event_id: str,
response: str,
calendar_id: str = "primary",
comment: Optional[str] = None,
send_updates: str = "all",
) -> str:
"""Internal implementation for responding to a calendar event invitation."""
valid_responses = {"accepted", "declined", "tentative", "needsAction"}
if response not in valid_responses:
raise UserInputError(
f"Invalid response '{response}'. Must be one of: {sorted(valid_responses)}"
)
existing_event = await asyncio.to_thread(
lambda: service.events().get(calendarId=calendar_id, eventId=event_id).execute()
)
attendees = existing_event.get("attendees")
if not attendees:
raise Exception("This event has no attendee list; cannot update RSVP.")
if existing_event.get("organizer", {}).get("self"):
raise Exception(
"You are the organizer of this event. Organizers cannot respond to their own invitations."
)
user_index = next((i for i, a in enumerate(attendees) if a.get("self")), None)
if user_index is None:
raise Exception(
f"{user_google_email} was not found in the event's attendee list."
)
updated_attendees = [dict(a) for a in attendees]
updated_attendees[user_index]["responseStatus"] = response
if comment is not None:
updated_attendees[user_index]["comment"] = comment
updated_event = await asyncio.to_thread(
lambda: (
service.events()
.patch(
calendarId=calendar_id,
eventId=event_id,
body={"attendees": updated_attendees},
sendUpdates=send_updates,
)
.execute()
)
)
summary = updated_event.get("summary", "Unknown event")
logger.info(
f"[rsvp_event] RSVP for event {event_id} set to '{response}' for {user_google_email}."
)
return f"Successfully updated RSVP for '{summary}' (ID: {event_id}) to '{response}' for {user_google_email}."
# ---------------------------------------------------------------------------
# Consolidated event management tool
# ---------------------------------------------------------------------------
@server.tool(
title="Manage Event",
annotations=ToolAnnotations(
readOnlyHint=False,
destructiveHint=True,
idempotentHint=False,
openWorldHint=True,
),
)
@handle_http_errors("manage_event", service_type="calendar")
@require_google_service("calendar", "calendar_events")
async def manage_event(
service,
user_google_email: str,
action: str,
summary: Optional[str] = None,
start_time: Optional[str] = None,
end_time: Optional[str] = None,
event_id: Optional[str] = None,
calendar_id: str = "primary",
description: Optional[str] = None,
location: Optional[str] = None,
attendees: Optional[StringOrDictList] = None,
timezone: Optional[str] = None,
attachments: Optional[StringList] = None,
add_google_meet: Optional[bool] = None,
conference_data: Optional[Dict[str, Any]] = None,
conference_provider: Optional[str] = None,
conference_uri: Optional[str] = None,
conference_passcode: Optional[str] = None,
conference_id: Optional[str] = None,
reminders: Optional[Union[str, List[Dict[str, Any]]]] = None,
use_default_reminders: Optional[bool] = None,
transparency: Optional[str] = None,
visibility: Optional[str] = None,
color_id: Optional[str] = None,
recurrence: Optional[StringList] = None,
guests_can_modify: Optional[bool] = None,
guests_can_invite_others: Optional[bool] = None,
guests_can_see_other_guests: Optional[bool] = None,
response: Optional[str] = None,
rsvp_comment: Optional[str] = None,
send_updates: Optional[str] = None,
*,
start_timezone: Optional[str] = None,
end_timezone: Optional[str] = None,
this_and_following: bool = False,
) -> str:
"""
Manages calendar events. Supports creating, updating, deleting, and RSVP.
Args:
user_google_email (str): The user's Google email address. Required.
action (str): Action to perform - "create", "update", "delete", or "rsvp".
summary (Optional[str]): Event title (required for create).
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.
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.
event_id (Optional[str]): Event ID (required for update and delete).
calendar_id (str): Calendar ID (default: 'primary').
description (Optional[str]): Event description.
location (Optional[str]): Event location.
attendees (Optional[List[Union[str, Dict[str, Any]]]]): Attendee email addresses, attendee objects (e.g. {"email": ..., "responseStatus": "accepted"}), or a mix of both.
timezone (Optional[str]): IANA timezone applied to both boundaries (e.g.,
"America/New_York"). Converts offset-bearing timestamps without changing their
instant; interprets offset-free timestamps as local times in this zone.
Overridden per boundary by start_timezone/end_timezone.
start_timezone (Optional[str]): IANA timezone for the start boundary only,
overriding timezone. Use for events whose two ends sit in different zones -
a flight departing 13:45 "Asia/Jerusalem" and landing 17:50
"Europe/Amsterdam" is one event authored in two zones. Explicit timestamp
offsets always preserve the instant, even when the zone differs.
end_timezone (Optional[str]): IANA timezone for the end boundary only,
overriding timezone. See start_timezone.
attachments (Optional[List[str]]): List of Google Drive file URLs or IDs to attach.
On action="update" this replaces the event's existing attachments rather than
appending to them, matching the Calendar API's patch semantics.
add_google_meet (Optional[bool]): Whether to add/remove native Google Meet.
conference_data (Optional[Dict[str, Any]]): Raw Google Calendar `conferenceData`
payload to attach a third-party conference (Zoom/Webex/Teams add-on). Use this
for full control; mutually exclusive with the conference_provider helper params
and with add_google_meet. (create/update only)
conference_provider (Optional[str]): Higher-level helper: third-party provider name
(e.g. "zoom", "webex", "teams"). Requires conference_uri. The MCP builds the
addOn `conferenceData` block internally. (create/update only)
conference_uri (Optional[str]): Join URL for the third-party conference (e.g.
"https://zoom.us/j/123456789"). Required when conference_provider is set.
conference_passcode (Optional[str]): Optional passcode for the third-party conference.
conference_id (Optional[str]): Optional provider-side conference/meeting ID.
reminders (Optional[Union[str, List[Dict[str, Any]]]]): Custom reminder objects.
use_default_reminders (Optional[bool]): Whether to use default reminders.
transparency (Optional[str]): "opaque" (busy) or "transparent" (free).
visibility (Optional[str]): "default", "public", "private", or "confidential".
color_id (Optional[str]): Event color, by name or ID: lavender (1), sage (2),
grape (3), flamingo (4), banana (5), tangerine (6), peacock (7),