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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -2
  3. package/README.npm.md +28 -0
  4. package/auth/__init__.py +1 -0
  5. package/auth/auth_info_middleware.py +419 -0
  6. package/auth/client_secrets.py +76 -0
  7. package/auth/credential_store.py +598 -0
  8. package/auth/external_oauth_provider.py +369 -0
  9. package/auth/gateway_identity.py +164 -0
  10. package/auth/google_auth.py +1550 -0
  11. package/auth/google_oauth_provider.py +20 -0
  12. package/auth/mcp_session_middleware.py +95 -0
  13. package/auth/oauth21_session_store.py +1332 -0
  14. package/auth/oauth_callback_server.py +466 -0
  15. package/auth/oauth_config.py +693 -0
  16. package/auth/oauth_proxy_config.py +122 -0
  17. package/auth/oauth_responses.py +230 -0
  18. package/auth/oauth_types.py +92 -0
  19. package/auth/permissions.py +330 -0
  20. package/auth/port_resolver.py +153 -0
  21. package/auth/request_identity.py +89 -0
  22. package/auth/scopes.py +369 -0
  23. package/auth/service_decorator.py +1109 -0
  24. package/bin/google-workspace-mcp.cjs +123 -0
  25. package/core/__init__.py +1 -0
  26. package/core/api_enablement.py +108 -0
  27. package/core/attachment_storage.py +496 -0
  28. package/core/camel_case_middleware.py +98 -0
  29. package/core/cli.py +161 -0
  30. package/core/comments.py +609 -0
  31. package/core/config.py +57 -0
  32. package/core/context.py +43 -0
  33. package/core/file_limits.py +632 -0
  34. package/core/gcs_attachment_storage.py +253 -0
  35. package/core/http_utils.py +339 -0
  36. package/core/log_formatter.py +270 -0
  37. package/core/portable_schema_middleware.py +67 -0
  38. package/core/server.py +1192 -0
  39. package/core/startup_ui.py +239 -0
  40. package/core/storage.py +23 -0
  41. package/core/telemetry.py +194 -0
  42. package/core/tool_descriptions.py +19 -0
  43. package/core/tool_registry.py +311 -0
  44. package/core/tool_tier_loader.py +197 -0
  45. package/core/tool_tiers.yaml +179 -0
  46. package/core/toolset_header_middleware.py +67 -0
  47. package/core/utils.py +1537 -0
  48. package/core/valkey_storage.py +271 -0
  49. package/core/warning_filters.py +19 -0
  50. package/fastmcp_server.py +198 -0
  51. package/gappsscript/README.md +512 -0
  52. package/gappsscript/TESTING.md +254 -0
  53. package/gappsscript/__init__.py +0 -0
  54. package/gappsscript/apps_script_tools.py +1940 -0
  55. package/gcalendar/__init__.py +1 -0
  56. package/gcalendar/calendar_helpers.py +1323 -0
  57. package/gcalendar/calendar_tools.py +2252 -0
  58. package/gchat/__init__.py +7 -0
  59. package/gchat/chat_helpers.py +410 -0
  60. package/gchat/chat_tools.py +798 -0
  61. package/gcontacts/__init__.py +1 -0
  62. package/gcontacts/contacts_helpers.py +765 -0
  63. package/gcontacts/contacts_tools.py +1685 -0
  64. package/gdocs/__init__.py +0 -0
  65. package/gdocs/docs_anchors.py +163 -0
  66. package/gdocs/docs_comments.py +89 -0
  67. package/gdocs/docs_helpers.py +2201 -0
  68. package/gdocs/docs_links.py +87 -0
  69. package/gdocs/docs_markdown.py +828 -0
  70. package/gdocs/docs_markdown_writer.py +592 -0
  71. package/gdocs/docs_plain_text.py +463 -0
  72. package/gdocs/docs_structure.py +621 -0
  73. package/gdocs/docs_tables.py +425 -0
  74. package/gdocs/docs_tools.py +3300 -0
  75. package/gdocs/managers/__init__.py +18 -0
  76. package/gdocs/managers/batch_operation_manager.py +1694 -0
  77. package/gdocs/managers/header_footer_manager.py +526 -0
  78. package/gdocs/managers/table_operation_manager.py +488 -0
  79. package/gdocs/managers/validation_manager.py +1504 -0
  80. package/gdocs/operation_schemas.py +594 -0
  81. package/gdrive/__init__.py +0 -0
  82. package/gdrive/drive_helpers.py +1738 -0
  83. package/gdrive/drive_tools.py +3085 -0
  84. package/gforms/__init__.py +3 -0
  85. package/gforms/forms_tools.py +575 -0
  86. package/gmail/__init__.py +1 -0
  87. package/gmail/gmail_helpers.py +2107 -0
  88. package/gmail/gmail_tools.py +4895 -0
  89. package/gmail/gmail_web_mime.py +441 -0
  90. package/gsearch/__init__.py +0 -0
  91. package/gsearch/search_tools.py +253 -0
  92. package/gsheets/__init__.py +31 -0
  93. package/gsheets/sheets_helpers.py +2236 -0
  94. package/gsheets/sheets_tools.py +3280 -0
  95. package/gslides/__init__.py +0 -0
  96. package/gslides/slides_digest.py +390 -0
  97. package/gslides/slides_helpers.py +392 -0
  98. package/gslides/slides_markup.py +770 -0
  99. package/gslides/slides_tools.py +376 -0
  100. package/gtasks/__init__.py +5 -0
  101. package/gtasks/tasks_tools.py +936 -0
  102. package/main.py +1170 -0
  103. package/package.json +43 -4
  104. package/pyproject.toml +173 -0
  105. package/uv.lock +2504 -0
