@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,609 @@
1
+ """
2
+ Core Comments Module
3
+
4
+ This module provides reusable comment management functions for Google Workspace applications.
5
+ All Google Workspace apps (Docs, Sheets, Slides) use the Drive API for comment operations.
6
+ """
7
+
8
+ import logging
9
+ import asyncio
10
+ import os
11
+ from typing import Awaitable, Callable, Optional
12
+
13
+ from mcp.types import ToolAnnotations
14
+
15
+ from auth.service_decorator import require_google_service, require_multiple_services
16
+ from core.server import server
17
+ from core.utils import UserInputError, handle_http_errors
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ READ_COMMENT_ANNOTATIONS = ToolAnnotations(
23
+ readOnlyHint=True,
24
+ destructiveHint=False,
25
+ idempotentHint=True,
26
+ openWorldHint=True,
27
+ )
28
+
29
+ MANAGE_COMMENT_ANNOTATIONS = ToolAnnotations(
30
+ readOnlyHint=False,
31
+ destructiveHint=True,
32
+ idempotentHint=False,
33
+ openWorldHint=True,
34
+ )
35
+
36
+
37
+ async def _manage_comment_dispatch(
38
+ service,
39
+ app_name: str,
40
+ file_id: str,
41
+ action: str,
42
+ comment_content: Optional[str] = None,
43
+ comment_id: Optional[str] = None,
44
+ cell: Optional[str] = None,
45
+ sheets_service=None,
46
+ insert_cell_comment: Optional[Callable[..., Awaitable[str]]] = None,
47
+ anchor_text: Optional[str] = None,
48
+ tab_id: Optional[str] = None,
49
+ docs_service=None,
50
+ insert_anchored_comment: Optional[Callable[..., Awaitable[dict]]] = None,
51
+ ) -> str:
52
+ """Route comment management actions to the appropriate implementation."""
53
+ action_lower = action.lower().strip()
54
+ anchor_text = anchor_text or None
55
+ tab_id = tab_id or None
56
+ if anchor_text is not None and not anchor_text.strip():
57
+ raise UserInputError("anchor_text must not be empty")
58
+ if cell and action_lower in ("reply", "resolve", "update", "delete"):
59
+ raise ValueError("cell is only supported for the create action")
60
+ if (anchor_text or tab_id) and action_lower in (
61
+ "reply",
62
+ "resolve",
63
+ "update",
64
+ "delete",
65
+ ):
66
+ raise UserInputError(
67
+ "anchor_text and tab_id are only supported for the create action"
68
+ )
69
+ if tab_id and not anchor_text:
70
+ raise UserInputError("tab_id requires anchor_text")
71
+ if action_lower == "create":
72
+ if not comment_content:
73
+ raise ValueError("comment_content is required for create action")
74
+ if cell:
75
+ if insert_cell_comment is None:
76
+ raise ValueError("insert_cell_comment is required for cell comments")
77
+ return await _create_cell_comment_impl(
78
+ insert_cell_comment, sheets_service, file_id, cell, comment_content
79
+ )
80
+ if anchor_text:
81
+ if insert_anchored_comment is None:
82
+ raise ValueError(
83
+ "insert_anchored_comment is required for anchored comments"
84
+ )
85
+ return await _create_anchored_comment_impl(
86
+ insert_anchored_comment,
87
+ docs_service,
88
+ file_id,
89
+ anchor_text,
90
+ comment_content,
91
+ tab_id,
92
+ )
93
+ return await _create_comment_impl(service, app_name, file_id, comment_content)
94
+ elif action_lower == "reply":
95
+ if not comment_id or not comment_content:
96
+ raise ValueError(
97
+ "comment_id and comment_content are required for reply action"
98
+ )
99
+ return await _reply_to_comment_impl(
100
+ service, app_name, file_id, comment_id, comment_content
101
+ )
102
+ elif action_lower == "resolve":
103
+ if not comment_id:
104
+ raise ValueError("comment_id is required for resolve action")
105
+ return await _resolve_comment_impl(service, app_name, file_id, comment_id)
106
+ elif action_lower == "update":
107
+ if not comment_id or not comment_content:
108
+ raise ValueError(
109
+ "comment_id and comment_content are required for update action"
110
+ )
111
+ return await _update_comment_impl(
112
+ service, app_name, file_id, comment_id, comment_content
113
+ )
114
+ elif action_lower == "delete":
115
+ if not comment_id:
116
+ raise ValueError("comment_id is required for delete action")
117
+ return await _delete_comment_impl(service, app_name, file_id, comment_id)
118
+ else:
119
+ raise ValueError(
120
+ f"Invalid action '{action_lower}'. Must be 'create', 'reply', "
121
+ "'resolve', 'update', or 'delete'."
122
+ )
123
+
124
+
125
+ def create_comment_tools(
126
+ app_name: str,
127
+ file_id_param: str,
128
+ insert_cell_comment: Optional[Callable[..., Awaitable[str]]] = None,
129
+ insert_anchored_comment: Optional[Callable[..., Awaitable[dict]]] = None,
130
+ ):
131
+ """
132
+ Factory function to create comment management tools for a specific Google Workspace app.
133
+
134
+ Args:
135
+ app_name: Name of the app (e.g., "document", "spreadsheet", "presentation")
136
+ file_id_param: Parameter name for the file ID (e.g., "document_id", "spreadsheet_id", "presentation_id")
137
+ insert_cell_comment: Spreadsheet only; passed in because gsheets imports this module.
138
+ insert_anchored_comment: Document only; passed in because gdocs imports this module.
139
+
140
+ Returns:
141
+ Dict containing the comment management functions with unique names
142
+ """
143
+
144
+ # --- Consolidated tools ---
145
+ list_func_name = f"list_{app_name}_comments"
146
+ manage_func_name = f"manage_{app_name}_comment"
147
+ app_title = app_name.replace("_", " ").title()
148
+
149
+ if file_id_param == "document_id":
150
+
151
+ @require_google_service("drive", "drive_read")
152
+ @handle_http_errors(list_func_name, is_read_only=True, service_type="drive")
153
+ async def list_comments(
154
+ service,
155
+ user_google_email: str,
156
+ document_id: str,
157
+ max_comments: int | None = None,
158
+ ) -> str:
159
+ """List all comments from a Google Document (optional max_comments to limit results)."""
160
+ return await _read_comments_impl(
161
+ service, app_name, document_id, max_comments=max_comments
162
+ )
163
+
164
+ # Use full Drive scope so comment operations remain visible to collaborators.
165
+ # The Docs API accepts it too, so anchored comments need no extra grant.
166
+ @require_multiple_services(
167
+ [
168
+ {"service_type": "drive", "scopes": "drive", "param_name": "service"},
169
+ {
170
+ "service_type": "docs",
171
+ "scopes": "drive",
172
+ "param_name": "docs_service",
173
+ },
174
+ ]
175
+ )
176
+ @handle_http_errors(manage_func_name, service_type="drive")
177
+ async def manage_comment(
178
+ service,
179
+ docs_service,
180
+ user_google_email: str,
181
+ document_id: str,
182
+ action: str,
183
+ comment_content: Optional[str] = None,
184
+ comment_id: Optional[str] = None,
185
+ anchor_text: Optional[str] = None,
186
+ tab_id: Optional[str] = None,
187
+ ) -> str:
188
+ """Manage comments on a Google Document.
189
+
190
+ Actions:
191
+ - create: Create a new comment. Requires comment_content. Pass
192
+ anchor_text (literal text within one paragraph that occurs exactly
193
+ once in the tab, table cells included) to anchor the comment to
194
+ that text in the margin, as the Docs editor does; otherwise it is
195
+ a document-level comment. tab_id picks the tab to search; the
196
+ first tab by default.
197
+ - reply: Reply to a comment. Requires comment_id and comment_content.
198
+ - resolve: Resolve a comment. Requires comment_id.
199
+ - update: Edit a comment's text. Requires comment_id and comment_content.
200
+ - delete: Delete a comment. Requires comment_id.
201
+ """
202
+ return await _manage_comment_dispatch(
203
+ service,
204
+ app_name,
205
+ document_id,
206
+ action,
207
+ comment_content,
208
+ comment_id,
209
+ anchor_text=anchor_text,
210
+ tab_id=tab_id,
211
+ docs_service=docs_service,
212
+ insert_anchored_comment=insert_anchored_comment,
213
+ )
214
+
215
+ elif file_id_param == "spreadsheet_id":
216
+
217
+ @require_google_service("drive", "drive_read")
218
+ @handle_http_errors(list_func_name, is_read_only=True, service_type="drive")
219
+ async def list_comments(
220
+ service,
221
+ user_google_email: str,
222
+ spreadsheet_id: str,
223
+ max_comments: int | None = None,
224
+ ) -> str:
225
+ """List all comments from a Google Spreadsheet (optional max_comments to limit results)."""
226
+ return await _read_comments_impl(
227
+ service, app_name, spreadsheet_id, max_comments=max_comments
228
+ )
229
+
230
+ # Use full Drive scope so comment operations remain visible to collaborators.
231
+ # Sheets batchUpdate also accepts it, so cell comments need no extra grant.
232
+ @require_multiple_services(
233
+ [
234
+ {"service_type": "drive", "scopes": "drive", "param_name": "service"},
235
+ {
236
+ "service_type": "sheets",
237
+ "scopes": "drive",
238
+ "param_name": "sheets_service",
239
+ },
240
+ ]
241
+ )
242
+ @handle_http_errors(manage_func_name, service_type="drive")
243
+ async def manage_comment(
244
+ service,
245
+ sheets_service,
246
+ user_google_email: str,
247
+ spreadsheet_id: str,
248
+ action: str,
249
+ comment_content: Optional[str] = None,
250
+ comment_id: Optional[str] = None,
251
+ cell: Optional[str] = None,
252
+ ) -> str:
253
+ """Manage comments on a Google Spreadsheet.
254
+
255
+ Actions:
256
+ - create: Create a new comment. Requires comment_content. Pass cell
257
+ (A1 notation, e.g. 'Sheet1!B2'; defaults to the first sheet) to
258
+ anchor it to a cell; otherwise it is a file-level comment.
259
+ - reply: Reply to a comment. Requires comment_id and comment_content.
260
+ - resolve: Resolve a comment. Requires comment_id.
261
+ - update: Edit a comment's text. Requires comment_id and comment_content.
262
+ - delete: Delete a comment. Requires comment_id.
263
+ """
264
+ return await _manage_comment_dispatch(
265
+ service,
266
+ app_name,
267
+ spreadsheet_id,
268
+ action,
269
+ comment_content,
270
+ comment_id,
271
+ cell=cell,
272
+ sheets_service=sheets_service,
273
+ insert_cell_comment=insert_cell_comment,
274
+ )
275
+
276
+ elif file_id_param == "presentation_id":
277
+
278
+ @require_google_service("drive", "drive_read")
279
+ @handle_http_errors(list_func_name, is_read_only=True, service_type="drive")
280
+ async def list_comments(
281
+ service,
282
+ user_google_email: str,
283
+ presentation_id: str,
284
+ max_comments: int | None = None,
285
+ ) -> str:
286
+ """List all comments from a Google Presentation (optional max_comments to limit results)."""
287
+ return await _read_comments_impl(
288
+ service, app_name, presentation_id, max_comments=max_comments
289
+ )
290
+
291
+ # Use full Drive scope so comment operations remain visible to collaborators.
292
+ @require_google_service("drive", "drive")
293
+ @handle_http_errors(manage_func_name, service_type="drive")
294
+ async def manage_comment(
295
+ service,
296
+ user_google_email: str,
297
+ presentation_id: str,
298
+ action: str,
299
+ comment_content: Optional[str] = None,
300
+ comment_id: Optional[str] = None,
301
+ ) -> str:
302
+ """Manage comments on a Google Presentation.
303
+
304
+ Actions:
305
+ - create: Create a new comment. Requires comment_content.
306
+ Note: The Drive API cannot anchor comments to arbitrary text;
307
+ Slides comments are element-scoped via the API.
308
+ - reply: Reply to a comment. Requires comment_id and comment_content.
309
+ - resolve: Resolve a comment. Requires comment_id.
310
+ - update: Edit a comment's text. Requires comment_id and comment_content.
311
+ - delete: Delete a comment. Requires comment_id.
312
+ """
313
+ return await _manage_comment_dispatch(
314
+ service, app_name, presentation_id, action, comment_content, comment_id
315
+ )
316
+
317
+ list_comments.__name__ = list_func_name
318
+ manage_comment.__name__ = manage_func_name
319
+ server.tool(
320
+ title=f"List {app_title} Comments",
321
+ annotations=READ_COMMENT_ANNOTATIONS,
322
+ )(list_comments)
323
+ server.tool(
324
+ title=f"Manage {app_title} Comment",
325
+ annotations=MANAGE_COMMENT_ANNOTATIONS,
326
+ )(manage_comment)
327
+
328
+ return {
329
+ "list_comments": list_comments,
330
+ "manage_comment": manage_comment,
331
+ }
332
+
333
+
334
+ def _format_field(label: str, value: str) -> str:
335
+ """Render a labeled value with continuation lines indented under the value.
336
+
337
+ Comment text is free-form and may contain newlines; without the hanging
338
+ indent a line such as "Author: ..." inside a comment body would be
339
+ indistinguishable from a real field.
340
+ """
341
+ return label + ("\n" + " " * len(label)).join(value.splitlines())
342
+
343
+
344
+ async def _read_comments_impl(
345
+ service, app_name: str, file_id: str, max_comments: int | None = None
346
+ ) -> str:
347
+ """Implementation for reading comments from any Google Workspace file."""
348
+ logger.info(f"[read_{app_name}_comments] Reading comments for {app_name} {file_id}")
349
+
350
+ if max_comments is not None and max_comments < 1:
351
+ raise UserInputError("max_comments must be a positive integer.")
352
+ if max_comments is None:
353
+ try:
354
+ max_comments = int(os.getenv("WORKSPACE_MCP_COMMENTS_MAX", "100"))
355
+ except ValueError:
356
+ max_comments = 100
357
+ if max_comments < 1:
358
+ max_comments = 100
359
+
360
+ comments: list = []
361
+ page_token: str | None = None
362
+
363
+ while len(comments) < max_comments:
364
+ remaining = max_comments - len(comments)
365
+ page_size = min(100, remaining)
366
+
367
+ kwargs: dict = {
368
+ "fileId": file_id,
369
+ "fields": "nextPageToken,comments(id,content,author,createdTime,modifiedTime,resolved,quotedFileContent,anchor,replies(content,author,id,createdTime,modifiedTime))",
370
+ "pageSize": page_size,
371
+ }
372
+ if page_token is not None:
373
+ kwargs["pageToken"] = page_token
374
+
375
+ response = await asyncio.to_thread(service.comments().list(**kwargs).execute)
376
+
377
+ page_comments = response.get("comments", [])
378
+ take = min(len(page_comments), max_comments - len(comments))
379
+ comments.extend(page_comments[:take])
380
+
381
+ page_token = response.get("nextPageToken")
382
+ if not page_token or len(comments) >= max_comments:
383
+ break
384
+
385
+ if not comments:
386
+ return f"No comments found in {app_name} {file_id}"
387
+
388
+ output = [f"Found {len(comments)} comments in {app_name} {file_id}:\n"]
389
+
390
+ for comment in comments:
391
+ author = comment.get("author", {}).get("displayName", "Unknown")
392
+ content = comment.get("content", "")
393
+ created = comment.get("createdTime", "")
394
+ resolved = comment.get("resolved", False)
395
+ comment_id = comment.get("id", "")
396
+ status = " [RESOLVED]" if resolved else ""
397
+
398
+ quoted_text = comment.get("quotedFileContent", {}).get("value", "")
399
+ anchor = comment.get("anchor", "")
400
+
401
+ output.append(f"Comment ID: {comment_id}")
402
+ output.append(f"Author: {author}")
403
+ output.append(f"Created: {created}{status}")
404
+ if quoted_text:
405
+ output.append(_format_field("Quoted text: ", quoted_text))
406
+ if anchor:
407
+ # Opaque, file-type specific; Slides lists element objectIds in `targets`.
408
+ output.append(_format_field("Anchor: ", anchor))
409
+ output.append(_format_field("Content: ", content))
410
+
411
+ replies = comment.get("replies", [])
412
+ if replies:
413
+ output.append(f" Replies ({len(replies)}):")
414
+ for reply in replies:
415
+ reply_author = reply.get("author", {}).get("displayName", "Unknown")
416
+ reply_content = reply.get("content", "")
417
+ reply_created = reply.get("createdTime", "")
418
+ reply_id = reply.get("id", "")
419
+ output.append(f" Reply ID: {reply_id}")
420
+ output.append(f" Author: {reply_author}")
421
+ output.append(f" Created: {reply_created}")
422
+ output.append(_format_field(" Content: ", reply_content))
423
+
424
+ output.append("") # Empty line between comments
425
+
426
+ return "\n".join(output)
427
+
428
+
429
+ async def _create_comment_impl(
430
+ service, app_name: str, file_id: str, comment_content: str
431
+ ) -> str:
432
+ """Implementation for creating a comment on any Google Workspace file.
433
+
434
+ Note: Comments created via the Drive API appear as document-level comments;
435
+ the Docs editor ignores Drive API anchors. For a Google Doc, pass anchor_text
436
+ to manage_document_comment to create an anchored comment through the Docs API.
437
+ """
438
+ logger.info(f"[create_{app_name}_comment] Creating comment in {app_name} {file_id}")
439
+
440
+ body = {"content": comment_content}
441
+
442
+ comment = await asyncio.to_thread(
443
+ service.comments()
444
+ .create(
445
+ fileId=file_id,
446
+ body=body,
447
+ fields="id,content,author,createdTime,modifiedTime",
448
+ )
449
+ .execute
450
+ )
451
+
452
+ comment_id = comment.get("id", "")
453
+ author = comment.get("author", {}).get("displayName", "Unknown")
454
+ created = comment.get("createdTime", "")
455
+
456
+ return f"Comment created successfully!\nComment ID: {comment_id}\nAuthor: {author}\nCreated: {created}\n{_format_field('Content: ', comment_content)}"
457
+
458
+
459
+ async def _create_cell_comment_impl(
460
+ insert_cell_comment: Callable[..., Awaitable[str]],
461
+ sheets_service,
462
+ spreadsheet_id: str,
463
+ cell: str,
464
+ comment_content: str,
465
+ ) -> str:
466
+ """Implementation for creating a cell-anchored comment on a spreadsheet."""
467
+ logger.info(
468
+ f"[create_spreadsheet_comment] Creating comment on {cell} in spreadsheet {spreadsheet_id}"
469
+ )
470
+ comment_id = await insert_cell_comment(
471
+ sheets_service, spreadsheet_id, cell, comment_content
472
+ )
473
+ return f"Comment created successfully on {cell}!\nComment ID: {comment_id}\n{_format_field('Content: ', comment_content)}"
474
+
475
+
476
+ async def _create_anchored_comment_impl(
477
+ insert_anchored_comment: Callable[..., Awaitable[dict]],
478
+ docs_service,
479
+ document_id: str,
480
+ anchor_text: str,
481
+ comment_content: str,
482
+ tab_id: Optional[str] = None,
483
+ ) -> str:
484
+ """Implementation for creating a text-anchored comment on a document."""
485
+ logger.info(
486
+ f"[create_document_comment] Creating anchored comment in document {document_id}"
487
+ )
488
+ created = await insert_anchored_comment(
489
+ docs_service, document_id, anchor_text, comment_content, tab_id
490
+ )
491
+ return (
492
+ f"Comment created successfully, anchored to the text "
493
+ f"(indices {created['start_index']}-{created['end_index']})!\n"
494
+ f"Comment ID: {created['comment_id']}\n"
495
+ f"{_format_field('Anchored text: ', created['quoted_text'])}\n"
496
+ f"{_format_field('Content: ', comment_content)}"
497
+ )
498
+
499
+
500
+ async def _reply_to_comment_impl(
501
+ service, app_name: str, file_id: str, comment_id: str, reply_content: str
502
+ ) -> str:
503
+ """Implementation for replying to a comment on any Google Workspace file."""
504
+ logger.info(
505
+ f"[reply_to_{app_name}_comment] Replying to comment {comment_id} in {app_name} {file_id}"
506
+ )
507
+
508
+ body = {"content": reply_content}
509
+
510
+ reply = await asyncio.to_thread(
511
+ service.replies()
512
+ .create(
513
+ fileId=file_id,
514
+ commentId=comment_id,
515
+ body=body,
516
+ fields="id,content,author,createdTime,modifiedTime",
517
+ )
518
+ .execute
519
+ )
520
+
521
+ reply_id = reply.get("id", "")
522
+ author = reply.get("author", {}).get("displayName", "Unknown")
523
+ created = reply.get("createdTime", "")
524
+
525
+ return f"Reply posted successfully!\nReply ID: {reply_id}\nAuthor: {author}\nCreated: {created}\n{_format_field('Content: ', reply_content)}"
526
+
527
+
528
+ async def _resolve_comment_impl(
529
+ service, app_name: str, file_id: str, comment_id: str
530
+ ) -> str:
531
+ """Implementation for resolving a comment on any Google Workspace file."""
532
+ logger.info(
533
+ f"[resolve_{app_name}_comment] Resolving comment {comment_id} in {app_name} {file_id}"
534
+ )
535
+
536
+ body = {"content": "This comment has been resolved.", "action": "resolve"}
537
+
538
+ reply = await asyncio.to_thread(
539
+ service.replies()
540
+ .create(
541
+ fileId=file_id,
542
+ commentId=comment_id,
543
+ body=body,
544
+ fields="id,content,author,createdTime,modifiedTime",
545
+ )
546
+ .execute
547
+ )
548
+
549
+ reply_id = reply.get("id", "")
550
+ author = reply.get("author", {}).get("displayName", "Unknown")
551
+ created = reply.get("createdTime", "")
552
+
553
+ return f"Comment {comment_id} has been resolved successfully.\nResolve reply ID: {reply_id}\nAuthor: {author}\nCreated: {created}"
554
+
555
+
556
+ async def _require_own_comment(service, file_id: str, comment_id: str) -> None:
557
+ """Raise UserInputError unless the authenticated user wrote the comment."""
558
+ comment = await asyncio.to_thread(
559
+ service.comments()
560
+ .get(fileId=file_id, commentId=comment_id, fields="author(me)")
561
+ .execute
562
+ )
563
+ if not comment.get("author", {}).get("me"):
564
+ raise UserInputError(
565
+ f"Comment {comment_id} was written by another user; only its author "
566
+ "can update or delete it."
567
+ )
568
+
569
+
570
+ async def _update_comment_impl(
571
+ service, app_name: str, file_id: str, comment_id: str, comment_content: str
572
+ ) -> str:
573
+ """Implementation for editing a comment on any Google Workspace file."""
574
+ logger.info(
575
+ f"[update_{app_name}_comment] Updating comment {comment_id} in {app_name} {file_id}"
576
+ )
577
+ await _require_own_comment(service, file_id, comment_id)
578
+
579
+ comment = await asyncio.to_thread(
580
+ service.comments()
581
+ .update(
582
+ fileId=file_id,
583
+ commentId=comment_id,
584
+ body={"content": comment_content},
585
+ fields="id,content,author,modifiedTime",
586
+ )
587
+ .execute
588
+ )
589
+
590
+ author = comment.get("author", {}).get("displayName", "Unknown")
591
+ modified = comment.get("modifiedTime", "")
592
+
593
+ return f"Comment {comment_id} updated successfully!\nAuthor: {author}\nModified: {modified}\n{_format_field('Content: ', comment_content)}"
594
+
595
+
596
+ async def _delete_comment_impl(
597
+ service, app_name: str, file_id: str, comment_id: str
598
+ ) -> str:
599
+ """Implementation for deleting a comment on any Google Workspace file."""
600
+ logger.info(
601
+ f"[delete_{app_name}_comment] Deleting comment {comment_id} in {app_name} {file_id}"
602
+ )
603
+ await _require_own_comment(service, file_id, comment_id)
604
+
605
+ await asyncio.to_thread(
606
+ service.comments().delete(fileId=file_id, commentId=comment_id).execute
607
+ )
608
+
609
+ return f"Comment {comment_id} deleted from {app_name} {file_id}."
package/core/config.py ADDED
@@ -0,0 +1,57 @@
1
+ """
2
+ Shared configuration for Google Workspace MCP server.
3
+ This module holds configuration values that need to be shared across modules
4
+ to avoid circular imports.
5
+
6
+ NOTE: OAuth configuration has been moved to auth.oauth_config for centralization.
7
+ This module now imports from there for backward compatibility.
8
+ """
9
+
10
+ import os
11
+ from typing import TYPE_CHECKING
12
+
13
+ from auth.oauth_config import (
14
+ get_oauth_base_url,
15
+ get_oauth_redirect_uri,
16
+ set_transport_mode,
17
+ get_transport_mode,
18
+ is_oauth21_enabled,
19
+ )
20
+
21
+ # Server configuration. WORKSPACE_MCP_PORT is resolved lazily via PEP 562
22
+ # __getattr__ so that the value reflects the current env at access time.
23
+ # main.py mutates WORKSPACE_MCP_PORT in os.environ at startup via the port
24
+ # resolver (auth.port_resolver.resolve_port); consumers that do
25
+ # `from core.config import WORKSPACE_MCP_PORT` inside a function will see the
26
+ # late-bound port instead of a frozen-at-module-import 8000.
27
+ WORKSPACE_MCP_BASE_URI = os.getenv("WORKSPACE_MCP_BASE_URI", "http://localhost")
28
+ WORKSPACE_EXTERNAL_URL = os.getenv("WORKSPACE_EXTERNAL_URL")
29
+
30
+ if TYPE_CHECKING:
31
+ WORKSPACE_MCP_PORT: int
32
+
33
+
34
+ def __getattr__(name: str) -> int:
35
+ if name == "WORKSPACE_MCP_PORT":
36
+ if os.getenv("WORKSPACE_MCP_RESOLVED_PORT") == "1":
37
+ return int(os.getenv("WORKSPACE_MCP_PORT", os.getenv("PORT", "8000")))
38
+ return int(os.getenv("PORT", os.getenv("WORKSPACE_MCP_PORT", "8000")))
39
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
40
+
41
+
42
+ # Disable USER_GOOGLE_EMAIL in OAuth 2.1 multi-user mode
43
+ USER_GOOGLE_EMAIL = (
44
+ None if is_oauth21_enabled() else os.getenv("USER_GOOGLE_EMAIL", None)
45
+ )
46
+
47
+ # Re-export OAuth functions for backward compatibility
48
+ __all__ = [
49
+ "WORKSPACE_MCP_PORT",
50
+ "WORKSPACE_MCP_BASE_URI",
51
+ "WORKSPACE_EXTERNAL_URL",
52
+ "USER_GOOGLE_EMAIL",
53
+ "get_oauth_base_url",
54
+ "get_oauth_redirect_uri",
55
+ "set_transport_mode",
56
+ "get_transport_mode",
57
+ ]