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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -2
  3. package/README.npm.md +34 -0
  4. package/auth/__init__.py +1 -0
  5. package/auth/auth_info_middleware.py +419 -0
  6. package/auth/client_secrets.py +76 -0
  7. package/auth/credential_store.py +598 -0
  8. package/auth/external_oauth_provider.py +369 -0
  9. package/auth/gateway_identity.py +164 -0
  10. package/auth/google_auth.py +1550 -0
  11. package/auth/google_oauth_provider.py +20 -0
  12. package/auth/mcp_session_middleware.py +95 -0
  13. package/auth/oauth21_session_store.py +1332 -0
  14. package/auth/oauth_callback_server.py +466 -0
  15. package/auth/oauth_config.py +693 -0
  16. package/auth/oauth_proxy_config.py +122 -0
  17. package/auth/oauth_responses.py +230 -0
  18. package/auth/oauth_types.py +92 -0
  19. package/auth/permissions.py +330 -0
  20. package/auth/port_resolver.py +153 -0
  21. package/auth/request_identity.py +89 -0
  22. package/auth/scopes.py +369 -0
  23. package/auth/service_decorator.py +1109 -0
  24. package/bin/google-workspace-mcp.cjs +123 -0
  25. package/core/__init__.py +1 -0
  26. package/core/api_enablement.py +108 -0
  27. package/core/attachment_storage.py +496 -0
  28. package/core/camel_case_middleware.py +98 -0
  29. package/core/cli.py +161 -0
  30. package/core/comments.py +609 -0
  31. package/core/config.py +57 -0
  32. package/core/context.py +43 -0
  33. package/core/file_limits.py +632 -0
  34. package/core/gcs_attachment_storage.py +253 -0
  35. package/core/http_utils.py +339 -0
  36. package/core/log_formatter.py +270 -0
  37. package/core/portable_schema_middleware.py +67 -0
  38. package/core/server.py +1192 -0
  39. package/core/startup_ui.py +239 -0
  40. package/core/storage.py +23 -0
  41. package/core/telemetry.py +194 -0
  42. package/core/tool_descriptions.py +19 -0
  43. package/core/tool_registry.py +311 -0
  44. package/core/tool_tier_loader.py +197 -0
  45. package/core/tool_tiers.yaml +179 -0
  46. package/core/toolset_header_middleware.py +67 -0
  47. package/core/utils.py +1537 -0
  48. package/core/valkey_storage.py +271 -0
  49. package/core/warning_filters.py +19 -0
  50. package/fastmcp_server.py +198 -0
  51. package/gappsscript/README.md +512 -0
  52. package/gappsscript/TESTING.md +254 -0
  53. package/gappsscript/__init__.py +0 -0
  54. package/gappsscript/apps_script_tools.py +1940 -0
  55. package/gcalendar/__init__.py +1 -0
  56. package/gcalendar/calendar_helpers.py +1323 -0
  57. package/gcalendar/calendar_tools.py +2252 -0
  58. package/gchat/__init__.py +7 -0
  59. package/gchat/chat_helpers.py +410 -0
  60. package/gchat/chat_tools.py +798 -0
  61. package/gcontacts/__init__.py +1 -0
  62. package/gcontacts/contacts_helpers.py +765 -0
  63. package/gcontacts/contacts_tools.py +1685 -0
  64. package/gdocs/__init__.py +0 -0
  65. package/gdocs/docs_anchors.py +163 -0
  66. package/gdocs/docs_comments.py +89 -0
  67. package/gdocs/docs_helpers.py +2201 -0
  68. package/gdocs/docs_links.py +87 -0
  69. package/gdocs/docs_markdown.py +828 -0
  70. package/gdocs/docs_markdown_writer.py +592 -0
  71. package/gdocs/docs_plain_text.py +463 -0
  72. package/gdocs/docs_structure.py +621 -0
  73. package/gdocs/docs_tables.py +425 -0
  74. package/gdocs/docs_tools.py +3300 -0
  75. package/gdocs/managers/__init__.py +18 -0
  76. package/gdocs/managers/batch_operation_manager.py +1694 -0
  77. package/gdocs/managers/header_footer_manager.py +526 -0
  78. package/gdocs/managers/table_operation_manager.py +488 -0
  79. package/gdocs/managers/validation_manager.py +1504 -0
  80. package/gdocs/operation_schemas.py +594 -0
  81. package/gdrive/__init__.py +0 -0
  82. package/gdrive/drive_helpers.py +1738 -0
  83. package/gdrive/drive_tools.py +3085 -0
  84. package/gforms/__init__.py +3 -0
  85. package/gforms/forms_tools.py +575 -0
  86. package/gmail/__init__.py +1 -0
  87. package/gmail/gmail_helpers.py +2107 -0
  88. package/gmail/gmail_tools.py +4895 -0
  89. package/gmail/gmail_web_mime.py +441 -0
  90. package/gsearch/__init__.py +0 -0
  91. package/gsearch/search_tools.py +253 -0
  92. package/gsheets/__init__.py +31 -0
  93. package/gsheets/sheets_helpers.py +2236 -0
  94. package/gsheets/sheets_tools.py +3280 -0
  95. package/gslides/__init__.py +0 -0
  96. package/gslides/slides_digest.py +390 -0
  97. package/gslides/slides_helpers.py +392 -0
  98. package/gslides/slides_markup.py +770 -0
  99. package/gslides/slides_tools.py +376 -0
  100. package/gtasks/__init__.py +5 -0
  101. package/gtasks/tasks_tools.py +936 -0
  102. package/main.py +1170 -0
  103. package/package.json +43 -4
  104. package/pyproject.toml +173 -0
  105. package/uv.lock +2504 -0
