@mutallip/google-workspace-mcp 0.0.0-stage → 2.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -2
  3. package/README.npm.md +34 -0
  4. package/auth/__init__.py +1 -0
  5. package/auth/auth_info_middleware.py +419 -0
  6. package/auth/client_secrets.py +76 -0
  7. package/auth/credential_store.py +598 -0
  8. package/auth/external_oauth_provider.py +369 -0
  9. package/auth/gateway_identity.py +164 -0
  10. package/auth/google_auth.py +1550 -0
  11. package/auth/google_oauth_provider.py +20 -0
  12. package/auth/mcp_session_middleware.py +95 -0
  13. package/auth/oauth21_session_store.py +1332 -0
  14. package/auth/oauth_callback_server.py +466 -0
  15. package/auth/oauth_config.py +693 -0
  16. package/auth/oauth_proxy_config.py +122 -0
  17. package/auth/oauth_responses.py +230 -0
  18. package/auth/oauth_types.py +92 -0
  19. package/auth/permissions.py +330 -0
  20. package/auth/port_resolver.py +153 -0
  21. package/auth/request_identity.py +89 -0
  22. package/auth/scopes.py +369 -0
  23. package/auth/service_decorator.py +1109 -0
  24. package/bin/google-workspace-mcp.cjs +123 -0
  25. package/core/__init__.py +1 -0
  26. package/core/api_enablement.py +108 -0
  27. package/core/attachment_storage.py +496 -0
  28. package/core/camel_case_middleware.py +98 -0
  29. package/core/cli.py +161 -0
  30. package/core/comments.py +609 -0
  31. package/core/config.py +57 -0
  32. package/core/context.py +43 -0
  33. package/core/file_limits.py +632 -0
  34. package/core/gcs_attachment_storage.py +253 -0
  35. package/core/http_utils.py +339 -0
  36. package/core/log_formatter.py +270 -0
  37. package/core/portable_schema_middleware.py +67 -0
  38. package/core/server.py +1192 -0
  39. package/core/startup_ui.py +239 -0
  40. package/core/storage.py +23 -0
  41. package/core/telemetry.py +194 -0
  42. package/core/tool_descriptions.py +19 -0
  43. package/core/tool_registry.py +311 -0
  44. package/core/tool_tier_loader.py +197 -0
  45. package/core/tool_tiers.yaml +179 -0
  46. package/core/toolset_header_middleware.py +67 -0
  47. package/core/utils.py +1537 -0
  48. package/core/valkey_storage.py +271 -0
  49. package/core/warning_filters.py +19 -0
  50. package/fastmcp_server.py +198 -0
  51. package/gappsscript/README.md +512 -0
  52. package/gappsscript/TESTING.md +254 -0
  53. package/gappsscript/__init__.py +0 -0
  54. package/gappsscript/apps_script_tools.py +1940 -0
  55. package/gcalendar/__init__.py +1 -0
  56. package/gcalendar/calendar_helpers.py +1323 -0
  57. package/gcalendar/calendar_tools.py +2252 -0
  58. package/gchat/__init__.py +7 -0
  59. package/gchat/chat_helpers.py +410 -0
  60. package/gchat/chat_tools.py +798 -0
  61. package/gcontacts/__init__.py +1 -0
  62. package/gcontacts/contacts_helpers.py +765 -0
  63. package/gcontacts/contacts_tools.py +1685 -0
  64. package/gdocs/__init__.py +0 -0
  65. package/gdocs/docs_anchors.py +163 -0
  66. package/gdocs/docs_comments.py +89 -0
  67. package/gdocs/docs_helpers.py +2201 -0
  68. package/gdocs/docs_links.py +87 -0
  69. package/gdocs/docs_markdown.py +828 -0
  70. package/gdocs/docs_markdown_writer.py +592 -0
  71. package/gdocs/docs_plain_text.py +463 -0
  72. package/gdocs/docs_structure.py +621 -0
  73. package/gdocs/docs_tables.py +425 -0
  74. package/gdocs/docs_tools.py +3300 -0
  75. package/gdocs/managers/__init__.py +18 -0
  76. package/gdocs/managers/batch_operation_manager.py +1694 -0
  77. package/gdocs/managers/header_footer_manager.py +526 -0
  78. package/gdocs/managers/table_operation_manager.py +488 -0
  79. package/gdocs/managers/validation_manager.py +1504 -0
  80. package/gdocs/operation_schemas.py +594 -0
  81. package/gdrive/__init__.py +0 -0
  82. package/gdrive/drive_helpers.py +1738 -0
  83. package/gdrive/drive_tools.py +3085 -0
  84. package/gforms/__init__.py +3 -0
  85. package/gforms/forms_tools.py +575 -0
  86. package/gmail/__init__.py +1 -0
  87. package/gmail/gmail_helpers.py +2107 -0
  88. package/gmail/gmail_tools.py +4895 -0
  89. package/gmail/gmail_web_mime.py +441 -0
  90. package/gsearch/__init__.py +0 -0
  91. package/gsearch/search_tools.py +253 -0
  92. package/gsheets/__init__.py +31 -0
  93. package/gsheets/sheets_helpers.py +2236 -0
  94. package/gsheets/sheets_tools.py +3280 -0
  95. package/gslides/__init__.py +0 -0
  96. package/gslides/slides_digest.py +390 -0
  97. package/gslides/slides_helpers.py +392 -0
  98. package/gslides/slides_markup.py +770 -0
  99. package/gslides/slides_tools.py +376 -0
  100. package/gtasks/__init__.py +5 -0
  101. package/gtasks/tasks_tools.py +936 -0
  102. package/main.py +1170 -0
  103. package/package.json +43 -4
  104. package/pyproject.toml +173 -0
  105. package/uv.lock +2504 -0
package/core/utils.py ADDED
@@ -0,0 +1,1537 @@
1
+ import base64
2
+ import binascii
3
+ import html
4
+ import io
5
+ import json
6
+ import logging
7
+ import os
8
+ import posixpath
9
+ import re
10
+ import stat
11
+ import sys
12
+ import tempfile
13
+ import urllib.parse
14
+ import zipfile
15
+ import ssl
16
+ import asyncio
17
+ import functools
18
+ import inspect
19
+
20
+ from pathlib import Path
21
+ from typing import (
22
+ Annotated,
23
+ Any,
24
+ BinaryIO,
25
+ List,
26
+ NamedTuple,
27
+ Optional,
28
+ TypeGuard,
29
+ Union,
30
+ )
31
+
32
+ try:
33
+ import fcntl
34
+ except ImportError:
35
+ fcntl = None
36
+
37
+ from pydantic import BeforeValidator
38
+ from defusedxml import DefusedXmlException, ElementTree as ET
39
+
40
+ import fastmcp
41
+ from fastmcp.exceptions import ToolError
42
+ from googleapiclient.errors import HttpError
43
+ from mcp.types import ImageContent
44
+ from .api_enablement import get_api_enablement_message
45
+ from auth.google_auth import GoogleAuthenticationError, get_default_credentials_dir
46
+ from auth.oauth_config import (
47
+ get_transport_mode,
48
+ is_external_oauth21_provider,
49
+ is_oauth21_enabled,
50
+ is_stateless_mode,
51
+ )
52
+ from .file_limits import get_max_office_xml_bytes
53
+
54
+ logger = logging.getLogger(__name__)
55
+
56
+ GOOGLE_API_WRITE_RETRIES = 3
57
+
58
+ _WORDPROCESSINGML_NAMESPACES = {
59
+ "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
60
+ "http://purl.oclc.org/ooxml/wordprocessingml/main",
61
+ }
62
+ _DRAWINGML_NAMESPACES = {
63
+ "http://schemas.openxmlformats.org/drawingml/2006/main",
64
+ "http://purl.oclc.org/ooxml/drawingml/main",
65
+ }
66
+ _MARKUP_COMPATIBILITY_NAMESPACE = (
67
+ "http://schemas.openxmlformats.org/markup-compatibility/2006"
68
+ )
69
+ _PACKAGE_RELATIONSHIPS_NAMESPACE = (
70
+ "http://schemas.openxmlformats.org/package/2006/relationships"
71
+ )
72
+ _OFFICE_RELATIONSHIP_BASES = {
73
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
74
+ "https://schemas.openxmlformats.org/officeDocument/2006/relationships",
75
+ "http://purl.oclc.org/ooxml/officeDocument/relationships",
76
+ }
77
+ _DOCX_MIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
78
+ _XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
79
+ _PPTX_MIME = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
80
+ _OFFICE_XML_MIME_TYPES = {_DOCX_MIME, _XLSX_MIME, _PPTX_MIME}
81
+ _SPREADSHEETML_NAMESPACES = {
82
+ "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
83
+ "http://purl.oclc.org/ooxml/spreadsheetml/main",
84
+ }
85
+ _WORD_TEXT_RELATIONSHIP_KINDS = {"header", "footer", "footnotes", "endnotes"}
86
+ _WORD_TEXT_RELATIONSHIP_TYPES = {
87
+ f"{base}/{kind}": kind
88
+ for base in _OFFICE_RELATIONSHIP_BASES
89
+ for kind in _WORD_TEXT_RELATIONSHIP_KINDS
90
+ }
91
+ _SUPPORTED_TEXT_CHOICE_NAMESPACES = {
92
+ *_WORDPROCESSINGML_NAMESPACES,
93
+ *_DRAWINGML_NAMESPACES,
94
+ "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas",
95
+ "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing",
96
+ "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup",
97
+ "http://schemas.microsoft.com/office/word/2010/wordprocessingShape",
98
+ "http://schemas.microsoft.com/office/word/2010/wordml",
99
+ "http://schemas.microsoft.com/office/word/2012/wordml",
100
+ "http://schemas.microsoft.com/office/drawing/2010/main",
101
+ }
102
+
103
+
104
+ class TransientNetworkError(Exception):
105
+ """Custom exception for transient network errors after retries."""
106
+
107
+ pass
108
+
109
+
110
+ class UserInputError(Exception):
111
+ """Raised for user-facing input/validation errors that shouldn't be retried."""
112
+
113
+ pass
114
+
115
+
116
+ class NotARegularFileError(OSError):
117
+ """Raised when a validated local path is not a regular file."""
118
+
119
+
120
+ _PATH_SEGMENT_PATTERN = re.compile(r"(?!\.+\Z)[A-Za-z0-9._-]+")
121
+
122
+
123
+ def is_path_segment(value: Any) -> TypeGuard[str]:
124
+ """Return True if value is safe unescaped as one segment of a Google API resource path."""
125
+ return isinstance(value, str) and _PATH_SEGMENT_PATTERN.fullmatch(value) is not None
126
+
127
+
128
+ def check_path_segment(value: Any, label: str) -> str:
129
+ """Return value, raising UserInputError unless is_path_segment accepts it."""
130
+ if not is_path_segment(value):
131
+ raise UserInputError(
132
+ f"Invalid {label} {value!r}: expected only letters, digits, '.', '_' or '-'."
133
+ )
134
+ return value
135
+
136
+
137
+ def _coerce_json_str_to_type(v: Any, expected_type: type) -> Any:
138
+ """Coerce a JSON-encoded string to a specific container type."""
139
+ if not isinstance(v, str):
140
+ return v
141
+
142
+ try:
143
+ parsed = json.loads(v)
144
+ except (json.JSONDecodeError, TypeError):
145
+ return v
146
+
147
+ return parsed if isinstance(parsed, expected_type) else v
148
+
149
+
150
+ def _coerce_json_str_to_list(v: Any) -> Any:
151
+ """Coerce a JSON-encoded string to a list.
152
+
153
+ Some MCP clients (e.g. Cowork) serialise array parameters as JSON strings
154
+ rather than native arrays. This ``BeforeValidator`` transparently converts
155
+ ``'["a","b"]'`` → ``["a", "b"]`` so Pydantic validation succeeds.
156
+ """
157
+ return _coerce_json_str_to_type(v, list)
158
+
159
+
160
+ StringList = Annotated[List[str], BeforeValidator(_coerce_json_str_to_list)]
161
+ """``List[str]`` that also accepts a JSON-encoded string of an array.
162
+
163
+ Use in tool signatures instead of ``List[str]`` to work around MCP clients
164
+ that send ``'["value"]'`` instead of ``["value"]``.
165
+ """
166
+
167
+
168
+ DictList = Annotated[List[dict[str, Any]], BeforeValidator(_coerce_json_str_to_list)]
169
+ """``List[dict]`` that also accepts a JSON-encoded string of an array.
170
+
171
+ Use in tool signatures instead of ``List[dict]`` to work around MCP clients
172
+ that send ``'[{"key":"val"}]'`` instead of ``[{"key":"val"}]``.
173
+ """
174
+
175
+
176
+ ObjectList = Annotated[List[object], BeforeValidator(_coerce_json_str_to_list)]
177
+ """``List[object]`` that also accepts a JSON-encoded string of an array."""
178
+
179
+
180
+ StringOrDictList = Annotated[
181
+ List[Union[str, dict[str, Any]]], BeforeValidator(_coerce_json_str_to_list)
182
+ ]
183
+ """List of strings and/or dicts that also accepts a JSON-encoded string of an array."""
184
+
185
+
186
+ def _coerce_json_str_to_dict(v: Any) -> Any:
187
+ """Coerce a JSON-encoded string to a dict.
188
+
189
+ Some MCP clients serialise dict parameters as JSON strings rather than
190
+ native objects. This ``BeforeValidator`` transparently converts
191
+ ``'{"key":"val"}'`` -> ``{"key": "val"}`` so Pydantic validation succeeds.
192
+ """
193
+ return _coerce_json_str_to_type(v, dict)
194
+
195
+
196
+ JsonDict = Annotated[dict[str, Any], BeforeValidator(_coerce_json_str_to_dict)]
197
+ """``dict`` that also accepts a JSON-encoded string of an object.
198
+
199
+ Use in tool signatures instead of ``Dict[str, Any]`` to work around MCP clients
200
+ that send ``'{"key":"val"}'`` instead of ``{"key": "val"}``.
201
+ """
202
+
203
+
204
+ # Directories from which local file reads are allowed.
205
+ # By default, only the managed attachment storage directory is trusted.
206
+ # Override via ALLOWED_FILE_DIRS env var (os.pathsep-separated paths).
207
+ _ALLOWED_FILE_DIRS_ENV = "ALLOWED_FILE_DIRS"
208
+
209
+ # Operators of hosted deployments, where the server cannot see the caller's
210
+ # disk, set this to stop tools reading server-side paths. Transport alone is not
211
+ # a reliable signal: streamable-http on localhost shares the caller's filesystem.
212
+ _DISABLE_LOCAL_FILES_ENV = "WORKSPACE_MCP_DISABLE_LOCAL_FILES"
213
+
214
+
215
+ def local_file_access_enabled() -> bool:
216
+ """Return whether tools may read files from the server's filesystem.
217
+
218
+ Disabled by ``WORKSPACE_MCP_DISABLE_LOCAL_FILES=true``, and implied by
219
+ stateless mode, which already denotes a diskless hosted deployment.
220
+ """
221
+ if is_stateless_mode():
222
+ return False
223
+ # Stray whitespace from YAML or .env files must not leave local files enabled.
224
+ return os.environ.get(_DISABLE_LOCAL_FILES_ENV, "").strip().lower() != "true"
225
+
226
+
227
+ def _hide_parameters(func, names: tuple[str, ...], hide: bool):
228
+ """Drop ``names`` from ``func``'s signature when ``hide`` is set.
229
+
230
+ Rewrites ``__signature__``, as ``require_google_service`` does, so FastMCP
231
+ omits the parameters from the schema and rejects them if a client with a
232
+ cached schema sends them anyway. Names are checked either way, so a stale
233
+ one fails at import. Each call reads the signature the previous decorator
234
+ left, so the decorators below stack.
235
+ """
236
+ sig = inspect.signature(func)
237
+ missing = [name for name in names if name not in sig.parameters]
238
+ if missing:
239
+ raise ValueError(f"{func.__name__} has no parameter(s) {missing} to hide.")
240
+ if hide:
241
+ func.__signature__ = sig.replace(
242
+ parameters=[p for p in sig.parameters.values() if p.name not in names]
243
+ )
244
+ return func
245
+
246
+
247
+ def hide_local_file_args(*names: str):
248
+ """Tool decorator: drop server-side path parameters when local files are off.
249
+
250
+ Apply directly under ``@server.tool`` so the rewritten signature is what
251
+ FastMCP sees (see ``_hide_parameters``). No-op when local file access is
252
+ enabled.
253
+ """
254
+
255
+ def decorator(func):
256
+ return _hide_parameters(func, names, hide=not local_file_access_enabled())
257
+
258
+ return decorator
259
+
260
+
261
+ def hide_remote_only_args(*names: str):
262
+ """Tool decorator: drop remote-only parameters when local files are on.
263
+
264
+ The inverse of ``hide_local_file_args``, so a tool carrying both kinds of
265
+ parameter advertises exactly one under any setting. Apply directly under
266
+ ``@server.tool``, stacked with ``hide_local_file_args`` in either order.
267
+ """
268
+
269
+ def decorator(func):
270
+ return _hide_parameters(func, names, hide=local_file_access_enabled())
271
+
272
+ return decorator
273
+
274
+
275
+ def _get_allowed_file_dirs() -> list[Path]:
276
+ """Return the list of directories from which local file access is permitted."""
277
+ from core.attachment_storage import STORAGE_DIR
278
+
279
+ allowed_dirs: list[Path] = [STORAGE_DIR]
280
+ env_val = os.environ.get(_ALLOWED_FILE_DIRS_ENV)
281
+ if env_val:
282
+ allowed_dirs.extend(
283
+ Path(p_stripped).expanduser().resolve()
284
+ for p in env_val.split(os.pathsep)
285
+ if (p_stripped := p.strip())
286
+ )
287
+
288
+ unique_dirs: list[Path] = []
289
+ seen: set[Path] = set()
290
+ for path in allowed_dirs:
291
+ if path in seen:
292
+ continue
293
+ seen.add(path)
294
+ unique_dirs.append(path)
295
+ return unique_dirs
296
+
297
+
298
+ def _file_identity(path: Path) -> Optional[tuple[int, int]]:
299
+ """Return ``(st_dev, st_ino)`` for ``path``, or None if it cannot be stat'ed."""
300
+ try:
301
+ stat_result = path.stat()
302
+ except OSError:
303
+ return None
304
+ return stat_result.st_dev, stat_result.st_ino
305
+
306
+
307
+ def validate_file_path(file_path: str) -> Path:
308
+ """
309
+ Validate that a file path is safe to read from the server filesystem.
310
+
311
+ Resolves the path canonically (following symlinks), then verifies it falls
312
+ within one of the allowed base directories. Rejects paths to sensitive
313
+ system locations regardless of allowlist.
314
+
315
+ Args:
316
+ file_path: The raw file path string to validate.
317
+
318
+ Returns:
319
+ Path: The resolved, validated Path object.
320
+
321
+ Raises:
322
+ UserInputError: If local file access is disabled on this server.
323
+ FileNotFoundError: If the path does not exist on the server.
324
+ ValueError: If the path is outside allowed directories or targets
325
+ a sensitive location.
326
+ """
327
+ if not local_file_access_enabled():
328
+ raise UserInputError(
329
+ "Local file access is disabled on this server: file paths resolve "
330
+ "on the server's filesystem, not the caller's. Provide the file by "
331
+ "URL or as inline content instead."
332
+ )
333
+
334
+ resolved = Path(file_path).resolve()
335
+
336
+ if not resolved.exists():
337
+ # Over HTTP the server may be on another machine, where a caller-side
338
+ # path can never exist, so say so rather than imply a typo.
339
+ hint = (
340
+ " Paths resolve on the MCP server's filesystem; if the server runs "
341
+ "on a different machine than the client, provide the file by URL "
342
+ "or as inline content instead."
343
+ if get_transport_mode() == "streamable-http"
344
+ else ""
345
+ )
346
+ raise FileNotFoundError(f"Path does not exist: {resolved}.{hint}")
347
+
348
+ return _check_resolved_path(resolved)
349
+
350
+
351
+ def _check_resolved_path(resolved: Path, on_disk: bool = False) -> Path:
352
+ """Return ``resolved`` if the local file policy allows it, else raise ValueError."""
353
+ # Block sensitive file patterns regardless of allowlist
354
+ resolved_str = str(resolved)
355
+ file_name = resolved.name.lower()
356
+
357
+ path_parts = [part.lower() for part in resolved.parts]
358
+
359
+ # Block .env files and variants (.env, .env.local, .env.production, etc.)
360
+ if any(part == ".env" or part.startswith(".env.") for part in path_parts):
361
+ raise ValueError(
362
+ f"Access to '{resolved_str}' is not allowed: "
363
+ ".env files may contain secrets and cannot be read, uploaded, or attached."
364
+ )
365
+
366
+ # Block well-known sensitive system paths (including macOS /private variants)
367
+ sensitive_prefixes = (
368
+ "/proc",
369
+ "/sys",
370
+ "/dev",
371
+ "/etc/shadow",
372
+ "/etc/passwd",
373
+ "/private/etc/shadow",
374
+ "/private/etc/passwd",
375
+ )
376
+ for prefix in sensitive_prefixes:
377
+ if resolved_str == prefix or resolved_str.startswith(prefix + "/"):
378
+ raise ValueError(
379
+ f"Access to '{resolved_str}' is not allowed: "
380
+ "path is in a restricted system location."
381
+ )
382
+
383
+ # Block sensitive directories that commonly contain credentials/keys.
384
+ if ".ssh" in path_parts or ".aws" in path_parts:
385
+ raise ValueError(
386
+ f"Access to '{resolved_str}' is not allowed: "
387
+ "path is in a directory that commonly contains secrets or credentials."
388
+ )
389
+
390
+ home = Path.home()
391
+ blocked_ids = {
392
+ _file_identity(blocked)
393
+ for blocked in (
394
+ home / ".kube",
395
+ home / ".gnupg",
396
+ home / ".docker" / "config.json",
397
+ home / ".config" / "gcloud",
398
+ Path(get_default_credentials_dir()),
399
+ )
400
+ } - {None}
401
+ if any(
402
+ _file_identity(ancestor) in blocked_ids
403
+ for ancestor in (resolved, *resolved.parents)
404
+ ):
405
+ raise ValueError(
406
+ f"Access to '{resolved_str}' is not allowed: "
407
+ "path is in a directory that commonly contains secrets or credentials."
408
+ )
409
+
410
+ # Block other credential/secret file patterns
411
+ sensitive_names = {
412
+ ".credentials",
413
+ ".credentials.json",
414
+ "credentials.json",
415
+ "client_secret.json",
416
+ "client_secrets.json",
417
+ "service_account.json",
418
+ "service-account.json",
419
+ ".npmrc",
420
+ ".pypirc",
421
+ ".netrc",
422
+ ".git-credentials",
423
+ }
424
+ if file_name in sensitive_names or path_parts[-2:] == [".docker", "config.json"]:
425
+ raise ValueError(
426
+ f"Access to '{resolved_str}' is not allowed: "
427
+ "this file commonly contains secrets or credentials."
428
+ )
429
+
430
+ allowed_dirs = _get_allowed_file_dirs()
431
+ if not allowed_dirs:
432
+ raise ValueError(
433
+ "No allowed file directories configured. "
434
+ "Set the ALLOWED_FILE_DIRS environment variable or configure "
435
+ "WORKSPACE_ATTACHMENT_DIR."
436
+ )
437
+
438
+ for allowed in allowed_dirs:
439
+ try:
440
+ resolved.relative_to(_on_disk_dir(allowed) if on_disk else allowed)
441
+ return resolved
442
+ except ValueError:
443
+ continue
444
+
445
+ raise ValueError(
446
+ f"Access to '{resolved_str}' is not allowed: "
447
+ f"path is outside permitted directories ({', '.join(str(d) for d in allowed_dirs)}). "
448
+ "Set ALLOWED_FILE_DIRS to adjust."
449
+ )
450
+
451
+
452
+ _VALIDATED_OPEN_FLAGS = getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
453
+ _DESCRIPTOR_PATHS = hasattr(fcntl, "F_GETPATH") or sys.platform.startswith("linux")
454
+
455
+
456
+ def _descriptor_path(fd: int) -> str:
457
+ """Return the real path of an open descriptor, raising OSError if unknown."""
458
+ if hasattr(fcntl, "F_GETPATH"):
459
+ return os.fsdecode(fcntl.fcntl(fd, fcntl.F_GETPATH, bytes(1024)).rstrip(b"\0"))
460
+ return os.readlink(f"/proc/self/fd/{fd}")
461
+
462
+
463
+ def _on_disk_dir(directory: Path) -> Path:
464
+ """Return ``directory`` spelled as the filesystem stores it."""
465
+ try:
466
+ fd = os.open(directory, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
467
+ except OSError:
468
+ return directory
469
+ try:
470
+ return Path(_descriptor_path(fd))
471
+ finally:
472
+ os.close(fd)
473
+
474
+
475
+ def _open_validated(path: str, flags: int) -> int:
476
+ """Opener that re-runs the local file policy on the file actually opened."""
477
+ try:
478
+ fd = os.open(path, flags | _VALIDATED_OPEN_FLAGS)
479
+ except PermissionError:
480
+ # Windows cannot open a directory, so it never reaches the fstat check.
481
+ if os.path.isdir(path):
482
+ raise NotARegularFileError(f"Path is not a file: {path}") from None
483
+ raise
484
+ try:
485
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
486
+ raise NotARegularFileError(f"Path is not a file: {path}")
487
+ if _DESCRIPTOR_PATHS:
488
+ _check_resolved_path(Path(_descriptor_path(fd)), on_disk=True)
489
+ except BaseException:
490
+ os.close(fd)
491
+ raise
492
+ return fd
493
+
494
+
495
+ def open_validated_file(file_path: str) -> BinaryIO:
496
+ """Open a validated path for binary reading; ``name`` is its resolved path."""
497
+ return open(str(validate_file_path(file_path)), "rb", opener=_open_validated)
498
+
499
+
500
+ def check_credentials_directory_permissions(credentials_dir: str = None) -> None:
501
+ """
502
+ Check if the service has appropriate permissions to create and write to the .credentials directory.
503
+
504
+ Args:
505
+ credentials_dir: Path to the credentials directory (default: uses get_default_credentials_dir())
506
+
507
+ Raises:
508
+ PermissionError: If the service lacks necessary permissions
509
+ OSError: If there are other file system issues
510
+ """
511
+ if credentials_dir is None:
512
+ from auth.google_auth import get_default_credentials_dir
513
+
514
+ credentials_dir = get_default_credentials_dir()
515
+
516
+ # Multiple server processes may initialize the same credentials directory at
517
+ # once. Keep the check idempotent: create the directory if needed, probe with
518
+ # a unique temporary file, and never remove the shared directory on failure.
519
+ try:
520
+ os.makedirs(credentials_dir, exist_ok=True)
521
+ with tempfile.NamedTemporaryFile(
522
+ dir=credentials_dir, prefix=".permission_test_"
523
+ ) as probe:
524
+ probe.write(b"test")
525
+ probe.flush()
526
+ except (PermissionError, OSError) as e:
527
+ raise PermissionError(
528
+ f"Cannot create or write to credentials directory "
529
+ f"'{os.path.abspath(credentials_dir)}': {e}"
530
+ )
531
+
532
+ # Debug level: the startup screen already reports this check and the path.
533
+ logger.debug(
534
+ f"Credentials directory permissions check passed: {os.path.abspath(credentials_dir)}"
535
+ )
536
+
537
+
538
+ class OfficeXmlExtractionError(Exception):
539
+ """Raised when an Office file cannot be read."""
540
+
541
+
542
+ class OfficeXmlTooLargeError(OfficeXmlExtractionError):
543
+ """Raised when an Office file expands beyond the configured limits.
544
+
545
+ A subclass, so callers that only know OfficeXmlExtractionError still stop
546
+ cleanly; callers that know it can say the file is too large rather than
547
+ damaged.
548
+ """
549
+
550
+
551
+ # An Office file is a ZIP archive. Nothing the archive says about itself is
552
+ # trusted further than it can be checked: the budget below bounds the bytes
553
+ # expanded out of it, whatever the compressed size was.
554
+ _ZIP_READ_CHUNK_BYTES = 64 * 1024
555
+
556
+ # OPC packaging (ECMA-376 Part 2) allows only these two. It matters here because
557
+ # ZipExtFile.read(n) passes a length bound to the decompressor for DEFLATE only:
558
+ # BZIP2 and LZMA members are decompressed a whole block at a time and sliced
559
+ # afterwards, so a counted read cannot bound them.
560
+ _OFFICE_ZIP_COMPRESSION = (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED)
561
+
562
+
563
+ def _office_extraction_too_large(
564
+ total_bytes: int, name: str, *, reason: str, activity: str
565
+ ) -> OfficeXmlTooLargeError:
566
+ """Build the common actionable error for either extraction boundary."""
567
+ return OfficeXmlTooLargeError(
568
+ f"{reason} the extraction limit of {total_bytes:,} bytes (exceeded while "
569
+ f"{activity} {name}; set by WORKSPACE_MCP_MAX_OFFICE_XML_BYTES). To read "
570
+ "it anyway, convert it to a native Google file in Drive (File > Save as "
571
+ "Google Docs, Sheets or Slides) and read the converted file: Google "
572
+ "exports native files as text itself, so nothing is expanded here."
573
+ )
574
+
575
+
576
+ class _ExpansionBudget:
577
+ """Bytes one Office file may still expand to, across all of its parts."""
578
+
579
+ def __init__(self, total_bytes: Optional[int]) -> None:
580
+ self.total_bytes = total_bytes
581
+ self.used = 0
582
+
583
+ def remaining(self) -> Optional[int]:
584
+ """Bytes that may still be read; None when expansion is uncapped."""
585
+ if self.total_bytes is None:
586
+ return None
587
+ return self.total_bytes - self.used
588
+
589
+ def too_large(self, name: str) -> OfficeXmlTooLargeError:
590
+ assert self.total_bytes is not None
591
+ return _office_extraction_too_large(
592
+ self.total_bytes,
593
+ name,
594
+ reason="the file expands beyond",
595
+ activity="reading",
596
+ )
597
+
598
+
599
+ class _ExtractedTextBudget:
600
+ """UTF-8 bytes of text one Office file may produce.
601
+
602
+ This is independent of the XML expansion budget. In particular, XLSX can
603
+ reference one shared string from many cells, making the extracted text much
604
+ larger than the XML that describes it.
605
+ """
606
+
607
+ def __init__(self, total_bytes: Optional[int]) -> None:
608
+ self.total_bytes = total_bytes
609
+ self.used = 0
610
+
611
+ def join(
612
+ self,
613
+ parts: list[str],
614
+ separator: str,
615
+ member: str,
616
+ *,
617
+ prefix: str = "",
618
+ ) -> str:
619
+ """Join ``parts`` only after proving the result fits the text budget."""
620
+ if self.total_bytes is not None:
621
+ size = self.used + len(prefix.encode("utf-8"))
622
+ separator_size = len(separator.encode("utf-8"))
623
+ for index, part in enumerate(parts):
624
+ if index:
625
+ size += separator_size
626
+ size += len(part.encode("utf-8"))
627
+ if size > self.total_bytes:
628
+ raise _office_extraction_too_large(
629
+ self.total_bytes,
630
+ member,
631
+ reason="the extracted text exceeds",
632
+ activity="extracting text from",
633
+ )
634
+ self.used = size
635
+ return separator.join(parts)
636
+
637
+
638
+ def _read_zip_member(zf: zipfile.ZipFile, name: str, budget: _ExpansionBudget) -> bytes:
639
+ """Read one ZIP member without expanding past the budget.
640
+
641
+ Raises KeyError when the member is absent, like ZipFile.read. The declared
642
+ size is checked first because it is free, but it is only a claim: the read
643
+ itself is counted, and stops at the limit whatever the header said.
644
+ """
645
+ info = zf.getinfo(name)
646
+ limit = budget.remaining()
647
+ if limit is None:
648
+ return zf.read(info)
649
+ if info.compress_type not in _OFFICE_ZIP_COMPRESSION:
650
+ raise OfficeXmlExtractionError(
651
+ f"{name} uses a compression method Office files do not allow"
652
+ )
653
+ if info.file_size > limit:
654
+ raise budget.too_large(name)
655
+
656
+ chunks: list[bytes] = []
657
+ read = 0
658
+ with zf.open(info) as member:
659
+ while True:
660
+ # One byte past the limit is enough to know the limit was exceeded.
661
+ chunk = member.read(min(_ZIP_READ_CHUNK_BYTES, limit - read + 1))
662
+ if not chunk:
663
+ break
664
+ read += len(chunk)
665
+ if read > limit:
666
+ raise budget.too_large(name)
667
+ chunks.append(chunk)
668
+ budget.used += read
669
+ return b"".join(chunks)
670
+
671
+
672
+ def _xml_name(tag: str) -> tuple[Optional[str], str]:
673
+ """Return an ElementTree tag's namespace URI and local name."""
674
+ if tag.startswith("{") and "}" in tag:
675
+ namespace, local_name = tag[1:].split("}", 1)
676
+ return namespace, local_name
677
+ return None, tag
678
+
679
+
680
+ def _parse_xml_with_choice_namespaces(
681
+ xml_content: bytes,
682
+ ) -> tuple[Any, dict[Any, dict[str, str]]]:
683
+ """Parse XML and retain the in-scope prefix map for each mc:Choice.
684
+
685
+ The maps are read-only and may be shared: every mc:Choice that starts while
686
+ the scope is unchanged gets the SAME dict. Copying the map per element cost
687
+ (declared prefixes x Choice elements), which a document controls on both
688
+ sides.
689
+ """
690
+ namespaces: dict[str, str] = {}
691
+ namespace_stack: list[tuple[str, Any]] = []
692
+ choice_namespaces: dict[Any, dict[str, str]] = {}
693
+ # A copy of `namespaces` as of the last scope change, made on demand.
694
+ snapshot: Optional[dict[str, str]] = None
695
+ missing = object()
696
+ xml_root = None
697
+
698
+ for event, value in ET.iterparse(
699
+ io.BytesIO(xml_content), events=("start-ns", "start", "end-ns")
700
+ ):
701
+ if event == "start-ns":
702
+ prefix, uri = value
703
+ prefix = prefix or ""
704
+ namespace_stack.append((prefix, namespaces.get(prefix, missing)))
705
+ namespaces[prefix] = uri
706
+ snapshot = None
707
+ elif event == "end-ns":
708
+ prefix, previous = namespace_stack.pop()
709
+ if previous is missing:
710
+ namespaces.pop(prefix, None)
711
+ else:
712
+ namespaces[prefix] = previous
713
+ snapshot = None
714
+ else:
715
+ element = value
716
+ if xml_root is None:
717
+ xml_root = element
718
+ if element.tag == f"{{{_MARKUP_COMPATIBILITY_NAMESPACE}}}Choice":
719
+ if snapshot is None:
720
+ snapshot = namespaces.copy()
721
+ choice_namespaces[element] = snapshot
722
+
723
+ if xml_root is None:
724
+ raise ET.ParseError("XML member has no root element")
725
+ return xml_root, choice_namespaces
726
+
727
+
728
+ def _resolve_internal_part_target(source_part: str, target: str) -> Optional[str]:
729
+ """Resolve an OPC internal relationship target to a ZIP member name."""
730
+ parsed = urllib.parse.urlsplit(target)
731
+ if parsed.scheme or parsed.netloc or not parsed.path:
732
+ return None
733
+
734
+ target_path = urllib.parse.unquote(parsed.path)
735
+ if "\\" in target_path:
736
+ return None
737
+ if target_path.startswith("/"):
738
+ resolved = posixpath.normpath(target_path.lstrip("/"))
739
+ else:
740
+ resolved = posixpath.normpath(
741
+ posixpath.join(posixpath.dirname(source_part), target_path)
742
+ )
743
+ if resolved in {"", ".", ".."} or resolved.startswith("../"):
744
+ return None
745
+ return resolved
746
+
747
+
748
+ def _relationship_id(element: Any) -> Optional[str]:
749
+ """Return an r:id attribute from either Transitional or Strict OOXML."""
750
+ for attribute, value in element.attrib.items():
751
+ namespace, local_name = _xml_name(attribute)
752
+ if namespace in _OFFICE_RELATIONSHIP_BASES and local_name == "id":
753
+ return value
754
+ return None
755
+
756
+
757
+ def _word_related_text_targets(
758
+ zf: zipfile.ZipFile, document_root: Any, budget: _ExpansionBudget
759
+ ) -> list[str]:
760
+ """Return active Word text parts using OPC relationships, not filenames."""
761
+ try:
762
+ relationships_xml = _read_zip_member(zf, "word/_rels/document.xml.rels", budget)
763
+ except KeyError:
764
+ return []
765
+ relationships_root = ET.fromstring(relationships_xml)
766
+
767
+ relationships: list[tuple[str, str, str]] = []
768
+ relationships_by_id: dict[str, tuple[str, str]] = {}
769
+ for relationship in relationships_root.iter():
770
+ if _xml_name(relationship.tag) != (
771
+ _PACKAGE_RELATIONSHIPS_NAMESPACE,
772
+ "Relationship",
773
+ ):
774
+ continue
775
+ if relationship.get("TargetMode", "Internal").lower() != "internal":
776
+ continue
777
+ relationship_id = relationship.get("Id")
778
+ kind = _WORD_TEXT_RELATIONSHIP_TYPES.get(relationship.get("Type", ""))
779
+ target = relationship.get("Target")
780
+ if not relationship_id or not kind or not target:
781
+ continue
782
+ resolved = _resolve_internal_part_target("word/document.xml", target)
783
+ if resolved is None:
784
+ logger.warning(
785
+ "Ignoring invalid internal Word relationship target %r", target
786
+ )
787
+ continue
788
+ relationships.append((relationship_id, kind, resolved))
789
+ relationships_by_id[relationship_id] = (kind, resolved)
790
+
791
+ active_header_footer_ids: dict[str, list[str]] = {"header": [], "footer": []}
792
+ for element in document_root.iter():
793
+ namespace, local_name = _xml_name(element.tag)
794
+ if namespace not in _WORDPROCESSINGML_NAMESPACES or local_name not in {
795
+ "headerReference",
796
+ "footerReference",
797
+ }:
798
+ continue
799
+ kind = "header" if local_name == "headerReference" else "footer"
800
+ relationship_id = _relationship_id(element)
801
+ if relationship_id and relationship_id not in active_header_footer_ids[kind]:
802
+ active_header_footer_ids[kind].append(relationship_id)
803
+
804
+ targets: list[str] = []
805
+ seen: set[str] = set()
806
+
807
+ def add_target(target: str) -> None:
808
+ if target not in seen:
809
+ seen.add(target)
810
+ targets.append(target)
811
+
812
+ for kind in ("header", "footer"):
813
+ for relationship_id in active_header_footer_ids[kind]:
814
+ relationship = relationships_by_id.get(relationship_id)
815
+ if relationship is not None and relationship[0] == kind:
816
+ add_target(relationship[1])
817
+
818
+ for wanted_kind in ("footnotes", "endnotes"):
819
+ for _, kind, target in relationships:
820
+ if kind == wanted_kind:
821
+ add_target(target)
822
+
823
+ return targets
824
+
825
+
826
+ def _branch_has_extractable_text(branch: Any) -> bool:
827
+ """Whether an AlternateContent branch has text or an explicit separator."""
828
+ parents = {child: parent for parent in branch.iter() for child in parent}
829
+ for element in branch.iter():
830
+ namespace, local_name = _xml_name(element.tag)
831
+ if local_name == "t" and element.text:
832
+ return True
833
+ if namespace in _WORDPROCESSINGML_NAMESPACES and local_name in {
834
+ "tab",
835
+ "br",
836
+ "cr",
837
+ }:
838
+ parent = parents.get(element)
839
+ if parent is not None and _xml_name(parent.tag)[1] == "r":
840
+ return True
841
+ if namespace in _DRAWINGML_NAMESPACES and local_name == "br":
842
+ parent = parents.get(element)
843
+ if parent is not None and _xml_name(parent.tag)[1] == "p":
844
+ return True
845
+ return False
846
+
847
+
848
+ def _alternate_content_skip_set(
849
+ xml_root: Any, choice_namespaces: dict[Any, dict[str, str]]
850
+ ) -> set[int]:
851
+ """Return node IDs belonging to unselected mc:AlternateContent branches."""
852
+ alternate_tag = f"{{{_MARKUP_COMPATIBILITY_NAMESPACE}}}AlternateContent"
853
+ choice_tag = f"{{{_MARKUP_COMPATIBILITY_NAMESPACE}}}Choice"
854
+ fallback_tag = f"{{{_MARKUP_COMPATIBILITY_NAMESPACE}}}Fallback"
855
+ skip: set[int] = set()
856
+
857
+ for alternate in xml_root.iter(alternate_tag):
858
+ children = list(alternate)
859
+ choices = [child for child in children if child.tag == choice_tag]
860
+ fallback = next(
861
+ (child for child in children if child.tag == fallback_tag), None
862
+ )
863
+ selected = None
864
+ last_resort = None
865
+ for choice in choices:
866
+ prefixes = choice.get("Requires", "").split()
867
+ namespaces = choice_namespaces.get(choice, {})
868
+ if prefixes and all(
869
+ namespaces.get(prefix) in _SUPPORTED_TEXT_CHOICE_NAMESPACES
870
+ for prefix in prefixes
871
+ ):
872
+ if _branch_has_extractable_text(choice):
873
+ selected = choice
874
+ break
875
+ elif last_resort is None and _branch_has_extractable_text(choice):
876
+ last_resort = choice
877
+ if selected is None and fallback is not None:
878
+ selected = fallback
879
+ if selected is None and last_resort is not None:
880
+ selected = last_resort
881
+
882
+ for branch in choices + ([fallback] if fallback is not None else []):
883
+ if branch is selected:
884
+ continue
885
+ skip.update(id(node) for node in branch.iter())
886
+
887
+ return skip
888
+
889
+
890
+ def _read_part(zf: zipfile.ZipFile, name: str, budget: _ExpansionBudget) -> bytes:
891
+ """Read a ZIP member the file cannot be valid without."""
892
+ try:
893
+ return _read_zip_member(zf, name, budget)
894
+ except KeyError as e:
895
+ raise OfficeXmlExtractionError(f"missing required part: {name}") from e
896
+
897
+
898
+ def _sheet_children(node: Any, local_name: str) -> List[Any]:
899
+ """Direct children of ``node`` named ``local_name`` in any SpreadsheetML namespace."""
900
+ return [
901
+ child
902
+ for child in node
903
+ if _xml_name(child.tag)[0] in _SPREADSHEETML_NAMESPACES
904
+ and _xml_name(child.tag)[1] == local_name
905
+ ]
906
+
907
+
908
+ def _rich_text(node: Any) -> str:
909
+ """Text of a rich-text container: a shared-string ``<si>`` or an inline ``<is>``.
910
+
911
+ Both hold a single ``<t>`` or runs ``<r><t>...</t></r>``. Phonetic guides
912
+ ``<rPh>`` also carry ``<t>`` but are annotations, so they are skipped.
913
+ """
914
+ parts: List[str] = []
915
+ for child in node:
916
+ namespace, local_name = _xml_name(child.tag)
917
+ if namespace not in _SPREADSHEETML_NAMESPACES:
918
+ continue
919
+ if local_name == "t":
920
+ parts.append(child.text or "")
921
+ elif local_name == "r":
922
+ parts.extend(t.text or "" for t in _sheet_children(child, "t"))
923
+ return "".join(parts)
924
+
925
+
926
+ def _read_shared_strings(
927
+ zf: zipfile.ZipFile, budget: _ExpansionBudget
928
+ ) -> Optional[List[str]]:
929
+ """Return workbook shared strings, or None when the part is absent."""
930
+ try:
931
+ shared_strings_xml = _read_zip_member(zf, "xl/sharedStrings.xml", budget)
932
+ except KeyError:
933
+ return None
934
+ root = ET.fromstring(shared_strings_xml)
935
+ return [_rich_text(si) for si in _sheet_children(root, "si")]
936
+
937
+
938
+ def _shared_string(shared_strings: Optional[List[str]], value: str, member: str) -> str:
939
+ """Resolve a t="s" cell value, rejecting references the workbook cannot satisfy."""
940
+ if shared_strings is None:
941
+ raise OfficeXmlExtractionError(
942
+ f"{member} references shared strings but xl/sharedStrings.xml is missing"
943
+ )
944
+ try:
945
+ index = int(value)
946
+ except ValueError as e:
947
+ raise OfficeXmlExtractionError(
948
+ f"non-integer shared string index {value!r} in {member}"
949
+ ) from e
950
+ if not 0 <= index < len(shared_strings):
951
+ raise OfficeXmlExtractionError(
952
+ f"shared string index {index} out of range in {member}"
953
+ )
954
+ return shared_strings[index]
955
+
956
+
957
+ def _spreadsheet_texts(
958
+ xml_root: Any, shared_strings: Optional[List[str]], member: str
959
+ ) -> List[str]:
960
+ """Return cell values from one worksheet in document order."""
961
+ namespace = _xml_name(xml_root.tag)[0]
962
+ if namespace not in _SPREADSHEETML_NAMESPACES:
963
+ return []
964
+ ns = f"{{{namespace}}}"
965
+ texts: List[str] = []
966
+ for cell in xml_root.iter(f"{ns}c"):
967
+ cell_type = cell.get("t")
968
+ inline = cell.find(f"{ns}is")
969
+ if cell_type == "inlineStr" and inline is not None:
970
+ if text := _rich_text(inline):
971
+ texts.append(text)
972
+ continue
973
+ value = cell.find(f"{ns}v")
974
+ if value is None or value.text is None:
975
+ continue
976
+ if cell_type == "s":
977
+ texts.append(_shared_string(shared_strings, value.text, member))
978
+ else:
979
+ texts.append(value.text)
980
+ return texts
981
+
982
+
983
+ def _paragraph_texts(
984
+ xml_root: Any, choice_namespaces: dict[Any, dict[str, str]]
985
+ ) -> List[str]:
986
+ """Return one line per Word/PowerPoint paragraph.
987
+
988
+ Runs concatenate without a separator because Word splits tokens across runs.
989
+ A nested text-box paragraph flushes its outer paragraph so XML order holds
990
+ without emitting the nested text twice.
991
+ """
992
+ parents = {child: parent for parent in xml_root.iter() for child in parent}
993
+
994
+ def line_owner(node: Any) -> Any:
995
+ """Closest paragraph ancestor, else nearest non-run container."""
996
+ cur = parents.get(node)
997
+ nearest_non_run = None
998
+ while cur is not None:
999
+ local_name = _xml_name(cur.tag)[1]
1000
+ if local_name == "p":
1001
+ return cur
1002
+ if nearest_non_run is None and local_name != "r":
1003
+ nearest_non_run = cur
1004
+ cur = parents.get(cur)
1005
+ return nearest_non_run
1006
+
1007
+ def parent_name(node: Any) -> Optional[str]:
1008
+ parent = parents.get(node)
1009
+ return None if parent is None else _xml_name(parent.tag)[1]
1010
+
1011
+ skip = _alternate_content_skip_set(xml_root, choice_namespaces)
1012
+ lines: List[str] = []
1013
+ current_owner = None
1014
+ current_parts: List[str] = []
1015
+
1016
+ def flush_line() -> None:
1017
+ # Strip space padding only; explicit tabs and breaks are content.
1018
+ line = "".join(current_parts).strip(" ")
1019
+ if line:
1020
+ lines.append(line)
1021
+
1022
+ for node in xml_root.iter():
1023
+ if id(node) in skip:
1024
+ continue
1025
+ namespace, local_name = _xml_name(node.tag)
1026
+ piece = None
1027
+ if local_name == "t" and node.text:
1028
+ piece = node.text
1029
+ elif namespace in _WORDPROCESSINGML_NAMESPACES and local_name in {
1030
+ "tab",
1031
+ "br",
1032
+ "cr",
1033
+ }:
1034
+ # w:tab under w:pPr/w:tabs is a tab stop, not content.
1035
+ if parent_name(node) == "r":
1036
+ piece = "\t" if local_name == "tab" else "\n"
1037
+ elif namespace in _DRAWINGML_NAMESPACES and local_name == "br":
1038
+ if parent_name(node) == "p":
1039
+ piece = "\n"
1040
+ if piece is None:
1041
+ continue
1042
+ owner = line_owner(node) or node
1043
+ if current_owner is not None and owner is not current_owner:
1044
+ flush_line()
1045
+ current_parts = []
1046
+ current_owner = owner
1047
+ current_parts.append(piece)
1048
+
1049
+ flush_line()
1050
+ return lines
1051
+
1052
+
1053
+ def extract_office_xml_text(file_bytes: bytes, mime_type: str) -> Optional[str]:
1054
+ """
1055
+ Very light-weight XML scraper for Word, Excel, PowerPoint files.
1056
+ Returns plain text, None when no text is present, and raises
1057
+ OfficeXmlExtractionError when the Office file cannot be read.
1058
+ Uses zipfile + defusedxml.ElementTree.
1059
+ """
1060
+ if mime_type not in _OFFICE_XML_MIME_TYPES:
1061
+ return None
1062
+
1063
+ # Outside the try: an invalid setting is a configuration error, and must not
1064
+ # be reported as a damaged file.
1065
+ max_bytes = get_max_office_xml_bytes()
1066
+ budget = _ExpansionBudget(max_bytes)
1067
+ text_budget = _ExtractedTextBudget(max_bytes)
1068
+
1069
+ try:
1070
+ with zipfile.ZipFile(io.BytesIO(file_bytes)) as zf:
1071
+ parsed_members: dict[str, tuple[Any, dict[Any, dict[str, str]]]] = {}
1072
+ shared_strings: Optional[List[str]] = None
1073
+ if mime_type == _DOCX_MIME:
1074
+ document = _parse_xml_with_choice_namespaces(
1075
+ _read_part(zf, "word/document.xml", budget)
1076
+ )
1077
+ parsed_members["word/document.xml"] = document
1078
+ targets = ["word/document.xml"]
1079
+ targets.extend(_word_related_text_targets(zf, document[0], budget))
1080
+ elif mime_type == _PPTX_MIME:
1081
+ ET.fromstring(_read_part(zf, "ppt/presentation.xml", budget))
1082
+ targets = [n for n in zf.namelist() if n.startswith("ppt/slides/slide")]
1083
+ else:
1084
+ ET.fromstring(_read_part(zf, "xl/workbook.xml", budget))
1085
+ targets = [
1086
+ n
1087
+ for n in zf.namelist()
1088
+ if n.startswith("xl/worksheets/sheet") and "drawing" not in n
1089
+ ]
1090
+ shared_strings = _read_shared_strings(zf, budget)
1091
+
1092
+ pieces: List[str] = []
1093
+ for member in targets:
1094
+ if mime_type == _XLSX_MIME:
1095
+ xml_root = ET.fromstring(_read_part(zf, member, budget))
1096
+ member_texts = _spreadsheet_texts(xml_root, shared_strings, member)
1097
+ sep = " "
1098
+ else:
1099
+ xml_root, choice_namespaces = parsed_members.get(
1100
+ member
1101
+ ) or _parse_xml_with_choice_namespaces(
1102
+ _read_part(zf, member, budget)
1103
+ )
1104
+ member_texts = _paragraph_texts(xml_root, choice_namespaces)
1105
+ # Paragraph boundaries carry meaning; keep them as newlines.
1106
+ sep = "\n"
1107
+ if member_texts:
1108
+ pieces.append(
1109
+ text_budget.join(
1110
+ member_texts,
1111
+ sep,
1112
+ member,
1113
+ prefix="\n\n" if pieces else "",
1114
+ )
1115
+ )
1116
+
1117
+ text = "\n\n".join(pieces).strip(" ")
1118
+ return text or None
1119
+
1120
+ except zipfile.BadZipFile as e:
1121
+ logger.warning(f"File is not a valid ZIP archive (mime_type: {mime_type}).")
1122
+ raise OfficeXmlExtractionError("not a valid Office file") from e
1123
+ except (ET.ParseError, DefusedXmlException) as e:
1124
+ raise OfficeXmlExtractionError("could not parse Office XML") from e
1125
+ except OfficeXmlExtractionError:
1126
+ raise
1127
+ except Exception as e:
1128
+ logger.error(
1129
+ f"Failed to extract office XML text for {mime_type}: {e}", exc_info=True
1130
+ )
1131
+ raise OfficeXmlExtractionError("could not read Office file") from e
1132
+
1133
+
1134
+ IMAGE_MIME_TYPES = {
1135
+ "image/png",
1136
+ "image/jpeg",
1137
+ "image/gif",
1138
+ "image/webp",
1139
+ "image/bmp",
1140
+ "image/tiff",
1141
+ "image/svg+xml",
1142
+ }
1143
+
1144
+ # Model APIs reject BMP, TIFF and SVG as image blocks.
1145
+ INLINE_IMAGE_MIME_TYPES = {"image/png", "image/jpeg", "image/gif", "image/webp"}
1146
+
1147
+ SVG_MIME_TYPE = "image/svg+xml"
1148
+
1149
+ # Line breaks, literal or as XML character references, may precede or split a
1150
+ # payload, but it ends with a base64 character so the match never runs into
1151
+ # the text that follows.
1152
+ _SVG_DATA_URI_RE = re.compile(
1153
+ r"data:(?P<mime>[\w.+-]+/[\w.+-]+)?(?:;[\w.+-]+=[\w.+-]+)*;base64,"
1154
+ r"(?P<payload>(?:\s|&#x?[0-9A-Fa-f]+;)*"
1155
+ r"[A-Za-z0-9+/]+(?:(?:\s|&#x?[0-9A-Fa-f]+;)*[A-Za-z0-9+/]+)*=*)",
1156
+ re.IGNORECASE,
1157
+ )
1158
+
1159
+ _SVG_MIN_ELIDED_PAYLOAD = 64
1160
+
1161
+
1162
+ def extract_pdf_text(file_bytes: bytes) -> Optional[str]:
1163
+ """
1164
+ Extract text from a PDF using pypdf.
1165
+ Returns plain text with pages separated by double newlines, or None on failure.
1166
+ """
1167
+ try:
1168
+ from pypdf import PdfReader
1169
+
1170
+ reader = PdfReader(io.BytesIO(file_bytes))
1171
+ pages = []
1172
+ for page in reader.pages:
1173
+ text = page.extract_text()
1174
+ if text:
1175
+ pages.append(text)
1176
+ if not pages:
1177
+ return None
1178
+ return "\n\n".join(pages).strip() or None
1179
+ except Exception as e:
1180
+ logger.warning(f"Failed to extract PDF text: {e}")
1181
+ return None
1182
+
1183
+
1184
+ def encode_image_content(file_bytes: bytes, mime_type: str) -> str:
1185
+ """
1186
+ Base64-encode image bytes with a mime type metadata prefix.
1187
+
1188
+ Args:
1189
+ file_bytes: The image file content as bytes.
1190
+ mime_type: The MIME type of the image (must start with "image/").
1191
+
1192
+ Returns:
1193
+ str: Base64-encoded image with mime type prefix.
1194
+
1195
+ Raises:
1196
+ ValueError: If mime_type is not an image MIME type.
1197
+ """
1198
+ if not mime_type.startswith("image/"):
1199
+ raise ValueError(
1200
+ f"Expected image/* MIME type, got '{mime_type}'. "
1201
+ "Only image content can be base64-encoded for multimodal clients."
1202
+ )
1203
+ encoded = base64.b64encode(file_bytes).decode("ascii")
1204
+ return f"[base64_image:{mime_type}]{encoded}"
1205
+
1206
+
1207
+ def image_content_from_bytes(file_bytes: bytes, mime_type: str) -> ImageContent:
1208
+ """
1209
+ Wrap image bytes as an MCP ImageContent block.
1210
+
1211
+ Args:
1212
+ file_bytes: The image file content as bytes.
1213
+ mime_type: The MIME type of the image (must start with "image/").
1214
+
1215
+ Returns:
1216
+ ImageContent: The image, base64-encoded, with its MIME type.
1217
+
1218
+ Raises:
1219
+ ValueError: If mime_type is not an image MIME type.
1220
+ """
1221
+ if not mime_type.startswith("image/"):
1222
+ raise ValueError(
1223
+ f"Expected image/* MIME type, got '{mime_type}'. "
1224
+ "Only image content can be returned as an image block."
1225
+ )
1226
+ return ImageContent(
1227
+ type="image",
1228
+ data=base64.b64encode(file_bytes).decode("ascii"),
1229
+ mimeType=mime_type,
1230
+ )
1231
+
1232
+
1233
+ def sniff_inline_image_mime_type(data: bytes) -> Optional[str]:
1234
+ """
1235
+ Identify image bytes by their magic number, for the types in
1236
+ INLINE_IMAGE_MIME_TYPES only.
1237
+
1238
+ Returns:
1239
+ Optional[str]: The MIME type, or None if the bytes are not PNG, JPEG,
1240
+ GIF or WebP.
1241
+ """
1242
+ if data.startswith(b"\x89PNG\r\n\x1a\n"):
1243
+ return "image/png"
1244
+ if data.startswith(b"\xff\xd8\xff"):
1245
+ return "image/jpeg"
1246
+ if data.startswith((b"GIF87a", b"GIF89a")):
1247
+ return "image/gif"
1248
+ if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
1249
+ return "image/webp"
1250
+ return None
1251
+
1252
+
1253
+ class SvgContent(NamedTuple):
1254
+ """An SVG read for a model: its markup, and the raster images it embeds."""
1255
+
1256
+ markup: str
1257
+ images: List[ImageContent]
1258
+
1259
+
1260
+ def svg_content(file_bytes: bytes) -> Optional[SvgContent]:
1261
+ """
1262
+ Read an SVG as its markup, with embedded raster images pulled out as
1263
+ image content. Each base64 data URI payload is replaced by a short note:
1264
+
1265
+ - A PNG, JPEG, GIF or WebP payload (identified by its bytes, not the type
1266
+ the URI declares) is decoded and attached as image content. Its note is
1267
+ numbered to match its position in ``images``.
1268
+ - Any other payload (fonts, BMP, TIFF, nested SVG, or base64 that doesn't
1269
+ decode) is omitted, and its note gives its size.
1270
+
1271
+ Payloads shorter than _SVG_MIN_ELIDED_PAYLOAD characters are left in
1272
+ place.
1273
+
1274
+ Args:
1275
+ file_bytes: The SVG file content as bytes.
1276
+
1277
+ Returns:
1278
+ Optional[SvgContent]: The markup and the attached images in document
1279
+ order, or None if the bytes are not UTF-8 text (for example a
1280
+ gzip-compressed .svgz file).
1281
+ """
1282
+ try:
1283
+ markup = file_bytes.decode("utf-8")
1284
+ except UnicodeDecodeError:
1285
+ return None
1286
+
1287
+ images: List[ImageContent] = []
1288
+
1289
+ def _elide(match: re.Match) -> str:
1290
+ payload = re.sub(r"\s", "", html.unescape(match.group("payload")))
1291
+ if len(payload) < _SVG_MIN_ELIDED_PAYLOAD:
1292
+ return match.group(0)
1293
+ declared = match.group("mime") or ""
1294
+ try:
1295
+ data = base64.b64decode(payload, validate=True)
1296
+ except (binascii.Error, ValueError):
1297
+ size = len(payload) * 3 // 4 - payload.count("=")
1298
+ return f"data:{declared};base64,[{size} bytes of invalid base64 omitted]"
1299
+ mime_type = sniff_inline_image_mime_type(data)
1300
+ if mime_type is None:
1301
+ return f"data:{declared};base64,[{len(data)} bytes omitted]"
1302
+ images.append(image_content_from_bytes(data, mime_type))
1303
+ return (
1304
+ f"data:{declared};base64,[embedded image {len(images)}, "
1305
+ f"{len(data)} bytes, attached as image content]"
1306
+ )
1307
+
1308
+ return SvgContent(_SVG_DATA_URI_RE.sub(_elide, markup), images)
1309
+
1310
+
1311
+ _URL_QUERY_RE = re.compile(r"\?.*?(?=\s+returned(?:\s|$)|[>\"']|$)")
1312
+
1313
+
1314
+ def _scrub_url_queries(text: str) -> str:
1315
+ """Strip query strings from any URL embedded in ``text`` before logging.
1316
+
1317
+ ``HttpError.__str__`` includes the full request URI, whose query string
1318
+ carries user content (e.g. ``.../messages?q=<the user's search terms>``)
1319
+ and can carry signed-URL secrets. The scheme/host/path identify the
1320
+ failing endpoint, which is all the log needs.
1321
+ """
1322
+ return _URL_QUERY_RE.sub("?<query-redacted>", text)
1323
+
1324
+
1325
+ def _format_http_error_for_log(error: HttpError) -> str:
1326
+ """Return operational HTTP failure context without response-body text."""
1327
+ status = getattr(error.resp, "status", "unknown")
1328
+ uri = getattr(error, "uri", None)
1329
+ request = _scrub_url_queries(uri) if uri else "<unknown>"
1330
+ return f"status={status}, request={request}"
1331
+
1332
+
1333
+ _RATE_LIMIT_ERROR_REASONS = frozenset(
1334
+ {
1335
+ "rateLimitExceeded",
1336
+ "userRateLimitExceeded",
1337
+ "quotaExceeded",
1338
+ "dailyLimitExceeded",
1339
+ "RATE_LIMIT_EXCEEDED",
1340
+ }
1341
+ )
1342
+
1343
+
1344
+ def _is_rate_limit_or_quota_error(error: HttpError) -> bool:
1345
+ """Return True when Google rejected the request for API rate or quota limits."""
1346
+ if error.resp.status == 429:
1347
+ return True
1348
+ if error.resp.status != 403:
1349
+ return False
1350
+ try:
1351
+ payload = json.loads(error.content)
1352
+ except ValueError:
1353
+ return False
1354
+ for entry in payload if isinstance(payload, list) else [payload]:
1355
+ err = entry.get("error") if isinstance(entry, dict) else None
1356
+ if not isinstance(err, dict):
1357
+ continue
1358
+ if err.get("status") == "RESOURCE_EXHAUSTED":
1359
+ return True
1360
+ items = [err]
1361
+ for key in ("errors", "details"):
1362
+ if isinstance(err.get(key), list):
1363
+ items.extend(err[key])
1364
+ for item in items:
1365
+ if not isinstance(item, dict):
1366
+ continue
1367
+ reason, detail_type = item.get("reason"), item.get("@type")
1368
+ if (isinstance(reason, str) and reason in _RATE_LIMIT_ERROR_REASONS) or (
1369
+ isinstance(detail_type, str)
1370
+ and detail_type.endswith("/google.rpc.QuotaFailure")
1371
+ ):
1372
+ return True
1373
+ return False
1374
+
1375
+
1376
+ APPS_SCRIPT_USER_SETTINGS_URL = "https://script.google.com/home/usersettings"
1377
+
1378
+
1379
+ def _is_apps_script_api_disabled_for_user(error: HttpError, error_details: str) -> bool:
1380
+ """Google reports the per-user setting off as a 403 or a 503 "Service error -27"."""
1381
+ host = urllib.parse.urlparse(getattr(error, "uri", None) or "").hostname
1382
+ if host != "script.googleapis.com":
1383
+ return False
1384
+ status = getattr(error.resp, "status", None)
1385
+ if status == 503:
1386
+ return "Service error -27" in error_details
1387
+ return status == 403 and "has not enabled the Apps Script API" in error_details
1388
+
1389
+
1390
+ def handle_http_errors(
1391
+ tool_name: str, is_read_only: bool = False, service_type: Optional[str] = None
1392
+ ):
1393
+ """
1394
+ A decorator to handle Google API HttpErrors and transient SSL errors in a standardized way.
1395
+
1396
+ It wraps a tool function, catches HttpError, logs a detailed error message,
1397
+ and raises a ToolError with a user-friendly message.
1398
+
1399
+ If is_read_only is True, it will also catch ssl.SSLError and retry with
1400
+ exponential backoff. After exhausting retries, it raises a TransientNetworkError.
1401
+
1402
+ Args:
1403
+ tool_name (str): The name of the tool being decorated (e.g., 'list_calendars').
1404
+ is_read_only (bool): If True, the operation is considered safe to retry on
1405
+ transient network errors. Defaults to False.
1406
+ service_type (str): Optional. The Google service type (e.g., 'calendar', 'gmail').
1407
+ """
1408
+
1409
+ def decorator(func):
1410
+ @functools.wraps(func)
1411
+ async def wrapper(*args, **kwargs):
1412
+ max_retries = 3
1413
+ base_delay = 1
1414
+
1415
+ for attempt in range(max_retries):
1416
+ try:
1417
+ return await func(*args, **kwargs)
1418
+ except ssl.SSLError as e:
1419
+ if is_read_only and attempt < max_retries - 1:
1420
+ delay = base_delay * (2**attempt)
1421
+ logger.warning(
1422
+ f"SSL error in {tool_name} on attempt {attempt + 1}: {e}. Retrying in {delay} seconds..."
1423
+ )
1424
+ await asyncio.sleep(delay)
1425
+ else:
1426
+ logger.error(
1427
+ f"SSL error in {tool_name} on final attempt: {e}. Raising exception."
1428
+ )
1429
+ raise TransientNetworkError(
1430
+ f"A transient SSL error occurred in '{tool_name}' after {max_retries} attempts. "
1431
+ "This is likely a temporary network or certificate issue. Please try again shortly."
1432
+ ) from e
1433
+ except UserInputError as e:
1434
+ message = f"Input error in {tool_name}: {e}"
1435
+ logger.warning(message)
1436
+ raise e
1437
+ except HttpError as error:
1438
+ user_google_email = kwargs.get("user_google_email", "N/A")
1439
+ error_details = str(error)
1440
+ error_summary = (
1441
+ f"HTTP {error.resp.status}"
1442
+ if fastmcp.settings.mask_error_details
1443
+ else error_details
1444
+ )
1445
+
1446
+ # Check if this is an API not enabled error
1447
+ if (
1448
+ error.resp.status == 403
1449
+ and "accessNotConfigured" in error_details
1450
+ ):
1451
+ enablement_msg = get_api_enablement_message(
1452
+ error_details, service_type
1453
+ )
1454
+
1455
+ if enablement_msg:
1456
+ message = (
1457
+ f"API error in {tool_name}: {enablement_msg}\n\n"
1458
+ f"User: {user_google_email}"
1459
+ )
1460
+ else:
1461
+ message = (
1462
+ f"API error in {tool_name}: {error_summary}. "
1463
+ f"The required API is not enabled for your project. "
1464
+ f"Please check the Google Cloud Console to enable it."
1465
+ )
1466
+ elif _is_apps_script_api_disabled_for_user(error, error_details):
1467
+ message = (
1468
+ f"API error in {tool_name}: the Apps Script API refused "
1469
+ f"the request (HTTP {error.resp.status}) for user "
1470
+ f"'{user_google_email}'. This usually means the Apps "
1471
+ f"Script API is turned off in that user's Apps Script "
1472
+ f"settings. LLM: Ask the user to open "
1473
+ f"{APPS_SCRIPT_USER_SETTINGS_URL}, turn on 'Google Apps "
1474
+ f"Script API', wait a minute, and retry."
1475
+ )
1476
+ elif _is_rate_limit_or_quota_error(error):
1477
+ message = (
1478
+ f"API error in {tool_name}: {error_summary}. "
1479
+ "Google API rate limit or quota exceeded (not an authentication failure). "
1480
+ "LLM: Retry later with fewer concurrent requests."
1481
+ )
1482
+ elif error.resp.status in [401, 403]:
1483
+ # Authentication/authorization errors
1484
+ if is_oauth21_enabled():
1485
+ if is_external_oauth21_provider():
1486
+ auth_hint = (
1487
+ "LLM: Ask the user to provide a valid OAuth 2.1 "
1488
+ "bearer token in the Authorization header and retry."
1489
+ )
1490
+ else:
1491
+ auth_hint = (
1492
+ "LLM: Ask the user to authenticate via their MCP "
1493
+ "client's OAuth 2.1 flow and retry."
1494
+ )
1495
+ else:
1496
+ auth_hint = (
1497
+ "LLM: Try 'start_google_auth' with the user's email "
1498
+ "and the appropriate service_name."
1499
+ )
1500
+ message = (
1501
+ f"API error in {tool_name}: {error_summary}. "
1502
+ f"You might need to re-authenticate for user '{user_google_email}'. "
1503
+ f"{auth_hint}"
1504
+ )
1505
+ else:
1506
+ # Other HTTP errors (400 Bad Request, etc.) - don't suggest re-auth
1507
+ message = f"API error in {tool_name}: {error_summary}"
1508
+
1509
+ # ERROR gets the scrubbed form (HttpError embeds the request
1510
+ # URI and may echo user content in its response details);
1511
+ # the full exception with traceback stays at DEBUG.
1512
+ logger.error(
1513
+ f"API error in {tool_name}: {_format_http_error_for_log(error)}"
1514
+ )
1515
+ logger.debug(f"API error detail in {tool_name}", exc_info=True)
1516
+ raise ToolError(message) from error
1517
+ except TransientNetworkError:
1518
+ # Re-raise without wrapping to preserve the specific error type
1519
+ raise
1520
+ except ToolError:
1521
+ # Re-raise explicit tool errors so FastMCP can surface them directly.
1522
+ raise
1523
+ except GoogleAuthenticationError:
1524
+ # Re-raise authentication errors without wrapping
1525
+ raise
1526
+ except Exception as e:
1527
+ message = f"An unexpected error occurred in {tool_name}: {e}"
1528
+ logger.exception(message)
1529
+ raise Exception(message) from e
1530
+
1531
+ # Propagate _required_google_scopes if present (for tool filtering)
1532
+ if hasattr(func, "_required_google_scopes"):
1533
+ wrapper._required_google_scopes = func._required_google_scopes
1534
+
1535
+ return wrapper
1536
+
1537
+ return decorator