@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,425 @@
1
+ """
2
+ Google Docs Table Operations
3
+
4
+ This module provides utilities for creating and manipulating tables
5
+ in Google Docs, including population with data and formatting.
6
+ """
7
+
8
+ import logging
9
+ from typing import Dict, Any, List, Optional, Union, Tuple
10
+
11
+ from gdocs.docs_helpers import create_update_table_cell_style_request
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ def build_table_population_requests(
17
+ table_info: Dict[str, Any], data: List[List[str]], bold_headers: bool = True
18
+ ) -> List[Dict[str, Any]]:
19
+ """
20
+ Build batch requests to populate a table with data.
21
+
22
+ Args:
23
+ table_info: Table information from document structure including cell indices
24
+ data: 2D array of data to insert into table
25
+ bold_headers: Whether to make the first row bold
26
+
27
+ Returns:
28
+ List of request dictionaries for batch update
29
+ """
30
+ requests = []
31
+ cells = table_info.get("cells", [])
32
+
33
+ if not cells:
34
+ logger.warning("No cell information found in table_info")
35
+ return requests
36
+
37
+ # Process each cell - ONLY INSERT, DON'T DELETE
38
+ for row_idx, row_data in enumerate(data):
39
+ if row_idx >= len(cells):
40
+ logger.warning(
41
+ f"Data has more rows ({len(data)}) than table ({len(cells)})"
42
+ )
43
+ break
44
+
45
+ for col_idx, cell_text in enumerate(row_data):
46
+ if col_idx >= len(cells[row_idx]):
47
+ logger.warning(
48
+ f"Data has more columns ({len(row_data)}) than table row {row_idx} ({len(cells[row_idx])})"
49
+ )
50
+ break
51
+
52
+ cell = cells[row_idx][col_idx]
53
+
54
+ # For new empty tables, use the insertion index
55
+ # For tables with existing content, check if cell only contains newline
56
+ existing_content = cell.get("content", "").strip()
57
+
58
+ # Only insert if we have text to insert
59
+ if cell_text:
60
+ # Use the specific insertion index for this cell
61
+ insertion_index = cell.get("insertion_index", cell["start_index"] + 1)
62
+
63
+ # If cell only contains a newline, replace it
64
+ if existing_content == "" or existing_content == "\n":
65
+ # Cell is empty (just newline), insert at the insertion index
66
+ requests.append(
67
+ {
68
+ "insertText": {
69
+ "location": {"index": insertion_index},
70
+ "text": cell_text,
71
+ }
72
+ }
73
+ )
74
+
75
+ # Apply bold formatting to first row if requested
76
+ if bold_headers and row_idx == 0:
77
+ requests.append(
78
+ {
79
+ "updateTextStyle": {
80
+ "range": {
81
+ "startIndex": insertion_index,
82
+ "endIndex": insertion_index + len(cell_text),
83
+ },
84
+ "textStyle": {"bold": True},
85
+ "fields": "bold",
86
+ }
87
+ }
88
+ )
89
+ else:
90
+ # Cell has content, append after existing content
91
+ # Find the end of existing content
92
+ cell_end = cell["end_index"] - 1 # Don't include cell end marker
93
+ requests.append(
94
+ {
95
+ "insertText": {
96
+ "location": {"index": cell_end},
97
+ "text": cell_text,
98
+ }
99
+ }
100
+ )
101
+
102
+ # Apply bold formatting to first row if requested
103
+ if bold_headers and row_idx == 0:
104
+ requests.append(
105
+ {
106
+ "updateTextStyle": {
107
+ "range": {
108
+ "startIndex": cell_end,
109
+ "endIndex": cell_end + len(cell_text),
110
+ },
111
+ "textStyle": {"bold": True},
112
+ "fields": "bold",
113
+ }
114
+ }
115
+ )
116
+
117
+ return requests
118
+
119
+
120
+ def calculate_cell_positions(
121
+ table_start_index: int,
122
+ rows: int,
123
+ cols: int,
124
+ existing_table_data: Optional[Dict[str, Any]] = None,
125
+ ) -> List[List[Dict[str, int]]]:
126
+ """
127
+ Calculate estimated positions for each cell in a table.
128
+
129
+ Args:
130
+ table_start_index: Starting index of the table
131
+ rows: Number of rows
132
+ cols: Number of columns
133
+ existing_table_data: Optional existing table data with actual positions
134
+
135
+ Returns:
136
+ 2D list of cell position dictionaries
137
+ """
138
+ if existing_table_data and "cells" in existing_table_data:
139
+ # Use actual positions from existing table
140
+ return existing_table_data["cells"]
141
+
142
+ # Estimate positions for a new table
143
+ # Note: These are estimates; actual positions depend on content
144
+ cells = []
145
+ current_index = table_start_index + 2 # Account for table start
146
+
147
+ for row_idx in range(rows):
148
+ row_cells = []
149
+ for col_idx in range(cols):
150
+ # Each cell typically starts with a paragraph marker
151
+ cell_start = current_index
152
+ cell_end = current_index + 2 # Minimum cell size
153
+
154
+ row_cells.append(
155
+ {
156
+ "row": row_idx,
157
+ "column": col_idx,
158
+ "start_index": cell_start,
159
+ "end_index": cell_end,
160
+ }
161
+ )
162
+
163
+ current_index = cell_end + 1
164
+
165
+ cells.append(row_cells)
166
+
167
+ return cells
168
+
169
+
170
+ def format_table_data(
171
+ raw_data: Union[List[List[str]], List[str], str],
172
+ ) -> List[List[str]]:
173
+ """
174
+ Normalize various data formats into a 2D array for table insertion.
175
+
176
+ Args:
177
+ raw_data: Data in various formats (2D list, 1D list, or delimited string)
178
+
179
+ Returns:
180
+ Normalized 2D list of strings
181
+ """
182
+ if isinstance(raw_data, str):
183
+ # Parse delimited string (detect delimiter)
184
+ lines = raw_data.strip().split("\n")
185
+ if "\t" in raw_data:
186
+ # Tab-delimited
187
+ return [line.split("\t") for line in lines]
188
+ elif "," in raw_data:
189
+ # Comma-delimited (simple CSV)
190
+ return [line.split(",") for line in lines]
191
+ else:
192
+ # Space-delimited or single column
193
+ return [[cell.strip() for cell in line.split()] for line in lines]
194
+
195
+ elif isinstance(raw_data, list):
196
+ if not raw_data:
197
+ return [[]]
198
+
199
+ # Check if it's already a 2D list
200
+ if isinstance(raw_data[0], list):
201
+ # Ensure all cells are strings
202
+ return [[str(cell) for cell in row] for row in raw_data]
203
+ else:
204
+ # Convert 1D list to single-column table
205
+ return [[str(cell)] for cell in raw_data]
206
+
207
+ else:
208
+ # Convert single value to 1x1 table
209
+ return [[str(raw_data)]]
210
+
211
+
212
+ def create_table_with_data(
213
+ index: int,
214
+ data: List[List[str]],
215
+ headers: Optional[List[str]] = None,
216
+ bold_headers: bool = True,
217
+ ) -> List[Dict[str, Any]]:
218
+ """
219
+ Create a table and populate it with data in one operation.
220
+
221
+ Args:
222
+ index: Position to insert the table
223
+ data: 2D array of table data
224
+ headers: Optional header row (will be prepended to data)
225
+ bold_headers: Whether to make headers bold
226
+
227
+ Returns:
228
+ List of request dictionaries for batch update
229
+ """
230
+ requests = []
231
+
232
+ # Prepare data with headers if provided
233
+ if headers:
234
+ full_data = [headers] + data
235
+ else:
236
+ full_data = data
237
+
238
+ # Normalize the data
239
+ full_data = format_table_data(full_data)
240
+
241
+ if not full_data or not full_data[0]:
242
+ raise ValueError("Cannot create table with empty data")
243
+
244
+ rows = len(full_data)
245
+ cols = len(full_data[0])
246
+
247
+ # Ensure all rows have the same number of columns
248
+ for row in full_data:
249
+ while len(row) < cols:
250
+ row.append("")
251
+
252
+ # Create the table
253
+ requests.append(
254
+ {"insertTable": {"location": {"index": index}, "rows": rows, "columns": cols}}
255
+ )
256
+
257
+ # Build text insertion requests for each cell
258
+ # Note: In practice, we'd need to get the actual document structure
259
+ # after table creation to get accurate indices
260
+
261
+ return requests
262
+
263
+
264
+ def build_table_style_requests(
265
+ table_start_index: int, style_options: Dict[str, Any]
266
+ ) -> List[Dict[str, Any]]:
267
+ """
268
+ Build requests to style a table.
269
+
270
+ Args:
271
+ table_start_index: Starting index of the table
272
+ style_options: Dictionary of style options
273
+ - border_width: Width of borders in points
274
+ - border_color: RGB color for borders
275
+ - background_color: RGB color for cell backgrounds
276
+ - header_background: RGB color for header row background
277
+
278
+ Returns:
279
+ List of request dictionaries for styling
280
+ """
281
+ requests = []
282
+
283
+ style_request = create_update_table_cell_style_request(
284
+ table_start_index=table_start_index,
285
+ background_color=style_options.get("background_color"),
286
+ border_color=style_options.get("border_color"),
287
+ border_width=style_options.get("border_width"),
288
+ border_edges=style_options.get("border_edges"),
289
+ )
290
+ if style_request:
291
+ requests.append(style_request)
292
+
293
+ # Header row specific styling
294
+ if "header_background" in style_options:
295
+ header_request = create_update_table_cell_style_request(
296
+ table_start_index=table_start_index,
297
+ background_color=style_options["header_background"],
298
+ row_index=0,
299
+ column_index=0,
300
+ row_span=1,
301
+ column_span=100, # Large number to cover all columns
302
+ )
303
+ if header_request:
304
+ requests.append(header_request)
305
+
306
+ return requests
307
+
308
+
309
+ def extract_table_as_data(table_info: Dict[str, Any]) -> List[List[str]]:
310
+ """
311
+ Extract table content as a 2D array of strings.
312
+
313
+ Args:
314
+ table_info: Table information from document structure
315
+
316
+ Returns:
317
+ 2D list of cell contents
318
+ """
319
+ data = []
320
+ cells = table_info.get("cells", [])
321
+
322
+ for row in cells:
323
+ row_data = []
324
+ for cell in row:
325
+ row_data.append(cell.get("content", "").strip())
326
+ data.append(row_data)
327
+
328
+ return data
329
+
330
+
331
+ def find_table_by_content(
332
+ tables: List[Dict[str, Any]], search_text: str, case_sensitive: bool = False
333
+ ) -> Optional[int]:
334
+ """
335
+ Find a table index by searching for content within it.
336
+
337
+ Args:
338
+ tables: List of table information from document
339
+ search_text: Text to search for in table cells
340
+ case_sensitive: Whether to do case-sensitive search
341
+
342
+ Returns:
343
+ Index of the first matching table, or None
344
+ """
345
+ search_text = search_text if case_sensitive else search_text.lower()
346
+
347
+ for idx, table in enumerate(tables):
348
+ for row in table.get("cells", []):
349
+ for cell in row:
350
+ cell_content = cell.get("content", "")
351
+ if not case_sensitive:
352
+ cell_content = cell_content.lower()
353
+
354
+ if search_text in cell_content:
355
+ return idx
356
+
357
+ return None
358
+
359
+
360
+ def validate_table_data(data: List[List[str]]) -> Tuple[bool, str]:
361
+ """
362
+ Validates table data format and provides specific error messages for LLMs.
363
+
364
+ WHAT THIS CHECKS:
365
+ - Data is a 2D list (list of lists)
366
+ - All rows have consistent column counts
367
+ - Dimensions are within Google Docs limits
368
+ - No None or undefined values
369
+
370
+ VALID FORMAT EXAMPLE:
371
+ [
372
+ ["Header1", "Header2"], # Row 0 - 2 columns
373
+ ["Data1", "Data2"], # Row 1 - 2 columns
374
+ ["Data3", "Data4"] # Row 2 - 2 columns
375
+ ]
376
+
377
+ INVALID FORMATS:
378
+ - [["col1"], ["col1", "col2"]] # Inconsistent column counts
379
+ - ["col1", "col2"] # Not 2D (missing inner lists)
380
+ - [["col1", None]] # Contains None values
381
+ - [] or [[]] # Empty data
382
+
383
+ Args:
384
+ data: 2D array of data to validate
385
+
386
+ Returns:
387
+ Tuple of (is_valid, error_message_with_examples)
388
+ """
389
+ if not data:
390
+ return (
391
+ False,
392
+ "Data is empty. Use format: [['col1', 'col2'], ['row1col1', 'row1col2']]",
393
+ )
394
+
395
+ if not isinstance(data, list):
396
+ return (
397
+ False,
398
+ f"Data must be a list, got {type(data).__name__}. Use format: [['col1', 'col2'], ['row1col1', 'row1col2']]",
399
+ )
400
+
401
+ if not all(isinstance(row, list) for row in data):
402
+ return (
403
+ False,
404
+ f"Data must be a 2D list (list of lists). Each row must be a list. Check your format: {data}",
405
+ )
406
+
407
+ # Check for consistent column count
408
+ col_counts = [len(row) for row in data]
409
+ if len(set(col_counts)) > 1:
410
+ return (
411
+ False,
412
+ f"All rows must have same number of columns. Found: {col_counts}. Fix your data format.",
413
+ )
414
+
415
+ # Check for reasonable size
416
+ rows = len(data)
417
+ cols = col_counts[0] if col_counts else 0
418
+
419
+ if rows > 1000:
420
+ return False, f"Too many rows ({rows}). Google Docs limit is 1000 rows."
421
+
422
+ if cols > 20:
423
+ return False, f"Too many columns ({cols}). Google Docs limit is 20 columns."
424
+
425
+ return True, f"Valid table data: {rows}x{cols} table format"