@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,936 @@
1
+ """
2
+ Google Tasks MCP Tools
3
+
4
+ This module provides MCP tools for interacting with Google Tasks API.
5
+ """
6
+
7
+ import asyncio
8
+ import logging
9
+ from datetime import datetime, timedelta, timezone
10
+ from typing import Any, Dict, List, Optional
11
+
12
+ from mcp import Resource
13
+
14
+ from auth.permissions import is_action_denied
15
+ from mcp.types import ToolAnnotations
16
+
17
+ from auth.service_decorator import require_google_service
18
+ from core.server import server
19
+ from core.utils import UserInputError, handle_http_errors
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ LIST_TASKS_MAX_RESULTS_DEFAULT = 20
24
+ LIST_TASKS_MAX_RESULTS_MAX = 10_000
25
+ LIST_TASKS_MAX_POSITION = "99999999999999999999"
26
+
27
+
28
+ class StructuredTask:
29
+ def __init__(self, task: Dict[str, str], is_placeholder_parent: bool) -> None:
30
+ self.id = task["id"]
31
+ self.title = task.get("title", None)
32
+ self.status = task.get("status", None)
33
+ self.due = task.get("due", None)
34
+ self.notes = task.get("notes", None)
35
+ self.updated = task.get("updated", None)
36
+ self.completed = task.get("completed", None)
37
+ self.is_placeholder_parent = is_placeholder_parent
38
+ self.subtasks: List["StructuredTask"] = []
39
+
40
+ def add_subtask(self, subtask: "StructuredTask") -> None:
41
+ self.subtasks.append(subtask)
42
+
43
+ def __repr__(self) -> str:
44
+ return f"StructuredTask(title={self.title}, {len(self.subtasks)} subtasks)"
45
+
46
+
47
+ def _adjust_due_max_for_tasks_api(due_max: str) -> str:
48
+ """
49
+ Compensate for the Google Tasks API treating dueMax as an exclusive bound.
50
+
51
+ The API stores due dates at day resolution and compares using < dueMax, so to
52
+ include tasks due on the requested date we bump the bound by one day.
53
+ """
54
+ try:
55
+ parsed = datetime.fromisoformat(due_max.replace("Z", "+00:00"))
56
+ except ValueError:
57
+ logger.warning(
58
+ "[list_tasks] Unable to parse due_max '%s'; sending unmodified value",
59
+ due_max,
60
+ )
61
+ return due_max
62
+
63
+ if parsed.tzinfo is None:
64
+ parsed = parsed.replace(tzinfo=timezone.utc)
65
+
66
+ adjusted = parsed + timedelta(days=1)
67
+ if adjusted.tzinfo == timezone.utc:
68
+ return adjusted.isoformat().replace("+00:00", "Z")
69
+ return adjusted.isoformat()
70
+
71
+
72
+ def _validate_rfc3339_date(due: str) -> None:
73
+ """Validate that due is a full RFC 3339 datetime (date-only strings are rejected by the API)."""
74
+ error_msg = f"Invalid due date format. Expected RFC 3339 datetime (e.g., '2026-04-25T00:00:00Z'), got '{due}'"
75
+ if "T" not in due:
76
+ raise UserInputError(error_msg)
77
+ try:
78
+ parsed = datetime.fromisoformat(
79
+ due[:-1] + "+00:00" if due.endswith("Z") else due
80
+ )
81
+ except ValueError:
82
+ raise UserInputError(error_msg) from None
83
+ if parsed.tzinfo is None or parsed.utcoffset() is None:
84
+ raise UserInputError(error_msg)
85
+
86
+
87
+ @server.tool(
88
+ title="List Task Lists",
89
+ annotations=ToolAnnotations(
90
+ readOnlyHint=True,
91
+ destructiveHint=False,
92
+ idempotentHint=True,
93
+ openWorldHint=True,
94
+ ),
95
+ )
96
+ @require_google_service("tasks", "tasks_read") # type: ignore
97
+ @handle_http_errors("list_task_lists", service_type="tasks") # type: ignore
98
+ async def list_task_lists(
99
+ service: Resource,
100
+ user_google_email: str,
101
+ max_results: int = 1000,
102
+ page_token: Optional[str] = None,
103
+ ) -> str:
104
+ """
105
+ List all task lists for the user.
106
+
107
+ Args:
108
+ user_google_email (str): The user's Google email address. Required.
109
+ max_results (int): Maximum number of task lists to return (default: 1000, max: 1000).
110
+ page_token (Optional[str]): Token for pagination.
111
+
112
+ Returns:
113
+ str: List of task lists with their IDs, titles, and details.
114
+ """
115
+ logger.info(f"[list_task_lists] Invoked. Email: '{user_google_email}'")
116
+
117
+ params: Dict[str, Any] = {}
118
+ if max_results is not None:
119
+ params["maxResults"] = max_results
120
+ if page_token:
121
+ params["pageToken"] = page_token
122
+
123
+ result = await asyncio.to_thread(service.tasklists().list(**params).execute)
124
+
125
+ task_lists = result.get("items", [])
126
+ next_page_token = result.get("nextPageToken")
127
+
128
+ if not task_lists:
129
+ return f"No task lists found for {user_google_email}."
130
+
131
+ response = f"Task Lists for {user_google_email}:\n"
132
+ for task_list in task_lists:
133
+ response += f"- {task_list['title']} (ID: {task_list['id']})\n"
134
+ response += f" Updated: {task_list.get('updated', 'N/A')}\n"
135
+
136
+ if next_page_token:
137
+ response += f"\nNext page token: {next_page_token}"
138
+
139
+ logger.info(f"Found {len(task_lists)} task lists for {user_google_email}")
140
+ return response
141
+
142
+
143
+ @server.tool(
144
+ title="Get Task List",
145
+ annotations=ToolAnnotations(
146
+ readOnlyHint=True,
147
+ destructiveHint=False,
148
+ idempotentHint=True,
149
+ openWorldHint=True,
150
+ ),
151
+ )
152
+ @require_google_service("tasks", "tasks_read") # type: ignore
153
+ @handle_http_errors("get_task_list", service_type="tasks") # type: ignore
154
+ async def get_task_list(
155
+ service: Resource, user_google_email: str, task_list_id: str
156
+ ) -> str:
157
+ """
158
+ Get details of a specific task list.
159
+
160
+ Args:
161
+ user_google_email (str): The user's Google email address. Required.
162
+ task_list_id (str): The ID of the task list to retrieve.
163
+
164
+ Returns:
165
+ str: Task list details including title, ID, and last updated time.
166
+ """
167
+ logger.info(
168
+ f"[get_task_list] Invoked. Email: '{user_google_email}', Task List ID: {task_list_id}"
169
+ )
170
+
171
+ task_list = await asyncio.to_thread(
172
+ service.tasklists().get(tasklist=task_list_id).execute
173
+ )
174
+
175
+ response = f"""Task List Details for {user_google_email}:
176
+ - Title: {task_list["title"]}
177
+ - ID: {task_list["id"]}
178
+ - Updated: {task_list.get("updated", "N/A")}
179
+ - Self Link: {task_list.get("selfLink", "N/A")}"""
180
+
181
+ logger.info(f"Retrieved task list {task_list_id} for {user_google_email}")
182
+ return response
183
+
184
+
185
+ # --- Task list _impl functions ---
186
+
187
+
188
+ async def _create_task_list_impl(
189
+ service: Resource, user_google_email: str, title: str
190
+ ) -> str:
191
+ """Implementation for creating a new task list."""
192
+ logger.info(
193
+ f"[create_task_list] Invoked. Email: '{user_google_email}', title_len={len(title)}"
194
+ )
195
+
196
+ body = {"title": title}
197
+
198
+ result = await asyncio.to_thread(service.tasklists().insert(body=body).execute)
199
+
200
+ response = f"""Task List Created for {user_google_email}:
201
+ - Title: {result["title"]}
202
+ - ID: {result["id"]}
203
+ - Created: {result.get("updated", "N/A")}
204
+ - Self Link: {result.get("selfLink", "N/A")}"""
205
+
206
+ logger.info(f"Created task list with ID {result['id']} for {user_google_email}")
207
+ return response
208
+
209
+
210
+ async def _update_task_list_impl(
211
+ service: Resource, user_google_email: str, task_list_id: str, title: str
212
+ ) -> str:
213
+ """Implementation for updating an existing task list."""
214
+ logger.info(
215
+ f"[update_task_list] Invoked. Email: '{user_google_email}', Task List ID: {task_list_id}, new_title_len={len(title)}"
216
+ )
217
+
218
+ body = {"id": task_list_id, "title": title}
219
+
220
+ result = await asyncio.to_thread(
221
+ service.tasklists().update(tasklist=task_list_id, body=body).execute
222
+ )
223
+
224
+ response = f"""Task List Updated for {user_google_email}:
225
+ - Title: {result["title"]}
226
+ - ID: {result["id"]}
227
+ - Updated: {result.get("updated", "N/A")}"""
228
+
229
+ logger.info(f"Updated task list {task_list_id} for {user_google_email}")
230
+ return response
231
+
232
+
233
+ async def _delete_task_list_impl(
234
+ service: Resource, user_google_email: str, task_list_id: str
235
+ ) -> str:
236
+ """Implementation for deleting a task list."""
237
+ logger.info(
238
+ f"[delete_task_list] Invoked. Email: '{user_google_email}', Task List ID: {task_list_id}"
239
+ )
240
+
241
+ await asyncio.to_thread(service.tasklists().delete(tasklist=task_list_id).execute)
242
+
243
+ response = f"Task list {task_list_id} has been deleted for {user_google_email}. All tasks in this list have also been deleted."
244
+
245
+ logger.info(f"Deleted task list {task_list_id} for {user_google_email}")
246
+ return response
247
+
248
+
249
+ async def _clear_completed_tasks_impl(
250
+ service: Resource, user_google_email: str, task_list_id: str
251
+ ) -> str:
252
+ """Implementation for clearing completed tasks from a task list."""
253
+ logger.info(
254
+ f"[clear_completed_tasks] Invoked. Email: '{user_google_email}', Task List ID: {task_list_id}"
255
+ )
256
+
257
+ await asyncio.to_thread(service.tasks().clear(tasklist=task_list_id).execute)
258
+
259
+ response = f"All completed tasks have been cleared from task list {task_list_id} for {user_google_email}. The tasks are now hidden and won't appear in default task list views."
260
+
261
+ logger.info(
262
+ f"Cleared completed tasks from list {task_list_id} for {user_google_email}"
263
+ )
264
+ return response
265
+
266
+
267
+ # --- Consolidated manage_task_list tool ---
268
+
269
+
270
+ @server.tool(
271
+ title="Manage Task List",
272
+ annotations=ToolAnnotations(
273
+ readOnlyHint=False,
274
+ destructiveHint=True,
275
+ idempotentHint=False,
276
+ openWorldHint=True,
277
+ ),
278
+ )
279
+ @require_google_service("tasks", "tasks") # type: ignore
280
+ @handle_http_errors("manage_task_list", service_type="tasks") # type: ignore
281
+ async def manage_task_list(
282
+ service: Resource,
283
+ user_google_email: str,
284
+ action: str,
285
+ task_list_id: Optional[str] = None,
286
+ title: Optional[str] = None,
287
+ ) -> str:
288
+ """
289
+ Manage task lists: create, update, delete, or clear completed tasks.
290
+
291
+ Args:
292
+ user_google_email (str): The user's Google email address. Required.
293
+ action (str): The action to perform. Must be one of: "create", "update", "delete", "clear_completed".
294
+ task_list_id (Optional[str]): The ID of the task list. Required for "update", "delete", and "clear_completed" actions.
295
+ title (Optional[str]): The title for the task list. Required for "create" and "update" actions.
296
+
297
+ Returns:
298
+ str: Result of the requested action.
299
+ """
300
+ logger.info(
301
+ f"[manage_task_list] Invoked. Email: '{user_google_email}', Action: '{action}'"
302
+ )
303
+
304
+ valid_actions = ("create", "update", "delete", "clear_completed")
305
+ if action not in valid_actions:
306
+ raise UserInputError(
307
+ f"Invalid action '{action}'. Must be one of: {', '.join(valid_actions)}"
308
+ )
309
+
310
+ if is_action_denied("tasks", action):
311
+ raise UserInputError(
312
+ f"The '{action}' action is not allowed under the current permission level."
313
+ )
314
+
315
+ if action == "create":
316
+ if not title:
317
+ raise UserInputError("'title' is required for the 'create' action.")
318
+ return await _create_task_list_impl(service, user_google_email, title)
319
+
320
+ if action == "update":
321
+ if not task_list_id:
322
+ raise UserInputError("'task_list_id' is required for the 'update' action.")
323
+ if not title:
324
+ raise UserInputError("'title' is required for the 'update' action.")
325
+ return await _update_task_list_impl(
326
+ service, user_google_email, task_list_id, title
327
+ )
328
+
329
+ if action == "delete":
330
+ if not task_list_id:
331
+ raise UserInputError("'task_list_id' is required for the 'delete' action.")
332
+ return await _delete_task_list_impl(service, user_google_email, task_list_id)
333
+
334
+ # action == "clear_completed"
335
+ if not task_list_id:
336
+ raise UserInputError(
337
+ "'task_list_id' is required for the 'clear_completed' action."
338
+ )
339
+ return await _clear_completed_tasks_impl(service, user_google_email, task_list_id)
340
+
341
+
342
+ # --- Task tools ---
343
+
344
+
345
+ @server.tool(
346
+ title="List Tasks",
347
+ annotations=ToolAnnotations(
348
+ readOnlyHint=True,
349
+ destructiveHint=False,
350
+ idempotentHint=True,
351
+ openWorldHint=True,
352
+ ),
353
+ )
354
+ @require_google_service("tasks", "tasks_read") # type: ignore
355
+ @handle_http_errors("list_tasks", service_type="tasks") # type: ignore
356
+ async def list_tasks(
357
+ service: Resource,
358
+ user_google_email: str,
359
+ task_list_id: str,
360
+ max_results: int = LIST_TASKS_MAX_RESULTS_DEFAULT,
361
+ page_token: Optional[str] = None,
362
+ show_completed: bool = True,
363
+ show_deleted: bool = False,
364
+ show_hidden: bool = False,
365
+ show_assigned: bool = False,
366
+ completed_max: Optional[str] = None,
367
+ completed_min: Optional[str] = None,
368
+ due_max: Optional[str] = None,
369
+ due_min: Optional[str] = None,
370
+ updated_min: Optional[str] = None,
371
+ ) -> str:
372
+ """
373
+ List all tasks in a specific task list.
374
+
375
+ Args:
376
+ user_google_email (str): The user's Google email address. Required.
377
+ task_list_id (str): The ID of the task list to retrieve tasks from.
378
+ max_results (int): Maximum number of tasks to return. (default: 20, max: 10000).
379
+ page_token (Optional[str]): Token for pagination.
380
+ show_completed (bool): Whether to include completed tasks (default: True). Note that show_hidden must also be true to show tasks completed in first party clients, such as the web UI and Google's mobile apps.
381
+ show_deleted (bool): Whether to include deleted tasks (default: False).
382
+ show_hidden (bool): Whether to include hidden tasks (default: False).
383
+ show_assigned (bool): Whether to include assigned tasks (default: False).
384
+ completed_max (Optional[str]): Upper bound for completion date (RFC 3339 timestamp).
385
+ completed_min (Optional[str]): Lower bound for completion date (RFC 3339 timestamp).
386
+ due_max (Optional[str]): Upper bound for due date (RFC 3339 timestamp).
387
+ due_min (Optional[str]): Lower bound for due date (RFC 3339 timestamp).
388
+ updated_min (Optional[str]): Lower bound for last modification time (RFC 3339 timestamp).
389
+
390
+ Returns:
391
+ str: List of tasks with their details.
392
+ """
393
+ logger.info(
394
+ f"[list_tasks] Invoked. Email: '{user_google_email}', Task List ID: {task_list_id}"
395
+ )
396
+
397
+ params: Dict[str, Any] = {"tasklist": task_list_id}
398
+ if max_results is not None:
399
+ params["maxResults"] = max_results
400
+ if page_token:
401
+ params["pageToken"] = page_token
402
+ if show_completed is not None:
403
+ params["showCompleted"] = show_completed
404
+ if show_deleted is not None:
405
+ params["showDeleted"] = show_deleted
406
+ if show_hidden is not None:
407
+ params["showHidden"] = show_hidden
408
+ if show_assigned is not None:
409
+ params["showAssigned"] = show_assigned
410
+ if completed_max:
411
+ params["completedMax"] = completed_max
412
+ if completed_min:
413
+ params["completedMin"] = completed_min
414
+ if due_max:
415
+ adjusted_due_max = _adjust_due_max_for_tasks_api(due_max)
416
+ if adjusted_due_max != due_max:
417
+ logger.info(
418
+ "[list_tasks] Adjusted due_max from '%s' to '%s' to include due date boundary",
419
+ due_max,
420
+ adjusted_due_max,
421
+ )
422
+ params["dueMax"] = adjusted_due_max
423
+ if due_min:
424
+ params["dueMin"] = due_min
425
+ if updated_min:
426
+ params["updatedMin"] = updated_min
427
+
428
+ result = await asyncio.to_thread(service.tasks().list(**params).execute)
429
+
430
+ tasks = result.get("items", [])
431
+ next_page_token = result.get("nextPageToken")
432
+
433
+ # In order to return a sorted and organized list of tasks all at once, we support retrieving more than a single
434
+ # page from the Google tasks API.
435
+ results_remaining = (
436
+ min(max_results, LIST_TASKS_MAX_RESULTS_MAX)
437
+ if max_results
438
+ else LIST_TASKS_MAX_RESULTS_DEFAULT
439
+ )
440
+ results_remaining -= len(tasks)
441
+ while results_remaining > 0 and next_page_token:
442
+ params["pageToken"] = next_page_token
443
+ params["maxResults"] = str(results_remaining)
444
+ result = await asyncio.to_thread(service.tasks().list(**params).execute)
445
+ more_tasks = result.get("items", [])
446
+ next_page_token = result.get("nextPageToken")
447
+ if len(more_tasks) == 0:
448
+ # For some unexpected reason, no more tasks were returned. Break to avoid an infinite loop.
449
+ break
450
+ tasks.extend(more_tasks)
451
+ results_remaining -= len(more_tasks)
452
+
453
+ if not tasks:
454
+ return f"No tasks found in task list {task_list_id} for {user_google_email}."
455
+
456
+ structured_tasks = get_structured_tasks(tasks)
457
+
458
+ response = f"Tasks in list {task_list_id} for {user_google_email}:\n"
459
+ response += serialize_tasks(structured_tasks, 0)
460
+
461
+ if next_page_token:
462
+ response += f"Next page token: {next_page_token}\n"
463
+
464
+ logger.info(
465
+ f"Found {len(tasks)} tasks in list {task_list_id} for {user_google_email}"
466
+ )
467
+ return response
468
+
469
+
470
+ def get_structured_tasks(tasks: List[Dict[str, str]]) -> List[StructuredTask]:
471
+ """
472
+ Convert a flat list of task dictionaries into StructuredTask objects based on parent-child relationships sorted by position.
473
+
474
+ Args:
475
+ tasks: List of task dictionaries.
476
+
477
+ Returns:
478
+ list: Sorted list of top-level StructuredTask objects with nested subtasks.
479
+ """
480
+ tasks_by_id = {
481
+ task["id"]: StructuredTask(task, is_placeholder_parent=False) for task in tasks
482
+ }
483
+ positions_by_id = {
484
+ task["id"]: int(task["position"]) for task in tasks if "position" in task
485
+ }
486
+
487
+ # Placeholder virtual root as parent for top-level tasks
488
+ root_task = StructuredTask(
489
+ {"id": "root", "title": "Root"}, is_placeholder_parent=False
490
+ )
491
+
492
+ for task in tasks:
493
+ structured_task = tasks_by_id[task["id"]]
494
+ parent_id = task.get("parent")
495
+ parent = None
496
+
497
+ if not parent_id:
498
+ # Task without parent: parent to the virtual root
499
+ parent = root_task
500
+ elif parent_id in tasks_by_id:
501
+ # Subtask: parent to its actual parent
502
+ parent = tasks_by_id[parent_id]
503
+ else:
504
+ # Orphaned subtask: create placeholder parent
505
+ # Due to paging or filtering, a subtask may have a parent that is not present in the list of tasks.
506
+ # We will create placeholder StructuredTask objects for these missing parents to maintain the hierarchy.
507
+ parent = StructuredTask({"id": parent_id}, is_placeholder_parent=True)
508
+ tasks_by_id[parent_id] = parent
509
+ root_task.add_subtask(parent)
510
+
511
+ parent.add_subtask(structured_task)
512
+
513
+ sort_structured_tasks(root_task, positions_by_id)
514
+ return root_task.subtasks
515
+
516
+
517
+ def sort_structured_tasks(
518
+ root_task: StructuredTask, positions_by_id: Dict[str, int]
519
+ ) -> None:
520
+ """
521
+ Recursively sort--in place--StructuredTask objects and their subtasks based on position.
522
+
523
+ Args:
524
+ root_task: The root StructuredTask object.
525
+ positions_by_id: Dictionary mapping task IDs to their positions.
526
+ """
527
+
528
+ def get_position(task: StructuredTask) -> int | float:
529
+ # Tasks without position go to the end (infinity)
530
+ result = positions_by_id.get(task.id, float("inf"))
531
+ return result
532
+
533
+ root_task.subtasks.sort(key=get_position)
534
+ for subtask in root_task.subtasks:
535
+ sort_structured_tasks(subtask, positions_by_id)
536
+
537
+
538
+ def serialize_tasks(structured_tasks: List[StructuredTask], subtask_level: int) -> str:
539
+ """
540
+ Serialize a list of StructuredTask objects into a formatted string with indentation for subtasks.
541
+ Args:
542
+ structured_tasks (list): List of StructuredTask objects.
543
+ subtask_level (int): Current level of indentation for subtasks.
544
+
545
+ Returns:
546
+ str: Formatted string representation of the tasks.
547
+ """
548
+ response = ""
549
+ placeholder_parent_count = 0
550
+ placeholder_parent_title = "Unknown parent"
551
+ for task in structured_tasks:
552
+ indent = " " * subtask_level
553
+ bullet = "-" if subtask_level == 0 else "*"
554
+ if task.title is not None:
555
+ title = task.title
556
+ elif task.is_placeholder_parent:
557
+ title = placeholder_parent_title
558
+ placeholder_parent_count += 1
559
+ else:
560
+ title = "Untitled"
561
+ response += f"{indent}{bullet} {title} (ID: {task.id})\n"
562
+ response += f"{indent} Status: {task.status or 'N/A'}\n"
563
+ response += f"{indent} Due: {task.due}\n" if task.due else ""
564
+ if task.notes:
565
+ response += f"{indent} Notes: {task.notes[:100]}{'...' if len(task.notes) > 100 else ''}\n"
566
+ response += f"{indent} Completed: {task.completed}\n" if task.completed else ""
567
+ response += f"{indent} Updated: {task.updated or 'N/A'}\n"
568
+ response += "\n"
569
+
570
+ response += serialize_tasks(task.subtasks, subtask_level + 1)
571
+
572
+ if placeholder_parent_count > 0:
573
+ # Placeholder parents should only appear at the top level
574
+ assert subtask_level == 0
575
+ response += f"""
576
+ {placeholder_parent_count} tasks with title {placeholder_parent_title} are included as placeholders.
577
+ These placeholders contain subtasks whose parents were not present in the task list.
578
+ This can occur due to pagination. Callers can often avoid this problem if max_results is large enough to contain all tasks (subtasks and their parents) without paging.
579
+ This can also occur due to filtering that excludes parent tasks while including their subtasks or due to deleted or hidden parent tasks.
580
+ """
581
+
582
+ return response
583
+
584
+
585
+ @server.tool(
586
+ title="Get Task",
587
+ annotations=ToolAnnotations(
588
+ readOnlyHint=True,
589
+ destructiveHint=False,
590
+ idempotentHint=True,
591
+ openWorldHint=True,
592
+ ),
593
+ )
594
+ @require_google_service("tasks", "tasks_read") # type: ignore
595
+ @handle_http_errors("get_task", service_type="tasks") # type: ignore
596
+ async def get_task(
597
+ service: Resource, user_google_email: str, task_list_id: str, task_id: str
598
+ ) -> str:
599
+ """
600
+ Get details of a specific task.
601
+
602
+ Args:
603
+ user_google_email (str): The user's Google email address. Required.
604
+ task_list_id (str): The ID of the task list containing the task.
605
+ task_id (str): The ID of the task to retrieve.
606
+
607
+ Returns:
608
+ str: Task details including title, notes, status, due date, etc.
609
+ """
610
+ logger.info(
611
+ f"[get_task] Invoked. Email: '{user_google_email}', Task List ID: {task_list_id}, Task ID: {task_id}"
612
+ )
613
+
614
+ task = await asyncio.to_thread(
615
+ service.tasks().get(tasklist=task_list_id, task=task_id).execute
616
+ )
617
+
618
+ response = f"""Task Details for {user_google_email}:
619
+ - Title: {task.get("title", "Untitled")}
620
+ - ID: {task["id"]}
621
+ - Status: {task.get("status", "N/A")}
622
+ - Updated: {task.get("updated", "N/A")}"""
623
+
624
+ if task.get("due"):
625
+ response += f"\n- Due Date: {task['due']}"
626
+ if task.get("completed"):
627
+ response += f"\n- Completed: {task['completed']}"
628
+ if task.get("notes"):
629
+ response += f"\n- Notes: {task['notes']}"
630
+ if task.get("parent"):
631
+ response += f"\n- Parent Task ID: {task['parent']}"
632
+ if task.get("position"):
633
+ response += f"\n- Position: {task['position']}"
634
+ if task.get("selfLink"):
635
+ response += f"\n- Self Link: {task['selfLink']}"
636
+ if task.get("webViewLink"):
637
+ response += f"\n- Web View Link: {task['webViewLink']}"
638
+
639
+ logger.info(f"Retrieved task {task_id} for {user_google_email}")
640
+ return response
641
+
642
+
643
+ # --- Task _impl functions ---
644
+
645
+
646
+ async def _create_task_impl(
647
+ service: Resource,
648
+ user_google_email: str,
649
+ task_list_id: str,
650
+ title: str,
651
+ notes: Optional[str] = None,
652
+ due: Optional[str] = None,
653
+ parent: Optional[str] = None,
654
+ previous: Optional[str] = None,
655
+ ) -> str:
656
+ """Implementation for creating a new task in a task list."""
657
+ logger.info(
658
+ f"[create_task] Invoked. Email: '{user_google_email}', Task List ID: {task_list_id}, title_len={len(title)}"
659
+ )
660
+
661
+ body = {"title": title}
662
+ if notes:
663
+ body["notes"] = notes
664
+ if due:
665
+ body["due"] = due
666
+
667
+ params = {"tasklist": task_list_id, "body": body}
668
+ if parent:
669
+ params["parent"] = parent
670
+ if previous:
671
+ params["previous"] = previous
672
+
673
+ result = await asyncio.to_thread(service.tasks().insert(**params).execute)
674
+
675
+ response = f"""Task Created for {user_google_email}:
676
+ - Title: {result["title"]}
677
+ - ID: {result["id"]}
678
+ - Status: {result.get("status", "N/A")}
679
+ - Updated: {result.get("updated", "N/A")}"""
680
+
681
+ if result.get("due"):
682
+ response += f"\n- Due Date: {result['due']}"
683
+ if result.get("notes"):
684
+ response += f"\n- Notes: {result['notes']}"
685
+ if result.get("webViewLink"):
686
+ response += f"\n- Web View Link: {result['webViewLink']}"
687
+
688
+ logger.info(f"Created task with ID {result['id']} for {user_google_email}")
689
+ return response
690
+
691
+
692
+ async def _update_task_impl(
693
+ service: Resource,
694
+ user_google_email: str,
695
+ task_list_id: str,
696
+ task_id: str,
697
+ title: Optional[str] = None,
698
+ notes: Optional[str] = None,
699
+ status: Optional[str] = None,
700
+ due: Optional[str] = None,
701
+ ) -> str:
702
+ """Implementation for updating an existing task."""
703
+ logger.info(
704
+ f"[update_task] Invoked. Email: '{user_google_email}', Task List ID: {task_list_id}, Task ID: {task_id}"
705
+ )
706
+
707
+ # First get the current task to build the update body
708
+ current_task = await asyncio.to_thread(
709
+ service.tasks().get(tasklist=task_list_id, task=task_id).execute
710
+ )
711
+
712
+ body = {
713
+ "id": task_id,
714
+ "title": title if title is not None else current_task.get("title", ""),
715
+ "status": status
716
+ if status is not None
717
+ else current_task.get("status", "needsAction"),
718
+ }
719
+
720
+ if notes is not None:
721
+ body["notes"] = notes
722
+ elif current_task.get("notes"):
723
+ body["notes"] = current_task["notes"]
724
+
725
+ if due is not None:
726
+ body["due"] = due
727
+ elif current_task.get("due"):
728
+ body["due"] = current_task["due"]
729
+
730
+ result = await asyncio.to_thread(
731
+ service.tasks().update(tasklist=task_list_id, task=task_id, body=body).execute
732
+ )
733
+
734
+ response = f"""Task Updated for {user_google_email}:
735
+ - Title: {result["title"]}
736
+ - ID: {result["id"]}
737
+ - Status: {result.get("status", "N/A")}
738
+ - Updated: {result.get("updated", "N/A")}"""
739
+
740
+ if result.get("due"):
741
+ response += f"\n- Due Date: {result['due']}"
742
+ if result.get("notes"):
743
+ response += f"\n- Notes: {result['notes']}"
744
+ if result.get("completed"):
745
+ response += f"\n- Completed: {result['completed']}"
746
+
747
+ logger.info(f"Updated task {task_id} for {user_google_email}")
748
+ return response
749
+
750
+
751
+ async def _delete_task_impl(
752
+ service: Resource, user_google_email: str, task_list_id: str, task_id: str
753
+ ) -> str:
754
+ """Implementation for deleting a task from a task list."""
755
+ logger.info(
756
+ f"[delete_task] Invoked. Email: '{user_google_email}', Task List ID: {task_list_id}, Task ID: {task_id}"
757
+ )
758
+
759
+ await asyncio.to_thread(
760
+ service.tasks().delete(tasklist=task_list_id, task=task_id).execute
761
+ )
762
+
763
+ response = f"Task {task_id} has been deleted from task list {task_list_id} for {user_google_email}."
764
+
765
+ logger.info(f"Deleted task {task_id} for {user_google_email}")
766
+ return response
767
+
768
+
769
+ async def _move_task_impl(
770
+ service: Resource,
771
+ user_google_email: str,
772
+ task_list_id: str,
773
+ task_id: str,
774
+ parent: Optional[str] = None,
775
+ previous: Optional[str] = None,
776
+ destination_task_list: Optional[str] = None,
777
+ ) -> str:
778
+ """Implementation for moving a task to a different position, parent, or list."""
779
+ logger.info(
780
+ f"[move_task] Invoked. Email: '{user_google_email}', Task List ID: {task_list_id}, Task ID: {task_id}"
781
+ )
782
+
783
+ params = {"tasklist": task_list_id, "task": task_id}
784
+ if parent:
785
+ params["parent"] = parent
786
+ if previous:
787
+ params["previous"] = previous
788
+ if destination_task_list:
789
+ params["destinationTasklist"] = destination_task_list
790
+
791
+ result = await asyncio.to_thread(service.tasks().move(**params).execute)
792
+
793
+ response = f"""Task Moved for {user_google_email}:
794
+ - Title: {result["title"]}
795
+ - ID: {result["id"]}
796
+ - Status: {result.get("status", "N/A")}
797
+ - Updated: {result.get("updated", "N/A")}"""
798
+
799
+ if result.get("parent"):
800
+ response += f"\n- Parent Task ID: {result['parent']}"
801
+ if result.get("position"):
802
+ response += f"\n- Position: {result['position']}"
803
+
804
+ move_details = []
805
+ if destination_task_list:
806
+ move_details.append(f"moved to task list {destination_task_list}")
807
+ if parent:
808
+ move_details.append(f"made a subtask of {parent}")
809
+ if previous:
810
+ move_details.append(f"positioned after {previous}")
811
+
812
+ if move_details:
813
+ response += f"\n- Move Details: {', '.join(move_details)}"
814
+
815
+ logger.info(f"Moved task {task_id} for {user_google_email}")
816
+ return response
817
+
818
+
819
+ # --- Consolidated manage_task tool ---
820
+
821
+
822
+ @server.tool(
823
+ title="Manage Task",
824
+ annotations=ToolAnnotations(
825
+ readOnlyHint=False,
826
+ destructiveHint=True,
827
+ idempotentHint=False,
828
+ openWorldHint=True,
829
+ ),
830
+ )
831
+ @require_google_service("tasks", "tasks") # type: ignore
832
+ @handle_http_errors("manage_task", service_type="tasks") # type: ignore
833
+ async def manage_task(
834
+ service: Resource,
835
+ user_google_email: str,
836
+ action: str,
837
+ task_list_id: str,
838
+ task_id: Optional[str] = None,
839
+ title: Optional[str] = None,
840
+ notes: Optional[str] = None,
841
+ status: Optional[str] = None,
842
+ due: Optional[str] = None,
843
+ parent: Optional[str] = None,
844
+ previous: Optional[str] = None,
845
+ destination_task_list: Optional[str] = None,
846
+ ) -> str:
847
+ """
848
+ Manage tasks: create, update, delete, or move tasks within task lists.
849
+
850
+ Args:
851
+ user_google_email (str): The user's Google email address. Required.
852
+ action (str): The action to perform. Must be one of: "create", "update", "delete", "move".
853
+ task_list_id (str): The ID of the task list. Required for all actions.
854
+ task_id (Optional[str]): The ID of the task. Required for "update", "delete", and "move" actions.
855
+ title (Optional[str]): The title of the task. Required for "create", optional for "update".
856
+ notes (Optional[str]): Notes/description for the task. Used by "create" and "update" actions.
857
+ status (Optional[str]): Task status ("needsAction" or "completed"). Used by "update" action.
858
+ due (Optional[str]): Due date in RFC 3339 format (e.g., "2024-12-31T23:59:59Z"). Used by "create" and "update" actions.
859
+ parent (Optional[str]): Parent task ID (for subtasks). Used by "create" and "move" actions.
860
+ previous (Optional[str]): Previous sibling task ID (for positioning). Used by "create" and "move" actions.
861
+ destination_task_list (Optional[str]): Destination task list ID (for moving between lists). Used by "move" action.
862
+
863
+ Returns:
864
+ str: Result of the requested action.
865
+ """
866
+ logger.info(
867
+ f"[manage_task] Invoked. Email: '{user_google_email}', Action: '{action}', Task List ID: {task_list_id}"
868
+ )
869
+
870
+ allowed_statuses = {"needsAction", "completed"}
871
+ if status is not None and status not in allowed_statuses:
872
+ raise UserInputError("invalid status: must be 'needsAction' or 'completed'")
873
+
874
+ if due is not None:
875
+ _validate_rfc3339_date(due)
876
+
877
+ valid_actions = ("create", "update", "delete", "move")
878
+ if action not in valid_actions:
879
+ raise UserInputError(
880
+ f"Invalid action '{action}'. Must be one of: {', '.join(valid_actions)}"
881
+ )
882
+
883
+ if is_action_denied("tasks", action):
884
+ raise UserInputError(
885
+ f"The '{action}' action is not allowed under the current permission level."
886
+ )
887
+
888
+ if action == "create":
889
+ if status is not None:
890
+ raise UserInputError("'status' is only supported for the 'update' action.")
891
+ if not title:
892
+ raise UserInputError("'title' is required for the 'create' action.")
893
+ return await _create_task_impl(
894
+ service,
895
+ user_google_email,
896
+ task_list_id,
897
+ title,
898
+ notes=notes,
899
+ due=due,
900
+ parent=parent,
901
+ previous=previous,
902
+ )
903
+
904
+ if action == "update":
905
+ if not task_id:
906
+ raise UserInputError("'task_id' is required for the 'update' action.")
907
+ return await _update_task_impl(
908
+ service,
909
+ user_google_email,
910
+ task_list_id,
911
+ task_id,
912
+ title=title,
913
+ notes=notes,
914
+ status=status,
915
+ due=due,
916
+ )
917
+
918
+ if action == "delete":
919
+ if not task_id:
920
+ raise UserInputError("'task_id' is required for the 'delete' action.")
921
+ return await _delete_task_impl(
922
+ service, user_google_email, task_list_id, task_id
923
+ )
924
+
925
+ # action == "move"
926
+ if not task_id:
927
+ raise UserInputError("'task_id' is required for the 'move' action.")
928
+ return await _move_task_impl(
929
+ service,
930
+ user_google_email,
931
+ task_list_id,
932
+ task_id,
933
+ parent=parent,
934
+ previous=previous,
935
+ destination_task_list=destination_task_list,
936
+ )