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

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 +28 -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,7 @@
1
+ """
2
+ Google Chat MCP Tools Package
3
+ """
4
+
5
+ from . import chat_tools
6
+
7
+ __all__ = ["chat_tools"]
@@ -0,0 +1,410 @@
1
+ """
2
+ Google Chat Helper Functions
3
+
4
+ Request execution, argument normalization, message parsing, and name
5
+ resolution for Chat senders and spaces via the People API.
6
+ """
7
+
8
+ import asyncio
9
+ import logging
10
+ import re
11
+ import ssl
12
+ from typing import Dict, List, Optional, Tuple
13
+
14
+ from fastmcp.exceptions import ToolError
15
+ from googleapiclient.errors import HttpError
16
+
17
+ from core.utils import UserInputError, is_path_segment
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ _SENDER_CACHE_MAX_SIZE = 256
22
+ # Keyed per owner: People API names can include the owner's own contact labels.
23
+ _sender_name_cache: Dict[Tuple[str, str], str] = {}
24
+ _UNNAMED_SPACE_FALLBACKS = {
25
+ "DIRECT_MESSAGE": "Direct message",
26
+ "GROUP_CHAT": "Group chat",
27
+ }
28
+ _SPACE_NAME_MAX_MEMBERS = 3
29
+ _PEOPLE_BATCH_SIZE = 200 # people.getBatchGet limit
30
+ _MAX_CONSECUTIVE_MEMBER_LOOKUP_FAILURES = 2
31
+ _SCOPE_ERROR_REASON = "ACCESS_TOKEN_SCOPE_INSUFFICIENT"
32
+ _SEARCH_MESSAGES_RETRY_BASE_DELAY_SECONDS = 1
33
+ _MESSAGE_NAME_PATTERN = re.compile(r"spaces/([^/]+)/messages/([^/]+)")
34
+
35
+
36
+ def _cache_key(cache_owner: Optional[str], user_id: str) -> Optional[Tuple[str, str]]:
37
+ """Return cache_owner's cache key for user_id, or None when there is no owner."""
38
+ owner = (cache_owner or "").strip().lower()
39
+ return (owner, user_id) if owner else None
40
+
41
+
42
+ def _cached_name(cache_owner: Optional[str], user_id: str) -> Optional[str]:
43
+ key = _cache_key(cache_owner, user_id)
44
+ return _sender_name_cache.get(key) if key else None
45
+
46
+
47
+ def _cache_sender(cache_owner: Optional[str], user_id: str, name: str) -> None:
48
+ """Store a resolved sender name, evicting oldest entries if cache is full."""
49
+ key = _cache_key(cache_owner, user_id)
50
+ if key is None:
51
+ return
52
+ if len(_sender_name_cache) >= _SENDER_CACHE_MAX_SIZE:
53
+ to_remove = list(_sender_name_cache.keys())[: _SENDER_CACHE_MAX_SIZE // 2]
54
+ for k in to_remove:
55
+ del _sender_name_cache[k]
56
+ _sender_name_cache[key] = name
57
+
58
+
59
+ def _person_name(person: dict) -> Optional[str]:
60
+ """Return a People API person's display name, falling back to their email."""
61
+ names = person.get("names") or [{}]
62
+ emails = person.get("emailAddresses") or [{}]
63
+ return names[0].get("displayName") or emails[0].get("value")
64
+
65
+
66
+ async def _resolve_sender(
67
+ people_service, sender_obj: dict, cache_owner: Optional[str] = None
68
+ ) -> str:
69
+ """Resolve a Chat message sender to a display name.
70
+
71
+ Fast path: use displayName if the API already provided it.
72
+ Slow path: look up the user via the People API and cache the result per cache_owner.
73
+ """
74
+ display_name = sender_obj.get("displayName")
75
+ if display_name:
76
+ return display_name
77
+
78
+ user_id = sender_obj.get("name", "") # e.g. "users/123456789"
79
+ if not user_id:
80
+ return "Unknown Sender"
81
+
82
+ cached = _cached_name(cache_owner, user_id)
83
+ if cached:
84
+ return cached
85
+
86
+ # Chat API uses "users/ID" but People API expects "people/ID"
87
+ people_resource = user_id.replace("users/", "people/", 1)
88
+ if people_service:
89
+ try:
90
+ person = await asyncio.to_thread(
91
+ people_service.people()
92
+ .get(resourceName=people_resource, personFields="names,emailAddresses")
93
+ .execute
94
+ )
95
+ resolved = _person_name(person)
96
+ if resolved:
97
+ _cache_sender(cache_owner, user_id, resolved)
98
+ return resolved
99
+ except HttpError as e:
100
+ logger.debug(f"People API lookup failed for {user_id}: {e}")
101
+ except Exception as e:
102
+ logger.debug(f"Unexpected error resolving {user_id}: {e}")
103
+
104
+ return user_id
105
+
106
+
107
+ async def _lookup_people_names(
108
+ people_service, user_ids: List[str], cache_owner: Optional[str] = None
109
+ ) -> Dict[str, str]:
110
+ """Resolve Chat user ids to display names with batched People API calls."""
111
+ names = {}
112
+ missing = []
113
+ for user_id in user_ids:
114
+ cached = _cached_name(cache_owner, user_id)
115
+ if cached:
116
+ names[user_id] = cached
117
+ else:
118
+ missing.append(user_id)
119
+ for start in range(0, len(missing), _PEOPLE_BATCH_SIZE):
120
+ chunk = missing[start : start + _PEOPLE_BATCH_SIZE]
121
+ try:
122
+ response = await asyncio.to_thread(
123
+ people_service.people()
124
+ .getBatchGet(
125
+ resourceNames=[
126
+ user_id.replace("users/", "people/", 1) for user_id in chunk
127
+ ],
128
+ personFields="names,emailAddresses",
129
+ )
130
+ .execute
131
+ )
132
+ except Exception as e:
133
+ logger.debug(f"People API batch lookup failed: {e}")
134
+ continue
135
+ for entry in response.get("responses", []):
136
+ name = _person_name(entry.get("person") or {})
137
+ requested = entry.get("requestedResourceName")
138
+ if name and requested:
139
+ user_id = requested.replace("people/", "users/", 1)
140
+ names[user_id] = name
141
+ _cache_sender(cache_owner, user_id, name)
142
+ return names
143
+
144
+
145
+ def _is_scope_error(error: HttpError) -> bool:
146
+ """Return True when an HttpError carries an ACCESS_TOKEN_SCOPE_INSUFFICIENT detail."""
147
+ details = error.error_details
148
+ return isinstance(details, list) and any(
149
+ isinstance(d, dict) and d.get("reason") == _SCOPE_ERROR_REASON for d in details
150
+ )
151
+
152
+
153
+ async def _list_memberships(
154
+ chat_service, space_name: str, limit: Optional[int] = None, **list_params
155
+ ) -> List[dict]:
156
+ """Return a space's memberships, stopping once more than limit are found."""
157
+ memberships = []
158
+ # Page-token requests must repeat the original pageSize.
159
+ page_size = 100 if limit is None else min(100, limit + 1)
160
+ params = {"parent": space_name, "pageSize": page_size, **list_params}
161
+ while True:
162
+ response = await asyncio.to_thread(
163
+ chat_service.spaces().members().list(**params).execute
164
+ )
165
+ memberships.extend(response.get("memberships", []))
166
+ if not response.get("nextPageToken") or (
167
+ limit is not None and len(memberships) > limit
168
+ ):
169
+ return memberships
170
+ params["pageToken"] = response["nextPageToken"]
171
+
172
+
173
+ async def _name_spaces(
174
+ chat_service,
175
+ people_service,
176
+ spaces: List[dict],
177
+ cache_owner: Optional[str] = None,
178
+ ) -> Dict[str, str]:
179
+ """Map space resource names to labels, naming unnamed spaces after their members."""
180
+ labels = {}
181
+ unnamed = []
182
+ for space in spaces:
183
+ space_name = space.get("name")
184
+ if space_name in labels:
185
+ continue
186
+ if space.get("displayName"):
187
+ labels[space_name] = space["displayName"]
188
+ else:
189
+ labels[space_name] = _UNNAMED_SPACE_FALLBACKS.get(
190
+ space.get("spaceType"), "Unnamed Space"
191
+ )
192
+ unnamed.append(space_name)
193
+ if not unnamed:
194
+ return labels
195
+
196
+ # Without the caller's id their own name would end up in every label.
197
+ try:
198
+ me = await asyncio.to_thread(
199
+ people_service.people()
200
+ .get(resourceName="people/me", personFields="metadata")
201
+ .execute
202
+ )
203
+ except Exception as e:
204
+ logger.debug(f"Could not look up the calling user: {e}")
205
+ return labels
206
+ if not me.get("resourceName"):
207
+ return labels
208
+ me_id = me["resourceName"].replace("people/", "users/", 1)
209
+
210
+ others_by_space = {}
211
+ consecutive_failures = 0
212
+ for space_name in unnamed:
213
+ try:
214
+ memberships = await _list_memberships(chat_service, space_name)
215
+ except HttpError as e:
216
+ logger.debug(f"Could not list members of {space_name}: {e}")
217
+ # Missing scope or throttling would fail every remaining space too.
218
+ if e.resp.status == 429 or _is_scope_error(e):
219
+ break
220
+ continue
221
+ except Exception as e:
222
+ logger.debug(f"Could not list members of {space_name}: {e}")
223
+ # Repeated network failures would make every remaining space wait too.
224
+ consecutive_failures += 1
225
+ if consecutive_failures >= _MAX_CONSECUTIVE_MEMBER_LOOKUP_FAILURES:
226
+ break
227
+ continue
228
+ consecutive_failures = 0
229
+ others = []
230
+ for membership in memberships:
231
+ member = membership.get("member", {})
232
+ if member.get("type") == "HUMAN" and member.get("name") != me_id:
233
+ others.append(member.get("name"))
234
+ if others:
235
+ others_by_space[space_name] = others
236
+
237
+ shown_ids = []
238
+ for others in others_by_space.values():
239
+ for user_id in others[:_SPACE_NAME_MAX_MEMBERS]:
240
+ if user_id not in shown_ids:
241
+ shown_ids.append(user_id)
242
+ people_names = await _lookup_people_names(people_service, shown_ids, cache_owner)
243
+
244
+ for space_name, others in others_by_space.items():
245
+ shown = others[:_SPACE_NAME_MAX_MEMBERS]
246
+ label = ", ".join(people_names.get(user_id, user_id) for user_id in shown)
247
+ remaining = len(others) - len(shown)
248
+ if remaining:
249
+ label += f" and {remaining} other{'s' if remaining > 1 else ''}"
250
+ labels[space_name] = label
251
+ return labels
252
+
253
+
254
+ _MEMBER_ROLE_LABELS = {
255
+ "ROLE_MANAGER": "manager",
256
+ "ROLE_ASSISTANT_MANAGER": "assistant manager",
257
+ "ROLE_MEMBER": "member",
258
+ }
259
+
260
+
261
+ async def _format_space_members(
262
+ chat_service, people_service, space_id: str, limit: int
263
+ ) -> str:
264
+ """List up to limit space members: people, apps, groups and pending invites."""
265
+ space = await asyncio.to_thread(chat_service.spaces().get(name=space_id).execute)
266
+ space_label = space.get("displayName") or _UNNAMED_SPACE_FALLBACKS.get(
267
+ space.get("spaceType"), "Unnamed Space"
268
+ )
269
+ try:
270
+ memberships = await _list_memberships(
271
+ chat_service, space_id, limit, showInvited=True, showGroups=True
272
+ )
273
+ except HttpError as e:
274
+ if _is_scope_error(e):
275
+ raise ToolError(
276
+ "Listing members needs the chat.memberships.readonly scope, which "
277
+ "this token lacks. Re-authenticate with the default Chat scopes and "
278
+ "retry. In service-account (domain-wide delegation) mode list_spaces "
279
+ "does not request that scope, so member listing is unavailable there."
280
+ ) from e
281
+ raise
282
+
283
+ has_more = len(memberships) > limit
284
+ memberships = memberships[:limit]
285
+ user_ids = [
286
+ m["member"]["name"]
287
+ for m in memberships
288
+ if m.get("member", {}).get("type") == "HUMAN" and m["member"].get("name")
289
+ ]
290
+ people_names = await _lookup_people_names(people_service, user_ids)
291
+
292
+ count = (
293
+ f"first {len(memberships)} shown, more exist (raise page_size to see more)"
294
+ if has_more
295
+ else str(len(memberships))
296
+ )
297
+ lines = [f"Members of '{space_label}' (ID: {space_id}): {count}"]
298
+ for membership in memberships:
299
+ role = _MEMBER_ROLE_LABELS.get(membership.get("role"), "unknown")
300
+ state = membership.get("state")
301
+ suffix = ", invited" if state == "INVITED" else ""
302
+ if "groupMember" in membership:
303
+ group_id = membership["groupMember"].get("name", "")
304
+ lines.append(f"- Group {group_id}" + (" (invited)" if suffix else ""))
305
+ continue
306
+ member = membership.get("member", {})
307
+ member_id = member.get("name", "")
308
+ name = (
309
+ people_names.get(member_id)
310
+ or member.get("displayName")
311
+ or member_id
312
+ or "Unknown"
313
+ )
314
+ kind = " [app]" if member.get("type") == "BOT" else ""
315
+ detail = (
316
+ f"{role}{suffix}" if name == member_id else f"{member_id}, {role}{suffix}"
317
+ )
318
+ lines.append(f"- {name}{kind} ({detail})")
319
+ return "\n".join(lines)
320
+
321
+
322
+ def _none_if_null_sentinel(value: Optional[str]) -> Optional[str]:
323
+ """Map the literal "null"/"None" some clients send for an omitted arg to None."""
324
+ if value is not None and value.strip().lower() in ("null", "none"):
325
+ return None
326
+ return value
327
+
328
+
329
+ def _none_if_blank(value: Optional[str]) -> Optional[str]:
330
+ """Treat a null sentinel or whitespace-only string as an omitted arg."""
331
+ value = _none_if_null_sentinel(value)
332
+ return value if value and value.strip() else None
333
+
334
+
335
+ def _normalize_space_resource_name(space_id: str) -> str:
336
+ """Return spaces/<id> for a space resource name or a bare space ID."""
337
+ value = space_id.strip().removeprefix("spaces/")
338
+ if not is_path_segment(value):
339
+ raise UserInputError(
340
+ f"Invalid space_id '{space_id}'. Expected spaces/X or a bare space ID X."
341
+ )
342
+ return f"spaces/{value}"
343
+
344
+
345
+ def _normalize_message_resource_name(
346
+ message_name: str, label: str = "message_id"
347
+ ) -> str:
348
+ """Return message_name if it is spaces/X/messages/Y with safe X and Y."""
349
+ match = _MESSAGE_NAME_PATTERN.fullmatch(message_name)
350
+ if match is None or not all(map(is_path_segment, match.groups())):
351
+ raise UserInputError(
352
+ f"Invalid {label} '{message_name}'. "
353
+ "Expected the full resource name, e.g. spaces/X/messages/Y."
354
+ )
355
+ return message_name
356
+
357
+
358
+ async def _execute_chat_request(
359
+ request_factory,
360
+ *,
361
+ request_label: str,
362
+ retries: int = 1,
363
+ semaphore: Optional[asyncio.Semaphore] = None,
364
+ ):
365
+ """Execute a Chat API request in a worker thread with optional SSL retries."""
366
+ for attempt in range(retries):
367
+ try:
368
+ if semaphore is None:
369
+ return await asyncio.to_thread(lambda: request_factory().execute())
370
+ async with semaphore:
371
+ return await asyncio.to_thread(lambda: request_factory().execute())
372
+ except ssl.SSLError as e:
373
+ if attempt == retries - 1:
374
+ raise
375
+ delay = _SEARCH_MESSAGES_RETRY_BASE_DELAY_SECONDS * (2**attempt)
376
+ logger.warning(
377
+ "[search_messages] SSL error during %s on attempt %s/%s: %s. Retrying in %s seconds.",
378
+ request_label,
379
+ attempt + 1,
380
+ retries,
381
+ e,
382
+ delay,
383
+ )
384
+ await asyncio.sleep(delay)
385
+
386
+
387
+ def _extract_rich_links(msg: dict) -> List[str]:
388
+ """Extract URLs from RICH_LINK annotations (smart chips).
389
+
390
+ When a user pastes a Google Workspace URL in Chat and it renders as a
391
+ smart chip, the URL is NOT in the text field; it's only available in
392
+ the annotations array as a RICH_LINK with richLinkMetadata.uri.
393
+ """
394
+ text = msg.get("text", "")
395
+ urls = []
396
+ for ann in msg.get("annotations", []):
397
+ if ann.get("type") == "RICH_LINK":
398
+ uri = ann.get("richLinkMetadata", {}).get("uri", "")
399
+ if uri and uri not in text:
400
+ urls.append(uri)
401
+ return urls
402
+
403
+
404
+ def _format_search_message_ids(message: dict) -> str:
405
+ identifiers = (
406
+ ("space_id", message.get("_space", {}).get("name")),
407
+ ("message_id", message.get("name")),
408
+ ("thread_id", message.get("thread", {}).get("name")),
409
+ )
410
+ return " ".join(f"[{label}: {value}]" for label, value in identifiers if value)