forked from taylorwilsdon/google_workspace_mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontacts_tools.py
More file actions
1696 lines (1432 loc) · 58.3 KB
/
Copy pathcontacts_tools.py
File metadata and controls
1696 lines (1432 loc) · 58.3 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 Contacts MCP Tools (People API)
This module provides MCP tools for interacting with Google Contacts via the People API.
"""
import asyncio
import logging
import warnings
from typing import Any, Dict, List, Literal, Optional
from googleapiclient.errors import HttpError
from mcp import Resource
from pydantic import AliasChoices, BaseModel, ConfigDict, Field
from mcp.types import ToolAnnotations
from auth.service_decorator import require_google_service
from core.server import server
from core.utils import UserInputError, handle_http_errors, StringList
from gcontacts.contacts_helpers import (
_format_contact,
_merge_emails,
_merge_nicknames,
_merge_organizations,
_merge_phones,
_merge_relations,
_merge_urls,
_merge_user_defined,
_parse_birthday,
)
logger = logging.getLogger(__name__)
# Default person fields for list/search operations
DEFAULT_PERSON_FIELDS = "names,nicknames,emailAddresses,phoneNumbers,organizations"
# Detailed person fields for get operations
DETAILED_PERSON_FIELDS = (
"names,nicknames,emailAddresses,phoneNumbers,organizations,biographies,"
"addresses,birthdays,urls,userDefined,relations,photos,metadata,memberships"
)
# Contact group fields
CONTACT_GROUP_FIELDS = "name,groupType,memberCount,metadata"
# Cache warmup tracking
_search_cache_warmed_up: Dict[str, bool] = {}
# Known phone types supported by Google People API (custom types also allowed)
KNOWN_PHONE_TYPES = {
"home",
"work",
"mobile",
"homeFax",
"workFax",
"otherFax",
"pager",
"workMobile",
"workPager",
"main",
"googleVoice",
"other",
"internal",
}
class PhoneInput(BaseModel):
"""Typed input for a phone entry."""
model_config = ConfigDict(extra="forbid")
number: Optional[str] = Field(
default=None,
description="Phone number value.",
)
value: Optional[str] = Field(
default=None,
description="Backward-compatible alias for the phone number value.",
)
type: Optional[str] = Field(
default=None,
description="Phone type such as mobile, work, home, or internal.",
)
class EmailInput(BaseModel):
"""Typed input for an email entry."""
model_config = ConfigDict(extra="forbid")
address: Optional[str] = Field(
default=None,
description="Email address value.",
)
value: Optional[str] = Field(
default=None,
description="Backward-compatible alias for the email address value.",
)
type: Optional[str] = Field(
default=None,
description="Email type such as work, home, or other.",
)
class OrganizationInput(BaseModel):
"""Typed input for an organization entry."""
model_config = ConfigDict(extra="forbid")
name: Optional[str] = Field(default=None, description="Organization name.")
title: Optional[str] = Field(default=None, description="Job title.")
department: Optional[str] = Field(default=None, description="Department name.")
jobDescription: Optional[str] = Field(
default=None,
description="Optional organization job description.",
validation_alias=AliasChoices("jobDescription", "description"),
)
type: Optional[str] = Field(
default=None,
description="Organization type such as work or school.",
)
class NicknameInput(BaseModel):
"""Typed input for a nickname entry."""
model_config = ConfigDict(extra="forbid")
value: str = Field(
description="Nickname value. Used for bilingual contacts (e.g. Hebrew alternative form).",
)
type: Optional[str] = Field(
default=None,
description="Nickname type such as default, alternate_name, maiden_name, initials, or other.",
)
class UrlInput(BaseModel):
"""Typed input for a URL entry."""
model_config = ConfigDict(extra="forbid")
value: str = Field(
description="The URL value (e.g. https://example.com).",
)
type: Optional[str] = Field(
default=None,
description="URL type such as homepage, blog, profile, work, ftp, reservations, or other. Custom values allowed.",
)
class UserDefinedInput(BaseModel):
"""Typed input for a userDefined custom field entry."""
model_config = ConfigDict(extra="forbid")
key: str = Field(
description="Custom field key (e.g. 'ID', 'Hebrew Birthday', 'Account Number').",
)
value: str = Field(
default="",
description="Custom field value. May be omitted when using remove mode (only the key is needed).",
)
class RelationInput(BaseModel):
"""Typed input for a relation entry (spouse, parent, child, etc.)."""
model_config = ConfigDict(extra="forbid")
person: str = Field(
description="The related person's name (matched against contact names by Google Assistant).",
)
type: Optional[str] = Field(
default=None,
description="Relation type: spouse, child, parent, father, mother, sister, brother, friend, manager, assistant, partner, sibling, domesticPartner, or custom.",
)
class ContactInput(BaseModel):
"""Typed batch-create input for a contact."""
model_config = ConfigDict(extra="forbid")
given_name: Optional[str] = None
family_name: Optional[str] = None
phones: Optional[List[PhoneInput]] = None
emails: Optional[List[EmailInput]] = None
organizations: Optional[List[OrganizationInput]] = None
nicknames: Optional[List[NicknameInput]] = None
urls: Optional[List[UrlInput]] = None
user_defined: Optional[List[UserDefinedInput]] = None
relations: Optional[List[RelationInput]] = None
notes: Optional[str] = None
address: Optional[str] = None
birthday: Optional[str] = Field(
default=None,
description="Birthday as 'YYYY-MM-DD', 'MM-DD' (no year), or 'clear'/'' to remove.",
)
phone: Optional[str] = None
email: Optional[str] = None
organization: Optional[str] = None
job_title: Optional[str] = None
class ContactUpdateInput(ContactInput):
"""Typed batch-update input for a contact."""
contact_id: str = Field(
description='Contact ID like "c123" or full resource name like "people/c123".'
)
def _coerce_phone_input(phone: Any) -> PhoneInput:
if isinstance(phone, PhoneInput):
return phone
if isinstance(phone, dict):
phone = dict(phone)
if not phone.get("type") and phone.get("label"):
phone["type"] = phone["label"]
phone.pop("label", None)
return PhoneInput.model_validate(phone)
def _coerce_email_input(email: Any) -> EmailInput:
if isinstance(email, EmailInput):
return email
if isinstance(email, dict):
email = dict(email)
if not email.get("type") and email.get("label"):
email["type"] = email["label"]
email.pop("label", None)
return EmailInput.model_validate(email)
def _coerce_organization_input(org: Any) -> OrganizationInput:
if isinstance(org, OrganizationInput):
return org
return OrganizationInput.model_validate(org)
def _coerce_nickname_input(nickname: Any) -> NicknameInput:
if isinstance(nickname, NicknameInput):
return nickname
if isinstance(nickname, str):
return NicknameInput(value=nickname)
return NicknameInput.model_validate(nickname)
def _coerce_url_input(url: Any) -> UrlInput:
if isinstance(url, UrlInput):
return url
if isinstance(url, str):
return UrlInput(value=url)
return UrlInput.model_validate(url)
def _coerce_user_defined_input(entry: Any) -> UserDefinedInput:
if isinstance(entry, UserDefinedInput):
return entry
return UserDefinedInput.model_validate(entry)
def _coerce_relation_input(relation: Any) -> RelationInput:
if isinstance(relation, RelationInput):
return relation
if isinstance(relation, str):
return RelationInput(person=relation)
return RelationInput.model_validate(relation)
def _coerce_contact_input(contact: Any) -> ContactInput:
if isinstance(contact, ContactInput):
return contact
return ContactInput.model_validate(contact)
def _coerce_contact_update_input(update: Any) -> ContactUpdateInput:
if isinstance(update, ContactUpdateInput):
return update
return ContactUpdateInput.model_validate(update)
def _build_person_body(
given_name: Optional[str] = None,
family_name: Optional[str] = None,
# New multi-value params
phones: Optional[List[PhoneInput]] = None,
emails: Optional[List[EmailInput]] = None,
organizations: Optional[List[OrganizationInput]] = None,
nicknames: Optional[List[NicknameInput]] = None,
urls: Optional[List[UrlInput]] = None,
user_defined: Optional[List[UserDefinedInput]] = None,
relations: Optional[List[RelationInput]] = None,
notes: Optional[str] = None,
address: Optional[str] = None,
birthday: Optional[str] = None,
# Deprecated single-value aliases
email: Optional[str] = None,
phone: Optional[str] = None,
organization: Optional[str] = None,
job_title: Optional[str] = None,
) -> Dict[str, Any]:
"""
Build a Person resource body for create/update operations.
Accepts both new list-based params (phones, emails, organizations) and
deprecated single-value aliases (phone, email, organization, job_title).
Args:
given_name: First name.
family_name: Last name.
phones: List of PhoneInput items {number, value?, type?}.
Supported types: mobile, work, home, main, workMobile, internal, other, etc.
Use type="internal" for PBX/ATS short numbers (e.g. 250, 301).
emails: List of EmailInput items {address, value?, type?}.
organizations: List of OrganizationInput items {name?, title?, department?, jobDescription?, type?}.
notes: Additional notes/biography.
address: Street address.
birthday: Birthday as 'YYYY-MM-DD', 'MM-DD' (no year), or 'clear'/'' to remove.
email: [DEPRECATED] Single email address. Use emails instead.
phone: [DEPRECATED] Single phone number. Use phones instead.
organization: [DEPRECATED] Company/organization name. Use organizations instead.
job_title: [DEPRECATED] Job title. Use organizations instead.
Returns:
Person resource body dictionary.
"""
body: Dict[str, Any] = {}
if phones is not None:
phones = [_coerce_phone_input(phone) for phone in phones]
if emails is not None:
emails = [_coerce_email_input(email_entry) for email_entry in emails]
if organizations is not None:
organizations = [_coerce_organization_input(org) for org in organizations]
if nicknames is not None:
nicknames = [_coerce_nickname_input(n) for n in nicknames]
if urls is not None:
urls = [_coerce_url_input(u) for u in urls]
if user_defined is not None:
user_defined = [_coerce_user_defined_input(ud) for ud in user_defined]
if relations is not None:
relations = [_coerce_relation_input(r) for r in relations]
if given_name or family_name:
body["names"] = [
{
"givenName": given_name or "",
"familyName": family_name or "",
}
]
# --- Emails ---
if emails is not None and email is not None:
warnings.warn(
"Parameter 'email' ignored because 'emails' was provided",
DeprecationWarning,
stacklevel=3,
)
if emails is None and email is not None:
warnings.warn(
"Parameter 'email' is deprecated. Use 'emails=[{\"address\": ..., \"type\": ...}]' instead.",
DeprecationWarning,
stacklevel=3,
)
emails = [EmailInput(address=email, type="other")]
if emails is not None:
email_entries = []
for e in emails:
entry: Dict[str, Any] = {"value": e.address or e.value or ""}
if e.type:
entry["type"] = e.type
if entry["value"]:
email_entries.append(entry)
body["emailAddresses"] = email_entries
# --- Phones ---
if phones is not None and phone is not None:
warnings.warn(
"Parameter 'phone' ignored because 'phones' was provided",
DeprecationWarning,
stacklevel=3,
)
if phones is None and phone is not None:
warnings.warn(
"Parameter 'phone' is deprecated. Use 'phones=[{\"number\": ..., \"type\": ...}]' instead.",
DeprecationWarning,
stacklevel=3,
)
phones = [PhoneInput(number=phone, type="mobile")]
if phones is not None:
phone_entries = []
for p in phones:
number = p.number or p.value or ""
if not number:
continue
entry = {"value": number}
if p.type:
entry["type"] = p.type
phone_entries.append(entry)
body["phoneNumbers"] = phone_entries
# --- Organizations ---
if organizations is not None and (
organization is not None or job_title is not None
):
ignored_params = []
if organization is not None:
ignored_params.append("'organization'")
if job_title is not None:
ignored_params.append("'job_title'")
ignored = " and ".join(ignored_params)
parameter_label = "Parameter" if len(ignored_params) == 1 else "Parameters"
warnings.warn(
f"{parameter_label} {ignored} ignored because 'organizations' was provided",
DeprecationWarning,
stacklevel=3,
)
if organizations is None and (organization is not None or job_title is not None):
if organization is not None:
warnings.warn(
"Parameter 'organization' is deprecated. Use 'organizations=[{\"name\": ..., \"type\": ...}]' instead.",
DeprecationWarning,
stacklevel=3,
)
if job_title is not None:
warnings.warn(
"Parameter 'job_title' is deprecated. Use 'organizations=[{\"title\": ...}]' instead.",
DeprecationWarning,
stacklevel=3,
)
organizations = [OrganizationInput(name=organization, title=job_title)]
if organizations is not None:
org_entries = []
for org in organizations:
entry = {}
if org.name:
entry["name"] = org.name
if org.title:
entry["title"] = org.title
if org.department:
entry["department"] = org.department
if org.jobDescription:
entry["jobDescription"] = org.jobDescription
if org.type:
entry["type"] = org.type
if entry:
org_entries.append(entry)
body["organizations"] = org_entries
# --- Nicknames ---
if nicknames is not None:
nickname_entries = []
for n in nicknames:
value = (n.value or "").strip()
if not value:
continue
entry: Dict[str, Any] = {"value": value}
if n.type:
entry["type"] = n.type
nickname_entries.append(entry)
body["nicknames"] = nickname_entries
# --- URLs ---
if urls is not None:
url_entries = []
for u in urls:
value = (u.value or "").strip()
if not value:
continue
entry = {"value": value}
if u.type:
entry["type"] = u.type
url_entries.append(entry)
body["urls"] = url_entries
# --- User Defined custom fields ---
if user_defined is not None:
ud_entries = []
for ud in user_defined:
key = (ud.key or "").strip()
value = (ud.value or "").strip()
if not key:
continue
entry: Dict[str, str] = {"key": key}
if value:
entry["value"] = value
ud_entries.append(entry)
body["userDefined"] = ud_entries
# --- Relations ---
if relations is not None:
relation_entries = []
for r in relations:
person = (r.person or "").strip()
if not person:
continue
entry = {"person": person}
if r.type:
entry["type"] = r.type
relation_entries.append(entry)
body["relations"] = relation_entries
# notes=None → no change. notes="" → explicit clear (empty biographies).
# notes="text" → write that text.
if notes is not None:
if notes:
body["biographies"] = [{"value": notes, "contentType": "TEXT_PLAIN"}]
else:
body["biographies"] = []
if address:
body["addresses"] = [{"formattedValue": address}]
if birthday is not None:
if birthday.strip().lower() in ("clear", ""):
body["birthdays"] = []
else:
body["birthdays"] = [_parse_birthday(birthday)]
return body
async def _warmup_search_cache(service: Resource, user_google_email: str) -> None:
"""
Warm up the People API search cache.
The People API requires an initial empty query to warm up the search cache
before searches will return results.
Args:
service: Authenticated People API service.
user_google_email: User's email for tracking.
"""
global _search_cache_warmed_up
if _search_cache_warmed_up.get(user_google_email):
return
try:
logger.debug(f"[contacts] Warming up search cache for {user_google_email}")
await asyncio.to_thread(
service.people()
.searchContacts(query="", readMask="names", pageSize=1)
.execute
)
_search_cache_warmed_up[user_google_email] = True
logger.debug(f"[contacts] Search cache warmed up for {user_google_email}")
except HttpError as e:
# Warmup failure is non-fatal, search may still work
logger.warning(f"[contacts] Search cache warmup failed: {e}")
# =============================================================================
# Core Tier Tools
# =============================================================================
@server.tool(
title="List Contacts",
annotations=ToolAnnotations(
readOnlyHint=True,
destructiveHint=False,
idempotentHint=True,
openWorldHint=True,
),
)
@require_google_service("people", "contacts_read")
@handle_http_errors("list_contacts", service_type="people")
async def list_contacts(
service: Resource,
user_google_email: str,
page_size: int = 100,
page_token: Optional[str] = None,
sort_order: Optional[str] = None,
) -> str:
"""
List contacts for the authenticated user.
Args:
user_google_email (str): The user's Google email address. Required.
page_size (int): Maximum number of contacts to return (default: 100, max: 1000).
page_token (Optional[str]): Token for pagination.
sort_order (Optional[str]): Sort order: "LAST_MODIFIED_ASCENDING", "LAST_MODIFIED_DESCENDING", "FIRST_NAME_ASCENDING", or "LAST_NAME_ASCENDING".
Returns:
str: List of contacts with their basic information.
"""
logger.info(f"[list_contacts] Invoked. Email: '{user_google_email}'")
if page_size < 1:
raise UserInputError("page_size must be >= 1")
page_size = min(page_size, 1000)
params: Dict[str, Any] = {
"resourceName": "people/me",
"personFields": DEFAULT_PERSON_FIELDS,
"pageSize": page_size,
}
if page_token:
params["pageToken"] = page_token
if sort_order:
params["sortOrder"] = sort_order
result = await asyncio.to_thread(
service.people().connections().list(**params).execute
)
connections = result.get("connections", [])
next_page_token = result.get("nextPageToken")
total_people = result.get("totalPeople", len(connections))
if not connections:
return f"No contacts found for {user_google_email}."
response = (
f"Contacts for {user_google_email} ({len(connections)} of {total_people}):\n\n"
)
for person in connections:
response += _format_contact(person) + "\n\n"
if next_page_token:
response += f"Next page token: {next_page_token}"
logger.info(f"Found {len(connections)} contacts for {user_google_email}")
return response
@server.tool(
title="Get Contact",
annotations=ToolAnnotations(
readOnlyHint=True,
destructiveHint=False,
idempotentHint=True,
openWorldHint=True,
),
)
@require_google_service("people", "contacts_read")
@handle_http_errors("get_contact", service_type="people")
async def get_contact(
service: Resource,
user_google_email: str,
contact_id: str,
) -> str:
"""
Get detailed information about a specific contact.
Args:
user_google_email (str): The user's Google email address. Required.
contact_id (str): The contact ID (e.g., "c1234567890" or full resource name "people/c1234567890").
Returns:
str: Detailed contact information.
"""
# Normalize resource name
if not contact_id.startswith("people/"):
resource_name = f"people/{contact_id}"
else:
resource_name = contact_id
logger.info(
f"[get_contact] Invoked. Email: '{user_google_email}', Contact: {resource_name}"
)
person = await asyncio.to_thread(
service.people()
.get(resourceName=resource_name, personFields=DETAILED_PERSON_FIELDS)
.execute
)
response = f"Contact Details for {user_google_email}:\n\n"
response += _format_contact(person, detailed=True)
logger.info(f"Retrieved contact {resource_name} for {user_google_email}")
return response
@server.tool(
title="Search Contacts",
annotations=ToolAnnotations(
readOnlyHint=True,
destructiveHint=False,
idempotentHint=True,
openWorldHint=True,
),
)
@require_google_service("people", "contacts_read")
@handle_http_errors("search_contacts", service_type="people")
async def search_contacts(
service: Resource,
user_google_email: str,
query: str,
page_size: int = 30,
) -> str:
"""
Search contacts by name, email, phone number, or other fields.
Args:
user_google_email (str): The user's Google email address. Required.
query (str): Search query string (searches names, emails, phone numbers).
page_size (int): Maximum number of results to return (default: 30, max: 30).
Returns:
str: Matching contacts with their basic information.
"""
logger.info(
f"[search_contacts] Invoked. Email: '{user_google_email}', Query: '{query}'"
)
if page_size < 1:
raise UserInputError("page_size must be >= 1")
page_size = min(page_size, 30)
# Warm up the search cache if needed
await _warmup_search_cache(service, user_google_email)
result = await asyncio.to_thread(
service.people()
.searchContacts(
query=query,
readMask=DEFAULT_PERSON_FIELDS,
pageSize=page_size,
)
.execute
)
results = result.get("results", [])
if not results:
return f"No contacts found matching '{query}' for {user_google_email}."
response = f"Search Results for '{query}' ({len(results)} found):\n\n"
for item in results:
person = item.get("person", {})
response += _format_contact(person) + "\n\n"
logger.info(
f"Found {len(results)} contacts matching '{query}' for {user_google_email}"
)
return response
@server.tool(
title="Manage Contact",
annotations=ToolAnnotations(
readOnlyHint=False,
destructiveHint=True,
idempotentHint=False,
openWorldHint=True,
),
)
@require_google_service("people", "contacts")
@handle_http_errors("manage_contact", service_type="people")
async def manage_contact(
service: Resource,
user_google_email: str,
action: Literal["create", "update", "delete"],
contact_id: Optional[str] = None,
given_name: Optional[str] = None,
family_name: Optional[str] = None,
# New multi-value params
phones: Optional[List[PhoneInput]] = None,
emails: Optional[List[EmailInput]] = None,
organizations: Optional[List[OrganizationInput]] = None,
nicknames: Optional[List[NicknameInput]] = None,
urls: Optional[List[UrlInput]] = None,
user_defined: Optional[List[UserDefinedInput]] = None,
relations: Optional[List[RelationInput]] = None,
notes: Optional[str] = None,
address: Optional[str] = None,
birthday: Optional[str] = None,
# Merge modes for update action
phones_mode: Literal["merge", "replace", "remove"] = "merge",
emails_mode: Literal["merge", "replace", "remove"] = "merge",
organizations_mode: Literal["merge", "replace", "remove"] = "merge",
nicknames_mode: Literal["merge", "replace", "remove"] = "merge",
urls_mode: Literal["merge", "replace", "remove"] = "merge",
user_defined_mode: Literal["merge", "replace", "remove"] = "merge",
relations_mode: Literal["merge", "replace", "remove"] = "merge",
# Deprecated single-value aliases
phone: Optional[str] = None,
email: Optional[str] = None,
organization: Optional[str] = None,
job_title: Optional[str] = None,
) -> str:
"""
Create, update, or delete a contact. Consolidated tool replacing create_contact,
update_contact, and delete_contact.
Args:
user_google_email (str): The user's Google email address. Required.
action (str): The action to perform: "create", "update", or "delete".
contact_id (Optional[str]): The contact ID. Required for "update" and "delete" actions.
given_name (Optional[str]): First name (for create/update).
family_name (Optional[str]): Last name (for create/update).
phones (Optional[List[Dict]]): List of phone dicts {number, type?}.
Supported types: mobile, work, home, main, workMobile, internal, other, etc.
Use type="internal" for internal PBX/ATS short numbers (e.g. 250, 301) — stored
as a standalone number without + prefix, displayed as "Internal: 250".
emails (Optional[List[Dict]]): List of email dicts {address, type?}.
organizations (Optional[List[Dict]]): List of org dicts {name?, title?, department?, jobDescription?, type?}.
nicknames (Optional[List[Dict]]): List of nickname dicts {value, type?}.
Useful for bilingual contacts (e.g. Hebrew/English alternative forms). Android dialer
and WhatsApp search both index nicknames, enabling cross-script lookup.
Supported types: default, alternate_name, maiden_name, initials, other, etc.
urls (Optional[List[Dict]]): List of URL dicts {value, type?}.
Supported types: homepage, blog, profile, work, ftp, reservations, other, etc.
user_defined (Optional[List[Dict]]): List of custom field dicts {key, value}.
Useful for structured data like account numbers, IDs, or custom dates.
relations (Optional[List[Dict]]): List of relation dicts {person, type?}.
Supported types: spouse, child, parent, friend, manager, assistant, etc.
notes (Optional[str]): Additional notes (for create/update).
address (Optional[str]): Street address (for create/update).
birthday (Optional[str]): Birthday as 'YYYY-MM-DD', 'MM-DD' (no year), or 'clear'/'' to remove.
phones_mode (str): How to update phones on "update": "merge" (default), "replace", or "remove".
merge = read-modify-write with dedup by canonicalForm/normalized value.
replace = overwrite all phones with provided list.
remove = delete phones matching provided numbers.
emails_mode (str): How to update emails on "update": "merge" (default), "replace", or "remove".
organizations_mode (str): How to update orgs on "update": "merge" (default), "replace", or "remove".
nicknames_mode (str): How to update nicknames on "update": "merge" (default), "replace", or "remove".
urls_mode (str): How to update urls on "update": "merge" (default), "replace", or "remove".
merge dedups by normalized URL (lowercased, trailing slash stripped).
user_defined_mode (str): How to update custom fields on "update": "merge" (default), "replace", or "remove".
merge overrides value on matching key; new keys appended.
relations_mode (str): How to update relations on "update": "merge" (default), "replace", or "remove".
phone (Optional[str]): [DEPRECATED] Single phone number. Use phones=[{"number":..., "type":"mobile"}].
email (Optional[str]): [DEPRECATED] Email address. Use emails=[{"address":..., "type":"other"}].
organization (Optional[str]): [DEPRECATED] Company name. Use organizations=[{"name":...}].
job_title (Optional[str]): [DEPRECATED] Job title. Use organizations=[{"title":...}].
Returns:
str: Result of the action performed.
"""
action = action.lower().strip()
if action not in ("create", "update", "delete"):
raise UserInputError(
f"Invalid action '{action}'. Must be 'create', 'update', or 'delete'."
)
for mode_name, mode_val in [
("phones_mode", phones_mode),
("emails_mode", emails_mode),
("organizations_mode", organizations_mode),
("nicknames_mode", nicknames_mode),
("urls_mode", urls_mode),
("user_defined_mode", user_defined_mode),
("relations_mode", relations_mode),
]:
if mode_val not in ("merge", "replace", "remove"):
raise UserInputError(
f"Invalid {mode_name} '{mode_val}'. Must be 'merge', 'replace', or 'remove'."
)
logger.info(
f"[manage_contact] Invoked. Action: '{action}', Email: '{user_google_email}'"
)
if action == "create":
body = _build_person_body(
given_name=given_name,
family_name=family_name,
phones=phones,
emails=emails,
organizations=organizations,
nicknames=nicknames,
urls=urls,
user_defined=user_defined,
relations=relations,
notes=notes,
address=address,
birthday=birthday,
phone=phone,
email=email,
organization=organization,
job_title=job_title,
)
if not body:
raise UserInputError(
"At least one field (name, email, phone, etc.) must be provided."
)
result = await asyncio.to_thread(
service.people()
.createContact(body=body, personFields=DETAILED_PERSON_FIELDS)
.execute
)
response = f"Contact Created for {user_google_email}:\n\n"
response += _format_contact(result, detailed=True)
created_id = result.get("resourceName", "").replace("people/", "")
logger.info(f"Created contact {created_id} for {user_google_email}")
return response
# update and delete both require contact_id
if not contact_id:
raise UserInputError(f"contact_id is required for '{action}' action.")
# Normalize resource name
if not contact_id.startswith("people/"):
resource_name = f"people/{contact_id}"
else:
resource_name = contact_id
if action == "update":
# Retry loop for etag conflicts (412 Precondition Failed)
max_retries = 3
for attempt in range(max_retries):
# Fetch the contact to get current state and etag
current = await asyncio.to_thread(
service.people()
.get(resourceName=resource_name, personFields=DETAILED_PERSON_FIELDS)
.execute
)
etag = current.get("etag")
if not etag:
raise Exception("Unable to get contact etag for update.")
# Build body from provided params (returns new values only)
new_body = _build_person_body(
given_name=given_name,
family_name=family_name,
phones=phones,
emails=emails,
organizations=organizations,
nicknames=nicknames,
urls=urls,
user_defined=user_defined,
relations=relations,
notes=notes,
address=address,
birthday=birthday,
phone=phone,
email=email,
organization=organization,
job_title=job_title,
)
if not new_body:
raise UserInputError(
"At least one field (name, email, phone, etc.) must be provided."
)
# Apply merge modes for array fields
merged_body: Dict[str, Any] = dict(new_body)
if "phoneNumbers" in new_body:
merged_body["phoneNumbers"] = _merge_phones(
current.get("phoneNumbers", []),
new_body["phoneNumbers"],
phones_mode,
)
if "emailAddresses" in new_body:
merged_body["emailAddresses"] = _merge_emails(
current.get("emailAddresses", []),
new_body["emailAddresses"],
emails_mode,
)
if "organizations" in new_body:
merged_body["organizations"] = _merge_organizations(
current.get("organizations", []),
new_body["organizations"],
organizations_mode,
)
if "nicknames" in new_body:
merged_body["nicknames"] = _merge_nicknames(
current.get("nicknames", []),
new_body["nicknames"],
nicknames_mode,
)
if "urls" in new_body:
merged_body["urls"] = _merge_urls(
current.get("urls", []),
new_body["urls"],
urls_mode,
)
if "userDefined" in new_body:
merged_body["userDefined"] = _merge_user_defined(
current.get("userDefined", []),
new_body["userDefined"],
user_defined_mode,
)
if "relations" in new_body: