@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,463 @@
1
+ """Context-preserving plain-text renderer for Google Docs API responses."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import re
7
+ from typing import Any
8
+
9
+ from gdocs.docs_links import LinkTarget, resolve_link_target, text_run_link
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ TAB_HEADER_FORMAT = "\n--- TAB: {tab_name} (ID: {tab_id}) ---\n"
14
+ _TRAILING_NEWLINES = re.compile(r"(\n+)$")
15
+ _STRUCTURAL_METADATA_KEYS = {
16
+ "startIndex",
17
+ "endIndex",
18
+ "suggestedInsertionIds",
19
+ "suggestedDeletionIds",
20
+ }
21
+ _PARAGRAPH_METADATA_KEYS = _STRUCTURAL_METADATA_KEYS | {
22
+ "suggestedTextStyleChanges",
23
+ }
24
+
25
+
26
+ def render_doc_to_plain_text(
27
+ doc: dict[str, Any], current_tab_id: str | None = None
28
+ ) -> str:
29
+ """Render a Docs API document without discarding semantic context.
30
+
31
+ The output intentionally remains plain text. Existing paragraph and tab
32
+ marker behavior is retained, while API-only structures receive readable
33
+ annotations instead of disappearing.
34
+ """
35
+ renderer = _PlainTextRenderer()
36
+ return renderer.render_document(doc, current_tab_id)
37
+
38
+
39
+ class _PlainTextRenderer:
40
+ """Render semantic annotations using each document tab's own metadata."""
41
+
42
+ def render_document(
43
+ self, doc: dict[str, Any], current_tab_id: str | None = None
44
+ ) -> str:
45
+ """Combine legacy body content and nested tabs without dropping whitespace."""
46
+ sections: list[str] = []
47
+
48
+ main_content = self._render_context(doc, current_tab_id=current_tab_id)
49
+ if main_content:
50
+ sections.append(main_content)
51
+
52
+ for tab in doc.get("tabs", []):
53
+ sections.append(self._render_tab(tab))
54
+
55
+ return "".join(sections)
56
+
57
+ def _render_tab(self, tab: dict[str, Any], level: int = 0) -> str:
58
+ """Label a tab and recursively render its children with indented titles."""
59
+ result: list[str] = []
60
+ document_tab = tab.get("documentTab")
61
+ if document_tab is not None:
62
+ props = tab.get("tabProperties", {})
63
+ title = props.get("title", "Untitled Tab")
64
+ tab_id = props.get("tabId", "Unknown ID")
65
+ indented_title = f"{' ' * level}{title}"
66
+ result.append(
67
+ TAB_HEADER_FORMAT.format(tab_name=indented_title, tab_id=tab_id)
68
+ )
69
+ result.append(self._render_context(document_tab, current_tab_id=tab_id))
70
+
71
+ for child in tab.get("childTabs", []):
72
+ result.append(self._render_tab(child, level + 1))
73
+ return "".join(result)
74
+
75
+ def _render_context(
76
+ self, context: dict[str, Any], current_tab_id: str | None
77
+ ) -> str:
78
+ """Render body and segments, then list positioned objects lacking anchors."""
79
+ referenced_positioned: set[str] = set()
80
+ parts: list[str] = []
81
+
82
+ body = context.get("body", {})
83
+ parts.append(
84
+ self._render_segment(
85
+ body.get("content", []),
86
+ context,
87
+ current_tab_id,
88
+ referenced_positioned,
89
+ )
90
+ )
91
+
92
+ for header_id, header in context.get("headers", {}).items():
93
+ parts.append(f"\n--- HEADER: {header_id} ---\n")
94
+ parts.append(
95
+ self._render_segment(
96
+ header.get("content", []),
97
+ context,
98
+ current_tab_id,
99
+ referenced_positioned,
100
+ )
101
+ )
102
+
103
+ for footer_id, footer in context.get("footers", {}).items():
104
+ parts.append(f"\n--- FOOTER: {footer_id} ---\n")
105
+ parts.append(
106
+ self._render_segment(
107
+ footer.get("content", []),
108
+ context,
109
+ current_tab_id,
110
+ referenced_positioned,
111
+ )
112
+ )
113
+
114
+ positioned_objects = context.get("positionedObjects", {})
115
+ unresolved = [
116
+ object_id
117
+ for object_id in positioned_objects
118
+ if object_id not in referenced_positioned
119
+ ]
120
+ if unresolved:
121
+ parts.append("\n--- UNRESOLVED POSITIONED OBJECTS ---\n")
122
+ for object_id in unresolved:
123
+ marker = self._render_object(
124
+ object_id,
125
+ positioned_objects,
126
+ object_kind="Positioned object",
127
+ )
128
+ parts.append(f"{object_id}: {marker}\n")
129
+
130
+ return "".join(parts)
131
+
132
+ def _render_segment(
133
+ self,
134
+ content: list[dict[str, Any]],
135
+ context: dict[str, Any],
136
+ current_tab_id: str | None,
137
+ referenced_positioned: set[str],
138
+ active_footnotes: set[str] | None = None,
139
+ ) -> str:
140
+ """Append referenced footnotes while preventing cycles in nested references."""
141
+ footnote_refs: list[str] = []
142
+ rendered = self._render_elements(
143
+ content,
144
+ context,
145
+ current_tab_id,
146
+ referenced_positioned,
147
+ footnote_refs,
148
+ )
149
+
150
+ active = set(active_footnotes or ())
151
+ for footnote_id in footnote_refs:
152
+ if footnote_id in active:
153
+ continue
154
+ footnote = context.get("footnotes", {}).get(footnote_id)
155
+ if not footnote:
156
+ continue
157
+ nested_active = active | {footnote_id}
158
+ footnote_text = self._render_segment(
159
+ footnote.get("content", []),
160
+ context,
161
+ current_tab_id,
162
+ referenced_positioned,
163
+ active_footnotes=nested_active,
164
+ ).strip()
165
+ if rendered and not rendered.endswith("\n"):
166
+ rendered += "\n"
167
+ rendered += f"Footnote {footnote_id}: {footnote_text}\n"
168
+
169
+ return rendered
170
+
171
+ def _render_elements(
172
+ self,
173
+ elements: list[dict[str, Any]],
174
+ context: dict[str, Any],
175
+ current_tab_id: str | None,
176
+ referenced_positioned: set[str],
177
+ footnote_refs: list[str],
178
+ ) -> str:
179
+ """Traverse structural elements and collect object and footnote references."""
180
+ parts: list[str] = []
181
+ for position, element in enumerate(elements):
182
+ if "paragraph" in element:
183
+ paragraph = self._render_paragraph(
184
+ element.get("paragraph", {}),
185
+ context,
186
+ current_tab_id,
187
+ referenced_positioned,
188
+ footnote_refs,
189
+ )
190
+ if paragraph:
191
+ parts.append(paragraph)
192
+ elif "table" in element:
193
+ if parts and not parts[-1].endswith("\n"):
194
+ parts.append("\n")
195
+ parts.append(
196
+ self._render_table(
197
+ element.get("table", {}),
198
+ context,
199
+ current_tab_id,
200
+ referenced_positioned,
201
+ footnote_refs,
202
+ )
203
+ )
204
+ elif "tableOfContents" in element:
205
+ table_of_contents = element.get("tableOfContents", {})
206
+ parts.append(
207
+ self._render_elements(
208
+ table_of_contents.get("content", []),
209
+ context,
210
+ current_tab_id,
211
+ referenced_positioned,
212
+ footnote_refs,
213
+ )
214
+ )
215
+ elif "sectionBreak" in element:
216
+ # The Docs API opens every body with a section break; only later
217
+ # ones reflect a break the author inserted.
218
+ if position > 0:
219
+ parts.append("[Section Break]\n")
220
+ else:
221
+ element_type = self._variant_type(element, _STRUCTURAL_METADATA_KEYS)
222
+ if element_type:
223
+ parts.append(self._unsupported_marker(element_type))
224
+ return "".join(parts)
225
+
226
+ def _render_paragraph(
227
+ self,
228
+ paragraph: dict[str, Any],
229
+ context: dict[str, Any],
230
+ current_tab_id: str | None,
231
+ referenced_positioned: set[str],
232
+ footnote_refs: list[str],
233
+ ) -> str:
234
+ """Preserve text runs and annotate chips, breaks, and anchored objects."""
235
+ parts: list[str] = []
236
+ elements = paragraph.get("elements", [])
237
+ for position, element in enumerate(elements):
238
+ if "textRun" in element:
239
+ text_run = element.get("textRun", {})
240
+ content = text_run.get("content", "").replace(
241
+ "\ue907", "[Smart Chip: details unavailable from Docs API]"
242
+ )
243
+ link = text_run.get("textStyle", {}).get("link")
244
+ # Annotate a link split across runs once, after its final run.
245
+ if link and text_run_link(elements, position + 1) == link:
246
+ parts.append(content)
247
+ else:
248
+ parts.append(
249
+ self._render_linked_text(content, link, current_tab_id)
250
+ )
251
+ elif "person" in element:
252
+ parts.append(self._render_person(element.get("person", {})))
253
+ elif "richLink" in element:
254
+ parts.append(self._render_rich_link(element.get("richLink", {})))
255
+ elif "dateElement" in element:
256
+ parts.append(self._render_date(element.get("dateElement", {})))
257
+ elif "dropdown" in element:
258
+ props = element["dropdown"].get("dropdownProperties", {})
259
+ parts.append(
260
+ props.get("displayValue") or "[Dropdown: details unavailable]"
261
+ )
262
+ elif "inlineObjectElement" in element:
263
+ object_id = element.get("inlineObjectElement", {}).get(
264
+ "inlineObjectId", ""
265
+ )
266
+ parts.append(
267
+ self._render_object(
268
+ object_id,
269
+ context.get("inlineObjects", {}),
270
+ object_kind="Inline object",
271
+ )
272
+ )
273
+ elif "positionedObjectElement" in element:
274
+ object_id = element.get("positionedObjectElement", {}).get(
275
+ "positionedObjectId", ""
276
+ )
277
+ referenced_positioned.add(object_id)
278
+ parts.append(
279
+ self._render_object(
280
+ object_id,
281
+ context.get("positionedObjects", {}),
282
+ object_kind="Positioned object",
283
+ )
284
+ )
285
+ elif "footnoteReference" in element:
286
+ footnote_id = element.get("footnoteReference", {}).get("footnoteId", "")
287
+ if footnote_id:
288
+ if footnote_id not in footnote_refs:
289
+ footnote_refs.append(footnote_id)
290
+ parts.append(f"[Footnote: {footnote_id}]")
291
+ elif "pageBreak" in element:
292
+ parts.append("[Page Break]")
293
+ elif "columnBreak" in element:
294
+ parts.append("[Column Break]")
295
+ elif "horizontalRule" in element:
296
+ parts.append("[Horizontal Rule]")
297
+ elif "autoText" in element:
298
+ auto_type = element.get("autoText", {}).get("type", "UNKNOWN")
299
+ parts.append(f"[Auto text: {auto_type}]")
300
+ elif "equation" in element:
301
+ parts.append("[Equation]")
302
+ else:
303
+ element_type = self._variant_type(element, _PARAGRAPH_METADATA_KEYS)
304
+ if element_type:
305
+ parts.append(self._unsupported_marker(element_type))
306
+
307
+ text = "".join(parts)
308
+ positioned_ids = paragraph.get("positionedObjectIds", [])
309
+ if positioned_ids:
310
+ trailing_newlines = ""
311
+ match = _TRAILING_NEWLINES.search(text)
312
+ if match:
313
+ trailing_newlines = match.group(1)
314
+ text = text[: match.start()]
315
+ for object_id in positioned_ids:
316
+ referenced_positioned.add(object_id)
317
+ marker = self._render_object(
318
+ object_id,
319
+ context.get("positionedObjects", {}),
320
+ object_kind="Positioned object",
321
+ )
322
+ separator = " " if text and not text.endswith((" ", "\t")) else ""
323
+ text += separator + marker
324
+ text += trailing_newlines
325
+ return text
326
+
327
+ def _render_table(
328
+ self,
329
+ table: dict[str, Any],
330
+ context: dict[str, Any],
331
+ current_tab_id: str | None,
332
+ referenced_positioned: set[str],
333
+ footnote_refs: list[str],
334
+ ) -> str:
335
+ """Separate cells with tabs and rows with newlines, flattening nested content."""
336
+ rows: list[str] = []
337
+ for row in table.get("tableRows", []):
338
+ cells: list[str] = []
339
+ for cell in row.get("tableCells", []):
340
+ cell_text = self._render_elements(
341
+ cell.get("content", []),
342
+ context,
343
+ current_tab_id,
344
+ referenced_positioned,
345
+ footnote_refs,
346
+ ).strip()
347
+ flattened_lines = [line.strip() for line in cell_text.splitlines()]
348
+ cells.append(" ".join(line for line in flattened_lines if line))
349
+ rows.append("\t".join(cells))
350
+ return "\n".join(rows) + ("\n" if rows else "")
351
+
352
+ def _render_linked_text(
353
+ self,
354
+ content: str,
355
+ link: dict[str, Any] | None,
356
+ current_tab_id: str | None,
357
+ ) -> str:
358
+ """Place link annotations before the text run's trailing newlines."""
359
+ target = resolve_link_target(link)
360
+ if not target or not content:
361
+ return content
362
+
363
+ trailing_newlines = ""
364
+ match = _TRAILING_NEWLINES.search(content)
365
+ if match:
366
+ trailing_newlines = match.group(1)
367
+ content = content[: match.start()]
368
+ if not content:
369
+ return trailing_newlines
370
+
371
+ return self._annotate_link(content, target, current_tab_id) + trailing_newlines
372
+
373
+ @staticmethod
374
+ def _annotate_link(
375
+ label: str, target: LinkTarget, current_tab_id: str | None
376
+ ) -> str:
377
+ """Append a readable destination, using the current tab for local targets."""
378
+ if target.kind == "url":
379
+ return f"{label} ({target.value})"
380
+ if target.kind in ("heading", "bookmark"):
381
+ tab_id = target.tab_id or current_tab_id
382
+ tab_part = f", tab: {tab_id}" if tab_id else ""
383
+ return f"{label} [{target.kind}: {target.value}{tab_part}]"
384
+ if target.kind == "tab":
385
+ return f"{label} [tab: {target.value}]"
386
+ return f"{label} [link target unavailable]"
387
+
388
+ @staticmethod
389
+ def _render_person(person: dict[str, Any]) -> str:
390
+ """Show a person's available name and email, or an explicit missing marker."""
391
+ props = person.get("personProperties", {})
392
+ name = props.get("name", "")
393
+ email = props.get("email", "")
394
+ if name and email:
395
+ return f"{name} <{email}>"
396
+ if name:
397
+ return name
398
+ if email:
399
+ return f"<{email}>"
400
+ return "[Person chip: details unavailable]"
401
+
402
+ @staticmethod
403
+ def _render_rich_link(rich_link: dict[str, Any]) -> str:
404
+ """Retain a rich link's title and URI even when only one is available."""
405
+ props = rich_link.get("richLinkProperties", {})
406
+ title = props.get("title", "")
407
+ uri = props.get("uri", "")
408
+ if title and uri:
409
+ return f"{title} ({uri})"
410
+ if title:
411
+ return title
412
+ if uri:
413
+ return uri
414
+ return "[Rich link: details unavailable]"
415
+
416
+ @staticmethod
417
+ def _render_date(date_element: dict[str, Any]) -> str:
418
+ """Prefer a date chip's display text, falling back to its timestamp."""
419
+ props = date_element.get("dateElementProperties", {})
420
+ return (
421
+ props.get("displayText")
422
+ or props.get("timestamp")
423
+ or "[Date: details unavailable]"
424
+ )
425
+
426
+ @staticmethod
427
+ def _render_object(
428
+ object_id: str,
429
+ objects: dict[str, Any],
430
+ *,
431
+ object_kind: str,
432
+ ) -> str:
433
+ """Describe an image from its metadata or identify an unresolved object."""
434
+ obj = objects.get(object_id, {}) if object_id else {}
435
+ properties_key = (
436
+ "inlineObjectProperties"
437
+ if object_kind == "Inline object"
438
+ else "positionedObjectProperties"
439
+ )
440
+ embedded = obj.get(properties_key, {}).get("embeddedObject", {})
441
+ title = embedded.get("title") or embedded.get("description") or ""
442
+ image_properties = embedded.get("imageProperties", {})
443
+ uri = image_properties.get("sourceUri")
444
+
445
+ if title and uri:
446
+ return f"[Image: {title}; URI: {uri}]"
447
+ if title:
448
+ return f"[Image: {title}]"
449
+ if uri:
450
+ return f"[Image; URI: {uri}]"
451
+ identifier = object_id or "ID"
452
+ return f"[{object_kind} {identifier}: details unavailable]"
453
+
454
+ @staticmethod
455
+ def _variant_type(element: dict[str, Any], ignored: set[str]) -> str | None:
456
+ """Find the element variant while ignoring structural and suggestion fields."""
457
+ return next((key for key in element if key not in ignored), None)
458
+
459
+ @staticmethod
460
+ def _unsupported_marker(element_type: str) -> str:
461
+ """Log an unknown variant and retain a visible marker in the output."""
462
+ logger.warning("Unsupported Google Docs element: %s", element_type)
463
+ return f"[Unsupported Google Docs element: {element_type}]"