forked from taylorwilsdon/google_workspace_mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalendar_tools.py
More file actions
2552 lines (2279 loc) · 99.1 KB
/
Copy pathcalendar_tools.py
File metadata and controls
2552 lines (2279 loc) · 99.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Google Calendar MCP Tools
This module provides MCP tools for interacting with Google Calendar API.
"""
import datetime
import logging
import asyncio
import re
import uuid
import json
from typing import List, Optional, Dict, Any, Union
import pytz
from googleapiclient.errors import HttpError
from googleapiclient.discovery import build
from auth.service_decorator import require_google_service
from core.utils import handle_http_errors, StringList
from gcalendar.calendar_helpers import (
_format_event_detail_lines,
_get_meeting_link,
)
from mcp.types import ToolAnnotations
from core.server import server
# Configure module logger
logger = logging.getLogger(__name__)
def _parse_reminders_json(
reminders_input: Optional[Union[str, List[Dict[str, Any]]]], function_name: str
) -> List[Dict[str, Any]]:
"""
Parse reminders from JSON string or list object and validate them.
Args:
reminders_input: JSON string containing reminder objects or list of reminder objects
function_name: Name of calling function for logging
Returns:
List of validated reminder objects
"""
if not reminders_input:
return []
# Handle both string (JSON) and list inputs
if isinstance(reminders_input, str):
try:
reminders = json.loads(reminders_input)
if not isinstance(reminders, list):
logger.warning(
f"[{function_name}] Reminders must be a JSON array, got {type(reminders).__name__}"
)
return []
except json.JSONDecodeError as e:
logger.warning(f"[{function_name}] Invalid JSON for reminders: {e}")
return []
elif isinstance(reminders_input, list):
reminders = reminders_input
else:
logger.warning(
f"[{function_name}] Reminders must be a JSON string or list, got {type(reminders_input).__name__}"
)
return []
# Validate reminders
if len(reminders) > 5:
logger.warning(
f"[{function_name}] More than 5 reminders provided, truncating to first 5"
)
reminders = reminders[:5]
validated_reminders = []
for reminder in reminders:
if (
not isinstance(reminder, dict)
or "method" not in reminder
or "minutes" not in reminder
):
logger.warning(
f"[{function_name}] Invalid reminder format: {reminder}, skipping"
)
continue
method = reminder["method"].lower()
if method not in ["popup", "email"]:
logger.warning(
f"[{function_name}] Invalid reminder method '{method}', must be 'popup' or 'email', skipping"
)
continue
minutes = reminder["minutes"]
if not isinstance(minutes, int) or minutes < 0 or minutes > 40320:
logger.warning(
f"[{function_name}] Invalid reminder minutes '{minutes}', must be integer 0-40320, skipping"
)
continue
validated_reminders.append({"method": method, "minutes": minutes})
return validated_reminders
def _apply_transparency_if_valid(
event_body: Dict[str, Any],
transparency: Optional[str],
function_name: str,
) -> None:
"""
Apply transparency to the event body if the provided value is valid.
Args:
event_body: Event payload being constructed.
transparency: Provided transparency value.
function_name: Name of the calling function for logging context.
"""
if transparency is None:
return
valid_transparency_values = ["opaque", "transparent"]
if transparency in valid_transparency_values:
event_body["transparency"] = transparency
logger.info(f"[{function_name}] Set transparency to '{transparency}'")
else:
logger.warning(
f"[{function_name}] Invalid transparency value '{transparency}', must be 'opaque' or 'transparent', skipping"
)
def _apply_visibility_if_valid(
event_body: Dict[str, Any],
visibility: Optional[str],
function_name: str,
) -> None:
"""
Apply visibility to the event body if the provided value is valid.
Args:
event_body: Event payload being constructed.
visibility: Provided visibility value.
function_name: Name of the calling function for logging context.
"""
if visibility is None:
return
valid_visibility_values = ["default", "public", "private", "confidential"]
if visibility in valid_visibility_values:
event_body["visibility"] = visibility
logger.info(f"[{function_name}] Set visibility to '{visibility}'")
else:
logger.warning(
f"[{function_name}] Invalid visibility value '{visibility}', must be 'default', 'public', 'private', or 'confidential', skipping"
)
_VALID_AUTO_DECLINE_MODES = {
"declineAllConflictingInvitations",
"declineOnlyNewConflictingInvitations",
"declineNone",
}
_VALID_FOCUS_TIME_CHAT_STATUSES = {
"available",
"doNotDisturb",
}
def _validate_auto_decline_mode(mode: Optional[str], function_name: str) -> str:
"""Validate and return auto decline mode, defaulting to declineAllConflictingInvitations.
Args:
mode: The auto decline mode to validate.
function_name: Name of the calling function for error context.
Returns:
A valid auto decline mode string.
"""
if mode is None:
return "declineAllConflictingInvitations"
if mode not in _VALID_AUTO_DECLINE_MODES:
raise ValueError(
f"[{function_name}] Invalid auto_decline_mode '{mode}'. "
f"Must be one of: {', '.join(sorted(_VALID_AUTO_DECLINE_MODES))}"
)
return mode
def _preserve_existing_fields(
event_body: Dict[str, Any],
existing_event: Dict[str, Any],
field_mappings: Dict[str, Any],
) -> None:
"""
Helper function to preserve existing event fields when not explicitly provided.
Args:
event_body: The event body being built for the API call
existing_event: The existing event data from the API
field_mappings: Dict mapping field names to their new values (None means preserve existing)
"""
for field_name, new_value in field_mappings.items():
if new_value is None and field_name in existing_event:
event_body[field_name] = existing_event[field_name]
logger.info(f"[modify_event] Preserving existing {field_name}")
elif new_value is not None:
event_body[field_name] = new_value
# Helper function to ensure time strings for API calls are correctly formatted
def _correct_time_format_for_api(
time_str: Optional[str], param_name: str, timezone: Optional[str] = None
) -> Optional[str]:
"""Normalize a time string into RFC3339 format suitable for the Google Calendar API."""
if not time_str:
return None
# Defensive normalization: some LLM-driven MCP clients double-encode JSON
# string arguments, passing values like '"2026-05-15T00:00:00Z"'
time_str = time_str.strip().strip('"').strip("'").strip()
if not time_str or time_str.lower() in ("null", "none"):
return None
logger.info(
f"_correct_time_format_for_api: Processing {param_name} with value '{time_str}', timezone: '{timezone}'"
)
# Handle date-only format (YYYY-MM-DD)
if len(time_str) == 10 and time_str.count("-") == 2:
try:
# Validate it's a proper date
datetime.datetime.strptime(time_str, "%Y-%m-%d")
# For date-only, convert using the provided timezone, or UTC if not provided
if timezone:
try:
tz = pytz.timezone(timezone)
# Parse the date and create a datetime at midnight in the specified timezone
date_obj = datetime.datetime.strptime(time_str, "%Y-%m-%d")
dt = tz.localize(date_obj)
# Convert to UTC and format as RFC3339
formatted = (
dt.astimezone(datetime.timezone.utc)
.isoformat()
.replace("+00:00", "Z")
)
except pytz.exceptions.UnknownTimeZoneError:
logger.warning(
f"Could not apply timezone '{timezone}', falling back to UTC for {param_name}"
)
formatted = f"{time_str}T00:00:00Z"
else:
formatted = f"{time_str}T00:00:00Z"
logger.info(
f"Formatting date-only {param_name} '{time_str}' to RFC3339: '{formatted}'"
)
return formatted
except ValueError:
logger.warning(
f"{param_name} '{time_str}' looks like a date but is not valid YYYY-MM-DD. Using as is."
)
return time_str
# Specifically address YYYY-MM-DDTHH:MM:SS by appending 'Z'
if (
len(time_str) == 19
and time_str[10] == "T"
and time_str.count(":") == 2
and not (
time_str.endswith("Z") or ("+" in time_str[10:]) or ("-" in time_str[10:])
)
):
try:
# Validate the format before appending 'Z'
datetime.datetime.strptime(time_str, "%Y-%m-%dT%H:%M:%S")
logger.info(
f"Formatting {param_name} '{time_str}' by appending 'Z' for UTC."
)
return time_str + "Z"
except ValueError:
logger.warning(
f"{param_name} '{time_str}' looks like it needs 'Z' but is not valid YYYY-MM-DDTHH:MM:SS. Using as is."
)
return time_str
# If it already has timezone info or doesn't match our patterns, return as is
logger.info(f"{param_name} '{time_str}' doesn't need formatting, using as is.")
return time_str
def _strip_utc_offset(datetime_str: str) -> str:
"""Strip UTC offset from an RFC3339 dateTime string, returning a naive local time.
When an IANA timezone (e.g. America/Los_Angeles) is provided alongside a dateTime,
the Google Calendar API uses the explicit offset from dateTime for scheduling and
only uses the IANA timezone for recurrence expansion. This means an LLM-generated
offset that doesn't account for DST (e.g. -08:00 during PDT) will place the event
at the wrong wall-clock time.
By stripping the offset and keeping only the naive local time + IANA timeZone,
Google Calendar resolves the correct DST-aware offset automatically.
Examples:
"2026-03-19T12:00:00-08:00" → "2026-03-19T12:00:00"
"2026-03-19T12:00:00-07:00" → "2026-03-19T12:00:00"
"2026-03-19T12:00:00Z" → "2026-03-19T12:00:00"
"2026-03-19T12:00:00" → "2026-03-19T12:00:00" (no-op)
"""
# Strip trailing Z
if datetime_str.endswith("Z"):
return datetime_str[:-1]
# Strip +HH:MM or -HH:MM offset at end (e.g. -07:00, +05:30)
return re.sub(r"[+-]\d{2}:\d{2}$", "", datetime_str)
@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) -> str:
"""
Retrieves a list of calendars accessible to the authenticated user.
Args:
user_google_email (str): The user's Google email address. Required.
Returns:
str: A formatted list of the user's calendars (summary, ID, primary status).
"""
logger.info(f"[list_calendars] Invoked. Email: '{user_google_email}'")
calendar_list_response = await asyncio.to_thread(
lambda: service.calendarList().list().execute()
)
items = calendar_list_response.get("items", [])
if not items:
return f"No calendars found for {user_google_email}."
calendars_summary_list = [
f'- "{cal.get("summary", "No Summary")}"{" (Primary)" if cal.get("primary") else ""} (ID: {cal["id"]})'
for cal in items
]
text_output = (
f"Successfully listed {len(items)} calendars for {user_google_email}:\n"
+ "\n".join(calendars_summary_list)
)
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,
) -> 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. 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. Defaults to 25. 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, and events that are not ordinary confirmed meetings report their event type (outOfOffice, workingLocation, focusTime) and status. 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.
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.
"""
logger.info(
f"[get_events] Raw parameters - event_id: '{event_id}', time_min: '{time_min}', time_max: '{time_max}', query: '{query}', detailed: {detailed}, include_attachments: {include_attachments}"
)
# 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
# Ensure time_min and time_max are correctly formatted for the API
formatted_time_min = _correct_time_format_for_api(time_min, "time_min", None)
if formatted_time_min:
effective_time_min = formatted_time_min
else:
utc_now = datetime.datetime.now(datetime.timezone.utc)
effective_time_min = utc_now.isoformat().replace("+00:00", "Z")
if time_min is None:
logger.info(
f"time_min not provided, defaulting to current UTC time: {effective_time_min}"
)
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: '{query}'"
)
# Build the request parameters dynamically
request_params = {
"calendarId": calendar_id,
"timeMin": effective_time_min,
"timeMax": effective_time_max,
"maxResults": max_results,
"singleEvents": True,
"orderBy": "startTime",
}
if query:
request_params["q"] = query
events_result = await asyncio.to_thread(
lambda: service.events().list(**request_params).execute()
)
items = events_result.get("items", [])
if not items:
if event_id:
return f"Event with ID '{event_id}' not found in calendar '{calendar_id}' for {user_google_email}."
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 = item["start"].get("dateTime", item["start"].get("date"))
end = item["end"].get("dateTime", item["end"].get("date"))
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 = item["start"].get("dateTime", item["start"].get("date"))
end_time = item["end"].get("dateTime", item["end"].get("date"))
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 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)
)
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.
# ---------------------------------------------------------------------------
# Friendly provider name -> conferenceSolution display name for the addOn block.
_CONFERENCE_SOLUTION_NAMES = {
"zoom": "Zoom Meeting",
"webex": "Webex",
"teams": "Microsoft Teams",
"microsoft teams": "Microsoft Teams",
}
def _build_addon_conference_data(
provider: str,
uri: str,
passcode: Optional[str] = None,
conference_id: Optional[str] = None,
) -> Dict[str, Any]:
"""Build a Google Calendar ``conferenceData`` block for a third-party add-on.
Used for providers (Zoom, Webex, Teams, ...) attached via the
``conferenceSolution.key.type = "addOn"`` mechanism rather than the native
``hangoutsMeet`` create request.
"""
provider = provider.strip()
uri = uri.strip()
name = _CONFERENCE_SOLUTION_NAMES.get(provider.lower(), provider)
entry_point: Dict[str, Any] = {
"entryPointType": "video",
"uri": uri,
"label": name,
}
if passcode:
entry_point["passcode"] = passcode
conference_data: Dict[str, Any] = {
"conferenceSolution": {"key": {"type": "addOn"}, "name": name},
"entryPoints": [entry_point],
}
if conference_id:
conference_data["conferenceId"] = conference_id
return conference_data
def _resolve_conference_data(
conference_data: Optional[Dict[str, Any]],
conference_provider: Optional[str],
conference_uri: Optional[str],
conference_passcode: Optional[str],
conference_id: Optional[str],
add_google_meet: Optional[bool],
) -> Optional[Dict[str, Any]]:
"""Resolve the conferencing inputs into a single ``conferenceData`` dict.
Accepts either a raw ``conference_data`` pass-through payload or the
higher-level ``conference_provider``/``conference_uri`` helper params, and
validates that they are not combined with each other or with
``add_google_meet``. Returns the resolved payload, or ``None`` if no
third-party conference was requested.
"""
helper_used = any(
[conference_provider, conference_uri, conference_passcode, conference_id]
)
if conference_data is not None and helper_used:
raise ValueError(
"Provide either conference_data (raw payload) or the "
"conference_provider/conference_uri helper params, not both."
)
resolved = conference_data
if helper_used:
provider = (conference_provider or "").strip()
uri = (conference_uri or "").strip()
if not (provider and uri):
raise ValueError(
"conference_provider and conference_uri are both required to "
"attach a third-party conference."
)
resolved = _build_addon_conference_data(
provider, uri, conference_passcode, conference_id
)
if resolved is not None and add_google_meet:
raise ValueError(
"Cannot attach a third-party conference and add_google_meet on the "
"same event; choose one."
)
return resolved
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[str]] = 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,
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",
) -> str:
"""Internal implementation for creating a calendar event."""
logger.info(
f"[create_event] Invoked. Email: '{user_google_email}', Summary: {summary}"
)
logger.info(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.info(
f"[create_event] Parsed attachments list from string: {attachments}"
)
# When an IANA timezone is provided, strip any UTC offset from dateTime values
# so Google Calendar resolves the correct DST-aware offset from the IANA name.
effective_start = start_time
effective_end = end_time
if timezone and "T" in start_time:
effective_start = _strip_utc_offset(start_time)
if timezone and "T" in end_time:
effective_end = _strip_utc_offset(end_time)
event_body: Dict[str, Any] = {
"summary": summary,
"start": (
{"date": start_time}
if "T" not in start_time
else {"dateTime": effective_start}
),
"end": (
{"date": end_time} if "T" not in end_time else {"dateTime": effective_end}
),
}
if recurrence:
event_body["recurrence"] = recurrence
if location:
event_body["location"] = location
if description:
event_body["description"] = description
if timezone:
if "dateTime" in event_body["start"]:
event_body["start"]["timeZone"] = timezone
if "dateTime" in event_body["end"]:
event_body["end"]["timeZone"] = timezone
if attendees:
event_body["attendees"] = [{"email": email} for email in attendees]
# 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:
# Accept both file URLs and file IDs. If a URL, extract the fileId.
event_body["attachments"] = []
drive_service = None
try:
try:
drive_service = service._http and build(
"drive", "v3", http=service._http
)
except Exception as e:
logger.warning(
f"Could not build Drive service for MIME type lookup: {e}"
)
for att in attachments:
file_id = None
if att.startswith("https://"):
# Match /d/<id>, /file/d/<id>, ?id=<id>
match = re.search(r"(?:/d/|/file/d/|id=)([\w-]+)", att)
file_id = match.group(1) if match else None
logger.info(
f"[create_event] Extracted file_id '{file_id}' from attachment URL '{att}'"
)
else:
file_id = att
logger.info(
f"[create_event] Using direct file_id '{file_id}' for attachment"
)
if file_id:
file_url = f"https://drive.google.com/open?id={file_id}"
mime_type = "application/vnd.google-apps.drive-sdk"
title = "Drive Attachment"
# Try to get the actual MIME type and filename from Drive
if drive_service:
try:
file_metadata = await asyncio.to_thread(
lambda: (
drive_service.files()
.get(
fileId=file_id,
fields="mimeType,name",
supportsAllDrives=True,
)
.execute()
)
)
mime_type = file_metadata.get("mimeType", mime_type)
filename = file_metadata.get("name")
if filename:
title = filename
logger.info(
f"[create_event] Using filename '{filename}' as attachment title"
)
else:
logger.info(
"[create_event] No filename found, using generic title"
)
except Exception as e:
logger.warning(
f"Could not fetch metadata for file {file_id}: {e}"
)
event_body["attachments"].append(
{
"fileUrl": file_url,
"title": title,
"mimeType": mime_type,
}
)
finally:
if drive_service:
drive_service.close()
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}"
# 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
def _normalize_attendees(
attendees: Optional[Union[List[str], List[Dict[str, Any]]]],
) -> Optional[List[Dict[str, Any]]]:
"""
Normalize attendees input to list of attendee objects.
Accepts either:
- List of email strings: ["user@example.com", "other@example.com"]
- List of attendee objects: [{"email": "user@example.com", "responseStatus": "accepted"}]
- Mixed list of both formats
Returns list of attendee dicts with at minimum 'email' key.
"""
if attendees is None:
return None
normalized = []
for att in attendees:
if isinstance(att, str):
normalized.append({"email": att})
elif isinstance(att, dict) and "email" in att:
normalized.append(att)
else:
logger.warning(
f"[_normalize_attendees] Invalid attendee format: {att}, skipping"
)
return normalized if normalized else None
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[Union[List[str], List[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,
send_updates: str = "all",
) -> 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:
effective_start = start_time
if timezone is not None and "T" in start_time:
effective_start = _strip_utc_offset(start_time)
event_body["start"] = (
{"date": start_time}
if "T" not in start_time
else {"dateTime": effective_start}
)
if timezone is not None and "dateTime" in event_body["start"]:
event_body["start"]["timeZone"] = timezone
if end_time is not None:
effective_end = end_time
if timezone is not None and "T" in end_time:
effective_end = _strip_utc_offset(end_time)
event_body["end"] = (
{"date": end_time} if "T" not in end_time else {"dateTime": effective_end}
)
if timezone is not None and "dateTime" in event_body["end"]:
event_body["end"]["timeZone"] = 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 = (
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"
)