@@ -0,0 +1,1685 @@
1
+ """
2
+ Google Contacts MCP Tools (People API)
3
+
4
+ This module provides MCP tools for interacting with Google Contacts via the People API.
5
+ """
6
+
7
+ import asyncio
8
+ import logging
9
+ import warnings
10
+ from typing import Any, Dict, List, Literal, Optional
11
+
12
+ from googleapiclient.errors import HttpError
13
+ from mcp import Resource
14
+ from pydantic import AliasChoices, BaseModel, ConfigDict, Field
15
+
16
+ from mcp.types import ToolAnnotations
17
+
18
+ from auth.oauth_config import is_service_account_enabled
19
+ from auth.service_decorator import require_google_service
20
+ from core.server import server
21
+ from core.utils import (
22
+ StringList,
23
+ UserInputError,
24
+ handle_http_errors,
25
+ hide_local_file_args,
26
+ )
27
+ from gcontacts.contacts_helpers import (
28
+ DEFAULT_PERSON_FIELDS,
29
+ OTHER_CONTACT_FIELDS,
30
+ _contact_group_resource_name,
31
+ _format_contact,
32
+ _list_contacts,
33
+ _manage_contact_photo,
34
+ _merge_emails,
35
+ _merge_names,
36
+ _merge_nicknames,
37
+ _merge_organizations,
38
+ _merge_phones,
39
+ _merge_relations,
40
+ _merge_urls,
41
+ _merge_user_defined,
42
+ _parse_birthday,
43
+ _people_resource_name,
44
+ _search_request,
45
+ )
46
+
47
+ logger = logging.getLogger(__name__)
48
+
49
+ # Detailed person fields for get operations
50
+ DETAILED_PERSON_FIELDS = (
51
+ "names,nicknames,emailAddresses,phoneNumbers,organizations,biographies,"
52
+ "addresses,birthdays,urls,userDefined,relations,photos,metadata,memberships"
53
+ )
54
+
55
+ # Contact group fields
56
+ CONTACT_GROUP_FIELDS = "name,groupType,memberCount,metadata"
57
+
58
+ # Cache warmup tracking
59
+ _search_cache_warmed_up: Dict[str, bool] = {}
60
+
61
+ # Known phone types supported by Google People API (custom types also allowed)
62
+ KNOWN_PHONE_TYPES = {
63
+ "home",
64
+ "work",
65
+ "mobile",
66
+ "homeFax",
67
+ "workFax",
68
+ "otherFax",
69
+ "pager",
70
+ "workMobile",
71
+ "workPager",
72
+ "main",
73
+ "googleVoice",
74
+ "other",
75
+ "internal",
76
+ }
77
+
78
+
79
+ class PhoneInput(BaseModel):
80
+ """Typed input for a phone entry."""
81
+
82
+ model_config = ConfigDict(extra="forbid")
83
+
84
+ number: Optional[str] = Field(
85
+ default=None,
86
+ description="Phone number value.",
87
+ )
88
+ value: Optional[str] = Field(
89
+ default=None,
90
+ description="Backward-compatible alias for the phone number value.",
91
+ )
92
+ type: Optional[str] = Field(
93
+ default=None,
94
+ description="Phone type such as mobile, work, home, or internal.",
95
+ )
96
+
97
+
98
+ class EmailInput(BaseModel):
99
+ """Typed input for an email entry."""
100
+
101
+ model_config = ConfigDict(extra="forbid")
102
+
103
+ address: Optional[str] = Field(
104
+ default=None,
105
+ description="Email address value.",
106
+ )
107
+ value: Optional[str] = Field(
108
+ default=None,
109
+ description="Backward-compatible alias for the email address value.",
110
+ )
111
+ type: Optional[str] = Field(
112
+ default=None,
113
+ description="Email type such as work, home, or other.",
114
+ )
115
+
116
+
117
+ class OrganizationInput(BaseModel):
118
+ """Typed input for an organization entry."""
119
+
120
+ model_config = ConfigDict(extra="forbid")
121
+
122
+ name: Optional[str] = Field(default=None, description="Organization name.")
123
+ title: Optional[str] = Field(default=None, description="Job title.")
124
+ department: Optional[str] = Field(default=None, description="Department name.")
125
+ jobDescription: Optional[str] = Field(
126
+ default=None,
127
+ description="Optional organization job description.",
128
+ validation_alias=AliasChoices("jobDescription", "description"),
129
+ )
130
+ type: Optional[str] = Field(
131
+ default=None,
132
+ description="Organization type such as work or school.",
133
+ )
134
+
135
+
136
+ class NicknameInput(BaseModel):
137
+ """Typed input for a nickname entry."""
138
+
139
+ model_config = ConfigDict(extra="forbid")
140
+
141
+ value: str = Field(
142
+ description="Nickname value. Used for bilingual contacts (e.g. Hebrew alternative form).",
143
+ )
144
+ type: Optional[str] = Field(
145
+ default=None,
146
+ description="Nickname type such as default, alternate_name, maiden_name, initials, or other.",
147
+ )
148
+
149
+
150
+ class UrlInput(BaseModel):
151
+ """Typed input for a URL entry."""
152
+
153
+ model_config = ConfigDict(extra="forbid")
154
+
155
+ value: str = Field(
156
+ description="The URL value (e.g. https://example.com).",
157
+ )
158
+ type: Optional[str] = Field(
159
+ default=None,
160
+ description="URL type such as homepage, blog, profile, work, ftp, reservations, or other. Custom values allowed.",
161
+ )
162
+
163
+
164
+ class UserDefinedInput(BaseModel):
165
+ """Typed input for a userDefined custom field entry."""
166
+
167
+ model_config = ConfigDict(extra="forbid")
168
+
169
+ key: str = Field(
170
+ description="Custom field key (e.g. 'ID', 'Hebrew Birthday', 'Account Number').",
171
+ )
172
+ value: str = Field(
173
+ default="",
174
+ description="Custom field value. May be omitted when using remove mode (only the key is needed).",
175
+ )
176
+
177
+
178
+ class RelationInput(BaseModel):
179
+ """Typed input for a relation entry (spouse, parent, child, etc.)."""
180
+
181
+ model_config = ConfigDict(extra="forbid")
182
+
183
+ person: str = Field(
184
+ description="The related person's name (matched against contact names by Google Assistant).",
185
+ )
186
+ type: Optional[str] = Field(
187
+ default=None,
188
+ description="Relation type: spouse, child, parent, father, mother, sister, brother, friend, manager, assistant, partner, sibling, domesticPartner, or custom.",
189
+ )
190
+
191
+
192
+ class ContactInput(BaseModel):
193
+ """Typed batch-create input for a contact."""
194
+
195
+ model_config = ConfigDict(extra="forbid")
196
+
197
+ given_name: Optional[str] = None
198
+ family_name: Optional[str] = None
199
+ phones: Optional[List[PhoneInput]] = None
200
+ emails: Optional[List[EmailInput]] = None
201
+ organizations: Optional[List[OrganizationInput]] = None
202
+ nicknames: Optional[List[NicknameInput]] = None
203
+ urls: Optional[List[UrlInput]] = None
204
+ user_defined: Optional[List[UserDefinedInput]] = None
205
+ relations: Optional[List[RelationInput]] = None
206
+ notes: Optional[str] = None
207
+ address: Optional[str] = None
208
+ birthday: Optional[str] = Field(
209
+ default=None,
210
+ description="Birthday as 'YYYY-MM-DD', 'MM-DD' (no year), or 'clear'/'' to remove.",
211
+ )
212
+ phone: Optional[str] = None
213
+ email: Optional[str] = None
214
+ organization: Optional[str] = None
215
+ job_title: Optional[str] = None
216
+
217
+
218
+ class ContactUpdateInput(ContactInput):
219
+ """Typed batch-update input for a contact."""
220
+
221
+ contact_id: str = Field(
222
+ description='Contact ID like "c123" or full resource name like "people/c123".'
223
+ )
224
+
225
+
226
+ def _coerce_phone_input(phone: Any) -> PhoneInput:
227
+ if isinstance(phone, PhoneInput):
228
+ return phone
229
+ if isinstance(phone, dict):
230
+ phone = dict(phone)
231
+ if not phone.get("type") and phone.get("label"):
232
+ phone["type"] = phone["label"]
233
+ phone.pop("label", None)
234
+ return PhoneInput.model_validate(phone)
235
+
236
+
237
+ def _coerce_email_input(email: Any) -> EmailInput:
238
+ if isinstance(email, EmailInput):
239
+ return email
240
+ if isinstance(email, dict):
241
+ email = dict(email)
242
+ if not email.get("type") and email.get("label"):
243
+ email["type"] = email["label"]
244
+ email.pop("label", None)
245
+ return EmailInput.model_validate(email)
246
+
247
+
248
+ def _coerce_organization_input(org: Any) -> OrganizationInput:
249
+ if isinstance(org, OrganizationInput):
250
+ return org
251
+ return OrganizationInput.model_validate(org)
252
+
253
+
254
+ def _coerce_nickname_input(nickname: Any) -> NicknameInput:
255
+ if isinstance(nickname, NicknameInput):
256
+ return nickname
257
+ if isinstance(nickname, str):
258
+ return NicknameInput(value=nickname)
259
+ return NicknameInput.model_validate(nickname)
260
+
261
+
262
+ def _coerce_url_input(url: Any) -> UrlInput:
263
+ if isinstance(url, UrlInput):
264
+ return url
265
+ if isinstance(url, str):
266
+ return UrlInput(value=url)
267
+ return UrlInput.model_validate(url)
268
+
269
+
270
+ def _coerce_user_defined_input(entry: Any) -> UserDefinedInput:
271
+ if isinstance(entry, UserDefinedInput):
272
+ return entry
273
+ return UserDefinedInput.model_validate(entry)
274
+
275
+
276
+ def _coerce_relation_input(relation: Any) -> RelationInput:
277
+ if isinstance(relation, RelationInput):
278
+ return relation
279
+ if isinstance(relation, str):
280
+ return RelationInput(person=relation)
281
+ return RelationInput.model_validate(relation)
282
+
283
+
284
+ def _coerce_contact_input(contact: Any) -> ContactInput:
285
+ if isinstance(contact, ContactInput):
286
+ return contact
287
+ return ContactInput.model_validate(contact)
288
+
289
+
290
+ def _coerce_contact_update_input(update: Any) -> ContactUpdateInput:
291
+ if isinstance(update, ContactUpdateInput):
292
+ return update
293
+ return ContactUpdateInput.model_validate(update)
294
+
295
+
296
+ def _build_person_body(
297
+ given_name: Optional[str] = None,
298
+ family_name: Optional[str] = None,
299
+ # New multi-value params
300
+ phones: Optional[List[PhoneInput]] = None,
301
+ emails: Optional[List[EmailInput]] = None,
302
+ organizations: Optional[List[OrganizationInput]] = None,
303
+ nicknames: Optional[List[NicknameInput]] = None,
304
+ urls: Optional[List[UrlInput]] = None,
305
+ user_defined: Optional[List[UserDefinedInput]] = None,
306
+ relations: Optional[List[RelationInput]] = None,
307
+ notes: Optional[str] = None,
308
+ address: Optional[str] = None,
309
+ birthday: Optional[str] = None,
310
+ # Deprecated single-value aliases
311
+ email: Optional[str] = None,
312
+ phone: Optional[str] = None,
313
+ organization: Optional[str] = None,
314
+ job_title: Optional[str] = None,
315
+ ) -> Dict[str, Any]:
316
+ """
317
+ Build a Person resource body for create/update operations.
318
+
319
+ Accepts both new list-based params (phones, emails, organizations) and
320
+ deprecated single-value aliases (phone, email, organization, job_title).
321
+
322
+ Args:
323
+ given_name: First name.
324
+ family_name: Last name.
325
+ phones: List of PhoneInput items {number, value?, type?}.
326
+ Supported types: mobile, work, home, main, workMobile, internal, other, etc.
327
+ Use type="internal" for PBX/ATS short numbers (e.g. 250, 301).
328
+ emails: List of EmailInput items {address, value?, type?}.
329
+ organizations: List of OrganizationInput items {name?, title?, department?, jobDescription?, type?}.
330
+ notes: Additional notes/biography.
331
+ address: Street address, replacing any existing addresses. "" clears them.
332
+ birthday: Birthday as 'YYYY-MM-DD', 'MM-DD' (no year), or 'clear'/'' to remove.
333
+ email: [DEPRECATED] Single email address. Use emails instead.
334
+ phone: [DEPRECATED] Single phone number. Use phones instead.
335
+ organization: [DEPRECATED] Company/organization name. Use organizations instead.
336
+ job_title: [DEPRECATED] Job title. Use organizations instead.
337
+
338
+ Returns:
339
+ Person resource body dictionary.
340
+ """
341
+ body: Dict[str, Any] = {}
342
+
343
+ if phones is not None:
344
+ phones = [_coerce_phone_input(phone) for phone in phones]
345
+ if emails is not None:
346
+ emails = [_coerce_email_input(email_entry) for email_entry in emails]
347
+ if organizations is not None:
348
+ organizations = [_coerce_organization_input(org) for org in organizations]
349
+ if nicknames is not None:
350
+ nicknames = [_coerce_nickname_input(n) for n in nicknames]
351
+ if urls is not None:
352
+ urls = [_coerce_url_input(u) for u in urls]
353
+ if user_defined is not None:
354
+ user_defined = [_coerce_user_defined_input(ud) for ud in user_defined]
355
+ if relations is not None:
356
+ relations = [_coerce_relation_input(r) for r in relations]
357
+
358
+ name = {
359
+ key: value
360
+ for key, value in (("givenName", given_name), ("familyName", family_name))
361
+ if value is not None
362
+ }
363
+ if name:
364
+ body["names"] = [name]
365
+
366
+ # --- Emails ---
367
+ if emails is not None and email is not None:
368
+ warnings.warn(
369
+ "Parameter 'email' ignored because 'emails' was provided",
370
+ DeprecationWarning,
371
+ stacklevel=3,
372
+ )
373
+ if emails is None and email is not None:
374
+ warnings.warn(
375
+ "Parameter 'email' is deprecated. Use 'emails=[{\"address\": ..., \"type\": ...}]' instead.",
376
+ DeprecationWarning,
377
+ stacklevel=3,
378
+ )
379
+ emails = [EmailInput(address=email, type="other")]
380
+
381
+ if emails is not None:
382
+ email_entries = []
383
+ for e in emails:
384
+ entry: Dict[str, Any] = {"value": e.address or e.value or ""}
385
+ if e.type:
386
+ entry["type"] = e.type
387
+ if entry["value"]:
388
+ email_entries.append(entry)
389
+ body["emailAddresses"] = email_entries
390
+
391
+ # --- Phones ---
392
+ if phones is not None and phone is not None:
393
+ warnings.warn(
394
+ "Parameter 'phone' ignored because 'phones' was provided",
395
+ DeprecationWarning,
396
+ stacklevel=3,
397
+ )
398
+ if phones is None and phone is not None:
399
+ warnings.warn(
400
+ "Parameter 'phone' is deprecated. Use 'phones=[{\"number\": ..., \"type\": ...}]' instead.",
401
+ DeprecationWarning,
402
+ stacklevel=3,
403
+ )
404
+ phones = [PhoneInput(number=phone, type="mobile")]
405
+
406
+ if phones is not None:
407
+ phone_entries = []
408
+ for p in phones:
409
+ number = p.number or p.value or ""
410
+ if not number:
411
+ continue
412
+ entry = {"value": number}
413
+ if p.type:
414
+ entry["type"] = p.type
415
+ phone_entries.append(entry)
416
+ body["phoneNumbers"] = phone_entries
417
+
418
+ # --- Organizations ---
419
+ if organizations is not None and (
420
+ organization is not None or job_title is not None
421
+ ):
422
+ ignored_params = []
423
+ if organization is not None:
424
+ ignored_params.append("'organization'")
425
+ if job_title is not None:
426
+ ignored_params.append("'job_title'")
427
+ ignored = " and ".join(ignored_params)
428
+ parameter_label = "Parameter" if len(ignored_params) == 1 else "Parameters"
429
+ warnings.warn(
430
+ f"{parameter_label} {ignored} ignored because 'organizations' was provided",
431
+ DeprecationWarning,
432
+ stacklevel=3,
433
+ )
434
+ if organizations is None and (organization is not None or job_title is not None):
435
+ if organization is not None:
436
+ warnings.warn(
437
+ "Parameter 'organization' is deprecated. Use 'organizations=[{\"name\": ..., \"type\": ...}]' instead.",
438
+ DeprecationWarning,
439
+ stacklevel=3,
440
+ )
441
+ if job_title is not None:
442
+ warnings.warn(
443
+ "Parameter 'job_title' is deprecated. Use 'organizations=[{\"title\": ...}]' instead.",
444
+ DeprecationWarning,
445
+ stacklevel=3,
446
+ )
447
+ organizations = [OrganizationInput(name=organization, title=job_title)]
448
+
449
+ if organizations is not None:
450
+ org_entries = []
451
+ for org in organizations:
452
+ entry = {}
453
+ if org.name:
454
+ entry["name"] = org.name
455
+ if org.title:
456
+ entry["title"] = org.title
457
+ if org.department:
458
+ entry["department"] = org.department
459
+ if org.jobDescription:
460
+ entry["jobDescription"] = org.jobDescription
461
+ if org.type:
462
+ entry["type"] = org.type
463
+ if entry:
464
+ org_entries.append(entry)
465
+ body["organizations"] = org_entries
466
+
467
+ # --- Nicknames ---
468
+ if nicknames is not None:
469
+ nickname_entries = []
470
+ for n in nicknames:
471
+ value = (n.value or "").strip()
472
+ if not value:
473
+ continue
474
+ entry: Dict[str, Any] = {"value": value}
475
+ if n.type:
476
+ entry["type"] = n.type
477
+ nickname_entries.append(entry)
478
+ body["nicknames"] = nickname_entries
479
+
480
+ # --- URLs ---
481
+ if urls is not None:
482
+ url_entries = []
483
+ for u in urls:
484
+ value = (u.value or "").strip()
485
+ if not value:
486
+ continue
487
+ entry = {"value": value}
488
+ if u.type:
489
+ entry["type"] = u.type
490
+ url_entries.append(entry)
491
+ body["urls"] = url_entries
492
+
493
+ # --- User Defined custom fields ---
494
+ if user_defined is not None:
495
+ ud_entries = []
496
+ for ud in user_defined:
497
+ key = (ud.key or "").strip()
498
+ value = (ud.value or "").strip()
499
+ if not key:
500
+ continue
501
+ entry: Dict[str, str] = {"key": key}
502
+ if value:
503
+ entry["value"] = value
504
+ ud_entries.append(entry)
505
+ body["userDefined"] = ud_entries
506
+
507
+ # --- Relations ---
508
+ if relations is not None:
509
+ relation_entries = []
510
+ for r in relations:
511
+ person = (r.person or "").strip()
512
+ if not person:
513
+ continue
514
+ entry = {"person": person}
515
+ if r.type:
516
+ entry["type"] = r.type
517
+ relation_entries.append(entry)
518
+ body["relations"] = relation_entries
519
+
520
+ # notes=None → no change. notes="" → explicit clear (empty biographies).
521
+ # notes="text" → write that text.
522
+ if notes is not None:
523
+ if notes:
524
+ body["biographies"] = [{"value": notes, "contentType": "TEXT_PLAIN"}]
525
+ else:
526
+ body["biographies"] = []
527
+
528
+ # Same convention as notes: None → no change, "" → explicit clear.
529
+ if address is not None:
530
+ body["addresses"] = [{"formattedValue": address}] if address else []
531
+
532
+ if birthday is not None:
533
+ if birthday.strip().lower() in ("clear", ""):
534
+ body["birthdays"] = []
535
+ else:
536
+ body["birthdays"] = [_parse_birthday(birthday)]
537
+
538
+ return body
539
+
540
+
541
+ async def _warmup_search_cache(
542
+ service: Resource, user_google_email: str, source: str
543
+ ) -> None:
544
+ """Send the empty-query search the People API needs before a source's first search."""
545
+ global _search_cache_warmed_up
546
+
547
+ cache_key = f"{source}:{user_google_email}"
548
+ if _search_cache_warmed_up.get(cache_key):
549
+ return
550
+
551
+ try:
552
+ logger.debug(f"[contacts] Warming up search cache for {user_google_email}")
553
+ request = _search_request(
554
+ service, source, query="", readMask="names", pageSize=1
555
+ )
556
+ await asyncio.to_thread(request.execute)
557
+ _search_cache_warmed_up[cache_key] = True
558
+ logger.debug(f"[contacts] Search cache warmed up for {user_google_email}")
559
+ except HttpError as e:
560
+ # Warmup failure is non-fatal, search may still work
561
+ logger.warning(f"[contacts] Search cache warmup failed: {e}")
562
+
563
+
564
+ # =============================================================================
565
+ # Core Tier Tools
566
+ # =============================================================================
567
+
568
+
569
+ @server.tool(
570
+ title="List Contacts",
571
+ annotations=ToolAnnotations(
572
+ readOnlyHint=True,
573
+ destructiveHint=False,
574
+ idempotentHint=True,
575
+ openWorldHint=True,
576
+ ),
577
+ )
578
+ @require_google_service("people", "contacts_read")
579
+ @handle_http_errors("list_contacts", is_read_only=True, service_type="people")
580
+ async def list_contacts(
581
+ service: Resource,
582
+ user_google_email: str,
583
+ page_size: int = 100,
584
+ page_token: Optional[str] = None,
585
+ sort_order: Optional[str] = None,
586
+ request_sync_token: bool = False,
587
+ sync_token: Optional[str] = None,
588
+ ) -> str:
589
+ """
590
+ List contacts for the authenticated user, optionally as a full or incremental sync.
591
+
592
+ Args:
593
+ user_google_email (str): The user's Google email address. Required.
594
+ page_size (int): Maximum number of contacts to return (default: 100, max: 1000).
595
+ page_token (Optional[str]): Token for pagination. Keep all other arguments unchanged when following it.
596
+ sort_order (Optional[str]): Sort order: "LAST_MODIFIED_ASCENDING", "LAST_MODIFIED_DESCENDING", "FIRST_NAME_ASCENDING", or "LAST_NAME_ASCENDING". Not supported when syncing.
597
+ request_sync_token (bool): Start a full sync. The last page returns a sync token.
598
+ sync_token (Optional[str]): List only changes since the sync that returned this token, marking deleted contacts. The last page returns a new sync token.
599
+
600
+ Returns:
601
+ str: List of contacts with their basic information.
602
+ """
603
+ return await _list_contacts(
604
+ service,
605
+ user_google_email,
606
+ page_size,
607
+ page_token,
608
+ sort_order,
609
+ request_sync_token,
610
+ sync_token,
611
+ )
612
+
613
+
614
+ @server.tool(
615
+ title="Get Contact",
616
+ annotations=ToolAnnotations(
617
+ readOnlyHint=True,
618
+ destructiveHint=False,
619
+ idempotentHint=True,
620
+ openWorldHint=True,
621
+ ),
622
+ )
623
+ @require_google_service("people", "contacts_read")
624
+ @handle_http_errors("get_contact", service_type="people")
625
+ async def get_contact(
626
+ service: Resource,
627
+ user_google_email: str,
628
+ contact_id: str,
629
+ ) -> str:
630
+ """
631
+ Get detailed information about a specific contact.
632
+
633
+ Args:
634
+ user_google_email (str): The user's Google email address. Required.
635
+ contact_id (str): The contact ID (e.g., "c1234567890" or full resource name "people/c1234567890").
636
+
637
+ Returns:
638
+ str: Detailed contact information.
639
+ """
640
+ resource_name = _people_resource_name(contact_id)
641
+
642
+ logger.info(
643
+ f"[get_contact] Invoked. Email: '{user_google_email}', Contact: {resource_name}"
644
+ )
645
+
646
+ person = await asyncio.to_thread(
647
+ service.people()
648
+ .get(resourceName=resource_name, personFields=DETAILED_PERSON_FIELDS)
649
+ .execute
650
+ )
651
+
652
+ response = f"Contact Details for {user_google_email}:\n\n"
653
+ response += _format_contact(person, detailed=True)
654
+
655
+ logger.info(f"Retrieved contact {resource_name} for {user_google_email}")
656
+ return response
657
+
658
+
659
+ @server.tool(
660
+ title="Search Contacts",
661
+ annotations=ToolAnnotations(
662
+ readOnlyHint=True,
663
+ destructiveHint=False,
664
+ idempotentHint=True,
665
+ openWorldHint=True,
666
+ ),
667
+ )
668
+ @require_google_service("people", "contacts_read")
669
+ @handle_http_errors("search_contacts", service_type="people")
670
+ async def search_contacts(
671
+ service: Resource,
672
+ user_google_email: str,
673
+ query: str,
674
+ page_size: int = 30,
675
+ source: Literal["saved", "other"] = "saved",
676
+ ) -> str:
677
+ """
678
+ Search contacts by name, email, phone number, or other fields.
679
+
680
+ Args:
681
+ user_google_email (str): The user's Google email address. Required.
682
+ query (str): Search query string (searches names, emails, phone numbers).
683
+ page_size (int): Maximum number of results to return (default: 30, max: 30).
684
+ source (str): "saved" (default) or "other" for people you've emailed but never saved (Gmail's "Other contacts").
685
+
686
+ Returns:
687
+ str: Matching contacts with their basic information.
688
+ """
689
+ logger.info(
690
+ f"[search_contacts] Invoked. Email: '{user_google_email}', query_len={len(query)}"
691
+ )
692
+ logger.debug(f"[search_contacts] Query: '{query}'")
693
+
694
+ if page_size < 1:
695
+ raise UserInputError("page_size must be >= 1")
696
+ page_size = min(page_size, 30)
697
+ if source == "other" and is_service_account_enabled():
698
+ raise UserInputError(
699
+ "source='other' is not available in service-account mode; "
700
+ "it needs user OAuth with the contacts.other.readonly scope."
701
+ )
702
+
703
+ # Warm up the search cache if needed
704
+ await _warmup_search_cache(service, user_google_email, source)
705
+
706
+ request = _search_request(
707
+ service,
708
+ source,
709
+ query=query,
710
+ readMask=OTHER_CONTACT_FIELDS if source == "other" else DEFAULT_PERSON_FIELDS,
711
+ pageSize=page_size,
712
+ )
713
+ result = await asyncio.to_thread(request.execute)
714
+
715
+ results = result.get("results", [])
716
+
717
+ if not results:
718
+ label = "other contacts" if source == "other" else "contacts"
719
+ return f"No {label} found matching '{query}' for {user_google_email}."
720
+
721
+ response = f"Search Results for '{query}' ({len(results)} found):\n\n"
722
+
723
+ for item in results:
724
+ person = item.get("person", {})
725
+ response += _format_contact(person) + "\n\n"
726
+
727
+ logger.info(f"Found {len(results)} contacts for {user_google_email}")
728
+ return response
729
+
730
+
731
+ @server.tool(
732
+ title="Manage Contact",
733
+ annotations=ToolAnnotations(
734
+ readOnlyHint=False,
735
+ destructiveHint=True,
736
+ idempotentHint=False,
737
+ openWorldHint=True,
738
+ ),
739
+ )
740
+ @hide_local_file_args("file_path")
741
+ @require_google_service("people", "contacts")
742
+ @handle_http_errors("manage_contact", service_type="people")
743
+ async def manage_contact(
744
+ service: Resource,
745
+ user_google_email: str,
746
+ action: Literal["create", "update", "delete", "set_photo", "delete_photo"],
747
+ contact_id: Optional[str] = None,
748
+ given_name: Optional[str] = None,
749
+ family_name: Optional[str] = None,
750
+ # New multi-value params
751
+ phones: Optional[List[PhoneInput]] = None,
752
+ emails: Optional[List[EmailInput]] = None,
753
+ organizations: Optional[List[OrganizationInput]] = None,
754
+ nicknames: Optional[List[NicknameInput]] = None,
755
+ urls: Optional[List[UrlInput]] = None,
756
+ user_defined: Optional[List[UserDefinedInput]] = None,
757
+ relations: Optional[List[RelationInput]] = None,
758
+ notes: Optional[str] = None,
759
+ address: Optional[str] = None,
760
+ birthday: Optional[str] = None,
761
+ # Merge modes for update action
762
+ phones_mode: Literal["merge", "replace", "remove"] = "merge",
763
+ emails_mode: Literal["merge", "replace", "remove"] = "merge",
764
+ organizations_mode: Literal["merge", "replace", "remove"] = "merge",
765
+ nicknames_mode: Literal["merge", "replace", "remove"] = "merge",
766
+ urls_mode: Literal["merge", "replace", "remove"] = "merge",
767
+ user_defined_mode: Literal["merge", "replace", "remove"] = "merge",
768
+ relations_mode: Literal["merge", "replace", "remove"] = "merge",
769
+ # Deprecated single-value aliases
770
+ phone: Optional[str] = None,
771
+ email: Optional[str] = None,
772
+ organization: Optional[str] = None,
773
+ job_title: Optional[str] = None,
774
+ photo_base64: Optional[str] = None,
775
+ file_path: Optional[str] = None,
776
+ ) -> str:
777
+ """
778
+ Create, update, or delete a contact, or set/remove its photo.
779
+ Photo actions modify only the photo, not the contact's other fields.
780
+
781
+ Args:
782
+ user_google_email (str): The user's Google email address. Required.
783
+ action (str): The action to perform: "create", "update", "delete", "set_photo", or "delete_photo".
784
+ contact_id (Optional[str]): The contact ID. Required for all actions except "create".
785
+ given_name (Optional[str]): First name (for create/update).
786
+ family_name (Optional[str]): Last name (for create/update).
787
+ phones (Optional[List[Dict]]): List of phone dicts {number, type?}.
788
+ Supported types: mobile, work, home, main, workMobile, internal, other, etc.
789
+ Use type="internal" for internal PBX/ATS short numbers (e.g. 250, 301) — stored
790
+ as a standalone number without + prefix, displayed as "Internal: 250".
791
+ emails (Optional[List[Dict]]): List of email dicts {address, type?}.
792
+ organizations (Optional[List[Dict]]): List of org dicts {name?, title?, department?, jobDescription?, type?}.
793
+ nicknames (Optional[List[Dict]]): List of nickname dicts {value, type?}.
794
+ Useful for bilingual contacts (e.g. Hebrew/English alternative forms). Android dialer
795
+ and WhatsApp search both index nicknames, enabling cross-script lookup.
796
+ Supported types: default, alternate_name, maiden_name, initials, other, etc.
797
+ urls (Optional[List[Dict]]): List of URL dicts {value, type?}.
798
+ Supported types: homepage, blog, profile, work, ftp, reservations, other, etc.
799
+ user_defined (Optional[List[Dict]]): List of custom field dicts {key, value}.
800
+ Useful for structured data like account numbers, IDs, or custom dates.
801
+ relations (Optional[List[Dict]]): List of relation dicts {person, type?}.
802
+ Supported types: spouse, child, parent, friend, manager, assistant, etc.
803
+ notes (Optional[str]): Additional notes (for create/update).
804
+ address (Optional[str]): Street address, replacing any existing addresses. "" clears them (for create/update).
805
+ birthday (Optional[str]): Birthday as 'YYYY-MM-DD', 'MM-DD' (no year), or 'clear'/'' to remove.
806
+ phones_mode (str): How to update phones on "update": "merge" (default), "replace", or "remove".
807
+ merge = read-modify-write with dedup by canonicalForm/normalized value.
808
+ replace = overwrite all phones with provided list.
809
+ remove = delete phones matching provided numbers.
810
+ emails_mode (str): How to update emails on "update": "merge" (default), "replace", or "remove".
811
+ organizations_mode (str): How to update orgs on "update": "merge" (default), "replace", or "remove".
812
+ nicknames_mode (str): How to update nicknames on "update": "merge" (default), "replace", or "remove".
813
+ urls_mode (str): How to update urls on "update": "merge" (default), "replace", or "remove".
814
+ merge and remove match URLs case-insensitively on scheme and host only, ignoring a trailing slash.
815
+ user_defined_mode (str): How to update custom fields on "update": "merge" (default), "replace", or "remove".
816
+ merge overrides value on matching key; new keys appended.
817
+ relations_mode (str): How to update relations on "update": "merge" (default), "replace", or "remove".
818
+ phone (Optional[str]): [DEPRECATED] Single phone number. Use phones=[{"number":..., "type":"mobile"}].
819
+ email (Optional[str]): [DEPRECATED] Email address. Use emails=[{"address":..., "type":"other"}].
820
+ organization (Optional[str]): [DEPRECATED] Company name. Use organizations=[{"name":...}].
821
+ job_title (Optional[str]): [DEPRECATED] Job title. Use organizations=[{"title":...}].
822
+ photo_base64 (Optional[str]): Raw Base64 JPEG or PNG bytes for "set_photo", without a data URL prefix. Maximum 5 MiB decoded.
823
+ file_path (Optional[str]): Server-side JPEG or PNG path for "set_photo", instead of photo_base64. Must be under ALLOWED_FILE_DIRS. Maximum 5 MiB.
824
+
825
+ Returns:
826
+ str: Result of the action performed.
827
+ """
828
+ action = action.lower().strip()
829
+ if action not in ("create", "update", "delete", "set_photo", "delete_photo"):
830
+ raise UserInputError(
831
+ f"Invalid action '{action}'. Must be 'create', 'update', 'delete', 'set_photo', or 'delete_photo'."
832
+ )
833
+
834
+ photo_base64 = photo_base64 or None
835
+ file_path = file_path or None
836
+ if action != "set_photo" and (photo_base64 is not None or file_path is not None):
837
+ raise UserInputError("Photo inputs are only supported with action='set_photo'.")
838
+
839
+ for mode_name, mode_val in [
840
+ ("phones_mode", phones_mode),
841
+ ("emails_mode", emails_mode),
842
+ ("organizations_mode", organizations_mode),
843
+ ("nicknames_mode", nicknames_mode),
844
+ ("urls_mode", urls_mode),
845
+ ("user_defined_mode", user_defined_mode),
846
+ ("relations_mode", relations_mode),
847
+ ]:
848
+ if mode_val not in ("merge", "replace", "remove"):
849
+ raise UserInputError(
850
+ f"Invalid {mode_name} '{mode_val}'. Must be 'merge', 'replace', or 'remove'."
851
+ )
852
+
853
+ logger.info(
854
+ f"[manage_contact] Invoked. Action: '{action}', Email: '{user_google_email}'"
855
+ )
856
+
857
+ if action == "create":
858
+ body = _build_person_body(
859
+ given_name=given_name,
860
+ family_name=family_name,
861
+ phones=phones,
862
+ emails=emails,
863
+ organizations=organizations,
864
+ nicknames=nicknames,
865
+ urls=urls,
866
+ user_defined=user_defined,
867
+ relations=relations,
868
+ notes=notes,
869
+ address=address,
870
+ birthday=birthday,
871
+ phone=phone,
872
+ email=email,
873
+ organization=organization,
874
+ job_title=job_title,
875
+ )
876
+
877
+ if not body:
878
+ raise UserInputError(
879
+ "At least one field (name, email, phone, etc.) must be provided."
880
+ )
881
+
882
+ result = await asyncio.to_thread(
883
+ service.people()
884
+ .createContact(body=body, personFields=DETAILED_PERSON_FIELDS)
885
+ .execute
886
+ )
887
+
888
+ response = f"Contact Created for {user_google_email}:\n\n"
889
+ response += _format_contact(result, detailed=True)
890
+
891
+ created_id = result.get("resourceName", "").replace("people/", "")
892
+ logger.info(f"Created contact {created_id} for {user_google_email}")
893
+ return response
894
+
895
+ if not contact_id:
896
+ raise UserInputError(f"contact_id is required for '{action}' action.")
897
+
898
+ resource_name = _people_resource_name(contact_id)
899
+
900
+ if action in ("set_photo", "delete_photo"):
901
+ return await _manage_contact_photo(
902
+ service, user_google_email, resource_name, action, photo_base64, file_path
903
+ )
904
+
905
+ if action == "update":
906
+ # Retry loop for etag conflicts (412 Precondition Failed)
907
+ max_retries = 3
908
+ for attempt in range(max_retries):
909
+ # Fetch the contact to get current state and etag
910
+ current = await asyncio.to_thread(
911
+ service.people()
912
+ .get(resourceName=resource_name, personFields=DETAILED_PERSON_FIELDS)
913
+ .execute
914
+ )
915
+
916
+ etag = current.get("etag")
917
+ if not etag:
918
+ raise Exception("Unable to get contact etag for update.")
919
+
920
+ # Build body from provided params (returns new values only)
921
+ new_body = _build_person_body(
922
+ given_name=given_name,
923
+ family_name=family_name,
924
+ phones=phones,
925
+ emails=emails,
926
+ organizations=organizations,
927
+ nicknames=nicknames,
928
+ urls=urls,
929
+ user_defined=user_defined,
930
+ relations=relations,
931
+ notes=notes,
932
+ address=address,
933
+ birthday=birthday,
934
+ phone=phone,
935
+ email=email,
936
+ organization=organization,
937
+ job_title=job_title,
938
+ )
939
+
940
+ if not new_body:
941
+ raise UserInputError(
942
+ "At least one field (name, email, phone, etc.) must be provided."
943
+ )
944
+
945
+ # Apply merge modes for array fields
946
+ merged_body: Dict[str, Any] = dict(new_body)
947
+
948
+ if "names" in new_body:
949
+ merged_body["names"] = _merge_names(
950
+ current.get("names", []), new_body["names"]
951
+ )
952
+
953
+ if "phoneNumbers" in new_body:
954
+ merged_body["phoneNumbers"] = _merge_phones(
955
+ current.get("phoneNumbers", []),
956
+ new_body["phoneNumbers"],
957
+ phones_mode,
958
+ )
959
+
960
+ if "emailAddresses" in new_body:
961
+ merged_body["emailAddresses"] = _merge_emails(
962
+ current.get("emailAddresses", []),
963
+ new_body["emailAddresses"],
964
+ emails_mode,
965
+ )
966
+
967
+ if "organizations" in new_body:
968
+ merged_body["organizations"] = _merge_organizations(
969
+ current.get("organizations", []),
970
+ new_body["organizations"],
971
+ organizations_mode,
972
+ )
973
+
974
+ if "nicknames" in new_body:
975
+ merged_body["nicknames"] = _merge_nicknames(
976
+ current.get("nicknames", []),
977
+ new_body["nicknames"],
978
+ nicknames_mode,
979
+ )
980
+
981
+ if "urls" in new_body:
982
+ merged_body["urls"] = _merge_urls(
983
+ current.get("urls", []),
984
+ new_body["urls"],
985
+ urls_mode,
986
+ )
987
+
988
+ if "userDefined" in new_body:
989
+ merged_body["userDefined"] = _merge_user_defined(
990
+ current.get("userDefined", []),
991
+ new_body["userDefined"],
992
+ user_defined_mode,
993
+ )
994
+
995
+ if "relations" in new_body:
996
+ merged_body["relations"] = _merge_relations(
997
+ current.get("relations", []),
998
+ new_body["relations"],
999
+ relations_mode,
1000
+ )
1001
+
1002
+ merged_body["etag"] = etag
1003
+
1004
+ update_person_fields = []
1005
+ if "names" in merged_body:
1006
+ update_person_fields.append("names")
1007
+ if "emailAddresses" in merged_body:
1008
+ update_person_fields.append("emailAddresses")
1009
+ if "phoneNumbers" in merged_body:
1010
+ update_person_fields.append("phoneNumbers")
1011
+ if "organizations" in merged_body:
1012
+ update_person_fields.append("organizations")
1013
+ if "nicknames" in merged_body:
1014
+ update_person_fields.append("nicknames")
1015
+ if "urls" in merged_body:
1016
+ update_person_fields.append("urls")
1017
+ if "userDefined" in merged_body:
1018
+ update_person_fields.append("userDefined")
1019
+ if "relations" in merged_body:
1020
+ update_person_fields.append("relations")
1021
+ if "biographies" in merged_body:
1022
+ update_person_fields.append("biographies")
1023
+ if "addresses" in merged_body:
1024
+ update_person_fields.append("addresses")
1025
+ if "birthdays" in merged_body:
1026
+ update_person_fields.append("birthdays")
1027
+
1028
+ try:
1029
+ result = await asyncio.to_thread(
1030
+ service.people()
1031
+ .updateContact(
1032
+ resourceName=resource_name,
1033
+ body=merged_body,
1034
+ updatePersonFields=",".join(update_person_fields),
1035
+ personFields=DETAILED_PERSON_FIELDS,
1036
+ )
1037
+ .execute
1038
+ )
1039
+
1040
+ response = f"Contact Updated for {user_google_email}:\n\n"
1041
+ response += _format_contact(result, detailed=True)
1042
+
1043
+ logger.info(f"Updated contact {resource_name} for {user_google_email}")
1044
+ return response
1045
+
1046
+ except HttpError as e:
1047
+ if e.resp.status == 412 and attempt < max_retries - 1:
1048
+ logger.warning(
1049
+ f"[manage_contact] etag conflict on attempt {attempt + 1}, retrying..."
1050
+ )
1051
+ continue
1052
+ raise
1053
+
1054
+ # action == "delete"
1055
+ await asyncio.to_thread(
1056
+ service.people().deleteContact(resourceName=resource_name).execute
1057
+ )
1058
+
1059
+ response = f"Contact {contact_id} has been deleted for {user_google_email}."
1060
+ logger.info(f"Deleted contact {resource_name} for {user_google_email}")
1061
+ return response
1062
+
1063
+
1064
+ # =============================================================================
1065
+ # Extended Tier Tools
1066
+ # =============================================================================
1067
+
1068
+
1069
+ @server.tool(
1070
+ title="List Contact Groups",
1071
+ annotations=ToolAnnotations(
1072
+ readOnlyHint=True,
1073
+ destructiveHint=False,
1074
+ idempotentHint=True,
1075
+ openWorldHint=True,
1076
+ ),
1077
+ )
1078
+ @require_google_service("people", "contacts_read")
1079
+ @handle_http_errors("list_contact_groups", service_type="people")
1080
+ async def list_contact_groups(
1081
+ service: Resource,
1082
+ user_google_email: str,
1083
+ page_size: int = 100,
1084
+ page_token: Optional[str] = None,
1085
+ ) -> str:
1086
+ """
1087
+ List contact groups (labels) for the user.
1088
+
1089
+ Args:
1090
+ user_google_email (str): The user's Google email address. Required.
1091
+ page_size (int): Maximum number of groups to return (default: 100, max: 1000).
1092
+ page_token (Optional[str]): Token for pagination.
1093
+
1094
+ Returns:
1095
+ str: List of contact groups with their details.
1096
+ """
1097
+ logger.info(f"[list_contact_groups] Invoked. Email: '{user_google_email}'")
1098
+
1099
+ if page_size < 1:
1100
+ raise UserInputError("page_size must be >= 1")
1101
+ page_size = min(page_size, 1000)
1102
+
1103
+ params: Dict[str, Any] = {
1104
+ "pageSize": page_size,
1105
+ "groupFields": CONTACT_GROUP_FIELDS,
1106
+ }
1107
+
1108
+ if page_token:
1109
+ params["pageToken"] = page_token
1110
+
1111
+ result = await asyncio.to_thread(service.contactGroups().list(**params).execute)
1112
+
1113
+ groups = result.get("contactGroups", [])
1114
+ next_page_token = result.get("nextPageToken")
1115
+
1116
+ if not groups:
1117
+ return f"No contact groups found for {user_google_email}."
1118
+
1119
+ response = f"Contact Groups for {user_google_email}:\n\n"
1120
+
1121
+ for group in groups:
1122
+ resource_name = group.get("resourceName", "")
1123
+ group_id = resource_name.replace("contactGroups/", "")
1124
+ name = group.get("name", "Unnamed")
1125
+ group_type = group.get("groupType", "USER_CONTACT_GROUP")
1126
+ member_count = group.get("memberCount", 0)
1127
+
1128
+ response += f"- {name}\n"
1129
+ response += f" ID: {group_id}\n"
1130
+ response += f" Type: {group_type}\n"
1131
+ response += f" Members: {member_count}\n\n"
1132
+
1133
+ if next_page_token:
1134
+ response += f"Next page token: {next_page_token}"
1135
+
1136
+ logger.info(f"Found {len(groups)} contact groups for {user_google_email}")
1137
+ return response
1138
+
1139
+
1140
+ @server.tool(
1141
+ title="Get Contact Group",
1142
+ annotations=ToolAnnotations(
1143
+ readOnlyHint=True,
1144
+ destructiveHint=False,
1145
+ idempotentHint=True,
1146
+ openWorldHint=True,
1147
+ ),
1148
+ )
1149
+ @require_google_service("people", "contacts_read")
1150
+ @handle_http_errors("get_contact_group", service_type="people")
1151
+ async def get_contact_group(
1152
+ service: Resource,
1153
+ user_google_email: str,
1154
+ group_id: str,
1155
+ max_members: int = 100,
1156
+ ) -> str:
1157
+ """
1158
+ Get details of a specific contact group including its members.
1159
+
1160
+ Args:
1161
+ user_google_email (str): The user's Google email address. Required.
1162
+ group_id (str): The contact group ID.
1163
+ max_members (int): Maximum number of members to return (default: 100, max: 1000).
1164
+
1165
+ Returns:
1166
+ str: Contact group details including members.
1167
+ """
1168
+ resource_name = _contact_group_resource_name(group_id)
1169
+
1170
+ logger.info(
1171
+ f"[get_contact_group] Invoked. Email: '{user_google_email}', Group: {resource_name}"
1172
+ )
1173
+
1174
+ if max_members < 1:
1175
+ raise UserInputError("max_members must be >= 1")
1176
+ max_members = min(max_members, 1000)
1177
+
1178
+ result = await asyncio.to_thread(
1179
+ service.contactGroups()
1180
+ .get(
1181
+ resourceName=resource_name,
1182
+ maxMembers=max_members,
1183
+ groupFields=CONTACT_GROUP_FIELDS,
1184
+ )
1185
+ .execute
1186
+ )
1187
+
1188
+ name = result.get("name", "Unnamed")
1189
+ group_type = result.get("groupType", "USER_CONTACT_GROUP")
1190
+ member_count = result.get("memberCount", 0)
1191
+ member_resource_names = result.get("memberResourceNames", [])
1192
+
1193
+ response = f"Contact Group Details for {user_google_email}:\n\n"
1194
+ response += f"Name: {name}\n"
1195
+ response += f"ID: {group_id}\n"
1196
+ response += f"Type: {group_type}\n"
1197
+ response += f"Total Members: {member_count}\n"
1198
+
1199
+ if member_resource_names:
1200
+ response += f"\nMembers ({len(member_resource_names)} shown):\n"
1201
+ for member in member_resource_names:
1202
+ contact_id = member.replace("people/", "")
1203
+ response += f" - {contact_id}\n"
1204
+
1205
+ logger.info(f"Retrieved contact group {resource_name} for {user_google_email}")
1206
+ return response
1207
+
1208
+
1209
+ # =============================================================================
1210
+ # Complete Tier Tools
1211
+ # =============================================================================
1212
+
1213
+
1214
+ @server.tool(
1215
+ title="Manage Contacts Batch",
1216
+ annotations=ToolAnnotations(
1217
+ readOnlyHint=False,
1218
+ destructiveHint=True,
1219
+ idempotentHint=False,
1220
+ openWorldHint=True,
1221
+ ),
1222
+ )
1223
+ @require_google_service("people", "contacts")
1224
+ @handle_http_errors("manage_contacts_batch", service_type="people")
1225
+ async def manage_contacts_batch(
1226
+ service: Resource,
1227
+ user_google_email: str,
1228
+ action: Literal["create", "update", "delete"],
1229
+ contacts: Optional[List[ContactInput]] = None,
1230
+ updates: Optional[List[ContactUpdateInput]] = None,
1231
+ contact_ids: Optional[StringList] = None,
1232
+ field: Optional[
1233
+ Literal[
1234
+ "names",
1235
+ "phoneNumbers",
1236
+ "emailAddresses",
1237
+ "organizations",
1238
+ "nicknames",
1239
+ "urls",
1240
+ "userDefined",
1241
+ "relations",
1242
+ "biographies",
1243
+ "addresses",
1244
+ "birthdays",
1245
+ ]
1246
+ ] = None,
1247
+ ) -> str:
1248
+ """
1249
+ Batch create, update, or delete contacts. Consolidated tool replacing
1250
+ batch_create_contacts, batch_update_contacts, and batch_delete_contacts.
1251
+
1252
+ Args:
1253
+ user_google_email (str): The user's Google email address. Required.
1254
+ action (str): The action to perform: "create", "update", or "delete".
1255
+ contacts (Optional[List[Dict]]): List of contact dicts for "create" action.
1256
+ Each dict may contain: given_name, family_name, phones, emails,
1257
+ organizations, nicknames, urls, user_defined, relations, notes, address,
1258
+ birthday. Deprecated: phone, email, organization, job_title.
1259
+ updates (Optional[List[Dict]]): List of update dicts for "update" action.
1260
+ Each dict must contain contact_id and may contain the same fields as contacts.
1261
+ contact_ids (Optional[List[str]]): List of contact IDs for "delete" action.
1262
+ field (str): For "update" action, the single People API field to update across
1263
+ all contacts in this batch. Required. Must be one of: names, phoneNumbers,
1264
+ emailAddresses, organizations, nicknames, urls, userDefined, relations,
1265
+ biographies, addresses, birthdays. Using a single field per batch call prevents
1266
+ unintentional data loss from a union updateMask overwriting unrelated fields.
1267
+
1268
+ Returns:
1269
+ str: Result of the batch action performed.
1270
+ """
1271
+ action = action.lower().strip()
1272
+ if action not in ("create", "update", "delete"):
1273
+ raise UserInputError(
1274
+ f"Invalid action '{action}'. Must be 'create', 'update', or 'delete'."
1275
+ )
1276
+
1277
+ logger.info(
1278
+ f"[manage_contacts_batch] Invoked. Action: '{action}', Email: '{user_google_email}'"
1279
+ )
1280
+
1281
+ if contacts is not None:
1282
+ contacts = [_coerce_contact_input(contact) for contact in contacts]
1283
+ if updates is not None:
1284
+ updates = [_coerce_contact_update_input(update) for update in updates]
1285
+
1286
+ if action == "create":
1287
+ if not contacts:
1288
+ raise UserInputError("contacts parameter is required for 'create' action.")
1289
+
1290
+ if len(contacts) > 200:
1291
+ raise UserInputError("Maximum 200 contacts can be created in a batch.")
1292
+
1293
+ contact_bodies = []
1294
+ for contact in contacts:
1295
+ body = _build_person_body(
1296
+ given_name=contact.given_name,
1297
+ family_name=contact.family_name,
1298
+ phones=contact.phones,
1299
+ emails=contact.emails,
1300
+ organizations=contact.organizations,
1301
+ nicknames=contact.nicknames,
1302
+ urls=contact.urls,
1303
+ user_defined=contact.user_defined,
1304
+ relations=contact.relations,
1305
+ notes=contact.notes,
1306
+ address=contact.address,
1307
+ birthday=contact.birthday,
1308
+ # deprecated aliases
1309
+ phone=contact.phone,
1310
+ email=contact.email,
1311
+ organization=contact.organization,
1312
+ job_title=contact.job_title,
1313
+ )
1314
+ if body:
1315
+ contact_bodies.append({"contactPerson": body})
1316
+
1317
+ if not contact_bodies:
1318
+ raise UserInputError("No valid contact data provided.")
1319
+
1320
+ batch_body = {
1321
+ "contacts": contact_bodies,
1322
+ "readMask": DEFAULT_PERSON_FIELDS,
1323
+ }
1324
+
1325
+ result = await asyncio.to_thread(
1326
+ service.people().batchCreateContacts(body=batch_body).execute
1327
+ )
1328
+
1329
+ created_people = result.get("createdPeople", [])
1330
+
1331
+ response = f"Batch Create Results for {user_google_email}:\n\n"
1332
+ response += f"Created {len(created_people)} contacts:\n\n"
1333
+
1334
+ for item in created_people:
1335
+ person = item.get("person", {})
1336
+ response += _format_contact(person) + "\n\n"
1337
+
1338
+ logger.info(
1339
+ f"Batch created {len(created_people)} contacts for {user_google_email}"
1340
+ )
1341
+ return response
1342
+
1343
+ if action == "update":
1344
+ if not updates:
1345
+ raise UserInputError("updates parameter is required for 'update' action.")
1346
+
1347
+ if len(updates) > 200:
1348
+ raise UserInputError("Maximum 200 contacts can be updated in a batch.")
1349
+
1350
+ # Validate field param — required to avoid multi-field mask issues
1351
+ valid_fields = {
1352
+ "names",
1353
+ "phoneNumbers",
1354
+ "emailAddresses",
1355
+ "organizations",
1356
+ "nicknames",
1357
+ "urls",
1358
+ "userDefined",
1359
+ "relations",
1360
+ "biographies",
1361
+ "addresses",
1362
+ "birthdays",
1363
+ }
1364
+ if not field:
1365
+ raise UserInputError(
1366
+ "field parameter is required for batch 'update' action. "
1367
+ "Must be one of: names, phoneNumbers, emailAddresses, organizations, "
1368
+ "nicknames, urls, userDefined, relations, biographies, addresses, birthdays. "
1369
+ "Use a single field per batch call to avoid unintentional data loss "
1370
+ "from a union updateMask."
1371
+ )
1372
+ if field not in valid_fields:
1373
+ raise UserInputError(
1374
+ f"Invalid field '{field}'. Must be one of: {', '.join(sorted(valid_fields))}."
1375
+ )
1376
+
1377
+ # Collect resource names for batch etag fetch
1378
+ resource_names = []
1379
+ for update in updates:
1380
+ cid = update.contact_id
1381
+ if not cid:
1382
+ raise UserInputError("Each update must include a contact_id.")
1383
+ resource_names.append(_people_resource_name(cid))
1384
+
1385
+ batch_get_result = await asyncio.to_thread(
1386
+ service.people()
1387
+ .getBatchGet(
1388
+ resourceNames=resource_names,
1389
+ personFields=f"metadata,{field}",
1390
+ )
1391
+ .execute
1392
+ )
1393
+
1394
+ current_people = {}
1395
+ lookup_misses: Dict[str, str] = {}
1396
+ for resp in batch_get_result.get("responses", []):
1397
+ person = resp.get("person", {})
1398
+ rname = person.get("resourceName")
1399
+ requested = resp.get("requestedResourceName", rname)
1400
+ if rname and person.get("etag"):
1401
+ current_people[rname] = person
1402
+ if requested != rname:
1403
+ lookup_misses[requested] = f"resolves to {rname}"
1404
+
1405
+ # Map field name to body key produced by _build_person_body
1406
+ field_to_body_key = {
1407
+ "names": "names",
1408
+ "phoneNumbers": "phoneNumbers",
1409
+ "emailAddresses": "emailAddresses",
1410
+ "organizations": "organizations",
1411
+ "nicknames": "nicknames",
1412
+ "urls": "urls",
1413
+ "userDefined": "userDefined",
1414
+ "relations": "relations",
1415
+ "biographies": "biographies",
1416
+ "addresses": "addresses",
1417
+ "birthdays": "birthdays",
1418
+ }
1419
+ body_key = field_to_body_key[field]
1420
+
1421
+ # Build contacts map (Dict[resourceName, Person]) — required by batchUpdateContacts API
1422
+ contacts_map: Dict[str, Any] = {}
1423
+ skipped: List[str] = []
1424
+
1425
+ for cid, update in zip(resource_names, updates):
1426
+ current = current_people.get(cid)
1427
+ if not current:
1428
+ logger.warning(f"No etag found for {cid}, skipping")
1429
+ skipped.append(f"{cid}: {lookup_misses.get(cid, 'not found')}")
1430
+ continue
1431
+
1432
+ body = _build_person_body(
1433
+ given_name=update.given_name,
1434
+ family_name=update.family_name,
1435
+ phones=update.phones,
1436
+ emails=update.emails,
1437
+ organizations=update.organizations,
1438
+ nicknames=update.nicknames,
1439
+ urls=update.urls,
1440
+ user_defined=update.user_defined,
1441
+ relations=update.relations,
1442
+ notes=update.notes,
1443
+ address=update.address,
1444
+ birthday=update.birthday,
1445
+ # deprecated aliases
1446
+ phone=update.phone,
1447
+ email=update.email,
1448
+ organization=update.organization,
1449
+ job_title=update.job_title,
1450
+ )
1451
+
1452
+ if body_key not in body:
1453
+ logger.warning(
1454
+ f"Field '{field}' (key '{body_key}') not present in update for {cid}, skipping"
1455
+ )
1456
+ skipped.append(f"{cid}: no {field} in the update")
1457
+ continue
1458
+
1459
+ if body_key == "names":
1460
+ body["names"] = _merge_names(current.get("names", []), body["names"])
1461
+
1462
+ person_body = {
1463
+ "etag": current["etag"],
1464
+ body_key: body[body_key],
1465
+ }
1466
+ contacts_map[cid] = person_body
1467
+
1468
+ skipped_report = f"Skipped {len(skipped)} contacts:\n" + "".join(
1469
+ f" {line}\n" for line in skipped
1470
+ )
1471
+ if not contacts_map:
1472
+ raise UserInputError(f"No valid update data provided.\n{skipped_report}")
1473
+
1474
+ batch_body = {
1475
+ "contacts": contacts_map,
1476
+ "updateMask": field,
1477
+ "readMask": DEFAULT_PERSON_FIELDS,
1478
+ }
1479
+
1480
+ result = await asyncio.to_thread(
1481
+ service.people().batchUpdateContacts(body=batch_body).execute
1482
+ )
1483
+
1484
+ update_results = result.get("updateResult", {})
1485
+
1486
+ response = f"Batch Update Results for {user_google_email}:\n\n"
1487
+ response += f"Updated {len(update_results)} contacts:\n\n"
1488
+
1489
+ for rname, update_result in update_results.items():
1490
+ person = update_result.get("person", {})
1491
+ response += _format_contact(person) + "\n\n"
1492
+
1493
+ if skipped:
1494
+ response += skipped_report
1495
+
1496
+ logger.info(
1497
+ f"Batch updated {len(update_results)} contacts for {user_google_email}"
1498
+ )
1499
+ return response
1500
+
1501
+ # action == "delete"
1502
+ if not contact_ids:
1503
+ raise UserInputError("contact_ids parameter is required for 'delete' action.")
1504
+
1505
+ if len(contact_ids) > 500:
1506
+ raise UserInputError("Maximum 500 contacts can be deleted in a batch.")
1507
+
1508
+ resource_names = [_people_resource_name(cid) for cid in contact_ids]
1509
+
1510
+ batch_body = {"resourceNames": resource_names}
1511
+
1512
+ await asyncio.to_thread(
1513
+ service.people().batchDeleteContacts(body=batch_body).execute
1514
+ )
1515
+
1516
+ response = f"Batch deleted {len(contact_ids)} contacts for {user_google_email}."
1517
+ logger.info(f"Batch deleted {len(contact_ids)} contacts for {user_google_email}")
1518
+ return response
1519
+
1520
+
1521
+ @server.tool(
1522
+ title="Manage Contact Group",
1523
+ annotations=ToolAnnotations(
1524
+ readOnlyHint=False,
1525
+ destructiveHint=True,
1526
+ idempotentHint=False,
1527
+ openWorldHint=True,
1528
+ ),
1529
+ )
1530
+ @require_google_service("people", "contacts")
1531
+ @handle_http_errors("manage_contact_group", service_type="people")
1532
+ async def manage_contact_group(
1533
+ service: Resource,
1534
+ user_google_email: str,
1535
+ action: str,
1536
+ group_id: Optional[str] = None,
1537
+ name: Optional[str] = None,
1538
+ delete_contacts: bool = False,
1539
+ add_contact_ids: Optional[StringList] = None,
1540
+ remove_contact_ids: Optional[StringList] = None,
1541
+ ) -> str:
1542
+ """
1543
+ Create, update, delete a contact group, or modify its members. Consolidated tool
1544
+ replacing create_contact_group, update_contact_group, delete_contact_group, and
1545
+ modify_contact_group_members.
1546
+
1547
+ Args:
1548
+ user_google_email (str): The user's Google email address. Required.
1549
+ action (str): The action to perform: "create", "update", "delete", or "modify_members".
1550
+ group_id (Optional[str]): The contact group ID. Required for "update", "delete",
1551
+ and "modify_members" actions.
1552
+ name (Optional[str]): The group name. Required for "create" and "update" actions.
1553
+ delete_contacts (bool): If True and action is "delete", also delete contacts in
1554
+ the group (default: False).
1555
+ add_contact_ids (Optional[List[str]]): Contact IDs to add (for "modify_members").
1556
+ remove_contact_ids (Optional[List[str]]): Contact IDs to remove (for "modify_members").
1557
+
1558
+ Returns:
1559
+ str: Result of the action performed.
1560
+ """
1561
+ action = action.lower().strip()
1562
+ if action not in ("create", "update", "delete", "modify_members"):
1563
+ raise UserInputError(
1564
+ f"Invalid action '{action}'. Must be 'create', 'update', 'delete', or 'modify_members'."
1565
+ )
1566
+
1567
+ logger.info(
1568
+ f"[manage_contact_group] Invoked. Action: '{action}', Email: '{user_google_email}'"
1569
+ )
1570
+
1571
+ if action == "create":
1572
+ if not name:
1573
+ raise UserInputError("name is required for 'create' action.")
1574
+
1575
+ body = {"contactGroup": {"name": name}}
1576
+
1577
+ result = await asyncio.to_thread(
1578
+ service.contactGroups().create(body=body).execute
1579
+ )
1580
+
1581
+ resource_name = result.get("resourceName", "")
1582
+ created_group_id = resource_name.replace("contactGroups/", "")
1583
+ created_name = result.get("name", name)
1584
+
1585
+ response = f"Contact Group Created for {user_google_email}:\n\n"
1586
+ response += f"Name: {created_name}\n"
1587
+ response += f"ID: {created_group_id}\n"
1588
+ response += f"Type: {result.get('groupType', 'USER_CONTACT_GROUP')}\n"
1589
+
1590
+ logger.info(f"Created contact group for {user_google_email}")
1591
+ return response
1592
+
1593
+ # All other actions require group_id
1594
+ if not group_id:
1595
+ raise UserInputError(f"group_id is required for '{action}' action.")
1596
+
1597
+ resource_name = _contact_group_resource_name(group_id)
1598
+
1599
+ if action == "update":
1600
+ if not name:
1601
+ raise UserInputError("name is required for 'update' action.")
1602
+
1603
+ body = {"contactGroup": {"name": name}}
1604
+
1605
+ result = await asyncio.to_thread(
1606
+ service.contactGroups()
1607
+ .update(resourceName=resource_name, body=body)
1608
+ .execute
1609
+ )
1610
+
1611
+ updated_name = result.get("name", name)
1612
+
1613
+ response = f"Contact Group Updated for {user_google_email}:\n\n"
1614
+ response += f"Name: {updated_name}\n"
1615
+ response += f"ID: {group_id}\n"
1616
+
1617
+ logger.info(f"Updated contact group {resource_name} for {user_google_email}")
1618
+ return response
1619
+
1620
+ if action == "delete":
1621
+ await asyncio.to_thread(
1622
+ service.contactGroups()
1623
+ .delete(resourceName=resource_name, deleteContacts=delete_contacts)
1624
+ .execute
1625
+ )
1626
+
1627
+ response = f"Contact group {group_id} has been deleted for {user_google_email}."
1628
+ if delete_contacts:
1629
+ response += " Contacts in the group were also deleted."
1630
+ else:
1631
+ response += " Contacts in the group were preserved."
1632
+
1633
+ logger.info(f"Deleted contact group {resource_name} for {user_google_email}")
1634
+ return response
1635
+
1636
+ # action == "modify_members"
1637
+ if not add_contact_ids and not remove_contact_ids:
1638
+ raise UserInputError(
1639
+ "At least one of add_contact_ids or remove_contact_ids must be provided."
1640
+ )
1641
+
1642
+ modify_body: Dict[str, Any] = {}
1643
+
1644
+ if add_contact_ids:
1645
+ modify_body["resourceNamesToAdd"] = [
1646
+ _people_resource_name(contact_id) for contact_id in add_contact_ids
1647
+ ]
1648
+
1649
+ if remove_contact_ids:
1650
+ modify_body["resourceNamesToRemove"] = [
1651
+ _people_resource_name(contact_id) for contact_id in remove_contact_ids
1652
+ ]
1653
+
1654
+ result = await asyncio.to_thread(
1655
+ service.contactGroups()
1656
+ .members()
1657
+ .modify(resourceName=resource_name, body=modify_body)
1658
+ .execute
1659
+ )
1660
+
1661
+ not_found = result.get("notFoundResourceNames") or []
1662
+ cannot_remove = result.get("canNotRemoveLastContactGroupResourceNames") or []
1663
+
1664
+ response = f"Contact Group Members Modified for {user_google_email}:\n\n"
1665
+ response += f"Group: {group_id}\n"
1666
+
1667
+ skipped = set(not_found)
1668
+ if add_contact_ids:
1669
+ added = set(modify_body["resourceNamesToAdd"]) - skipped
1670
+ response += f"Added: {len(added)} contacts\n"
1671
+ if remove_contact_ids:
1672
+ removed = (
1673
+ set(modify_body["resourceNamesToRemove"]) - skipped - set(cannot_remove)
1674
+ )
1675
+ response += f"Removed: {len(removed)} contacts\n"
1676
+
1677
+ if not_found:
1678
+ response += f"\nNot found: {', '.join(not_found)}\n"
1679
+ if cannot_remove:
1680
+ response += f"\nCannot remove (last group): {', '.join(cannot_remove)}\n"
1681
+
1682
+ logger.info(
1683
+ f"Modified contact group members for {resource_name} for {user_google_email}"
1684
+ )
1685
+ return response