@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/server.py
ADDED
|
@@ -0,0 +1,1192 @@
|
|
|
1
|
+
# ruff: noqa: E402
|
|
2
|
+
# Startup warning filters must be installed before importing FastMCP/Authlib dependencies.
|
|
3
|
+
import asyncio
|
|
4
|
+
import gc
|
|
5
|
+
import hashlib
|
|
6
|
+
import inspect
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
11
|
+
from typing import Any, List, Optional, TypeVar, overload
|
|
12
|
+
from importlib import metadata
|
|
13
|
+
from urllib.parse import urlparse, ParseResult
|
|
14
|
+
|
|
15
|
+
from core.warning_filters import install_startup_warning_filters
|
|
16
|
+
|
|
17
|
+
install_startup_warning_filters()
|
|
18
|
+
|
|
19
|
+
from auth.auth_info_middleware import AuthInfoMiddleware
|
|
20
|
+
from core.camel_case_middleware import CamelCaseArgumentsMiddleware, to_snake_case
|
|
21
|
+
from core.portable_schema_middleware import PortableSchemaMiddleware
|
|
22
|
+
from core.tool_descriptions import docstring_description
|
|
23
|
+
from core.toolset_header_middleware import ToolsetHeaderMiddleware
|
|
24
|
+
from auth.google_auth import (
|
|
25
|
+
check_client_secrets,
|
|
26
|
+
get_google_api_timeout,
|
|
27
|
+
handle_auth_callback,
|
|
28
|
+
start_auth_flow,
|
|
29
|
+
)
|
|
30
|
+
from auth.gateway_identity import get_verified_gateway_principal
|
|
31
|
+
from auth.mcp_session_middleware import MCPSessionMiddleware
|
|
32
|
+
from auth.oauth21_session_store import set_auth_provider
|
|
33
|
+
from auth.oauth_config import (
|
|
34
|
+
is_oauth21_enabled,
|
|
35
|
+
is_external_oauth21_provider,
|
|
36
|
+
get_oauth_config,
|
|
37
|
+
is_trust_gateway_identity,
|
|
38
|
+
)
|
|
39
|
+
from auth.oauth_proxy_config import (
|
|
40
|
+
get_oauth_proxy_consent_kwargs,
|
|
41
|
+
get_oauth_proxy_expiry_kwargs,
|
|
42
|
+
get_oauth_proxy_google_prompt_kwargs,
|
|
43
|
+
)
|
|
44
|
+
from auth.oauth_responses import (
|
|
45
|
+
create_error_response,
|
|
46
|
+
create_success_response,
|
|
47
|
+
create_server_error_response,
|
|
48
|
+
)
|
|
49
|
+
from auth.scopes import PROTOCOL_AUTH_SCOPES, SCOPES, get_current_scopes # noqa
|
|
50
|
+
from core.config import (
|
|
51
|
+
USER_GOOGLE_EMAIL,
|
|
52
|
+
get_transport_mode,
|
|
53
|
+
set_transport_mode as _set_transport_mode,
|
|
54
|
+
get_oauth_redirect_uri as get_oauth_redirect_uri_for_current_mode,
|
|
55
|
+
)
|
|
56
|
+
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
|
|
57
|
+
import fastmcp
|
|
58
|
+
from fastmcp import FastMCP
|
|
59
|
+
from auth.google_oauth_provider import GoogleProvider
|
|
60
|
+
from fastmcp.server.lifespan import lifespan
|
|
61
|
+
from fastmcp.utilities.types import AnyFunction
|
|
62
|
+
from mcp.types import ToolAnnotations, Icon
|
|
63
|
+
from starlette.applications import Starlette
|
|
64
|
+
from starlette.datastructures import MutableHeaders
|
|
65
|
+
from starlette.middleware import Middleware
|
|
66
|
+
from starlette.requests import Request
|
|
67
|
+
from starlette.types import ASGIApp, Scope, Receive, Send
|
|
68
|
+
|
|
69
|
+
logging.basicConfig(level=logging.INFO)
|
|
70
|
+
logger = logging.getLogger(__name__)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class WorkspaceGoogleProvider(GoogleProvider):
|
|
74
|
+
"""GoogleProvider whose 401 challenge advertises every tool scope.
|
|
75
|
+
|
|
76
|
+
Protocol-level validation requires only the identity scopes (#733), but
|
|
77
|
+
fastmcp >= 4 copies the validated scopes into the ``WWW-Authenticate``
|
|
78
|
+
challenge, so a client honouring it would obtain a token no tool can use
|
|
79
|
+
(#1116). Challenge with the scopes clients may request instead.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def get_challenge_scopes(
|
|
83
|
+
self, required_scopes: Optional[List[str]] = None
|
|
84
|
+
) -> List[str]:
|
|
85
|
+
if required_scopes is None:
|
|
86
|
+
return self.client_registration_options.valid_scopes
|
|
87
|
+
return required_scopes
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
_auth_provider: Optional[GoogleProvider] = None
|
|
91
|
+
_oauth_client_storage = None
|
|
92
|
+
_legacy_callback_registered = False
|
|
93
|
+
|
|
94
|
+
_READINESS_TIMEOUT_ENV = "WORKSPACE_MCP_READINESS_TIMEOUT_SECONDS"
|
|
95
|
+
_DEFAULT_READINESS_TIMEOUT_SECONDS = 1.0
|
|
96
|
+
_READINESS_PROBE_COLLECTION = "workspace-mcp-health"
|
|
97
|
+
_READINESS_PROBE_KEY = "readiness-probe"
|
|
98
|
+
|
|
99
|
+
session_middleware = Middleware(MCPSessionMiddleware)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
# Schemes whose origins are trusted by the scheme alone. The Origin header is a
|
|
103
|
+
# browser-forbidden header, so a remote web page (the DNS-rebinding threat this
|
|
104
|
+
# middleware defends against) cannot forge one of these — only the local IDE
|
|
105
|
+
# runtime emits them. VS Code in particular assigns a fresh, unpredictable host
|
|
106
|
+
# (a per-session GUID) to every webview, so its origin can never be enumerated in
|
|
107
|
+
# an allowlist; the scheme itself is the trust boundary.
|
|
108
|
+
TRUSTED_ORIGIN_SCHEMES = frozenset({"vscode-webview"})
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
|
|
112
|
+
|
|
113
|
+
# Default authority ports per scheme, used to compare an Origin against the Host
|
|
114
|
+
# header that received the request (a same-origin check).
|
|
115
|
+
_DEFAULT_PORTS = {"http": 80, "https": 443, "ws": 80, "wss": 443}
|
|
116
|
+
_ALLOW_NULL_ORIGIN_CONSENT_ENV = "WORKSPACE_MCP_ALLOW_NULL_ORIGIN_CONSENT"
|
|
117
|
+
_SESSION_IDLE_TIMEOUT_ENV = "WORKSPACE_MCP_SESSION_IDLE_TIMEOUT"
|
|
118
|
+
# Leave a minute beyond the usual one-hour Google access-token lifetime.
|
|
119
|
+
_DEFAULT_SESSION_IDLE_TIMEOUT_SECONDS = 60 * 60 + 60
|
|
120
|
+
_GOOGLE_API_WORKERS_ENV = "WORKSPACE_MCP_GOOGLE_API_WORKERS"
|
|
121
|
+
_ALLOWED_HOSTS_ENV = "WORKSPACE_MCP_ALLOWED_HOSTS"
|
|
122
|
+
_STATELESS_HTTP_ENV = "WORKSPACE_MCP_STATELESS_HTTP"
|
|
123
|
+
_SERVER_INSTRUCTIONS_ENV = "WORKSPACE_MCP_SERVER_INSTRUCTIONS"
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _parse_bool_env(value: str) -> bool:
|
|
127
|
+
"""Parse environment variable string to boolean."""
|
|
128
|
+
return value.lower() in ("1", "true", "yes", "on")
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _normalize_parsed(parsed: ParseResult) -> Optional[str]:
|
|
132
|
+
if not parsed.scheme:
|
|
133
|
+
return None
|
|
134
|
+
if not parsed.hostname:
|
|
135
|
+
return None
|
|
136
|
+
try:
|
|
137
|
+
port = parsed.port
|
|
138
|
+
except ValueError:
|
|
139
|
+
return None
|
|
140
|
+
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
|
141
|
+
netloc = f"{host}:{port}" if port is not None else host
|
|
142
|
+
return f"{parsed.scheme}://{netloc}"
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _normalize_origin(origin: str) -> Optional[str]:
|
|
146
|
+
return _normalize_parsed(urlparse(origin))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _get_allowed_http_origins() -> set[str]:
|
|
150
|
+
from auth.oauth_config import get_oauth_config
|
|
151
|
+
|
|
152
|
+
config = get_oauth_config()
|
|
153
|
+
origins = set()
|
|
154
|
+
for origin in config.get_allowed_origins():
|
|
155
|
+
normalized = _normalize_origin(origin)
|
|
156
|
+
if normalized:
|
|
157
|
+
origins.add(normalized)
|
|
158
|
+
if config.external_url:
|
|
159
|
+
normalized = _normalize_origin(config.external_url)
|
|
160
|
+
if normalized:
|
|
161
|
+
origins.add(normalized)
|
|
162
|
+
return origins
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _is_origin_allowed(origin: str) -> bool:
|
|
166
|
+
parsed = urlparse(origin)
|
|
167
|
+
if parsed.scheme in TRUSTED_ORIGIN_SCHEMES:
|
|
168
|
+
return True
|
|
169
|
+
if parsed.hostname in _LOOPBACK_HOSTS:
|
|
170
|
+
return True
|
|
171
|
+
normalized = _normalize_parsed(parsed)
|
|
172
|
+
if not normalized:
|
|
173
|
+
return False
|
|
174
|
+
return normalized in _get_allowed_http_origins()
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _is_same_origin_as_host(origin: str, host_header: Optional[str]) -> bool:
|
|
178
|
+
"""Return True when the Origin's authority matches the request's Host header.
|
|
179
|
+
|
|
180
|
+
This lets the OAuth proxy consent page post back to whatever host served it
|
|
181
|
+
without that host being in the allowlist. It is honored only in OAuth 2.1 mode:
|
|
182
|
+
a DNS-rebinding page controls both Host and Origin, so a same-origin match proves
|
|
183
|
+
nothing on its own, and only OAuth 2.1 mode requires a bearer token the
|
|
184
|
+
rebinding page cannot obtain on every MCP request.
|
|
185
|
+
"""
|
|
186
|
+
if not host_header:
|
|
187
|
+
return False
|
|
188
|
+
parsed = urlparse(origin)
|
|
189
|
+
if not parsed.hostname:
|
|
190
|
+
return False
|
|
191
|
+
try:
|
|
192
|
+
host = urlparse(f"//{host_header}")
|
|
193
|
+
origin_port = parsed.port or _DEFAULT_PORTS.get(parsed.scheme)
|
|
194
|
+
host_port = host.port or _DEFAULT_PORTS.get(parsed.scheme)
|
|
195
|
+
except ValueError:
|
|
196
|
+
return False
|
|
197
|
+
return (
|
|
198
|
+
parsed.hostname == host.hostname
|
|
199
|
+
and origin_port == host_port
|
|
200
|
+
and is_oauth21_enabled()
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _is_host_allowed(host_header: Optional[str], allowed_hosts: frozenset[str]) -> bool:
|
|
205
|
+
"""Return True when Host names loopback, an allowed host, or an allowed origin."""
|
|
206
|
+
try:
|
|
207
|
+
hostname = urlparse(f"//{host_header}").hostname if host_header else None
|
|
208
|
+
except ValueError:
|
|
209
|
+
return False
|
|
210
|
+
if not hostname:
|
|
211
|
+
return False
|
|
212
|
+
return (
|
|
213
|
+
hostname in _LOOPBACK_HOSTS
|
|
214
|
+
or hostname in allowed_hosts
|
|
215
|
+
or hostname in {urlparse(o).hostname for o in _get_allowed_http_origins()}
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _is_null_origin_consent_compat_allowed(scope: Scope, origin: str) -> bool:
|
|
220
|
+
"""Allow known opaque-origin consent POSTs only when explicitly enabled.
|
|
221
|
+
|
|
222
|
+
Some browser/MCP-client OAuth redirect chains end with Chrome sending
|
|
223
|
+
``Origin: null`` on the consent form submission, which this middleware would
|
|
224
|
+
otherwise reject. The bypass is opt-in and scoped to that exact request shape;
|
|
225
|
+
the consent handler itself still enforces a double-submit CSRF check (the form
|
|
226
|
+
token must match the SameSite=Lax ``MCP_CONSENT_STATE`` cookie), so origin
|
|
227
|
+
validation is defense in depth here rather than the only guard.
|
|
228
|
+
"""
|
|
229
|
+
if origin != "null":
|
|
230
|
+
return False
|
|
231
|
+
if scope.get("method") != "POST":
|
|
232
|
+
return False
|
|
233
|
+
if scope.get("path") != "/consent":
|
|
234
|
+
return False
|
|
235
|
+
|
|
236
|
+
return _parse_bool_env(os.getenv(_ALLOW_NULL_ORIGIN_CONSENT_ENV, "").strip())
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
class OriginValidationMiddleware:
|
|
240
|
+
"""Reject browser-originated HTTP requests from untrusted origins."""
|
|
241
|
+
|
|
242
|
+
def __init__(
|
|
243
|
+
self, app: ASGIApp, allowed_hosts: Optional[frozenset[str]] = None
|
|
244
|
+
) -> None:
|
|
245
|
+
self.app = app
|
|
246
|
+
self.allowed_hosts = allowed_hosts
|
|
247
|
+
|
|
248
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
249
|
+
if scope["type"] == "http":
|
|
250
|
+
headers = dict(scope.get("headers") or [])
|
|
251
|
+
raw_origin = headers.get(b"origin")
|
|
252
|
+
raw_host = headers.get(b"host")
|
|
253
|
+
host_header = raw_host.decode("latin-1") if raw_host else None
|
|
254
|
+
if self.allowed_hosts is not None and not _is_host_allowed(
|
|
255
|
+
host_header, self.allowed_hosts
|
|
256
|
+
):
|
|
257
|
+
logger.warning("Rejected HTTP request for Host: %s", host_header)
|
|
258
|
+
response = JSONResponse({"error": "Host not allowed"}, status_code=403)
|
|
259
|
+
await response(scope, receive, send)
|
|
260
|
+
return
|
|
261
|
+
if raw_origin:
|
|
262
|
+
origin = raw_origin.decode("latin-1")
|
|
263
|
+
if not _is_origin_allowed(origin) and not _is_same_origin_as_host(
|
|
264
|
+
origin, host_header
|
|
265
|
+
):
|
|
266
|
+
if _is_null_origin_consent_compat_allowed(scope, origin):
|
|
267
|
+
logger.info(
|
|
268
|
+
"Allowing OAuth consent POST with Origin: null because "
|
|
269
|
+
"%s is enabled",
|
|
270
|
+
_ALLOW_NULL_ORIGIN_CONSENT_ENV,
|
|
271
|
+
)
|
|
272
|
+
await self.app(scope, receive, send)
|
|
273
|
+
return
|
|
274
|
+
logger.warning("Rejected HTTP request from Origin: %s", origin)
|
|
275
|
+
response = JSONResponse(
|
|
276
|
+
{"error": "Origin not allowed"}, status_code=403
|
|
277
|
+
)
|
|
278
|
+
await response(scope, receive, send)
|
|
279
|
+
return
|
|
280
|
+
|
|
281
|
+
await self.app(scope, receive, send)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
class WellKnownCacheControlMiddleware:
|
|
285
|
+
"""Force no-cache headers for OAuth well-known discovery endpoints."""
|
|
286
|
+
|
|
287
|
+
def __init__(self, app):
|
|
288
|
+
self.app = app
|
|
289
|
+
|
|
290
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
291
|
+
if scope["type"] != "http":
|
|
292
|
+
await self.app(scope, receive, send)
|
|
293
|
+
return
|
|
294
|
+
|
|
295
|
+
path = scope.get("path", "")
|
|
296
|
+
is_oauth_well_known = (
|
|
297
|
+
path == "/.well-known/oauth-authorization-server"
|
|
298
|
+
or path.startswith("/.well-known/oauth-authorization-server/")
|
|
299
|
+
or path == "/.well-known/oauth-protected-resource"
|
|
300
|
+
or path.startswith("/.well-known/oauth-protected-resource/")
|
|
301
|
+
)
|
|
302
|
+
if not is_oauth_well_known:
|
|
303
|
+
await self.app(scope, receive, send)
|
|
304
|
+
return
|
|
305
|
+
|
|
306
|
+
async def send_with_no_cache_headers(message):
|
|
307
|
+
if message["type"] == "http.response.start":
|
|
308
|
+
headers = MutableHeaders(raw=message.setdefault("headers", []))
|
|
309
|
+
headers["Cache-Control"] = "no-store, must-revalidate"
|
|
310
|
+
headers["ETag"] = f'"{_compute_scope_fingerprint()}"'
|
|
311
|
+
await send(message)
|
|
312
|
+
|
|
313
|
+
await self.app(scope, receive, send_with_no_cache_headers)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
well_known_cache_control_middleware = Middleware(WellKnownCacheControlMiddleware)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def get_stateless_http() -> bool:
|
|
320
|
+
"""Parse WORKSPACE_MCP_STATELESS_HTTP; ValueError unless unset, true or false."""
|
|
321
|
+
raw = os.getenv(_STATELESS_HTTP_ENV, "").strip().lower()
|
|
322
|
+
if raw not in ("", "true", "false"):
|
|
323
|
+
raise ValueError(f"{_STATELESS_HTTP_ENV} must be true or false, got {raw!r}")
|
|
324
|
+
return raw == "true"
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def get_session_idle_timeout() -> Optional[int]:
|
|
328
|
+
"""Parse WORKSPACE_MCP_SESSION_IDLE_TIMEOUT; 0 defers to FastMCP's setting.
|
|
329
|
+
|
|
330
|
+
Invalid values raise instead of falling back, so a misconfigured deployment
|
|
331
|
+
fails at startup.
|
|
332
|
+
"""
|
|
333
|
+
raw = os.getenv(_SESSION_IDLE_TIMEOUT_ENV, "").strip()
|
|
334
|
+
if not raw:
|
|
335
|
+
return _DEFAULT_SESSION_IDLE_TIMEOUT_SECONDS
|
|
336
|
+
try:
|
|
337
|
+
value = int(raw)
|
|
338
|
+
except ValueError:
|
|
339
|
+
value = -1
|
|
340
|
+
if value < 0:
|
|
341
|
+
raise ValueError(
|
|
342
|
+
f"{_SESSION_IDLE_TIMEOUT_ENV} must be a non-negative integer "
|
|
343
|
+
f"(seconds), got {raw!r}"
|
|
344
|
+
)
|
|
345
|
+
return value or None
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _compute_scope_fingerprint() -> str:
|
|
349
|
+
"""Compute a short hash of the current scope configuration for cache-busting."""
|
|
350
|
+
scopes_str = ",".join(sorted(get_current_scopes()))
|
|
351
|
+
return hashlib.sha256(scopes_str.encode()).hexdigest()[:12]
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def get_allowed_hosts() -> Optional[frozenset[str]]:
|
|
355
|
+
"""Parse WORKSPACE_MCP_ALLOWED_HOSTS; None when unset, ValueError when invalid."""
|
|
356
|
+
raw = os.getenv(_ALLOWED_HOSTS_ENV, "").strip()
|
|
357
|
+
if not raw:
|
|
358
|
+
return None
|
|
359
|
+
hosts = set()
|
|
360
|
+
for entry in (part.strip() for part in raw.split(",")):
|
|
361
|
+
try:
|
|
362
|
+
parsed = urlparse(f"//{entry}")
|
|
363
|
+
valid = (
|
|
364
|
+
parsed.hostname is not None
|
|
365
|
+
and parsed.port is None
|
|
366
|
+
and parsed.netloc == entry
|
|
367
|
+
and "@" not in entry
|
|
368
|
+
and "*" not in entry
|
|
369
|
+
)
|
|
370
|
+
except ValueError:
|
|
371
|
+
valid = False
|
|
372
|
+
if not valid:
|
|
373
|
+
raise ValueError(
|
|
374
|
+
f"{_ALLOWED_HOSTS_ENV} must be a comma-separated list of hostnames "
|
|
375
|
+
f"without ports, got {entry!r}"
|
|
376
|
+
)
|
|
377
|
+
hosts.add(parsed.hostname)
|
|
378
|
+
return frozenset(hosts)
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def get_google_api_workers() -> Optional[int]:
|
|
382
|
+
"""Parse WORKSPACE_MCP_GOOGLE_API_WORKERS; unset keeps asyncio's default.
|
|
383
|
+
|
|
384
|
+
Invalid values raise instead of falling back, so a misconfigured deployment
|
|
385
|
+
fails at startup.
|
|
386
|
+
"""
|
|
387
|
+
raw = os.getenv(_GOOGLE_API_WORKERS_ENV, "").strip()
|
|
388
|
+
if not raw:
|
|
389
|
+
return None
|
|
390
|
+
try:
|
|
391
|
+
value = int(raw)
|
|
392
|
+
except ValueError:
|
|
393
|
+
value = 0
|
|
394
|
+
if value < 1:
|
|
395
|
+
raise ValueError(
|
|
396
|
+
f"{_GOOGLE_API_WORKERS_ENV} must be a positive integer, got {raw!r}"
|
|
397
|
+
)
|
|
398
|
+
return value
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
@lifespan
|
|
402
|
+
async def _freeze_startup_heap(server: FastMCP):
|
|
403
|
+
"""Exempt objects loaded at startup from garbage collection.
|
|
404
|
+
|
|
405
|
+
Each tool call ends with a full collection to free googleapiclient reference
|
|
406
|
+
cycles. Freezing the modules and tool registry first keeps that collection
|
|
407
|
+
under a millisecond instead of scanning the whole startup heap every call.
|
|
408
|
+
"""
|
|
409
|
+
gc.collect()
|
|
410
|
+
gc.freeze()
|
|
411
|
+
yield None
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
@lifespan
|
|
415
|
+
async def _google_api_executor(server: FastMCP):
|
|
416
|
+
"""Size the executor that runs blocking Google API calls, when configured.
|
|
417
|
+
|
|
418
|
+
Tools run Google HTTP requests through asyncio.to_thread, so this pool caps
|
|
419
|
+
how many requests one process has in flight across all users. The request
|
|
420
|
+
timeout is validated here too, so an invalid one fails startup.
|
|
421
|
+
"""
|
|
422
|
+
get_google_api_timeout()
|
|
423
|
+
workers = get_google_api_workers()
|
|
424
|
+
if workers:
|
|
425
|
+
asyncio.get_running_loop().set_default_executor(
|
|
426
|
+
ThreadPoolExecutor(workers, thread_name_prefix="google-api")
|
|
427
|
+
)
|
|
428
|
+
yield None
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
F = TypeVar("F", bound=AnyFunction)
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
# Custom FastMCP that adds secure middleware stack for OAuth 2.1
|
|
435
|
+
class SecureFastMCP(FastMCP):
|
|
436
|
+
@overload
|
|
437
|
+
def tool(self, name_or_fn: F, **kwargs: Any) -> F: ...
|
|
438
|
+
|
|
439
|
+
@overload
|
|
440
|
+
def tool(
|
|
441
|
+
self, name_or_fn: str | None = None, **kwargs: Any
|
|
442
|
+
) -> Callable[[F], F]: ...
|
|
443
|
+
|
|
444
|
+
def tool(
|
|
445
|
+
self, name_or_fn: str | AnyFunction | None = None, **kwargs: Any
|
|
446
|
+
) -> AnyFunction | Callable[[F], F]:
|
|
447
|
+
"""Register a tool described by its docstring above ``Args:``, or ``description``."""
|
|
448
|
+
register = super().tool
|
|
449
|
+
if kwargs.get("description") is not None:
|
|
450
|
+
return register(name_or_fn, **kwargs)
|
|
451
|
+
kwargs.pop("description", None)
|
|
452
|
+
if inspect.isroutine(name_or_fn):
|
|
453
|
+
return register(
|
|
454
|
+
name_or_fn, description=docstring_description(name_or_fn), **kwargs
|
|
455
|
+
)
|
|
456
|
+
if name_or_fn is None or (
|
|
457
|
+
isinstance(name_or_fn, str) and kwargs.get("name") is None
|
|
458
|
+
):
|
|
459
|
+
if name_or_fn is not None:
|
|
460
|
+
kwargs["name"] = name_or_fn
|
|
461
|
+
|
|
462
|
+
def register_with_description(fn: F) -> F:
|
|
463
|
+
return register(fn, description=docstring_description(fn), **kwargs)
|
|
464
|
+
|
|
465
|
+
return register_with_description
|
|
466
|
+
# Let FastMCP raise its usual error for unsupported arguments.
|
|
467
|
+
return register(name_or_fn, **kwargs)
|
|
468
|
+
|
|
469
|
+
def http_app(self, **kwargs) -> "Starlette":
|
|
470
|
+
"""Override to add secure middleware stack for OAuth 2.1."""
|
|
471
|
+
# Bound memory retained by abandoned stateful sessions. Resolve an omitted
|
|
472
|
+
# or None stateless_http the same way FastMCP does.
|
|
473
|
+
stateless_http = kwargs.get("stateless_http")
|
|
474
|
+
if stateless_http is None:
|
|
475
|
+
stateless_http = fastmcp.settings.stateless_http
|
|
476
|
+
if not stateless_http and "session_idle_timeout" not in kwargs:
|
|
477
|
+
kwargs["session_idle_timeout"] = get_session_idle_timeout()
|
|
478
|
+
app = super().http_app(**kwargs)
|
|
479
|
+
|
|
480
|
+
# Add middleware in order (first added = outermost layer)
|
|
481
|
+
app.user_middleware.insert(0, well_known_cache_control_middleware)
|
|
482
|
+
app.user_middleware.insert(
|
|
483
|
+
1, Middleware(OriginValidationMiddleware, allowed_hosts=get_allowed_hosts())
|
|
484
|
+
)
|
|
485
|
+
|
|
486
|
+
# Session Management - extracts session info for MCP context
|
|
487
|
+
app.user_middleware.insert(2, session_middleware)
|
|
488
|
+
|
|
489
|
+
# Rebuild middleware stack
|
|
490
|
+
app.middleware_stack = app.build_middleware_stack()
|
|
491
|
+
logger.debug(
|
|
492
|
+
"Added middleware stack: WellKnownCacheControl, OriginValidation, "
|
|
493
|
+
"Session Management"
|
|
494
|
+
)
|
|
495
|
+
return app
|
|
496
|
+
|
|
497
|
+
async def list_tools(self, *, run_middleware: bool = True):
|
|
498
|
+
"""Override to mark user_google_email as optional when USER_GOOGLE_EMAIL is set.
|
|
499
|
+
|
|
500
|
+
In single-user / self-hosted mode the env var provides the default email, so
|
|
501
|
+
callers (agents, MCP adapters) should not be required to supply it. We patch
|
|
502
|
+
the JSON schema returned by list_tools to remove 'user_google_email' from the
|
|
503
|
+
``required`` array and inject the env-var value as the ``default``. The
|
|
504
|
+
runtime still resolves the email correctly via the service decorator.
|
|
505
|
+
"""
|
|
506
|
+
tools = list(await super().list_tools(run_middleware=run_middleware))
|
|
507
|
+
if is_trust_gateway_identity():
|
|
508
|
+
patched = []
|
|
509
|
+
for tool in tools:
|
|
510
|
+
if tool.name != "start_google_auth":
|
|
511
|
+
patched.append(tool)
|
|
512
|
+
continue
|
|
513
|
+
schema = dict(tool.parameters)
|
|
514
|
+
required = [
|
|
515
|
+
name
|
|
516
|
+
for name in schema.get("required", [])
|
|
517
|
+
if name != "user_google_email"
|
|
518
|
+
]
|
|
519
|
+
properties = dict(schema.get("properties", {}))
|
|
520
|
+
properties.pop("user_google_email", None)
|
|
521
|
+
schema.update(required=required, properties=properties)
|
|
522
|
+
patched.append(tool.model_copy(update={"parameters": schema}))
|
|
523
|
+
return patched
|
|
524
|
+
if not USER_GOOGLE_EMAIL or is_oauth21_enabled():
|
|
525
|
+
return tools
|
|
526
|
+
patched = []
|
|
527
|
+
for tool in tools:
|
|
528
|
+
schema = dict(tool.parameters)
|
|
529
|
+
required = list(schema.get("required", []))
|
|
530
|
+
if "user_google_email" in required:
|
|
531
|
+
required = [r for r in required if r != "user_google_email"]
|
|
532
|
+
props = {k: dict(v) for k, v in schema.get("properties", {}).items()}
|
|
533
|
+
if "user_google_email" in props:
|
|
534
|
+
props["user_google_email"]["default"] = USER_GOOGLE_EMAIL
|
|
535
|
+
props["user_google_email"]["description"] = (
|
|
536
|
+
f"Optional. Defaults to {USER_GOOGLE_EMAIL}; omit it."
|
|
537
|
+
)
|
|
538
|
+
schema = dict(schema, required=required, properties=props)
|
|
539
|
+
patched.append(tool.model_copy(update={"parameters": schema}))
|
|
540
|
+
else:
|
|
541
|
+
patched.append(tool)
|
|
542
|
+
return patched
|
|
543
|
+
|
|
544
|
+
async def call_tool(self, name: str, arguments: Optional[dict], *args, **kwargs):
|
|
545
|
+
"""Inject user_google_email before pydantic validates the call arguments.
|
|
546
|
+
|
|
547
|
+
When USER_GOOGLE_EMAIL is configured and OAuth 2.1 is not active, callers
|
|
548
|
+
(agents, adapters) are allowed to omit user_google_email. FastMCP validates
|
|
549
|
+
arguments against the function signature BEFORE calling the tool, so we must
|
|
550
|
+
inject the default BEFORE that validation step.
|
|
551
|
+
"""
|
|
552
|
+
arguments = arguments or {}
|
|
553
|
+
if is_trust_gateway_identity():
|
|
554
|
+
# The verified gateway principal is authoritative for every tool, and the
|
|
555
|
+
# parameter is gone from tool signatures. Drop any caller-supplied email
|
|
556
|
+
# (older clients may have the pre-gateway schema cached) instead of letting
|
|
557
|
+
# it fail signature validation, and never inject USER_GOOGLE_EMAIL.
|
|
558
|
+
arguments = {
|
|
559
|
+
key: value
|
|
560
|
+
for key, value in arguments.items()
|
|
561
|
+
if key != "user_google_email"
|
|
562
|
+
}
|
|
563
|
+
elif (
|
|
564
|
+
not is_oauth21_enabled()
|
|
565
|
+
and USER_GOOGLE_EMAIL
|
|
566
|
+
and not any(to_snake_case(key) == "user_google_email" for key in arguments)
|
|
567
|
+
):
|
|
568
|
+
tool = await self.get_tool(name)
|
|
569
|
+
if tool and "user_google_email" in tool.parameters.get("properties", {}):
|
|
570
|
+
arguments = {**arguments, "user_google_email": USER_GOOGLE_EMAIL}
|
|
571
|
+
return await super().call_tool(name, arguments, *args, **kwargs)
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def get_server_instructions() -> Optional[str]:
|
|
575
|
+
"""Return WORKSPACE_MCP_SERVER_INSTRUCTIONS, then the single-user account context."""
|
|
576
|
+
sections = [os.getenv(_SERVER_INSTRUCTIONS_ENV, "").strip()]
|
|
577
|
+
# Skipped in trusted-gateway mode: the verified principal supersedes the configured
|
|
578
|
+
# default, and user_google_email is no longer a tool parameter clients can pass.
|
|
579
|
+
if USER_GOOGLE_EMAIL and not is_trust_gateway_identity():
|
|
580
|
+
sections.append(
|
|
581
|
+
f"Connected Google account: {USER_GOOGLE_EMAIL}\n\n"
|
|
582
|
+
f"When using Google Workspace tools, always use `{USER_GOOGLE_EMAIL}` "
|
|
583
|
+
"as the `user_google_email` parameter. Do not ask the user for their "
|
|
584
|
+
"email address."
|
|
585
|
+
)
|
|
586
|
+
logger.info(f"Server instructions configured for user: {USER_GOOGLE_EMAIL}")
|
|
587
|
+
return "\n\n".join(filter(None, sections)) or None
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
# Branding for the OAuth consent page: FastMCP's OAuth proxy renders the server's
|
|
591
|
+
# name / icon / website on the consent screen (auth/oauth_config reads the env vars).
|
|
592
|
+
_brand_config = get_oauth_config()
|
|
593
|
+
_brand_icons = (
|
|
594
|
+
[Icon(src=_brand_config.brand_icon_url)] if _brand_config.brand_icon_url else None
|
|
595
|
+
)
|
|
596
|
+
|
|
597
|
+
server = SecureFastMCP(
|
|
598
|
+
name=_brand_config.brand_name or "google_workspace",
|
|
599
|
+
auth=None,
|
|
600
|
+
instructions=get_server_instructions(),
|
|
601
|
+
website_url=_brand_config.brand_website_url,
|
|
602
|
+
icons=_brand_icons,
|
|
603
|
+
lifespan=_freeze_startup_heap | _google_api_executor,
|
|
604
|
+
)
|
|
605
|
+
|
|
606
|
+
# Narrow tools per request with X-MCP-Toolsets / X-MCP-Tools. See
|
|
607
|
+
# https://github.com/taylorwilsdon/google_workspace_mcp/issues/509
|
|
608
|
+
server.add_middleware(ToolsetHeaderMiddleware())
|
|
609
|
+
|
|
610
|
+
# Accept camelCase argument names (calendarId, timeMin, ...) from callers that
|
|
611
|
+
# mirror the Google API field names, mapping them onto the snake_case tool
|
|
612
|
+
# parameters. See https://github.com/taylorwilsdon/google_workspace_mcp/issues/918
|
|
613
|
+
server.add_middleware(CamelCaseArgumentsMiddleware())
|
|
614
|
+
|
|
615
|
+
# Add the AuthInfo middleware to inject authentication into FastMCP context
|
|
616
|
+
auth_info_middleware = AuthInfoMiddleware()
|
|
617
|
+
server.add_middleware(auth_info_middleware)
|
|
618
|
+
|
|
619
|
+
# Advertise tool schemas without null unions or ``const``, which Gemini's
|
|
620
|
+
# function-calling schema cannot represent. See
|
|
621
|
+
# https://github.com/taylorwilsdon/google_workspace_mcp/issues/1099
|
|
622
|
+
server.add_middleware(PortableSchemaMiddleware())
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
def _parse_allowed_redirect_uris(value: Optional[str]) -> Optional[List[str]]:
|
|
626
|
+
"""Parse a comma-separated list of OAuth client redirect URIs.
|
|
627
|
+
|
|
628
|
+
Returns a list of non-empty, trimmed URIs, or None when the input is
|
|
629
|
+
empty/None. Returning None preserves FastMCP's default behaviour of
|
|
630
|
+
accepting any client-supplied redirect URI during DCR — callers that
|
|
631
|
+
want to lock down registration must supply a non-empty list.
|
|
632
|
+
|
|
633
|
+
Patterns supported by FastMCP's matcher (see
|
|
634
|
+
``fastmcp.server.auth.redirect_validation``) include ``*`` for port
|
|
635
|
+
and path globs (e.g. ``http://localhost:*/callback``) and ``*.example.com``
|
|
636
|
+
for subdomain wildcards.
|
|
637
|
+
"""
|
|
638
|
+
if not value:
|
|
639
|
+
return None
|
|
640
|
+
uris = [u.strip() for u in value.split(",") if u.strip()]
|
|
641
|
+
return uris or None
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def set_transport_mode(mode: str):
|
|
645
|
+
"""Sets the transport mode for the server."""
|
|
646
|
+
_set_transport_mode(mode)
|
|
647
|
+
# Debug level: the startup banner already shows the active transport.
|
|
648
|
+
logger.debug(f"Transport: {mode}")
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def _ensure_legacy_callback_route() -> None:
|
|
652
|
+
global _legacy_callback_registered
|
|
653
|
+
if _legacy_callback_registered:
|
|
654
|
+
return
|
|
655
|
+
server.custom_route("/oauth2callback", methods=["GET"])(legacy_oauth2_callback)
|
|
656
|
+
_legacy_callback_registered = True
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def configure_server_for_http():
|
|
660
|
+
"""
|
|
661
|
+
Configures the authentication provider for HTTP transport.
|
|
662
|
+
This must be called BEFORE server.run().
|
|
663
|
+
"""
|
|
664
|
+
global _auth_provider, _oauth_client_storage
|
|
665
|
+
|
|
666
|
+
transport_mode = get_transport_mode()
|
|
667
|
+
|
|
668
|
+
if transport_mode != "streamable-http":
|
|
669
|
+
return
|
|
670
|
+
|
|
671
|
+
# Use centralized OAuth configuration
|
|
672
|
+
from auth.oauth_config import get_oauth_config
|
|
673
|
+
|
|
674
|
+
config = get_oauth_config()
|
|
675
|
+
|
|
676
|
+
# Check if OAuth 2.1 is enabled via centralized config
|
|
677
|
+
oauth21_enabled = config.is_oauth21_enabled()
|
|
678
|
+
|
|
679
|
+
if oauth21_enabled:
|
|
680
|
+
if not config.is_configured():
|
|
681
|
+
raise RuntimeError(
|
|
682
|
+
"streamable-http transport requires GOOGLE_OAUTH_CLIENT_ID so OAuth 2.1 "
|
|
683
|
+
"protocol authentication can be configured."
|
|
684
|
+
)
|
|
685
|
+
|
|
686
|
+
if not config.client_secret and not config.is_external_oauth21_provider():
|
|
687
|
+
# MCP clients stay secretless, but this server performs the Google code
|
|
688
|
+
# exchange itself and Google requires a secret for it. Fail here instead
|
|
689
|
+
# of at the last step of the user's browser flow.
|
|
690
|
+
raise RuntimeError(
|
|
691
|
+
"OAuth 2.1 requires GOOGLE_OAUTH_CLIENT_SECRET: Google rejects the "
|
|
692
|
+
"authorization code exchange without a client secret (invalid_request: "
|
|
693
|
+
"client_secret is missing), even for public clients using PKCE. Set "
|
|
694
|
+
"GOOGLE_OAUTH_CLIENT_SECRET (or provide it via a client secrets file "
|
|
695
|
+
"through GOOGLE_CLIENT_SECRET_PATH), or set "
|
|
696
|
+
"EXTERNAL_OAUTH21_PROVIDER=true if another identity provider performs "
|
|
697
|
+
"the code exchange."
|
|
698
|
+
)
|
|
699
|
+
|
|
700
|
+
def validate_and_derive_jwt_key(
|
|
701
|
+
jwt_signing_key_override: str | None, client_secret: str | None
|
|
702
|
+
) -> bytes:
|
|
703
|
+
"""Validate JWT signing key override and derive the final JWT key."""
|
|
704
|
+
if jwt_signing_key_override:
|
|
705
|
+
if len(jwt_signing_key_override) < 12:
|
|
706
|
+
logger.warning(
|
|
707
|
+
"OAuth 2.1: FASTMCP_SERVER_AUTH_GOOGLE_JWT_SIGNING_KEY is less than 12 characters; "
|
|
708
|
+
"use a longer secret to improve key derivation strength."
|
|
709
|
+
)
|
|
710
|
+
return derive_jwt_key(
|
|
711
|
+
low_entropy_material=jwt_signing_key_override,
|
|
712
|
+
salt="fastmcp-jwt-signing-key",
|
|
713
|
+
)
|
|
714
|
+
if client_secret:
|
|
715
|
+
return derive_jwt_key(
|
|
716
|
+
high_entropy_material=client_secret,
|
|
717
|
+
salt="fastmcp-jwt-signing-key",
|
|
718
|
+
)
|
|
719
|
+
raise ValueError(
|
|
720
|
+
"Public client OAuth 2.1 requires FASTMCP_SERVER_AUTH_GOOGLE_JWT_SIGNING_KEY "
|
|
721
|
+
"when GOOGLE_OAUTH_CLIENT_SECRET is not set."
|
|
722
|
+
)
|
|
723
|
+
|
|
724
|
+
try:
|
|
725
|
+
# Import common dependencies for storage backends
|
|
726
|
+
from key_value.aio.wrappers.encryption import FernetEncryptionWrapper
|
|
727
|
+
from cryptography.fernet import Fernet
|
|
728
|
+
from fastmcp.server.auth.jwt_issuer import derive_jwt_key
|
|
729
|
+
|
|
730
|
+
provider_valid_scopes: List[str] = sorted(get_current_scopes())
|
|
731
|
+
provider_required_scopes: List[str] = sorted(PROTOCOL_AUTH_SCOPES)
|
|
732
|
+
|
|
733
|
+
client_storage = None
|
|
734
|
+
jwt_signing_key_override = (
|
|
735
|
+
os.getenv("FASTMCP_SERVER_AUTH_GOOGLE_JWT_SIGNING_KEY", "").strip()
|
|
736
|
+
or None
|
|
737
|
+
)
|
|
738
|
+
storage_backend = (
|
|
739
|
+
os.getenv("WORKSPACE_MCP_OAUTH_PROXY_STORAGE_BACKEND", "")
|
|
740
|
+
.strip()
|
|
741
|
+
.lower()
|
|
742
|
+
)
|
|
743
|
+
valkey_host = os.getenv("WORKSPACE_MCP_OAUTH_PROXY_VALKEY_HOST", "").strip()
|
|
744
|
+
|
|
745
|
+
# Determine storage backend: valkey, disk, memory (default)
|
|
746
|
+
use_valkey = storage_backend == "valkey" or bool(valkey_host)
|
|
747
|
+
use_disk = storage_backend == "disk"
|
|
748
|
+
|
|
749
|
+
if use_valkey:
|
|
750
|
+
try:
|
|
751
|
+
from core.valkey_storage import (
|
|
752
|
+
ResilientValkeyStore,
|
|
753
|
+
build_valkey_client_config,
|
|
754
|
+
configure_glide_logging,
|
|
755
|
+
describe_valkey_client_config,
|
|
756
|
+
)
|
|
757
|
+
|
|
758
|
+
configure_glide_logging()
|
|
759
|
+
valkey_config = build_valkey_client_config()
|
|
760
|
+
client_storage = ResilientValkeyStore(config=valkey_config)
|
|
761
|
+
|
|
762
|
+
jwt_signing_key = validate_and_derive_jwt_key(
|
|
763
|
+
jwt_signing_key_override, config.client_secret
|
|
764
|
+
)
|
|
765
|
+
|
|
766
|
+
storage_encryption_key = derive_jwt_key(
|
|
767
|
+
high_entropy_material=jwt_signing_key.decode(),
|
|
768
|
+
salt="fastmcp-storage-encryption-key",
|
|
769
|
+
)
|
|
770
|
+
|
|
771
|
+
client_storage = FernetEncryptionWrapper(
|
|
772
|
+
key_value=client_storage,
|
|
773
|
+
fernet=Fernet(key=storage_encryption_key),
|
|
774
|
+
)
|
|
775
|
+
logger.info(
|
|
776
|
+
"OAuth 2.1: Using ResilientValkeyStore for FastMCP OAuth proxy client_storage (%s)",
|
|
777
|
+
describe_valkey_client_config(valkey_config),
|
|
778
|
+
)
|
|
779
|
+
logger.info(
|
|
780
|
+
"OAuth 2.1: Applied Fernet encryption wrapper to Valkey client_storage (key derived from FASTMCP_SERVER_AUTH_GOOGLE_JWT_SIGNING_KEY or GOOGLE_OAUTH_CLIENT_SECRET)."
|
|
781
|
+
)
|
|
782
|
+
except ImportError as exc:
|
|
783
|
+
logger.warning(
|
|
784
|
+
"OAuth 2.1: Valkey client_storage requested but Valkey dependencies are not installed (%s). "
|
|
785
|
+
"Install 'workspace-mcp[valkey]' (or 'py-key-value-aio[valkey]', which includes 'valkey-glide') "
|
|
786
|
+
"or unset WORKSPACE_MCP_OAUTH_PROXY_STORAGE_BACKEND/WORKSPACE_MCP_OAUTH_PROXY_VALKEY_HOST.",
|
|
787
|
+
exc,
|
|
788
|
+
)
|
|
789
|
+
except ValueError as exc:
|
|
790
|
+
logger.warning(
|
|
791
|
+
"OAuth 2.1: Invalid Valkey configuration; falling back to default storage (%s).",
|
|
792
|
+
exc,
|
|
793
|
+
)
|
|
794
|
+
elif use_disk:
|
|
795
|
+
try:
|
|
796
|
+
from core.storage import make_sanitized_file_store
|
|
797
|
+
|
|
798
|
+
disk_directory = os.getenv(
|
|
799
|
+
"WORKSPACE_MCP_OAUTH_PROXY_DISK_DIRECTORY", ""
|
|
800
|
+
).strip()
|
|
801
|
+
if not disk_directory:
|
|
802
|
+
# Default to FASTMCP_HOME/oauth-proxy or ~/.fastmcp/oauth-proxy
|
|
803
|
+
fastmcp_home = os.getenv("FASTMCP_HOME", "").strip()
|
|
804
|
+
if fastmcp_home:
|
|
805
|
+
disk_directory = os.path.join(fastmcp_home, "oauth-proxy")
|
|
806
|
+
else:
|
|
807
|
+
disk_directory = os.path.expanduser(
|
|
808
|
+
"~/.fastmcp/oauth-proxy"
|
|
809
|
+
)
|
|
810
|
+
|
|
811
|
+
client_storage = make_sanitized_file_store(disk_directory)
|
|
812
|
+
|
|
813
|
+
jwt_signing_key = validate_and_derive_jwt_key(
|
|
814
|
+
jwt_signing_key_override, config.client_secret
|
|
815
|
+
)
|
|
816
|
+
|
|
817
|
+
storage_encryption_key = derive_jwt_key(
|
|
818
|
+
high_entropy_material=jwt_signing_key.decode(),
|
|
819
|
+
salt="fastmcp-storage-encryption-key",
|
|
820
|
+
)
|
|
821
|
+
|
|
822
|
+
client_storage = FernetEncryptionWrapper(
|
|
823
|
+
key_value=client_storage,
|
|
824
|
+
fernet=Fernet(key=storage_encryption_key),
|
|
825
|
+
)
|
|
826
|
+
logger.info(
|
|
827
|
+
"OAuth 2.1: Using FileTreeStore for FastMCP OAuth proxy client_storage (directory=%s)",
|
|
828
|
+
disk_directory,
|
|
829
|
+
)
|
|
830
|
+
except ImportError as exc:
|
|
831
|
+
logger.warning(
|
|
832
|
+
"OAuth 2.1: Disk storage requested but dependencies not available (%s). "
|
|
833
|
+
"Falling back to default storage.",
|
|
834
|
+
exc,
|
|
835
|
+
)
|
|
836
|
+
elif storage_backend == "memory":
|
|
837
|
+
from key_value.aio.stores.memory import MemoryStore
|
|
838
|
+
|
|
839
|
+
client_storage = MemoryStore()
|
|
840
|
+
logger.info(
|
|
841
|
+
"OAuth 2.1: Using MemoryStore for FastMCP OAuth proxy client_storage"
|
|
842
|
+
)
|
|
843
|
+
# else: client_storage remains None, FastMCP uses its default
|
|
844
|
+
|
|
845
|
+
# Ensure JWT signing key is always derived for all storage backends
|
|
846
|
+
if "jwt_signing_key" not in locals():
|
|
847
|
+
jwt_signing_key = validate_and_derive_jwt_key(
|
|
848
|
+
jwt_signing_key_override, config.client_secret
|
|
849
|
+
)
|
|
850
|
+
|
|
851
|
+
expiry_kwargs = get_oauth_proxy_expiry_kwargs()
|
|
852
|
+
|
|
853
|
+
# Check if external OAuth provider is configured
|
|
854
|
+
if config.is_external_oauth21_provider():
|
|
855
|
+
# External OAuth mode: use custom provider that handles ya29.* access tokens
|
|
856
|
+
from auth.external_oauth_provider import (
|
|
857
|
+
ExternalOAuthProvider,
|
|
858
|
+
get_token_validation_workers,
|
|
859
|
+
get_token_validation_cache_ttl,
|
|
860
|
+
)
|
|
861
|
+
|
|
862
|
+
provider = ExternalOAuthProvider(
|
|
863
|
+
client_id=config.client_id,
|
|
864
|
+
client_secret=config.client_secret,
|
|
865
|
+
base_url=config.get_oauth_base_url(),
|
|
866
|
+
redirect_path=config.redirect_path,
|
|
867
|
+
required_scopes=provider_valid_scopes,
|
|
868
|
+
resource_server_url=config.get_oauth_base_url(),
|
|
869
|
+
jwt_signing_key=jwt_signing_key,
|
|
870
|
+
token_validation_workers=get_token_validation_workers(),
|
|
871
|
+
token_validation_cache_ttl=get_token_validation_cache_ttl(),
|
|
872
|
+
**expiry_kwargs,
|
|
873
|
+
)
|
|
874
|
+
server.auth = provider
|
|
875
|
+
_oauth_client_storage = None
|
|
876
|
+
|
|
877
|
+
logger.info("OAuth 2.1 enabled with EXTERNAL provider mode")
|
|
878
|
+
logger.info(
|
|
879
|
+
"Expecting Authorization bearer tokens in tool call headers"
|
|
880
|
+
)
|
|
881
|
+
logger.info(
|
|
882
|
+
"Protected resource metadata points to Google's authorization server"
|
|
883
|
+
)
|
|
884
|
+
else:
|
|
885
|
+
# Standard OAuth 2.1 mode: use FastMCP's GoogleProvider
|
|
886
|
+
allowed_client_redirect_uris = _parse_allowed_redirect_uris(
|
|
887
|
+
os.getenv("WORKSPACE_MCP_ALLOWED_CLIENT_REDIRECT_URIS")
|
|
888
|
+
)
|
|
889
|
+
if allowed_client_redirect_uris:
|
|
890
|
+
logger.info(
|
|
891
|
+
"OAuth 2.1: restricting DCR client redirect URIs to allowlist: %s",
|
|
892
|
+
allowed_client_redirect_uris,
|
|
893
|
+
)
|
|
894
|
+
if client_storage is None:
|
|
895
|
+
storage_fingerprint = hashlib.sha256(
|
|
896
|
+
derive_jwt_key(
|
|
897
|
+
high_entropy_material=jwt_signing_key.decode(),
|
|
898
|
+
salt="fastmcp-storage-encryption-key",
|
|
899
|
+
)
|
|
900
|
+
).hexdigest()[:12]
|
|
901
|
+
logger.info(
|
|
902
|
+
"OAuth 2.1: Using FastMCP default encrypted FileTreeStore for OAuth proxy client_storage (directory=%s). "
|
|
903
|
+
"Set WORKSPACE_MCP_OAUTH_PROXY_STORAGE_BACKEND to memory, disk or valkey to change it.",
|
|
904
|
+
(
|
|
905
|
+
fastmcp.settings.home / "oauth-proxy" / storage_fingerprint
|
|
906
|
+
).absolute(),
|
|
907
|
+
)
|
|
908
|
+
provider = WorkspaceGoogleProvider(
|
|
909
|
+
client_id=config.client_id,
|
|
910
|
+
client_secret=config.client_secret,
|
|
911
|
+
base_url=config.get_oauth_base_url(),
|
|
912
|
+
redirect_path=config.redirect_path,
|
|
913
|
+
required_scopes=provider_required_scopes,
|
|
914
|
+
valid_scopes=provider_valid_scopes,
|
|
915
|
+
client_storage=client_storage,
|
|
916
|
+
jwt_signing_key=jwt_signing_key,
|
|
917
|
+
allowed_client_redirect_uris=allowed_client_redirect_uris,
|
|
918
|
+
**expiry_kwargs,
|
|
919
|
+
**get_oauth_proxy_consent_kwargs(),
|
|
920
|
+
**get_oauth_proxy_google_prompt_kwargs(),
|
|
921
|
+
)
|
|
922
|
+
if provider.client_registration_options is not None:
|
|
923
|
+
# Keep protocol-level auth limited to base identity scopes, but
|
|
924
|
+
# allow dynamically registered MCP clients to request any scope
|
|
925
|
+
# needed by enabled tools during subsequent authorization flows.
|
|
926
|
+
provider.client_registration_options.default_scopes = (
|
|
927
|
+
provider_valid_scopes
|
|
928
|
+
)
|
|
929
|
+
# CIMD clients can bypass DCR defaults and fall back to FastMCP's
|
|
930
|
+
# internal scope string, so keep it aligned with valid scopes too.
|
|
931
|
+
cimd_default_scope = " ".join(provider_valid_scopes)
|
|
932
|
+
provider._default_scope_str = cimd_default_scope
|
|
933
|
+
cimd_manager = getattr(provider, "_cimd_manager", None)
|
|
934
|
+
if cimd_manager is not None:
|
|
935
|
+
cimd_manager.default_scope = cimd_default_scope
|
|
936
|
+
# Enable protocol-level auth
|
|
937
|
+
server.auth = provider
|
|
938
|
+
_oauth_client_storage = client_storage
|
|
939
|
+
|
|
940
|
+
# Always set auth provider for token validation in middleware
|
|
941
|
+
set_auth_provider(provider)
|
|
942
|
+
_auth_provider = provider
|
|
943
|
+
except Exception as exc:
|
|
944
|
+
logger.error(
|
|
945
|
+
"Failed to initialize FastMCP GoogleProvider: %s", exc, exc_info=True
|
|
946
|
+
)
|
|
947
|
+
raise
|
|
948
|
+
else:
|
|
949
|
+
# Debug level: main.py surfaces the loopback default as a startup notice.
|
|
950
|
+
logger.debug(
|
|
951
|
+
"OAuth 2.0 legacy mode - streamable HTTP defaults to loopback unless "
|
|
952
|
+
"WORKSPACE_MCP_HOST is explicitly set."
|
|
953
|
+
)
|
|
954
|
+
server.auth = None
|
|
955
|
+
_auth_provider = None
|
|
956
|
+
_oauth_client_storage = None
|
|
957
|
+
set_auth_provider(None)
|
|
958
|
+
_ensure_legacy_callback_route()
|
|
959
|
+
|
|
960
|
+
|
|
961
|
+
def get_auth_provider() -> Optional[GoogleProvider]:
|
|
962
|
+
"""Gets the global authentication provider instance."""
|
|
963
|
+
return _auth_provider
|
|
964
|
+
|
|
965
|
+
|
|
966
|
+
def close_auth_provider() -> None:
|
|
967
|
+
"""Release resources owned by the configured authentication provider."""
|
|
968
|
+
global _auth_provider, _oauth_client_storage
|
|
969
|
+
|
|
970
|
+
provider = _auth_provider
|
|
971
|
+
_auth_provider = None
|
|
972
|
+
_oauth_client_storage = None
|
|
973
|
+
set_auth_provider(None)
|
|
974
|
+
if server.auth is provider:
|
|
975
|
+
server.auth = None
|
|
976
|
+
|
|
977
|
+
close = getattr(provider, "close", None)
|
|
978
|
+
if callable(close):
|
|
979
|
+
try:
|
|
980
|
+
close()
|
|
981
|
+
except Exception:
|
|
982
|
+
logger.warning("Failed to close authentication provider", exc_info=True)
|
|
983
|
+
|
|
984
|
+
|
|
985
|
+
@server.custom_route("/", methods=["GET"])
|
|
986
|
+
@server.custom_route("/health", methods=["GET"])
|
|
987
|
+
async def health_check(request: Request):
|
|
988
|
+
try:
|
|
989
|
+
version = metadata.version("workspace-mcp")
|
|
990
|
+
except metadata.PackageNotFoundError:
|
|
991
|
+
version = "dev"
|
|
992
|
+
return JSONResponse(
|
|
993
|
+
{
|
|
994
|
+
"status": "healthy",
|
|
995
|
+
"service": "workspace-mcp",
|
|
996
|
+
"version": version,
|
|
997
|
+
"transport": get_transport_mode(),
|
|
998
|
+
}
|
|
999
|
+
)
|
|
1000
|
+
|
|
1001
|
+
|
|
1002
|
+
def _readiness_timeout_seconds() -> float:
|
|
1003
|
+
raw = os.getenv(_READINESS_TIMEOUT_ENV, "").strip()
|
|
1004
|
+
if not raw:
|
|
1005
|
+
return _DEFAULT_READINESS_TIMEOUT_SECONDS
|
|
1006
|
+
try:
|
|
1007
|
+
value = float(raw)
|
|
1008
|
+
except ValueError:
|
|
1009
|
+
value = 0.0
|
|
1010
|
+
if not 0 < value < float("inf"):
|
|
1011
|
+
logger.warning(
|
|
1012
|
+
"%s=%r is not a positive number of seconds; using %ss",
|
|
1013
|
+
_READINESS_TIMEOUT_ENV,
|
|
1014
|
+
raw,
|
|
1015
|
+
_DEFAULT_READINESS_TIMEOUT_SECONDS,
|
|
1016
|
+
)
|
|
1017
|
+
return _DEFAULT_READINESS_TIMEOUT_SECONDS
|
|
1018
|
+
return value
|
|
1019
|
+
|
|
1020
|
+
|
|
1021
|
+
@server.custom_route("/health/ready", methods=["GET"])
|
|
1022
|
+
async def readiness_check(request: Request):
|
|
1023
|
+
"""Readiness probe: 503 while the OAuth proxy's storage backend is unreachable."""
|
|
1024
|
+
storage = _oauth_client_storage
|
|
1025
|
+
if storage is None:
|
|
1026
|
+
return JSONResponse({"status": "ready", "storage": "default"})
|
|
1027
|
+
|
|
1028
|
+
timeout = _readiness_timeout_seconds()
|
|
1029
|
+
try:
|
|
1030
|
+
await asyncio.wait_for(
|
|
1031
|
+
storage.get(
|
|
1032
|
+
key=_READINESS_PROBE_KEY, collection=_READINESS_PROBE_COLLECTION
|
|
1033
|
+
),
|
|
1034
|
+
timeout=timeout,
|
|
1035
|
+
)
|
|
1036
|
+
except asyncio.TimeoutError:
|
|
1037
|
+
error = f"storage probe timed out after {timeout:g}s"
|
|
1038
|
+
logger.warning("Readiness probe: OAuth storage %s", error)
|
|
1039
|
+
except Exception as exc:
|
|
1040
|
+
error = type(exc).__name__
|
|
1041
|
+
logger.warning("Readiness probe: OAuth storage unavailable (%s)", error)
|
|
1042
|
+
else:
|
|
1043
|
+
return JSONResponse({"status": "ready", "storage": "ok"})
|
|
1044
|
+
|
|
1045
|
+
return JSONResponse(
|
|
1046
|
+
{"status": "unavailable", "storage": "unavailable", "error": error},
|
|
1047
|
+
status_code=503,
|
|
1048
|
+
)
|
|
1049
|
+
|
|
1050
|
+
|
|
1051
|
+
@server.custom_route("/attachments/{file_id}", methods=["GET"])
|
|
1052
|
+
async def serve_attachment(request: Request):
|
|
1053
|
+
"""Serve a stored attachment file."""
|
|
1054
|
+
from core.attachment_storage import get_attachment_storage
|
|
1055
|
+
|
|
1056
|
+
file_id = request.path_params["file_id"]
|
|
1057
|
+
storage = get_attachment_storage()
|
|
1058
|
+
metadata = storage.get_attachment_metadata(file_id)
|
|
1059
|
+
|
|
1060
|
+
if not metadata:
|
|
1061
|
+
return JSONResponse(
|
|
1062
|
+
{"error": "Attachment not found or expired"}, status_code=404
|
|
1063
|
+
)
|
|
1064
|
+
|
|
1065
|
+
file_path = storage.get_attachment_path(file_id)
|
|
1066
|
+
if not file_path:
|
|
1067
|
+
return JSONResponse({"error": "Attachment file not found"}, status_code=404)
|
|
1068
|
+
|
|
1069
|
+
return FileResponse(
|
|
1070
|
+
path=str(file_path),
|
|
1071
|
+
filename=metadata["filename"],
|
|
1072
|
+
media_type=metadata["mime_type"],
|
|
1073
|
+
)
|
|
1074
|
+
|
|
1075
|
+
|
|
1076
|
+
async def legacy_oauth2_callback(request: Request) -> HTMLResponse:
|
|
1077
|
+
state = request.query_params.get("state")
|
|
1078
|
+
code = request.query_params.get("code")
|
|
1079
|
+
error = request.query_params.get("error")
|
|
1080
|
+
|
|
1081
|
+
if error:
|
|
1082
|
+
msg = (
|
|
1083
|
+
f"Authentication failed: Google returned an error: {error}. State: {state}."
|
|
1084
|
+
)
|
|
1085
|
+
logger.error(msg)
|
|
1086
|
+
return create_error_response(msg)
|
|
1087
|
+
|
|
1088
|
+
if not code:
|
|
1089
|
+
msg = "Authentication failed: No authorization code received from Google."
|
|
1090
|
+
logger.error(msg)
|
|
1091
|
+
return create_error_response(msg)
|
|
1092
|
+
|
|
1093
|
+
try:
|
|
1094
|
+
error_message = check_client_secrets()
|
|
1095
|
+
if error_message:
|
|
1096
|
+
return create_server_error_response(error_message)
|
|
1097
|
+
|
|
1098
|
+
logger.info("OAuth callback: Received authorization code.")
|
|
1099
|
+
|
|
1100
|
+
mcp_session_id = None
|
|
1101
|
+
if hasattr(request, "state") and hasattr(request.state, "session_id"):
|
|
1102
|
+
mcp_session_id = request.state.session_id
|
|
1103
|
+
|
|
1104
|
+
verified_user_id, credentials = await handle_auth_callback(
|
|
1105
|
+
scopes=get_current_scopes(),
|
|
1106
|
+
authorization_response=str(request.url),
|
|
1107
|
+
redirect_uri=get_oauth_redirect_uri_for_current_mode(),
|
|
1108
|
+
session_id=mcp_session_id,
|
|
1109
|
+
)
|
|
1110
|
+
|
|
1111
|
+
logger.info(
|
|
1112
|
+
f"OAuth callback: Successfully authenticated user: {verified_user_id}."
|
|
1113
|
+
)
|
|
1114
|
+
|
|
1115
|
+
return create_success_response(verified_user_id)
|
|
1116
|
+
except Exception as e:
|
|
1117
|
+
logger.error(f"Error processing OAuth callback: {str(e)}", exc_info=True)
|
|
1118
|
+
return create_server_error_response(str(e))
|
|
1119
|
+
|
|
1120
|
+
|
|
1121
|
+
@server.tool(
|
|
1122
|
+
title="Start Google Auth",
|
|
1123
|
+
annotations=ToolAnnotations(
|
|
1124
|
+
readOnlyHint=False,
|
|
1125
|
+
destructiveHint=False,
|
|
1126
|
+
idempotentHint=False,
|
|
1127
|
+
openWorldHint=True,
|
|
1128
|
+
),
|
|
1129
|
+
)
|
|
1130
|
+
async def start_google_auth(
|
|
1131
|
+
service_name: str, user_google_email: str = USER_GOOGLE_EMAIL
|
|
1132
|
+
) -> str:
|
|
1133
|
+
"""
|
|
1134
|
+
Manually initiate Google OAuth authentication flow.
|
|
1135
|
+
|
|
1136
|
+
NOTE: This is a legacy OAuth 2.0 tool and is disabled when OAuth 2.1 is enabled.
|
|
1137
|
+
The authentication system automatically handles credential checks and prompts for
|
|
1138
|
+
authentication when needed. Only use this tool if:
|
|
1139
|
+
1. You need to re-authenticate with different credentials
|
|
1140
|
+
2. You want to proactively authenticate before using other tools
|
|
1141
|
+
3. The automatic authentication flow failed and you need to retry
|
|
1142
|
+
|
|
1143
|
+
In most cases, simply try calling the Google Workspace tool you need - it will
|
|
1144
|
+
automatically handle authentication if required.
|
|
1145
|
+
"""
|
|
1146
|
+
if is_oauth21_enabled():
|
|
1147
|
+
if is_external_oauth21_provider():
|
|
1148
|
+
return (
|
|
1149
|
+
"start_google_auth is disabled when OAuth 2.1 is enabled. "
|
|
1150
|
+
"Provide a valid OAuth 2.1 bearer token in the Authorization header "
|
|
1151
|
+
"and retry the original tool."
|
|
1152
|
+
)
|
|
1153
|
+
return (
|
|
1154
|
+
"start_google_auth is disabled when OAuth 2.1 is enabled. "
|
|
1155
|
+
"Authenticate through your MCP client's OAuth 2.1 flow and retry the "
|
|
1156
|
+
"original tool."
|
|
1157
|
+
)
|
|
1158
|
+
|
|
1159
|
+
if is_trust_gateway_identity():
|
|
1160
|
+
user_google_email = await get_verified_gateway_principal()
|
|
1161
|
+
|
|
1162
|
+
if not user_google_email:
|
|
1163
|
+
raise ValueError("user_google_email must be provided.")
|
|
1164
|
+
|
|
1165
|
+
error_message = check_client_secrets()
|
|
1166
|
+
if error_message:
|
|
1167
|
+
return f"**Authentication Error:** {error_message}"
|
|
1168
|
+
|
|
1169
|
+
try:
|
|
1170
|
+
# Only stdio legacy OAuth depends on the standalone callback server; the
|
|
1171
|
+
# helper no-ops in other transports and binds the port lazily (#832).
|
|
1172
|
+
from auth.oauth_callback_server import ensure_stdio_oauth_callback_available
|
|
1173
|
+
|
|
1174
|
+
success, error_msg = await asyncio.to_thread(
|
|
1175
|
+
ensure_stdio_oauth_callback_available
|
|
1176
|
+
)
|
|
1177
|
+
if not success:
|
|
1178
|
+
error_detail = f" ({error_msg})" if error_msg else ""
|
|
1179
|
+
return f"**Error:** Cannot initiate OAuth flow - callback server unavailable{error_detail}"
|
|
1180
|
+
|
|
1181
|
+
auth_message = await start_auth_flow(
|
|
1182
|
+
user_google_email=user_google_email,
|
|
1183
|
+
service_name=service_name,
|
|
1184
|
+
redirect_uri=get_oauth_redirect_uri_for_current_mode(),
|
|
1185
|
+
principal_source=(
|
|
1186
|
+
"gateway_assertion" if is_trust_gateway_identity() else None
|
|
1187
|
+
),
|
|
1188
|
+
)
|
|
1189
|
+
return auth_message
|
|
1190
|
+
except Exception as e:
|
|
1191
|
+
logger.error(f"Failed to start Google authentication flow: {e}", exc_info=True)
|
|
1192
|
+
return f"**Error:** An unexpected error occurred: {e}"
|