mcp-google-tasks 0.2.0__py3-none-any.whl

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.
@@ -0,0 +1,3 @@
1
+ """Google Tasks MCP server for Obot: multi-user OAuth or single-user tokens."""
2
+
3
+ __version__ = "0.2.0"
@@ -0,0 +1,6 @@
1
+ """Allow ``python -m mcp_google_tasks``."""
2
+
3
+ from mcp_google_tasks.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
@@ -0,0 +1,567 @@
1
+ """The seam between the MCP tools and the Google Tasks REST API v1.
2
+
3
+ Tools depend only on the ``TasksApi`` protocol. ``GoogleTasksClient`` is the
4
+ real adapter: it takes a shared ``httpx.AsyncClient`` and a
5
+ ``CredentialSource`` and knows nothing about transports or auth modes, so
6
+ tests drive it with ``httpx.MockTransport`` and a fake credential source.
7
+ """
8
+
9
+ import unicodedata
10
+ from collections.abc import Mapping
11
+ from typing import Literal, Protocol
12
+ from urllib.parse import quote
13
+
14
+ import httpx
15
+ import structlog
16
+ from pydantic import BaseModel, ValidationError
17
+
18
+ from mcp_google_tasks.credentials import CredentialSource
19
+ from mcp_google_tasks.errors import ApiError, ConnectivityError, InvalidArgumentError
20
+ from mcp_google_tasks.models import (
21
+ CurrentUserInfo,
22
+ Task,
23
+ TaskList,
24
+ TaskListsResponse,
25
+ TasksResponse,
26
+ )
27
+
28
+ GOOGLE_TASKS_API_BASE = "https://tasks.googleapis.com/tasks/v1"
29
+ GOOGLE_USERINFO_ENDPOINT = "https://www.googleapis.com/oauth2/v3/userinfo"
30
+ REQUEST_TIMEOUT = httpx.Timeout(30.0, connect=10.0)
31
+
32
+ # Resources read every page; these bound the work one read can cause.
33
+ PAGE_SIZE = 100
34
+ MAX_PAGES = 50
35
+
36
+ # Identifiers Google defines as aliases, passed through unencoded.
37
+ _ALIASES = frozenset({"@default", "@me"})
38
+
39
+ type HttpMethod = Literal["GET", "POST", "PUT", "PATCH", "DELETE"]
40
+ type QueryParamValue = str | int | bool
41
+ type QueryParams = Mapping[str, QueryParamValue]
42
+ type RequestBody = dict[str, str | bool | None]
43
+
44
+ log = structlog.get_logger(__name__)
45
+
46
+
47
+ class TasksApi(Protocol):
48
+ """One async method per Google Tasks endpoint the tools use."""
49
+
50
+ async def list_tasklists(
51
+ self, *, max_results: int | None = None, page_token: str | None = None
52
+ ) -> TaskListsResponse:
53
+ """List the user's task lists (tasklists.list)."""
54
+ ...
55
+
56
+ async def get_tasklist(self, tasklist_id: str) -> TaskList:
57
+ """Get one task list (tasklists.get)."""
58
+ ...
59
+
60
+ async def insert_tasklist(self, title: str) -> TaskList:
61
+ """Create a task list (tasklists.insert)."""
62
+ ...
63
+
64
+ async def update_tasklist(self, tasklist_id: str, title: str) -> TaskList:
65
+ """Replace a task list (tasklists.update)."""
66
+ ...
67
+
68
+ async def patch_tasklist(self, tasklist_id: str, title: str) -> TaskList:
69
+ """Partially update a task list (tasklists.patch)."""
70
+ ...
71
+
72
+ async def delete_tasklist(self, tasklist_id: str) -> None:
73
+ """Delete a task list (tasklists.delete)."""
74
+ ...
75
+
76
+ async def list_tasks(
77
+ self, tasklist_id: str, *, query: QueryParams | None = None
78
+ ) -> TasksResponse:
79
+ """List tasks in a list (tasks.list)."""
80
+ ...
81
+
82
+ async def get_task(self, tasklist_id: str, task_id: str) -> Task:
83
+ """Get one task (tasks.get)."""
84
+ ...
85
+
86
+ async def insert_task(
87
+ self,
88
+ tasklist_id: str,
89
+ body: RequestBody,
90
+ *,
91
+ parent: str | None = None,
92
+ previous: str | None = None,
93
+ ) -> Task:
94
+ """Create a task (tasks.insert)."""
95
+ ...
96
+
97
+ async def update_task(self, tasklist_id: str, task_id: str, body: RequestBody) -> Task:
98
+ """Replace a task (tasks.update)."""
99
+ ...
100
+
101
+ async def patch_task(self, tasklist_id: str, task_id: str, body: RequestBody) -> Task:
102
+ """Partially update a task (tasks.patch)."""
103
+ ...
104
+
105
+ async def delete_task(self, tasklist_id: str, task_id: str) -> None:
106
+ """Delete a task (tasks.delete)."""
107
+ ...
108
+
109
+ async def move_task(
110
+ self,
111
+ tasklist_id: str,
112
+ task_id: str,
113
+ *,
114
+ parent: str | None = None,
115
+ previous: str | None = None,
116
+ destination_tasklist: str | None = None,
117
+ ) -> Task:
118
+ """Move or reparent a task (tasks.move)."""
119
+ ...
120
+
121
+ async def clear_tasks(self, tasklist_id: str) -> None:
122
+ """Hide all completed tasks in a list (tasks.clear)."""
123
+ ...
124
+
125
+ async def get_userinfo(self) -> CurrentUserInfo:
126
+ """Get the token owner's profile from the OpenID userinfo endpoint."""
127
+ ...
128
+
129
+
130
+ def encode_segment(value: str, what: str = "identifier") -> str:
131
+ """Validate and percent-encode one URL path segment.
132
+
133
+ Args:
134
+ value: The identifier to place in the path.
135
+ what: Name of the argument, for the error message.
136
+
137
+ Returns:
138
+ The encoded segment. ``@default`` and ``@me`` pass through unchanged;
139
+ everything else is encoded with no safe characters, so ``/``, ``?``
140
+ and ``#`` cannot change the request path.
141
+
142
+ Raises:
143
+ InvalidArgumentError: The value is empty, ``.``/``..``, or holds control characters.
144
+ """
145
+ if value in _ALIASES:
146
+ return quote(value, safe="@")
147
+ if not value or value.strip() == "":
148
+ msg = f"{what} must not be empty."
149
+ raise InvalidArgumentError(msg)
150
+ if value in {".", ".."}:
151
+ msg = f"{what} must not be {value!r}."
152
+ raise InvalidArgumentError(msg)
153
+ if any(unicodedata.category(ch) == "Cc" for ch in value):
154
+ msg = f"{what} must not contain control characters."
155
+ raise InvalidArgumentError(msg)
156
+ return quote(value, safe="")
157
+
158
+
159
+ def _clean_params(params: QueryParams | None) -> dict[str, str] | None:
160
+ """Render query values as Google expects (booleans as ``true``/``false``)."""
161
+ if not params:
162
+ return None
163
+ return {
164
+ key: ("true" if value else "false") if isinstance(value, bool) else str(value)
165
+ for key, value in params.items()
166
+ }
167
+
168
+
169
+ def extract_google_error(response: httpx.Response) -> tuple[str, str | None]:
170
+ """Extract a readable message and status string from a Google API error.
171
+
172
+ Args:
173
+ response: The error response.
174
+
175
+ Returns:
176
+ ``(message, api_status)``; ``api_status`` is None when Google gave none.
177
+ """
178
+ try:
179
+ payload = response.json()
180
+ except ValueError:
181
+ text = response.text.strip()
182
+ return (text or response.reason_phrase or "Unknown error", None)
183
+
184
+ if isinstance(payload, dict):
185
+ err = payload.get("error")
186
+ if isinstance(err, dict):
187
+ message = str(err.get("message") or response.reason_phrase)
188
+ status = err.get("status")
189
+ return (message, str(status) if status is not None else None)
190
+ if isinstance(err, str):
191
+ return (err, None)
192
+ return (response.text.strip() or response.reason_phrase, None)
193
+
194
+
195
+ def _parse[M: BaseModel](model: type[M], response: httpx.Response) -> M:
196
+ """Validate a JSON body into ``model``, mapping surprises to ``ApiError``."""
197
+ try:
198
+ return model.model_validate(response.json())
199
+ except (ValueError, ValidationError) as exc:
200
+ msg = f"Unexpected response body from Google ({model.__name__} expected)."
201
+ raise ApiError(response.status_code, msg) from exc
202
+
203
+
204
+ class GoogleTasksClient:
205
+ """``TasksApi`` over HTTPS with httpx."""
206
+
207
+ def __init__(
208
+ self,
209
+ http: httpx.AsyncClient,
210
+ credentials: CredentialSource,
211
+ *,
212
+ base_url: str = GOOGLE_TASKS_API_BASE,
213
+ ) -> None:
214
+ """Create the adapter.
215
+
216
+ Args:
217
+ http: Shared, pooled client; it carries no credentials of its own.
218
+ credentials: Supplies the bearer token for each request.
219
+ base_url: Root of the Tasks API, replaceable in tests.
220
+ """
221
+ self._http = http
222
+ self._credentials = credentials
223
+ self._base_url = base_url.rstrip("/")
224
+
225
+ async def _request(
226
+ self,
227
+ method: HttpMethod,
228
+ url: str,
229
+ *,
230
+ params: QueryParams | None = None,
231
+ json_body: RequestBody | None = None,
232
+ ) -> httpx.Response:
233
+ """Send an authenticated request; on 401, refresh once and retry.
234
+
235
+ Raises:
236
+ ConnectivityError: Google could not be reached.
237
+ ApiError: Google answered with a non-success status.
238
+ """
239
+ clean = _clean_params(params)
240
+ refreshed = False
241
+ while True:
242
+ token = await self._credentials.bearer_token()
243
+ try:
244
+ response = await self._http.request(
245
+ method,
246
+ url,
247
+ params=clean,
248
+ json=json_body,
249
+ headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},
250
+ timeout=REQUEST_TIMEOUT,
251
+ )
252
+ except httpx.HTTPError as exc:
253
+ msg = (
254
+ f"Could not reach Google ({exc.__class__.__name__}). "
255
+ "Check network connectivity and try again."
256
+ )
257
+ raise ConnectivityError(msg) from exc
258
+ log.debug("google_response", method=method, status=response.status_code)
259
+ if (
260
+ response.status_code == httpx.codes.UNAUTHORIZED
261
+ and not refreshed
262
+ and await self._credentials.refresh()
263
+ ):
264
+ refreshed = True
265
+ continue
266
+ if response.is_error:
267
+ message, api_status = extract_google_error(response)
268
+ raise ApiError(response.status_code, message, api_status)
269
+ return response
270
+
271
+ def _url(self, *segments: str) -> str:
272
+ """Join pre-encoded segments onto the Tasks API root."""
273
+ return "/".join((self._base_url, *segments))
274
+
275
+ @staticmethod
276
+ def _list(tasklist_id: str) -> str:
277
+ return encode_segment(tasklist_id, "tasklist_id")
278
+
279
+ @staticmethod
280
+ def _task(task_id: str) -> str:
281
+ return encode_segment(task_id, "task_id")
282
+
283
+ async def list_tasklists(
284
+ self, *, max_results: int | None = None, page_token: str | None = None
285
+ ) -> TaskListsResponse:
286
+ """List the user's task lists (tasklists.list).
287
+
288
+ Args:
289
+ max_results: Page size (1-100).
290
+ page_token: Token from a previous page.
291
+
292
+ Returns:
293
+ One page of task lists.
294
+ """
295
+ params: dict[str, QueryParamValue] = {}
296
+ if max_results is not None:
297
+ params["maxResults"] = max_results
298
+ if page_token is not None:
299
+ params["pageToken"] = page_token
300
+ response = await self._request("GET", self._url("users", "@me", "lists"), params=params)
301
+ return _parse(TaskListsResponse, response)
302
+
303
+ async def get_tasklist(self, tasklist_id: str) -> TaskList:
304
+ """Get one task list (tasklists.get).
305
+
306
+ Args:
307
+ tasklist_id: Task list ID or ``@default``.
308
+
309
+ Returns:
310
+ The task list.
311
+ """
312
+ url = self._url("users", "@me", "lists", self._list(tasklist_id))
313
+ return _parse(TaskList, await self._request("GET", url))
314
+
315
+ async def insert_tasklist(self, title: str) -> TaskList:
316
+ """Create a task list (tasklists.insert).
317
+
318
+ Args:
319
+ title: Title of the new list.
320
+
321
+ Returns:
322
+ The created task list.
323
+ """
324
+ url = self._url("users", "@me", "lists")
325
+ return _parse(TaskList, await self._request("POST", url, json_body={"title": title}))
326
+
327
+ async def update_tasklist(self, tasklist_id: str, title: str) -> TaskList:
328
+ """Replace a task list (tasklists.update).
329
+
330
+ Args:
331
+ tasklist_id: Task list ID or ``@default``.
332
+ title: New title.
333
+
334
+ Returns:
335
+ The updated task list.
336
+ """
337
+ url = self._url("users", "@me", "lists", self._list(tasklist_id))
338
+ body: RequestBody = {"id": tasklist_id, "title": title}
339
+ return _parse(TaskList, await self._request("PUT", url, json_body=body))
340
+
341
+ async def patch_tasklist(self, tasklist_id: str, title: str) -> TaskList:
342
+ """Partially update a task list (tasklists.patch).
343
+
344
+ Args:
345
+ tasklist_id: Task list ID or ``@default``.
346
+ title: New title.
347
+
348
+ Returns:
349
+ The updated task list.
350
+ """
351
+ url = self._url("users", "@me", "lists", self._list(tasklist_id))
352
+ return _parse(TaskList, await self._request("PATCH", url, json_body={"title": title}))
353
+
354
+ async def delete_tasklist(self, tasklist_id: str) -> None:
355
+ """Delete a task list and all of its tasks (tasklists.delete).
356
+
357
+ Args:
358
+ tasklist_id: Task list ID.
359
+ """
360
+ await self._request("DELETE", self._url("users", "@me", "lists", self._list(tasklist_id)))
361
+
362
+ async def list_tasks(
363
+ self, tasklist_id: str, *, query: QueryParams | None = None
364
+ ) -> TasksResponse:
365
+ """List tasks in a list (tasks.list).
366
+
367
+ Args:
368
+ tasklist_id: Task list ID or ``@default``.
369
+ query: Google query parameters (camelCase names), already validated.
370
+
371
+ Returns:
372
+ One page of tasks.
373
+ """
374
+ url = self._url("lists", self._list(tasklist_id), "tasks")
375
+ return _parse(TasksResponse, await self._request("GET", url, params=query))
376
+
377
+ async def get_task(self, tasklist_id: str, task_id: str) -> Task:
378
+ """Get one task (tasks.get).
379
+
380
+ Args:
381
+ tasklist_id: Task list ID or ``@default``.
382
+ task_id: Task ID.
383
+
384
+ Returns:
385
+ The task.
386
+ """
387
+ url = self._url("lists", self._list(tasklist_id), "tasks", self._task(task_id))
388
+ return _parse(Task, await self._request("GET", url))
389
+
390
+ async def insert_task(
391
+ self,
392
+ tasklist_id: str,
393
+ body: RequestBody,
394
+ *,
395
+ parent: str | None = None,
396
+ previous: str | None = None,
397
+ ) -> Task:
398
+ """Create a task (tasks.insert).
399
+
400
+ Args:
401
+ tasklist_id: Task list ID or ``@default``.
402
+ body: Task fields (camelCase names).
403
+ parent: Parent task ID, to create a subtask.
404
+ previous: Sibling task ID to insert after.
405
+
406
+ Returns:
407
+ The created task.
408
+ """
409
+ params: dict[str, QueryParamValue] = {}
410
+ if parent is not None:
411
+ params["parent"] = parent
412
+ if previous is not None:
413
+ params["previous"] = previous
414
+ url = self._url("lists", self._list(tasklist_id), "tasks")
415
+ return _parse(Task, await self._request("POST", url, params=params, json_body=body))
416
+
417
+ async def update_task(self, tasklist_id: str, task_id: str, body: RequestBody) -> Task:
418
+ """Replace a task (tasks.update).
419
+
420
+ Args:
421
+ tasklist_id: Task list ID or ``@default``.
422
+ task_id: Task ID.
423
+ body: Full task body (camelCase names).
424
+
425
+ Returns:
426
+ The updated task.
427
+ """
428
+ url = self._url("lists", self._list(tasklist_id), "tasks", self._task(task_id))
429
+ return _parse(Task, await self._request("PUT", url, json_body=body))
430
+
431
+ async def patch_task(self, tasklist_id: str, task_id: str, body: RequestBody) -> Task:
432
+ """Partially update a task (tasks.patch).
433
+
434
+ Args:
435
+ tasklist_id: Task list ID or ``@default``.
436
+ task_id: Task ID.
437
+ body: Fields to change (camelCase names); ``None`` clears a field.
438
+
439
+ Returns:
440
+ The updated task.
441
+ """
442
+ url = self._url("lists", self._list(tasklist_id), "tasks", self._task(task_id))
443
+ return _parse(Task, await self._request("PATCH", url, json_body=body))
444
+
445
+ async def delete_task(self, tasklist_id: str, task_id: str) -> None:
446
+ """Delete a task (tasks.delete).
447
+
448
+ Args:
449
+ tasklist_id: Task list ID or ``@default``.
450
+ task_id: Task ID.
451
+ """
452
+ url = self._url("lists", self._list(tasklist_id), "tasks", self._task(task_id))
453
+ await self._request("DELETE", url)
454
+
455
+ async def move_task(
456
+ self,
457
+ tasklist_id: str,
458
+ task_id: str,
459
+ *,
460
+ parent: str | None = None,
461
+ previous: str | None = None,
462
+ destination_tasklist: str | None = None,
463
+ ) -> Task:
464
+ """Move or reparent a task (tasks.move).
465
+
466
+ Args:
467
+ tasklist_id: Source task list ID or ``@default``.
468
+ task_id: Task ID.
469
+ parent: New parent task ID.
470
+ previous: New previous sibling task ID.
471
+ destination_tasklist: Destination list ID, to move across lists.
472
+
473
+ Returns:
474
+ The moved task.
475
+ """
476
+ params: dict[str, QueryParamValue] = {}
477
+ if parent is not None:
478
+ params["parent"] = parent
479
+ if previous is not None:
480
+ params["previous"] = previous
481
+ if destination_tasklist is not None:
482
+ params["destinationTasklist"] = destination_tasklist
483
+ url = self._url("lists", self._list(tasklist_id), "tasks", self._task(task_id), "move")
484
+ return _parse(Task, await self._request("POST", url, params=params))
485
+
486
+ async def clear_tasks(self, tasklist_id: str) -> None:
487
+ """Hide all completed tasks in a list (tasks.clear).
488
+
489
+ Args:
490
+ tasklist_id: Task list ID or ``@default``.
491
+ """
492
+ await self._request("POST", self._url("lists", self._list(tasklist_id), "clear"))
493
+
494
+ async def get_userinfo(self) -> CurrentUserInfo:
495
+ """Get the token owner's profile from the OpenID userinfo endpoint.
496
+
497
+ Returns:
498
+ The user's ``sub``, ``email`` and ``name``; ``scopes`` is empty
499
+ because userinfo does not report them.
500
+ """
501
+ response = await self._request("GET", GOOGLE_USERINFO_ENDPOINT)
502
+ try:
503
+ data = response.json()
504
+ except ValueError as exc:
505
+ msg = "Unexpected response body from Google userinfo."
506
+ raise ApiError(response.status_code, msg) from exc
507
+ if not isinstance(data, dict):
508
+ msg = "Unexpected response body from Google userinfo."
509
+ raise ApiError(response.status_code, msg)
510
+ return CurrentUserInfo(
511
+ sub=_opt_str(data.get("sub")),
512
+ email=_opt_str(data.get("email")),
513
+ name=_opt_str(data.get("name")),
514
+ scopes=[],
515
+ )
516
+
517
+
518
+ def _opt_str(value: object) -> str | None:
519
+ """Stringify a claim, keeping None as None."""
520
+ return str(value) if value is not None else None
521
+
522
+
523
+ async def fetch_all_tasklists(api: TasksApi) -> TaskListsResponse:
524
+ """Read every page of task lists, up to ``MAX_PAGES`` pages.
525
+
526
+ Args:
527
+ api: The Tasks API.
528
+
529
+ Returns:
530
+ All task lists. If the cap was hit, ``next_page_token`` holds the token
531
+ for the remaining pages so the truncation is visible.
532
+ """
533
+ first = await api.list_tasklists(max_results=PAGE_SIZE)
534
+ items = list(first.items)
535
+ token = first.next_page_token
536
+ pages = 1
537
+ while token and pages < MAX_PAGES:
538
+ page = await api.list_tasklists(max_results=PAGE_SIZE, page_token=token)
539
+ items.extend(page.items)
540
+ token = page.next_page_token
541
+ pages += 1
542
+ return first.model_copy(update={"items": items, "next_page_token": token})
543
+
544
+
545
+ async def fetch_all_tasks(api: TasksApi, tasklist_id: str) -> TasksResponse:
546
+ """Read every page of tasks in a list, up to ``MAX_PAGES`` pages.
547
+
548
+ Args:
549
+ api: The Tasks API.
550
+ tasklist_id: Task list ID or ``@default``.
551
+
552
+ Returns:
553
+ All tasks with Google's default filters. If the cap was hit,
554
+ ``next_page_token`` holds the token for the remaining pages.
555
+ """
556
+ first = await api.list_tasks(tasklist_id, query={"maxResults": PAGE_SIZE})
557
+ items = list(first.items)
558
+ token = first.next_page_token
559
+ pages = 1
560
+ while token and pages < MAX_PAGES:
561
+ page = await api.list_tasks(
562
+ tasklist_id, query={"maxResults": PAGE_SIZE, "pageToken": token}
563
+ )
564
+ items.extend(page.items)
565
+ token = page.next_page_token
566
+ pages += 1
567
+ return first.model_copy(update={"items": items, "next_page_token": token})