@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.
- package/LICENSE +21 -0
- package/README.md +353 -2
- package/README.npm.md +34 -0
- package/auth/__init__.py +1 -0
- package/auth/auth_info_middleware.py +419 -0
- package/auth/client_secrets.py +76 -0
- package/auth/credential_store.py +598 -0
- package/auth/external_oauth_provider.py +369 -0
- package/auth/gateway_identity.py +164 -0
- package/auth/google_auth.py +1550 -0
- package/auth/google_oauth_provider.py +20 -0
- package/auth/mcp_session_middleware.py +95 -0
- package/auth/oauth21_session_store.py +1332 -0
- package/auth/oauth_callback_server.py +466 -0
- package/auth/oauth_config.py +693 -0
- package/auth/oauth_proxy_config.py +122 -0
- package/auth/oauth_responses.py +230 -0
- package/auth/oauth_types.py +92 -0
- package/auth/permissions.py +330 -0
- package/auth/port_resolver.py +153 -0
- package/auth/request_identity.py +89 -0
- package/auth/scopes.py +369 -0
- package/auth/service_decorator.py +1109 -0
- package/bin/google-workspace-mcp.cjs +123 -0
- package/core/__init__.py +1 -0
- package/core/api_enablement.py +108 -0
- package/core/attachment_storage.py +496 -0
- package/core/camel_case_middleware.py +98 -0
- package/core/cli.py +161 -0
- package/core/comments.py +609 -0
- package/core/config.py +57 -0
- package/core/context.py +43 -0
- package/core/file_limits.py +632 -0
- package/core/gcs_attachment_storage.py +253 -0
- package/core/http_utils.py +339 -0
- package/core/log_formatter.py +270 -0
- package/core/portable_schema_middleware.py +67 -0
- package/core/server.py +1192 -0
- package/core/startup_ui.py +239 -0
- package/core/storage.py +23 -0
- package/core/telemetry.py +194 -0
- package/core/tool_descriptions.py +19 -0
- package/core/tool_registry.py +311 -0
- package/core/tool_tier_loader.py +197 -0
- package/core/tool_tiers.yaml +179 -0
- package/core/toolset_header_middleware.py +67 -0
- package/core/utils.py +1537 -0
- package/core/valkey_storage.py +271 -0
- package/core/warning_filters.py +19 -0
- package/fastmcp_server.py +198 -0
- package/gappsscript/README.md +512 -0
- package/gappsscript/TESTING.md +254 -0
- package/gappsscript/__init__.py +0 -0
- package/gappsscript/apps_script_tools.py +1940 -0
- package/gcalendar/__init__.py +1 -0
- package/gcalendar/calendar_helpers.py +1323 -0
- package/gcalendar/calendar_tools.py +2252 -0
- package/gchat/__init__.py +7 -0
- package/gchat/chat_helpers.py +410 -0
- package/gchat/chat_tools.py +798 -0
- package/gcontacts/__init__.py +1 -0
- package/gcontacts/contacts_helpers.py +765 -0
- package/gcontacts/contacts_tools.py +1685 -0
- package/gdocs/__init__.py +0 -0
- package/gdocs/docs_anchors.py +163 -0
- package/gdocs/docs_comments.py +89 -0
- package/gdocs/docs_helpers.py +2201 -0
- package/gdocs/docs_links.py +87 -0
- package/gdocs/docs_markdown.py +828 -0
- package/gdocs/docs_markdown_writer.py +592 -0
- package/gdocs/docs_plain_text.py +463 -0
- package/gdocs/docs_structure.py +621 -0
- package/gdocs/docs_tables.py +425 -0
- package/gdocs/docs_tools.py +3300 -0
- package/gdocs/managers/__init__.py +18 -0
- package/gdocs/managers/batch_operation_manager.py +1694 -0
- package/gdocs/managers/header_footer_manager.py +526 -0
- package/gdocs/managers/table_operation_manager.py +488 -0
- package/gdocs/managers/validation_manager.py +1504 -0
- package/gdocs/operation_schemas.py +594 -0
- package/gdrive/__init__.py +0 -0
- package/gdrive/drive_helpers.py +1738 -0
- package/gdrive/drive_tools.py +3085 -0
- package/gforms/__init__.py +3 -0
- package/gforms/forms_tools.py +575 -0
- package/gmail/__init__.py +1 -0
- package/gmail/gmail_helpers.py +2107 -0
- package/gmail/gmail_tools.py +4895 -0
- package/gmail/gmail_web_mime.py +441 -0
- package/gsearch/__init__.py +0 -0
- package/gsearch/search_tools.py +253 -0
- package/gsheets/__init__.py +31 -0
- package/gsheets/sheets_helpers.py +2236 -0
- package/gsheets/sheets_tools.py +3280 -0
- package/gslides/__init__.py +0 -0
- package/gslides/slides_digest.py +390 -0
- package/gslides/slides_helpers.py +392 -0
- package/gslides/slides_markup.py +770 -0
- package/gslides/slides_tools.py +376 -0
- package/gtasks/__init__.py +5 -0
- package/gtasks/tasks_tools.py +936 -0
- package/main.py +1170 -0
- package/package.json +43 -4
- package/pyproject.toml +173 -0
- package/uv.lock +2504 -0
package/core/context.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# core/context.py
|
|
2
|
+
import contextvars
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
# Context variable to hold injected credentials for the life of a single request.
|
|
6
|
+
_injected_oauth_credentials = contextvars.ContextVar(
|
|
7
|
+
"injected_oauth_credentials", default=None
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
# Context variable to hold FastMCP session ID for the life of a single request.
|
|
11
|
+
_fastmcp_session_id = contextvars.ContextVar("fastmcp_session_id", default=None)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def get_injected_oauth_credentials():
|
|
15
|
+
"""
|
|
16
|
+
Retrieve injected OAuth credentials for the current request context.
|
|
17
|
+
This is called by the authentication layer to check for request-scoped credentials.
|
|
18
|
+
"""
|
|
19
|
+
return _injected_oauth_credentials.get()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def set_injected_oauth_credentials(credentials: Optional[dict]):
|
|
23
|
+
"""
|
|
24
|
+
Set or clear the injected OAuth credentials for the current request context.
|
|
25
|
+
This is called by the service decorator.
|
|
26
|
+
"""
|
|
27
|
+
_injected_oauth_credentials.set(credentials)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def get_fastmcp_session_id() -> Optional[str]:
|
|
31
|
+
"""
|
|
32
|
+
Retrieve the FastMCP session ID for the current request context.
|
|
33
|
+
This is called by authentication layer to get the current session.
|
|
34
|
+
"""
|
|
35
|
+
return _fastmcp_session_id.get()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def set_fastmcp_session_id(session_id: Optional[str]):
|
|
39
|
+
"""
|
|
40
|
+
Set or clear the FastMCP session ID for the current request context.
|
|
41
|
+
This is called when a FastMCP request starts.
|
|
42
|
+
"""
|
|
43
|
+
_fastmcp_session_id.set(session_id)
|
|
@@ -0,0 +1,632 @@
|
|
|
1
|
+
"""Env-gated limits for in-memory Google file / attachment downloads.
|
|
2
|
+
|
|
3
|
+
``WORKSPACE_MCP_MAX_FILE_BYTES`` caps how many bytes a tool may buffer into
|
|
4
|
+
process memory (Drive MediaIo downloads, Gmail attachments, etc.).
|
|
5
|
+
|
|
6
|
+
Default is disabled (``0`` / unset) so existing deployments keep uncapped
|
|
7
|
+
behavior. Set a positive integer (e.g. ``5242880`` for 5 MiB) to enable.
|
|
8
|
+
|
|
9
|
+
``WORKSPACE_MCP_MAX_OFFICE_XML_BYTES`` independently caps both the XML expanded
|
|
10
|
+
from one Office file and the text extracted from it. It is on by default;
|
|
11
|
+
``0`` disables it.
|
|
12
|
+
|
|
13
|
+
``WORKSPACE_MCP_STATELESS_INLINE_MAX_BYTES`` caps the file a stateless-mode
|
|
14
|
+
download returns inline. It defaults to 10 MiB and never exceeds
|
|
15
|
+
``WORKSPACE_MCP_MAX_FILE_BYTES``.
|
|
16
|
+
|
|
17
|
+
``WORKSPACE_MCP_MAX_CONTENT_CHARS`` sets the default page size of the text
|
|
18
|
+
``get_drive_file_content`` returns; the rest is available by calling again with
|
|
19
|
+
an offset, and a client can pass ``full_content=True`` for all of it in one
|
|
20
|
+
call. It defaults to 40,000 characters; ``0`` returns whole content by default.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import asyncio
|
|
26
|
+
import io
|
|
27
|
+
import os
|
|
28
|
+
import sys
|
|
29
|
+
import time
|
|
30
|
+
from collections import OrderedDict
|
|
31
|
+
from collections.abc import Callable, Hashable
|
|
32
|
+
from typing import Any, Optional
|
|
33
|
+
|
|
34
|
+
import httpx
|
|
35
|
+
from google.auth.transport.requests import Request as GoogleAuthRequest
|
|
36
|
+
from googleapiclient.errors import HttpError
|
|
37
|
+
from googleapiclient.http import MediaIoBaseDownload
|
|
38
|
+
|
|
39
|
+
_ENV_NAME = "WORKSPACE_MCP_MAX_FILE_BYTES"
|
|
40
|
+
_OFFICE_XML_ENV_NAME = "WORKSPACE_MCP_MAX_OFFICE_XML_BYTES"
|
|
41
|
+
_STATELESS_INLINE_ENV_NAME = "WORKSPACE_MCP_STATELESS_INLINE_MAX_BYTES"
|
|
42
|
+
_CONTENT_CHARS_ENV_NAME = "WORKSPACE_MCP_MAX_CONTENT_CHARS"
|
|
43
|
+
_PAGED_CONTENT_CACHE_ENV_NAME = "WORKSPACE_MCP_PAGED_CONTENT_CACHE_BYTES"
|
|
44
|
+
|
|
45
|
+
# Office files are ZIP archives, so the download cap above bounds only the
|
|
46
|
+
# COMPRESSED size, and XML compresses by orders of magnitude. Unlike the
|
|
47
|
+
# download cap this one is on by default: the download cap is opt-in to protect
|
|
48
|
+
# deployments that need large downloads, and nothing comparable depends on
|
|
49
|
+
# unbounded expansion.
|
|
50
|
+
#
|
|
51
|
+
# This counts expanded XML bytes, not memory. The parsed tree is much larger:
|
|
52
|
+
# measured with tracemalloc on 1 MiB of XML, peak allocation was about 14x the
|
|
53
|
+
# XML size for paragraphs of short text and about 30x for empty elements. The
|
|
54
|
+
# default therefore allows a worst case in the hundreds of MiB per extraction;
|
|
55
|
+
# small containers should set it lower.
|
|
56
|
+
DEFAULT_MAX_OFFICE_XML_BYTES = 25 * 1024 * 1024 # 25 MiB
|
|
57
|
+
|
|
58
|
+
# Base64 inflates an inline payload by a third, so this is ~13.4 MiB on the wire.
|
|
59
|
+
DEFAULT_STATELESS_INLINE_MAX_BYTES = 10 * 1024 * 1024 # 10 MiB
|
|
60
|
+
|
|
61
|
+
DEFAULT_MAX_CONTENT_CHARS = 40_000
|
|
62
|
+
|
|
63
|
+
DEFAULT_PAGED_CONTENT_CACHE_BYTES = 32 * 1024 * 1024 # 32 MiB
|
|
64
|
+
|
|
65
|
+
# Keep the uncapped path from asking httplib2 to materialize its 100 MiB
|
|
66
|
+
# default response chunk. This does not impose a total-size limit; it only
|
|
67
|
+
# bounds the transient allocation made by each MediaIoBaseDownload request.
|
|
68
|
+
_MEDIA_DOWNLOAD_CHUNK_SIZE_BYTES = 256 * 1024 # 256 KiB
|
|
69
|
+
|
|
70
|
+
# Stream read size when a byte cap is active. Keep small so we can abort
|
|
71
|
+
# near the ceiling even when Content-Length is absent.
|
|
72
|
+
_STREAM_READ_SIZE_BYTES = 64 * 1024 # 64 KiB
|
|
73
|
+
|
|
74
|
+
# Error bodies are diagnostic data, not file payloads. They must still be
|
|
75
|
+
# bounded or an upstream/proxy error can bypass the configured memory guard.
|
|
76
|
+
_MAX_ERROR_BODY_BYTES = 64 * 1024 # 64 KiB
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class FileTooLargeError(ValueError):
|
|
80
|
+
"""Raised when a download would exceed ``WORKSPACE_MCP_MAX_FILE_BYTES``."""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def get_max_file_bytes() -> Optional[int]:
|
|
84
|
+
"""Return the configured max download size in bytes, or ``None`` if uncapped.
|
|
85
|
+
|
|
86
|
+
Parsing rules:
|
|
87
|
+
- unset, empty, or ``0`` → uncapped (``None``)
|
|
88
|
+
- positive int → that many bytes
|
|
89
|
+
- invalid or negative value → raise ``ValueError``
|
|
90
|
+
"""
|
|
91
|
+
value = _byte_count_from_env(_ENV_NAME)
|
|
92
|
+
return value or None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def get_max_office_xml_bytes() -> Optional[int]:
|
|
96
|
+
"""Return the cap on bytes expanded out of one Office file, or ``None``.
|
|
97
|
+
|
|
98
|
+
Parsing rules:
|
|
99
|
+
- unset or empty → ``DEFAULT_MAX_OFFICE_XML_BYTES``
|
|
100
|
+
- ``0`` → uncapped (``None``)
|
|
101
|
+
- positive int → that many bytes
|
|
102
|
+
- invalid or negative value → raise ``ValueError``
|
|
103
|
+
"""
|
|
104
|
+
value = _byte_count_from_env(_OFFICE_XML_ENV_NAME)
|
|
105
|
+
if value is None:
|
|
106
|
+
return DEFAULT_MAX_OFFICE_XML_BYTES
|
|
107
|
+
return value or None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def get_stateless_inline_max_bytes() -> int:
|
|
111
|
+
"""Return the largest file a stateless-mode download may return inline.
|
|
112
|
+
|
|
113
|
+
Parsing rules:
|
|
114
|
+
- unset or empty → ``DEFAULT_STATELESS_INLINE_MAX_BYTES``
|
|
115
|
+
- ``0`` → nothing is inlined
|
|
116
|
+
- positive int → that many bytes
|
|
117
|
+
- invalid or negative value → raise ``ValueError``
|
|
118
|
+
|
|
119
|
+
Inlining holds the whole file in memory, so ``WORKSPACE_MCP_MAX_FILE_BYTES``
|
|
120
|
+
lowers this when set.
|
|
121
|
+
"""
|
|
122
|
+
value = _byte_count_from_env(_STATELESS_INLINE_ENV_NAME)
|
|
123
|
+
if value is None:
|
|
124
|
+
value = DEFAULT_STATELESS_INLINE_MAX_BYTES
|
|
125
|
+
max_file_bytes = get_max_file_bytes()
|
|
126
|
+
return min(value, max_file_bytes) if max_file_bytes else value
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def get_max_content_chars() -> Optional[int]:
|
|
130
|
+
"""Return the default page size for content reads in characters, or ``None``
|
|
131
|
+
for whole content.
|
|
132
|
+
|
|
133
|
+
Parsing rules:
|
|
134
|
+
- unset or empty → ``DEFAULT_MAX_CONTENT_CHARS``
|
|
135
|
+
- ``0`` → whole content (``None``)
|
|
136
|
+
- positive int → that many characters
|
|
137
|
+
- invalid or negative value → raise ``ValueError``
|
|
138
|
+
"""
|
|
139
|
+
value = _byte_count_from_env(_CONTENT_CHARS_ENV_NAME, unit="character")
|
|
140
|
+
if value is None:
|
|
141
|
+
return DEFAULT_MAX_CONTENT_CHARS
|
|
142
|
+
return value or None
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def get_paged_content_cache_bytes() -> int:
|
|
146
|
+
"""Return the memory paged content may be kept in between calls.
|
|
147
|
+
|
|
148
|
+
Parsing rules:
|
|
149
|
+
- unset or empty → ``DEFAULT_PAGED_CONTENT_CACHE_BYTES``
|
|
150
|
+
- ``0`` → nothing is kept
|
|
151
|
+
- positive int → that many bytes
|
|
152
|
+
- invalid or negative value → raise ``ValueError``
|
|
153
|
+
"""
|
|
154
|
+
value = _byte_count_from_env(_PAGED_CONTENT_CACHE_ENV_NAME)
|
|
155
|
+
return DEFAULT_PAGED_CONTENT_CACHE_BYTES if value is None else value
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def validate_file_limit_settings() -> None:
|
|
159
|
+
"""Raise ``ValueError`` if any file-limit environment setting is invalid."""
|
|
160
|
+
get_max_file_bytes()
|
|
161
|
+
get_max_office_xml_bytes()
|
|
162
|
+
get_stateless_inline_max_bytes()
|
|
163
|
+
get_max_content_chars()
|
|
164
|
+
get_paged_content_cache_bytes()
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _byte_count_from_env(name: str, *, unit: str = "byte") -> Optional[int]:
|
|
168
|
+
"""Parse a non-negative count from ``name``; ``None`` when unset or empty."""
|
|
169
|
+
raw = os.getenv(name)
|
|
170
|
+
if raw is None or raw.strip() == "":
|
|
171
|
+
return None
|
|
172
|
+
try:
|
|
173
|
+
value = int(raw.strip())
|
|
174
|
+
except ValueError as exc:
|
|
175
|
+
raise ValueError(
|
|
176
|
+
f"Invalid {name}={raw!r}; expected a non-negative integer {unit} count."
|
|
177
|
+
) from exc
|
|
178
|
+
if value < 0:
|
|
179
|
+
raise ValueError(
|
|
180
|
+
f"Invalid {name}={raw!r}; expected a non-negative integer {unit} count."
|
|
181
|
+
)
|
|
182
|
+
return value
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def page_content_text(
|
|
186
|
+
text: str,
|
|
187
|
+
*,
|
|
188
|
+
offset: int = 0,
|
|
189
|
+
max_chars: Optional[int] = None,
|
|
190
|
+
alternative: str = "",
|
|
191
|
+
) -> str:
|
|
192
|
+
"""Return up to ``max_chars`` of ``text`` from ``offset``, plus a read-on note
|
|
193
|
+
with the next offset when more follows. ``None`` means no limit."""
|
|
194
|
+
total = len(text)
|
|
195
|
+
if offset > total:
|
|
196
|
+
return (
|
|
197
|
+
f"[offset={offset:,} is past the end of the content "
|
|
198
|
+
f"({total:,} characters).]"
|
|
199
|
+
)
|
|
200
|
+
if max_chars is None or total - offset <= max_chars:
|
|
201
|
+
return text[offset:]
|
|
202
|
+
|
|
203
|
+
page = text[offset : offset + max_chars]
|
|
204
|
+
line_end = page.rfind("\n") + 1
|
|
205
|
+
if line_end >= max_chars / 2:
|
|
206
|
+
page = page[:line_end]
|
|
207
|
+
end = offset + len(page)
|
|
208
|
+
return (
|
|
209
|
+
f"{page}\n\n[Truncated: showing characters {offset:,} to {end:,} of "
|
|
210
|
+
f"{total:,}; {total - end:,} more follow (default page size "
|
|
211
|
+
f"{max_chars:,}, set by {_CONTENT_CHARS_ENV_NAME}). Call again with offset={end} to "
|
|
212
|
+
f"read on{alternative}.]"
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class PagedContentCache:
|
|
217
|
+
"""TTL and LRU cache of paged text, bounded by ``max_bytes`` of memory.
|
|
218
|
+
|
|
219
|
+
A single entry may take at most a quarter of ``max_bytes``.
|
|
220
|
+
"""
|
|
221
|
+
|
|
222
|
+
def __init__(
|
|
223
|
+
self,
|
|
224
|
+
*,
|
|
225
|
+
ttl_seconds: float,
|
|
226
|
+
clock: Callable[[], float] = time.monotonic,
|
|
227
|
+
) -> None:
|
|
228
|
+
self._ttl_seconds = ttl_seconds
|
|
229
|
+
self._clock = clock
|
|
230
|
+
self._entries: OrderedDict[Hashable, tuple[float, str, int]] = OrderedDict()
|
|
231
|
+
self._bytes = 0
|
|
232
|
+
|
|
233
|
+
def get(self, key: Hashable) -> Optional[str]:
|
|
234
|
+
entry = self._entries.get(key)
|
|
235
|
+
if entry is None:
|
|
236
|
+
return None
|
|
237
|
+
stored_at, text, _ = entry
|
|
238
|
+
if self._clock() - stored_at > self._ttl_seconds:
|
|
239
|
+
self._drop(key)
|
|
240
|
+
return None
|
|
241
|
+
self._entries.move_to_end(key)
|
|
242
|
+
return text
|
|
243
|
+
|
|
244
|
+
def put(self, key: Hashable, text: str, *, max_bytes: int) -> None:
|
|
245
|
+
now = self._clock()
|
|
246
|
+
for stale in [
|
|
247
|
+
k for k, (t, _, _) in self._entries.items() if now - t > self._ttl_seconds
|
|
248
|
+
]:
|
|
249
|
+
self._drop(stale)
|
|
250
|
+
if key in self._entries:
|
|
251
|
+
self._drop(key)
|
|
252
|
+
size = sys.getsizeof(text)
|
|
253
|
+
if size > max_bytes // 4:
|
|
254
|
+
return
|
|
255
|
+
self._entries[key] = (now, text, size)
|
|
256
|
+
self._bytes += size
|
|
257
|
+
while self._bytes > max_bytes:
|
|
258
|
+
self._drop(next(iter(self._entries)))
|
|
259
|
+
|
|
260
|
+
def clear(self) -> None:
|
|
261
|
+
self._entries.clear()
|
|
262
|
+
self._bytes = 0
|
|
263
|
+
|
|
264
|
+
def _drop(self, key: Hashable) -> None:
|
|
265
|
+
_, _, size = self._entries.pop(key)
|
|
266
|
+
self._bytes -= size
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def format_file_too_large_message(
|
|
270
|
+
*,
|
|
271
|
+
size_bytes: int,
|
|
272
|
+
max_bytes: int,
|
|
273
|
+
file_name: Optional[str] = None,
|
|
274
|
+
file_id: Optional[str] = None,
|
|
275
|
+
web_view_link: Optional[str] = None,
|
|
276
|
+
kind: str = "file",
|
|
277
|
+
) -> str:
|
|
278
|
+
"""Build an agent-friendly error that points at alternatives, not file surgery."""
|
|
279
|
+
label = f'"{file_name}"' if file_name else f"this {kind}"
|
|
280
|
+
id_part = f" (ID: {file_id})" if file_id else ""
|
|
281
|
+
link_part = ""
|
|
282
|
+
if web_view_link and web_view_link != "#":
|
|
283
|
+
link_part = f"\nOpen in Google Drive: {web_view_link}"
|
|
284
|
+
|
|
285
|
+
return (
|
|
286
|
+
f"Error: {label}{id_part} is too large to load into this MCP server "
|
|
287
|
+
f"({size_bytes:,} bytes; limit is {max_bytes:,} bytes via {_ENV_NAME}).\n"
|
|
288
|
+
f"Full binary download through this tool is not available for oversized "
|
|
289
|
+
f"{kind}s.{link_part}\n"
|
|
290
|
+
"Alternatives:\n"
|
|
291
|
+
"- Use get_doc_content / get_doc_as_markdown for Google Docs\n"
|
|
292
|
+
"- Use read_sheet_values for Google Sheets\n"
|
|
293
|
+
"- Use get_drive_file_content for text-oriented exports when under the limit\n"
|
|
294
|
+
"- Open the Drive link above for large binaries (video, zip, large PDF, etc.)"
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def ensure_within_file_size_limit(
|
|
299
|
+
size_bytes: Optional[int],
|
|
300
|
+
*,
|
|
301
|
+
file_name: Optional[str] = None,
|
|
302
|
+
file_id: Optional[str] = None,
|
|
303
|
+
web_view_link: Optional[str] = None,
|
|
304
|
+
kind: str = "file",
|
|
305
|
+
max_bytes: Optional[int] = None,
|
|
306
|
+
) -> None:
|
|
307
|
+
"""Raise ``FileTooLargeError`` if a declared size exceeds the configured cap."""
|
|
308
|
+
limit = get_max_file_bytes() if max_bytes is None else max_bytes
|
|
309
|
+
if limit is None or size_bytes is None:
|
|
310
|
+
return
|
|
311
|
+
try:
|
|
312
|
+
declared = int(size_bytes)
|
|
313
|
+
except (TypeError, ValueError):
|
|
314
|
+
return
|
|
315
|
+
if declared > limit:
|
|
316
|
+
raise FileTooLargeError(
|
|
317
|
+
format_file_too_large_message(
|
|
318
|
+
size_bytes=declared,
|
|
319
|
+
max_bytes=limit,
|
|
320
|
+
file_name=file_name,
|
|
321
|
+
file_id=file_id,
|
|
322
|
+
web_view_link=web_view_link,
|
|
323
|
+
kind=kind,
|
|
324
|
+
)
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _raise_too_large(
|
|
329
|
+
*,
|
|
330
|
+
size_bytes: int,
|
|
331
|
+
max_bytes: int,
|
|
332
|
+
file_name: Optional[str],
|
|
333
|
+
file_id: Optional[str],
|
|
334
|
+
web_view_link: Optional[str],
|
|
335
|
+
kind: str,
|
|
336
|
+
) -> None:
|
|
337
|
+
raise FileTooLargeError(
|
|
338
|
+
format_file_too_large_message(
|
|
339
|
+
size_bytes=size_bytes,
|
|
340
|
+
max_bytes=max_bytes,
|
|
341
|
+
file_name=file_name,
|
|
342
|
+
file_id=file_id,
|
|
343
|
+
web_view_link=web_view_link,
|
|
344
|
+
kind=kind,
|
|
345
|
+
)
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _authorize_headers(
|
|
350
|
+
request_obj: Any, *, force_refresh: bool = False
|
|
351
|
+
) -> dict[str, str]:
|
|
352
|
+
"""Copy request headers and authorize them like ``AuthorizedHttp`` does."""
|
|
353
|
+
headers = dict(getattr(request_obj, "headers", None) or {})
|
|
354
|
+
http = getattr(request_obj, "http", None)
|
|
355
|
+
credentials = getattr(http, "credentials", None) if http is not None else None
|
|
356
|
+
if credentials is None:
|
|
357
|
+
return headers
|
|
358
|
+
|
|
359
|
+
# Reuse AuthorizedHttp's refresh transport when available. A fallback
|
|
360
|
+
# google-auth Request owns a requests.Session, so close it deterministically.
|
|
361
|
+
auth_request = getattr(http, "_request", None)
|
|
362
|
+
owned_auth_request = auth_request is None
|
|
363
|
+
if owned_auth_request:
|
|
364
|
+
auth_request = GoogleAuthRequest()
|
|
365
|
+
try:
|
|
366
|
+
if force_refresh:
|
|
367
|
+
credentials.refresh(auth_request)
|
|
368
|
+
method = (getattr(request_obj, "method", None) or "GET").upper()
|
|
369
|
+
uri = getattr(request_obj, "uri", None) or ""
|
|
370
|
+
credentials.before_request(auth_request, method, uri, headers)
|
|
371
|
+
finally:
|
|
372
|
+
if owned_auth_request:
|
|
373
|
+
auth_request.session.close()
|
|
374
|
+
return headers
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
async def _download_media_bytes_uncapped(request_obj: Any) -> bytes:
|
|
378
|
+
"""Download via MediaIoBaseDownload (full response may be buffered per chunk)."""
|
|
379
|
+
fh = io.BytesIO()
|
|
380
|
+
downloader = MediaIoBaseDownload(
|
|
381
|
+
fh, request_obj, chunksize=_MEDIA_DOWNLOAD_CHUNK_SIZE_BYTES
|
|
382
|
+
)
|
|
383
|
+
done = False
|
|
384
|
+
while not done:
|
|
385
|
+
_status, done = await asyncio.to_thread(downloader.next_chunk)
|
|
386
|
+
return fh.getvalue()
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
async def _accumulate_capped_stream(
|
|
390
|
+
resp: httpx.Response,
|
|
391
|
+
*,
|
|
392
|
+
limit: int,
|
|
393
|
+
file_name: Optional[str],
|
|
394
|
+
file_id: Optional[str],
|
|
395
|
+
web_view_link: Optional[str],
|
|
396
|
+
kind: str,
|
|
397
|
+
) -> bytes:
|
|
398
|
+
"""Read an open streamed response, aborting once past ``limit``."""
|
|
399
|
+
content_encoding = resp.headers.get("content-encoding", "").strip().lower()
|
|
400
|
+
content_length = resp.headers.get("content-length")
|
|
401
|
+
# Content-Length describes the encoded wire representation, whereas
|
|
402
|
+
# aiter_bytes() yields decoded bytes. It is only comparable to the file-byte
|
|
403
|
+
# limit for identity responses. Capped requests ask for identity below, but
|
|
404
|
+
# keep this guard for non-compliant intermediaries.
|
|
405
|
+
if content_length is not None and content_encoding in {"", "identity"}:
|
|
406
|
+
try:
|
|
407
|
+
declared = int(content_length)
|
|
408
|
+
except ValueError:
|
|
409
|
+
declared = None
|
|
410
|
+
if declared is not None and declared > limit:
|
|
411
|
+
# Close without reading the body into process memory.
|
|
412
|
+
_raise_too_large(
|
|
413
|
+
size_bytes=declared,
|
|
414
|
+
max_bytes=limit,
|
|
415
|
+
file_name=file_name,
|
|
416
|
+
file_id=file_id,
|
|
417
|
+
web_view_link=web_view_link,
|
|
418
|
+
kind=kind,
|
|
419
|
+
)
|
|
420
|
+
|
|
421
|
+
read_size = max(1, min(_STREAM_READ_SIZE_BYTES, limit))
|
|
422
|
+
# BytesIO.getvalue() exposes its immutable backing bytes without the
|
|
423
|
+
# bytearray -> bytes full-size copy that previously doubled peak memory at
|
|
424
|
+
# successful completion.
|
|
425
|
+
buf = io.BytesIO()
|
|
426
|
+
buffered_size = 0
|
|
427
|
+
async for chunk in resp.aiter_bytes(chunk_size=read_size):
|
|
428
|
+
if not chunk:
|
|
429
|
+
continue
|
|
430
|
+
next_size = buffered_size + len(chunk)
|
|
431
|
+
if next_size > limit:
|
|
432
|
+
_raise_too_large(
|
|
433
|
+
size_bytes=next_size,
|
|
434
|
+
max_bytes=limit,
|
|
435
|
+
file_name=file_name,
|
|
436
|
+
file_id=file_id,
|
|
437
|
+
web_view_link=web_view_link,
|
|
438
|
+
kind=kind,
|
|
439
|
+
)
|
|
440
|
+
buf.write(chunk)
|
|
441
|
+
buffered_size = next_size
|
|
442
|
+
return buf.getvalue()
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _http_status_error(
|
|
446
|
+
resp: httpx.Response, *, content: Optional[bytes] = None
|
|
447
|
+
) -> httpx.HTTPStatusError:
|
|
448
|
+
"""Build an HTTPStatusError for a completed (possibly streamed) response."""
|
|
449
|
+
if content is not None:
|
|
450
|
+
# A streaming response does not expose .content until it has been read
|
|
451
|
+
# completely. Build a small completed response containing only the
|
|
452
|
+
# bounded diagnostic prefix so downstream error conversion stays safe.
|
|
453
|
+
resp = httpx.Response(
|
|
454
|
+
status_code=resp.status_code,
|
|
455
|
+
headers=resp.headers,
|
|
456
|
+
content=content,
|
|
457
|
+
request=resp.request,
|
|
458
|
+
extensions=resp.extensions,
|
|
459
|
+
)
|
|
460
|
+
return httpx.HTTPStatusError(
|
|
461
|
+
f"Client error '{resp.status_code} {resp.reason_phrase}' for url '{resp.request.url}'",
|
|
462
|
+
request=resp.request,
|
|
463
|
+
response=resp,
|
|
464
|
+
)
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
async def _read_bounded_error_body(resp: httpx.Response, *, limit: int) -> bytes:
|
|
468
|
+
"""Read at most ``limit`` decoded bytes from an HTTP error response."""
|
|
469
|
+
body = bytearray()
|
|
470
|
+
async for chunk in resp.aiter_bytes(
|
|
471
|
+
chunk_size=max(1, min(_STREAM_READ_SIZE_BYTES, limit))
|
|
472
|
+
):
|
|
473
|
+
remaining = limit - len(body)
|
|
474
|
+
if remaining <= 0:
|
|
475
|
+
break
|
|
476
|
+
body.extend(chunk[:remaining])
|
|
477
|
+
if len(body) >= limit:
|
|
478
|
+
break
|
|
479
|
+
return bytes(body)
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
async def download_http_url_bytes(
|
|
483
|
+
url: str,
|
|
484
|
+
*,
|
|
485
|
+
headers: Optional[dict[str, str]] = None,
|
|
486
|
+
method: str = "GET",
|
|
487
|
+
file_name: Optional[str] = None,
|
|
488
|
+
file_id: Optional[str] = None,
|
|
489
|
+
web_view_link: Optional[str] = None,
|
|
490
|
+
kind: str = "file",
|
|
491
|
+
max_bytes: Optional[int] = None,
|
|
492
|
+
) -> bytes:
|
|
493
|
+
"""Download ``url`` into memory, honoring ``WORKSPACE_MCP_MAX_FILE_BYTES``.
|
|
494
|
+
|
|
495
|
+
When a cap is set, streams and aborts on Content-Length or mid-body.
|
|
496
|
+
Raises ``FileTooLargeError`` when over the limit, or
|
|
497
|
+
``httpx.HTTPStatusError`` for non-2xx responses.
|
|
498
|
+
"""
|
|
499
|
+
limit = get_max_file_bytes() if max_bytes is None else max_bytes
|
|
500
|
+
req_headers = dict(headers or {})
|
|
501
|
+
timeout = httpx.Timeout(120.0, connect=30.0)
|
|
502
|
+
method = method.upper()
|
|
503
|
+
|
|
504
|
+
if limit is not None:
|
|
505
|
+
# googleapiclient media requests advertise gzip by default. httpx then
|
|
506
|
+
# reports the compressed Content-Length but yields decompressed chunks,
|
|
507
|
+
# making the two size checks use different units and allowing the
|
|
508
|
+
# decoder to allocate far beyond the cap before a chunk is yielded.
|
|
509
|
+
req_headers = {
|
|
510
|
+
key: value
|
|
511
|
+
for key, value in req_headers.items()
|
|
512
|
+
if key.lower() != "accept-encoding"
|
|
513
|
+
}
|
|
514
|
+
req_headers["Accept-Encoding"] = "identity"
|
|
515
|
+
|
|
516
|
+
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client:
|
|
517
|
+
if limit is None:
|
|
518
|
+
resp = await client.request(method, url, headers=req_headers)
|
|
519
|
+
if resp.status_code >= 400:
|
|
520
|
+
raise _http_status_error(resp)
|
|
521
|
+
return resp.content
|
|
522
|
+
|
|
523
|
+
async with client.stream(method, url, headers=req_headers) as resp:
|
|
524
|
+
if resp.status_code >= 400:
|
|
525
|
+
error_limit = max(1, min(_MAX_ERROR_BODY_BYTES, limit))
|
|
526
|
+
error_body = await _read_bounded_error_body(resp, limit=error_limit)
|
|
527
|
+
raise _http_status_error(resp, content=error_body)
|
|
528
|
+
return await _accumulate_capped_stream(
|
|
529
|
+
resp,
|
|
530
|
+
limit=limit,
|
|
531
|
+
file_name=file_name,
|
|
532
|
+
file_id=file_id,
|
|
533
|
+
web_view_link=web_view_link,
|
|
534
|
+
kind=kind,
|
|
535
|
+
)
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
async def _download_media_bytes_capped(
|
|
539
|
+
request_obj: Any,
|
|
540
|
+
*,
|
|
541
|
+
limit: int,
|
|
542
|
+
file_name: Optional[str],
|
|
543
|
+
file_id: Optional[str],
|
|
544
|
+
web_view_link: Optional[str],
|
|
545
|
+
kind: str,
|
|
546
|
+
) -> bytes:
|
|
547
|
+
"""Stream a media URL and abort before buffering past ``limit``.
|
|
548
|
+
|
|
549
|
+
``MediaIoBaseDownload`` cannot enforce this for Drive ``export_media``:
|
|
550
|
+
exports often ignore ``Range`` and return HTTP 200 with the entire body,
|
|
551
|
+
which httplib2 buffers into ``content`` before any size check runs.
|
|
552
|
+
"""
|
|
553
|
+
uri = getattr(request_obj, "uri", None)
|
|
554
|
+
if not uri:
|
|
555
|
+
raise ValueError("media request is missing uri")
|
|
556
|
+
|
|
557
|
+
method = (getattr(request_obj, "method", None) or "GET").upper()
|
|
558
|
+
headers = await asyncio.to_thread(_authorize_headers, request_obj)
|
|
559
|
+
try:
|
|
560
|
+
try:
|
|
561
|
+
return await download_http_url_bytes(
|
|
562
|
+
uri,
|
|
563
|
+
headers=headers,
|
|
564
|
+
method=method,
|
|
565
|
+
file_name=file_name,
|
|
566
|
+
file_id=file_id,
|
|
567
|
+
web_view_link=web_view_link,
|
|
568
|
+
kind=kind,
|
|
569
|
+
max_bytes=limit,
|
|
570
|
+
)
|
|
571
|
+
except httpx.HTTPStatusError as exc:
|
|
572
|
+
# Match google-auth's AuthorizedHttp behavior: a token can be
|
|
573
|
+
# rejected after it passed the local expiry check, so refresh and
|
|
574
|
+
# retry exactly once on 401 before surfacing an auth failure.
|
|
575
|
+
http = getattr(request_obj, "http", None)
|
|
576
|
+
credentials = (
|
|
577
|
+
getattr(http, "credentials", None) if http is not None else None
|
|
578
|
+
)
|
|
579
|
+
if exc.response.status_code != 401 or credentials is None:
|
|
580
|
+
raise
|
|
581
|
+
headers = await asyncio.to_thread(
|
|
582
|
+
_authorize_headers, request_obj, force_refresh=True
|
|
583
|
+
)
|
|
584
|
+
return await download_http_url_bytes(
|
|
585
|
+
uri,
|
|
586
|
+
headers=headers,
|
|
587
|
+
method=method,
|
|
588
|
+
file_name=file_name,
|
|
589
|
+
file_id=file_id,
|
|
590
|
+
web_view_link=web_view_link,
|
|
591
|
+
kind=kind,
|
|
592
|
+
max_bytes=limit,
|
|
593
|
+
)
|
|
594
|
+
except httpx.HTTPStatusError as exc:
|
|
595
|
+
body = exc.response.content or b""
|
|
596
|
+
httplib2_resp = type(
|
|
597
|
+
"Response",
|
|
598
|
+
(),
|
|
599
|
+
{
|
|
600
|
+
"status": exc.response.status_code,
|
|
601
|
+
"reason": exc.response.reason_phrase,
|
|
602
|
+
},
|
|
603
|
+
)()
|
|
604
|
+
raise HttpError(httplib2_resp, body, uri=uri) from exc
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
async def download_media_bytes(
|
|
608
|
+
request_obj: Any,
|
|
609
|
+
*,
|
|
610
|
+
file_name: Optional[str] = None,
|
|
611
|
+
file_id: Optional[str] = None,
|
|
612
|
+
web_view_link: Optional[str] = None,
|
|
613
|
+
kind: str = "file",
|
|
614
|
+
max_bytes: Optional[int] = None,
|
|
615
|
+
) -> bytes:
|
|
616
|
+
"""Download a Drive ``get_media`` / ``export_media`` request into memory.
|
|
617
|
+
|
|
618
|
+
When ``WORKSPACE_MCP_MAX_FILE_BYTES`` is set, streams the response and
|
|
619
|
+
aborts as soon as Content-Length or buffered bytes exceed the cap — so
|
|
620
|
+
Google Docs PDF exports (which ignore Range) cannot fill the cgroup.
|
|
621
|
+
"""
|
|
622
|
+
limit = get_max_file_bytes() if max_bytes is None else max_bytes
|
|
623
|
+
if limit is None:
|
|
624
|
+
return await _download_media_bytes_uncapped(request_obj)
|
|
625
|
+
return await _download_media_bytes_capped(
|
|
626
|
+
request_obj,
|
|
627
|
+
limit=limit,
|
|
628
|
+
file_name=file_name,
|
|
629
|
+
file_id=file_id,
|
|
630
|
+
web_view_link=web_view_link,
|
|
631
|
+
kind=kind,
|
|
632
|
+
)
|