@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
|
@@ -0,0 +1,1109 @@
|
|
|
1
|
+
import gc
|
|
2
|
+
import inspect
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
import re
|
|
8
|
+
from functools import wraps
|
|
9
|
+
from typing import Dict, List, Optional, Any, Callable, Union, Tuple
|
|
10
|
+
from contextlib import ExitStack
|
|
11
|
+
|
|
12
|
+
from google.auth.exceptions import RefreshError
|
|
13
|
+
from google.oauth2 import service_account as google_service_account
|
|
14
|
+
from fastmcp.server.dependencies import get_access_token, get_context
|
|
15
|
+
from auth.google_auth import (
|
|
16
|
+
GoogleAuthenticationError,
|
|
17
|
+
build_google_service,
|
|
18
|
+
get_authenticated_google_service,
|
|
19
|
+
recycling,
|
|
20
|
+
)
|
|
21
|
+
from auth.gateway_identity import (
|
|
22
|
+
require_gateway_principal,
|
|
23
|
+
get_verified_gateway_principal,
|
|
24
|
+
)
|
|
25
|
+
from auth.request_identity import get_request_identity
|
|
26
|
+
from core.config import USER_GOOGLE_EMAIL as _ENV_USER_EMAIL
|
|
27
|
+
from auth.oauth21_session_store import (
|
|
28
|
+
get_auth_provider,
|
|
29
|
+
get_oauth21_session_store,
|
|
30
|
+
ensure_session_from_access_token,
|
|
31
|
+
)
|
|
32
|
+
from auth.oauth_config import (
|
|
33
|
+
is_oauth21_enabled,
|
|
34
|
+
get_oauth_config,
|
|
35
|
+
is_external_oauth21_provider,
|
|
36
|
+
is_service_account_enabled,
|
|
37
|
+
is_trust_gateway_identity,
|
|
38
|
+
)
|
|
39
|
+
from core.context import set_fastmcp_session_id
|
|
40
|
+
from core.telemetry import record_authenticated_user, record_google_principal
|
|
41
|
+
from auth.scopes import (
|
|
42
|
+
GMAIL_READONLY_SCOPE,
|
|
43
|
+
GMAIL_SEND_SCOPE,
|
|
44
|
+
GMAIL_COMPOSE_SCOPE,
|
|
45
|
+
GMAIL_MODIFY_SCOPE,
|
|
46
|
+
GMAIL_LABELS_SCOPE,
|
|
47
|
+
GMAIL_SETTINGS_BASIC_SCOPE,
|
|
48
|
+
DRIVE_SCOPE,
|
|
49
|
+
DRIVE_READONLY_SCOPE,
|
|
50
|
+
DRIVE_FILE_SCOPE,
|
|
51
|
+
DOCS_READONLY_SCOPE,
|
|
52
|
+
DOCS_WRITE_SCOPE,
|
|
53
|
+
CALENDAR_SCOPE,
|
|
54
|
+
CALENDAR_READONLY_SCOPE,
|
|
55
|
+
CALENDAR_EVENTS_SCOPE,
|
|
56
|
+
SHEETS_READONLY_SCOPE,
|
|
57
|
+
SHEETS_WRITE_SCOPE,
|
|
58
|
+
CHAT_READONLY_SCOPE,
|
|
59
|
+
CHAT_WRITE_SCOPE,
|
|
60
|
+
CHAT_SPACES_SCOPE,
|
|
61
|
+
CHAT_SPACES_READONLY_SCOPE,
|
|
62
|
+
FORMS_BODY_SCOPE,
|
|
63
|
+
FORMS_BODY_READONLY_SCOPE,
|
|
64
|
+
FORMS_RESPONSES_READONLY_SCOPE,
|
|
65
|
+
SLIDES_SCOPE,
|
|
66
|
+
SLIDES_READONLY_SCOPE,
|
|
67
|
+
TASKS_SCOPE,
|
|
68
|
+
TASKS_READONLY_SCOPE,
|
|
69
|
+
CONTACTS_SCOPE,
|
|
70
|
+
CONTACTS_READONLY_SCOPE,
|
|
71
|
+
CUSTOM_SEARCH_SCOPE,
|
|
72
|
+
SCRIPT_PROJECTS_SCOPE,
|
|
73
|
+
SCRIPT_PROJECTS_READONLY_SCOPE,
|
|
74
|
+
SCRIPT_DEPLOYMENTS_SCOPE,
|
|
75
|
+
SCRIPT_DEPLOYMENTS_READONLY_SCOPE,
|
|
76
|
+
SCRIPT_EXTERNAL_REQUEST_SCOPE,
|
|
77
|
+
SCRIPT_SCRIPTAPP_SCOPE,
|
|
78
|
+
has_required_scopes,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
logger = logging.getLogger(__name__)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class GoogleScopeError(GoogleAuthenticationError):
|
|
85
|
+
"""The authenticated account has not granted this tool's permissions."""
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _missing_scope_message(service_name: str, error: GoogleScopeError) -> str:
|
|
89
|
+
return (
|
|
90
|
+
f"Permission required for {service_name}: {error}. "
|
|
91
|
+
"Reconnect using your MCP client's OAuth flow and grant access to this "
|
|
92
|
+
"service if it is available for your account. Other services with granted "
|
|
93
|
+
"permissions remain usable."
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _release_google_service_cycles() -> None:
|
|
98
|
+
"""Collect cyclic references retained by googleapiclient Resource objects.
|
|
99
|
+
|
|
100
|
+
A client the caller still references survives, so callers drop theirs first.
|
|
101
|
+
"""
|
|
102
|
+
gc.collect()
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _get_configured_user_google_email() -> Optional[str]:
|
|
106
|
+
"""Return the configured default user email, preferring the live environment."""
|
|
107
|
+
return os.getenv("USER_GOOGLE_EMAIL") or _ENV_USER_EMAIL
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# Authentication helper functions
|
|
111
|
+
async def _get_auth_context(
|
|
112
|
+
tool_name: str,
|
|
113
|
+
) -> Tuple[Optional[str], Optional[str], Optional[str]]:
|
|
114
|
+
"""
|
|
115
|
+
Get authentication context from FastMCP.
|
|
116
|
+
|
|
117
|
+
Returns:
|
|
118
|
+
Tuple of (authenticated_user, auth_method, mcp_session_id)
|
|
119
|
+
"""
|
|
120
|
+
try:
|
|
121
|
+
ctx = get_context()
|
|
122
|
+
identity = await get_request_identity(ctx)
|
|
123
|
+
if identity is None:
|
|
124
|
+
return None, None, None
|
|
125
|
+
|
|
126
|
+
authenticated_user, auth_method = identity
|
|
127
|
+
mcp_session_id = ctx.session_id if hasattr(ctx, "session_id") else None
|
|
128
|
+
|
|
129
|
+
# Opt-in: enrich the active tool-call span with the human-readable user
|
|
130
|
+
# email (no-op unless WORKSPACE_MCP_OTEL_USER_EMAIL is set).
|
|
131
|
+
record_authenticated_user(authenticated_user)
|
|
132
|
+
|
|
133
|
+
if mcp_session_id:
|
|
134
|
+
set_fastmcp_session_id(mcp_session_id)
|
|
135
|
+
|
|
136
|
+
logger.debug(
|
|
137
|
+
f"[{tool_name}] Middleware context: user={authenticated_user}, "
|
|
138
|
+
f"method={auth_method}, session={mcp_session_id}"
|
|
139
|
+
)
|
|
140
|
+
return authenticated_user, auth_method, mcp_session_id
|
|
141
|
+
|
|
142
|
+
except Exception as e:
|
|
143
|
+
logger.debug(f"[{tool_name}] Could not get FastMCP context: {e}")
|
|
144
|
+
return None, None, None
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _user_email_is_managed() -> bool:
|
|
148
|
+
"""True when the server determines user_google_email from a verified identity
|
|
149
|
+
(an OAuth 2.1 access token OR a trusted-gateway assertion) instead of the caller
|
|
150
|
+
passing it. Drives hiding + auto-filling the user_google_email tool parameter so
|
|
151
|
+
the client never has to ask for it."""
|
|
152
|
+
return is_oauth21_enabled() or is_trust_gateway_identity()
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _detect_oauth_version(
|
|
156
|
+
authenticated_user: Optional[str], mcp_session_id: Optional[str], tool_name: str
|
|
157
|
+
) -> bool:
|
|
158
|
+
"""
|
|
159
|
+
Detect whether to use OAuth 2.1 based on configuration and context.
|
|
160
|
+
|
|
161
|
+
Returns:
|
|
162
|
+
True if OAuth 2.1 should be used, False otherwise
|
|
163
|
+
"""
|
|
164
|
+
if not is_oauth21_enabled():
|
|
165
|
+
return False
|
|
166
|
+
|
|
167
|
+
# When OAuth 2.1 is enabled globally, ALWAYS use OAuth 2.1 for authenticated users
|
|
168
|
+
if authenticated_user:
|
|
169
|
+
logger.debug(
|
|
170
|
+
f"[{tool_name}] OAuth 2.1 selected for authenticated user '{authenticated_user}'"
|
|
171
|
+
)
|
|
172
|
+
return True
|
|
173
|
+
|
|
174
|
+
# If FastMCP protocol-level auth is enabled, a validated access token should
|
|
175
|
+
# be available even if middleware state wasn't populated.
|
|
176
|
+
try:
|
|
177
|
+
if get_access_token() is not None:
|
|
178
|
+
logger.debug(f"[{tool_name}] OAuth 2.1 selected via validated access token")
|
|
179
|
+
return True
|
|
180
|
+
except Exception as e:
|
|
181
|
+
logger.debug(
|
|
182
|
+
f"[{tool_name}] Could not inspect access token for OAuth mode: {e}"
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
# Only use version detection for unauthenticated requests
|
|
186
|
+
config = get_oauth_config()
|
|
187
|
+
request_params = {}
|
|
188
|
+
if mcp_session_id:
|
|
189
|
+
request_params["session_id"] = mcp_session_id
|
|
190
|
+
|
|
191
|
+
oauth_version = config.detect_oauth_version(request_params)
|
|
192
|
+
use_oauth21 = oauth_version == "oauth21"
|
|
193
|
+
logger.debug(
|
|
194
|
+
f"[{tool_name}] OAuth version detected: {oauth_version} (use_oauth21={use_oauth21})"
|
|
195
|
+
)
|
|
196
|
+
return use_oauth21
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _update_email_in_args(args: tuple, index: int, new_email: str) -> tuple:
|
|
200
|
+
"""Update email at specific index in args tuple."""
|
|
201
|
+
if index < len(args):
|
|
202
|
+
args_list = list(args)
|
|
203
|
+
args_list[index] = new_email
|
|
204
|
+
return tuple(args_list)
|
|
205
|
+
return args
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _override_oauth21_user_email(
|
|
209
|
+
use_oauth21: bool,
|
|
210
|
+
authenticated_user: Optional[str],
|
|
211
|
+
current_user_email: str,
|
|
212
|
+
args: tuple,
|
|
213
|
+
kwargs: dict,
|
|
214
|
+
param_names: List[str],
|
|
215
|
+
tool_name: str,
|
|
216
|
+
service_type: str = "",
|
|
217
|
+
) -> Tuple[str, tuple]:
|
|
218
|
+
"""
|
|
219
|
+
Override user_google_email with authenticated user when using OAuth 2.1.
|
|
220
|
+
|
|
221
|
+
Trusted-gateway mode never reaches this helper: its call sites are gated on
|
|
222
|
+
``not _user_email_is_managed()``, and the gateway principal is injected directly.
|
|
223
|
+
|
|
224
|
+
Returns:
|
|
225
|
+
Tuple of (updated_user_email, updated_args)
|
|
226
|
+
"""
|
|
227
|
+
if not (
|
|
228
|
+
use_oauth21 and authenticated_user and current_user_email != authenticated_user
|
|
229
|
+
):
|
|
230
|
+
return current_user_email, args
|
|
231
|
+
|
|
232
|
+
service_suffix = f" for service '{service_type}'" if service_type else ""
|
|
233
|
+
logger.info(
|
|
234
|
+
f"[{tool_name}] OAuth 2.1: Overriding user_google_email from '{current_user_email}' to authenticated user '{authenticated_user}'{service_suffix}"
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
# Update in kwargs if present
|
|
238
|
+
if "user_google_email" in kwargs:
|
|
239
|
+
kwargs["user_google_email"] = authenticated_user
|
|
240
|
+
|
|
241
|
+
# Update in args if user_google_email is passed positionally
|
|
242
|
+
try:
|
|
243
|
+
user_email_index = param_names.index("user_google_email")
|
|
244
|
+
args = _update_email_in_args(args, user_email_index, authenticated_user)
|
|
245
|
+
except ValueError:
|
|
246
|
+
pass # user_google_email not in positional parameters
|
|
247
|
+
|
|
248
|
+
return authenticated_user, args
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _get_service_account_credentials(
|
|
252
|
+
scopes: List[str], subject: str
|
|
253
|
+
) -> google_service_account.Credentials:
|
|
254
|
+
"""
|
|
255
|
+
Build service account credentials for domain-wide delegation.
|
|
256
|
+
|
|
257
|
+
Args:
|
|
258
|
+
scopes: OAuth scopes to request
|
|
259
|
+
subject: Email of the domain user to impersonate
|
|
260
|
+
|
|
261
|
+
Returns:
|
|
262
|
+
google.oauth2.service_account.Credentials instance
|
|
263
|
+
|
|
264
|
+
Raises:
|
|
265
|
+
GoogleAuthenticationError: If credentials cannot be built
|
|
266
|
+
"""
|
|
267
|
+
config = get_oauth_config()
|
|
268
|
+
try:
|
|
269
|
+
if config.service_account_key_file:
|
|
270
|
+
return google_service_account.Credentials.from_service_account_file(
|
|
271
|
+
config.service_account_key_file, scopes=scopes, subject=subject
|
|
272
|
+
)
|
|
273
|
+
service_account_key_json = config.service_account_key_json
|
|
274
|
+
if (
|
|
275
|
+
not isinstance(service_account_key_json, str)
|
|
276
|
+
or not service_account_key_json.strip()
|
|
277
|
+
):
|
|
278
|
+
raise GoogleAuthenticationError(
|
|
279
|
+
"Service account credentials require either service_account_key_file "
|
|
280
|
+
"or a non-empty service_account_key_json."
|
|
281
|
+
)
|
|
282
|
+
try:
|
|
283
|
+
info = json.loads(service_account_key_json)
|
|
284
|
+
except json.JSONDecodeError as e:
|
|
285
|
+
raise GoogleAuthenticationError(
|
|
286
|
+
"Failed to parse service_account_key_json: invalid JSON."
|
|
287
|
+
) from e
|
|
288
|
+
return google_service_account.Credentials.from_service_account_info(
|
|
289
|
+
info, scopes=scopes, subject=subject
|
|
290
|
+
)
|
|
291
|
+
except GoogleAuthenticationError:
|
|
292
|
+
raise
|
|
293
|
+
except Exception as e:
|
|
294
|
+
raise GoogleAuthenticationError(
|
|
295
|
+
f"Failed to build service account credentials: {e}"
|
|
296
|
+
) from e
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _validate_dwd_domain(email: str, config) -> None:
|
|
300
|
+
"""Raise if email's domain is not in the configured allowlist (when set)."""
|
|
301
|
+
if not config.dwd_allowed_domains:
|
|
302
|
+
return
|
|
303
|
+
domain = email.rsplit("@", 1)[-1].lower()
|
|
304
|
+
if domain not in config.dwd_allowed_domains:
|
|
305
|
+
raise GoogleAuthenticationError(
|
|
306
|
+
f"Domain '{domain}' is not in DWD_ALLOWED_DOMAINS. "
|
|
307
|
+
f"Allowed: {', '.join(config.dwd_allowed_domains)}"
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _widen_drive_scope_for_dwd(scopes: List[str], tool_name: str) -> List[str]:
|
|
312
|
+
"""
|
|
313
|
+
Substitute the full Drive scope for drive.file in service-account mode.
|
|
314
|
+
|
|
315
|
+
drive.file grants access only to files the app created or the user picked
|
|
316
|
+
through the Drive file picker. A domain-wide-delegation service account never
|
|
317
|
+
goes through a picker, so under drive.file every Drive write tool gets a bare
|
|
318
|
+
404 on any pre-existing file. The delegated token carries exactly the scopes
|
|
319
|
+
requested here, so SCOPE_HIERARCHY never applies, and the effective privilege
|
|
320
|
+
is governed by the Admin console's DWD scope allowlist regardless.
|
|
321
|
+
"""
|
|
322
|
+
if DRIVE_FILE_SCOPE not in scopes:
|
|
323
|
+
return scopes
|
|
324
|
+
|
|
325
|
+
widened = [DRIVE_SCOPE if s == DRIVE_FILE_SCOPE else s for s in scopes]
|
|
326
|
+
logger.debug(
|
|
327
|
+
f"[{tool_name}] Service-account mode: requesting {DRIVE_SCOPE} in place of "
|
|
328
|
+
f"{DRIVE_FILE_SCOPE}, which cannot reach pre-existing files under "
|
|
329
|
+
"domain-wide delegation. Authorize it in the Admin console DWD scope list."
|
|
330
|
+
)
|
|
331
|
+
return widened
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
async def _authenticate_service(
|
|
335
|
+
use_oauth21: bool,
|
|
336
|
+
service_name: str,
|
|
337
|
+
service_version: str,
|
|
338
|
+
tool_name: str,
|
|
339
|
+
user_google_email: str,
|
|
340
|
+
resolved_scopes: List[str],
|
|
341
|
+
mcp_session_id: Optional[str],
|
|
342
|
+
authenticated_user: Optional[str],
|
|
343
|
+
) -> Tuple[Any, str]:
|
|
344
|
+
"""
|
|
345
|
+
Authenticate and get Google service using appropriate OAuth version.
|
|
346
|
+
|
|
347
|
+
Returns:
|
|
348
|
+
Tuple of (service, actual_user_email)
|
|
349
|
+
"""
|
|
350
|
+
if is_service_account_enabled():
|
|
351
|
+
canonical_email = _get_configured_user_google_email()
|
|
352
|
+
if not canonical_email:
|
|
353
|
+
raise GoogleAuthenticationError(
|
|
354
|
+
"Service account mode requires USER_GOOGLE_EMAIL to be configured."
|
|
355
|
+
)
|
|
356
|
+
|
|
357
|
+
config = get_oauth_config()
|
|
358
|
+
target_email = user_google_email or canonical_email
|
|
359
|
+
_validate_dwd_domain(target_email, config)
|
|
360
|
+
if target_email.lower() != canonical_email.lower():
|
|
361
|
+
if not is_trust_gateway_identity():
|
|
362
|
+
raise GoogleAuthenticationError(
|
|
363
|
+
"DWD subjects other than USER_GOOGLE_EMAIL require "
|
|
364
|
+
"trusted-gateway authentication."
|
|
365
|
+
)
|
|
366
|
+
principal = await get_verified_gateway_principal()
|
|
367
|
+
if target_email.lower() != principal:
|
|
368
|
+
raise GoogleAuthenticationError(
|
|
369
|
+
"Requested DWD subject does not match the verified gateway principal."
|
|
370
|
+
)
|
|
371
|
+
target_email = principal
|
|
372
|
+
|
|
373
|
+
credentials = _get_service_account_credentials(
|
|
374
|
+
_widen_drive_scope_for_dwd(resolved_scopes, tool_name), target_email
|
|
375
|
+
)
|
|
376
|
+
service = build_google_service(service_name, service_version, credentials)
|
|
377
|
+
logger.info(
|
|
378
|
+
f"[{tool_name}] Authenticated {service_name} for "
|
|
379
|
+
f"{target_email} via service-account"
|
|
380
|
+
)
|
|
381
|
+
record_google_principal("service-account", target_email)
|
|
382
|
+
return service, target_email
|
|
383
|
+
|
|
384
|
+
if use_oauth21:
|
|
385
|
+
logger.debug(f"[{tool_name}] Using OAuth 2.1 flow")
|
|
386
|
+
auth_mode = "oauth2.1"
|
|
387
|
+
service, actual_user_email = await get_authenticated_google_service_oauth21(
|
|
388
|
+
service_name=service_name,
|
|
389
|
+
version=service_version,
|
|
390
|
+
tool_name=tool_name,
|
|
391
|
+
user_google_email=user_google_email,
|
|
392
|
+
required_scopes=resolved_scopes,
|
|
393
|
+
session_id=mcp_session_id,
|
|
394
|
+
auth_token_email=authenticated_user,
|
|
395
|
+
allow_recent_auth=False,
|
|
396
|
+
)
|
|
397
|
+
else:
|
|
398
|
+
logger.debug(f"[{tool_name}] Using legacy OAuth 2.0 flow")
|
|
399
|
+
auth_mode = "oauth2.0"
|
|
400
|
+
service, actual_user_email = await get_authenticated_google_service(
|
|
401
|
+
service_name=service_name,
|
|
402
|
+
version=service_version,
|
|
403
|
+
tool_name=tool_name,
|
|
404
|
+
user_google_email=user_google_email,
|
|
405
|
+
required_scopes=resolved_scopes,
|
|
406
|
+
session_id=mcp_session_id,
|
|
407
|
+
)
|
|
408
|
+
record_google_principal(auth_mode, actual_user_email)
|
|
409
|
+
return service, actual_user_email
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
async def get_authenticated_google_service_oauth21(
|
|
413
|
+
service_name: str,
|
|
414
|
+
version: str,
|
|
415
|
+
tool_name: str,
|
|
416
|
+
user_google_email: str,
|
|
417
|
+
required_scopes: List[str],
|
|
418
|
+
session_id: Optional[str] = None,
|
|
419
|
+
auth_token_email: Optional[str] = None,
|
|
420
|
+
allow_recent_auth: bool = False,
|
|
421
|
+
) -> tuple[Any, str]:
|
|
422
|
+
"""
|
|
423
|
+
OAuth 2.1 authentication using the session store with security validation.
|
|
424
|
+
"""
|
|
425
|
+
provider = get_auth_provider()
|
|
426
|
+
access_token = get_access_token()
|
|
427
|
+
|
|
428
|
+
if provider and access_token:
|
|
429
|
+
token_email = None
|
|
430
|
+
if getattr(access_token, "claims", None):
|
|
431
|
+
token_email = access_token.claims.get("email")
|
|
432
|
+
|
|
433
|
+
resolved_email = token_email or auth_token_email or user_google_email
|
|
434
|
+
if not resolved_email:
|
|
435
|
+
raise GoogleAuthenticationError(
|
|
436
|
+
"Authenticated user email could not be determined from access token."
|
|
437
|
+
)
|
|
438
|
+
|
|
439
|
+
if auth_token_email and token_email and token_email != auth_token_email:
|
|
440
|
+
raise GoogleAuthenticationError(
|
|
441
|
+
"Access token email does not match authenticated session context."
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
if token_email and user_google_email and token_email != user_google_email:
|
|
445
|
+
raise GoogleAuthenticationError(
|
|
446
|
+
f"Authenticated account {token_email} does not match requested user {user_google_email}."
|
|
447
|
+
)
|
|
448
|
+
|
|
449
|
+
credentials = await ensure_session_from_access_token(
|
|
450
|
+
access_token, resolved_email, session_id
|
|
451
|
+
)
|
|
452
|
+
if not credentials:
|
|
453
|
+
raise GoogleAuthenticationError(
|
|
454
|
+
"Unable to build Google credentials from authenticated access token."
|
|
455
|
+
)
|
|
456
|
+
|
|
457
|
+
scopes_available = set(credentials.scopes or [])
|
|
458
|
+
if not scopes_available and getattr(access_token, "scopes", None):
|
|
459
|
+
scopes_available = set(access_token.scopes)
|
|
460
|
+
|
|
461
|
+
if not has_required_scopes(scopes_available, required_scopes):
|
|
462
|
+
raise GoogleScopeError(
|
|
463
|
+
f"OAuth credentials lack required scopes. Need: {required_scopes}, Have: {sorted(scopes_available)}"
|
|
464
|
+
)
|
|
465
|
+
|
|
466
|
+
service = build_google_service(service_name, version, credentials)
|
|
467
|
+
logger.info(
|
|
468
|
+
f"[{tool_name}] Authenticated {service_name} for "
|
|
469
|
+
f"{resolved_email} via oauth2.1"
|
|
470
|
+
)
|
|
471
|
+
return service, resolved_email
|
|
472
|
+
|
|
473
|
+
store = get_oauth21_session_store()
|
|
474
|
+
|
|
475
|
+
# Use the validation method to ensure session can only access its own credentials
|
|
476
|
+
credentials = store.get_credentials_with_validation(
|
|
477
|
+
requested_user_email=user_google_email,
|
|
478
|
+
session_id=session_id,
|
|
479
|
+
auth_token_email=auth_token_email,
|
|
480
|
+
allow_recent_auth=allow_recent_auth,
|
|
481
|
+
)
|
|
482
|
+
|
|
483
|
+
if not credentials:
|
|
484
|
+
raise GoogleAuthenticationError(
|
|
485
|
+
f"Access denied: Cannot retrieve credentials for {user_google_email}. "
|
|
486
|
+
f"You can only access credentials for your authenticated account."
|
|
487
|
+
)
|
|
488
|
+
|
|
489
|
+
if not credentials.scopes:
|
|
490
|
+
scopes_available = set(required_scopes)
|
|
491
|
+
else:
|
|
492
|
+
scopes_available = set(credentials.scopes)
|
|
493
|
+
|
|
494
|
+
if not has_required_scopes(scopes_available, required_scopes):
|
|
495
|
+
raise GoogleScopeError(
|
|
496
|
+
f"OAuth 2.1 credentials lack required scopes. Need: {required_scopes}, Have: {sorted(scopes_available)}"
|
|
497
|
+
)
|
|
498
|
+
|
|
499
|
+
service = build_google_service(service_name, version, credentials)
|
|
500
|
+
logger.info(
|
|
501
|
+
f"[{tool_name}] Authenticated {service_name} for "
|
|
502
|
+
f"{user_google_email} via oauth2.1"
|
|
503
|
+
)
|
|
504
|
+
|
|
505
|
+
return service, user_google_email
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def _extract_oauth21_user_email(
|
|
509
|
+
authenticated_user: Optional[str], func_name: str
|
|
510
|
+
) -> str:
|
|
511
|
+
"""
|
|
512
|
+
Extract user email for OAuth 2.1 mode.
|
|
513
|
+
|
|
514
|
+
Args:
|
|
515
|
+
authenticated_user: The authenticated user from context
|
|
516
|
+
func_name: Name of the function being decorated (for error messages)
|
|
517
|
+
|
|
518
|
+
Returns:
|
|
519
|
+
User email string
|
|
520
|
+
|
|
521
|
+
Raises:
|
|
522
|
+
Exception: If no authenticated user found in OAuth 2.1 mode
|
|
523
|
+
"""
|
|
524
|
+
if not authenticated_user:
|
|
525
|
+
raise Exception(
|
|
526
|
+
f"OAuth 2.1 mode requires an authenticated user for {func_name}, but none was found."
|
|
527
|
+
)
|
|
528
|
+
return authenticated_user
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def _extract_managed_user_email(
|
|
532
|
+
authenticated_user: Optional[str],
|
|
533
|
+
auth_method: Optional[str],
|
|
534
|
+
func_name: str,
|
|
535
|
+
) -> str:
|
|
536
|
+
"""Resolve an email from the configured authoritative identity source."""
|
|
537
|
+
if is_trust_gateway_identity():
|
|
538
|
+
return require_gateway_principal(authenticated_user, auth_method)
|
|
539
|
+
return _extract_oauth21_user_email(authenticated_user, func_name)
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
def _extract_oauth20_user_email(
|
|
543
|
+
args: tuple, kwargs: dict, wrapper_sig: inspect.Signature
|
|
544
|
+
) -> str:
|
|
545
|
+
"""
|
|
546
|
+
Extract user email for OAuth 2.0 mode from function arguments.
|
|
547
|
+
|
|
548
|
+
Args:
|
|
549
|
+
args: Positional arguments passed to wrapper
|
|
550
|
+
kwargs: Keyword arguments passed to wrapper
|
|
551
|
+
wrapper_sig: Function signature for parameter binding
|
|
552
|
+
|
|
553
|
+
Returns:
|
|
554
|
+
User email string
|
|
555
|
+
|
|
556
|
+
Raises:
|
|
557
|
+
Exception: If user_google_email parameter not found
|
|
558
|
+
"""
|
|
559
|
+
# Use partial binding so single-user mode can omit user_google_email and
|
|
560
|
+
# let the configured env-var default supply it.
|
|
561
|
+
bound_args = wrapper_sig.bind_partial(*args, **kwargs)
|
|
562
|
+
bound_args.apply_defaults()
|
|
563
|
+
|
|
564
|
+
user_google_email = bound_args.arguments.get("user_google_email")
|
|
565
|
+
if not user_google_email:
|
|
566
|
+
# Fall back to USER_GOOGLE_EMAIL env var for single-user / self-hosted mode.
|
|
567
|
+
# This allows callers (agents) to omit the parameter when a default is configured.
|
|
568
|
+
user_google_email = _get_configured_user_google_email()
|
|
569
|
+
if not user_google_email:
|
|
570
|
+
raise Exception("'user_google_email' parameter is required but was not found.")
|
|
571
|
+
# Ensure the resolved email is visible to the original function via kwargs
|
|
572
|
+
kwargs["user_google_email"] = user_google_email
|
|
573
|
+
return user_google_email
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def _remove_user_email_arg_from_docstring(docstring: str) -> str:
|
|
577
|
+
"""
|
|
578
|
+
Remove user_google_email parameter documentation from docstring.
|
|
579
|
+
|
|
580
|
+
Args:
|
|
581
|
+
docstring: The original function docstring
|
|
582
|
+
|
|
583
|
+
Returns:
|
|
584
|
+
Modified docstring with user_google_email parameter removed
|
|
585
|
+
"""
|
|
586
|
+
if not docstring:
|
|
587
|
+
return docstring
|
|
588
|
+
|
|
589
|
+
# Pattern to match user_google_email parameter documentation
|
|
590
|
+
# Handles various formats like:
|
|
591
|
+
# - user_google_email (str): The user's Google email address. Required.
|
|
592
|
+
# - user_google_email: Description
|
|
593
|
+
# - user_google_email (str) - Description
|
|
594
|
+
patterns = [
|
|
595
|
+
r"^\s*user_google_email\s*\([^)]*\)\s*:\s*[^\n]*\.?\s*(?:Required\.?)?\s*\n",
|
|
596
|
+
r"^\s*user_google_email\s*:\s*[^\n]*\n",
|
|
597
|
+
r"^\s*user_google_email\s*\([^)]*\)\s*-\s*[^\n]*\n",
|
|
598
|
+
]
|
|
599
|
+
|
|
600
|
+
modified_docstring = docstring
|
|
601
|
+
for pattern in patterns:
|
|
602
|
+
modified_docstring = re.sub(pattern, "", modified_docstring, flags=re.MULTILINE)
|
|
603
|
+
|
|
604
|
+
# Clean up any sequence of 3 or more newlines that might have been created
|
|
605
|
+
modified_docstring = re.sub(r"\n{3,}", "\n\n", modified_docstring)
|
|
606
|
+
return modified_docstring
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
# Service configuration mapping
|
|
610
|
+
SERVICE_CONFIGS = {
|
|
611
|
+
"gmail": {"service": "gmail", "version": "v1"},
|
|
612
|
+
"drive": {"service": "drive", "version": "v3"},
|
|
613
|
+
"calendar": {"service": "calendar", "version": "v3"},
|
|
614
|
+
"docs": {"service": "docs", "version": "v1"},
|
|
615
|
+
"sheets": {"service": "sheets", "version": "v4"},
|
|
616
|
+
"chat": {"service": "chat", "version": "v1"},
|
|
617
|
+
"forms": {"service": "forms", "version": "v1"},
|
|
618
|
+
"slides": {"service": "slides", "version": "v1"},
|
|
619
|
+
"tasks": {"service": "tasks", "version": "v1"},
|
|
620
|
+
"people": {"service": "people", "version": "v1"},
|
|
621
|
+
"customsearch": {"service": "customsearch", "version": "v1"},
|
|
622
|
+
"script": {"service": "script", "version": "v1"},
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
# Scope group definitions for easy reference
|
|
627
|
+
SCOPE_GROUPS = {
|
|
628
|
+
# Gmail scopes
|
|
629
|
+
"gmail_read": GMAIL_READONLY_SCOPE,
|
|
630
|
+
"gmail_send": GMAIL_SEND_SCOPE,
|
|
631
|
+
"gmail_compose": GMAIL_COMPOSE_SCOPE,
|
|
632
|
+
"gmail_modify": GMAIL_MODIFY_SCOPE,
|
|
633
|
+
"gmail_labels": GMAIL_LABELS_SCOPE,
|
|
634
|
+
"gmail_settings_basic": GMAIL_SETTINGS_BASIC_SCOPE,
|
|
635
|
+
# Drive scopes
|
|
636
|
+
"drive": DRIVE_SCOPE,
|
|
637
|
+
"drive_full": DRIVE_SCOPE,
|
|
638
|
+
"drive_read": DRIVE_READONLY_SCOPE,
|
|
639
|
+
"drive_file": DRIVE_FILE_SCOPE,
|
|
640
|
+
# Docs scopes
|
|
641
|
+
"docs_read": DOCS_READONLY_SCOPE,
|
|
642
|
+
"docs_write": DOCS_WRITE_SCOPE,
|
|
643
|
+
# Calendar scopes
|
|
644
|
+
"calendar": CALENDAR_SCOPE,
|
|
645
|
+
"calendar_read": CALENDAR_READONLY_SCOPE,
|
|
646
|
+
"calendar_events": CALENDAR_EVENTS_SCOPE,
|
|
647
|
+
# Sheets scopes
|
|
648
|
+
"sheets_read": SHEETS_READONLY_SCOPE,
|
|
649
|
+
"sheets_write": SHEETS_WRITE_SCOPE,
|
|
650
|
+
# Chat scopes
|
|
651
|
+
"chat_read": CHAT_READONLY_SCOPE,
|
|
652
|
+
"chat_write": CHAT_WRITE_SCOPE,
|
|
653
|
+
"chat_spaces": CHAT_SPACES_SCOPE,
|
|
654
|
+
"chat_spaces_readonly": CHAT_SPACES_READONLY_SCOPE,
|
|
655
|
+
# Forms scopes
|
|
656
|
+
"forms": FORMS_BODY_SCOPE,
|
|
657
|
+
"forms_read": FORMS_BODY_READONLY_SCOPE,
|
|
658
|
+
"forms_responses_read": FORMS_RESPONSES_READONLY_SCOPE,
|
|
659
|
+
# Slides scopes
|
|
660
|
+
"slides": SLIDES_SCOPE,
|
|
661
|
+
"slides_read": SLIDES_READONLY_SCOPE,
|
|
662
|
+
# Tasks scopes
|
|
663
|
+
"tasks": TASKS_SCOPE,
|
|
664
|
+
"tasks_read": TASKS_READONLY_SCOPE,
|
|
665
|
+
# Contacts scopes
|
|
666
|
+
"contacts": CONTACTS_SCOPE,
|
|
667
|
+
"contacts_read": CONTACTS_READONLY_SCOPE,
|
|
668
|
+
# Custom Search scope
|
|
669
|
+
"customsearch": CUSTOM_SEARCH_SCOPE,
|
|
670
|
+
# Apps Script scopes
|
|
671
|
+
"script_readonly": SCRIPT_PROJECTS_READONLY_SCOPE,
|
|
672
|
+
"script_projects": SCRIPT_PROJECTS_SCOPE,
|
|
673
|
+
"script_full": SCRIPT_PROJECTS_SCOPE,
|
|
674
|
+
"script_deployments": SCRIPT_DEPLOYMENTS_SCOPE,
|
|
675
|
+
"script_deployments_readonly": SCRIPT_DEPLOYMENTS_READONLY_SCOPE,
|
|
676
|
+
"script_run": SCRIPT_EXTERNAL_REQUEST_SCOPE,
|
|
677
|
+
"script_scriptapp": SCRIPT_SCRIPTAPP_SCOPE,
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
def _resolve_scopes(scopes: Union[str, List[str]]) -> List[str]:
|
|
682
|
+
"""Resolve scope names to actual scope URLs."""
|
|
683
|
+
if isinstance(scopes, str):
|
|
684
|
+
if scopes in SCOPE_GROUPS:
|
|
685
|
+
return [SCOPE_GROUPS[scopes]]
|
|
686
|
+
else:
|
|
687
|
+
return [scopes]
|
|
688
|
+
|
|
689
|
+
resolved = []
|
|
690
|
+
for scope in scopes:
|
|
691
|
+
if scope in SCOPE_GROUPS:
|
|
692
|
+
resolved.append(SCOPE_GROUPS[scope])
|
|
693
|
+
else:
|
|
694
|
+
resolved.append(scope)
|
|
695
|
+
return resolved
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
def _handle_token_refresh_error(
|
|
699
|
+
error: RefreshError, user_email: str, service_name: str
|
|
700
|
+
) -> str:
|
|
701
|
+
"""
|
|
702
|
+
Handle token refresh errors gracefully, particularly expired/revoked tokens.
|
|
703
|
+
|
|
704
|
+
Args:
|
|
705
|
+
error: The RefreshError that occurred
|
|
706
|
+
user_email: User's email address
|
|
707
|
+
service_name: Name of the Google service
|
|
708
|
+
|
|
709
|
+
Returns:
|
|
710
|
+
A user-friendly error message with instructions for reauthentication
|
|
711
|
+
"""
|
|
712
|
+
error_str = str(error)
|
|
713
|
+
|
|
714
|
+
if (
|
|
715
|
+
"invalid_grant" in error_str.lower()
|
|
716
|
+
or "expired or revoked" in error_str.lower()
|
|
717
|
+
):
|
|
718
|
+
logger.warning(
|
|
719
|
+
f"Token expired or revoked for user {user_email} accessing {service_name}"
|
|
720
|
+
)
|
|
721
|
+
|
|
722
|
+
service_display_name = f"Google {service_name.title()}"
|
|
723
|
+
if is_oauth21_enabled():
|
|
724
|
+
if is_external_oauth21_provider():
|
|
725
|
+
oauth21_step = (
|
|
726
|
+
"Provide a valid OAuth 2.1 bearer token in the Authorization header"
|
|
727
|
+
)
|
|
728
|
+
else:
|
|
729
|
+
oauth21_step = "Sign in through your MCP client's OAuth 2.1 flow"
|
|
730
|
+
|
|
731
|
+
return (
|
|
732
|
+
f"**Authentication Required: Token Expired/Revoked for {service_display_name}**\n\n"
|
|
733
|
+
f"Your Google authentication token for {user_email} has expired or been revoked. "
|
|
734
|
+
f"This commonly happens when:\n"
|
|
735
|
+
f"- The token has been unused for an extended period\n"
|
|
736
|
+
f"- You've changed your Google account password\n"
|
|
737
|
+
f"- You've revoked access to the application\n\n"
|
|
738
|
+
f"**To resolve this, please:**\n"
|
|
739
|
+
f"1. {oauth21_step}\n"
|
|
740
|
+
f"2. Retry your original command\n\n"
|
|
741
|
+
f"The application will automatically use the new credentials once authentication is complete."
|
|
742
|
+
)
|
|
743
|
+
|
|
744
|
+
return (
|
|
745
|
+
f"**Authentication Required: Token Expired/Revoked for {service_display_name}**\n\n"
|
|
746
|
+
f"Your Google authentication token for {user_email} has expired or been revoked. "
|
|
747
|
+
f"This commonly happens when:\n"
|
|
748
|
+
f"- The token has been unused for an extended period\n"
|
|
749
|
+
f"- You've changed your Google account password\n"
|
|
750
|
+
f"- You've revoked access to the application\n\n"
|
|
751
|
+
f"**To resolve this, please:**\n"
|
|
752
|
+
f"1. Run `start_google_auth` with your email ({user_email}) and service_name='{service_display_name}'\n"
|
|
753
|
+
f"2. Complete the authentication flow in your browser\n"
|
|
754
|
+
f"3. Retry your original command\n\n"
|
|
755
|
+
f"The application will automatically use the new credentials once authentication is complete."
|
|
756
|
+
)
|
|
757
|
+
else:
|
|
758
|
+
# Handle other types of refresh errors
|
|
759
|
+
logger.error(f"Unexpected refresh error for user {user_email}: {error}")
|
|
760
|
+
if is_oauth21_enabled():
|
|
761
|
+
if is_external_oauth21_provider():
|
|
762
|
+
return (
|
|
763
|
+
f"Authentication error occurred for {user_email}. "
|
|
764
|
+
"Please provide a valid OAuth 2.1 bearer token and retry."
|
|
765
|
+
)
|
|
766
|
+
return (
|
|
767
|
+
f"Authentication error occurred for {user_email}. "
|
|
768
|
+
"Please sign in via your MCP client's OAuth 2.1 flow and retry."
|
|
769
|
+
)
|
|
770
|
+
return (
|
|
771
|
+
f"Authentication error occurred for {user_email}. "
|
|
772
|
+
f"Please try running `start_google_auth` with your email and the appropriate service name to reauthenticate."
|
|
773
|
+
)
|
|
774
|
+
|
|
775
|
+
|
|
776
|
+
def require_google_service(
|
|
777
|
+
service_type: str,
|
|
778
|
+
scopes: Union[str, List[str]],
|
|
779
|
+
version: Optional[str] = None,
|
|
780
|
+
):
|
|
781
|
+
"""
|
|
782
|
+
Decorator that automatically handles Google service authentication and injection.
|
|
783
|
+
|
|
784
|
+
Args:
|
|
785
|
+
service_type: Type of Google service ("gmail", "drive", "calendar", etc.)
|
|
786
|
+
scopes: Required scopes (can be scope group names or actual URLs)
|
|
787
|
+
version: Service version (defaults to standard version for service type)
|
|
788
|
+
|
|
789
|
+
Usage:
|
|
790
|
+
@require_google_service("gmail", "gmail_read")
|
|
791
|
+
async def search_messages(service, user_google_email: str, query: str):
|
|
792
|
+
# service parameter is automatically injected
|
|
793
|
+
# Original authentication logic is handled automatically
|
|
794
|
+
"""
|
|
795
|
+
|
|
796
|
+
def decorator(func: Callable) -> Callable:
|
|
797
|
+
original_sig = inspect.signature(func)
|
|
798
|
+
params = list(original_sig.parameters.values())
|
|
799
|
+
|
|
800
|
+
# The decorated function must have 'service' as its first parameter.
|
|
801
|
+
if not params or params[0].name != "service":
|
|
802
|
+
raise TypeError(
|
|
803
|
+
f"Function '{func.__name__}' decorated with @require_google_service "
|
|
804
|
+
"must have 'service' as its first parameter."
|
|
805
|
+
)
|
|
806
|
+
|
|
807
|
+
# Create a new signature for the wrapper that excludes the 'service' parameter.
|
|
808
|
+
# In OAuth 2.1 mode, also exclude 'user_google_email' since it's automatically determined.
|
|
809
|
+
if _user_email_is_managed():
|
|
810
|
+
# Remove both 'service' and 'user_google_email' parameters
|
|
811
|
+
filtered_params = [p for p in params[1:] if p.name != "user_google_email"]
|
|
812
|
+
wrapper_sig = original_sig.replace(parameters=filtered_params)
|
|
813
|
+
else:
|
|
814
|
+
# Only remove 'service' parameter for OAuth 2.0 mode.
|
|
815
|
+
# user_google_email stays required in the signature; call_tool() in
|
|
816
|
+
# SecureFastMCP injects the env-var default before pydantic validates.
|
|
817
|
+
wrapper_sig = original_sig.replace(parameters=params[1:])
|
|
818
|
+
|
|
819
|
+
@wraps(func)
|
|
820
|
+
async def wrapper(*args, **kwargs):
|
|
821
|
+
# Note: `args` and `kwargs` are now the arguments for the *wrapper*,
|
|
822
|
+
# which does not include 'service'.
|
|
823
|
+
|
|
824
|
+
# Get authentication context early to determine OAuth mode
|
|
825
|
+
authenticated_user, auth_method, mcp_session_id = await _get_auth_context(
|
|
826
|
+
func.__name__
|
|
827
|
+
)
|
|
828
|
+
|
|
829
|
+
# Extract user_google_email based on OAuth mode
|
|
830
|
+
if _user_email_is_managed():
|
|
831
|
+
user_google_email = _extract_managed_user_email(
|
|
832
|
+
authenticated_user,
|
|
833
|
+
auth_method,
|
|
834
|
+
func.__name__,
|
|
835
|
+
)
|
|
836
|
+
else:
|
|
837
|
+
user_google_email = _extract_oauth20_user_email(
|
|
838
|
+
args, kwargs, wrapper_sig
|
|
839
|
+
)
|
|
840
|
+
|
|
841
|
+
# Get service configuration from the decorator's arguments
|
|
842
|
+
if service_type not in SERVICE_CONFIGS:
|
|
843
|
+
raise Exception(f"Unknown service type: {service_type}")
|
|
844
|
+
|
|
845
|
+
config = SERVICE_CONFIGS[service_type]
|
|
846
|
+
service_name = config["service"]
|
|
847
|
+
service_version = version or config["version"]
|
|
848
|
+
|
|
849
|
+
# Resolve scopes
|
|
850
|
+
resolved_scopes = _resolve_scopes(scopes)
|
|
851
|
+
|
|
852
|
+
try:
|
|
853
|
+
tool_name = func.__name__
|
|
854
|
+
|
|
855
|
+
# Log requested user identity for audit visibility.
|
|
856
|
+
logger.info(
|
|
857
|
+
f"[{tool_name}] {user_google_email} -> "
|
|
858
|
+
f"{service_name}/{service_version}"
|
|
859
|
+
)
|
|
860
|
+
|
|
861
|
+
# Detect OAuth version
|
|
862
|
+
use_oauth21 = _detect_oauth_version(
|
|
863
|
+
authenticated_user, mcp_session_id, tool_name
|
|
864
|
+
)
|
|
865
|
+
|
|
866
|
+
# In OAuth 2.1 mode, user_google_email is already set to authenticated_user
|
|
867
|
+
# In OAuth 2.0 mode, we may need to override it
|
|
868
|
+
if not _user_email_is_managed():
|
|
869
|
+
wrapper_params = list(wrapper_sig.parameters.keys())
|
|
870
|
+
user_google_email, args = _override_oauth21_user_email(
|
|
871
|
+
use_oauth21,
|
|
872
|
+
authenticated_user,
|
|
873
|
+
user_google_email,
|
|
874
|
+
args,
|
|
875
|
+
kwargs,
|
|
876
|
+
wrapper_params,
|
|
877
|
+
tool_name,
|
|
878
|
+
)
|
|
879
|
+
|
|
880
|
+
# Authenticate service
|
|
881
|
+
service, actual_user_email = await _authenticate_service(
|
|
882
|
+
use_oauth21,
|
|
883
|
+
service_name,
|
|
884
|
+
service_version,
|
|
885
|
+
tool_name,
|
|
886
|
+
user_google_email,
|
|
887
|
+
resolved_scopes,
|
|
888
|
+
mcp_session_id,
|
|
889
|
+
authenticated_user,
|
|
890
|
+
)
|
|
891
|
+
except GoogleScopeError as e:
|
|
892
|
+
logger.info(
|
|
893
|
+
"[%s] Missing %s permissions: %s", tool_name, service_name, e
|
|
894
|
+
)
|
|
895
|
+
return _missing_scope_message(service_name, e)
|
|
896
|
+
except GoogleAuthenticationError as e:
|
|
897
|
+
logger.error(
|
|
898
|
+
f"[{tool_name}] Auth failed for {user_google_email} | "
|
|
899
|
+
f"{service_name}/{service_version} | "
|
|
900
|
+
f"method={auth_method or 'none'} | {e}"
|
|
901
|
+
)
|
|
902
|
+
# Re-raise the original error without wrapping it
|
|
903
|
+
raise
|
|
904
|
+
|
|
905
|
+
try:
|
|
906
|
+
# In OAuth 2.1 mode, we need to add user_google_email to kwargs since it was removed from signature
|
|
907
|
+
if _user_email_is_managed():
|
|
908
|
+
kwargs["user_google_email"] = user_google_email
|
|
909
|
+
|
|
910
|
+
# Prepend the fetched service object to the original arguments
|
|
911
|
+
with recycling(service):
|
|
912
|
+
return await func(service, *args, **kwargs)
|
|
913
|
+
except RefreshError as e:
|
|
914
|
+
error_message = _handle_token_refresh_error(
|
|
915
|
+
e, actual_user_email, service_name
|
|
916
|
+
)
|
|
917
|
+
raise GoogleAuthenticationError(error_message)
|
|
918
|
+
finally:
|
|
919
|
+
del service
|
|
920
|
+
_release_google_service_cycles()
|
|
921
|
+
|
|
922
|
+
# Set the wrapper's signature to the one without 'service'
|
|
923
|
+
wrapper.__signature__ = wrapper_sig
|
|
924
|
+
|
|
925
|
+
# Conditionally modify docstring to remove user_google_email parameter documentation
|
|
926
|
+
if _user_email_is_managed():
|
|
927
|
+
logger.debug(
|
|
928
|
+
"OAuth 2.1 mode enabled, removing user_google_email from docstring"
|
|
929
|
+
)
|
|
930
|
+
if func.__doc__:
|
|
931
|
+
wrapper.__doc__ = _remove_user_email_arg_from_docstring(func.__doc__)
|
|
932
|
+
|
|
933
|
+
# Attach required scopes to the wrapper for tool filtering
|
|
934
|
+
wrapper._required_google_scopes = _resolve_scopes(scopes)
|
|
935
|
+
|
|
936
|
+
return wrapper
|
|
937
|
+
|
|
938
|
+
return decorator
|
|
939
|
+
|
|
940
|
+
|
|
941
|
+
def require_multiple_services(service_configs: List[Dict[str, Any]]):
|
|
942
|
+
"""
|
|
943
|
+
Decorator for functions that need multiple Google services.
|
|
944
|
+
|
|
945
|
+
Args:
|
|
946
|
+
service_configs: List of service configurations, each containing:
|
|
947
|
+
- service_type: Type of service
|
|
948
|
+
- scopes: Required scopes
|
|
949
|
+
- param_name: Name to inject service as (e.g., 'drive_service', 'docs_service')
|
|
950
|
+
- version: Optional version override
|
|
951
|
+
|
|
952
|
+
Usage:
|
|
953
|
+
@require_multiple_services([
|
|
954
|
+
{"service_type": "drive", "scopes": "drive_read", "param_name": "drive_service"},
|
|
955
|
+
{"service_type": "docs", "scopes": "docs_read", "param_name": "docs_service"}
|
|
956
|
+
])
|
|
957
|
+
async def get_doc_with_metadata(drive_service, docs_service, user_google_email: str, doc_id: str):
|
|
958
|
+
# Both services are automatically injected
|
|
959
|
+
"""
|
|
960
|
+
|
|
961
|
+
def decorator(func: Callable) -> Callable:
|
|
962
|
+
original_sig = inspect.signature(func)
|
|
963
|
+
|
|
964
|
+
service_param_names = {config["param_name"] for config in service_configs}
|
|
965
|
+
params = list(original_sig.parameters.values())
|
|
966
|
+
|
|
967
|
+
# Remove injected service params from the wrapper signature; drop user_google_email only for OAuth 2.1.
|
|
968
|
+
filtered_params = [p for p in params if p.name not in service_param_names]
|
|
969
|
+
if _user_email_is_managed():
|
|
970
|
+
filtered_params = [
|
|
971
|
+
p for p in filtered_params if p.name != "user_google_email"
|
|
972
|
+
]
|
|
973
|
+
|
|
974
|
+
wrapper_sig = original_sig.replace(parameters=filtered_params)
|
|
975
|
+
wrapper_param_names = [p.name for p in filtered_params]
|
|
976
|
+
|
|
977
|
+
@wraps(func)
|
|
978
|
+
async def wrapper(*args, **kwargs):
|
|
979
|
+
# Get authentication context early
|
|
980
|
+
tool_name = func.__name__
|
|
981
|
+
authenticated_user, auth_method, mcp_session_id = await _get_auth_context(
|
|
982
|
+
tool_name
|
|
983
|
+
)
|
|
984
|
+
|
|
985
|
+
# Extract user_google_email based on OAuth mode
|
|
986
|
+
if _user_email_is_managed():
|
|
987
|
+
user_google_email = _extract_managed_user_email(
|
|
988
|
+
authenticated_user,
|
|
989
|
+
auth_method,
|
|
990
|
+
tool_name,
|
|
991
|
+
)
|
|
992
|
+
else:
|
|
993
|
+
user_google_email = _extract_oauth20_user_email(
|
|
994
|
+
args, kwargs, wrapper_sig
|
|
995
|
+
)
|
|
996
|
+
|
|
997
|
+
# Log requested user identity for audit visibility.
|
|
998
|
+
services_desc = ", ".join(c["service_type"] for c in service_configs)
|
|
999
|
+
logger.info(f"[{tool_name}] {user_google_email} -> [{services_desc}]")
|
|
1000
|
+
|
|
1001
|
+
services_created = False
|
|
1002
|
+
try:
|
|
1003
|
+
# Authenticate all services
|
|
1004
|
+
with ExitStack() as stack:
|
|
1005
|
+
for config in service_configs:
|
|
1006
|
+
service_type = config["service_type"]
|
|
1007
|
+
scopes = config["scopes"]
|
|
1008
|
+
param_name = config["param_name"]
|
|
1009
|
+
version = config.get("version")
|
|
1010
|
+
|
|
1011
|
+
if service_type not in SERVICE_CONFIGS:
|
|
1012
|
+
raise Exception(f"Unknown service type: {service_type}")
|
|
1013
|
+
|
|
1014
|
+
service_config = SERVICE_CONFIGS[service_type]
|
|
1015
|
+
service_name = service_config["service"]
|
|
1016
|
+
service_version = version or service_config["version"]
|
|
1017
|
+
resolved_scopes = _resolve_scopes(scopes)
|
|
1018
|
+
|
|
1019
|
+
try:
|
|
1020
|
+
# Detect OAuth version (simplified for multiple services)
|
|
1021
|
+
use_oauth21 = (
|
|
1022
|
+
is_oauth21_enabled() and authenticated_user is not None
|
|
1023
|
+
)
|
|
1024
|
+
|
|
1025
|
+
# In OAuth 2.0 mode, we may need to override user_google_email
|
|
1026
|
+
if not _user_email_is_managed():
|
|
1027
|
+
user_google_email, args = _override_oauth21_user_email(
|
|
1028
|
+
use_oauth21,
|
|
1029
|
+
authenticated_user,
|
|
1030
|
+
user_google_email,
|
|
1031
|
+
args,
|
|
1032
|
+
kwargs,
|
|
1033
|
+
wrapper_param_names,
|
|
1034
|
+
tool_name,
|
|
1035
|
+
service_type,
|
|
1036
|
+
)
|
|
1037
|
+
|
|
1038
|
+
# Authenticate service
|
|
1039
|
+
service, _ = await _authenticate_service(
|
|
1040
|
+
use_oauth21,
|
|
1041
|
+
service_name,
|
|
1042
|
+
service_version,
|
|
1043
|
+
tool_name,
|
|
1044
|
+
user_google_email,
|
|
1045
|
+
resolved_scopes,
|
|
1046
|
+
mcp_session_id,
|
|
1047
|
+
authenticated_user,
|
|
1048
|
+
)
|
|
1049
|
+
|
|
1050
|
+
# Inject service with specified parameter name
|
|
1051
|
+
kwargs[param_name] = service
|
|
1052
|
+
stack.enter_context(recycling(service))
|
|
1053
|
+
services_created = True
|
|
1054
|
+
|
|
1055
|
+
except GoogleScopeError as e:
|
|
1056
|
+
logger.info(
|
|
1057
|
+
"[%s] Missing %s permissions: %s",
|
|
1058
|
+
tool_name,
|
|
1059
|
+
service_name,
|
|
1060
|
+
e,
|
|
1061
|
+
)
|
|
1062
|
+
return _missing_scope_message(service_name, e)
|
|
1063
|
+
except GoogleAuthenticationError as e:
|
|
1064
|
+
logger.error(
|
|
1065
|
+
f"[{tool_name}] Auth failed for {user_google_email} | "
|
|
1066
|
+
f"{service_name}/{service_version} | "
|
|
1067
|
+
f"method={auth_method or 'none'} | {e}"
|
|
1068
|
+
)
|
|
1069
|
+
# Re-raise the original error without wrapping it
|
|
1070
|
+
raise
|
|
1071
|
+
|
|
1072
|
+
# Call the original function with refresh error handling
|
|
1073
|
+
try:
|
|
1074
|
+
# In OAuth 2.1 mode, we need to add user_google_email to kwargs since it was removed from signature
|
|
1075
|
+
if _user_email_is_managed():
|
|
1076
|
+
kwargs["user_google_email"] = user_google_email
|
|
1077
|
+
|
|
1078
|
+
return await func(*args, **kwargs)
|
|
1079
|
+
except RefreshError as e:
|
|
1080
|
+
# Handle token refresh errors gracefully
|
|
1081
|
+
error_message = _handle_token_refresh_error(
|
|
1082
|
+
e, user_google_email, "Multiple Services"
|
|
1083
|
+
)
|
|
1084
|
+
raise GoogleAuthenticationError(error_message)
|
|
1085
|
+
finally:
|
|
1086
|
+
if services_created:
|
|
1087
|
+
del service, kwargs
|
|
1088
|
+
_release_google_service_cycles()
|
|
1089
|
+
|
|
1090
|
+
# Set the wrapper's signature
|
|
1091
|
+
wrapper.__signature__ = wrapper_sig
|
|
1092
|
+
|
|
1093
|
+
# Conditionally modify docstring to remove user_google_email parameter documentation
|
|
1094
|
+
if _user_email_is_managed():
|
|
1095
|
+
logger.debug(
|
|
1096
|
+
"OAuth 2.1 mode enabled, removing user_google_email from docstring"
|
|
1097
|
+
)
|
|
1098
|
+
if func.__doc__:
|
|
1099
|
+
wrapper.__doc__ = _remove_user_email_arg_from_docstring(func.__doc__)
|
|
1100
|
+
|
|
1101
|
+
# Attach all required scopes to the wrapper for tool filtering
|
|
1102
|
+
all_scopes = []
|
|
1103
|
+
for config in service_configs:
|
|
1104
|
+
all_scopes.extend(_resolve_scopes(config["scopes"]))
|
|
1105
|
+
wrapper._required_google_scopes = all_scopes
|
|
1106
|
+
|
|
1107
|
+
return wrapper
|
|
1108
|
+
|
|
1109
|
+
return decorator
|