@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,526 @@
1
+ """
2
+ Header Footer Manager
3
+
4
+ This module provides high-level operations for managing headers and footers
5
+ in Google Docs, extracting complex logic from the main tools module.
6
+ """
7
+
8
+ import logging
9
+ import asyncio
10
+ from typing import Any, Optional
11
+
12
+ from gdocs.docs_helpers import (
13
+ create_create_header_footer_request,
14
+ create_delete_range_request,
15
+ create_insert_text_request,
16
+ )
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ class HeaderFooterManager:
22
+ """
23
+ High-level manager for Google Docs header and footer operations.
24
+
25
+ Handles complex header/footer operations including:
26
+ - Finding and updating existing headers/footers
27
+ - Content replacement with proper range calculation
28
+ - Section type management
29
+ """
30
+
31
+ def __init__(self, service):
32
+ """
33
+ Initialize the header footer manager.
34
+
35
+ Args:
36
+ service: Google Docs API service instance
37
+ """
38
+ self.service = service
39
+ self._style_field_map = {
40
+ "header": {
41
+ "DEFAULT": "defaultHeaderId",
42
+ "FIRST_PAGE_ONLY": "firstPageHeaderId",
43
+ "EVEN_PAGE": "evenPageHeaderId",
44
+ },
45
+ "footer": {
46
+ "DEFAULT": "defaultFooterId",
47
+ "FIRST_PAGE_ONLY": "firstPageFooterId",
48
+ "EVEN_PAGE": "evenPageFooterId",
49
+ },
50
+ }
51
+
52
+ async def update_header_footer_content(
53
+ self,
54
+ document_id: str,
55
+ section_type: str,
56
+ content: str,
57
+ header_footer_type: str = "DEFAULT",
58
+ ) -> tuple[bool, str]:
59
+ """
60
+ Updates header or footer content in a document.
61
+
62
+ This method extracts the complex logic from update_doc_headers_footers tool function.
63
+
64
+ Args:
65
+ document_id: ID of the document to update
66
+ section_type: Type of section ("header" or "footer")
67
+ content: New content for the section
68
+ header_footer_type: Type of header/footer ("DEFAULT", "FIRST_PAGE_ONLY", "EVEN_PAGE")
69
+
70
+ Returns:
71
+ Tuple of (success, message)
72
+ """
73
+ logger.info(f"Updating {section_type} in document {document_id}")
74
+
75
+ # Validate section type
76
+ if section_type not in ["header", "footer"]:
77
+ return False, "section_type must be 'header' or 'footer'"
78
+
79
+ # Validate header/footer type
80
+ if header_footer_type not in ["DEFAULT", "FIRST_PAGE_ONLY", "EVEN_PAGE"]:
81
+ return (
82
+ False,
83
+ "header_footer_type must be 'DEFAULT', 'FIRST_PAGE_ONLY', or 'EVEN_PAGE'",
84
+ )
85
+
86
+ try:
87
+ # Get document structure
88
+ doc = await self._get_document(document_id)
89
+ target_doc, active_tab_id = self._get_target_doc_for_header_footer(doc)
90
+
91
+ # Find the target section
92
+ target_section, section_id = await self._find_target_section(
93
+ target_doc, section_type, header_footer_type
94
+ )
95
+
96
+ if not section_id:
97
+ created_id = await self._create_missing_section(
98
+ document_id, section_type, header_footer_type
99
+ )
100
+ if not created_id:
101
+ return (
102
+ False,
103
+ f"No {section_type} found in document and automatic creation failed",
104
+ )
105
+ doc = await self._get_document(document_id)
106
+ target_doc, active_tab_id = self._get_target_doc_for_header_footer(doc)
107
+ target_section = (
108
+ target_doc.get("headers", {}).get(created_id)
109
+ if section_type == "header"
110
+ else target_doc.get("footers", {}).get(created_id)
111
+ )
112
+ section_id = created_id
113
+
114
+ # Update the content
115
+ success, replace_message = await self._replace_section_content(
116
+ document_id, target_section, content, section_id, active_tab_id
117
+ )
118
+
119
+ if not success:
120
+ # Retry once after re-fetching the document. Newly created headers/footers
121
+ # can lag briefly before their segment content becomes fully visible.
122
+ refreshed_doc = await self._get_document(document_id)
123
+ refreshed_target_doc, refreshed_tab_id = (
124
+ self._get_target_doc_for_header_footer(refreshed_doc)
125
+ )
126
+ (
127
+ refreshed_section,
128
+ refreshed_section_id,
129
+ ) = await self._find_target_section(
130
+ refreshed_target_doc, section_type, header_footer_type
131
+ )
132
+ if refreshed_section_id:
133
+ success, replace_message = await self._replace_section_content(
134
+ document_id,
135
+ refreshed_section,
136
+ content,
137
+ refreshed_section_id,
138
+ refreshed_tab_id,
139
+ )
140
+
141
+ if success:
142
+ return True, f"Updated {section_type} content in document {document_id}"
143
+ else:
144
+ return False, replace_message
145
+
146
+ except Exception as e:
147
+ logger.error(f"Failed to update {section_type}: {str(e)}")
148
+ return False, f"Failed to update {section_type}: {str(e)}"
149
+
150
+ async def _get_document(self, document_id: str) -> dict[str, Any]:
151
+ """Get the full document data."""
152
+ return await asyncio.to_thread(
153
+ self.service.documents()
154
+ .get(documentId=document_id, includeTabsContent=True)
155
+ .execute
156
+ )
157
+
158
+ def _get_target_doc_for_header_footer(
159
+ self, doc: dict[str, Any]
160
+ ) -> tuple[dict[str, Any], Optional[str]]:
161
+ """
162
+ Return the document-like content container for header/footer operations.
163
+
164
+ In tabbed docs, text content lives under tab.documentTab rather than the
165
+ legacy top-level body/headers/footers/documentStyle fields.
166
+ """
167
+ tabs = doc.get("tabs", [])
168
+ if not tabs:
169
+ return doc, None
170
+
171
+ flattened_tabs: list[dict[str, Any]] = []
172
+
173
+ def add_tab_and_children(tab: dict[str, Any]) -> None:
174
+ flattened_tabs.append(tab)
175
+ for child in tab.get("childTabs", []):
176
+ add_tab_and_children(child)
177
+
178
+ for tab in tabs:
179
+ add_tab_and_children(tab)
180
+
181
+ for tab in flattened_tabs:
182
+ document_tab = tab.get("documentTab")
183
+ if not document_tab:
184
+ continue
185
+ tab_id = tab.get("tabProperties", {}).get("tabId")
186
+ tab_doc = dict(document_tab)
187
+ if "title" not in tab_doc:
188
+ tab_doc["title"] = doc.get("title", "")
189
+ return tab_doc, tab_id
190
+
191
+ return doc, None
192
+
193
+ async def _find_target_section(
194
+ self, doc: dict[str, Any], section_type: str, header_footer_type: str
195
+ ) -> tuple[Optional[dict[str, Any]], Optional[str]]:
196
+ """
197
+ Find the target header or footer section.
198
+
199
+ Args:
200
+ doc: Document data
201
+ section_type: "header" or "footer"
202
+ header_footer_type: Type of header/footer
203
+
204
+ Returns:
205
+ Tuple of (section_data, section_id) or (None, None) if not found
206
+ """
207
+ if section_type == "header":
208
+ sections = doc.get("headers", {})
209
+ else:
210
+ sections = doc.get("footers", {})
211
+
212
+ style_section_id = self._resolve_section_id_from_styles(
213
+ doc, section_type, header_footer_type
214
+ )
215
+ if style_section_id:
216
+ return sections.get(style_section_id), style_section_id
217
+
218
+ # First, try to find an exact match based on common patterns
219
+ for section_id, section_data in sections.items():
220
+ # Check if section_data contains type information
221
+ if "type" in section_data and section_data["type"] == header_footer_type:
222
+ return section_data, section_id
223
+
224
+ # If no exact match, try pattern matching on section ID
225
+ # Google Docs often uses predictable section ID patterns
226
+ target_patterns = {
227
+ "DEFAULT": ["default", "kix"], # DEFAULT headers often have these patterns
228
+ "FIRST_PAGE": ["first", "firstpage"],
229
+ "EVEN_PAGE": ["even", "evenpage"],
230
+ "FIRST_PAGE_ONLY": ["first", "firstpage"], # Legacy support
231
+ }
232
+
233
+ patterns = target_patterns.get(header_footer_type, [])
234
+ for pattern in patterns:
235
+ for section_id, section_data in sections.items():
236
+ if pattern.lower() in section_id.lower():
237
+ return section_data, section_id
238
+
239
+ # If still no match, return the first available section as fallback
240
+ # This maintains backward compatibility
241
+ for section_id, section_data in sections.items():
242
+ return section_data, section_id
243
+
244
+ return None, None
245
+
246
+ def _resolve_section_id_from_styles(
247
+ self, doc: dict[str, Any], section_type: str, header_footer_type: str
248
+ ) -> Optional[str]:
249
+ """Resolve a header/footer segment ID from document or section styles."""
250
+ style_field = self._style_field_map.get(section_type, {}).get(
251
+ header_footer_type
252
+ )
253
+ if not style_field:
254
+ return None
255
+
256
+ # SectionStyle overrides DocumentStyle for the first section.
257
+ for element in doc.get("body", {}).get("content", []):
258
+ section_style = element.get("sectionBreak", {}).get("sectionStyle", {})
259
+ if not section_style:
260
+ continue
261
+ section_id = section_style.get(style_field)
262
+ if section_id:
263
+ return section_id
264
+ break
265
+
266
+ return doc.get("documentStyle", {}).get(style_field)
267
+
268
+ async def _replace_section_content(
269
+ self,
270
+ document_id: str,
271
+ section: dict[str, Any],
272
+ new_content: str,
273
+ section_id: str,
274
+ tab_id: Optional[str],
275
+ ) -> tuple[bool, str]:
276
+ """
277
+ Replace the content in a header or footer section.
278
+
279
+ Args:
280
+ document_id: Document ID
281
+ section: Section data containing content elements
282
+ new_content: New content to insert
283
+
284
+ Returns:
285
+ Tuple of (success, message)
286
+ """
287
+ content_elements = section.get("content", []) if section else []
288
+ first_para = self._find_first_paragraph(content_elements)
289
+ has_meaningful_content = self._segment_has_meaningful_content(content_elements)
290
+ if first_para:
291
+ start_index = first_para.get("startIndex", 0)
292
+ end_index = first_para.get("endIndex", 0)
293
+ else:
294
+ start_index = 0
295
+ end_index = 0
296
+
297
+ # Build requests to replace content
298
+ requests = []
299
+
300
+ # Delete existing content if any (preserve paragraph structure)
301
+ # Docs segments often contain a single empty paragraph marker. Deleting
302
+ # start..end-1 in that case produces an empty range, which the API rejects.
303
+ if has_meaningful_content and end_index - start_index > 1:
304
+ requests.append(
305
+ create_delete_range_request(
306
+ start_index,
307
+ end_index - 1, # Preserve the trailing paragraph marker
308
+ tab_id=tab_id,
309
+ segment_id=section_id,
310
+ )
311
+ )
312
+
313
+ # Insert new content
314
+ if first_para and has_meaningful_content:
315
+ requests.append(
316
+ create_insert_text_request(
317
+ start_index,
318
+ new_content,
319
+ tab_id=tab_id,
320
+ segment_id=section_id,
321
+ )
322
+ )
323
+ else:
324
+ # Newly created or empty segments may not expose paragraph content yet.
325
+ # Append directly to the segment so callers do not need a follow-up create.
326
+ requests.append(
327
+ create_insert_text_request(
328
+ None,
329
+ new_content,
330
+ tab_id=tab_id,
331
+ segment_id=section_id,
332
+ end_of_segment=True,
333
+ )
334
+ )
335
+
336
+ try:
337
+ await asyncio.to_thread(
338
+ self.service.documents()
339
+ .batchUpdate(documentId=document_id, body={"requests": requests})
340
+ .execute
341
+ )
342
+ return True, "ok"
343
+
344
+ except Exception as e:
345
+ logger.error(f"Failed to replace section content: {str(e)}")
346
+ return (
347
+ False,
348
+ f"Failed to write {section_id} segment content: {str(e)}",
349
+ )
350
+
351
+ def _segment_has_meaningful_content(
352
+ self, content_elements: list[dict[str, Any]]
353
+ ) -> bool:
354
+ """
355
+ Return True when a header/footer segment contains user-visible text beyond
356
+ the default empty paragraph marker.
357
+ """
358
+ for element in content_elements:
359
+ paragraph = element.get("paragraph")
360
+ if not paragraph:
361
+ continue
362
+ for para_element in paragraph.get("elements", []):
363
+ text_run = para_element.get("textRun")
364
+ if not text_run:
365
+ continue
366
+ content = text_run.get("content", "")
367
+ if content.strip():
368
+ return True
369
+ return False
370
+
371
+ async def _create_missing_section(
372
+ self, document_id: str, section_type: str, header_footer_type: str = "DEFAULT"
373
+ ) -> Optional[str]:
374
+ """Create a missing header/footer and return its new segment ID."""
375
+ request = create_create_header_footer_request(section_type, header_footer_type)
376
+ try:
377
+ result = await asyncio.to_thread(
378
+ self.service.documents()
379
+ .batchUpdate(documentId=document_id, body={"requests": [request]})
380
+ .execute
381
+ )
382
+ except Exception as e:
383
+ if "already exists" in str(e).lower():
384
+ try:
385
+ doc = await self._get_document(document_id)
386
+ return self._resolve_section_id_from_styles(
387
+ doc, section_type, header_footer_type
388
+ )
389
+ except Exception:
390
+ pass
391
+ logger.error(f"Failed to create missing {section_type}: {str(e)}")
392
+ return None
393
+
394
+ replies = result.get("replies", [])
395
+ if not replies:
396
+ return None
397
+
398
+ reply = replies[0]
399
+ if section_type == "header":
400
+ return reply.get("createHeader", {}).get("headerId")
401
+ return reply.get("createFooter", {}).get("footerId")
402
+
403
+ def _find_first_paragraph(
404
+ self, content_elements: list[dict[str, Any]]
405
+ ) -> Optional[dict[str, Any]]:
406
+ """Find the first paragraph element in content."""
407
+ for element in content_elements:
408
+ if "paragraph" in element:
409
+ return element
410
+ return None
411
+
412
+ async def get_header_footer_info(self, document_id: str) -> dict[str, Any]:
413
+ """
414
+ Get information about all headers and footers in the document.
415
+
416
+ Args:
417
+ document_id: Document ID
418
+
419
+ Returns:
420
+ Dictionary with header and footer information
421
+ """
422
+ try:
423
+ doc = await self._get_document(document_id)
424
+
425
+ headers_info = {}
426
+ for header_id, header_data in doc.get("headers", {}).items():
427
+ headers_info[header_id] = self._extract_section_info(header_data)
428
+
429
+ footers_info = {}
430
+ for footer_id, footer_data in doc.get("footers", {}).items():
431
+ footers_info[footer_id] = self._extract_section_info(footer_data)
432
+
433
+ return {
434
+ "headers": headers_info,
435
+ "footers": footers_info,
436
+ "has_headers": bool(headers_info),
437
+ "has_footers": bool(footers_info),
438
+ }
439
+
440
+ except Exception as e:
441
+ logger.error(f"Failed to get header/footer info: {str(e)}")
442
+ return {"error": str(e)}
443
+
444
+ def _extract_section_info(self, section_data: dict[str, Any]) -> dict[str, Any]:
445
+ """Extract useful information from a header/footer section."""
446
+ content_elements = section_data.get("content", [])
447
+
448
+ # Extract text content
449
+ text_content = ""
450
+ for element in content_elements:
451
+ if "paragraph" in element:
452
+ para = element["paragraph"]
453
+ for para_element in para.get("elements", []):
454
+ if "textRun" in para_element:
455
+ text_content += para_element["textRun"].get("content", "")
456
+
457
+ return {
458
+ "content_preview": text_content[:100] if text_content else "(empty)",
459
+ "element_count": len(content_elements),
460
+ "start_index": content_elements[0].get("startIndex", 0)
461
+ if content_elements
462
+ else 0,
463
+ "end_index": content_elements[-1].get("endIndex", 0)
464
+ if content_elements
465
+ else 0,
466
+ }
467
+
468
+ async def create_header_footer(
469
+ self, document_id: str, section_type: str, header_footer_type: str = "DEFAULT"
470
+ ) -> tuple[bool, str]:
471
+ """
472
+ Create a new header or footer section.
473
+
474
+ Args:
475
+ document_id: Document ID
476
+ section_type: "header" or "footer"
477
+ header_footer_type: Type of header/footer ("DEFAULT", "FIRST_PAGE", or "EVEN_PAGE")
478
+
479
+ Returns:
480
+ Tuple of (success, message)
481
+ """
482
+ if section_type not in ["header", "footer"]:
483
+ return False, "section_type must be 'header' or 'footer'"
484
+
485
+ # Map our type names to API type names
486
+ type_mapping = {
487
+ "DEFAULT": "DEFAULT",
488
+ "FIRST_PAGE": "FIRST_PAGE",
489
+ "EVEN_PAGE": "EVEN_PAGE",
490
+ "FIRST_PAGE_ONLY": "FIRST_PAGE", # Support legacy name
491
+ }
492
+
493
+ api_type = type_mapping.get(header_footer_type, header_footer_type)
494
+ if api_type not in ["DEFAULT", "FIRST_PAGE", "EVEN_PAGE"]:
495
+ return (
496
+ False,
497
+ "header_footer_type must be 'DEFAULT', 'FIRST_PAGE', or 'EVEN_PAGE'",
498
+ )
499
+
500
+ try:
501
+ # Build the request
502
+ request = {"type": api_type}
503
+
504
+ # Create the appropriate request type
505
+ if section_type == "header":
506
+ batch_request = {"createHeader": request}
507
+ else:
508
+ batch_request = {"createFooter": request}
509
+
510
+ # Execute the request
511
+ await asyncio.to_thread(
512
+ self.service.documents()
513
+ .batchUpdate(documentId=document_id, body={"requests": [batch_request]})
514
+ .execute
515
+ )
516
+
517
+ return True, f"Successfully created {section_type} with type {api_type}"
518
+
519
+ except Exception as e:
520
+ error_msg = str(e)
521
+ if "already exists" in error_msg.lower():
522
+ return (
523
+ False,
524
+ f"A {section_type} of type {api_type} already exists in the document",
525
+ )
526
+ return False, f"Failed to create {section_type}: {error_msg}"