@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
@@ -0,0 +1,466 @@
1
+ """
2
+ Transport-aware OAuth callback handling.
3
+
4
+ In streamable-http mode: Uses the existing FastAPI server
5
+ In stdio mode: Starts a minimal HTTP server just for OAuth callbacks
6
+ """
7
+
8
+ import asyncio
9
+ import errno
10
+ import logging
11
+ import os
12
+ import threading
13
+ import time
14
+ import socket
15
+ import uvicorn
16
+
17
+ from fastapi import FastAPI, Request
18
+ from fastapi.responses import FileResponse, JSONResponse
19
+ from typing import Optional
20
+ from urllib.parse import urlparse
21
+ from urllib.error import HTTPError, URLError
22
+ from urllib.request import urlopen
23
+
24
+ from auth.scopes import SCOPES, get_current_scopes # noqa
25
+ from auth.oauth_responses import (
26
+ create_error_response,
27
+ create_success_response,
28
+ create_server_error_response,
29
+ )
30
+ from auth.google_auth import handle_auth_callback, check_client_secrets
31
+ from auth.oauth_config import (
32
+ get_oauth_redirect_uri,
33
+ get_oauth_config,
34
+ get_transport_mode,
35
+ )
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+
40
+ class MinimalOAuthServer:
41
+ """
42
+ Minimal HTTP server for OAuth callbacks in stdio mode.
43
+ Only starts when needed and uses the same port (8000) as streamable-http mode.
44
+ """
45
+
46
+ def __init__(self, port: int = 8000, base_uri: str = "http://localhost"):
47
+ self.port = port
48
+ self.base_uri = base_uri
49
+ self.app = FastAPI()
50
+ self.server = None
51
+ self.server_thread = None
52
+ self.is_running = False
53
+ self._reusing_external_listener = False
54
+
55
+ # Setup the callback route
56
+ self._setup_callback_route()
57
+ # Setup attachment serving route
58
+ self._setup_attachment_route()
59
+
60
+ def _setup_callback_route(self):
61
+ """Setup the OAuth callback route."""
62
+
63
+ @self.app.get("/oauth2callback")
64
+ async def oauth_callback(request: Request):
65
+ """Handle OAuth callback - same logic as in core/server.py"""
66
+ code = request.query_params.get("code")
67
+ error = request.query_params.get("error")
68
+
69
+ if error:
70
+ error_message = (
71
+ f"Authentication failed: Google returned an error: {error}."
72
+ )
73
+ logger.error(error_message)
74
+ return create_error_response(error_message)
75
+
76
+ if not code:
77
+ error_message = (
78
+ "Authentication failed: No authorization code received from Google."
79
+ )
80
+ logger.error(error_message)
81
+ return create_error_response(error_message)
82
+
83
+ try:
84
+ # Check if we have credentials available (environment variables or file)
85
+ error_message = check_client_secrets()
86
+ if error_message:
87
+ return create_server_error_response(error_message)
88
+
89
+ logger.info(
90
+ "OAuth callback: Received authorization code. Attempting to exchange for tokens."
91
+ )
92
+
93
+ # Session ID tracking removed - not needed
94
+
95
+ # Exchange code for credentials
96
+ redirect_uri = get_oauth_redirect_uri()
97
+ verified_user_id, credentials = await handle_auth_callback(
98
+ scopes=get_current_scopes(),
99
+ authorization_response=str(request.url),
100
+ redirect_uri=redirect_uri,
101
+ session_id=None,
102
+ allow_missing_state_fallback=os.getenv("MCP_SINGLE_USER_MODE")
103
+ == "1",
104
+ )
105
+
106
+ logger.info(
107
+ f"OAuth callback: Successfully authenticated user: {verified_user_id}."
108
+ )
109
+
110
+ # Return success page using shared template
111
+ return create_success_response(verified_user_id)
112
+
113
+ except Exception as e:
114
+ error_message_detail = f"Error processing OAuth callback: {str(e)}"
115
+ logger.error(error_message_detail, exc_info=True)
116
+ return create_server_error_response(str(e))
117
+
118
+ def _setup_attachment_route(self):
119
+ """Setup the attachment serving route."""
120
+ from core.attachment_storage import get_attachment_storage
121
+
122
+ @self.app.get("/attachments/{file_id}")
123
+ async def serve_attachment(file_id: str, request: Request):
124
+ """Serve a stored attachment file."""
125
+ storage = get_attachment_storage()
126
+ metadata = storage.get_attachment_metadata(file_id)
127
+
128
+ if not metadata:
129
+ return JSONResponse(
130
+ {"error": "Attachment not found or expired"}, status_code=404
131
+ )
132
+
133
+ file_path = storage.get_attachment_path(file_id)
134
+ if not file_path:
135
+ return JSONResponse(
136
+ {"error": "Attachment file not found"}, status_code=404
137
+ )
138
+
139
+ return FileResponse(
140
+ path=str(file_path),
141
+ filename=metadata["filename"],
142
+ media_type=metadata["mime_type"],
143
+ )
144
+
145
+ def is_actually_running(self) -> bool:
146
+ """
147
+ Check whether *this* server instance owns the callback port.
148
+
149
+ Returns False immediately if we have never called ``start()`` — a foreign
150
+ process listening on the same port must not be mistaken for our OAuth server.
151
+ Only after we have successfully started do we probe the port to confirm the
152
+ server thread is still alive and responding.
153
+ """
154
+ # We never started — don't probe the port at all. A foreign listener (e.g.
155
+ # another local web server) would make a raw TCP connect_ex succeed and cause
156
+ # is_actually_running() to return True, silently skipping OAuth setup.
157
+ if not self.is_running and self.server_thread is None:
158
+ return False
159
+
160
+ if self.server_thread and not self.server_thread.is_alive():
161
+ return False
162
+ try:
163
+ parsed_uri = urlparse(self.base_uri)
164
+ hostname = parsed_uri.hostname or "localhost"
165
+ except Exception:
166
+ hostname = "localhost"
167
+ try:
168
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
169
+ s.settimeout(1.0)
170
+ if s.connect_ex((hostname, self.port)) == 0:
171
+ return True
172
+ except Exception:
173
+ return False
174
+
175
+ try:
176
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
177
+ s.bind((hostname, self.port))
178
+ except OSError as exc:
179
+ if exc.errno == errno.EADDRINUSE:
180
+ return True
181
+ return False
182
+ except Exception:
183
+ return False
184
+
185
+ return False
186
+
187
+ def matches_endpoint(self, port: int, base_uri: str) -> bool:
188
+ """Return True when this server instance matches the requested callback endpoint."""
189
+ if self.port != port:
190
+ return False
191
+ self_parsed = urlparse(self.base_uri)
192
+ other_parsed = urlparse(base_uri)
193
+ if self_parsed.scheme.lower() != other_parsed.scheme.lower():
194
+ return False
195
+ if (self_parsed.hostname or "").lower() != (
196
+ other_parsed.hostname or ""
197
+ ).lower():
198
+ return False
199
+ default_port = 443 if self_parsed.scheme.lower() == "https" else 80
200
+ self_port = self_parsed.port or default_port
201
+ other_port = other_parsed.port or default_port
202
+ if self_port != other_port:
203
+ return False
204
+ self_path = self_parsed.path.rstrip("/") or ""
205
+ other_path = other_parsed.path.rstrip("/") or ""
206
+ return self_path == other_path
207
+
208
+ def _callback_endpoint_looks_like_workspace(self, hostname: str) -> bool:
209
+ """
210
+ Probe an occupied callback port for this app's OAuth callback handler.
211
+
212
+ This is intentionally only used after bind returns EADDRINUSE in stdio
213
+ mode. A no-code request to our handler returns the shared
214
+ "Authentication Error" page with HTTP 400, which is enough to distinguish
215
+ the boot-time workspace callback listener from a random local process.
216
+ """
217
+ try:
218
+ parsed_uri = urlparse(self.base_uri)
219
+ scheme = parsed_uri.scheme or "http"
220
+ if scheme not in {"http", "https"}:
221
+ return False
222
+ probe_host = hostname
223
+ if probe_host in {"0.0.0.0", "::"}:
224
+ probe_host = "127.0.0.1"
225
+ if ":" in probe_host and not probe_host.startswith("["):
226
+ probe_host = f"[{probe_host}]"
227
+ base_path = parsed_uri.path.rstrip("/")
228
+ probe_url = f"{scheme}://{probe_host}:{self.port}{base_path}/oauth2callback"
229
+
230
+ try:
231
+ with urlopen(probe_url, timeout=1.0) as response:
232
+ status_code = response.status
233
+ body = response.read(4096).decode("utf-8", errors="replace")
234
+ except HTTPError as exc:
235
+ status_code = exc.code
236
+ body = exc.read(4096).decode("utf-8", errors="replace")
237
+
238
+ return status_code in {200, 400} and (
239
+ "Authentication Error" in body or "Authentication Successful" in body
240
+ )
241
+ except (OSError, URLError, ValueError):
242
+ return False
243
+
244
+ def start(self) -> tuple[bool, str]:
245
+ """
246
+ Start the minimal OAuth server.
247
+
248
+ Returns:
249
+ Tuple of (success: bool, error_message: str)
250
+ """
251
+ if self.is_running:
252
+ if self.is_actually_running():
253
+ logger.info("Minimal OAuth server is already running")
254
+ return True, ""
255
+ else:
256
+ logger.warning(
257
+ "Minimal OAuth server was marked running but port is not responding. Restarting."
258
+ )
259
+ self.stop()
260
+ self.server = None
261
+ self.server_thread = None
262
+
263
+ # Check if port is available
264
+ # Extract hostname from base_uri (e.g., "http://localhost" -> "localhost")
265
+ try:
266
+ parsed_uri = urlparse(self.base_uri)
267
+ hostname = parsed_uri.hostname or "localhost"
268
+ except Exception:
269
+ hostname = "localhost"
270
+
271
+ try:
272
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
273
+ s.bind((hostname, self.port))
274
+ except OSError as exc:
275
+ if (
276
+ exc.errno == errno.EADDRINUSE
277
+ and self._callback_endpoint_looks_like_workspace(hostname)
278
+ ):
279
+ logger.info(
280
+ "OAuth callback server already available on %s:%s; reusing existing listener",
281
+ hostname,
282
+ self.port,
283
+ )
284
+ self.is_running = True
285
+ self._reusing_external_listener = True
286
+ return True, ""
287
+ error_msg = f"Port {self.port} is already in use on {hostname}. Cannot start minimal OAuth server."
288
+ logger.error(error_msg)
289
+ return False, error_msg
290
+
291
+ self._reusing_external_listener = False
292
+
293
+ def run_server():
294
+ """Run the server in a separate thread."""
295
+ try:
296
+ config = uvicorn.Config(
297
+ self.app,
298
+ host=hostname,
299
+ port=self.port,
300
+ log_level="warning",
301
+ access_log=False,
302
+ # Match FastMCP's own uvicorn config: uvicorn's "auto"
303
+ # default resolves to the deprecated legacy-websockets
304
+ # implementation whenever `websockets` is installed.
305
+ ws="websockets-sansio",
306
+ )
307
+ self.server = uvicorn.Server(config)
308
+ asyncio.run(self.server.serve())
309
+
310
+ except Exception as e:
311
+ logger.error(f"Minimal OAuth server error: {e}", exc_info=True)
312
+ self.is_running = False
313
+
314
+ # Start server in background thread
315
+ self.server_thread = threading.Thread(target=run_server, daemon=True)
316
+ self.server_thread.start()
317
+
318
+ # Wait for server to start
319
+ max_wait = 3.0
320
+ start_time = time.time()
321
+ while time.time() - start_time < max_wait:
322
+ try:
323
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
324
+ result = s.connect_ex((hostname, self.port))
325
+ if result == 0:
326
+ self.is_running = True
327
+ logger.info(
328
+ f"Minimal OAuth server started on {hostname}:{self.port}"
329
+ )
330
+ return True, ""
331
+ except Exception:
332
+ pass
333
+ time.sleep(0.1)
334
+
335
+ error_msg = f"Failed to start minimal OAuth server on {hostname}:{self.port} - server did not respond within {max_wait}s"
336
+ logger.error(error_msg)
337
+ return False, error_msg
338
+
339
+ def stop(self):
340
+ """Stop the minimal OAuth server."""
341
+ if not self.is_running:
342
+ return
343
+
344
+ if self._reusing_external_listener:
345
+ self.is_running = False
346
+ self._reusing_external_listener = False
347
+ logger.info("Minimal OAuth server external listener reuse released")
348
+ return
349
+
350
+ try:
351
+ if self.server:
352
+ if hasattr(self.server, "should_exit"):
353
+ self.server.should_exit = True
354
+
355
+ if self.server_thread and self.server_thread.is_alive():
356
+ self.server_thread.join(timeout=3.0)
357
+
358
+ self.is_running = False
359
+ self._reusing_external_listener = False
360
+ logger.info("Minimal OAuth server stopped")
361
+
362
+ except Exception as e:
363
+ logger.error(f"Error stopping minimal OAuth server: {e}", exc_info=True)
364
+
365
+
366
+ # Global instance for stdio mode
367
+ _minimal_oauth_server: Optional[MinimalOAuthServer] = None
368
+ _minimal_oauth_server_lock = threading.Lock()
369
+
370
+
371
+ def ensure_oauth_callback_available(
372
+ transport_mode: str = "stdio", port: int = 8000, base_uri: str = "http://localhost"
373
+ ) -> tuple[bool, str]:
374
+ """
375
+ Ensure OAuth callback endpoint is available for the given transport mode.
376
+
377
+ For streamable-http: Assumes the main server is already running
378
+ For stdio: Starts a minimal server if needed
379
+
380
+ Args:
381
+ transport_mode: "stdio" or "streamable-http"
382
+ port: Port number (default 8000)
383
+ base_uri: Base URI (default "http://localhost")
384
+
385
+ Returns:
386
+ Tuple of (success: bool, error_message: str)
387
+ """
388
+ global _minimal_oauth_server
389
+
390
+ if transport_mode == "streamable-http":
391
+ # In streamable-http mode, the main FastAPI server should handle callbacks
392
+ logger.debug(
393
+ "Using existing FastAPI server for OAuth callbacks (streamable-http mode)"
394
+ )
395
+ return True, ""
396
+
397
+ elif transport_mode == "stdio":
398
+ with _minimal_oauth_server_lock:
399
+ # In stdio mode, start or refresh the minimal callback server as needed.
400
+ if _minimal_oauth_server and not _minimal_oauth_server.matches_endpoint(
401
+ port, base_uri
402
+ ):
403
+ logger.info(
404
+ "OAuth callback endpoint changed from %s:%s to %s:%s; recreating minimal OAuth server",
405
+ _minimal_oauth_server.base_uri,
406
+ _minimal_oauth_server.port,
407
+ base_uri,
408
+ port,
409
+ )
410
+ _minimal_oauth_server.stop()
411
+ _minimal_oauth_server = None
412
+
413
+ if _minimal_oauth_server is None:
414
+ logger.info(
415
+ f"Creating minimal OAuth server instance for {base_uri}:{port}"
416
+ )
417
+ _minimal_oauth_server = MinimalOAuthServer(port, base_uri)
418
+
419
+ if not _minimal_oauth_server.is_actually_running():
420
+ logger.info("Starting minimal OAuth server for stdio mode")
421
+ success, error_msg = _minimal_oauth_server.start()
422
+ if success:
423
+ logger.info(
424
+ f"Minimal OAuth server successfully started on {base_uri}:{port}"
425
+ )
426
+ return True, ""
427
+ else:
428
+ logger.error(
429
+ f"Failed to start minimal OAuth server on {base_uri}:{port}: {error_msg}"
430
+ )
431
+ return False, error_msg
432
+ else:
433
+ logger.info("Minimal OAuth server is already running")
434
+ return True, ""
435
+
436
+ else:
437
+ error_msg = f"Unknown transport mode: {transport_mode}"
438
+ logger.error(error_msg)
439
+ return False, error_msg
440
+
441
+
442
+ def ensure_stdio_oauth_callback_available() -> tuple[bool, str]:
443
+ """
444
+ Lazily start the stdio OAuth-callback / attachment listener on demand.
445
+
446
+ Binding the callback port is deferred until it is actually needed — an auth
447
+ flow starting or an attachment URL being handed out — so short-lived stdio
448
+ spawns that do neither never occupy a port in the fallback range (issue #832).
449
+
450
+ No-op (returns success) outside stdio transport, where the main HTTP server
451
+ already serves these routes. Uses the active OAuth config so the listener
452
+ binds the same port the redirect and attachment URLs are composed from.
453
+ """
454
+ if get_transport_mode() != "stdio":
455
+ return True, ""
456
+ config = get_oauth_config()
457
+ return ensure_oauth_callback_available("stdio", config.port, config.base_uri)
458
+
459
+
460
+ def cleanup_oauth_callback_server():
461
+ """Clean up the minimal OAuth server if it was started."""
462
+ global _minimal_oauth_server
463
+ with _minimal_oauth_server_lock:
464
+ if _minimal_oauth_server:
465
+ _minimal_oauth_server.stop()
466
+ _minimal_oauth_server = None