@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,3300 @@
1
+ """
2
+ Google Docs MCP Tools
3
+
4
+ This module provides MCP tools for interacting with Google Docs API and managing Google Docs via Drive.
5
+ """
6
+
7
+ import logging
8
+ import asyncio
9
+ import io
10
+ import re
11
+ from typing import List, Any, Literal, Optional, Union
12
+ from urllib.parse import parse_qs, urlsplit
13
+
14
+ from typing_extensions import TypedDict
15
+
16
+ from googleapiclient.errors import HttpError
17
+ from googleapiclient.http import MediaIoBaseUpload
18
+
19
+ from mcp.types import ToolAnnotations
20
+
21
+ # Auth & server utilities
22
+ from auth.service_decorator import require_google_service, require_multiple_services
23
+ from core.file_limits import (
24
+ FileTooLargeError,
25
+ download_media_bytes,
26
+ ensure_within_file_size_limit,
27
+ )
28
+ from core.utils import (
29
+ GOOGLE_API_WRITE_RETRIES,
30
+ OfficeXmlExtractionError,
31
+ OfficeXmlTooLargeError,
32
+ extract_office_xml_text,
33
+ handle_http_errors,
34
+ UserInputError,
35
+ )
36
+ from core.server import server
37
+ from core.comments import create_comment_tools
38
+ from gdocs.docs_comments import insert_anchored_comment
39
+
40
+ # Import helper functions for document operations
41
+ from gdocs.docs_helpers import (
42
+ create_insert_text_request,
43
+ create_delete_range_request,
44
+ create_format_text_request,
45
+ create_find_replace_request,
46
+ create_insert_table_request,
47
+ create_insert_page_break_request,
48
+ create_insert_image_request,
49
+ create_bullet_list_request,
50
+ create_delete_bullet_list_request,
51
+ create_insert_doc_tab_request,
52
+ create_update_doc_tab_request,
53
+ create_delete_doc_tab_request,
54
+ validate_suggestions_view_mode,
55
+ validate_write_mode,
56
+ build_batch_update_body,
57
+ suggestion_save_error,
58
+ create_update_paragraph_style_request,
59
+ extract_text_from_elements,
60
+ process_tab_hierarchy,
61
+ )
62
+
63
+ # Import document structure and table utilities
64
+ from gdocs.docs_structure import (
65
+ parse_document_structure,
66
+ find_tables,
67
+ analyze_document_complexity,
68
+ summarize_paragraph_layout,
69
+ truncate_preview,
70
+ find_heading_section,
71
+ heading_section_document,
72
+ )
73
+ from gdocs.docs_tables import extract_table_as_data
74
+ from gdocs.docs_markdown import (
75
+ convert_doc_to_markdown,
76
+ format_comments_inline,
77
+ format_comments_appendix,
78
+ parse_drive_comments,
79
+ )
80
+ from gdocs.docs_markdown_writer import (
81
+ build_markdown_insert_requests,
82
+ build_section_markdown_requests,
83
+ markdown_to_docs_requests,
84
+ )
85
+ from gdocs.docs_plain_text import render_doc_to_plain_text
86
+ from gdocs.operation_schemas import BatchDocOperations, ParagraphBorderEdge
87
+
88
+ # Import operation managers for complex business logic
89
+ from gdocs.managers import (
90
+ TableOperationManager,
91
+ HeaderFooterManager,
92
+ ValidationManager,
93
+ BatchOperationManager,
94
+ )
95
+ from gdrive.drive_helpers import (
96
+ escape_drive_query_value,
97
+ flag_incomplete_search,
98
+ move_new_file_to_folder,
99
+ )
100
+ import json
101
+
102
+ logger = logging.getLogger(__name__)
103
+ HEADER_FOOTER_RUNTIME_CANARY = "docs-hf-canary-20260328b"
104
+
105
+ # Field mask for inspect_doc_structure. It must name every field the structure
106
+ # parser reads and nothing more: dropping per-run textStyle and the suggestion
107
+ # bookkeeping stops a summary call from paying to serialize the whole document
108
+ # (issue #1052). Keep in sync with gdocs/docs_structure.py.
109
+ _STRUCTURE_CONTENT_FIELDS = (
110
+ "content("
111
+ "startIndex,endIndex,"
112
+ "paragraph(elements(startIndex,endIndex,textRun/content),paragraphStyle,bullet,"
113
+ "positionedObjectIds,suggestedPositionedObjectIds),"
114
+ "table(tableRows/tableCells(startIndex,endIndex,content),tableStyle),"
115
+ "sectionBreak/sectionStyle,"
116
+ "tableOfContents"
117
+ ")"
118
+ )
119
+ # headers/footers are maps and childTabs is recursive, so neither is sub-masked:
120
+ # both stay whole, which costs little and cannot silently drop content.
121
+ # With includeTabsContent=True the API rejects legacy top-level text fields in
122
+ # the mask (issue #1108), so everything but the title is read from tabs.
123
+ _STRUCTURE_FIELDS = (
124
+ f"title,tabs(tabProperties,childTabs,documentTab("
125
+ f"documentStyle,namedRanges,headers,footers,body({_STRUCTURE_CONTENT_FIELDS})))"
126
+ )
127
+
128
+
129
+ def _find_tab(tabs: list, target_tab_id: str) -> Optional[dict]:
130
+ """Find a tab by ID anywhere in the document's tab tree."""
131
+ for tab in tabs:
132
+ if tab.get("tabProperties", {}).get("tabId") == target_tab_id:
133
+ return tab
134
+ found = _find_tab(tab.get("childTabs", []), target_tab_id)
135
+ if found:
136
+ return found
137
+ return None
138
+
139
+
140
+ def _tab_title(tab: dict) -> str:
141
+ """Human-readable title for a tab, for use in output headers."""
142
+ return tab.get("tabProperties", {}).get("title", "Untitled Tab")
143
+
144
+
145
+ def _parse_doc_reference(
146
+ document_id: str, tab_id: Optional[str]
147
+ ) -> tuple[str, Optional[str], bool]:
148
+ """Split a document ID or URL into (document_id, tab_id, tab_from_url).
149
+
150
+ A URL's ?tab= selects that tab unless tab_id was passed explicitly.
151
+ """
152
+ url_match = re.search(r"/d/([\w-]+)", document_id)
153
+ if not url_match:
154
+ return document_id, tab_id, False
155
+ url_tabs = parse_qs(urlsplit(document_id).query).get("tab", [])
156
+ if tab_id is None and url_tabs:
157
+ return url_match.group(1), url_tabs[0], True
158
+ return url_match.group(1), tab_id, False
159
+
160
+
161
+ def _url_tab_notice(tabs: list, tab: dict, tab_id: str) -> str:
162
+ """Say when a tab picked from a URL hid other tabs.
163
+
164
+ Browsers add ?tab= to every Docs URL, so the caller may not expect it.
165
+ """
166
+ if tabs == [tab] and not tab.get("childTabs"):
167
+ return ""
168
+ return (
169
+ f"Showing only tab '{_tab_title(tab)}' ({tab_id}) from the URL; "
170
+ 'pass tab_id="" to read every tab.'
171
+ )
172
+
173
+
174
+ @server.tool(
175
+ title="Search Docs",
176
+ annotations=ToolAnnotations(
177
+ readOnlyHint=True,
178
+ destructiveHint=False,
179
+ idempotentHint=True,
180
+ openWorldHint=True,
181
+ ),
182
+ )
183
+ @handle_http_errors("search_docs", is_read_only=True, service_type="docs")
184
+ @require_google_service("drive", "drive_read")
185
+ async def search_docs(
186
+ service: Any,
187
+ user_google_email: str,
188
+ query: str,
189
+ page_size: int = 10,
190
+ page_token: Optional[str] = None,
191
+ corpora: Optional[str] = None,
192
+ drive_id: Optional[str] = None,
193
+ ) -> str:
194
+ """
195
+ Searches for Google Docs by name using Drive API (mimeType filter).
196
+
197
+ Args:
198
+ user_google_email: The user's Google email address.
199
+ query: Text to search for in document names.
200
+ page_size: Maximum number of documents to return. Defaults to 10.
201
+ page_token: Page token from a previous response's nextPageToken to
202
+ retrieve the next page of results.
203
+ corpora: Corpus to search ('user', 'domain', 'drive', 'allDrives').
204
+ Defaults to 'drive' when drive_id is set, otherwise 'allDrives'.
205
+ drive_id: Optional shared drive ID to search.
206
+
207
+ Returns:
208
+ str: A formatted list of Google Docs matching the search query.
209
+ Includes a nextPageToken line when more results are available.
210
+ """
211
+ logger.info(f"[search_docs] Email={user_google_email}, query_len={len(query)}")
212
+ logger.debug(f"[search_docs] Query='{query}'")
213
+
214
+ escaped_query = escape_drive_query_value(query)
215
+
216
+ response = await asyncio.to_thread(
217
+ service.files()
218
+ .list(
219
+ q=f"name contains '{escaped_query}' and mimeType='application/vnd.google-apps.document' and trashed=false",
220
+ pageSize=page_size,
221
+ pageToken=page_token,
222
+ fields="nextPageToken, incompleteSearch, files(id, name, createdTime, modifiedTime, webViewLink)",
223
+ supportsAllDrives=True,
224
+ includeItemsFromAllDrives=True,
225
+ corpora=corpora or ("drive" if drive_id else "allDrives"),
226
+ driveId=drive_id,
227
+ )
228
+ .execute
229
+ )
230
+ files = response.get("files", [])
231
+ next_token = response.get("nextPageToken")
232
+ if not files and not next_token:
233
+ return flag_incomplete_search(
234
+ f"No Google Docs found matching '{query}'.", response
235
+ )
236
+
237
+ output = [f"Found {len(files)} Google Docs matching '{query}':"]
238
+ for f in files:
239
+ output.append(
240
+ f"- {f['name']} (ID: {f['id']}) Modified: {f.get('modifiedTime')} Link: {f.get('webViewLink')}"
241
+ )
242
+ if next_token:
243
+ output.append(f"nextPageToken: {next_token}")
244
+ return flag_incomplete_search("\n".join(output), response)
245
+
246
+
247
+ @server.tool(
248
+ title="Get Doc Content",
249
+ annotations=ToolAnnotations(
250
+ readOnlyHint=True,
251
+ destructiveHint=False,
252
+ idempotentHint=True,
253
+ openWorldHint=True,
254
+ ),
255
+ )
256
+ @handle_http_errors("get_doc_content", is_read_only=True, service_type="docs")
257
+ @require_multiple_services(
258
+ [
259
+ {
260
+ "service_type": "drive",
261
+ "scopes": "drive_read",
262
+ "param_name": "drive_service",
263
+ },
264
+ {"service_type": "docs", "scopes": "docs_read", "param_name": "docs_service"},
265
+ ]
266
+ )
267
+ async def get_doc_content(
268
+ drive_service: Any,
269
+ docs_service: Any,
270
+ user_google_email: str,
271
+ document_id: str,
272
+ suggestions_view_mode: str = "DEFAULT_FOR_CURRENT_ACCESS",
273
+ tab_id: Optional[str] = None,
274
+ preserve_context: bool = False,
275
+ heading: Optional[str] = None,
276
+ heading_level: Optional[int] = None,
277
+ ) -> str:
278
+ """
279
+ Retrieves content of a Google Doc or a Drive file (like .docx) identified by document_id.
280
+ - Native Google Docs: Fetches content via Docs API.
281
+ - Office files (.docx, etc.) stored in Drive: Downloads via Drive API and extracts text.
282
+
283
+ By default, native Google Docs text is index-aligned with the document:
284
+ empty paragraphs are preserved and every non-text element that occupies an
285
+ index (inline object, page break, footnote reference, ...) is rendered as one
286
+ U+FFFC placeholder per index. The document body starts at index 1, so an
287
+ offset n into the text that follows "--- CONTENT ---" is document index n + 1,
288
+ and that index can be passed straight to format_text or delete_text. Tables
289
+ and multi-tab documents interleave separators, so alignment holds up to the
290
+ first table or tab header.
291
+
292
+ Set preserve_context=True for readable link destinations, internal targets,
293
+ smart-chip values, table boundaries, headers, footers, footnotes, and object
294
+ context exposed by the Docs API. This output is plain text, not Markdown,
295
+ and its offsets must not be used as document editing indices. Comments,
296
+ revision history, exact visual layout, and chip details hidden by the API
297
+ are not included. Use get_doc_as_markdown for formatting or comments.
298
+
299
+ Args:
300
+ user_google_email: User's Google email address
301
+ document_id: ID of the Google Doc or Drive file (or full URL). A Docs
302
+ URL's ?tab= selects that tab unless tab_id is also specified.
303
+ suggestions_view_mode: How to render suggestions in the returned content:
304
+ - "DEFAULT_FOR_CURRENT_ACCESS": Default based on user's access level
305
+ - "SUGGESTIONS_INLINE": Suggested changes appear inline in the document
306
+ - "PREVIEW_SUGGESTIONS_ACCEPTED": Preview as if all suggestions were accepted
307
+ - "PREVIEW_WITHOUT_SUGGESTIONS": Preview as if all suggestions were rejected
308
+ tab_id: Optional ID of a single tab to read (from inspect_doc_structure).
309
+ When given, only that tab's content is returned with no tab separator,
310
+ so the default output stays index-aligned with that tab. When
311
+ omitted, every tab is returned with "--- TAB: ... ---" markers.
312
+ Pass "" to read every tab of a URL that carries ?tab=. This
313
+ filters output only: the whole document is still fetched.
314
+ preserve_context: Include readable semantic annotations for native Docs.
315
+ Defaults to False to retain index alignment. Office extraction is
316
+ unaffected. With tab_id, only the selected tab is rendered.
317
+ heading: Text of a body heading (case-insensitive, must match exactly one)
318
+ whose section to return instead of the whole document: the heading and
319
+ everything below it up to the next heading of equal or shallower level.
320
+ The header reports the section's start index s, and in the default
321
+ output offset n is document index n + s. Native Google Docs only;
322
+ tab_id is required when the doc has multiple tabs.
323
+ heading_level: Optional 1-6 heading level to narrow the heading match.
324
+
325
+ Returns:
326
+ str: The document content with metadata header.
327
+ """
328
+ validation_error = validate_suggestions_view_mode(suggestions_view_mode)
329
+ if validation_error:
330
+ return validation_error
331
+ document_id, tab_id, tab_from_url = _parse_doc_reference(document_id, tab_id)
332
+ logger.info(
333
+ f"[get_doc_content] Invoked. Document/File ID: '{document_id}', tab: '{tab_id}' for user '{user_google_email}'"
334
+ )
335
+
336
+ file_metadata = await asyncio.to_thread(
337
+ drive_service.files()
338
+ .get(
339
+ fileId=document_id,
340
+ fields="id, name, mimeType, webViewLink, size",
341
+ supportsAllDrives=True,
342
+ )
343
+ .execute
344
+ )
345
+ mime_type = file_metadata.get("mimeType", "")
346
+ file_name = file_metadata.get("name", "Unknown File")
347
+ web_view_link = file_metadata.get("webViewLink", "#")
348
+
349
+ logger.info(
350
+ f"[get_doc_content] File '{file_name}' (ID: {document_id}) has mimeType: '{mime_type}'"
351
+ )
352
+
353
+ body_text = ""
354
+ notice = ""
355
+
356
+ if mime_type == "application/vnd.google-apps.document":
357
+ logger.info("[get_doc_content] Processing as native Google Doc.")
358
+ doc_data = await asyncio.to_thread(
359
+ docs_service.documents()
360
+ .get(
361
+ documentId=document_id,
362
+ includeTabsContent=True,
363
+ suggestionsViewMode=suggestions_view_mode,
364
+ )
365
+ .execute
366
+ )
367
+ if heading is not None:
368
+ section = heading_section_document(doc_data, heading, heading_level, tab_id)
369
+ content = section["body"]["content"]
370
+ notice = (
371
+ f"Showing only the section under heading {heading!r}, "
372
+ f"starting at document index {content[0]['startIndex']}."
373
+ )
374
+ if tab_from_url:
375
+ tabs = doc_data.get("tabs", [])
376
+ tab_notice = _url_tab_notice(tabs, _find_tab(tabs, tab_id), tab_id)
377
+ notice = f"{tab_notice} {notice}".lstrip()
378
+ body_text = (
379
+ render_doc_to_plain_text(section, tab_id)
380
+ if preserve_context
381
+ else extract_text_from_elements(content)
382
+ )
383
+ elif tab_id:
384
+ tabs = doc_data.get("tabs", [])
385
+ tab = _find_tab(tabs, tab_id)
386
+ if tab is None:
387
+ return f"Error: Tab {tab_id} not found in document."
388
+ if "documentTab" not in tab:
389
+ return f"Error: Tab {tab_id} is not a document tab and has no body content."
390
+ if tab_from_url:
391
+ notice = _url_tab_notice(tabs, tab, tab_id)
392
+ # No tab separator: the caller named one tab. The default output
393
+ # stays index-aligned; context annotations are opt-in.
394
+ file_name = f"{file_name} [tab: {_tab_title(tab)}]"
395
+ if preserve_context:
396
+ body_text = render_doc_to_plain_text(tab["documentTab"], tab_id)
397
+ else:
398
+ body_text = extract_text_from_elements(
399
+ tab["documentTab"].get("body", {}).get("content", [])
400
+ )
401
+ elif preserve_context:
402
+ body_text = render_doc_to_plain_text(doc_data)
403
+ else:
404
+ processed_text_lines = []
405
+
406
+ # Truthiness, not .strip(): a body or tab made up entirely of empty
407
+ # paragraphs still occupies indices, so dropping it would reintroduce
408
+ # the drift this alignment exists to prevent.
409
+ body_elements = doc_data.get("body", {}).get("content", [])
410
+ main_content = extract_text_from_elements(body_elements)
411
+ if main_content:
412
+ processed_text_lines.append(main_content)
413
+
414
+ for tab in doc_data.get("tabs", []):
415
+ tab_content = process_tab_hierarchy(tab)
416
+ if tab_content:
417
+ processed_text_lines.append(tab_content)
418
+
419
+ body_text = "".join(processed_text_lines)
420
+ elif heading is not None:
421
+ return "Error: 'heading' is only supported for native Google Docs."
422
+ else:
423
+ logger.info(
424
+ f"[get_doc_content] Processing as Drive file (e.g., .docx, other). MimeType: {mime_type}"
425
+ )
426
+
427
+ export_mime_type_map = {
428
+ # Example: "application/vnd.google-apps.spreadsheet"z: "text/csv",
429
+ # Native GSuite types that are not Docs would go here if this function
430
+ # was intended to export them. For .docx, direct download is used.
431
+ }
432
+ effective_export_mime = export_mime_type_map.get(mime_type)
433
+
434
+ # Declared Drive size applies to binary downloads (not GSuite exports).
435
+ if not effective_export_mime:
436
+ try:
437
+ ensure_within_file_size_limit(
438
+ file_metadata.get("size"),
439
+ file_name=file_name,
440
+ file_id=document_id,
441
+ web_view_link=web_view_link,
442
+ )
443
+ except FileTooLargeError as e:
444
+ return str(e)
445
+
446
+ request_obj = (
447
+ drive_service.files().export_media(
448
+ fileId=document_id,
449
+ mimeType=effective_export_mime,
450
+ supportsAllDrives=True,
451
+ )
452
+ if effective_export_mime
453
+ else drive_service.files().get_media(
454
+ fileId=document_id, supportsAllDrives=True
455
+ )
456
+ )
457
+
458
+ try:
459
+ file_content_bytes = await download_media_bytes(
460
+ request_obj,
461
+ file_name=file_name,
462
+ file_id=document_id,
463
+ web_view_link=web_view_link,
464
+ )
465
+ except FileTooLargeError as e:
466
+ return str(e)
467
+
468
+ try:
469
+ office_text = extract_office_xml_text(file_content_bytes, mime_type)
470
+ except OfficeXmlTooLargeError as e:
471
+ # Not damaged, and not to be retried as raw text: say what happened.
472
+ office_text = f"[Could not read '{mime_type}' file - {e}]"
473
+ except OfficeXmlExtractionError as e:
474
+ office_text = (
475
+ f"[Could not read '{mime_type}' file - it appears damaged or is "
476
+ f"not a valid Office document: {e}]"
477
+ )
478
+ if office_text:
479
+ body_text = office_text
480
+ else:
481
+ try:
482
+ body_text = file_content_bytes.decode("utf-8")
483
+ except UnicodeDecodeError:
484
+ body_text = (
485
+ f"[Binary or unsupported text encoding for mimeType '{mime_type}' - "
486
+ f"{len(file_content_bytes)} bytes]"
487
+ )
488
+
489
+ # The notice stays above the content marker so content offsets keep their
490
+ # alignment with document indices.
491
+ header = (
492
+ f'File: "{file_name}" (ID: {document_id}, Type: {mime_type})\n'
493
+ f"Link: {web_view_link}\n"
494
+ + (f"{notice}\n" if notice else "")
495
+ + "\n--- CONTENT ---\n"
496
+ )
497
+ return header + body_text
498
+
499
+
500
+ @server.tool(
501
+ title="List Docs in Folder",
502
+ annotations=ToolAnnotations(
503
+ readOnlyHint=True,
504
+ destructiveHint=False,
505
+ idempotentHint=True,
506
+ openWorldHint=True,
507
+ ),
508
+ )
509
+ @handle_http_errors("list_docs_in_folder", is_read_only=True, service_type="docs")
510
+ @require_google_service("drive", "drive_read")
511
+ async def list_docs_in_folder(
512
+ service: Any,
513
+ user_google_email: str,
514
+ folder_id: str = "root",
515
+ page_size: int = 100,
516
+ page_token: Optional[str] = None,
517
+ ) -> str:
518
+ """
519
+ Lists Google Docs within a specific Drive folder.
520
+
521
+ Args:
522
+ user_google_email: The user's Google email address.
523
+ folder_id: ID of the Drive folder to list. Defaults to 'root'.
524
+ page_size: Maximum number of documents to return. Defaults to 100.
525
+ page_token: Page token from a previous response's nextPageToken to
526
+ retrieve the next page of results.
527
+
528
+ Returns:
529
+ str: A formatted list of Google Docs in the specified folder.
530
+ Includes a nextPageToken line when more results are available.
531
+ """
532
+ logger.info(
533
+ f"[list_docs_in_folder] Invoked. Email: '{user_google_email}', Folder ID: '{folder_id}'"
534
+ )
535
+
536
+ rsp = await asyncio.to_thread(
537
+ service.files()
538
+ .list(
539
+ q=f"'{folder_id}' in parents and mimeType='application/vnd.google-apps.document' and trashed=false",
540
+ pageSize=page_size,
541
+ pageToken=page_token,
542
+ fields="nextPageToken, files(id, name, modifiedTime, webViewLink)",
543
+ supportsAllDrives=True,
544
+ includeItemsFromAllDrives=True,
545
+ )
546
+ .execute
547
+ )
548
+ items = rsp.get("files", [])
549
+ next_token = rsp.get("nextPageToken")
550
+ if not items and not next_token:
551
+ return f"No Google Docs found in folder '{folder_id}'."
552
+ out = [f"Found {len(items)} Docs in folder '{folder_id}':"]
553
+ for f in items:
554
+ out.append(
555
+ f"- {f['name']} (ID: {f['id']}) Modified: {f.get('modifiedTime')} Link: {f.get('webViewLink')}"
556
+ )
557
+ if next_token:
558
+ out.append(f"nextPageToken: {next_token}")
559
+ return "\n".join(out)
560
+
561
+
562
+ @server.tool(
563
+ title="Create Doc",
564
+ annotations=ToolAnnotations(
565
+ readOnlyHint=False,
566
+ destructiveHint=False,
567
+ idempotentHint=False,
568
+ openWorldHint=True,
569
+ ),
570
+ )
571
+ @handle_http_errors("create_doc", service_type="docs")
572
+ @require_google_service("docs", "docs_write")
573
+ async def create_doc(
574
+ service: Any,
575
+ user_google_email: str,
576
+ title: str,
577
+ content: str = "",
578
+ folder_id: str = "root",
579
+ ) -> str:
580
+ """
581
+ Creates a new Google Doc and optionally inserts initial content.
582
+
583
+ `content` is inserted as plain text (Markdown is not rendered); use
584
+ import_to_google_doc to create a doc from Markdown.
585
+
586
+ After creation, the document body starts at index 1. A new empty doc
587
+ has total length 2 (one section break at index 0, one newline at index 1).
588
+
589
+ To build a rich document after creation, use batch_update_doc with
590
+ insert_text operations using end_of_segment=true to append content
591
+ sequentially without calculating indices. Then call inspect_doc_structure
592
+ to get exact positions before applying formatting in a separate batch call.
593
+
594
+ Args:
595
+ user_google_email: User's Google email address
596
+ title: Title of the new document
597
+ content: Optional initial plain text content to insert
598
+ folder_id: The ID of the parent folder. Defaults to 'root'. For shared
599
+ drives, this must be a folder ID within the shared drive.
600
+
601
+ Returns:
602
+ str: Confirmation message with document ID, link, and initial document state.
603
+ """
604
+ logger.info(
605
+ f"[create_doc] Invoked. Email: '{user_google_email}', title_len={len(title)}, "
606
+ f"folder_id='{folder_id}'"
607
+ )
608
+
609
+ doc = await asyncio.to_thread(
610
+ service.documents().create(body={"title": title}).execute
611
+ )
612
+ doc_id = doc.get("documentId")
613
+
614
+ placement_note = await move_new_file_to_folder(
615
+ user_google_email, doc_id, folder_id, "create_doc"
616
+ )
617
+
618
+ if content:
619
+ requests = [{"insertText": {"location": {"index": 1}, "text": content}}]
620
+ await asyncio.to_thread(
621
+ service.documents()
622
+ .batchUpdate(documentId=doc_id, body={"requests": requests})
623
+ .execute
624
+ )
625
+ link = f"https://docs.google.com/document/d/{doc_id}/edit"
626
+ if content:
627
+ content_note = f"Initial content: {len(content)} characters inserted."
628
+ else:
629
+ content_note = "Document is empty (body starts at index 1, total length 2)."
630
+ msg = (
631
+ f"Created Google Doc '{title}' (ID: {doc_id}) for {user_google_email}."
632
+ f"{placement_note} "
633
+ f"{content_note} "
634
+ f"Use batch_update_doc with end_of_segment=true to append content. "
635
+ f"Link: {link}"
636
+ )
637
+ logger.info(
638
+ f"Successfully created Google Doc (ID: {doc_id}) for {user_google_email}. Link: {link}"
639
+ )
640
+ return msg
641
+
642
+
643
+ async def _modify_doc_text_by_heading(
644
+ service: Any,
645
+ document_id: str,
646
+ heading: str,
647
+ heading_level: Optional[int],
648
+ text: Optional[str],
649
+ tab_id: Optional[str],
650
+ segment_id: Optional[str],
651
+ start_index: Optional[int],
652
+ end_index: Optional[int],
653
+ end_of_segment: bool,
654
+ formatting_params: list,
655
+ validator: ValidationManager,
656
+ write_mode: str,
657
+ ) -> str:
658
+ """Replace, append to, or format the section under ``heading`` in one guarded write."""
659
+ has_formatting = any(p is not None for p in formatting_params)
660
+ if not heading.strip():
661
+ return "Error: 'heading' must not be empty."
662
+ if start_index is not None or end_index is not None:
663
+ return "Error: 'start_index'/'end_index' cannot be combined with 'heading'; the section range is resolved from the heading."
664
+ if segment_id is not None:
665
+ return "Error: 'heading' addresses the document body only; 'segment_id' cannot be combined with it."
666
+ if heading_level is not None and not 1 <= heading_level <= 6:
667
+ return "Error: 'heading_level' must be between 1 and 6."
668
+ if text is not None and has_formatting:
669
+ return "Error: In heading mode 'text' is rendered as Markdown; use Markdown syntax for inline formatting instead of formatting parameters."
670
+ if text is None and end_of_segment:
671
+ return "Error: end_of_segment cannot be used when applying formatting."
672
+ if has_formatting:
673
+ is_valid, error_msg = validator.validate_text_formatting_params(
674
+ *formatting_params
675
+ )
676
+ if not is_valid:
677
+ return f"Error: {error_msg}"
678
+
679
+ doc = await asyncio.to_thread(
680
+ service.documents().get(documentId=document_id, includeTabsContent=True).execute
681
+ )
682
+ section = find_heading_section(doc, heading, heading_level, tab_id)
683
+ body_start, section_end = section["body_start"], section["section_end"]
684
+ body_is_empty = section_end <= body_start
685
+
686
+ if text is None:
687
+ if body_is_empty:
688
+ return f"Error: The section under heading {heading!r} has no content to format."
689
+ requests = [
690
+ create_format_text_request(
691
+ body_start, section_end, *formatting_params, tab_id, None
692
+ )
693
+ ]
694
+ operation = f"Applied formatting to section {body_start}-{section_end} under heading {heading!r}"
695
+ else:
696
+ if not end_of_segment and section["footnote_refs"]:
697
+ raise UserInputError(
698
+ f"The section under heading {heading!r} contains "
699
+ f"{section['footnote_refs']} footnote reference(s); replacing it would "
700
+ "detach them. Use end_of_segment=true to append, or edit by index."
701
+ )
702
+ requests = build_section_markdown_requests(
703
+ section, text, end_of_segment, tab_id
704
+ )
705
+ if not requests:
706
+ return "Error: 'text' rendered to no content; nothing to insert."
707
+ verb = "Appended to" if end_of_segment or body_is_empty else "Replaced"
708
+ operation = f"{verb} section under heading {heading!r}"
709
+
710
+ body = build_batch_update_body(requests, write_mode)
711
+ if doc.get("revisionId"):
712
+ body.setdefault("writeControl", {})["requiredRevisionId"] = doc["revisionId"]
713
+ result = await asyncio.to_thread(
714
+ service.documents().batchUpdate(documentId=document_id, body=body).execute
715
+ )
716
+ save_error = suggestion_save_error(result, write_mode)
717
+ if save_error:
718
+ return f"Error: {save_error}"
719
+
720
+ if write_mode == "SUGGEST":
721
+ operation = f"Suggested: {operation}"
722
+ link = f"https://docs.google.com/document/d/{document_id}/edit"
723
+ return f"{operation} in document {document_id}. Link: {link}"
724
+
725
+
726
+ @server.tool(
727
+ title="Modify Doc Text",
728
+ annotations=ToolAnnotations(
729
+ readOnlyHint=False,
730
+ destructiveHint=True,
731
+ idempotentHint=False,
732
+ openWorldHint=True,
733
+ ),
734
+ )
735
+ @handle_http_errors("modify_doc_text", service_type="docs")
736
+ @require_google_service("docs", "docs_write")
737
+ async def modify_doc_text(
738
+ service: Any,
739
+ user_google_email: str,
740
+ document_id: str,
741
+ start_index: Optional[int] = None,
742
+ end_index: Optional[int] = None,
743
+ text: Optional[str] = None,
744
+ heading: Optional[str] = None,
745
+ heading_level: Optional[int] = None,
746
+ tab_id: Optional[str] = None,
747
+ segment_id: Optional[str] = None,
748
+ end_of_segment: bool = False,
749
+ bold: Optional[bool] = None,
750
+ italic: Optional[bool] = None,
751
+ underline: Optional[bool] = None,
752
+ strikethrough: Optional[bool] = None,
753
+ font_size: Optional[float] = None,
754
+ font_family: Optional[str] = None,
755
+ font_weight: Optional[int] = None,
756
+ text_color: Optional[str] = None,
757
+ background_color: Optional[str] = None,
758
+ link_url: Optional[str] = None,
759
+ clear_link: Optional[bool] = None,
760
+ baseline_offset: Optional[str] = None,
761
+ small_caps: Optional[bool] = None,
762
+ write_mode: str = "EDIT",
763
+ ) -> str:
764
+ """
765
+ Modifies text in a Google Doc - can insert/replace text and/or apply formatting in a single operation.
766
+
767
+ TIP: To append text to the end of the document without calculating indices,
768
+ set end_of_segment=true. This avoids index calculation errors.
769
+
770
+ HEADING MODE: Pass heading instead of start_index to edit the body below a
771
+ heading, up to the next heading of equal or shallower level. text is
772
+ rendered as Markdown and replaces that body; end_of_segment=true appends
773
+ instead. Formatting parameters without text format the whole body.
774
+
775
+ For ordinary header/footer text, prefer update_doc_headers_footers.
776
+ Only pass segment_id when you already have a real header/footer/footnote
777
+ segment ID from inspect_doc_structure output. Do not guess IDs such as
778
+ "kix.header" or "kix.footer".
779
+
780
+ Args:
781
+ user_google_email: User's Google email address
782
+ document_id: ID of the document to update
783
+ start_index: Start position for operation using Docs API indices from
784
+ inspect_doc_structure. For the main body, 0 is also accepted as an
785
+ alias for the first writable position. Required unless heading is set.
786
+ end_index: End position for text replacement/formatting (if not provided with text, text is inserted)
787
+ text: New text to insert or replace with (optional - can format existing text without changing it).
788
+ Rendered as Markdown when heading is set.
789
+ heading: Text of a body heading (case-insensitive, must match exactly one) whose
790
+ section to edit instead of start_index/end_index
791
+ heading_level: Optional 1-6 heading level to narrow the heading match
792
+ tab_id: Optional document tab ID to target (required with heading when the doc has multiple tabs)
793
+ segment_id: Optional header/footer/footnote segment ID to target
794
+ end_of_segment: Insert text at the end of the targeted segment instead of start_index
795
+ bold: Whether to make text bold (True/False/None to leave unchanged)
796
+ italic: Whether to make text italic (True/False/None to leave unchanged)
797
+ underline: Whether to underline text (True/False/None to leave unchanged)
798
+ strikethrough: Whether to strike through text (True/False/None to leave unchanged)
799
+ font_size: Font size in points
800
+ font_family: Font family name (e.g., "Arial", "Times New Roman")
801
+ font_weight: Font weight (100-900 in steps of 100; requires font_family)
802
+ text_color: Foreground text color (#RRGGBB)
803
+ background_color: Background/highlight color (#RRGGBB)
804
+ link_url: Hyperlink URL (http/https)
805
+ clear_link: Remove hyperlink from the target range
806
+ baseline_offset: One of NONE, SUPERSCRIPT, SUBSCRIPT
807
+ small_caps: Whether to apply small caps
808
+ write_mode: "EDIT" (default) applies the change directly; "SUGGEST"
809
+ records it as a suggested edit that collaborators can accept or reject
810
+
811
+ Returns:
812
+ str: Confirmation message with operation details
813
+ """
814
+ logger.info(
815
+ f"[modify_doc_text] Doc={document_id}, start={start_index}, end={end_index}, text={text is not None}, "
816
+ f"formatting={any(p is not None for p in [bold, italic, underline, strikethrough, font_size, font_family, font_weight, text_color, background_color, link_url, clear_link, baseline_offset, small_caps])}"
817
+ )
818
+
819
+ # Input validation
820
+ validator = ValidationManager()
821
+
822
+ is_valid, error_msg = validator.validate_document_id(document_id)
823
+ if not is_valid:
824
+ return f"Error: {error_msg}"
825
+
826
+ write_mode_error = validate_write_mode(write_mode)
827
+ if write_mode_error:
828
+ return write_mode_error
829
+
830
+ # Validate that we have something to do
831
+ formatting_params = [
832
+ bold,
833
+ italic,
834
+ underline,
835
+ strikethrough,
836
+ font_size,
837
+ font_family,
838
+ font_weight,
839
+ text_color,
840
+ background_color,
841
+ link_url,
842
+ clear_link,
843
+ baseline_offset,
844
+ small_caps,
845
+ ]
846
+ if text is None and not any(p is not None for p in formatting_params):
847
+ return "Error: Must provide either 'text' to insert/replace, or formatting parameters (bold, italic, underline, strikethrough, font_size, font_family, font_weight, text_color, background_color, link_url, clear_link, baseline_offset, small_caps)."
848
+
849
+ if heading is not None:
850
+ return await _modify_doc_text_by_heading(
851
+ service,
852
+ document_id,
853
+ heading,
854
+ heading_level,
855
+ text,
856
+ tab_id,
857
+ segment_id,
858
+ start_index,
859
+ end_index,
860
+ end_of_segment,
861
+ formatting_params,
862
+ validator,
863
+ write_mode,
864
+ )
865
+ if start_index is None:
866
+ return "Error: 'start_index' is required unless 'heading' is provided."
867
+
868
+ # Validate text formatting params if provided
869
+ if any(p is not None for p in formatting_params):
870
+ is_valid, error_msg = validator.validate_text_formatting_params(
871
+ bold,
872
+ italic,
873
+ underline,
874
+ strikethrough,
875
+ font_size,
876
+ font_family,
877
+ font_weight,
878
+ text_color,
879
+ background_color,
880
+ link_url,
881
+ clear_link,
882
+ baseline_offset,
883
+ small_caps,
884
+ )
885
+ if not is_valid:
886
+ return f"Error: {error_msg}"
887
+
888
+ # For formatting, we need end_index
889
+ if end_index is None:
890
+ return "Error: 'end_index' is required when applying formatting."
891
+ if end_of_segment:
892
+ return "Error: end_of_segment cannot be used when applying formatting."
893
+
894
+ is_valid, error_msg = validator.validate_index_range(start_index, end_index)
895
+ if not is_valid:
896
+ return f"Error: {error_msg}"
897
+
898
+ requests = []
899
+ operations = []
900
+
901
+ # Handle text insertion/replacement
902
+ if text is not None:
903
+ if end_index is not None and end_index > start_index:
904
+ # Text replacement
905
+ if end_of_segment:
906
+ return "Error: end_of_segment cannot be combined with text replacement."
907
+ if start_index == 0 and segment_id is None and tab_id is None:
908
+ # Special case: Cannot delete at index 0 (first section break)
909
+ # Instead, we insert new text at index 1 and then delete the old text
910
+ requests.append(
911
+ create_insert_text_request(1, text, tab_id, segment_id=segment_id)
912
+ )
913
+ adjusted_end = end_index + len(text)
914
+ requests.append(
915
+ create_delete_range_request(
916
+ 1 + len(text), adjusted_end, tab_id, segment_id=segment_id
917
+ )
918
+ )
919
+ operations.append(
920
+ f"Replaced text from index {start_index} to {end_index}"
921
+ )
922
+ else:
923
+ # Normal replacement: delete old text, then insert new text
924
+ requests.extend(
925
+ [
926
+ create_delete_range_request(
927
+ start_index, end_index, tab_id, segment_id=segment_id
928
+ ),
929
+ create_insert_text_request(
930
+ start_index, text, tab_id, segment_id=segment_id
931
+ ),
932
+ ]
933
+ )
934
+ operations.append(
935
+ f"Replaced text from index {start_index} to {end_index}"
936
+ )
937
+ else:
938
+ # Text insertion
939
+ actual_index = (
940
+ 1
941
+ if start_index == 0
942
+ and not end_of_segment
943
+ and segment_id is None
944
+ and tab_id is None
945
+ else start_index
946
+ )
947
+ requests.append(
948
+ create_insert_text_request(
949
+ None if end_of_segment else actual_index,
950
+ text,
951
+ tab_id,
952
+ segment_id=segment_id,
953
+ end_of_segment=end_of_segment,
954
+ )
955
+ )
956
+ if end_of_segment:
957
+ operations.append(
958
+ f"Inserted text at end of segment '{segment_id or 'body'}'"
959
+ )
960
+ else:
961
+ operations.append(f"Inserted text at index {start_index}")
962
+
963
+ # Handle formatting
964
+ if any(p is not None for p in formatting_params):
965
+ # Adjust range for formatting based on text operations
966
+ format_start = start_index
967
+ format_end = end_index
968
+
969
+ if text is not None:
970
+ if end_index is not None and end_index > start_index:
971
+ # Text was replaced - format the new text
972
+ format_end = start_index + len(text)
973
+ else:
974
+ # Text was inserted - format the inserted text
975
+ actual_index = 1 if start_index == 0 else start_index
976
+ format_start = actual_index
977
+ format_end = actual_index + len(text)
978
+
979
+ # Handle special case for formatting at index 0
980
+ if format_start == 0 and segment_id is None and tab_id is None:
981
+ format_start = 1
982
+ if format_end is not None and format_end <= format_start:
983
+ format_end = format_start + 1
984
+
985
+ requests.append(
986
+ create_format_text_request(
987
+ format_start,
988
+ format_end,
989
+ bold,
990
+ italic,
991
+ underline,
992
+ strikethrough,
993
+ font_size,
994
+ font_family,
995
+ font_weight,
996
+ text_color,
997
+ background_color,
998
+ link_url,
999
+ clear_link,
1000
+ baseline_offset,
1001
+ small_caps,
1002
+ tab_id,
1003
+ segment_id,
1004
+ )
1005
+ )
1006
+
1007
+ format_details = [
1008
+ f"{name}={value}"
1009
+ for name, value in [
1010
+ ("bold", bold),
1011
+ ("italic", italic),
1012
+ ("underline", underline),
1013
+ ("strikethrough", strikethrough),
1014
+ ("font_size", font_size),
1015
+ ("font_family", font_family),
1016
+ ("font_weight", font_weight),
1017
+ ("text_color", text_color),
1018
+ ("background_color", background_color),
1019
+ ("link_url", link_url),
1020
+ ("clear_link", clear_link),
1021
+ ("baseline_offset", baseline_offset),
1022
+ ("small_caps", small_caps),
1023
+ ]
1024
+ if value is not None
1025
+ ]
1026
+
1027
+ operations.append(
1028
+ f"Applied formatting ({', '.join(format_details)}) to range {format_start}-{format_end}"
1029
+ )
1030
+
1031
+ try:
1032
+ result = await asyncio.to_thread(
1033
+ service.documents()
1034
+ .batchUpdate(
1035
+ documentId=document_id,
1036
+ body=build_batch_update_body(requests, write_mode),
1037
+ )
1038
+ .execute
1039
+ )
1040
+ except HttpError as error:
1041
+ raise _rewrite_modify_doc_text_http_error(error, segment_id) from error
1042
+
1043
+ save_error = suggestion_save_error(result, write_mode)
1044
+ if save_error:
1045
+ return f"Error: {save_error}"
1046
+
1047
+ link = f"https://docs.google.com/document/d/{document_id}/edit"
1048
+ if write_mode == "SUGGEST":
1049
+ operations = [f"Suggested: {operation}" for operation in operations]
1050
+ operation_summary = "; ".join(operations)
1051
+ text_info = f" Text length: {len(text)} characters." if text else ""
1052
+ return f"{operation_summary} in document {document_id}.{text_info} Link: {link}"
1053
+
1054
+
1055
+ @server.tool(
1056
+ title="Find and Replace Doc",
1057
+ annotations=ToolAnnotations(
1058
+ readOnlyHint=False,
1059
+ destructiveHint=True,
1060
+ idempotentHint=False,
1061
+ openWorldHint=True,
1062
+ ),
1063
+ )
1064
+ @handle_http_errors("find_and_replace_doc", service_type="docs")
1065
+ @require_google_service("docs", "docs_write")
1066
+ async def find_and_replace_doc(
1067
+ service: Any,
1068
+ user_google_email: str,
1069
+ document_id: str,
1070
+ find_text: str,
1071
+ replace_text: str,
1072
+ match_case: bool = False,
1073
+ tab_id: Optional[str] = None,
1074
+ write_mode: str = "EDIT",
1075
+ ) -> str:
1076
+ """
1077
+ Finds and replaces text throughout a Google Doc. No index calculation required.
1078
+
1079
+ This is the safest way to update specific text in a document because it
1080
+ does not require knowing any indices. Use this tool when you need to:
1081
+ - Replace placeholder text (e.g., {{TITLE}}) with real content
1082
+ - Update specific words or phrases throughout the document
1083
+ - Make targeted text changes without risk of index errors
1084
+
1085
+ For building documents from scratch, consider inserting text with unique
1086
+ placeholders via batch_update_doc, then using this tool to replace them.
1087
+
1088
+ Args:
1089
+ user_google_email: User's Google email address
1090
+ document_id: ID of the document to update
1091
+ find_text: Text to search for
1092
+ replace_text: Text to replace with
1093
+ match_case: Whether to match case exactly
1094
+ tab_id: Optional ID of the tab to target
1095
+ write_mode: "EDIT" (default) applies the replacements directly; "SUGGEST"
1096
+ records them as suggested edits that collaborators can accept or reject
1097
+
1098
+ Returns:
1099
+ str: Confirmation message with replacement count
1100
+ """
1101
+ logger.info(
1102
+ f"[find_and_replace_doc] Doc={document_id}, find_len={len(find_text)}, replace_len={len(replace_text)}, tab='{tab_id}'"
1103
+ )
1104
+ logger.debug(f"[find_and_replace_doc] find='{find_text}', replace='{replace_text}'")
1105
+
1106
+ write_mode_error = validate_write_mode(write_mode)
1107
+ if write_mode_error:
1108
+ return write_mode_error
1109
+
1110
+ requests = [
1111
+ create_find_replace_request(find_text, replace_text, match_case, tab_id)
1112
+ ]
1113
+
1114
+ result = await asyncio.to_thread(
1115
+ service.documents()
1116
+ .batchUpdate(
1117
+ documentId=document_id,
1118
+ body=build_batch_update_body(requests, write_mode),
1119
+ )
1120
+ .execute
1121
+ )
1122
+
1123
+ save_error = suggestion_save_error(result, write_mode)
1124
+ if save_error:
1125
+ return f"Error: {save_error}"
1126
+
1127
+ # Extract number of replacements from response
1128
+ replacements = 0
1129
+ if "replies" in result and result["replies"]:
1130
+ reply = result["replies"][0]
1131
+ if "replaceAllText" in reply:
1132
+ replacements = reply["replaceAllText"].get("occurrencesChanged", 0)
1133
+
1134
+ link = f"https://docs.google.com/document/d/{document_id}/edit"
1135
+ verb = "Suggested replacing" if write_mode == "SUGGEST" else "Replaced"
1136
+ return f"{verb} {replacements} occurrence(s) of '{find_text}' with '{replace_text}' in document {document_id}. Link: {link}"
1137
+
1138
+
1139
+ @server.tool(
1140
+ title="Insert Doc Elements",
1141
+ annotations=ToolAnnotations(
1142
+ readOnlyHint=False,
1143
+ destructiveHint=False,
1144
+ idempotentHint=False,
1145
+ openWorldHint=True,
1146
+ ),
1147
+ )
1148
+ @handle_http_errors("insert_doc_elements", service_type="docs")
1149
+ @require_google_service("docs", "docs_write")
1150
+ async def insert_doc_elements(
1151
+ service: Any,
1152
+ user_google_email: str,
1153
+ document_id: str,
1154
+ element_type: str,
1155
+ index: int,
1156
+ rows: Optional[int] = None,
1157
+ columns: Optional[int] = None,
1158
+ list_type: Optional[str] = None,
1159
+ text: Optional[str] = None,
1160
+ ) -> str:
1161
+ """
1162
+ Inserts structural elements like tables, lists, or page breaks into a Google Doc.
1163
+
1164
+ Args:
1165
+ user_google_email: User's Google email address
1166
+ document_id: ID of the document to update
1167
+ element_type: Type of element to insert ("table", "list", "page_break")
1168
+ index: Position to insert element (0-based)
1169
+ rows: Number of rows for table (required for table)
1170
+ columns: Number of columns for table (required for table)
1171
+ list_type: Type of list ("UNORDERED", "ORDERED") (required for list)
1172
+ text: Initial text content for list items
1173
+
1174
+ Returns:
1175
+ str: Confirmation message with insertion details
1176
+ """
1177
+ logger.info(
1178
+ f"[insert_doc_elements] Doc={document_id}, type={element_type}, index={index}"
1179
+ )
1180
+
1181
+ # Handle the special case where we can't insert at the first section break
1182
+ # If index is 0, bump it to 1 to avoid the section break
1183
+ if index == 0:
1184
+ logger.debug("Adjusting index from 0 to 1 to avoid first section break")
1185
+ index = 1
1186
+
1187
+ requests = []
1188
+
1189
+ if element_type == "table":
1190
+ if not rows or not columns:
1191
+ return "Error: 'rows' and 'columns' parameters are required for table insertion."
1192
+
1193
+ requests.append(create_insert_table_request(index, rows, columns))
1194
+ description = f"table ({rows}x{columns})"
1195
+
1196
+ elif element_type == "list":
1197
+ if not list_type:
1198
+ return "Error: 'list_type' parameter is required for list insertion ('UNORDERED' or 'ORDERED')."
1199
+
1200
+ if not text:
1201
+ text = "List item"
1202
+
1203
+ # Insert text first, then create list
1204
+ requests.extend(
1205
+ [
1206
+ create_insert_text_request(index, text + "\n"),
1207
+ create_bullet_list_request(index, index + len(text), list_type),
1208
+ ]
1209
+ )
1210
+ description = f"{list_type.lower()} list"
1211
+
1212
+ elif element_type == "page_break":
1213
+ requests.append(create_insert_page_break_request(index))
1214
+ description = "page break"
1215
+
1216
+ else:
1217
+ return f"Error: Unsupported element type '{element_type}'. Supported types: 'table', 'list', 'page_break'."
1218
+
1219
+ await asyncio.to_thread(
1220
+ service.documents()
1221
+ .batchUpdate(documentId=document_id, body={"requests": requests})
1222
+ .execute
1223
+ )
1224
+
1225
+ link = f"https://docs.google.com/document/d/{document_id}/edit"
1226
+ return f"Inserted {description} at index {index} in document {document_id}. Link: {link}"
1227
+
1228
+
1229
+ @server.tool(
1230
+ title="Insert Doc Image",
1231
+ annotations=ToolAnnotations(
1232
+ readOnlyHint=False,
1233
+ destructiveHint=False,
1234
+ idempotentHint=False,
1235
+ openWorldHint=True,
1236
+ ),
1237
+ )
1238
+ @handle_http_errors("insert_doc_image", service_type="docs")
1239
+ @require_multiple_services(
1240
+ [
1241
+ {"service_type": "docs", "scopes": "docs_write", "param_name": "docs_service"},
1242
+ {
1243
+ "service_type": "drive",
1244
+ "scopes": "drive_read",
1245
+ "param_name": "drive_service",
1246
+ },
1247
+ ]
1248
+ )
1249
+ async def insert_doc_image(
1250
+ docs_service: Any,
1251
+ drive_service: Any,
1252
+ user_google_email: str,
1253
+ document_id: str,
1254
+ image_source: str,
1255
+ index: int,
1256
+ width: int = 0,
1257
+ height: int = 0,
1258
+ ) -> str:
1259
+ """
1260
+ Inserts an image into a Google Doc from Drive or a URL.
1261
+
1262
+ Args:
1263
+ user_google_email: User's Google email address
1264
+ document_id: ID of the document to update
1265
+ image_source: Drive file ID or public image URL
1266
+ index: Position to insert image (0-based)
1267
+ width: Image width in points (optional)
1268
+ height: Image height in points (optional)
1269
+
1270
+ Returns:
1271
+ str: Confirmation message with insertion details
1272
+ """
1273
+ logger.info(
1274
+ f"[insert_doc_image] Doc={document_id}, source={image_source}, index={index}"
1275
+ )
1276
+
1277
+ # Handle the special case where we can't insert at the first section break
1278
+ # If index is 0, bump it to 1 to avoid the section break
1279
+ if index == 0:
1280
+ logger.debug("Adjusting index from 0 to 1 to avoid first section break")
1281
+ index = 1
1282
+
1283
+ # Determine if source is a Drive file ID or URL
1284
+ is_drive_file = not (
1285
+ image_source.startswith("http://") or image_source.startswith("https://")
1286
+ )
1287
+
1288
+ if is_drive_file:
1289
+ # Verify Drive file exists and get metadata
1290
+ try:
1291
+ file_metadata = await asyncio.to_thread(
1292
+ drive_service.files()
1293
+ .get(
1294
+ fileId=image_source,
1295
+ fields="id, name, mimeType",
1296
+ supportsAllDrives=True,
1297
+ )
1298
+ .execute
1299
+ )
1300
+ mime_type = file_metadata.get("mimeType", "")
1301
+ if not mime_type.startswith("image/"):
1302
+ return f"Error: File {image_source} is not an image (MIME type: {mime_type})."
1303
+
1304
+ image_uri = f"https://drive.google.com/uc?id={image_source}"
1305
+ source_description = f"Drive file {file_metadata.get('name', image_source)}"
1306
+ except Exception as e:
1307
+ return f"Error: Could not access Drive file {image_source}: {str(e)}"
1308
+ else:
1309
+ image_uri = image_source
1310
+ source_description = "URL image"
1311
+
1312
+ # Use helper to create image request
1313
+ requests = [create_insert_image_request(index, image_uri, width, height)]
1314
+
1315
+ await asyncio.to_thread(
1316
+ docs_service.documents()
1317
+ .batchUpdate(documentId=document_id, body={"requests": requests})
1318
+ .execute
1319
+ )
1320
+
1321
+ size_info = ""
1322
+ if width or height:
1323
+ size_info = f" (size: {width or 'auto'}x{height or 'auto'} points)"
1324
+
1325
+ link = f"https://docs.google.com/document/d/{document_id}/edit"
1326
+ return f"Inserted {source_description}{size_info} at index {index} in document {document_id}. Link: {link}"
1327
+
1328
+
1329
+ @server.tool(
1330
+ title="Update Doc Headers Footers",
1331
+ annotations=ToolAnnotations(
1332
+ readOnlyHint=False,
1333
+ destructiveHint=True,
1334
+ idempotentHint=False,
1335
+ openWorldHint=True,
1336
+ ),
1337
+ )
1338
+ @handle_http_errors("update_doc_headers_footers", service_type="docs")
1339
+ @require_google_service("docs", "docs_write")
1340
+ async def update_doc_headers_footers(
1341
+ service: Any,
1342
+ user_google_email: str,
1343
+ document_id: str,
1344
+ section_type: str,
1345
+ content: str,
1346
+ header_footer_type: str = "DEFAULT",
1347
+ ) -> str:
1348
+ """
1349
+ Safely creates or updates header/footer text in a Google Doc.
1350
+
1351
+ This is the default tool for header/footer content. Do NOT use
1352
+ batch_update_doc with create_header_footer just to set header/footer text;
1353
+ that low-level operation is only for advanced section-break workflows and
1354
+ can fail when the default header/footer already exists.
1355
+
1356
+ This tool handles both creation and update in one call:
1357
+ - If the header/footer does not exist, it is automatically created first.
1358
+ - If the header/footer already exists, its content is replaced.
1359
+
1360
+ You do NOT need to create a header/footer separately before calling this tool.
1361
+ Simply call it with the desired content and it will work whether the
1362
+ header/footer exists or not.
1363
+
1364
+ Args:
1365
+ user_google_email: User's Google email address
1366
+ document_id: ID of the document to update
1367
+ section_type: Type of section to create or update ("header" or "footer")
1368
+ content: Text content for the header/footer
1369
+ header_footer_type: Type of header/footer ("DEFAULT", "FIRST_PAGE_ONLY", "EVEN_PAGE")
1370
+
1371
+ Returns:
1372
+ str: Confirmation message with update details
1373
+ """
1374
+ logger.info(f"[update_doc_headers_footers] Doc={document_id}, type={section_type}")
1375
+
1376
+ # Input validation
1377
+ validator = ValidationManager()
1378
+
1379
+ is_valid, error_msg = validator.validate_document_id(document_id)
1380
+ if not is_valid:
1381
+ return f"Error: {error_msg}"
1382
+
1383
+ is_valid, error_msg = validator.validate_header_footer_params(
1384
+ section_type, header_footer_type
1385
+ )
1386
+ if not is_valid:
1387
+ return f"Error: {error_msg}"
1388
+
1389
+ is_valid, error_msg = validator.validate_text_content(content)
1390
+ if not is_valid:
1391
+ return f"Error: {error_msg}"
1392
+
1393
+ # Use HeaderFooterManager to handle the complex logic
1394
+ header_footer_manager = HeaderFooterManager(service)
1395
+
1396
+ success, message = await header_footer_manager.update_header_footer_content(
1397
+ document_id, section_type, content, header_footer_type
1398
+ )
1399
+
1400
+ if success:
1401
+ link = f"https://docs.google.com/document/d/{document_id}/edit"
1402
+ return f"{message}. Runtime: {HEADER_FOOTER_RUNTIME_CANARY}. Link: {link}"
1403
+ else:
1404
+ return f"Error: {message}. Runtime: {HEADER_FOOTER_RUNTIME_CANARY}"
1405
+
1406
+
1407
+ @server.tool(
1408
+ title="Batch Update Doc",
1409
+ annotations=ToolAnnotations(
1410
+ readOnlyHint=False,
1411
+ destructiveHint=True,
1412
+ idempotentHint=False,
1413
+ openWorldHint=True,
1414
+ ),
1415
+ )
1416
+ @handle_http_errors("batch_update_doc", service_type="docs")
1417
+ @require_google_service("docs", "docs_write")
1418
+ async def batch_update_doc(
1419
+ service: Any,
1420
+ user_google_email: str,
1421
+ document_id: str,
1422
+ operations: BatchDocOperations,
1423
+ write_mode: str = "EDIT",
1424
+ ) -> str:
1425
+ """
1426
+ Executes multiple low-level document operations in a single atomic batch update.
1427
+
1428
+ For normal header/footer text, prefer update_doc_headers_footers.
1429
+ Only use create_header_footer here for advanced section-break layouts.
1430
+
1431
+ RECOMMENDED WORKFLOW FOR BUILDING DOCUMENTS:
1432
+ =============================================
1433
+ To avoid index calculation errors, build documents in phases:
1434
+
1435
+ PHASE 1 - INSERT ALL CONTENT (use end_of_segment=true, no index math):
1436
+ Append text, section breaks, and page breaks sequentially.
1437
+ Each operation appends to the end of the body. No index needed.
1438
+ Example batch: [
1439
+ {"type": "insert_text", "end_of_segment": true, "text": "Report Title\\n"},
1440
+ {"type": "insert_text", "end_of_segment": true, "text": "\\nExecutive Summary\\n"},
1441
+ {"type": "insert_text", "end_of_segment": true, "text": "Revenue grew 15%.\\n"},
1442
+ {"type": "insert_section_break", "end_of_segment": true, "section_type": "NEXT_PAGE"},
1443
+ {"type": "insert_text", "end_of_segment": true, "text": "Detailed Analysis\\n"}
1444
+ ]
1445
+
1446
+ PHASE 2 - CREATE HEADERS/FOOTERS (if needed):
1447
+ For normal header/footer text, use update_doc_headers_footers
1448
+ (it auto-creates if missing and writes the content for you).
1449
+ Only include create_header_footer operations in a batch when you are
1450
+ intentionally managing advanced section-break-specific layouts.
1451
+
1452
+ PHASE 3 - INSPECT STRUCTURE:
1453
+ Call inspect_doc_structure with detailed=true to get exact start_index
1454
+ and end_index for every paragraph and element.
1455
+
1456
+ PHASE 4 - APPLY FORMATTING (separate batch using indices from Phase 3):
1457
+ Use the real indices from inspect_doc_structure output: [
1458
+ {"type": "update_paragraph_style", "start_index": 1, "end_index": 15,
1459
+ "heading_level": 1, "alignment": "CENTER"},
1460
+ {"type": "format_text", "start_index": 1, "end_index": 15,
1461
+ "bold": true, "font_size": 24},
1462
+ {"type": "create_bullet_list", "start_index": 50, "end_index": 120,
1463
+ "list_type": "ORDERED"}
1464
+ ]
1465
+
1466
+ ALTERNATIVE - FIND_REPLACE PATTERN (no indices needed at all):
1467
+ Insert text with unique placeholders, then use find_replace:
1468
+ [
1469
+ {"type": "insert_text", "end_of_segment": true, "text": "{{TITLE}}\\n{{BODY}}\\n"},
1470
+ {"type": "find_replace", "find_text": "{{TITLE}}", "replace_text": "Quarterly Report"},
1471
+ {"type": "find_replace", "find_text": "{{BODY}}", "replace_text": "The results show..."}
1472
+ ]
1473
+
1474
+ ALTERNATIVE - SEMANTIC ANCHORS (target existing structure without indices):
1475
+ Insertion operations accept after_heading, before_heading, or anchor_text with
1476
+ anchor_position instead of index. Each is resolved against the document at
1477
+ execution time, so it cannot go stale the way a pre-computed index can, and
1478
+ an anchor matching zero or several places is refused rather than guessed.
1479
+ Submit anchored insertions in their own batch; they execute from highest
1480
+ index to lowest to keep targets stable. [
1481
+ {"type": "insert_text", "after_heading": "Results",
1482
+ "text": "Revenue grew 15%.\\n"},
1483
+ {"type": "insert_text", "anchor_text": "Conclusion",
1484
+ "anchor_position": "before", "text": "See appendix.\\n"}
1485
+ ]
1486
+
1487
+ WARNING - AVOID THIS ANTI-PATTERN:
1488
+ Do NOT pre-compute sequential indices for multiple insert_text operations.
1489
+ Each insertion shifts all subsequent indices and manual calculation is error-prone.
1490
+ Use end_of_segment=true instead, which always appends to the current end.
1491
+ BAD: [{"type":"insert_text","index":1,"text":"Hello\\n"},
1492
+ {"type":"insert_text","index":8,"text":"World\\n"}] <- index 8 may be wrong
1493
+ GOOD: [{"type":"insert_text","end_of_segment":true,"text":"Hello\\n"},
1494
+ {"type":"insert_text","end_of_segment":true,"text":"World\\n"}]
1495
+
1496
+ Args:
1497
+ user_google_email: User's Google email address
1498
+ document_id: ID of the document to update
1499
+ operations: List of operation dicts. Each operation MUST have a 'type' field.
1500
+ All operations accept an optional 'tab_id' to target a specific tab.
1501
+ write_mode: "EDIT" (default) applies the batch directly; "SUGGEST" records
1502
+ every operation as a suggested edit that collaborators can accept
1503
+ or reject. The Docs API rejects some operations in SUGGEST mode,
1504
+ such as named range and tab changes.
1505
+
1506
+ Supported operation types and their parameters:
1507
+
1508
+ insert_text - required: text (str)
1509
+ PREFERRED: end_of_segment (bool) - set true to append at end
1510
+ of body without calculating an index. Safest way to build
1511
+ documents sequentially.
1512
+ optional: index (int), tab_id, segment_id
1513
+ delete_text - required: start_index (int), end_index (int)
1514
+ optional: tab_id, segment_id
1515
+ replace_text - required: start_index (int), end_index (int), text (str)
1516
+ optional: tab_id, segment_id
1517
+ format_text - required: start_index (int), end_index (int)
1518
+ optional: bold, italic, underline, strikethrough, font_size,
1519
+ font_family, font_weight, text_color, background_color,
1520
+ link_url, clear_link, baseline_offset, small_caps,
1521
+ tab_id, segment_id
1522
+ update_paragraph_style
1523
+ - required: start_index (int), end_index (int)
1524
+ optional: heading_level (0-6, 0=normal), alignment
1525
+ (START/CENTER/END/JUSTIFIED), line_spacing,
1526
+ indent_first_line, indent_start, indent_end,
1527
+ space_above, space_below, named_style_type,
1528
+ direction, keep_lines_together, keep_with_next,
1529
+ avoid_widow_and_orphan, page_break_before,
1530
+ spacing_mode, shading_color, border_edges,
1531
+ border_color, border_width, border_padding,
1532
+ border_dash, tab_id, segment_id
1533
+ update_table_cell_style
1534
+ - required: table_start_index (int)
1535
+ optional: background_color, border_color, border_width,
1536
+ padding_top, padding_bottom, padding_left,
1537
+ padding_right (float, points),
1538
+ content_alignment ("TOP"|"MIDDLE"|"BOTTOM"),
1539
+ row_index, column_index, row_span, column_span,
1540
+ border_edges ("top"|"bottom"|"left"|"right")
1541
+ Use inspect_doc_structure to find table_start_index from
1542
+ table_details[].start_index. If row/column values are
1543
+ omitted, the style is applied to the entire table.
1544
+ insert_table - required: rows (int), columns (int)
1545
+ optional: index (int), tab_id, segment_id, end_of_segment
1546
+ insert_table_row - required: table_start_index (int), row_index (int)
1547
+ optional: insert_below (bool, default true), tab_id
1548
+ delete_table_row - required: table_start_index (int), row_index (int)
1549
+ optional: tab_id
1550
+ insert_table_column
1551
+ - required: table_start_index (int), column_index (int)
1552
+ optional: insert_right (bool, default true), tab_id
1553
+ delete_table_column
1554
+ - required: table_start_index (int), column_index (int)
1555
+ optional: tab_id
1556
+ merge_table_cells
1557
+ - required: table_start_index (int), row_index (int),
1558
+ column_index (int), row_span (int), column_span (int)
1559
+ optional: tab_id
1560
+ unmerge_table_cells
1561
+ - required: table_start_index (int), row_index (int),
1562
+ column_index (int), row_span (int), column_span (int)
1563
+ optional: tab_id
1564
+ update_table_column_properties
1565
+ - required: table_start_index (int), column_indices (list[int])
1566
+ optional: width (float, points), width_type
1567
+ (FIXED_WIDTH|EVENLY_DISTRIBUTED), tab_id
1568
+ update_table_row_style
1569
+ - required: table_start_index (int), row_indices (list[int])
1570
+ optional: min_row_height (float, points), tab_id
1571
+ pin_table_header_rows
1572
+ - required: table_start_index (int),
1573
+ pinned_header_rows_count (int)
1574
+ optional: tab_id
1575
+ Set pinned_header_rows_count=1 to repeat the first row as
1576
+ a header across page breaks (0 unpins all rows). This is
1577
+ the writable request for the tableHeader state reported
1578
+ in TableRowStyle.
1579
+ insert_page_break- optional: index (int), end_of_segment, tab_id
1580
+ insert_person - required: email (str)
1581
+ optional: index (int), end_of_segment, tab_id, segment_id
1582
+ Inserts an @mention person smart chip.
1583
+ create_dropdown_definition - required: title, options (2-50 choices)
1584
+ optional: dropdown_definition_id, tab_id
1585
+ Each choice: display_value; optional option_id, text_color,
1586
+ background_color (six-digit hex). IDs may be server-generated.
1587
+ insert_dropdown - required: dropdown_definition_id and one insertion location
1588
+ optional: selected_option_id (defaults to first option),
1589
+ tab_id, segment_id; supports semantic anchors.
1590
+ Definition and chip must be in the same tab.
1591
+ insert_date - required: date (str, YYYY-MM-DD or ISO 8601 with a time zone)
1592
+ optional: index (int), end_of_segment, tab_id, segment_id,
1593
+ date_format, time_format, timezone
1594
+ Inserts a date smart chip.
1595
+ insert_section_break
1596
+ - optional: index (int), end_of_segment, section_type
1597
+ ('CONTINUOUS'|'NEXT_PAGE')
1598
+ find_replace - required: find_text (str), replace_text (str)
1599
+ optional: match_case (bool, default false)
1600
+ create_bullet_list - required: start_index (int), end_index (int)
1601
+ optional: list_type ('UNORDERED'|'ORDERED'|'CHECKBOX'|'NONE',
1602
+ default UNORDERED), nesting_level (0-8),
1603
+ paragraph_start_indices (list[int]), bullet_preset
1604
+ Use list_type='NONE' to remove existing bullet/list formatting
1605
+ create_named_range
1606
+ - required: name (str), start_index (int), end_index (int)
1607
+ optional: tab_id, segment_id
1608
+ replace_named_range_content
1609
+ - required: text (str)
1610
+ optional: named_range_id, named_range_name, tab_id
1611
+ delete_named_range
1612
+ - optional: named_range_id, named_range_name, tab_id
1613
+ update_document_style
1614
+ - optional: background_color, margin_top, margin_bottom,
1615
+ margin_left, margin_right, margin_header,
1616
+ margin_footer, page_width, page_height,
1617
+ page_number_start, use_even_page_header_footer,
1618
+ use_first_page_header_footer,
1619
+ flip_page_orientation, document_mode, tab_id
1620
+ update_section_style
1621
+ - required: start_index (int), end_index (int)
1622
+ optional: margin_top, margin_bottom, margin_left,
1623
+ margin_right, margin_header, margin_footer,
1624
+ page_number_start, use_first_page_header_footer,
1625
+ flip_page_orientation, content_direction,
1626
+ column_count, column_spacing,
1627
+ column_separator_style
1628
+ create_header_footer
1629
+ - required: section_type ('header'|'footer')
1630
+ optional: header_footer_type, section_break_index
1631
+ Advanced only. For ordinary header/footer text, use
1632
+ update_doc_headers_footers instead.
1633
+ insert_image - required: image_uri (str)
1634
+ optional: index, width, height, tab_id, segment_id,
1635
+ end_of_segment
1636
+ insert_doc_tab - required: title (str), index (int)
1637
+ optional: parent_tab_id (str)
1638
+ delete_doc_tab - required: tab_id (str)
1639
+ update_doc_tab - required: tab_id (str), title (str)
1640
+
1641
+ Example - Safe document building (no index calculation needed):
1642
+ [
1643
+ {"type": "insert_text", "end_of_segment": true, "text": "Quarterly Report\\n\\n"},
1644
+ {"type": "insert_text", "end_of_segment": true, "text": "Executive Summary\\n"},
1645
+ {"type": "insert_text", "end_of_segment": true, "text": "Revenue grew 15% YoY.\\n"}
1646
+ ]
1647
+
1648
+ Example - Formatting (use exact indices from inspect_doc_structure output):
1649
+ [
1650
+ {"type": "format_text", "start_index": 1, "end_index": 19, "bold": true, "font_size": 24},
1651
+ {"type": "update_paragraph_style", "start_index": 1, "end_index": 19,
1652
+ "heading_level": 1, "alignment": "CENTER"},
1653
+ {"type": "update_paragraph_style", "start_index": 20, "end_index": 39, "heading_level": 2}
1654
+ ]
1655
+
1656
+ Example - Using find_replace (zero index risk):
1657
+ [
1658
+ {"type": "find_replace", "find_text": "{{DATE}}", "replace_text": "March 2026"},
1659
+ {"type": "find_replace", "find_text": "{{AUTHOR}}", "replace_text": "Jane Smith"}
1660
+ ]
1661
+
1662
+ Example - Insert table at end of document:
1663
+ [{"type": "insert_table", "end_of_segment": true, "rows": 3, "columns": 4}]
1664
+
1665
+ Example - Headers, footers, and document style:
1666
+ [
1667
+ {"type": "create_header_footer", "section_type": "header"},
1668
+ {"type": "create_header_footer", "section_type": "footer"},
1669
+ {"type": "update_document_style", "margin_top": 72, "margin_bottom": 72}
1670
+ ]
1671
+
1672
+ Returns:
1673
+ str: Confirmation message with batch results and document length for chaining
1674
+ """
1675
+ normalized_operations = [
1676
+ operation.model_dump(exclude_none=True)
1677
+ if hasattr(operation, "model_dump")
1678
+ else operation
1679
+ for operation in operations
1680
+ ]
1681
+
1682
+ logger.debug(
1683
+ f"[batch_update_doc] Doc={document_id}, operations={len(normalized_operations)}"
1684
+ )
1685
+
1686
+ # Input validation
1687
+ validator = ValidationManager()
1688
+
1689
+ is_valid, error_msg = validator.validate_document_id(document_id)
1690
+ if not is_valid:
1691
+ return f"Error: {error_msg}"
1692
+
1693
+ is_valid, error_msg = validator.validate_batch_operations(normalized_operations)
1694
+ if not is_valid:
1695
+ return f"Error: {error_msg}"
1696
+
1697
+ write_mode_error = validate_write_mode(write_mode)
1698
+ if write_mode_error:
1699
+ return write_mode_error
1700
+
1701
+ # Use BatchOperationManager to handle the complex logic
1702
+ batch_manager = BatchOperationManager(service)
1703
+
1704
+ success, message, metadata = await batch_manager.execute_batch_operations(
1705
+ document_id, normalized_operations, write_mode
1706
+ )
1707
+
1708
+ if success:
1709
+ link = f"https://docs.google.com/document/d/{document_id}/edit"
1710
+ replies_count = metadata.get("replies_count", 0)
1711
+ doc_length = metadata.get("document_length")
1712
+ length_info = f" Document length: {doc_length}." if doc_length else ""
1713
+
1714
+ parts = [
1715
+ f"{message} on document {document_id}. ",
1716
+ f"API replies: {replies_count}.{length_info}",
1717
+ ]
1718
+
1719
+ revision_before = metadata.get("revision_before")
1720
+ revision_after = metadata.get("revision_after")
1721
+ if revision_before or revision_after:
1722
+ parts.append(
1723
+ f" Revision: {revision_before or 'unknown'} -> "
1724
+ f"{revision_after or 'unknown'}."
1725
+ )
1726
+
1727
+ if metadata.get("dropdown_results"):
1728
+ parts.append(
1729
+ f"\nDropdown results: {json.dumps(metadata['dropdown_results'])}\n"
1730
+ )
1731
+
1732
+ # Reporting what the edited range now looks like lets the caller confirm
1733
+ # styles and list membership landed without a second round trip.
1734
+ for target in metadata.get("target_ranges", [metadata]):
1735
+ if (
1736
+ target.get("tab_id")
1737
+ or target.get("segment_id")
1738
+ or len(metadata.get("target_ranges", [])) > 1
1739
+ ):
1740
+ parts.append(
1741
+ f"\nTarget tab: {target.get('tab_id') or 'first'}, "
1742
+ f"segment: {target.get('segment_id') or 'body'}. "
1743
+ f"Document length: {target.get('document_length')}."
1744
+ )
1745
+ affected = target.get("affected_range")
1746
+ if affected:
1747
+ parts.append("\nAffected range after edit:")
1748
+ for entry in affected:
1749
+ bullet = ", in list" if entry["in_list"] else ""
1750
+ preview = entry["text_preview"].replace("\n", " ").strip()
1751
+ parts.append(
1752
+ f"\n [{entry['start_index']}-{entry['end_index']}] "
1753
+ f'{entry["named_style"] or "UNKNOWN"}{bullet}: "{preview}"'
1754
+ )
1755
+ parts.append("\n")
1756
+
1757
+ parts.append(
1758
+ f" To apply formatting, call inspect_doc_structure to get exact text positions. "
1759
+ f"Link: {link}"
1760
+ )
1761
+ return "".join(parts)
1762
+ else:
1763
+ return f"Error: {message}"
1764
+
1765
+
1766
+ @server.tool(
1767
+ title="Inspect Doc Structure",
1768
+ annotations=ToolAnnotations(
1769
+ readOnlyHint=True,
1770
+ destructiveHint=False,
1771
+ idempotentHint=True,
1772
+ openWorldHint=True,
1773
+ ),
1774
+ )
1775
+ @handle_http_errors("inspect_doc_structure", is_read_only=True, service_type="docs")
1776
+ @require_google_service("docs", "docs_read")
1777
+ async def inspect_doc_structure(
1778
+ service: Any,
1779
+ user_google_email: str,
1780
+ document_id: str,
1781
+ detailed: bool = False,
1782
+ tab_id: Optional[str] = None,
1783
+ preview_chars: Optional[int] = 100,
1784
+ ) -> str:
1785
+ """
1786
+ Essential tool for finding safe insertion points and understanding document structure.
1787
+
1788
+ USE THIS FOR:
1789
+ - Finding the correct index for table insertion
1790
+ - Understanding document layout before making changes
1791
+ - Locating existing tables and their positions
1792
+ - Getting document statistics and complexity info
1793
+ - Inspecting structure of specific tabs
1794
+
1795
+ CRITICAL FOR TABLE OPERATIONS:
1796
+ ALWAYS call this BEFORE creating tables to get a safe insertion index.
1797
+
1798
+ WHAT THE OUTPUT SHOWS:
1799
+ - total_elements: Number of document elements
1800
+ - total_length: Maximum safe index for insertion
1801
+ - tables: Number of existing tables
1802
+ - table_details: Position and dimensions of each table
1803
+ - headers / footers: Real segment IDs and previews for header/footer editing
1804
+ - tabs: List of available tabs in the document (if no tab_id specified)
1805
+ - empty_paragraphs: newline-only count, excluding existing/suggested object anchors
1806
+ - empty_paragraph_ranges: start/end extents, capped at 100
1807
+ - empty_paragraph_ranges_truncated: whether ranges were omitted
1808
+ - last_paragraph: is_list_item and is_empty, or null if no body paragraphs
1809
+
1810
+ Paragraph statistics cover top-level body paragraphs and appear at the top
1811
+ level in basic mode or under "statistics" in detailed mode.
1812
+ Ranges can include required empty paragraphs. Before cleanup, use detailed=true
1813
+ to check adjacent elements, formatting, and object anchors. Preserve the final
1814
+ newline and newlines before tables, tables of contents, or section breaks.
1815
+ If the body ends with an empty paragraph, that paragraph's range has
1816
+ end == total_length; truncation may omit that range.
1817
+
1818
+ WORKFLOW FOR TABLE INSERTION:
1819
+ Step 1: Call this function
1820
+ Step 2: Note the "total_length" value
1821
+ Step 3: Use an index < total_length for table insertion
1822
+ Step 4: Create your table
1823
+
1824
+ FORMATTING WORKFLOW:
1825
+ After inserting all text via batch_update_doc with end_of_segment=true,
1826
+ call this tool with detailed=true to get exact start_index and end_index
1827
+ for every paragraph. Use those indices directly in format_text and
1828
+ update_paragraph_style operations in a second batch_update_doc call.
1829
+
1830
+ HEADER/FOOTER WORKFLOW:
1831
+ For ordinary header/footer text, use update_doc_headers_footers.
1832
+ If you need low-level segment editing, call this tool first and use the
1833
+ real segment_id values returned under headers/footers. Do not invent IDs.
1834
+
1835
+ The detailed output includes elements[].start_index and elements[].end_index
1836
+ with text_preview for each paragraph, making it easy to identify which
1837
+ ranges to format.
1838
+
1839
+ SUB-PARAGRAPH FORMATTING:
1840
+ text_preview is truncated to 100 characters by default. To compute the index
1841
+ of a token inside a longer paragraph, pass preview_chars=0 or None for untruncated
1842
+ text, then add the token's UTF-16 offset within that text to the paragraph's
1843
+ start_index (non-BMP characters such as emoji occupy two UTF-16 units).
1844
+
1845
+ Args:
1846
+ user_google_email: User's Google email address
1847
+ document_id: ID of the document to inspect
1848
+ detailed: Whether to return detailed structure information
1849
+ tab_id: Optional ID of the tab to inspect. If not provided, inspects main document.
1850
+ preview_chars: Maximum characters of paragraph, header and footer text
1851
+ preview. Pass 0 or None for the full text, needed to locate a token inside a
1852
+ paragraph longer than the default 100 characters.
1853
+
1854
+ Returns:
1855
+ str: JSON string containing document structure and safe insertion indices
1856
+ """
1857
+ logger.debug(
1858
+ f"[inspect_doc_structure] Doc={document_id}, detailed={detailed}, "
1859
+ f"tab_id={tab_id}, preview_chars={preview_chars}"
1860
+ )
1861
+
1862
+ # Get the document. The field mask keeps this summary call from paying to
1863
+ # serialize every text run's styling, which made inspecting a document cost
1864
+ # the same as reading it.
1865
+ doc = await asyncio.to_thread(
1866
+ service.documents()
1867
+ .get(
1868
+ documentId=document_id,
1869
+ includeTabsContent=True,
1870
+ fields=_STRUCTURE_FIELDS,
1871
+ )
1872
+ .execute
1873
+ )
1874
+
1875
+ # If tab_id is specified, find the tab and use its content
1876
+ target_content = doc.get("body", {})
1877
+
1878
+ if tab_id:
1879
+ tab = _find_tab(doc.get("tabs", []), tab_id)
1880
+ if tab and "documentTab" in tab:
1881
+ document_tab = tab["documentTab"]
1882
+ target_content = document_tab.get("body", {})
1883
+ analysis_named_ranges = document_tab.get("namedRanges", {})
1884
+ elif tab:
1885
+ return f"Error: Tab {tab_id} is not a document tab and has no body content."
1886
+ else:
1887
+ return f"Error: Tab {tab_id} not found in document."
1888
+ else:
1889
+ analysis_named_ranges = doc.get("namedRanges", {})
1890
+ document_tab = None
1891
+
1892
+ # Create a dummy doc object for analysis tools that expect a full doc
1893
+ analysis_doc = doc.copy()
1894
+ analysis_doc["body"] = target_content
1895
+ analysis_doc["namedRanges"] = analysis_named_ranges
1896
+ if tab_id and document_tab:
1897
+ analysis_doc["headers"] = document_tab.get("headers", {})
1898
+ analysis_doc["footers"] = document_tab.get("footers", {})
1899
+ analysis_doc["documentStyle"] = document_tab.get("documentStyle", {})
1900
+ elif not tab_id and doc.get("tabs"):
1901
+ # Default to the first document tab for tab-aware header/footer inspection.
1902
+ def first_document_tab(tabs):
1903
+ for candidate in tabs:
1904
+ if "documentTab" in candidate:
1905
+ return candidate["documentTab"]
1906
+ child = first_document_tab(candidate.get("childTabs", []))
1907
+ if child:
1908
+ return child
1909
+ return None
1910
+
1911
+ first_tab_doc = first_document_tab(doc.get("tabs", []))
1912
+ if first_tab_doc:
1913
+ analysis_doc["body"] = first_tab_doc.get("body", {})
1914
+ analysis_doc["namedRanges"] = first_tab_doc.get("namedRanges", {})
1915
+ analysis_doc["headers"] = first_tab_doc.get("headers", {})
1916
+ analysis_doc["footers"] = first_tab_doc.get("footers", {})
1917
+ analysis_doc["documentStyle"] = first_tab_doc.get("documentStyle", {})
1918
+
1919
+ structure = parse_document_structure(analysis_doc, preview_chars)
1920
+
1921
+ if detailed:
1922
+ # Return full parsed structure
1923
+ # Simplify for JSON serialization
1924
+ result = {
1925
+ "title": structure["title"],
1926
+ "total_length": structure["total_length"],
1927
+ "statistics": {
1928
+ "elements": len(structure["body"]),
1929
+ "tables": len(structure["tables"]),
1930
+ "paragraphs": sum(
1931
+ 1 for e in structure["body"] if e.get("type") == "paragraph"
1932
+ ),
1933
+ "section_breaks": len(structure["section_breaks"]),
1934
+ "named_ranges": len(structure["named_ranges"]),
1935
+ "has_headers": bool(structure["headers"]),
1936
+ "has_footers": bool(structure["footers"]),
1937
+ **summarize_paragraph_layout(structure),
1938
+ },
1939
+ "elements": [],
1940
+ }
1941
+
1942
+ # Add element summaries
1943
+ for element in structure["body"]:
1944
+ elem_summary = {
1945
+ "type": element["type"],
1946
+ "start_index": element["start_index"],
1947
+ "end_index": element["end_index"],
1948
+ }
1949
+
1950
+ if element["type"] == "table":
1951
+ elem_summary["rows"] = element["rows"]
1952
+ elem_summary["columns"] = element["columns"]
1953
+ elem_summary["cell_count"] = len(element.get("cells", []))
1954
+ elif element["type"] == "paragraph":
1955
+ elem_summary["text_preview"] = truncate_preview(
1956
+ element.get("text", ""), preview_chars
1957
+ )
1958
+ elem_summary["is_list_item"] = bool(element.get("is_list_item"))
1959
+ for key in ("positioned_object_ids", "suggested_positioned_object_ids"):
1960
+ if key in element:
1961
+ elem_summary[key] = element[key]
1962
+
1963
+ result["elements"].append(elem_summary)
1964
+
1965
+ # Add table details
1966
+ if structure["tables"]:
1967
+ result["tables"] = []
1968
+ for i, table in enumerate(structure["tables"]):
1969
+ table_data = extract_table_as_data(table)
1970
+ result["tables"].append(
1971
+ {
1972
+ "index": i,
1973
+ "position": {
1974
+ "start": table["start_index"],
1975
+ "end": table["end_index"],
1976
+ },
1977
+ "dimensions": {
1978
+ "rows": table["rows"],
1979
+ "columns": table["columns"],
1980
+ },
1981
+ "preview": table_data[:3] if table_data else [], # First 3 rows
1982
+ }
1983
+ )
1984
+
1985
+ if structure["section_breaks"]:
1986
+ result["section_breaks"] = [
1987
+ {
1988
+ "start_index": section_break["start_index"],
1989
+ "end_index": section_break["end_index"],
1990
+ "section_style": section_break.get("section_style", {}),
1991
+ }
1992
+ for section_break in structure["section_breaks"]
1993
+ ]
1994
+
1995
+ if structure["named_ranges"]:
1996
+ result["named_ranges"] = structure["named_ranges"]
1997
+
1998
+ else:
1999
+ # Return basic analysis
2000
+ result = analyze_document_complexity(analysis_doc)
2001
+
2002
+ # Add table information
2003
+ tables = find_tables(analysis_doc)
2004
+ if tables:
2005
+ result["table_details"] = []
2006
+ for i, table in enumerate(tables):
2007
+ result["table_details"].append(
2008
+ {
2009
+ "index": i,
2010
+ "rows": table["rows"],
2011
+ "columns": table["columns"],
2012
+ "start_index": table["start_index"],
2013
+ "end_index": table["end_index"],
2014
+ }
2015
+ )
2016
+
2017
+ if structure["headers"]:
2018
+ result["headers"] = _build_segment_inspection_entries(
2019
+ analysis_doc, structure, "header"
2020
+ )
2021
+
2022
+ else:
2023
+ header_entries = _build_segment_inspection_entries(
2024
+ analysis_doc, structure, "header"
2025
+ )
2026
+ if header_entries:
2027
+ result["headers"] = header_entries
2028
+
2029
+ if structure["footers"]:
2030
+ result["footers"] = _build_segment_inspection_entries(
2031
+ analysis_doc, structure, "footer"
2032
+ )
2033
+ else:
2034
+ footer_entries = _build_segment_inspection_entries(
2035
+ analysis_doc, structure, "footer"
2036
+ )
2037
+ if footer_entries:
2038
+ result["footers"] = footer_entries
2039
+
2040
+ # Always include available tabs if no tab_id was specified
2041
+ if not tab_id:
2042
+
2043
+ def get_tabs_summary(tabs):
2044
+ summary = []
2045
+ for tab in tabs:
2046
+ props = tab.get("tabProperties", {})
2047
+ tab_info = {
2048
+ "title": props.get("title"),
2049
+ "tab_id": props.get("tabId"),
2050
+ }
2051
+ if "childTabs" in tab:
2052
+ tab_info["child_tabs"] = get_tabs_summary(tab["childTabs"])
2053
+ summary.append(tab_info)
2054
+ return summary
2055
+
2056
+ result["tabs"] = get_tabs_summary(doc.get("tabs", []))
2057
+
2058
+ if tab_id:
2059
+ result["inspected_tab_id"] = tab_id
2060
+
2061
+ link = f"https://docs.google.com/document/d/{document_id}/edit"
2062
+ return f"Document structure analysis for {document_id}:\n\n{json.dumps(result, indent=2)}\n\nLink: {link}"
2063
+
2064
+
2065
+ def _rewrite_modify_doc_text_http_error(
2066
+ error: HttpError, segment_id: Optional[str]
2067
+ ) -> Exception:
2068
+ """
2069
+ Convert common low-level Docs API failures into actionable caller guidance.
2070
+ """
2071
+ details = str(error)
2072
+ lowered = details.lower()
2073
+
2074
+ if segment_id and "segment with id" in lowered and "was not found" in lowered:
2075
+ return UserInputError(
2076
+ f"segment_id '{segment_id}' was not found. segment_id must be a real "
2077
+ "header/footer/footnote ID returned by inspect_doc_structure; do not "
2078
+ "guess IDs such as 'kix.header'. For ordinary header/footer text, use "
2079
+ "update_doc_headers_footers instead."
2080
+ )
2081
+
2082
+ return error
2083
+
2084
+
2085
+ def _build_segment_inspection_entries(
2086
+ doc: dict[str, Any], structure: dict[str, Any], section_type: str
2087
+ ) -> list[dict[str, Any]]:
2088
+ """
2089
+ Build header/footer inspection entries from both populated segments and style IDs.
2090
+ """
2091
+ parsed_segments = (
2092
+ structure["headers"] if section_type == "header" else structure["footers"]
2093
+ )
2094
+ entries: dict[str, dict[str, Any]] = {}
2095
+
2096
+ for segment_id, segment_info in parsed_segments.items():
2097
+ entries[segment_id] = {
2098
+ "segment_id": segment_id,
2099
+ "start_index": segment_info["start_index"],
2100
+ "end_index": segment_info["end_index"],
2101
+ "content_preview": segment_info.get("text_preview", ""),
2102
+ "element_count": segment_info.get("element_count", 0),
2103
+ "source": "segment_content",
2104
+ }
2105
+
2106
+ style_field_map = {
2107
+ "header": {
2108
+ "DEFAULT": "defaultHeaderId",
2109
+ "FIRST_PAGE_ONLY": "firstPageHeaderId",
2110
+ "EVEN_PAGE": "evenPageHeaderId",
2111
+ },
2112
+ "footer": {
2113
+ "DEFAULT": "defaultFooterId",
2114
+ "FIRST_PAGE_ONLY": "firstPageFooterId",
2115
+ "EVEN_PAGE": "evenPageFooterId",
2116
+ },
2117
+ }
2118
+
2119
+ for variant, style_field in style_field_map[section_type].items():
2120
+ doc_style_id = doc.get("documentStyle", {}).get(style_field)
2121
+ if doc_style_id and doc_style_id not in entries:
2122
+ entries[doc_style_id] = {
2123
+ "segment_id": doc_style_id,
2124
+ "start_index": 0,
2125
+ "end_index": 0,
2126
+ "content_preview": "",
2127
+ "element_count": 0,
2128
+ "source": f"documentStyle.{style_field}",
2129
+ "variant": variant,
2130
+ }
2131
+
2132
+ for element in doc.get("body", {}).get("content", []):
2133
+ section_style = element.get("sectionBreak", {}).get("sectionStyle", {})
2134
+ if not section_style:
2135
+ continue
2136
+ section_id = section_style.get(style_field)
2137
+ if section_id and section_id not in entries:
2138
+ entries[section_id] = {
2139
+ "segment_id": section_id,
2140
+ "start_index": 0,
2141
+ "end_index": 0,
2142
+ "content_preview": "",
2143
+ "element_count": 0,
2144
+ "source": f"sectionStyle.{style_field}",
2145
+ "variant": variant,
2146
+ }
2147
+ break
2148
+
2149
+ return list(entries.values())
2150
+
2151
+
2152
+ @server.tool(
2153
+ title="Create Table with Data",
2154
+ annotations=ToolAnnotations(
2155
+ readOnlyHint=False,
2156
+ destructiveHint=False,
2157
+ idempotentHint=False,
2158
+ openWorldHint=True,
2159
+ ),
2160
+ )
2161
+ @handle_http_errors("create_table_with_data", service_type="docs")
2162
+ @require_google_service("docs", "docs_write")
2163
+ async def create_table_with_data(
2164
+ service: Any,
2165
+ user_google_email: str,
2166
+ document_id: str,
2167
+ table_data: List[List[str]],
2168
+ index: int,
2169
+ bold_headers: bool = True,
2170
+ tab_id: Optional[str] = None,
2171
+ header_rows: int = 0,
2172
+ ) -> str:
2173
+ """
2174
+ Creates a table and populates it with data in one reliable operation.
2175
+
2176
+ CRITICAL: YOU MUST CALL inspect_doc_structure FIRST TO GET THE INDEX!
2177
+
2178
+ MANDATORY WORKFLOW - DO THESE STEPS IN ORDER:
2179
+
2180
+ Step 1: ALWAYS call inspect_doc_structure first
2181
+ Step 2: Use the 'total_length' value from inspect_doc_structure as your index
2182
+ Step 3: Format data as 2D list: [["col1", "col2"], ["row1col1", "row1col2"]]
2183
+ Step 4: Call this function with the correct index and data
2184
+
2185
+ EXAMPLE DATA FORMAT:
2186
+ table_data = [
2187
+ ["Header1", "Header2", "Header3"], # Row 0 - headers
2188
+ ["Data1", "Data2", "Data3"], # Row 1 - first data row
2189
+ ["Data4", "Data5", "Data6"] # Row 2 - second data row
2190
+ ]
2191
+
2192
+ CRITICAL INDEX REQUIREMENTS:
2193
+ - NEVER use index values like 1, 2, 10 without calling inspect_doc_structure first
2194
+ - ALWAYS get index from inspect_doc_structure 'total_length' field
2195
+ - Index must be a valid insertion point in the document
2196
+
2197
+ DATA FORMAT REQUIREMENTS:
2198
+ - Must be 2D list of strings only
2199
+ - Each inner list = one table row
2200
+ - All rows MUST have same number of columns
2201
+ - Use empty strings "" for empty cells, never None
2202
+ - Use debug_table_structure after creation to verify results
2203
+
2204
+ Args:
2205
+ user_google_email: User's Google email address
2206
+ document_id: ID of the document to update
2207
+ table_data: 2D list of strings - EXACT format: [["col1", "col2"], ["row1col1", "row1col2"]]
2208
+ index: Document position (MANDATORY: get from inspect_doc_structure 'total_length')
2209
+ bold_headers: Whether to make first row bold (default: true)
2210
+ tab_id: Optional tab ID to create the table in a specific tab
2211
+ header_rows: Number of leading rows to mark as a repeating header that
2212
+ reappears after each page break. Must be between 0 and the number of
2213
+ table rows (default: 0 = none)
2214
+
2215
+ Returns:
2216
+ str: Confirmation with table details and link
2217
+ """
2218
+ logger.debug(f"[create_table_with_data] Doc={document_id}, index={index}")
2219
+
2220
+ # Input validation
2221
+ validator = ValidationManager()
2222
+
2223
+ is_valid, error_msg = validator.validate_document_id(document_id)
2224
+ if not is_valid:
2225
+ return f"ERROR: {error_msg}"
2226
+
2227
+ is_valid, error_msg = validator.validate_table_data(table_data)
2228
+ if not is_valid:
2229
+ return f"ERROR: {error_msg}"
2230
+
2231
+ is_valid, error_msg = validator.validate_index(index, "Index")
2232
+ if not is_valid:
2233
+ return f"ERROR: {error_msg}"
2234
+
2235
+ # Use TableOperationManager to handle the complex logic
2236
+ table_manager = TableOperationManager(service)
2237
+
2238
+ # Try to create the table, and if it fails due to index being at document end, retry with index-1
2239
+ effective_index = index
2240
+ success, message, metadata = await table_manager.create_and_populate_table(
2241
+ document_id, table_data, index, bold_headers, tab_id, header_rows
2242
+ )
2243
+
2244
+ # If it failed due to index being at or beyond document end, retry with adjusted index
2245
+ if not success and "must be less than the end index" in message:
2246
+ logger.debug(
2247
+ f"Index {index} is at document boundary, retrying with index {index - 1}"
2248
+ )
2249
+ effective_index = index - 1
2250
+ success, message, metadata = await table_manager.create_and_populate_table(
2251
+ document_id,
2252
+ table_data,
2253
+ effective_index,
2254
+ bold_headers,
2255
+ tab_id,
2256
+ header_rows,
2257
+ )
2258
+
2259
+ if success:
2260
+ link = f"https://docs.google.com/document/d/{document_id}/edit"
2261
+ rows = metadata.get("rows", 0)
2262
+ columns = metadata.get("columns", 0)
2263
+ status = "PARTIAL SUCCESS" if metadata.get("partial_success") else "SUCCESS"
2264
+
2265
+ return f"{status}: {message}. Table: {rows}x{columns}, Index: {effective_index}. Link: {link}"
2266
+ else:
2267
+ return f"ERROR: {message}"
2268
+
2269
+
2270
+ @server.tool(
2271
+ title="Debug Table Structure",
2272
+ annotations=ToolAnnotations(
2273
+ readOnlyHint=True,
2274
+ destructiveHint=False,
2275
+ idempotentHint=True,
2276
+ openWorldHint=True,
2277
+ ),
2278
+ )
2279
+ @handle_http_errors("debug_table_structure", is_read_only=True, service_type="docs")
2280
+ @require_google_service("docs", "docs_read")
2281
+ async def debug_table_structure(
2282
+ service: Any,
2283
+ user_google_email: str,
2284
+ document_id: str,
2285
+ table_index: int = 0,
2286
+ tab_id: Optional[str] = None,
2287
+ ) -> str:
2288
+ """
2289
+ ESSENTIAL DEBUGGING TOOL - Use this whenever tables don't work as expected.
2290
+
2291
+ USE THIS IMMEDIATELY WHEN:
2292
+ - Table population put data in wrong cells
2293
+ - You get "table not found" errors
2294
+ - Data appears concatenated in first cell
2295
+ - Need to understand existing table structure
2296
+ - Planning to fill existing cells with modify_doc_text at their insertion_index
2297
+
2298
+ WHAT THIS SHOWS YOU:
2299
+ - Exact table dimensions (rows × columns)
2300
+ - Each cell's position coordinates (row,col)
2301
+ - Current content in each cell
2302
+ - Insertion indices for each cell
2303
+ - Table boundaries and ranges
2304
+
2305
+ HOW TO READ THE OUTPUT:
2306
+ - "dimensions": "2x3" = 2 rows, 3 columns
2307
+ - "position": "(0,0)" = first row, first column
2308
+ - "current_content": What's actually in each cell right now
2309
+ - "insertion_index": Where new text would be inserted in that cell
2310
+
2311
+ WORKFLOW INTEGRATION:
2312
+ 1. After creating table → Use this to verify structure
2313
+ 2. Before populating → Use this to plan your data format
2314
+ 3. After population fails → Use this to see what went wrong
2315
+ 4. When debugging → Compare your data array to actual table structure
2316
+
2317
+ Args:
2318
+ user_google_email: User's Google email address
2319
+ document_id: ID of the document to inspect
2320
+ table_index: Which table to debug (0 = first table, 1 = second table, etc.)
2321
+ tab_id: Optional ID of the tab containing the table (from inspect_doc_structure).
2322
+ If not provided, inspects the first tab.
2323
+
2324
+ Returns:
2325
+ str: Detailed JSON structure showing table layout, cell positions, and current content
2326
+ """
2327
+ logger.debug(
2328
+ f"[debug_table_structure] Doc={document_id}, table_index={table_index}, "
2329
+ f"tab_id={tab_id}"
2330
+ )
2331
+
2332
+ # Get the document
2333
+ doc = await asyncio.to_thread(
2334
+ service.documents()
2335
+ .get(documentId=document_id, includeTabsContent=bool(tab_id))
2336
+ .execute
2337
+ )
2338
+
2339
+ if tab_id:
2340
+ tab = _find_tab(doc.get("tabs", []), tab_id)
2341
+ if not tab:
2342
+ return f"Error: Tab {tab_id} not found in document."
2343
+ if "documentTab" not in tab:
2344
+ return f"Error: Tab {tab_id} is not a document tab and has no body content."
2345
+ doc = tab["documentTab"]
2346
+
2347
+ # Find tables
2348
+ tables = find_tables(doc)
2349
+ if table_index >= len(tables):
2350
+ return f"Error: Table index {table_index} not found. Document has {len(tables)} table(s)."
2351
+
2352
+ table_info = tables[table_index]
2353
+
2354
+ # Extract detailed cell information
2355
+ debug_info = {
2356
+ "table_index": table_index,
2357
+ "dimensions": f"{table_info['rows']}x{table_info['columns']}",
2358
+ "table_range": f"[{table_info['start_index']}-{table_info['end_index']}]",
2359
+ "cells": [],
2360
+ }
2361
+
2362
+ for row_idx, row in enumerate(table_info["cells"]):
2363
+ row_info = []
2364
+ for col_idx, cell in enumerate(row):
2365
+ cell_debug = {
2366
+ "position": f"({row_idx},{col_idx})",
2367
+ "range": f"[{cell['start_index']}-{cell['end_index']}]",
2368
+ "insertion_index": cell.get("insertion_index", "N/A"),
2369
+ "current_content": repr(cell.get("content", "")),
2370
+ "content_elements_count": len(cell.get("content_elements", [])),
2371
+ }
2372
+ row_info.append(cell_debug)
2373
+ debug_info["cells"].append(row_info)
2374
+
2375
+ link = f"https://docs.google.com/document/d/{document_id}/edit"
2376
+ return f"Table structure debug for table {table_index}:\n\n{json.dumps(debug_info, indent=2)}\n\nLink: {link}"
2377
+
2378
+
2379
+ @server.tool(
2380
+ title="Export Doc to PDF",
2381
+ annotations=ToolAnnotations(
2382
+ readOnlyHint=False,
2383
+ destructiveHint=False,
2384
+ idempotentHint=False,
2385
+ openWorldHint=True,
2386
+ ),
2387
+ )
2388
+ @handle_http_errors("export_doc_to_pdf", service_type="drive")
2389
+ @require_google_service("drive", "drive_file")
2390
+ async def export_doc_to_pdf(
2391
+ service: Any,
2392
+ user_google_email: str,
2393
+ document_id: str,
2394
+ pdf_filename: Optional[str] = None,
2395
+ folder_id: Optional[str] = None,
2396
+ ) -> str:
2397
+ """
2398
+ Exports a Google Doc to PDF format and saves it to Google Drive.
2399
+
2400
+ Args:
2401
+ user_google_email: User's Google email address
2402
+ document_id: ID of the Google Doc to export
2403
+ pdf_filename: Name for the PDF file (optional - if not provided, uses original name + "_PDF")
2404
+ folder_id: Drive folder ID to save PDF in (optional - if not provided, saves in root)
2405
+
2406
+ Returns:
2407
+ str: Confirmation message with PDF file details and links
2408
+ """
2409
+ logger.info(
2410
+ f"[export_doc_to_pdf] Email={user_google_email}, Doc={document_id}, pdf_filename={pdf_filename}, folder_id={folder_id}"
2411
+ )
2412
+
2413
+ # Get file metadata first to validate it's a Google Doc
2414
+ try:
2415
+ file_metadata = await asyncio.to_thread(
2416
+ service.files()
2417
+ .get(
2418
+ fileId=document_id,
2419
+ fields="id, name, mimeType, webViewLink",
2420
+ supportsAllDrives=True,
2421
+ )
2422
+ .execute
2423
+ )
2424
+ except Exception as e:
2425
+ return f"Error: Could not access document {document_id}: {str(e)}"
2426
+
2427
+ mime_type = file_metadata.get("mimeType", "")
2428
+ original_name = file_metadata.get("name", "Unknown Document")
2429
+ web_view_link = file_metadata.get("webViewLink", "#")
2430
+
2431
+ # Verify it's a Google Doc
2432
+ if mime_type != "application/vnd.google-apps.document":
2433
+ return f"Error: File '{original_name}' is not a Google Doc (MIME type: {mime_type}). Only native Google Docs can be exported to PDF."
2434
+
2435
+ logger.info(f"[export_doc_to_pdf] Exporting doc {document_id} to PDF")
2436
+
2437
+ # Export the document as PDF
2438
+ try:
2439
+ request_obj = service.files().export_media(
2440
+ fileId=document_id, mimeType="application/pdf"
2441
+ )
2442
+
2443
+ try:
2444
+ pdf_content = await download_media_bytes(
2445
+ request_obj,
2446
+ file_name=original_name,
2447
+ file_id=document_id,
2448
+ web_view_link=web_view_link,
2449
+ )
2450
+ except FileTooLargeError as e:
2451
+ return str(e)
2452
+
2453
+ pdf_size = len(pdf_content)
2454
+ fh = io.BytesIO(pdf_content)
2455
+
2456
+ except Exception as e:
2457
+ return f"Error: Failed to export document to PDF: {str(e)}"
2458
+
2459
+ # Determine PDF filename
2460
+ if not pdf_filename:
2461
+ pdf_filename = f"{original_name}_PDF.pdf"
2462
+ elif not pdf_filename.endswith(".pdf"):
2463
+ pdf_filename += ".pdf"
2464
+
2465
+ # Upload PDF to Drive
2466
+ try:
2467
+ # Create media upload object
2468
+ media = MediaIoBaseUpload(fh, mimetype="application/pdf", resumable=True)
2469
+
2470
+ # Prepare file metadata for upload
2471
+ file_metadata = {"name": pdf_filename, "mimeType": "application/pdf"}
2472
+
2473
+ # Add parent folder if specified
2474
+ if folder_id:
2475
+ file_metadata["parents"] = [folder_id]
2476
+
2477
+ # Upload the file
2478
+ uploaded_file = await asyncio.to_thread(
2479
+ service.files()
2480
+ .create(
2481
+ body=file_metadata,
2482
+ media_body=media,
2483
+ fields="id, name, webViewLink, parents",
2484
+ supportsAllDrives=True,
2485
+ )
2486
+ .execute,
2487
+ num_retries=GOOGLE_API_WRITE_RETRIES,
2488
+ )
2489
+
2490
+ pdf_file_id = uploaded_file.get("id")
2491
+ pdf_web_link = uploaded_file.get("webViewLink", "#")
2492
+ pdf_parents = uploaded_file.get("parents", [])
2493
+
2494
+ logger.info(
2495
+ f"[export_doc_to_pdf] Successfully uploaded PDF to Drive: {pdf_file_id}"
2496
+ )
2497
+
2498
+ folder_info = ""
2499
+ if folder_id:
2500
+ folder_info = f" in folder {folder_id}"
2501
+ elif pdf_parents:
2502
+ folder_info = f" in folder {pdf_parents[0]}"
2503
+
2504
+ return f"Successfully exported '{original_name}' to PDF and saved to Drive as '{pdf_filename}' (ID: {pdf_file_id}, {pdf_size:,} bytes){folder_info}. PDF: {pdf_web_link} | Original: {web_view_link}"
2505
+
2506
+ except Exception as e:
2507
+ return f"Error: Failed to upload PDF to Drive: {str(e)}. PDF was generated successfully ({pdf_size:,} bytes) but could not be saved to Drive."
2508
+
2509
+
2510
+ # ==============================================================================
2511
+ # STYLING TOOLS - Paragraph Formatting
2512
+ # ==============================================================================
2513
+
2514
+
2515
+ async def _get_paragraph_start_indices_in_range(
2516
+ service: Any, document_id: str, start_index: int, end_index: int
2517
+ ) -> list[int]:
2518
+ """
2519
+ Fetch paragraph start indices that overlap a target range.
2520
+ """
2521
+ doc_data = await asyncio.to_thread(
2522
+ service.documents()
2523
+ .get(
2524
+ documentId=document_id,
2525
+ fields="body/content(startIndex,endIndex,paragraph)",
2526
+ )
2527
+ .execute
2528
+ )
2529
+
2530
+ paragraph_starts = []
2531
+ for element in doc_data.get("body", {}).get("content", []):
2532
+ if "paragraph" not in element:
2533
+ continue
2534
+ paragraph_start = element.get("startIndex")
2535
+ paragraph_end = element.get("endIndex")
2536
+ if not isinstance(paragraph_start, int) or not isinstance(paragraph_end, int):
2537
+ continue
2538
+ if paragraph_end > start_index and paragraph_start < end_index:
2539
+ paragraph_starts.append(paragraph_start)
2540
+
2541
+ return paragraph_starts or [start_index]
2542
+
2543
+
2544
+ @server.tool(
2545
+ title="Update Paragraph Style",
2546
+ annotations=ToolAnnotations(
2547
+ readOnlyHint=False,
2548
+ destructiveHint=False,
2549
+ idempotentHint=False,
2550
+ openWorldHint=True,
2551
+ ),
2552
+ )
2553
+ @handle_http_errors("update_paragraph_style", service_type="docs")
2554
+ @require_google_service("docs", "docs_write")
2555
+ async def update_paragraph_style(
2556
+ service: Any,
2557
+ user_google_email: str,
2558
+ document_id: str,
2559
+ start_index: int,
2560
+ end_index: int,
2561
+ heading_level: Optional[int] = None,
2562
+ alignment: Optional[str] = None,
2563
+ line_spacing: Optional[float] = None,
2564
+ indent_first_line: Optional[float] = None,
2565
+ indent_start: Optional[float] = None,
2566
+ indent_end: Optional[float] = None,
2567
+ space_above: Optional[float] = None,
2568
+ space_below: Optional[float] = None,
2569
+ named_style_type: Optional[str] = None,
2570
+ tab_id: Optional[str] = None,
2571
+ segment_id: Optional[str] = None,
2572
+ direction: Optional[str] = None,
2573
+ keep_lines_together: Optional[bool] = None,
2574
+ keep_with_next: Optional[bool] = None,
2575
+ avoid_widow_and_orphan: Optional[bool] = None,
2576
+ page_break_before: Optional[bool] = None,
2577
+ spacing_mode: Optional[str] = None,
2578
+ shading_color: Optional[str] = None,
2579
+ border_edges: Optional[list[ParagraphBorderEdge]] = None,
2580
+ border_color: Optional[str] = None,
2581
+ border_width: Optional[float] = None,
2582
+ border_padding: Optional[float] = None,
2583
+ border_dash: Optional[str] = None,
2584
+ list_type: Optional[str] = None,
2585
+ list_nesting_level: Optional[int] = None,
2586
+ bullet_preset: Optional[str] = None,
2587
+ ) -> str:
2588
+ """
2589
+ Apply paragraph-level formatting, heading styles, and/or list formatting to a range in a Google Doc.
2590
+
2591
+ This tool can apply named heading styles (H1-H6) for semantic document structure,
2592
+ create bulleted or numbered lists with nested indentation, and customize paragraph
2593
+ properties like alignment, spacing, and indentation. All operations can be applied
2594
+ in a single call.
2595
+
2596
+ Args:
2597
+ user_google_email: User's Google email address
2598
+ document_id: Document ID to modify
2599
+ start_index: Start position using Docs API indices from
2600
+ inspect_doc_structure. For the main body, 0 is also accepted as an
2601
+ alias for the first writable position.
2602
+ end_index: End position (exclusive) - should cover the entire paragraph
2603
+ heading_level: Heading level 0-6 (0 = NORMAL_TEXT, 1 = H1, 2 = H2, etc.)
2604
+ Use for semantic document structure
2605
+ alignment: Text alignment - 'START' (left), 'CENTER', 'END' (right), or 'JUSTIFIED'
2606
+ line_spacing: Line spacing multiplier (1.0 = single, 1.5 = 1.5x, 2.0 = double)
2607
+ indent_first_line: First line indent in points (e.g., 36 for 0.5 inch)
2608
+ indent_start: Left/start indent in points
2609
+ indent_end: Right/end indent in points
2610
+ space_above: Space above paragraph in points (e.g., 12 for one line)
2611
+ space_below: Space below paragraph in points
2612
+ named_style_type: Direct named style type - 'NORMAL_TEXT', 'TITLE', 'SUBTITLE',
2613
+ 'HEADING_1' through 'HEADING_6'. Mutually exclusive with heading_level.
2614
+ tab_id: Optional document tab ID to target
2615
+ segment_id: Optional header/footer/footnote segment ID to target
2616
+ direction: Paragraph direction - 'LEFT_TO_RIGHT' or 'RIGHT_TO_LEFT'
2617
+ keep_lines_together: Keep all lines of the paragraph together
2618
+ keep_with_next: Keep the paragraph with the next paragraph
2619
+ avoid_widow_and_orphan: Avoid widows/orphans for the paragraph
2620
+ page_break_before: Start the paragraph on a new page
2621
+ spacing_mode: 'NEVER_COLLAPSE' or 'COLLAPSE_LISTS'
2622
+ shading_color: Paragraph shading/background color (#RRGGBB)
2623
+ border_edges: Paragraph border edges to update ('top', 'bottom', 'left',
2624
+ 'right', or 'between'); omit to update all four outer edges
2625
+ border_color: Border color (#RRGGBB; defaults to black)
2626
+ border_width: Border width in points (defaults to 1)
2627
+ border_padding: Border padding in points (defaults to 4)
2628
+ border_dash: Border dash style ('SOLID', 'DOT', or 'DASH'; defaults to 'SOLID')
2629
+ list_type: Create a list from existing paragraphs ('UNORDERED' for bullets, 'ORDERED' for numbers, 'CHECKBOX' for checklists), or 'NONE' to remove existing list formatting from the range. Use 'NONE' when text inserted after a list has inherited its bullets: setting named_style_type or heading_level does not clear list membership, only 'NONE' does.
2630
+ list_nesting_level: Nesting level for lists (0-8, where 0 is top level, default is 0)
2631
+ Use higher levels for nested/indented list items
2632
+ bullet_preset: Optional explicit Google Docs bullet preset
2633
+
2634
+ Returns:
2635
+ str: Confirmation message with formatting details
2636
+
2637
+ Examples:
2638
+ # Apply H1 heading style
2639
+ update_paragraph_style(document_id="...", start_index=1, end_index=20, heading_level=1)
2640
+
2641
+ # Create a bulleted list
2642
+ update_paragraph_style(document_id="...", start_index=1, end_index=50,
2643
+ list_type="UNORDERED")
2644
+
2645
+ # Create a nested numbered list item
2646
+ update_paragraph_style(document_id="...", start_index=1, end_index=30,
2647
+ list_type="ORDERED", list_nesting_level=1)
2648
+
2649
+ # Apply H2 heading with custom spacing
2650
+ update_paragraph_style(document_id="...", start_index=1, end_index=30,
2651
+ heading_level=2, space_above=18, space_below=12)
2652
+
2653
+ # Center-align a paragraph with double spacing
2654
+ update_paragraph_style(document_id="...", start_index=1, end_index=50,
2655
+ alignment="CENTER", line_spacing=2.0)
2656
+ """
2657
+ logger.info(
2658
+ f"[update_paragraph_style] Doc={document_id}, Range: {start_index}-{end_index}"
2659
+ )
2660
+
2661
+ # Validate range
2662
+ if start_index < 0:
2663
+ return "Error: start_index must be >= 0"
2664
+ if end_index <= start_index:
2665
+ return "Error: end_index must be greater than start_index"
2666
+
2667
+ # Validate list parameters
2668
+ list_type_value = list_type
2669
+ if list_type_value is not None:
2670
+ # Coerce non-string inputs to string before normalization to avoid AttributeError
2671
+ if not isinstance(list_type_value, str):
2672
+ list_type_value = str(list_type_value)
2673
+ valid_list_types = ["UNORDERED", "ORDERED", "CHECKBOX", "NONE"]
2674
+ normalized_list_type = list_type_value.upper()
2675
+ if normalized_list_type not in valid_list_types:
2676
+ return f"Error: list_type must be one of: {', '.join(valid_list_types)}"
2677
+
2678
+ list_type_value = normalized_list_type
2679
+
2680
+ if list_nesting_level is not None:
2681
+ if list_type_value is None:
2682
+ return "Error: list_nesting_level requires list_type parameter"
2683
+ if list_type_value == "NONE":
2684
+ return "Error: list_nesting_level cannot be used with list_type='NONE'"
2685
+ if not isinstance(list_nesting_level, int):
2686
+ return "Error: list_nesting_level must be an integer"
2687
+ if list_nesting_level < 0 or list_nesting_level > 8:
2688
+ return "Error: list_nesting_level must be between 0 and 8"
2689
+
2690
+ if bullet_preset is not None and list_type_value in (None, "NONE"):
2691
+ return "Error: bullet_preset requires list_type 'UNORDERED', 'ORDERED', or 'CHECKBOX'"
2692
+
2693
+ style_params = {
2694
+ "heading_level": heading_level,
2695
+ "alignment": alignment,
2696
+ "line_spacing": line_spacing,
2697
+ "indent_first_line": indent_first_line,
2698
+ "indent_start": indent_start,
2699
+ "indent_end": indent_end,
2700
+ "space_above": space_above,
2701
+ "space_below": space_below,
2702
+ "named_style_type": named_style_type,
2703
+ "direction": direction,
2704
+ "keep_lines_together": keep_lines_together,
2705
+ "keep_with_next": keep_with_next,
2706
+ "avoid_widow_and_orphan": avoid_widow_and_orphan,
2707
+ "page_break_before": page_break_before,
2708
+ "spacing_mode": spacing_mode,
2709
+ "shading_color": shading_color,
2710
+ "border_edges": border_edges,
2711
+ "border_color": border_color,
2712
+ "border_width": border_width,
2713
+ "border_padding": border_padding,
2714
+ "border_dash": border_dash,
2715
+ }
2716
+ # A list-only call has no style params, so skip the validator's
2717
+ # "at least one style param" check rather than discarding its errors.
2718
+ if list_type_value is None or any(v is not None for v in style_params.values()):
2719
+ is_valid, error_msg = ValidationManager().validate_paragraph_style_params(
2720
+ **style_params
2721
+ )
2722
+ if not is_valid:
2723
+ return f"Error: {error_msg}"
2724
+
2725
+ # Create batch update requests
2726
+ requests = []
2727
+
2728
+ # Add paragraph style update if we have any style changes
2729
+ paragraph_style_request = create_update_paragraph_style_request(
2730
+ start_index,
2731
+ end_index,
2732
+ heading_level,
2733
+ alignment,
2734
+ line_spacing,
2735
+ indent_first_line,
2736
+ indent_start,
2737
+ indent_end,
2738
+ space_above,
2739
+ space_below,
2740
+ tab_id,
2741
+ named_style_type,
2742
+ segment_id,
2743
+ direction,
2744
+ keep_lines_together,
2745
+ keep_with_next,
2746
+ avoid_widow_and_orphan,
2747
+ page_break_before,
2748
+ spacing_mode,
2749
+ shading_color,
2750
+ border_edges,
2751
+ border_color,
2752
+ border_width,
2753
+ border_padding,
2754
+ border_dash,
2755
+ )
2756
+ if paragraph_style_request:
2757
+ requests.append(paragraph_style_request)
2758
+
2759
+ # Add list creation or removal if requested
2760
+ if list_type_value == "NONE":
2761
+ # Docs continues list membership into text inserted after a list, and a
2762
+ # named-style change does not clear it. Only deleteParagraphBullets does.
2763
+ requests.append(
2764
+ create_delete_bullet_list_request(
2765
+ start_index, end_index, tab_id, segment_id=segment_id
2766
+ )
2767
+ )
2768
+ elif list_type_value is not None:
2769
+ # Default to level 0 if not specified
2770
+ nesting_level = list_nesting_level if list_nesting_level is not None else 0
2771
+ try:
2772
+ paragraph_start_indices = None
2773
+ if nesting_level > 0:
2774
+ paragraph_start_indices = await _get_paragraph_start_indices_in_range(
2775
+ service, document_id, start_index, end_index
2776
+ )
2777
+ list_requests = create_bullet_list_request(
2778
+ start_index,
2779
+ end_index,
2780
+ list_type_value,
2781
+ nesting_level,
2782
+ paragraph_start_indices=paragraph_start_indices,
2783
+ doc_tab_id=tab_id,
2784
+ bullet_preset=bullet_preset,
2785
+ segment_id=segment_id,
2786
+ )
2787
+ requests.extend(list_requests)
2788
+ except ValueError as e:
2789
+ return f"Error: {e}"
2790
+
2791
+ # Validate we have at least one operation
2792
+ if not requests:
2793
+ return f"No paragraph style changes or list creation specified for document {document_id}"
2794
+
2795
+ await asyncio.to_thread(
2796
+ service.documents()
2797
+ .batchUpdate(documentId=document_id, body={"requests": requests})
2798
+ .execute
2799
+ )
2800
+
2801
+ # Build summary
2802
+ summary_parts = []
2803
+ if named_style_type is not None:
2804
+ summary_parts.append(named_style_type)
2805
+ elif heading_level is not None:
2806
+ summary_parts.append(
2807
+ "NORMAL_TEXT" if heading_level == 0 else f"HEADING_{heading_level}"
2808
+ )
2809
+ detail_labels = [
2810
+ name
2811
+ for name, value in style_params.items()
2812
+ if value is not None and name not in ("heading_level", "named_style_type")
2813
+ ]
2814
+ if detail_labels:
2815
+ summary_parts.append(", ".join(detail_labels))
2816
+ if list_type_value is not None:
2817
+ list_desc = f"{list_type_value.lower()} list"
2818
+ if list_nesting_level is not None and list_nesting_level > 0:
2819
+ list_desc += f" (level {list_nesting_level})"
2820
+ if bullet_preset is not None:
2821
+ list_desc += f" using {bullet_preset}"
2822
+ summary_parts.append(list_desc)
2823
+
2824
+ link = f"https://docs.google.com/document/d/{document_id}/edit"
2825
+ return f"Applied paragraph formatting ({', '.join(summary_parts)}) to range {start_index}-{end_index} in document {document_id}. Link: {link}"
2826
+
2827
+
2828
+ @server.tool(
2829
+ title="Get Doc as Markdown",
2830
+ annotations=ToolAnnotations(
2831
+ readOnlyHint=True,
2832
+ destructiveHint=False,
2833
+ idempotentHint=True,
2834
+ openWorldHint=True,
2835
+ ),
2836
+ )
2837
+ @handle_http_errors("get_doc_as_markdown", is_read_only=True, service_type="docs")
2838
+ @require_multiple_services(
2839
+ [
2840
+ {
2841
+ "service_type": "drive",
2842
+ "scopes": "drive_read",
2843
+ "param_name": "drive_service",
2844
+ },
2845
+ {"service_type": "docs", "scopes": "docs_read", "param_name": "docs_service"},
2846
+ ]
2847
+ )
2848
+ async def get_doc_as_markdown(
2849
+ drive_service: Any,
2850
+ docs_service: Any,
2851
+ user_google_email: str,
2852
+ document_id: str,
2853
+ include_comments: bool = True,
2854
+ comment_mode: str = "inline",
2855
+ include_resolved: bool = False,
2856
+ suggestions_view_mode: str = "DEFAULT_FOR_CURRENT_ACCESS",
2857
+ tab_id: Optional[str] = None,
2858
+ include_colors: bool = False,
2859
+ heading: Optional[str] = None,
2860
+ heading_level: Optional[int] = None,
2861
+ ) -> str:
2862
+ """
2863
+ Reads a Google Doc and returns it as clean Markdown with optional comment context.
2864
+
2865
+ Unlike get_doc_content which returns plain text, this tool preserves document
2866
+ formatting as Markdown: headings, bold/italic/strikethrough, links, code spans,
2867
+ ordered/unordered lists with nesting, and tables.
2868
+
2869
+ When comments are included (the default), each comment's anchor text — the specific
2870
+ text the comment was attached to — is preserved, giving full context for the discussion.
2871
+
2872
+ Args:
2873
+ user_google_email: User's Google email address
2874
+ document_id: ID of the Google Doc (or full URL). When a full URL is provided
2875
+ and it contains a ?tab= query parameter, that tab is used automatically
2876
+ unless tab_id is also specified (explicit tab_id takes precedence).
2877
+ include_comments: Whether to include comments (default: True)
2878
+ comment_mode: How to display comments:
2879
+ - "inline": Footnote-style references placed at the anchor text location (default)
2880
+ - "appendix": All comments grouped at the bottom with blockquoted anchor text
2881
+ - "none": No comments included
2882
+ include_resolved: Whether to include resolved comments (default: False)
2883
+ suggestions_view_mode: How to render suggestions in the returned content:
2884
+ - "DEFAULT_FOR_CURRENT_ACCESS": SUGGESTIONS_INLINE with edit access,
2885
+ PREVIEW_WITHOUT_SUGGESTIONS with view-only access
2886
+ - "SUGGESTIONS_INLINE": Suggested changes appear inline, marked as
2887
+ {++inserted text++} and {--deleted text--} with a legend at the top;
2888
+ suggested text formatting is shown as if accepted
2889
+ - "PREVIEW_SUGGESTIONS_ACCEPTED": Preview as if all suggestions were accepted
2890
+ - "PREVIEW_WITHOUT_SUGGESTIONS": Preview as if all suggestions were rejected
2891
+ tab_id: Optional ID of a single tab to read (from inspect_doc_structure).
2892
+ When given, only that tab's content is rendered, without its child tabs
2893
+ and without a tab heading, and comments are listed as document-wide.
2894
+ When omitted, every tab is rendered. Pass "" to read every tab of a
2895
+ URL that carries ?tab=. This filters output only: the whole document
2896
+ is still fetched.
2897
+ include_colors: Follow text that has an explicit RGB foreground color
2898
+ with "[color: #rrggbb]" (default: False). Theme colors are not shown.
2899
+ heading: Text of a body heading (case-insensitive, must match exactly one)
2900
+ whose section to render instead of the whole document: the heading and
2901
+ everything below it up to the next heading of equal or shallower level.
2902
+ Comments are listed as document-wide. tab_id is required when the doc
2903
+ has multiple tabs.
2904
+ heading_level: Optional 1-6 heading level to narrow the heading match.
2905
+
2906
+ Returns:
2907
+ str: The document content as Markdown, optionally with comments
2908
+ """
2909
+ document_id, tab_id, tab_from_url = _parse_doc_reference(document_id, tab_id)
2910
+
2911
+ valid_modes = ("inline", "appendix", "none")
2912
+ if comment_mode not in valid_modes:
2913
+ return f"Error: comment_mode must be one of {valid_modes}, got '{comment_mode}'"
2914
+
2915
+ validation_error = validate_suggestions_view_mode(suggestions_view_mode)
2916
+ if validation_error:
2917
+ return validation_error
2918
+
2919
+ logger.info(
2920
+ f"[get_doc_as_markdown] Doc={document_id}, tab={tab_id}, comments={include_comments}, mode={comment_mode}"
2921
+ )
2922
+
2923
+ # Fetch document content via Docs API (includeTabsContent for multi-tab docs)
2924
+ try:
2925
+ doc = await asyncio.wait_for(
2926
+ asyncio.to_thread(
2927
+ docs_service.documents()
2928
+ .get(
2929
+ documentId=document_id,
2930
+ includeTabsContent=True,
2931
+ suggestionsViewMode=suggestions_view_mode,
2932
+ )
2933
+ .execute
2934
+ ),
2935
+ timeout=30,
2936
+ )
2937
+ except (TimeoutError, asyncio.TimeoutError):
2938
+ return (
2939
+ f"Error: Timed out fetching document {document_id} from Google Docs API. "
2940
+ "The document may be too large or there may be a network issue. Please try again."
2941
+ )
2942
+
2943
+ notice = ""
2944
+ if heading is not None:
2945
+ tabs = doc.get("tabs", [])
2946
+ doc = heading_section_document(doc, heading, heading_level, tab_id)
2947
+ if tab_from_url:
2948
+ notice = _url_tab_notice(tabs, _find_tab(tabs, tab_id), tab_id)
2949
+ elif tab_id:
2950
+ tabs = doc.get("tabs", [])
2951
+ tab = _find_tab(tabs, tab_id)
2952
+ if tab is None:
2953
+ return f"Error: Tab {tab_id} not found in document."
2954
+ if "documentTab" not in tab:
2955
+ return f"Error: Tab {tab_id} is not a document tab and has no body content."
2956
+ if tab_from_url:
2957
+ notice = _url_tab_notice(tabs, tab, tab_id)
2958
+ # Drop childTabs so only the named tab renders, and leave it as the sole
2959
+ # tab so it renders without a tab heading.
2960
+ doc = {**doc, "tabs": [{k: v for k, v in tab.items() if k != "childTabs"}]}
2961
+
2962
+ markdown = convert_doc_to_markdown(doc, include_colors=include_colors)
2963
+ if notice:
2964
+ markdown = f"*{notice}*\n\n{markdown}"
2965
+
2966
+ if not include_comments or comment_mode == "none":
2967
+ return markdown
2968
+
2969
+ # Fetch comments via Drive API
2970
+ all_comments = []
2971
+ page_token = None
2972
+
2973
+ while True:
2974
+ response = await asyncio.to_thread(
2975
+ drive_service.comments()
2976
+ .list(
2977
+ fileId=document_id,
2978
+ fields="comments(id,content,author,createdTime,modifiedTime,"
2979
+ "resolved,quotedFileContent,"
2980
+ "replies(id,content,author,createdTime,modifiedTime)),"
2981
+ "nextPageToken",
2982
+ includeDeleted=False,
2983
+ pageToken=page_token,
2984
+ )
2985
+ .execute
2986
+ )
2987
+ all_comments.extend(response.get("comments", []))
2988
+ page_token = response.get("nextPageToken")
2989
+ if not page_token:
2990
+ break
2991
+
2992
+ comments = parse_drive_comments(
2993
+ {"comments": all_comments}, include_resolved=include_resolved
2994
+ )
2995
+
2996
+ if not comments:
2997
+ return markdown
2998
+
2999
+ # Drive comments carry no tab association, so with one tab selected they
3000
+ # stay document-wide instead of being pinned to matching text in this tab.
3001
+ partial = bool(tab_id) or heading is not None
3002
+ if comment_mode == "inline" and not partial:
3003
+ return format_comments_inline(markdown, comments)
3004
+ appendix = format_comments_appendix(
3005
+ comments, title="Comments (entire document)" if partial else "Comments"
3006
+ )
3007
+ return markdown.rstrip("\n") + "\n\n" + appendix
3008
+
3009
+
3010
+ def _find_tab_last_element(doc: dict, target_tab_id: str) -> Optional[dict]:
3011
+ """Walk the document tabs tree and return the last element of target tab's body.
3012
+
3013
+ Returns:
3014
+ The last body element (``{}`` for an empty body), or ``None`` when the
3015
+ *target_tab_id* does not exist in the document or when the matching tab
3016
+ has no ``documentTab``.
3017
+ """
3018
+
3019
+ def walk(tabs: list) -> Optional[dict]:
3020
+ for tab in tabs:
3021
+ tab_props = tab.get("tabProperties", {})
3022
+ if tab_props.get("tabId") == target_tab_id:
3023
+ if "documentTab" not in tab:
3024
+ return None
3025
+ document_tab = tab.get("documentTab", {})
3026
+ body = document_tab.get("body", {})
3027
+ content = body.get("content", [])
3028
+ return content[-1] if content else {}
3029
+ child_tabs = tab.get("childTabs", [])
3030
+ if child_tabs:
3031
+ found = walk(child_tabs)
3032
+ if found is not None:
3033
+ return found
3034
+ return None
3035
+
3036
+ return walk(doc.get("tabs", []))
3037
+
3038
+
3039
+ class CreateDocTabResponse(TypedDict):
3040
+ action: Literal["create"]
3041
+ success: bool
3042
+ message: str
3043
+ tab_id: Optional[str]
3044
+ requests_applied: int
3045
+ link: Optional[str]
3046
+
3047
+
3048
+ class DeleteDocTabResponse(TypedDict):
3049
+ action: Literal["delete"]
3050
+ success: bool
3051
+ message: str
3052
+ tab_id: Optional[str]
3053
+ requests_applied: int
3054
+ link: Optional[str]
3055
+
3056
+
3057
+ class RenameDocTabResponse(TypedDict):
3058
+ action: Literal["rename"]
3059
+ success: bool
3060
+ message: str
3061
+ tab_id: Optional[str]
3062
+ requests_applied: int
3063
+ link: Optional[str]
3064
+
3065
+
3066
+ class PopulateMarkdownTabResponse(TypedDict):
3067
+ action: Literal["populate_from_markdown"]
3068
+ success: bool
3069
+ message: str
3070
+ tab_id: Optional[str]
3071
+ requests_applied: int
3072
+ link: Optional[str]
3073
+
3074
+
3075
+ ManageDocTabResponse = Union[
3076
+ CreateDocTabResponse,
3077
+ DeleteDocTabResponse,
3078
+ RenameDocTabResponse,
3079
+ PopulateMarkdownTabResponse,
3080
+ ]
3081
+
3082
+
3083
+ @server.tool(
3084
+ title="Manage Doc Tab",
3085
+ annotations=ToolAnnotations(
3086
+ readOnlyHint=False,
3087
+ destructiveHint=True,
3088
+ idempotentHint=False,
3089
+ openWorldHint=True,
3090
+ ),
3091
+ )
3092
+ @handle_http_errors("manage_doc_tab", service_type="docs")
3093
+ @require_google_service("docs", "docs_write")
3094
+ async def manage_doc_tab(
3095
+ service: Any,
3096
+ user_google_email: str,
3097
+ document_id: str,
3098
+ action: Literal["create", "rename", "delete", "populate_from_markdown"],
3099
+ tab_id: Optional[str] = None,
3100
+ title: Optional[str] = None,
3101
+ index: Optional[int] = None,
3102
+ parent_tab_id: Optional[str] = None,
3103
+ markdown_text: Optional[str] = None,
3104
+ replace_existing: bool = True,
3105
+ ) -> ManageDocTabResponse:
3106
+ """
3107
+ Manage document tabs: create, rename, delete, or populate from Markdown.
3108
+
3109
+ Args:
3110
+ user_google_email: User's Google email address
3111
+ document_id: ID of the document
3112
+ action: Action to perform - "create", "rename", "delete", or "populate_from_markdown"
3113
+ tab_id: Tab ID (required for rename, delete, populate_from_markdown; use inspect_doc_structure to find IDs)
3114
+ title: Tab title (required for create; used by rename)
3115
+ index: Position index for new tab, 0-based among siblings (required for create)
3116
+ parent_tab_id: Optional parent tab ID to nest under (create only)
3117
+ markdown_text: Markdown source to render (populate_from_markdown only)
3118
+ replace_existing: Clear tab body before inserting markdown (default True)
3119
+
3120
+ Returns:
3121
+ dict with action result including document link
3122
+ """
3123
+ logger.info(f"[manage_doc_tab] action={action}, doc={document_id}, tab_id={tab_id}")
3124
+ link = f"https://docs.google.com/document/d/{document_id}/edit"
3125
+
3126
+ if action == "create":
3127
+ if not title:
3128
+ raise UserInputError("'title' is required for the 'create' action.")
3129
+ if index is None:
3130
+ raise UserInputError("'index' is required for the 'create' action.")
3131
+
3132
+ request = create_insert_doc_tab_request(title, index, parent_tab_id)
3133
+ result = await asyncio.to_thread(
3134
+ service.documents()
3135
+ .batchUpdate(documentId=document_id, body={"requests": [request]})
3136
+ .execute
3137
+ )
3138
+
3139
+ new_tab_id = None
3140
+ if "replies" in result and result["replies"]:
3141
+ reply = result["replies"][0]
3142
+ # Google returns under "addDocumentTab"; accept "createDocumentTab"
3143
+ # as a defensive fallback.
3144
+ for key in ("addDocumentTab", "createDocumentTab"):
3145
+ if key in reply:
3146
+ new_tab_id = reply[key].get("tabProperties", {}).get("tabId")
3147
+ break
3148
+
3149
+ msg = f"Inserted tab '{title}' at index {index} in document {document_id}."
3150
+ if new_tab_id:
3151
+ msg += f" Tab ID: {new_tab_id}."
3152
+ if parent_tab_id:
3153
+ msg += f" Nested under parent tab {parent_tab_id}."
3154
+ return {
3155
+ "action": action,
3156
+ "success": True,
3157
+ "message": msg,
3158
+ "tab_id": new_tab_id,
3159
+ "requests_applied": 1,
3160
+ "link": link,
3161
+ }
3162
+
3163
+ if action == "delete":
3164
+ if not tab_id:
3165
+ raise UserInputError("'tab_id' is required for the 'delete' action.")
3166
+
3167
+ request = create_delete_doc_tab_request(tab_id)
3168
+ await asyncio.to_thread(
3169
+ service.documents()
3170
+ .batchUpdate(documentId=document_id, body={"requests": [request]})
3171
+ .execute
3172
+ )
3173
+ return {
3174
+ "action": action,
3175
+ "success": True,
3176
+ "message": f"Deleted tab '{tab_id}' from document {document_id}.",
3177
+ "tab_id": tab_id,
3178
+ "requests_applied": 1,
3179
+ "link": link,
3180
+ }
3181
+
3182
+ if action == "rename":
3183
+ if not tab_id:
3184
+ raise UserInputError("'tab_id' is required for the 'rename' action.")
3185
+ if not title:
3186
+ raise UserInputError("'title' is required for the 'rename' action.")
3187
+
3188
+ request = create_update_doc_tab_request(tab_id, title)
3189
+ await asyncio.to_thread(
3190
+ service.documents()
3191
+ .batchUpdate(documentId=document_id, body={"requests": [request]})
3192
+ .execute
3193
+ )
3194
+ return {
3195
+ "action": action,
3196
+ "success": True,
3197
+ "message": f"Renamed tab '{tab_id}' to '{title}' in document {document_id}.",
3198
+ "tab_id": tab_id,
3199
+ "requests_applied": 1,
3200
+ "link": link,
3201
+ }
3202
+
3203
+ # action == "populate_from_markdown"
3204
+ if not tab_id:
3205
+ raise UserInputError(
3206
+ "'tab_id' is required for the 'populate_from_markdown' action."
3207
+ )
3208
+ if markdown_text is None:
3209
+ raise UserInputError(
3210
+ "'markdown_text' is required for the 'populate_from_markdown' action."
3211
+ )
3212
+
3213
+ all_requests: List[dict] = []
3214
+
3215
+ doc = await asyncio.to_thread(
3216
+ service.documents().get(documentId=document_id, includeTabsContent=True).execute
3217
+ )
3218
+ try:
3219
+ last_element = _find_tab_last_element(doc, tab_id)
3220
+ except ValueError as exc:
3221
+ raise UserInputError(str(exc))
3222
+ if last_element is None:
3223
+ raise UserInputError(f"'{tab_id}' not found in document")
3224
+ tab_end = last_element.get("endIndex", 1)
3225
+
3226
+ if replace_existing:
3227
+ markdown_requests = markdown_to_docs_requests(markdown_text, tab_id=tab_id)
3228
+ if markdown_text.strip() and not markdown_requests:
3229
+ raise UserInputError(
3230
+ "'markdown_text' rendered to no content; the tab was left unchanged."
3231
+ )
3232
+ # tab_end includes the segment-terminating newline that Google Docs
3233
+ # refuses to delete, so we delete up to tab_end - 1. Empty tabs
3234
+ # (tab_end <= 2) have nothing to clear.
3235
+ if tab_end > 2:
3236
+ all_requests.append(
3237
+ {
3238
+ "deleteContentRange": {
3239
+ "range": {
3240
+ "startIndex": 1,
3241
+ "endIndex": tab_end - 1,
3242
+ "tabId": tab_id,
3243
+ }
3244
+ }
3245
+ }
3246
+ )
3247
+ all_requests.extend(markdown_requests)
3248
+ else:
3249
+ # Append after existing content instead of prepending at index 1.
3250
+ insert_at = tab_end - 1 if tab_end > 2 else 1
3251
+ all_requests.extend(
3252
+ build_markdown_insert_requests(
3253
+ markdown_text,
3254
+ insert_at,
3255
+ tab_id=tab_id,
3256
+ split_paragraph=last_element.get("startIndex", insert_at) < insert_at,
3257
+ drop_bullet="bullet" in last_element.get("paragraph", {}),
3258
+ )
3259
+ )
3260
+
3261
+ if not all_requests:
3262
+ return {
3263
+ "action": action,
3264
+ "success": True,
3265
+ "message": (
3266
+ f"No changes applied to tab '{tab_id}' in document {document_id}; "
3267
+ "markdown produced no requests."
3268
+ ),
3269
+ "tab_id": tab_id,
3270
+ "requests_applied": 0,
3271
+ "link": link,
3272
+ }
3273
+
3274
+ await asyncio.to_thread(
3275
+ service.documents()
3276
+ .batchUpdate(documentId=document_id, body={"requests": all_requests})
3277
+ .execute
3278
+ )
3279
+
3280
+ return {
3281
+ "action": action,
3282
+ "success": True,
3283
+ "message": (
3284
+ f"Populated tab '{tab_id}' in document {document_id} "
3285
+ f"from {len(markdown_text)} characters of markdown."
3286
+ ),
3287
+ "requests_applied": len(all_requests),
3288
+ "tab_id": tab_id,
3289
+ "link": link,
3290
+ }
3291
+
3292
+
3293
+ # Create comment management tools for documents
3294
+ _comment_tools = create_comment_tools(
3295
+ "document", "document_id", insert_anchored_comment=insert_anchored_comment
3296
+ )
3297
+
3298
+ # Extract and register the functions
3299
+ list_document_comments = _comment_tools["list_comments"]
3300
+ manage_document_comment = _comment_tools["manage_comment"]