@mutallip/google-workspace-mcp 0.0.0-stage → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +353 -2
- package/README.npm.md +28 -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
|
@@ -0,0 +1,496 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Temporary attachment storage for Gmail attachments.
|
|
3
|
+
|
|
4
|
+
Stores attachments to local disk and returns file paths for direct access.
|
|
5
|
+
Files are automatically cleaned up after expiration (default 1 hour).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import base64
|
|
9
|
+
import logging
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import shutil
|
|
13
|
+
import time
|
|
14
|
+
import unicodedata
|
|
15
|
+
import uuid
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import NamedTuple, Optional, Dict
|
|
18
|
+
from datetime import datetime, timedelta
|
|
19
|
+
from urllib.parse import urlparse
|
|
20
|
+
|
|
21
|
+
from core import config
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
# Default expiration: 1 hour
|
|
26
|
+
DEFAULT_EXPIRATION_SECONDS = 3600
|
|
27
|
+
|
|
28
|
+
# Storage directory - configurable via WORKSPACE_ATTACHMENT_DIR env var
|
|
29
|
+
# Uses absolute path to avoid creating tmp/ in arbitrary working directories (see #327)
|
|
30
|
+
_default_dir = str(Path.home() / ".workspace-mcp" / "attachments")
|
|
31
|
+
STORAGE_DIR = (
|
|
32
|
+
Path(os.getenv("WORKSPACE_ATTACHMENT_DIR", _default_dir)).expanduser().resolve()
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
# Fallback extensions for attachments that arrive without a filename.
|
|
36
|
+
_MIME_TO_EXTENSION = {
|
|
37
|
+
"image/jpeg": ".jpg",
|
|
38
|
+
"image/png": ".png",
|
|
39
|
+
"image/gif": ".gif",
|
|
40
|
+
"application/pdf": ".pdf",
|
|
41
|
+
"application/zip": ".zip",
|
|
42
|
+
"text/plain": ".txt",
|
|
43
|
+
"text/html": ".html",
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
_MAX_FILE_NAME_BYTES = 255
|
|
47
|
+
|
|
48
|
+
_WINDOWS_RESERVED_FILENAME_CHARS = re.compile(r'[<>:"/\\|?*\x00-\x1f]')
|
|
49
|
+
_WINDOWS_RESERVED_NAMES = {
|
|
50
|
+
"CON",
|
|
51
|
+
"PRN",
|
|
52
|
+
"AUX",
|
|
53
|
+
"NUL",
|
|
54
|
+
*(f"COM{i}" for i in range(1, 10)),
|
|
55
|
+
*(f"LPT{i}" for i in range(1, 10)),
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _ensure_storage_dir() -> None:
|
|
60
|
+
"""Create the storage directory on first use, not at import time."""
|
|
61
|
+
STORAGE_DIR.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def sanitize_attachment_filename(filename: Optional[str]) -> str:
|
|
65
|
+
"""Return a filesystem-safe attachment filename."""
|
|
66
|
+
if not filename:
|
|
67
|
+
return "attachment"
|
|
68
|
+
|
|
69
|
+
# Normalize Unicode space separators (category "Zs") to a plain ASCII space.
|
|
70
|
+
filename = "".join(
|
|
71
|
+
" " if unicodedata.category(ch) == "Zs" else ch for ch in filename
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
sanitized = _WINDOWS_RESERVED_FILENAME_CHARS.sub("_", filename).rstrip(" .")
|
|
75
|
+
if not sanitized:
|
|
76
|
+
return "attachment"
|
|
77
|
+
|
|
78
|
+
stem = sanitized.split(".", 1)[0]
|
|
79
|
+
if stem.upper() in _WINDOWS_RESERVED_NAMES:
|
|
80
|
+
sanitized = f"_{sanitized}"
|
|
81
|
+
|
|
82
|
+
return sanitized
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _build_save_name(
|
|
86
|
+
file_id: str, filename: Optional[str], mime_type: Optional[str]
|
|
87
|
+
) -> str:
|
|
88
|
+
"""Build a collision-free on-disk name, keeping the original stem when given."""
|
|
89
|
+
if filename:
|
|
90
|
+
# The full file_id, not a prefix: a truncated one lets two distinct
|
|
91
|
+
# attachments land on the same path, silently overwriting the first.
|
|
92
|
+
safe_filename = Path(sanitize_attachment_filename(filename))
|
|
93
|
+
tail = f"_{file_id}{safe_filename.suffix}"
|
|
94
|
+
if len(tail.encode()) >= _MAX_FILE_NAME_BYTES:
|
|
95
|
+
tail = f"_{file_id}"
|
|
96
|
+
budget = _MAX_FILE_NAME_BYTES - len(tail.encode())
|
|
97
|
+
# Drop any character split by the byte cut.
|
|
98
|
+
stem = safe_filename.stem.encode()[:budget].decode(errors="ignore")
|
|
99
|
+
return f"{stem}{tail}"
|
|
100
|
+
return f"{file_id}{_MIME_TO_EXTENSION.get(mime_type or '', '')}"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class SavedAttachment(NamedTuple):
|
|
104
|
+
"""Result of saving an attachment: provides both the UUID and the absolute file path."""
|
|
105
|
+
|
|
106
|
+
file_id: str
|
|
107
|
+
path: str
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class AttachmentStorage:
|
|
111
|
+
"""Manages temporary storage of email attachments."""
|
|
112
|
+
|
|
113
|
+
def __init__(self, expiration_seconds: int = DEFAULT_EXPIRATION_SECONDS):
|
|
114
|
+
self.expiration_seconds = expiration_seconds
|
|
115
|
+
self._metadata: Dict[str, Dict] = {}
|
|
116
|
+
|
|
117
|
+
def save_attachment(
|
|
118
|
+
self,
|
|
119
|
+
base64_data: str,
|
|
120
|
+
filename: Optional[str] = None,
|
|
121
|
+
mime_type: Optional[str] = None,
|
|
122
|
+
) -> SavedAttachment:
|
|
123
|
+
"""
|
|
124
|
+
Save an attachment to local disk.
|
|
125
|
+
|
|
126
|
+
Args:
|
|
127
|
+
base64_data: Base64-encoded attachment data
|
|
128
|
+
filename: Original filename (optional)
|
|
129
|
+
mime_type: MIME type (optional)
|
|
130
|
+
|
|
131
|
+
Returns:
|
|
132
|
+
SavedAttachment with file_id (UUID) and path (absolute file path)
|
|
133
|
+
"""
|
|
134
|
+
# Decode base64 data
|
|
135
|
+
try:
|
|
136
|
+
file_bytes = base64.urlsafe_b64decode(base64_data)
|
|
137
|
+
except Exception as e:
|
|
138
|
+
logger.error(f"Failed to decode base64 attachment data: {e}")
|
|
139
|
+
raise ValueError(f"Invalid base64 data: {e}")
|
|
140
|
+
|
|
141
|
+
return self.save_attachment_bytes(file_bytes, filename, mime_type)
|
|
142
|
+
|
|
143
|
+
def save_attachment_bytes(
|
|
144
|
+
self,
|
|
145
|
+
file_bytes: bytes,
|
|
146
|
+
filename: Optional[str] = None,
|
|
147
|
+
mime_type: Optional[str] = None,
|
|
148
|
+
) -> SavedAttachment:
|
|
149
|
+
"""Save an already-decoded attachment without a base64 round trip."""
|
|
150
|
+
_ensure_storage_dir()
|
|
151
|
+
|
|
152
|
+
file_id = str(uuid.uuid4())
|
|
153
|
+
save_name = _build_save_name(file_id, filename, mime_type)
|
|
154
|
+
|
|
155
|
+
# Save file with restrictive permissions (sensitive email/drive content)
|
|
156
|
+
file_path = STORAGE_DIR / save_name
|
|
157
|
+
try:
|
|
158
|
+
fd = os.open(
|
|
159
|
+
file_path,
|
|
160
|
+
os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_BINARY", 0),
|
|
161
|
+
0o600,
|
|
162
|
+
)
|
|
163
|
+
try:
|
|
164
|
+
total_written = 0
|
|
165
|
+
data_len = len(file_bytes)
|
|
166
|
+
data_view = memoryview(file_bytes)
|
|
167
|
+
while total_written < data_len:
|
|
168
|
+
written = os.write(fd, data_view[total_written:])
|
|
169
|
+
if written == 0:
|
|
170
|
+
raise OSError(
|
|
171
|
+
"os.write returned 0 bytes; could not write attachment data"
|
|
172
|
+
)
|
|
173
|
+
total_written += written
|
|
174
|
+
finally:
|
|
175
|
+
os.close(fd)
|
|
176
|
+
logger.info(
|
|
177
|
+
f"Saved attachment file_id={file_id} filename={filename or save_name} "
|
|
178
|
+
f"({len(file_bytes)} bytes) to {file_path}"
|
|
179
|
+
)
|
|
180
|
+
except Exception as e:
|
|
181
|
+
logger.error(
|
|
182
|
+
f"Failed to save attachment file_id={file_id} "
|
|
183
|
+
f"filename={filename or save_name} to {file_path}: {e}"
|
|
184
|
+
)
|
|
185
|
+
raise
|
|
186
|
+
|
|
187
|
+
return self._record(
|
|
188
|
+
file_id, file_path, save_name, filename, mime_type, len(file_bytes)
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
def save_attachment_from_path(
|
|
192
|
+
self,
|
|
193
|
+
src_path: str,
|
|
194
|
+
filename: Optional[str] = None,
|
|
195
|
+
mime_type: Optional[str] = None,
|
|
196
|
+
) -> SavedAttachment:
|
|
197
|
+
"""
|
|
198
|
+
Adopt an already-downloaded file without loading it into memory.
|
|
199
|
+
|
|
200
|
+
The counterpart to save_attachment() for payloads that were streamed
|
|
201
|
+
straight to disk. Nothing here is proportional to the file size, so a
|
|
202
|
+
multi-gigabyte Drive download costs no RAM (see #994).
|
|
203
|
+
|
|
204
|
+
Args:
|
|
205
|
+
src_path: Path to the downloaded file. Consumed - it is moved into
|
|
206
|
+
storage, so the caller must not reuse it afterwards.
|
|
207
|
+
filename: Original filename (optional)
|
|
208
|
+
mime_type: MIME type (optional)
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
SavedAttachment with file_id (UUID) and path (absolute file path)
|
|
212
|
+
"""
|
|
213
|
+
_ensure_storage_dir()
|
|
214
|
+
|
|
215
|
+
file_id = str(uuid.uuid4())
|
|
216
|
+
save_name = _build_save_name(file_id, filename, mime_type)
|
|
217
|
+
file_path = STORAGE_DIR / save_name
|
|
218
|
+
|
|
219
|
+
try:
|
|
220
|
+
# Publish with a fresh mtime so a concurrent sweep cannot expire it.
|
|
221
|
+
os.utime(src_path, None)
|
|
222
|
+
# shutil.move degrades to a streamed copy across filesystems, so it
|
|
223
|
+
# stays memory-safe when the temp dir is on another mount.
|
|
224
|
+
shutil.move(str(src_path), str(file_path))
|
|
225
|
+
os.chmod(file_path, 0o600)
|
|
226
|
+
size = file_path.stat().st_size
|
|
227
|
+
logger.info(
|
|
228
|
+
f"Saved attachment file_id={file_id} filename={filename or save_name} "
|
|
229
|
+
f"({size} bytes) to {file_path}"
|
|
230
|
+
)
|
|
231
|
+
return self._record(
|
|
232
|
+
file_id, file_path, save_name, filename, mime_type, size
|
|
233
|
+
)
|
|
234
|
+
except Exception as e:
|
|
235
|
+
# The move can land before a later finalization step fails, leaving a file in
|
|
236
|
+
# storage that no metadata entry will ever expire. Drop it rather
|
|
237
|
+
# than orphan it, but never let cleanup mask the original failure.
|
|
238
|
+
try:
|
|
239
|
+
file_path.unlink(missing_ok=True)
|
|
240
|
+
except OSError as cleanup_error:
|
|
241
|
+
logger.warning(
|
|
242
|
+
f"Failed to remove partially saved attachment {file_path}: "
|
|
243
|
+
f"{cleanup_error}"
|
|
244
|
+
)
|
|
245
|
+
logger.error(
|
|
246
|
+
f"Failed to save attachment file_id={file_id} "
|
|
247
|
+
f"filename={filename or save_name} to {file_path}: {e}"
|
|
248
|
+
)
|
|
249
|
+
raise
|
|
250
|
+
|
|
251
|
+
def _record(
|
|
252
|
+
self,
|
|
253
|
+
file_id: str,
|
|
254
|
+
file_path: Path,
|
|
255
|
+
save_name: str,
|
|
256
|
+
filename: Optional[str],
|
|
257
|
+
mime_type: Optional[str],
|
|
258
|
+
size: int,
|
|
259
|
+
) -> SavedAttachment:
|
|
260
|
+
"""Record a stored file's metadata and return its handle."""
|
|
261
|
+
self._metadata[file_id] = {
|
|
262
|
+
"file_path": str(file_path),
|
|
263
|
+
"filename": save_name,
|
|
264
|
+
"original_filename": filename,
|
|
265
|
+
"mime_type": mime_type or "application/octet-stream",
|
|
266
|
+
"size": size,
|
|
267
|
+
"created_at": datetime.now(),
|
|
268
|
+
"expires_at": datetime.now() + timedelta(seconds=self.expiration_seconds),
|
|
269
|
+
}
|
|
270
|
+
return SavedAttachment(file_id=file_id, path=str(file_path))
|
|
271
|
+
|
|
272
|
+
def get_attachment_path(self, file_id: str) -> Optional[Path]:
|
|
273
|
+
"""
|
|
274
|
+
Get the file path for an attachment ID.
|
|
275
|
+
|
|
276
|
+
Args:
|
|
277
|
+
file_id: Unique file ID
|
|
278
|
+
|
|
279
|
+
Returns:
|
|
280
|
+
Path object if file exists and not expired, None otherwise
|
|
281
|
+
"""
|
|
282
|
+
if file_id not in self._metadata:
|
|
283
|
+
logger.warning(f"Attachment {file_id} not found in metadata")
|
|
284
|
+
return None
|
|
285
|
+
|
|
286
|
+
metadata = self._metadata[file_id]
|
|
287
|
+
file_path = Path(metadata["file_path"])
|
|
288
|
+
|
|
289
|
+
# Check if expired
|
|
290
|
+
if datetime.now() > metadata["expires_at"]:
|
|
291
|
+
logger.info(f"Attachment {file_id} has expired, cleaning up")
|
|
292
|
+
self._cleanup_file(file_id)
|
|
293
|
+
return None
|
|
294
|
+
|
|
295
|
+
# Check if file exists
|
|
296
|
+
if not file_path.exists():
|
|
297
|
+
logger.warning(f"Attachment file {file_path} does not exist")
|
|
298
|
+
del self._metadata[file_id]
|
|
299
|
+
return None
|
|
300
|
+
|
|
301
|
+
return file_path
|
|
302
|
+
|
|
303
|
+
def get_attachment_metadata(self, file_id: str) -> Optional[Dict]:
|
|
304
|
+
"""
|
|
305
|
+
Get metadata for an attachment.
|
|
306
|
+
|
|
307
|
+
Args:
|
|
308
|
+
file_id: Unique file ID
|
|
309
|
+
|
|
310
|
+
Returns:
|
|
311
|
+
Metadata dict if exists and not expired, None otherwise
|
|
312
|
+
"""
|
|
313
|
+
if file_id not in self._metadata:
|
|
314
|
+
return None
|
|
315
|
+
|
|
316
|
+
metadata = self._metadata[file_id].copy()
|
|
317
|
+
|
|
318
|
+
# Check if expired
|
|
319
|
+
if datetime.now() > metadata["expires_at"]:
|
|
320
|
+
self._cleanup_file(file_id)
|
|
321
|
+
return None
|
|
322
|
+
|
|
323
|
+
return metadata
|
|
324
|
+
|
|
325
|
+
def _cleanup_file(self, file_id: str) -> None:
|
|
326
|
+
"""Remove file and metadata."""
|
|
327
|
+
if file_id in self._metadata:
|
|
328
|
+
file_path = Path(self._metadata[file_id]["file_path"])
|
|
329
|
+
try:
|
|
330
|
+
if file_path.exists():
|
|
331
|
+
file_path.unlink()
|
|
332
|
+
logger.debug(f"Deleted expired attachment file: {file_path}")
|
|
333
|
+
except Exception as e:
|
|
334
|
+
logger.warning(f"Failed to delete attachment file {file_path}: {e}")
|
|
335
|
+
del self._metadata[file_id]
|
|
336
|
+
|
|
337
|
+
def sweep_expired(self) -> int:
|
|
338
|
+
"""Remove files older than the expiration window based on mtime."""
|
|
339
|
+
cutoff = time.time() - self.expiration_seconds
|
|
340
|
+
swept: set[str] = set()
|
|
341
|
+
|
|
342
|
+
try:
|
|
343
|
+
if not STORAGE_DIR.exists():
|
|
344
|
+
return 0
|
|
345
|
+
|
|
346
|
+
for path in STORAGE_DIR.iterdir():
|
|
347
|
+
try:
|
|
348
|
+
if not path.is_file():
|
|
349
|
+
continue
|
|
350
|
+
if path.stat().st_mtime >= cutoff:
|
|
351
|
+
continue
|
|
352
|
+
path.unlink()
|
|
353
|
+
except OSError as e:
|
|
354
|
+
logger.warning(f"Failed to remove expired attachment {path}: {e}")
|
|
355
|
+
continue
|
|
356
|
+
swept.add(str(path))
|
|
357
|
+
except OSError as e:
|
|
358
|
+
logger.warning(f"Failed to scan attachment storage {STORAGE_DIR}: {e}")
|
|
359
|
+
|
|
360
|
+
if swept:
|
|
361
|
+
stale_ids = [
|
|
362
|
+
file_id
|
|
363
|
+
for file_id, metadata in self._metadata.items()
|
|
364
|
+
if metadata["file_path"] in swept
|
|
365
|
+
]
|
|
366
|
+
for file_id in stale_ids:
|
|
367
|
+
del self._metadata[file_id]
|
|
368
|
+
logger.info(f"Swept {len(swept)} expired attachment(s) from {STORAGE_DIR}")
|
|
369
|
+
|
|
370
|
+
return len(swept)
|
|
371
|
+
|
|
372
|
+
def cleanup_expired(self) -> int:
|
|
373
|
+
"""
|
|
374
|
+
Clean up expired attachments.
|
|
375
|
+
|
|
376
|
+
Returns:
|
|
377
|
+
Number of files cleaned up
|
|
378
|
+
"""
|
|
379
|
+
now = datetime.now()
|
|
380
|
+
expired_ids = [
|
|
381
|
+
file_id
|
|
382
|
+
for file_id, metadata in self._metadata.items()
|
|
383
|
+
if now > metadata["expires_at"]
|
|
384
|
+
]
|
|
385
|
+
|
|
386
|
+
for file_id in expired_ids:
|
|
387
|
+
self._cleanup_file(file_id)
|
|
388
|
+
|
|
389
|
+
return len(expired_ids) + self.sweep_expired()
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
# Global instance
|
|
393
|
+
_attachment_storage: Optional[AttachmentStorage] = None
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def get_attachment_storage() -> AttachmentStorage:
|
|
397
|
+
"""Get the global attachment storage instance.
|
|
398
|
+
|
|
399
|
+
Returns the GCS-backed storage instead of local disk when
|
|
400
|
+
``WORKSPACE_MCP_FILES_GCS_BUCKET`` is set on an HTTP transport.
|
|
401
|
+
"""
|
|
402
|
+
# core.gcs_attachment_storage imports this module, so import it lazily.
|
|
403
|
+
from core.gcs_attachment_storage import (
|
|
404
|
+
gcs_files_enabled,
|
|
405
|
+
get_gcs_attachment_storage,
|
|
406
|
+
)
|
|
407
|
+
|
|
408
|
+
if gcs_files_enabled():
|
|
409
|
+
return get_gcs_attachment_storage()
|
|
410
|
+
|
|
411
|
+
global _attachment_storage
|
|
412
|
+
if _attachment_storage is None:
|
|
413
|
+
_attachment_storage = AttachmentStorage()
|
|
414
|
+
_attachment_storage.sweep_expired()
|
|
415
|
+
return _attachment_storage
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def _trusted_attachment_bases() -> set[tuple[str, str, str]]:
|
|
419
|
+
"""Return the (scheme, host, path prefix) bases of this server's attachment links."""
|
|
420
|
+
bases: set[tuple[str, str, str]] = set()
|
|
421
|
+
for base in (
|
|
422
|
+
config.WORKSPACE_EXTERNAL_URL,
|
|
423
|
+
f"{config.WORKSPACE_MCP_BASE_URI}:{config.WORKSPACE_MCP_PORT}",
|
|
424
|
+
):
|
|
425
|
+
if not base:
|
|
426
|
+
continue
|
|
427
|
+
parsed = urlparse(base)
|
|
428
|
+
if parsed.scheme and parsed.netloc:
|
|
429
|
+
bases.add(
|
|
430
|
+
(parsed.scheme.lower(), parsed.netloc.lower(), parsed.path.rstrip("/"))
|
|
431
|
+
)
|
|
432
|
+
return bases
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def resolve_local_attachment(url: str) -> Optional[tuple[Path, Dict]]:
|
|
436
|
+
"""Return (path, metadata) when ``url`` is this server's own /attachments/{id} link."""
|
|
437
|
+
parsed = urlparse(url)
|
|
438
|
+
prefix, separator, file_id = parsed.path.rstrip("/").rpartition("/attachments/")
|
|
439
|
+
if not separator or "/" in file_id:
|
|
440
|
+
return None
|
|
441
|
+
base = (parsed.scheme.lower(), parsed.netloc.lower(), prefix)
|
|
442
|
+
if (parsed.netloc or prefix) and base not in _trusted_attachment_bases():
|
|
443
|
+
return None
|
|
444
|
+
|
|
445
|
+
storage = get_attachment_storage()
|
|
446
|
+
metadata = storage.get_attachment_metadata(file_id)
|
|
447
|
+
if metadata is None:
|
|
448
|
+
return None
|
|
449
|
+
file_path = storage.get_attachment_path(file_id)
|
|
450
|
+
if file_path is None:
|
|
451
|
+
return None
|
|
452
|
+
return Path(file_path), metadata
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def get_attachment_url(file_id: str) -> str:
|
|
456
|
+
"""
|
|
457
|
+
Generate a URL for accessing an attachment.
|
|
458
|
+
|
|
459
|
+
Args:
|
|
460
|
+
file_id: Unique file ID
|
|
461
|
+
|
|
462
|
+
Returns:
|
|
463
|
+
Full URL to access the attachment
|
|
464
|
+
"""
|
|
465
|
+
from core.gcs_attachment_storage import (
|
|
466
|
+
gcs_files_enabled,
|
|
467
|
+
get_gcs_attachment_storage,
|
|
468
|
+
)
|
|
469
|
+
|
|
470
|
+
if gcs_files_enabled():
|
|
471
|
+
return get_gcs_attachment_storage().get_signed_url(file_id)
|
|
472
|
+
|
|
473
|
+
from core.config import WORKSPACE_MCP_PORT, WORKSPACE_MCP_BASE_URI
|
|
474
|
+
|
|
475
|
+
# In stdio mode the attachment route is served by the lazily-started callback
|
|
476
|
+
# server; bring it up now so the URL we hand out is actually reachable. The
|
|
477
|
+
# import is local to avoid pulling the FastAPI/uvicorn auth stack into this
|
|
478
|
+
# lightweight, widely-imported module (matches every other call site, #832).
|
|
479
|
+
from auth.oauth_callback_server import ensure_stdio_oauth_callback_available
|
|
480
|
+
|
|
481
|
+
success, error_msg = ensure_stdio_oauth_callback_available()
|
|
482
|
+
if not success:
|
|
483
|
+
logger.warning(
|
|
484
|
+
"Failed to start stdio attachment server; attachment URL may be "
|
|
485
|
+
"unreachable: %s",
|
|
486
|
+
error_msg,
|
|
487
|
+
)
|
|
488
|
+
|
|
489
|
+
# Use external URL if set (for reverse proxy scenarios)
|
|
490
|
+
external_url = os.getenv("WORKSPACE_EXTERNAL_URL")
|
|
491
|
+
if external_url:
|
|
492
|
+
base_url = external_url.rstrip("/")
|
|
493
|
+
else:
|
|
494
|
+
base_url = f"{WORKSPACE_MCP_BASE_URI}:{WORKSPACE_MCP_PORT}"
|
|
495
|
+
|
|
496
|
+
return f"{base_url}/attachments/{file_id}"
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Middleware that lets callers use camelCase argument names on snake_case tools.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import re
|
|
7
|
+
from typing import Any, Dict, Optional
|
|
8
|
+
|
|
9
|
+
from fastmcp.server.middleware import CallNext, Middleware, MiddlewareContext
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
# Split on lowercase/digit -> uppercase ("timeMin") and on the tail of an
|
|
14
|
+
# acronym run followed by a new word ("fooURLValue" -> "foo_URL_Value").
|
|
15
|
+
_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def to_snake_case(name: str) -> str:
|
|
19
|
+
"""Convert a camelCase argument name to snake_case (``timeMin`` -> ``time_min``)."""
|
|
20
|
+
return _CAMEL_BOUNDARY.sub("_", name).lower()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class CamelCaseArgumentsMiddleware(Middleware):
|
|
24
|
+
"""Translate camelCase tool arguments to their snake_case equivalents.
|
|
25
|
+
|
|
26
|
+
Every tool in this server declares snake_case parameters with
|
|
27
|
+
``additionalProperties: false``, so callers that mirror the Google API
|
|
28
|
+
field names (``calendarId``, ``timeMin``, ``maxResults``, ...) fail schema
|
|
29
|
+
validation before the request ever reaches Google. This middleware renames
|
|
30
|
+
an argument key when all of the following hold:
|
|
31
|
+
|
|
32
|
+
* the key is not itself a declared parameter of the tool,
|
|
33
|
+
* its snake_case conversion is a declared parameter, and
|
|
34
|
+
* the caller did not also pass the snake_case key explicitly.
|
|
35
|
+
|
|
36
|
+
Everything else passes through untouched, so existing snake_case callers
|
|
37
|
+
(and genuinely invalid arguments) behave exactly as before.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
async def on_call_tool(self, context: MiddlewareContext, call_next: CallNext):
|
|
41
|
+
arguments = context.message.arguments
|
|
42
|
+
if arguments:
|
|
43
|
+
normalized = await self._normalize_arguments(context, arguments)
|
|
44
|
+
if normalized is not None:
|
|
45
|
+
context = context.copy(
|
|
46
|
+
message=context.message.model_copy(update={"arguments": normalized})
|
|
47
|
+
)
|
|
48
|
+
return await call_next(context)
|
|
49
|
+
|
|
50
|
+
async def _normalize_arguments(
|
|
51
|
+
self, context: MiddlewareContext, arguments: Dict[str, Any]
|
|
52
|
+
) -> Optional[Dict[str, Any]]:
|
|
53
|
+
"""Return arguments with camelCase keys renamed, or None if unchanged."""
|
|
54
|
+
if not context.fastmcp_context:
|
|
55
|
+
return None
|
|
56
|
+
|
|
57
|
+
tool = await context.fastmcp_context.fastmcp.get_tool(context.message.name)
|
|
58
|
+
if tool is None:
|
|
59
|
+
# Unknown tool — let the normal "tool not found" handling run.
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
properties = (tool.parameters or {}).get("properties")
|
|
63
|
+
if not properties:
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
renames = {}
|
|
67
|
+
for key in arguments:
|
|
68
|
+
if key in properties:
|
|
69
|
+
continue
|
|
70
|
+
snake_key = to_snake_case(key)
|
|
71
|
+
if (
|
|
72
|
+
snake_key != key
|
|
73
|
+
and snake_key in properties
|
|
74
|
+
and snake_key not in arguments
|
|
75
|
+
):
|
|
76
|
+
renames[key] = snake_key
|
|
77
|
+
|
|
78
|
+
# If two distinct keys normalize to the same parameter (e.g. "iCalUid"
|
|
79
|
+
# and "iCalUID"), the request is ambiguous — leave those keys untouched
|
|
80
|
+
# so schema validation rejects them instead of silently picking one.
|
|
81
|
+
target_counts: Dict[str, int] = {}
|
|
82
|
+
for snake_key in renames.values():
|
|
83
|
+
target_counts[snake_key] = target_counts.get(snake_key, 0) + 1
|
|
84
|
+
renames = {
|
|
85
|
+
key: snake_key
|
|
86
|
+
for key, snake_key in renames.items()
|
|
87
|
+
if target_counts[snake_key] == 1
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if not renames:
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
logger.debug(
|
|
94
|
+
"[CamelCaseArgumentsMiddleware] Renaming arguments for tool '%s': %s",
|
|
95
|
+
context.message.name,
|
|
96
|
+
renames,
|
|
97
|
+
)
|
|
98
|
+
return {renames.get(key, key): value for key, value in arguments.items()}
|