@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,765 @@
1
+ """
2
+ Google Contacts Helper Functions
3
+
4
+ This module provides listing, parsing, normalizing, formatting, and merging
5
+ logic for Google Contacts (People API), separate from the MCP tool definitions
6
+ and Pydantic input models in contacts_tools.py.
7
+ """
8
+
9
+ import asyncio
10
+ import base64
11
+ import binascii
12
+ import datetime
13
+ import logging
14
+ import re
15
+ from typing import Any, Dict, List, Optional
16
+
17
+ from googleapiclient.errors import HttpError
18
+
19
+ from core.utils import (
20
+ NotARegularFileError,
21
+ UserInputError,
22
+ check_path_segment,
23
+ local_file_access_enabled,
24
+ open_validated_file,
25
+ )
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ DEFAULT_PERSON_FIELDS = "names,nicknames,emailAddresses,phoneNumbers,organizations"
30
+ OTHER_CONTACT_FIELDS = "names,emailAddresses,phoneNumbers"
31
+
32
+
33
+ def _resource_name(value: str, collection: str, label: str) -> str:
34
+ """Return collection/<id> for a bare ID or a full resource name, refusing unsafe IDs."""
35
+ prefix = f"{collection}/"
36
+ return prefix + check_path_segment(value.removeprefix(prefix), label)
37
+
38
+
39
+ def _people_resource_name(contact_id: str) -> str:
40
+ """Return people/<id> for "c123" or "people/c123", refusing unsafe IDs."""
41
+ return _resource_name(contact_id, "people", "contact_id")
42
+
43
+
44
+ def _contact_group_resource_name(group_id: str) -> str:
45
+ """Return contactGroups/<id> for "abc" or "contactGroups/abc", refusing unsafe IDs."""
46
+ return _resource_name(group_id, "contactGroups", "group_id")
47
+
48
+
49
+ _URL_SCHEME_HOST_RE = re.compile(
50
+ r"([a-z][a-z0-9+.-]*:)(?!//)|((?:[a-z][a-z0-9+.-]*:)?//)?([^/?#@]*@)?([^/?#]*)",
51
+ re.IGNORECASE,
52
+ )
53
+
54
+ _MAX_CONTACT_PHOTO_BYTES = 5 * 1024 * 1024
55
+
56
+
57
+ def _prepare_contact_photo(
58
+ photo_base64: Optional[str], file_path: Optional[str]
59
+ ) -> str:
60
+ """Read one bounded photo input; leave image decoding to the People API."""
61
+ if (photo_base64 is None) == (file_path is None):
62
+ sources = (
63
+ "photo_base64 or file_path"
64
+ if local_file_access_enabled()
65
+ else "photo_base64"
66
+ )
67
+ raise UserInputError(f"set_photo takes exactly one photo input: {sources}.")
68
+
69
+ if file_path is not None:
70
+ try:
71
+ with open_validated_file(file_path) as image:
72
+ photo = image.read(_MAX_CONTACT_PHOTO_BYTES + 1)
73
+ except NotARegularFileError:
74
+ raise UserInputError("Contact photo must be a regular file.") from None
75
+ except (OSError, ValueError) as exc:
76
+ raise UserInputError(f"Cannot read contact photo: {exc}") from exc
77
+ elif photo_base64 is not None:
78
+ max_encoded = 4 * ((_MAX_CONTACT_PHOTO_BYTES + 2) // 3)
79
+ if len(photo_base64) > max_encoded:
80
+ raise UserInputError("Contact photo exceeds the 5 MiB tool limit.")
81
+ try:
82
+ photo = base64.b64decode(photo_base64, validate=True)
83
+ except (binascii.Error, ValueError) as exc:
84
+ raise UserInputError(
85
+ "photo_base64 must be raw, valid Base64 (not a data URL)."
86
+ ) from exc
87
+
88
+ if not photo:
89
+ raise UserInputError("Contact photo must not be empty.")
90
+ if len(photo) > _MAX_CONTACT_PHOTO_BYTES:
91
+ raise UserInputError("Contact photo exceeds the 5 MiB tool limit.")
92
+ return base64.b64encode(photo).decode("ascii")
93
+
94
+
95
+ async def _manage_contact_photo(
96
+ service: Any,
97
+ user_google_email: str,
98
+ resource_name: str,
99
+ action: str,
100
+ photo_base64: Optional[str],
101
+ file_path: Optional[str],
102
+ ) -> str:
103
+ """Set or remove only the contact photo; on set, return the new photo URL."""
104
+ contact_id = resource_name.removeprefix("people/")
105
+ if action == "delete_photo":
106
+ await asyncio.to_thread(
107
+ service.people().deleteContactPhoto(resourceName=resource_name).execute
108
+ )
109
+ return (
110
+ f"Contact photo removed for {user_google_email}:\nContact ID: {contact_id}"
111
+ )
112
+
113
+ encoded = await asyncio.to_thread(_prepare_contact_photo, photo_base64, file_path)
114
+ result = await asyncio.to_thread(
115
+ service.people()
116
+ .updateContactPhoto(
117
+ resourceName=resource_name,
118
+ body={
119
+ "photoBytes": encoded,
120
+ "personFields": "photos",
121
+ "sources": ["READ_SOURCE_TYPE_CONTACT"],
122
+ },
123
+ )
124
+ .execute
125
+ )
126
+ response = (
127
+ f"Contact photo updated for {user_google_email}:\nContact ID: {contact_id}"
128
+ )
129
+ for photo in result.get("person", {}).get("photos", []):
130
+ if photo.get("url"):
131
+ response += f"\nPhoto URL: {photo['url']}"
132
+ return response
133
+
134
+
135
+ def _is_expired_sync_token(exc: HttpError) -> bool:
136
+ """Recognize the People API expiry reason, retaining HTTP 410 as a fallback."""
137
+ status = getattr(exc.resp, "status", None)
138
+ if status == 410:
139
+ return True
140
+ details = getattr(exc, "error_details", None)
141
+ return (
142
+ status == 400
143
+ and isinstance(details, list)
144
+ and any(
145
+ isinstance(detail, dict) and detail.get("reason") == "EXPIRED_SYNC_TOKEN"
146
+ for detail in details
147
+ )
148
+ )
149
+
150
+
151
+ def _search_request(service: Any, source: str, **params: Any) -> Any:
152
+ """Build a saved contacts or other contacts search request."""
153
+ if source == "other":
154
+ return service.otherContacts().search(**params)
155
+ return service.people().searchContacts(**params)
156
+
157
+
158
+ async def _list_contacts(
159
+ service: Any,
160
+ user_google_email: str,
161
+ page_size: int,
162
+ page_token: Optional[str],
163
+ sort_order: Optional[str],
164
+ request_sync_token: bool,
165
+ sync_token: Optional[str],
166
+ ) -> str:
167
+ """List one page of contacts, ending the last sync page with a sync token."""
168
+ if page_size < 1:
169
+ raise UserInputError("page_size must be >= 1")
170
+ if sync_token is not None and not sync_token.strip():
171
+ raise UserInputError("sync_token must not be empty")
172
+ syncing = request_sync_token or sync_token is not None
173
+ if syncing and sort_order:
174
+ raise UserInputError("sort_order is not supported when syncing contacts")
175
+
176
+ params: Dict[str, Any] = {
177
+ "resourceName": "people/me",
178
+ "personFields": DEFAULT_PERSON_FIELDS,
179
+ "pageSize": min(page_size, 1000),
180
+ }
181
+ if page_token:
182
+ params["pageToken"] = page_token
183
+ if sort_order:
184
+ params["sortOrder"] = sort_order
185
+ if syncing:
186
+ params["personFields"] += ",metadata"
187
+ params["requestSyncToken"] = True
188
+ if sync_token:
189
+ params["syncToken"] = sync_token
190
+
191
+ try:
192
+ result = await asyncio.to_thread(
193
+ service.people().connections().list(**params).execute
194
+ )
195
+ except HttpError as exc:
196
+ if sync_token and _is_expired_sync_token(exc):
197
+ return "Sync token expired. Start a new full sync with request_sync_token=true."
198
+ raise
199
+
200
+ connections = result.get("connections", [])
201
+ if connections:
202
+ total_people = result.get("totalPeople", len(connections))
203
+ response = f"Contacts for {user_google_email} ({len(connections)} of {total_people}):\n\n"
204
+ response += "".join(f"{_format_contact(person)}\n\n" for person in connections)
205
+ elif syncing:
206
+ response = f"No contacts returned for {user_google_email}.\n\n"
207
+ else:
208
+ return f"No contacts found for {user_google_email}."
209
+
210
+ if result.get("nextPageToken"):
211
+ response += f"Next page token: {result['nextPageToken']}"
212
+ if result.get("nextSyncToken"):
213
+ response += f"Next sync token: {result['nextSyncToken']}"
214
+ return response
215
+
216
+
217
+ # Name fields the People API derives from the structured parts. Sending them
218
+ # back alongside an edited part would conflict with (or override) the edit.
219
+ _DERIVED_NAME_FIELDS = (
220
+ "metadata",
221
+ "displayName",
222
+ "displayNameLastFirst",
223
+ "unstructuredName",
224
+ )
225
+
226
+
227
+ def _parse_birthday(s: str) -> Dict[str, Any]:
228
+ """Parse 'YYYY-MM-DD' or 'MM-DD' into a People API birthday object."""
229
+ parts = s.strip().split("-")
230
+ try:
231
+ if len(parts) == 3:
232
+ year, month, day = int(parts[0]), int(parts[1]), int(parts[2])
233
+ elif len(parts) == 2:
234
+ year, month, day = None, int(parts[0]), int(parts[1])
235
+ else:
236
+ raise ValueError
237
+ except ValueError:
238
+ raise UserInputError(
239
+ f"Invalid birthday format '{s}'. Use 'YYYY-MM-DD' or 'MM-DD'."
240
+ ) from None
241
+
242
+ if not 1 <= month <= 12 or not 1 <= day <= 31:
243
+ raise UserInputError(
244
+ f"Invalid birthday '{s}': month must be 1-12 and day must be 1-31."
245
+ )
246
+
247
+ # Reject impossible day/month combinations (e.g. Feb 30, Apr 31) and bad
248
+ # years before they reach the People API. For year-less dates use a leap
249
+ # year (2000) so Feb 29 is accepted.
250
+ try:
251
+ datetime.date(year if year is not None else 2000, month, day)
252
+ except ValueError:
253
+ raise UserInputError(
254
+ f"Invalid birthday '{s}': not a real calendar date."
255
+ ) from None
256
+
257
+ date = {"month": month, "day": day}
258
+ if year is not None:
259
+ date["year"] = year
260
+ return {"date": date}
261
+
262
+
263
+ def _normalize_phone(value: str) -> str:
264
+ """Return a normalized phone string for deduplication. Strips non-digit chars except leading +."""
265
+ stripped = re.sub(r"[^\d+]", "", value)
266
+ return stripped.lower()
267
+
268
+
269
+ def _normalize_email(value: str) -> str:
270
+ """Return a normalized email string for deduplication."""
271
+ return value.strip().lower()
272
+
273
+
274
+ def _normalize_nickname(value: str) -> str:
275
+ """Return a normalized nickname string for deduplication."""
276
+ return value.strip().lower()
277
+
278
+
279
+ def _normalize_url(value: str) -> str:
280
+ """Return a normalized URL string for deduplication. Lowercases scheme/host, strips trailing slash."""
281
+ stripped = value.strip()
282
+ match = _URL_SCHEME_HOST_RE.match(stripped)
283
+ opaque_scheme, scheme, userinfo, host = match.groups(default="")
284
+ prefix = (opaque_scheme + scheme).lower()
285
+ normalized = prefix + userinfo + host.lower() + stripped[match.end() :]
286
+ return normalized.removesuffix("/")
287
+
288
+
289
+ def _normalize_user_defined_key(value: str) -> str:
290
+ """Return a normalized userDefined key for deduplication."""
291
+ return value.strip().lower()
292
+
293
+
294
+ def _normalize_relation_person(value: str) -> str:
295
+ """Return a normalized relation person name for deduplication."""
296
+ return value.strip().lower()
297
+
298
+
299
+ def _format_phone_line(phone: Dict[str, Any]) -> str:
300
+ """
301
+ Format a single phone entry into a display line.
302
+
303
+ Returns e.g. '+79270000000 (mobile)' or '250 (Internal)'.
304
+ """
305
+ value = phone.get("value", "")
306
+ phone_type = phone.get("type", "")
307
+ formatted_type = phone.get("formattedType", "")
308
+
309
+ if phone_type == "internal":
310
+ label = "Internal"
311
+ elif formatted_type:
312
+ label = formatted_type
313
+ elif phone_type:
314
+ label = phone_type
315
+ else:
316
+ label = ""
317
+
318
+ if label:
319
+ return f"{value} ({label})"
320
+ return value
321
+
322
+
323
+ def _format_email_line(email: Dict[str, Any]) -> str:
324
+ """
325
+ Format a single email entry into a display line.
326
+
327
+ Returns e.g. 'user@example.com (work)'.
328
+ """
329
+ value = email.get("value", "")
330
+ email_type = email.get("type", "")
331
+ formatted_type = email.get("formattedType", "")
332
+
333
+ label = formatted_type or email_type or ""
334
+ if label:
335
+ return f"{value} ({label})"
336
+ return value
337
+
338
+
339
+ def _format_contact(person: Dict[str, Any], detailed: bool = False) -> str:
340
+ """
341
+ Format a Person resource into a readable string.
342
+
343
+ Args:
344
+ person: The Person resource from the People API.
345
+ detailed: Whether to include detailed fields.
346
+
347
+ Returns:
348
+ Formatted string representation of the contact.
349
+ """
350
+ resource_name = person.get("resourceName", "Unknown")
351
+ contact_id = resource_name.replace("people/", "") if resource_name else "Unknown"
352
+
353
+ lines = [f"Contact ID: {contact_id}"]
354
+ if person.get("metadata", {}).get("deleted"):
355
+ lines.append("Deleted: yes")
356
+
357
+ # Names
358
+ names = person.get("names", [])
359
+ if names:
360
+ primary_name = names[0]
361
+ display_name = primary_name.get("displayName", "")
362
+ if display_name:
363
+ lines.append(f"Name: {display_name}")
364
+
365
+ # Nicknames — bilingual alternative names
366
+ nicknames = person.get("nicknames", [])
367
+ if nicknames:
368
+ nickname_values = [n.get("value", "") for n in nicknames if n.get("value")]
369
+ if nickname_values:
370
+ lines.append(f"Nicknames: {', '.join(nickname_values)}")
371
+
372
+ # Email addresses — each on its own line with type label
373
+ emails = person.get("emailAddresses", [])
374
+ if emails:
375
+ valid_emails = [e for e in emails if e.get("value")]
376
+ if valid_emails:
377
+ if len(valid_emails) == 1:
378
+ lines.append(f"Email: {_format_email_line(valid_emails[0])}")
379
+ else:
380
+ lines.append("Emails:")
381
+ for e in valid_emails:
382
+ lines.append(f" - {_format_email_line(e)}")
383
+
384
+ # Phone numbers — each on its own line with type label
385
+ phones = person.get("phoneNumbers", [])
386
+ if phones:
387
+ valid_phones = [p for p in phones if p.get("value")]
388
+ if valid_phones:
389
+ if len(valid_phones) == 1:
390
+ lines.append(f"Phone: {_format_phone_line(valid_phones[0])}")
391
+ else:
392
+ lines.append("Phones:")
393
+ for p in valid_phones:
394
+ lines.append(f" - {_format_phone_line(p)}")
395
+
396
+ # Organizations
397
+ orgs = person.get("organizations", [])
398
+ if orgs:
399
+ org = orgs[0]
400
+ org_parts = []
401
+ if org.get("title"):
402
+ org_parts.append(org["title"])
403
+ if org.get("name"):
404
+ org_parts.append(f"at {org['name']}")
405
+ if org_parts:
406
+ lines.append(f"Organization: {' '.join(org_parts)}")
407
+
408
+ if detailed:
409
+ # Addresses
410
+ addresses = person.get("addresses", [])
411
+ if addresses:
412
+ addr = addresses[0]
413
+ formatted_addr = addr.get("formattedValue", "")
414
+ if formatted_addr:
415
+ lines.append(f"Address: {formatted_addr}")
416
+
417
+ # Birthday
418
+ birthdays = person.get("birthdays", [])
419
+ if birthdays:
420
+ bday = birthdays[0].get("date", {})
421
+ if bday:
422
+ bday_str = f"{bday.get('month', '?')}/{bday.get('day', '?')}"
423
+ if bday.get("year"):
424
+ bday_str = f"{bday.get('year')}/{bday_str}"
425
+ lines.append(f"Birthday: {bday_str}")
426
+
427
+ # URLs
428
+ urls = person.get("urls", [])
429
+ if urls:
430
+ url_list = [u.get("value", "") for u in urls if u.get("value")]
431
+ if url_list:
432
+ lines.append(f"URLs: {', '.join(url_list)}")
433
+
434
+ # User-defined custom fields
435
+ user_defined = person.get("userDefined", [])
436
+ if user_defined:
437
+ valid_ud = [ud for ud in user_defined if ud.get("key") and ud.get("value")]
438
+ if valid_ud:
439
+ lines.append("Custom Fields:")
440
+ for ud in valid_ud:
441
+ lines.append(f" - {ud['key']}: {ud['value']}")
442
+
443
+ # Relations (spouse, family, etc.)
444
+ relations = person.get("relations", [])
445
+ if relations:
446
+ valid_rels = [r for r in relations if r.get("person")]
447
+ if valid_rels:
448
+ lines.append("Relations:")
449
+ for r in valid_rels:
450
+ rel_type = r.get("formattedType") or r.get("type") or ""
451
+ if rel_type:
452
+ lines.append(f" - {r['person']} ({rel_type})")
453
+ else:
454
+ lines.append(f" - {r['person']}")
455
+
456
+ # Biography/Notes
457
+ bios = person.get("biographies", [])
458
+ if bios:
459
+ bio = bios[0].get("value", "")
460
+ if bio:
461
+ # Truncate long bios
462
+ if len(bio) > 200:
463
+ bio = bio[:200] + "..."
464
+ lines.append(f"Notes: {bio}")
465
+
466
+ # Metadata
467
+ metadata = person.get("metadata", {})
468
+ if metadata:
469
+ sources = metadata.get("sources", [])
470
+ if sources:
471
+ source_types = [s.get("type", "") for s in sources]
472
+ if source_types:
473
+ lines.append(f"Sources: {', '.join(source_types)}")
474
+
475
+ return "\n".join(lines)
476
+
477
+
478
+ def _merge_phones(
479
+ existing: List[Dict[str, Any]],
480
+ new_phones: List[Dict[str, Any]],
481
+ mode: str,
482
+ ) -> List[Dict[str, Any]]:
483
+ """
484
+ Merge phone lists according to mode.
485
+
486
+ Args:
487
+ existing: Current phoneNumbers from People API.
488
+ new_phones: New phone entries (API format: {value, type?, ...}).
489
+ mode: 'merge', 'replace', or 'remove'.
490
+
491
+ Returns:
492
+ Merged phone list.
493
+ """
494
+
495
+ def phone_key(phone: Dict[str, Any]) -> str:
496
+ return _normalize_phone(phone.get("canonicalForm") or phone.get("value", ""))
497
+
498
+ if mode == "replace":
499
+ return new_phones
500
+ if mode == "remove":
501
+ remove_normalized = {
502
+ _normalize_phone(p["value"]) for p in new_phones if p.get("value")
503
+ }
504
+ return [
505
+ p
506
+ for p in existing
507
+ if _normalize_phone(p.get("value", "")) not in remove_normalized
508
+ ]
509
+ # merge: add new entries that don't already exist (dedup by canonicalForm or normalized value)
510
+ result = list(existing)
511
+ existing_keys = set()
512
+ for p in existing:
513
+ existing_keys.add(phone_key(p))
514
+ for p in new_phones:
515
+ canonical = phone_key(p)
516
+ if canonical not in existing_keys:
517
+ result.append(p)
518
+ existing_keys.add(canonical)
519
+ return result
520
+
521
+
522
+ def _merge_emails(
523
+ existing: List[Dict[str, Any]],
524
+ new_emails: List[Dict[str, Any]],
525
+ mode: str,
526
+ ) -> List[Dict[str, Any]]:
527
+ """
528
+ Merge email lists according to mode.
529
+
530
+ Args:
531
+ existing: Current emailAddresses from People API.
532
+ new_emails: New email entries (API format: {value, type?, ...}).
533
+ mode: 'merge', 'replace', or 'remove'.
534
+
535
+ Returns:
536
+ Merged email list.
537
+ """
538
+ if mode == "replace":
539
+ return new_emails
540
+ if mode == "remove":
541
+ remove_normalized = {
542
+ _normalize_email(e["value"]) for e in new_emails if e.get("value")
543
+ }
544
+ return [
545
+ e
546
+ for e in existing
547
+ if _normalize_email(e.get("value", "")) not in remove_normalized
548
+ ]
549
+ # merge: add new entries not already present (dedup by lowercased address)
550
+ result = list(existing)
551
+ existing_keys = {_normalize_email(e.get("value", "")) for e in existing}
552
+ for e in new_emails:
553
+ normalized = _normalize_email(e.get("value", ""))
554
+ if normalized not in existing_keys:
555
+ result.append(e)
556
+ existing_keys.add(normalized)
557
+ return result
558
+
559
+
560
+ def _merge_organizations(
561
+ existing: List[Dict[str, Any]],
562
+ new_orgs: List[Dict[str, Any]],
563
+ mode: str,
564
+ ) -> List[Dict[str, Any]]:
565
+ """
566
+ Merge organization lists according to mode.
567
+
568
+ Args:
569
+ existing: Current organizations from People API.
570
+ new_orgs: New org entries (API format).
571
+ mode: 'merge', 'replace', or 'remove'.
572
+
573
+ Returns:
574
+ Merged org list.
575
+ """
576
+
577
+ def organization_key(org: Dict[str, Any]) -> tuple[str, str, str, str, str]:
578
+ job_description = org.get("jobDescription") or org.get("description") or ""
579
+ return (
580
+ ((org.get("name") or "").strip().lower()),
581
+ ((org.get("title") or "").strip().lower()),
582
+ ((org.get("department") or "").strip().lower()),
583
+ job_description.strip().lower(),
584
+ ((org.get("type") or "").strip().lower()),
585
+ )
586
+
587
+ if mode == "replace":
588
+ return new_orgs
589
+ if mode == "remove":
590
+ remove_keys = {organization_key(org) for org in new_orgs}
591
+ return [org for org in existing if organization_key(org) not in remove_keys]
592
+ # merge: add orgs whose identifying fields don't already exist
593
+ result = list(existing)
594
+ existing_keys = {organization_key(org) for org in existing}
595
+ for org in new_orgs:
596
+ org_key = organization_key(org)
597
+ if org_key not in existing_keys:
598
+ result.append(org)
599
+ existing_keys.add(org_key)
600
+ return result
601
+
602
+
603
+ def _merge_nicknames(
604
+ existing: List[Dict[str, Any]],
605
+ new_nicknames: List[Dict[str, Any]],
606
+ mode: str,
607
+ ) -> List[Dict[str, Any]]:
608
+ """
609
+ Merge nickname lists according to mode. Dedup by lowercased value.
610
+ """
611
+ if mode == "replace":
612
+ return new_nicknames
613
+ if mode == "remove":
614
+ remove_normalized = {
615
+ _normalize_nickname(n["value"]) for n in new_nicknames if n.get("value")
616
+ }
617
+ return [
618
+ n
619
+ for n in existing
620
+ if _normalize_nickname(n.get("value", "")) not in remove_normalized
621
+ ]
622
+ # merge: add new entries not already present
623
+ result = list(existing)
624
+ existing_keys = {_normalize_nickname(n.get("value", "")) for n in existing}
625
+ for n in new_nicknames:
626
+ normalized = _normalize_nickname(n.get("value", ""))
627
+ if normalized not in existing_keys:
628
+ result.append(n)
629
+ existing_keys.add(normalized)
630
+ return result
631
+
632
+
633
+ def _merge_urls(
634
+ existing: List[Dict[str, Any]],
635
+ new_urls: List[Dict[str, Any]],
636
+ mode: str,
637
+ ) -> List[Dict[str, Any]]:
638
+ """
639
+ Merge URL lists according to mode. Dedup by normalized URL (scheme/host lowercased, trailing slash stripped).
640
+ """
641
+ if mode == "replace":
642
+ return new_urls
643
+ if mode == "remove":
644
+ remove_normalized = {
645
+ _normalize_url(u["value"]) for u in new_urls if u.get("value")
646
+ }
647
+ return [
648
+ u
649
+ for u in existing
650
+ if _normalize_url(u.get("value", "")) not in remove_normalized
651
+ ]
652
+ # merge: add new entries not already present
653
+ result = list(existing)
654
+ existing_keys = {_normalize_url(u.get("value", "")) for u in existing}
655
+ for u in new_urls:
656
+ normalized = _normalize_url(u.get("value", ""))
657
+ if normalized not in existing_keys:
658
+ result.append(u)
659
+ existing_keys.add(normalized)
660
+ return result
661
+
662
+
663
+ def _merge_user_defined(
664
+ existing: List[Dict[str, Any]],
665
+ new_ud: List[Dict[str, Any]],
666
+ mode: str,
667
+ ) -> List[Dict[str, Any]]:
668
+ """
669
+ Merge userDefined custom-field lists according to mode. Dedup by normalized key.
670
+ On merge, new value overrides existing for the same key.
671
+ """
672
+ if mode == "replace":
673
+ return new_ud
674
+ if mode == "remove":
675
+ remove_keys = {
676
+ _normalize_user_defined_key(ud["key"]) for ud in new_ud if ud.get("key")
677
+ }
678
+ return [
679
+ ud
680
+ for ud in existing
681
+ if _normalize_user_defined_key(ud.get("key", "")) not in remove_keys
682
+ ]
683
+ # merge: new value overrides existing for matching key; new keys appended
684
+ new_by_key = {_normalize_user_defined_key(ud.get("key", "")): ud for ud in new_ud}
685
+ result = []
686
+ seen_keys = set()
687
+ for ud in existing:
688
+ norm_key = _normalize_user_defined_key(ud.get("key", ""))
689
+ if norm_key in new_by_key:
690
+ result.append(new_by_key[norm_key])
691
+ seen_keys.add(norm_key)
692
+ else:
693
+ result.append(ud)
694
+ for norm_key, ud in new_by_key.items():
695
+ if norm_key not in seen_keys:
696
+ result.append(ud)
697
+ return result
698
+
699
+
700
+ def _merge_relations(
701
+ existing: List[Dict[str, Any]],
702
+ new_relations: List[Dict[str, Any]],
703
+ mode: str,
704
+ ) -> List[Dict[str, Any]]:
705
+ """
706
+ Merge relations lists according to mode. Dedup by (normalized person, normalized type) tuple.
707
+ """
708
+
709
+ def relation_key(rel: Dict[str, Any]) -> tuple[str, str]:
710
+ label = rel.get("formattedType") or rel.get("type") or ""
711
+ return (
712
+ _normalize_relation_person(rel.get("person", "")),
713
+ label.strip().lower(),
714
+ )
715
+
716
+ if mode == "replace":
717
+ return new_relations
718
+ if mode == "remove":
719
+ remove_keys = {relation_key(r) for r in new_relations}
720
+ return [r for r in existing if relation_key(r) not in remove_keys]
721
+ # merge: add new entries not already present
722
+ result = list(existing)
723
+ existing_keys = {relation_key(r) for r in existing}
724
+ for r in new_relations:
725
+ rk = relation_key(r)
726
+ if rk not in existing_keys:
727
+ result.append(r)
728
+ existing_keys.add(rk)
729
+ return result
730
+
731
+
732
+ def _merge_names(
733
+ existing: List[Dict[str, Any]],
734
+ new_names: List[Dict[str, Any]],
735
+ ) -> List[Dict[str, Any]]:
736
+ """
737
+ Overlay the provided name parts onto the contact's existing name, so changing
738
+ one part (e.g. givenName) keeps the rest (familyName, middleName, suffix...).
739
+ """
740
+ current = next(
741
+ (
742
+ name
743
+ for name in existing
744
+ if name.get("metadata", {}).get("source", {}).get("type") == "CONTACT"
745
+ ),
746
+ {},
747
+ )
748
+ unstructured = current.get("unstructuredName")
749
+ if unstructured and unstructured != " ".join(
750
+ current[part]
751
+ for part in (
752
+ "honorificPrefix",
753
+ "givenName",
754
+ "middleName",
755
+ "familyName",
756
+ "honorificSuffix",
757
+ )
758
+ if current.get(part)
759
+ ):
760
+ raise UserInputError(
761
+ "Cannot partially update a name with an unstructuredName that "
762
+ "cannot be represented by its structured parts."
763
+ )
764
+ kept = {k: v for k, v in current.items() if k not in _DERIVED_NAME_FIELDS}
765
+ return [{**kept, **new_names[0]}]