@@ -0,0 +1,419 @@
1
+ """
2
+ Authentication middleware to populate context state with user information
3
+ """
4
+
5
+ import asyncio
6
+ import logging
7
+ import time
8
+
9
+ from fastmcp.server.dependencies import get_access_token, get_http_headers
10
+ from fastmcp.server.middleware import Middleware, MiddlewareContext
11
+
12
+ from auth.external_oauth_provider import get_session_time
13
+ from auth.gateway_identity import GatewayIdentityError, extract_email_from_assertion
14
+ from auth.oauth21_session_store import ensure_session_from_access_token
15
+ from auth.oauth_config import get_oauth_config, is_trust_gateway_identity
16
+ from auth.oauth_types import WorkspaceAccessToken
17
+ from auth.request_identity import (
18
+ get_request_identity,
19
+ reset_request_identity,
20
+ set_request_identity,
21
+ )
22
+
23
+ # Configure logging
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ def _token_fingerprint(token: str) -> str:
28
+ """Return a safe, short fingerprint of a bearer token for logging."""
29
+ if not token:
30
+ return "none"
31
+ return f"{token[:8]}…(len={len(token)})"
32
+
33
+
34
+ class AuthInfoMiddleware(Middleware):
35
+ """
36
+ Middleware to extract authentication information from JWT tokens
37
+ and populate the FastMCP context state for use in tools and prompts.
38
+ """
39
+
40
+ async def _process_request_for_auth(self, context: MiddlewareContext):
41
+ """Helper to extract, verify, and store auth info from a request."""
42
+ if not context.fastmcp_context:
43
+ logger.warning("No fastmcp_context available")
44
+ return
45
+
46
+ # Shadow any identity inherited from session state before any auth path
47
+ # runs. Paths below may fail and still fall through to the tool, so this
48
+ # is what guarantees an unauthenticated request reads None rather than an
49
+ # earlier request's principal.
50
+ await reset_request_identity(context.fastmcp_context)
51
+
52
+ authenticated_user = None
53
+ auth_via = None
54
+
55
+ # Trusted-gateway identity: verify the SIGNED assertion the fronting proxy injects
56
+ # and use the asserted email as the principal. This is the highest-priority and only
57
+ # trusted source in this mode (MCP_ENABLE_OAUTH21 is off — the proxy owns the handshake).
58
+ if is_trust_gateway_identity():
59
+ try:
60
+ header_name = get_oauth_config().gateway_identity_header
61
+ hdrs = get_http_headers(include={header_name}) or {}
62
+ assertion = hdrs.get(header_name)
63
+ if not assertion:
64
+ raise GatewayIdentityError(
65
+ f"Missing trusted-gateway identity header '{header_name}'"
66
+ )
67
+
68
+ # Offload the (synchronous) JWKS fetch/verify off the event loop —
69
+ # PyJWKClient can do network I/O on cold start / key rotation.
70
+ verified_email = await asyncio.to_thread(
71
+ extract_email_from_assertion, assertion
72
+ )
73
+ if not verified_email:
74
+ raise GatewayIdentityError(
75
+ "Trusted-gateway identity assertion failed verification"
76
+ )
77
+
78
+ await set_request_identity(
79
+ context.fastmcp_context,
80
+ email=verified_email,
81
+ via="gateway_assertion",
82
+ )
83
+ logger.info("✓ Authenticated via gateway_assertion: %s", verified_email)
84
+ return
85
+ except GatewayIdentityError:
86
+ logger.warning(
87
+ "[AuthInfoMiddleware] Trusted-gateway authentication rejected"
88
+ )
89
+ raise
90
+ except Exception as e:
91
+ logger.error(
92
+ f"[AuthInfoMiddleware] Error processing gateway identity assertion: {e}"
93
+ )
94
+ raise GatewayIdentityError(
95
+ "Trusted-gateway identity verification failed"
96
+ ) from e
97
+
98
+ # First check if FastMCP has already validated an access token
99
+ try:
100
+ access_token = get_access_token()
101
+ if access_token:
102
+ logger.info("[AuthInfoMiddleware] FastMCP access_token found")
103
+ user_email = getattr(access_token, "email", None)
104
+ if not user_email and hasattr(access_token, "claims"):
105
+ user_email = access_token.claims.get("email")
106
+
107
+ if user_email:
108
+ logger.info(
109
+ f"✓ Using FastMCP validated token for user: {user_email}"
110
+ )
111
+ await set_request_identity(
112
+ context.fastmcp_context,
113
+ email=user_email,
114
+ via="fastmcp_oauth",
115
+ )
116
+ authenticated_user = user_email
117
+ auth_via = "fastmcp_oauth"
118
+ else:
119
+ logger.warning(
120
+ f"FastMCP access_token found but no email. Type: {type(access_token).__name__}"
121
+ )
122
+ except Exception as e:
123
+ logger.debug(f"Could not get FastMCP access_token: {e}")
124
+
125
+ # Try to get the HTTP request to extract Authorization header
126
+ if not authenticated_user:
127
+ try:
128
+ # Capture the full headers for diagnostics, then scope auth parsing to authorization.
129
+ all_headers = get_http_headers()
130
+ logger.info(
131
+ f"[AuthInfoMiddleware] get_http_headers() returned: {all_headers is not None}, keys: {list(all_headers.keys()) if all_headers else 'None'}"
132
+ )
133
+ headers = get_http_headers(include={"authorization"})
134
+ if headers:
135
+ logger.debug("Processing HTTP headers for authentication")
136
+
137
+ # Get the Authorization header
138
+ auth_header = headers.get("authorization", "")
139
+ if auth_header.startswith("Bearer "):
140
+ token_str = auth_header[7:] # Remove "Bearer " prefix
141
+ logger.info("Found Bearer token in request")
142
+
143
+ # For Google OAuth tokens (ya29.*), we need to verify them differently
144
+ if token_str.startswith("ya29."):
145
+ logger.debug("Detected Google OAuth access token format")
146
+
147
+ # Verify the token to get user info
148
+ from core.server import get_auth_provider
149
+
150
+ auth_provider = get_auth_provider()
151
+
152
+ if auth_provider:
153
+ try:
154
+ # Verify the token
155
+ verified_auth = await auth_provider.verify_token(
156
+ token_str
157
+ )
158
+ if verified_auth:
159
+ # Extract user email from verified token
160
+ user_email = getattr(
161
+ verified_auth, "email", None
162
+ )
163
+ if not user_email and hasattr(
164
+ verified_auth, "claims"
165
+ ):
166
+ user_email = verified_auth.claims.get(
167
+ "email"
168
+ )
169
+
170
+ if isinstance(
171
+ verified_auth, WorkspaceAccessToken
172
+ ):
173
+ # ExternalOAuthProvider returns a fully-formed WorkspaceAccessToken
174
+ access_token = verified_auth
175
+ else:
176
+ # Standard GoogleProvider returns a base AccessToken;
177
+ # wrap it in WorkspaceAccessToken for identical downstream handling
178
+ verified_expires = getattr(
179
+ verified_auth, "expires_at", None
180
+ )
181
+ access_token = WorkspaceAccessToken(
182
+ token=token_str,
183
+ client_id=getattr(
184
+ verified_auth, "client_id", None
185
+ )
186
+ or "google",
187
+ scopes=getattr(
188
+ verified_auth, "scopes", []
189
+ )
190
+ or [],
191
+ session_id=f"google_oauth_{token_str[:8]}",
192
+ expires_at=verified_expires
193
+ if verified_expires is not None
194
+ else int(time.time())
195
+ + get_session_time(),
196
+ claims=getattr(
197
+ verified_auth, "claims", {}
198
+ )
199
+ or {},
200
+ sub=getattr(verified_auth, "sub", None)
201
+ or user_email,
202
+ email=user_email,
203
+ )
204
+
205
+ mcp_session_id = getattr(
206
+ context.fastmcp_context, "session_id", None
207
+ )
208
+ await ensure_session_from_access_token(
209
+ access_token,
210
+ user_email,
211
+ mcp_session_id,
212
+ )
213
+ await set_request_identity(
214
+ context.fastmcp_context,
215
+ email=user_email,
216
+ via="bearer_token",
217
+ )
218
+ authenticated_user = user_email
219
+ auth_via = "bearer_token"
220
+ else:
221
+ logger.error(
222
+ f"[AuthInfoMiddleware] Token verification returned None "
223
+ f"reason=verify_token_returned_none "
224
+ f"token={_token_fingerprint(token_str)} "
225
+ f"provider={type(auth_provider).__name__}"
226
+ )
227
+ except Exception as e:
228
+ logger.error(
229
+ f"[AuthInfoMiddleware] Token verification raised exception "
230
+ f"reason=verify_token_exception "
231
+ f"token={_token_fingerprint(token_str)} "
232
+ f"exc_type={type(e).__name__}"
233
+ )
234
+ else:
235
+ logger.warning(
236
+ "No auth provider available to verify Google token"
237
+ )
238
+
239
+ else:
240
+ # Non-Google JWT tokens require verification
241
+ # SECURITY: Never set authenticated_user_email from unverified tokens
242
+ logger.debug(
243
+ "Unverified JWT token rejected - only verified tokens accepted"
244
+ )
245
+ else:
246
+ logger.debug("No Bearer token in Authorization header")
247
+ else:
248
+ logger.debug(
249
+ "No HTTP headers available (might be using stdio transport)"
250
+ )
251
+ except Exception as e:
252
+ logger.debug(f"Could not get HTTP request: {e}")
253
+
254
+ # After trying HTTP headers, check for other authentication methods
255
+ # This consolidates all authentication logic in the middleware
256
+ if not authenticated_user:
257
+ logger.debug(
258
+ "No authentication found via bearer token, checking other methods"
259
+ )
260
+
261
+ # Check transport mode
262
+ from core.config import get_transport_mode
263
+
264
+ transport_mode = get_transport_mode()
265
+
266
+ if transport_mode == "stdio":
267
+ # In stdio mode, check if there's a session with credentials
268
+ # This is ONLY safe in stdio mode because it's single-user
269
+ logger.debug("Checking for stdio mode authentication")
270
+
271
+ arguments = getattr(context.message, "arguments", None) or {}
272
+ requested_user = arguments.get("user_google_email")
273
+
274
+ if requested_user:
275
+ try:
276
+ from auth.oauth21_session_store import get_oauth21_session_store
277
+
278
+ store = get_oauth21_session_store()
279
+
280
+ # Check if user has a recent session
281
+ if store.has_session(requested_user):
282
+ logger.debug(
283
+ f"Using recent stdio session for {requested_user}"
284
+ )
285
+ # In stdio mode, we can trust the user has authenticated recently
286
+ await set_request_identity(
287
+ context.fastmcp_context,
288
+ email=requested_user,
289
+ via="stdio_session",
290
+ )
291
+ authenticated_user = requested_user
292
+ auth_via = "stdio_session"
293
+ except Exception as e:
294
+ logger.debug(f"Error checking stdio session: {e}")
295
+
296
+ # If no requested user was provided but exactly one session exists, assume it in stdio mode
297
+ if not authenticated_user:
298
+ try:
299
+ from auth.oauth21_session_store import get_oauth21_session_store
300
+
301
+ store = get_oauth21_session_store()
302
+ single_user = store.get_single_user_email()
303
+ if single_user:
304
+ logger.debug(
305
+ f"Defaulting to single stdio OAuth session for {single_user}"
306
+ )
307
+ await set_request_identity(
308
+ context.fastmcp_context,
309
+ email=single_user,
310
+ via="stdio_single_session",
311
+ )
312
+ authenticated_user = single_user
313
+ auth_via = "stdio_single_session"
314
+ except Exception as e:
315
+ logger.debug(
316
+ f"Error determining stdio single-user session: {e}"
317
+ )
318
+
319
+ # Check for MCP session binding
320
+ if not authenticated_user and hasattr(
321
+ context.fastmcp_context, "session_id"
322
+ ):
323
+ mcp_session_id = context.fastmcp_context.session_id
324
+ if mcp_session_id:
325
+ try:
326
+ from auth.oauth21_session_store import get_oauth21_session_store
327
+
328
+ store = get_oauth21_session_store()
329
+
330
+ # Check if this MCP session is bound to a user
331
+ bound_user = store.get_user_by_mcp_session(mcp_session_id)
332
+ if bound_user:
333
+ logger.debug(f"MCP session bound to {bound_user}")
334
+ await set_request_identity(
335
+ context.fastmcp_context,
336
+ email=bound_user,
337
+ via="mcp_session_binding",
338
+ )
339
+ authenticated_user = bound_user
340
+ auth_via = "mcp_session_binding"
341
+ except Exception as e:
342
+ logger.debug(f"Error checking MCP session binding: {e}")
343
+
344
+ # Single exit point with logging
345
+ if authenticated_user:
346
+ logger.info(f"✓ Authenticated via {auth_via}: {authenticated_user}")
347
+ identity = await get_request_identity(context.fastmcp_context)
348
+ logger.debug(f"Request identity after auth: {identity}")
349
+ else:
350
+ try:
351
+ auth_header = (get_http_headers() or {}).get("authorization", "")
352
+ except Exception:
353
+ auth_header = ""
354
+ if auth_header[:7].lower() == "bearer ":
355
+ bearer = auth_header[7:]
356
+ token_fp = _token_fingerprint(bearer)
357
+ token_kind = (
358
+ "google_oauth" if bearer.startswith("ya29.") else "jwt_or_other"
359
+ )
360
+ else:
361
+ token_fp = "none"
362
+ token_kind = "no_bearer"
363
+ session_id = getattr(context.fastmcp_context, "session_id", None)
364
+ expected_legacy_http_no_bearer = (
365
+ transport_mode == "streamable-http"
366
+ and token_kind == "no_bearer"
367
+ and not get_oauth_config().is_oauth21_enabled()
368
+ and not is_trust_gateway_identity()
369
+ )
370
+ if not expected_legacy_http_no_bearer:
371
+ logger.warning(
372
+ f"[AuthInfoMiddleware] No authenticated user resolved "
373
+ f"reason=all_auth_paths_failed "
374
+ f"token={token_fp} "
375
+ f"token_kind={token_kind} "
376
+ f"session_id={session_id}"
377
+ )
378
+
379
+ async def on_call_tool(self, context: MiddlewareContext, call_next):
380
+ """Extract auth info from token and set in context state"""
381
+ logger.debug("Processing tool call authentication")
382
+
383
+ try:
384
+ await self._process_request_for_auth(context)
385
+
386
+ logger.debug("Passing to next handler")
387
+ result = await call_next(context)
388
+ logger.debug("Handler completed")
389
+ return result
390
+
391
+ except Exception as e:
392
+ if (
393
+ isinstance(e, GatewayIdentityError)
394
+ or "GoogleAuthenticationError" in str(type(e))
395
+ or "Access denied: Cannot retrieve credentials" in str(e)
396
+ ):
397
+ logger.info(f"Authentication check failed: {e}")
398
+ raise
399
+
400
+ async def on_get_prompt(self, context: MiddlewareContext, call_next):
401
+ """Extract auth info for prompt requests too"""
402
+ logger.debug("Processing prompt authentication")
403
+
404
+ try:
405
+ await self._process_request_for_auth(context)
406
+
407
+ logger.debug("Passing prompt to next handler")
408
+ result = await call_next(context)
409
+ logger.debug("Prompt handler completed")
410
+ return result
411
+
412
+ except Exception as e:
413
+ if (
414
+ isinstance(e, GatewayIdentityError)
415
+ or "GoogleAuthenticationError" in str(type(e))
416
+ or "Access denied: Cannot retrieve credentials" in str(e)
417
+ ):
418
+ logger.info(f"Authentication check failed in prompt: {e}")
419
+ raise
@@ -0,0 +1,76 @@
1
+ """Shared resolution and loading of the Google OAuth client secrets file.
2
+
3
+ Used by both the legacy per-user Google grant flow (auth/google_auth.py) and
4
+ the OAuth 2.1 protocol auth configuration (auth/oauth_config.py) so they agree
5
+ on where the client secrets file lives and how it is parsed.
6
+
7
+ Path resolution priority:
8
+ 1. GOOGLE_CLIENT_SECRET_PATH
9
+ 2. GOOGLE_CLIENT_SECRETS (legacy alias)
10
+ 3. <repo root>/client_secret.json (default)
11
+ """
12
+
13
+ import json
14
+ import os
15
+ from typing import Any, Dict
16
+
17
+ _CLIENT_SECRET_PATH_ENV = "GOOGLE_CLIENT_SECRET_PATH"
18
+ _CLIENT_SECRETS_ENV = "GOOGLE_CLIENT_SECRETS"
19
+
20
+
21
+ def get_client_secrets_path() -> str:
22
+ """Resolve the client secrets file path from environment variables.
23
+
24
+ A "~" prefix is expanded; the default is <repo root>/client_secret.json.
25
+
26
+ Returns:
27
+ The path to the client secrets JSON file.
28
+ """
29
+ path = os.getenv(_CLIENT_SECRET_PATH_ENV) or os.getenv(_CLIENT_SECRETS_ENV)
30
+ if path:
31
+ # Container images and MCP client configs routinely pass "~/..." with no
32
+ # shell to expand it, so resolve it here rather than failing to find it.
33
+ return os.path.expanduser(path)
34
+ # Assumes this file is in auth/ and client_secret.json is in the root
35
+ return os.path.join(
36
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
37
+ "client_secret.json",
38
+ )
39
+
40
+
41
+ def load_client_secrets_file(client_secrets_path: str) -> Dict[str, Any]:
42
+ """Load the client credentials section from a client secrets JSON file.
43
+
44
+ Args:
45
+ client_secrets_path: Path to the client secrets JSON file.
46
+
47
+ Returns:
48
+ The "web" or "installed" section of the client secrets file.
49
+
50
+ Raises:
51
+ ValueError: If the top-level value is not a JSON object, or the
52
+ "web"/"installed" section is missing or not an object.
53
+ IOError: If the file cannot be read.
54
+ json.JSONDecodeError: If the file is not valid JSON.
55
+ """
56
+ with open(client_secrets_path, "r") as f:
57
+ client_config = json.load(f)
58
+ if not isinstance(client_config, dict):
59
+ raise ValueError(
60
+ f"Client secrets file {client_secrets_path} has unexpected format. "
61
+ "Expected a top-level JSON object with a 'web' or 'installed' section."
62
+ )
63
+ # The file usually contains a top-level key like "web" or "installed"
64
+ for section_name in ("web", "installed"):
65
+ if section_name in client_config:
66
+ section = client_config[section_name]
67
+ if not isinstance(section, dict):
68
+ raise ValueError(
69
+ f"Client secrets file {client_secrets_path} has unexpected format. "
70
+ f"The '{section_name}' section must be a JSON object."
71
+ )
72
+ return section
73
+ raise ValueError(
74
+ f"Client secrets file {client_secrets_path} has unexpected format. "
75
+ "Expected a 'web' or 'installed' section."
76
+ )