@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
File without changes
@@ -0,0 +1,390 @@
1
+ """
2
+ Google Slides digests: the plain-text views ``get_presentation`` returns for
3
+ the ``deck``, ``layouts`` and ``page`` actions.
4
+
5
+ ``deck`` lists slides with their titles, layouts and element counts, paged by
6
+ slide. ``page`` lists every element on one slide with its ID and all its text,
7
+ and no presentation detail. ``layouts`` lists a deck's layouts and the
8
+ placeholders each provides.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
14
+
15
+ from gslides.slides_markup import element_kind, iter_elements, placeholder_key
16
+
17
+ EMU_PER_PT = 12700
18
+ LAYOUT_CAP = 25
19
+ DECK_PAGE_SLIDES = 100
20
+ _TITLE_TYPES = ("TITLE", "CENTERED_TITLE")
21
+ _BODY_TYPES = ("SUBTITLE", "BODY")
22
+
23
+
24
+ def _paragraphs(text: Optional[Dict[str, Any]]) -> List[Tuple[Optional[int], str]]:
25
+ """(bullet level or None, paragraph text) for a text body, empties dropped."""
26
+ out: List[Tuple[Optional[int], str]] = []
27
+ level: Optional[int] = None
28
+ buf: List[str] = []
29
+
30
+ def flush() -> None:
31
+ line = "".join(buf).replace("\u000b", " ").strip()
32
+ if line:
33
+ out.append((level, line))
34
+
35
+ for te in (text or {}).get("textElements", []):
36
+ if "paragraphMarker" in te:
37
+ flush()
38
+ buf = []
39
+ bullet = te["paragraphMarker"].get("bullet")
40
+ level = bullet.get("nestingLevel", 0) if bullet is not None else None
41
+ elif "textRun" in te:
42
+ buf.append(te["textRun"].get("content", "").rstrip("\n"))
43
+ elif "autoText" in te:
44
+ buf.append(te["autoText"].get("content", ""))
45
+ flush()
46
+ return out
47
+
48
+
49
+ def _notes(
50
+ slide: Dict[str, Any],
51
+ ) -> Tuple[Optional[str], List[Tuple[Optional[int], str]]]:
52
+ notes_page = (slide.get("slideProperties") or {}).get("notesPage") or {}
53
+ notes_id = (notes_page.get("notesProperties") or {}).get("speakerNotesObjectId")
54
+ for el in notes_page.get("pageElements", []):
55
+ if el.get("objectId") == notes_id:
56
+ return notes_id, _paragraphs((el.get("shape") or {}).get("text"))
57
+ return notes_id, []
58
+
59
+
60
+ def _largest_font(text: Optional[Dict[str, Any]]) -> float:
61
+ sizes = [
62
+ ((te["textRun"].get("style") or {}).get("fontSize") or {}).get("magnitude", 0)
63
+ for te in (text or {}).get("textElements", [])
64
+ if "textRun" in te and te["textRun"].get("content", "").strip()
65
+ ]
66
+ return max(sizes, default=0)
67
+
68
+
69
+ def slide_title(slide: Dict[str, Any]) -> Optional[str]:
70
+ """Title placeholder text, else the text set in the largest font.
71
+
72
+ A subtitle or body placeholder that inherits its size outranks sized text.
73
+ Ties go to z-order.
74
+ """
75
+ shapes = [
76
+ el.get("shape") or {} for el, _ in iter_elements(slide.get("pageElements", []))
77
+ ]
78
+ for shape in shapes:
79
+ if (shape.get("placeholder") or {}).get("type") in _TITLE_TYPES:
80
+ paras = _paragraphs(shape.get("text"))
81
+ if paras:
82
+ return paras[0][1]
83
+ best: Optional[str] = None
84
+ best_size = -1.0
85
+ for shape in shapes:
86
+ paras = _paragraphs(shape.get("text"))
87
+ if not paras:
88
+ continue
89
+ size = _largest_font(shape.get("text"))
90
+ if not size and (shape.get("placeholder") or {}).get("type") in _BODY_TYPES:
91
+ size = float("inf")
92
+ if size > best_size:
93
+ best, best_size = paras[0][1], size
94
+ return best
95
+
96
+
97
+ def _plural(n: int, word: str) -> str:
98
+ return f"{n} {word}" if n == 1 else f"{n} {word}s"
99
+
100
+
101
+ def _counts(slide: Dict[str, Any]) -> str:
102
+ counts: Dict[str, int] = {}
103
+ tables = []
104
+ for el, _ in iter_elements(slide.get("pageElements", [])):
105
+ kind = element_kind(el)
106
+ if kind == "group":
107
+ continue
108
+ counts[kind] = counts.get(kind, 0) + 1
109
+ if kind == "table":
110
+ tables.append(f"{el['table'].get('rows')}x{el['table'].get('columns')}")
111
+ parts = []
112
+ for kind, n in counts.items():
113
+ part = _plural(n, kind)
114
+ if kind == "table":
115
+ part += f" ({', '.join(tables)})"
116
+ parts.append(part)
117
+ return ", ".join(parts) or "empty"
118
+
119
+
120
+ # --- layouts ----------------------------------------------------------------
121
+
122
+
123
+ def _layout_usage(pres: Dict[str, Any]) -> Dict[str, List[int]]:
124
+ used: Dict[str, List[int]] = {}
125
+ for n, slide in enumerate(pres.get("slides", []), 1):
126
+ lid = (slide.get("slideProperties") or {}).get("layoutObjectId")
127
+ used.setdefault(lid, []).append(n)
128
+ return used
129
+
130
+
131
+ def _slide_list(numbers: List[int]) -> str:
132
+ if not numbers:
133
+ return "-"
134
+ ranges, start, prev = [], numbers[0], numbers[0]
135
+ for n in numbers[1:] + [None]:
136
+ if n is not None and n == prev + 1:
137
+ prev = n
138
+ continue
139
+ ranges.append(str(start) if start == prev else f"{start}-{prev}")
140
+ if n is not None:
141
+ start = prev = n
142
+ label = "slide" if len(numbers) == 1 else "slides"
143
+ return f"{label} {', '.join(ranges)}"
144
+
145
+
146
+ def _layout_line(layout: Dict[str, Any], used: Dict[str, List[int]]) -> str:
147
+ props = layout.get("layoutProperties") or {}
148
+ kinds = [
149
+ p for p in (placeholder_key(el) for el in layout.get("pageElements", [])) if p
150
+ ]
151
+ return (
152
+ f" {layout.get('objectId')} {props.get('displayName', '')} "
153
+ f"{', '.join(kinds) or '-'} {_slide_list(used.get(layout.get('objectId'), []))}"
154
+ )
155
+
156
+
157
+ def _master_of_position(pres: Dict[str, Any], after: Optional[str]) -> Optional[str]:
158
+ """The master add_slide resolves a layout against when inserting there."""
159
+ slides = pres.get("slides", [])
160
+ if not slides:
161
+ masters = pres.get("masters", [])
162
+ return masters[0].get("objectId") if masters else None
163
+ if after == "start":
164
+ anchor = slides[0]
165
+ else:
166
+ anchor = next((s for s in slides if s.get("objectId") == after), slides[-1])
167
+ return (anchor.get("slideProperties") or {}).get("masterObjectId")
168
+
169
+
170
+ def format_layouts(
171
+ pres: Dict[str, Any],
172
+ after: Optional[str] = None,
173
+ only_used: bool = False,
174
+ used_by: Optional[Iterable[str]] = None,
175
+ ) -> List[str]:
176
+ """Layout lines grouped by master.
177
+
178
+ ``only_used`` keeps layouts some slide uses; ``used_by`` narrows that to
179
+ the given layout IDs (those used by one page of the deck).
180
+ """
181
+ used = _layout_usage(pres)
182
+ wanted = set(used_by) if used_by is not None else set(used)
183
+ masters = {m.get("objectId"): m for m in pres.get("masters", [])}
184
+ only_master = _master_of_position(pres, after) if after else None
185
+ by_master: Dict[str, List[Dict[str, Any]]] = {}
186
+ for layout in pres.get("layouts", []):
187
+ mid = (layout.get("layoutProperties") or {}).get("masterObjectId")
188
+ if only_master and mid != only_master:
189
+ continue
190
+ if only_used and layout.get("objectId") not in wanted:
191
+ continue
192
+ by_master.setdefault(mid, []).append(layout)
193
+ lines: List[str] = []
194
+ for mid, layouts in by_master.items():
195
+ if len(masters) > 1:
196
+ name = (masters.get(mid, {}).get("masterProperties") or {}).get(
197
+ "displayName", ""
198
+ )
199
+ lines.append(f"Master {mid} {name}".rstrip())
200
+ lines.extend(_layout_line(layout, used) for layout in layouts)
201
+ return lines
202
+
203
+
204
+ # --- deck -------------------------------------------------------------------
205
+
206
+
207
+ def format_deck(
208
+ pres: Dict[str, Any], offset: int = 0, limit: int = DECK_PAGE_SLIDES
209
+ ) -> str:
210
+ """Deck digest, ``limit`` slides from slide index ``offset``, ending with
211
+ the offset to call again with when more slides follow."""
212
+ pid = pres.get("presentationId")
213
+ size = pres.get("pageSize") or {}
214
+ w = size.get("width", {}).get("magnitude", 0) / EMU_PER_PT
215
+ h = size.get("height", {}).get("magnitude", 0) / EMU_PER_PT
216
+ slides = pres.get("slides", [])
217
+ total = len(slides)
218
+ if total and offset >= total:
219
+ return f"[offset={offset:,} is past the last slide ({total:,} slides).]"
220
+ shown = slides[offset : offset + limit]
221
+ lines = [
222
+ f"Presentation: {pres.get('title', '')}",
223
+ f"ID: {pid}",
224
+ f"URL: https://docs.google.com/presentation/d/{pid}/edit",
225
+ f"Slides: {total} Page size: {w:g} x {h:g} pt Revision: {pres.get('revisionId', '-')}",
226
+ "",
227
+ ]
228
+ for n, slide in enumerate(shown, offset + 1):
229
+ _, notes = _notes(slide)
230
+ chars = sum(len(t) for _, t in notes)
231
+ layout = (slide.get("slideProperties") or {}).get("layoutObjectId")
232
+ lines.append(
233
+ f"{n}. {slide.get('objectId')} {slide_title(slide) or '(no title)'}"
234
+ )
235
+ lines.append(
236
+ f" layout {layout} {_counts(slide)} notes: {f'{chars} chars' if chars else '-'}"
237
+ )
238
+ layouts = pres.get("layouts", [])
239
+ paged = len(shown) < total
240
+ lines.append("")
241
+ if len(layouts) <= LAYOUT_CAP:
242
+ lines.append("Layouts:")
243
+ lines.extend(format_layouts(pres))
244
+ else:
245
+ page_layouts = {
246
+ (s.get("slideProperties") or {}).get("layoutObjectId") for s in shown
247
+ }
248
+ listed = format_layouts(pres, only_used=True, used_by=page_layouts)
249
+ lines.append(
250
+ "Layouts used by these slides:" if paged else "Layouts used by slides:"
251
+ )
252
+ lines.extend(listed)
253
+ count = sum(1 for line in listed if line.startswith(" "))
254
+ masters = len(pres.get("masters", []))
255
+ lines.append(
256
+ f"+ {len(layouts) - count} more layouts in {_plural(masters, 'master')}: "
257
+ 'get_presentation(action="layouts")'
258
+ )
259
+ end = offset + len(shown)
260
+ if paged:
261
+ note = f"[Showing slides {offset + 1:,} to {end:,} of {total:,}"
262
+ if end < total:
263
+ note += f"; {total - end:,} more follow. Call again with offset={end} to read on"
264
+ lines.extend(["", note + ".]"])
265
+ return "\n".join(lines)
266
+
267
+
268
+ # --- page -------------------------------------------------------------------
269
+
270
+
271
+ def _element_lines(el: Dict[str, Any], indent: str) -> List[str]:
272
+ kind = element_kind(el)
273
+ oid = el.get("objectId")
274
+ lines: List[str] = []
275
+ if kind == "shape":
276
+ shape = el["shape"]
277
+ head = f"{indent}- shape {oid} {shape.get('shapeType')}"
278
+ ph = placeholder_key(el)
279
+ if ph:
280
+ head += f" placeholder={ph}"
281
+ lines.append(head)
282
+ for level, text in _paragraphs(shape.get("text")):
283
+ prefix = "" if level is None else " " * level + "- "
284
+ lines.append(f"{indent} {prefix}{text}")
285
+ elif kind == "table":
286
+ table = el["table"]
287
+ lines.append(
288
+ f"{indent}- table {oid} {table.get('rows')}x{table.get('columns')}"
289
+ )
290
+ for row in table.get("tableRows", []):
291
+ for cell in row.get("tableCells", []):
292
+ text = " / ".join(t for _, t in _paragraphs(cell.get("text")))
293
+ if not text:
294
+ continue
295
+ loc = cell.get("location", {})
296
+ span = ""
297
+ if cell.get("rowSpan", 1) > 1 or cell.get("columnSpan", 1) > 1:
298
+ span = f" span={cell.get('rowSpan', 1)}x{cell.get('columnSpan', 1)}"
299
+ lines.append(
300
+ f"{indent} [{loc.get('rowIndex', 0)},{loc.get('columnIndex', 0)}]{span} {text}"
301
+ )
302
+ elif kind == "image":
303
+ image = el["image"]
304
+ head = f"{indent}- image {oid}"
305
+ if image.get("sourceUrl"):
306
+ head += f" src={image['sourceUrl']}"
307
+ lines.append(head)
308
+ elif kind == "chart":
309
+ chart = el["sheetsChart"]
310
+ lines.append(
311
+ f"{indent}- chart {oid} spreadsheet={chart.get('spreadsheetId')} chart={chart.get('chartId')}"
312
+ )
313
+ elif kind == "line":
314
+ lines.append(
315
+ f"{indent}- line {oid} {el['line'].get('lineCategory', 'STRAIGHT')}"
316
+ )
317
+ elif kind == "group":
318
+ children = el["elementGroup"].get("children", [])
319
+ lines.append(f"{indent}- group {oid} {_plural(len(children), 'element')}")
320
+ for child in children:
321
+ lines.extend(_element_lines(child, indent + " "))
322
+ elif kind == "wordArt":
323
+ lines.append(
324
+ f"{indent}- wordArt {oid} {el['wordArt'].get('renderedText', '')}"
325
+ )
326
+ elif kind == "video":
327
+ video = el["video"]
328
+ lines.append(
329
+ f"{indent}- video {oid} {video.get('source')} id={video.get('id')}"
330
+ )
331
+ else:
332
+ lines.append(f"{indent}- {kind} {oid}")
333
+ alt = " / ".join(t for t in (el.get("title"), el.get("description")) if t)
334
+ if alt:
335
+ lines.append(f"{indent} alt: {alt}")
336
+ return lines
337
+
338
+
339
+ def _inherited(pres: Optional[Dict[str, Any]], slide: Dict[str, Any]) -> Optional[str]:
340
+ """Say what is visible but has no element ID on the slide."""
341
+ parts = []
342
+ background = (slide.get("pageProperties") or {}).get("pageBackgroundFill") or {}
343
+ if background.get("propertyState") not in (None, "INHERIT", "NOT_RENDERED"):
344
+ parts.append("the page background")
345
+ if pres:
346
+ props = slide.get("slideProperties") or {}
347
+ drawn = 0
348
+ for page in pres.get("layouts", []) + pres.get("masters", []):
349
+ if page.get("objectId") in (
350
+ props.get("layoutObjectId"),
351
+ props.get("masterObjectId"),
352
+ ):
353
+ drawn += sum(
354
+ 1 for el in page.get("pageElements", []) if not placeholder_key(el)
355
+ )
356
+ if drawn:
357
+ parts.append(f"{_plural(drawn, 'element')} drawn by the layout and master")
358
+ if not parts:
359
+ return None
360
+ return f"Also visible, with no element IDs here: {' and '.join(parts)}. render_page_to_image shows them."
361
+
362
+
363
+ def format_page(
364
+ slide: Dict[str, Any],
365
+ revision: Optional[str] = None,
366
+ pres: Optional[Dict[str, Any]] = None,
367
+ ) -> str:
368
+ elements = slide.get("pageElements", [])
369
+ lines = [
370
+ f"page {slide.get('objectId')} {slide.get('pageType', 'SLIDE')} "
371
+ f"{_plural(len(elements), 'element')} revision {revision or slide.get('revisionId', '-')}",
372
+ "",
373
+ ]
374
+ for el in elements:
375
+ lines.extend(_element_lines(el, ""))
376
+ notes_id, notes = _notes(slide)
377
+ if notes_id:
378
+ # The notes shape ID is the only valid target for writing notes, so it
379
+ # is listed even when the notes are empty.
380
+ lines.append("")
381
+ lines.append(f"notes shape {notes_id}:" + ("" if notes else " (empty)"))
382
+ lines.extend(
383
+ f" {' ' * (lvl or 0)}{'- ' if lvl is not None else ''}{t}"
384
+ for lvl, t in notes
385
+ )
386
+ inherited = _inherited(pres, slide)
387
+ if inherited:
388
+ lines.append("")
389
+ lines.append(inherited)
390
+ return "\n".join(lines)