@mutallip/google-workspace-mcp 0.0.0-stage → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +353 -2
- package/README.npm.md +28 -0
- package/auth/__init__.py +1 -0
- package/auth/auth_info_middleware.py +419 -0
- package/auth/client_secrets.py +76 -0
- package/auth/credential_store.py +598 -0
- package/auth/external_oauth_provider.py +369 -0
- package/auth/gateway_identity.py +164 -0
- package/auth/google_auth.py +1550 -0
- package/auth/google_oauth_provider.py +20 -0
- package/auth/mcp_session_middleware.py +95 -0
- package/auth/oauth21_session_store.py +1332 -0
- package/auth/oauth_callback_server.py +466 -0
- package/auth/oauth_config.py +693 -0
- package/auth/oauth_proxy_config.py +122 -0
- package/auth/oauth_responses.py +230 -0
- package/auth/oauth_types.py +92 -0
- package/auth/permissions.py +330 -0
- package/auth/port_resolver.py +153 -0
- package/auth/request_identity.py +89 -0
- package/auth/scopes.py +369 -0
- package/auth/service_decorator.py +1109 -0
- package/bin/google-workspace-mcp.cjs +123 -0
- package/core/__init__.py +1 -0
- package/core/api_enablement.py +108 -0
- package/core/attachment_storage.py +496 -0
- package/core/camel_case_middleware.py +98 -0
- package/core/cli.py +161 -0
- package/core/comments.py +609 -0
- package/core/config.py +57 -0
- package/core/context.py +43 -0
- package/core/file_limits.py +632 -0
- package/core/gcs_attachment_storage.py +253 -0
- package/core/http_utils.py +339 -0
- package/core/log_formatter.py +270 -0
- package/core/portable_schema_middleware.py +67 -0
- package/core/server.py +1192 -0
- package/core/startup_ui.py +239 -0
- package/core/storage.py +23 -0
- package/core/telemetry.py +194 -0
- package/core/tool_descriptions.py +19 -0
- package/core/tool_registry.py +311 -0
- package/core/tool_tier_loader.py +197 -0
- package/core/tool_tiers.yaml +179 -0
- package/core/toolset_header_middleware.py +67 -0
- package/core/utils.py +1537 -0
- package/core/valkey_storage.py +271 -0
- package/core/warning_filters.py +19 -0
- package/fastmcp_server.py +198 -0
- package/gappsscript/README.md +512 -0
- package/gappsscript/TESTING.md +254 -0
- package/gappsscript/__init__.py +0 -0
- package/gappsscript/apps_script_tools.py +1940 -0
- package/gcalendar/__init__.py +1 -0
- package/gcalendar/calendar_helpers.py +1323 -0
- package/gcalendar/calendar_tools.py +2252 -0
- package/gchat/__init__.py +7 -0
- package/gchat/chat_helpers.py +410 -0
- package/gchat/chat_tools.py +798 -0
- package/gcontacts/__init__.py +1 -0
- package/gcontacts/contacts_helpers.py +765 -0
- package/gcontacts/contacts_tools.py +1685 -0
- package/gdocs/__init__.py +0 -0
- package/gdocs/docs_anchors.py +163 -0
- package/gdocs/docs_comments.py +89 -0
- package/gdocs/docs_helpers.py +2201 -0
- package/gdocs/docs_links.py +87 -0
- package/gdocs/docs_markdown.py +828 -0
- package/gdocs/docs_markdown_writer.py +592 -0
- package/gdocs/docs_plain_text.py +463 -0
- package/gdocs/docs_structure.py +621 -0
- package/gdocs/docs_tables.py +425 -0
- package/gdocs/docs_tools.py +3300 -0
- package/gdocs/managers/__init__.py +18 -0
- package/gdocs/managers/batch_operation_manager.py +1694 -0
- package/gdocs/managers/header_footer_manager.py +526 -0
- package/gdocs/managers/table_operation_manager.py +488 -0
- package/gdocs/managers/validation_manager.py +1504 -0
- package/gdocs/operation_schemas.py +594 -0
- package/gdrive/__init__.py +0 -0
- package/gdrive/drive_helpers.py +1738 -0
- package/gdrive/drive_tools.py +3085 -0
- package/gforms/__init__.py +3 -0
- package/gforms/forms_tools.py +575 -0
- package/gmail/__init__.py +1 -0
- package/gmail/gmail_helpers.py +2107 -0
- package/gmail/gmail_tools.py +4895 -0
- package/gmail/gmail_web_mime.py +441 -0
- package/gsearch/__init__.py +0 -0
- package/gsearch/search_tools.py +253 -0
- package/gsheets/__init__.py +31 -0
- package/gsheets/sheets_helpers.py +2236 -0
- package/gsheets/sheets_tools.py +3280 -0
- package/gslides/__init__.py +0 -0
- package/gslides/slides_digest.py +390 -0
- package/gslides/slides_helpers.py +392 -0
- package/gslides/slides_markup.py +770 -0
- package/gslides/slides_tools.py +376 -0
- package/gtasks/__init__.py +5 -0
- package/gtasks/tasks_tools.py +936 -0
- package/main.py +1170 -0
- package/package.json +43 -4
- package/pyproject.toml +173 -0
- package/uv.lock +2504 -0
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"""Valkey-backed storage for the FastMCP OAuth proxy (requires the ``valkey`` extra)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import functools
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
10
|
+
from typing import TYPE_CHECKING, TypeVar
|
|
11
|
+
|
|
12
|
+
from glide import Logger as GlideLogger, LogLevel
|
|
13
|
+
from glide.glide_client import GlideClient
|
|
14
|
+
from glide_shared.config import (
|
|
15
|
+
AdvancedGlideClientConfiguration,
|
|
16
|
+
GlideClientConfiguration,
|
|
17
|
+
NodeAddress,
|
|
18
|
+
ServerCredentials,
|
|
19
|
+
)
|
|
20
|
+
from glide_shared.exceptions import (
|
|
21
|
+
ClosingError,
|
|
22
|
+
ConnectionError as GlideConnectionError,
|
|
23
|
+
)
|
|
24
|
+
from key_value.aio.stores.valkey import ValkeyStore
|
|
25
|
+
|
|
26
|
+
if TYPE_CHECKING:
|
|
27
|
+
from key_value.aio._utils.managed_entry import ManagedEntry
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger(__name__)
|
|
30
|
+
|
|
31
|
+
T = TypeVar("T")
|
|
32
|
+
|
|
33
|
+
ENV_PREFIX = "WORKSPACE_MCP_OAUTH_PROXY_VALKEY_"
|
|
34
|
+
|
|
35
|
+
_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1"})
|
|
36
|
+
_TLS_DEFAULT_PORT = 6380
|
|
37
|
+
|
|
38
|
+
DEFAULT_REMOTE_REQUEST_TIMEOUT_MS = 5000
|
|
39
|
+
DEFAULT_REMOTE_CONNECTION_TIMEOUT_MS = 10000
|
|
40
|
+
|
|
41
|
+
_RECOVERABLE_ERRORS = (ClosingError, GlideConnectionError)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _env_str(env: Mapping[str, str], name: str) -> str:
|
|
45
|
+
return env.get(ENV_PREFIX + name, "").strip()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _env_bool(env: Mapping[str, str], name: str, default: bool) -> bool:
|
|
49
|
+
raw = _env_str(env, name)
|
|
50
|
+
if not raw:
|
|
51
|
+
return default
|
|
52
|
+
return raw.lower() in ("1", "true", "yes", "on")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _env_int(
|
|
56
|
+
env: Mapping[str, str], name: str, default: int | None, *, minimum: int = 0
|
|
57
|
+
) -> int | None:
|
|
58
|
+
raw = _env_str(env, name)
|
|
59
|
+
if not raw:
|
|
60
|
+
return default
|
|
61
|
+
try:
|
|
62
|
+
value = int(raw)
|
|
63
|
+
except ValueError:
|
|
64
|
+
raise ValueError(
|
|
65
|
+
f"{ENV_PREFIX}{name} must be an integer, got {raw!r}"
|
|
66
|
+
) from None
|
|
67
|
+
if value < minimum:
|
|
68
|
+
raise ValueError(f"{ENV_PREFIX}{name} must be >= {minimum}, got {value}")
|
|
69
|
+
return value
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def build_valkey_client_config(
|
|
73
|
+
env: Mapping[str, str] | None = None,
|
|
74
|
+
) -> GlideClientConfiguration:
|
|
75
|
+
"""Build the glide client configuration from ``WORKSPACE_MCP_OAUTH_PROXY_VALKEY_*``.
|
|
76
|
+
|
|
77
|
+
Raises:
|
|
78
|
+
ValueError: if a numeric setting is not a valid integer.
|
|
79
|
+
"""
|
|
80
|
+
if env is None:
|
|
81
|
+
env = os.environ
|
|
82
|
+
|
|
83
|
+
host = _env_str(env, "HOST") or "localhost"
|
|
84
|
+
port = _env_int(env, "PORT", 6379, minimum=1)
|
|
85
|
+
use_tls = _env_bool(env, "USE_TLS", default=port == _TLS_DEFAULT_PORT)
|
|
86
|
+
|
|
87
|
+
needs_generous_timeouts = use_tls or host not in _LOOPBACK_HOSTS
|
|
88
|
+
request_timeout_ms = _env_int(
|
|
89
|
+
env,
|
|
90
|
+
"REQUEST_TIMEOUT_MS",
|
|
91
|
+
DEFAULT_REMOTE_REQUEST_TIMEOUT_MS if needs_generous_timeouts else None,
|
|
92
|
+
minimum=1,
|
|
93
|
+
)
|
|
94
|
+
connection_timeout_ms = _env_int(
|
|
95
|
+
env,
|
|
96
|
+
"CONNECTION_TIMEOUT_MS",
|
|
97
|
+
DEFAULT_REMOTE_CONNECTION_TIMEOUT_MS if needs_generous_timeouts else None,
|
|
98
|
+
minimum=1,
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
username = _env_str(env, "USERNAME") or None
|
|
102
|
+
password = _env_str(env, "PASSWORD") or None
|
|
103
|
+
credentials = (
|
|
104
|
+
ServerCredentials(password=password, username=username) if password else None
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
return GlideClientConfiguration(
|
|
108
|
+
addresses=[NodeAddress(host=host, port=port)],
|
|
109
|
+
use_tls=use_tls,
|
|
110
|
+
credentials=credentials,
|
|
111
|
+
database_id=_env_int(env, "DB", 0),
|
|
112
|
+
request_timeout=request_timeout_ms,
|
|
113
|
+
advanced_config=AdvancedGlideClientConfiguration(
|
|
114
|
+
connection_timeout=connection_timeout_ms
|
|
115
|
+
),
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def describe_valkey_client_config(config: GlideClientConfiguration) -> str:
|
|
120
|
+
"""Summarize a client configuration for logs, without credentials."""
|
|
121
|
+
address = config.addresses[0]
|
|
122
|
+
return (
|
|
123
|
+
f"host={address.host}, port={address.port}, db={config.database_id}, "
|
|
124
|
+
f"tls={config.use_tls}, "
|
|
125
|
+
f"request_timeout_ms={config.request_timeout or 'glide default'}, "
|
|
126
|
+
f"connection_timeout_ms="
|
|
127
|
+
f"{config.advanced_config.connection_timeout or 'glide default'}"
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def configure_glide_logging() -> None:
|
|
132
|
+
"""Set glide's log level from this module's effective Python log level."""
|
|
133
|
+
level = logger.getEffectiveLevel()
|
|
134
|
+
if level <= logging.DEBUG:
|
|
135
|
+
glide_level = LogLevel.DEBUG
|
|
136
|
+
elif level <= logging.WARNING:
|
|
137
|
+
glide_level = LogLevel.WARN
|
|
138
|
+
else:
|
|
139
|
+
glide_level = LogLevel.ERROR
|
|
140
|
+
GlideLogger.set_logger_config(glide_level)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
async def _create_client(config: GlideClientConfiguration) -> GlideClient:
|
|
144
|
+
return await GlideClient.create(config)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class ResilientValkeyStore(ValkeyStore):
|
|
148
|
+
"""``ValkeyStore`` that replaces a closed or disconnected glide client and retries once."""
|
|
149
|
+
|
|
150
|
+
def __init__(
|
|
151
|
+
self, *, config: GlideClientConfiguration, default_collection: str | None = None
|
|
152
|
+
) -> None:
|
|
153
|
+
super().__init__(default_collection=default_collection)
|
|
154
|
+
self._client_config = config
|
|
155
|
+
self._reconnect_lock = asyncio.Lock()
|
|
156
|
+
credentials = config.credentials
|
|
157
|
+
self._secrets = (
|
|
158
|
+
tuple(s for s in (credentials.password, credentials.username) if s)
|
|
159
|
+
if credentials
|
|
160
|
+
else ()
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
async def _setup(self) -> None:
|
|
164
|
+
self._connected_client = await _create_client(self._client_config)
|
|
165
|
+
self._exit_stack.push_async_callback(self._close_current_client)
|
|
166
|
+
|
|
167
|
+
async def _close_current_client(self) -> None:
|
|
168
|
+
client, self._connected_client = self._connected_client, None
|
|
169
|
+
if client is not None:
|
|
170
|
+
await client.close()
|
|
171
|
+
|
|
172
|
+
def _redact(self, message: str) -> str:
|
|
173
|
+
for secret in self._secrets:
|
|
174
|
+
message = message.replace(secret, "<redacted>")
|
|
175
|
+
return message
|
|
176
|
+
|
|
177
|
+
async def _reconnect(
|
|
178
|
+
self, failed_client: GlideClient | None, reason: BaseException | None
|
|
179
|
+
) -> None:
|
|
180
|
+
async with self._reconnect_lock:
|
|
181
|
+
if self._connected_client is not failed_client:
|
|
182
|
+
return
|
|
183
|
+
|
|
184
|
+
if reason is None:
|
|
185
|
+
logger.warning(
|
|
186
|
+
"Valkey OAuth storage has no connected client (previous "
|
|
187
|
+
"reconnect failed); reconnecting"
|
|
188
|
+
)
|
|
189
|
+
else:
|
|
190
|
+
logger.warning(
|
|
191
|
+
"Valkey OAuth storage connection lost (%s: %s); reconnecting",
|
|
192
|
+
type(reason).__name__,
|
|
193
|
+
self._redact(str(reason)),
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
self._connected_client = None
|
|
197
|
+
if failed_client is not None:
|
|
198
|
+
try:
|
|
199
|
+
await failed_client.close()
|
|
200
|
+
except Exception:
|
|
201
|
+
logger.debug(
|
|
202
|
+
"Ignoring error closing failed Valkey client", exc_info=True
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
try:
|
|
206
|
+
self._connected_client = await _create_client(self._client_config)
|
|
207
|
+
except Exception as exc:
|
|
208
|
+
logger.warning(
|
|
209
|
+
"Valkey OAuth storage reconnect failed (%s: %s)",
|
|
210
|
+
type(exc).__name__,
|
|
211
|
+
self._redact(str(exc)),
|
|
212
|
+
)
|
|
213
|
+
raise
|
|
214
|
+
logger.info("Valkey OAuth storage reconnected")
|
|
215
|
+
|
|
216
|
+
async def _with_reconnect(self, operation: Callable[[], Awaitable[T]]) -> T:
|
|
217
|
+
client = self._connected_client
|
|
218
|
+
if client is None:
|
|
219
|
+
await self._reconnect(failed_client=None, reason=None)
|
|
220
|
+
client = self._connected_client
|
|
221
|
+
try:
|
|
222
|
+
return await operation()
|
|
223
|
+
except _RECOVERABLE_ERRORS as exc:
|
|
224
|
+
await self._reconnect(failed_client=client, reason=exc)
|
|
225
|
+
return await operation()
|
|
226
|
+
|
|
227
|
+
async def _get_managed_entry(
|
|
228
|
+
self, *, key: str, collection: str
|
|
229
|
+
) -> ManagedEntry | None:
|
|
230
|
+
return await self._with_reconnect(
|
|
231
|
+
functools.partial(
|
|
232
|
+
super()._get_managed_entry, key=key, collection=collection
|
|
233
|
+
)
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
async def _get_managed_entries(
|
|
237
|
+
self, *, collection: str, keys: Sequence[str]
|
|
238
|
+
) -> list[ManagedEntry | None]:
|
|
239
|
+
return await self._with_reconnect(
|
|
240
|
+
functools.partial(
|
|
241
|
+
super()._get_managed_entries, collection=collection, keys=keys
|
|
242
|
+
)
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
async def _put_managed_entry(
|
|
246
|
+
self, *, key: str, collection: str, managed_entry: ManagedEntry
|
|
247
|
+
) -> None:
|
|
248
|
+
return await self._with_reconnect(
|
|
249
|
+
functools.partial(
|
|
250
|
+
super()._put_managed_entry,
|
|
251
|
+
key=key,
|
|
252
|
+
collection=collection,
|
|
253
|
+
managed_entry=managed_entry,
|
|
254
|
+
)
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
async def _delete_managed_entry(self, *, key: str, collection: str) -> bool:
|
|
258
|
+
return await self._with_reconnect(
|
|
259
|
+
functools.partial(
|
|
260
|
+
super()._delete_managed_entry, key=key, collection=collection
|
|
261
|
+
)
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
async def _delete_managed_entries(
|
|
265
|
+
self, *, keys: Sequence[str], collection: str
|
|
266
|
+
) -> int:
|
|
267
|
+
return await self._with_reconnect(
|
|
268
|
+
functools.partial(
|
|
269
|
+
super()._delete_managed_entries, keys=keys, collection=collection
|
|
270
|
+
)
|
|
271
|
+
)
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Warning filters for known third-party startup noise."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import warnings
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def install_startup_warning_filters() -> None:
|
|
9
|
+
"""Install narrow warning filters needed before importing server dependencies."""
|
|
10
|
+
try:
|
|
11
|
+
from authlib.deprecate import AuthlibDeprecationWarning
|
|
12
|
+
except ImportError: # pragma: no cover - only relevant if FastMCP drops Authlib
|
|
13
|
+
return
|
|
14
|
+
|
|
15
|
+
warnings.filterwarnings(
|
|
16
|
+
"ignore",
|
|
17
|
+
message=r"authlib\.jose module is deprecated.*",
|
|
18
|
+
category=AuthlibDeprecationWarning,
|
|
19
|
+
)
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
# ruff: noqa
|
|
2
|
+
"""
|
|
3
|
+
FastMCP Cloud entrypoint for the Google Workspace MCP server.
|
|
4
|
+
Enforces OAuth 2.1 + stateless defaults required by FastMCP-hosted deployments.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
from dotenv import load_dotenv
|
|
11
|
+
|
|
12
|
+
# Load environment variables BEFORE any other imports that might read them
|
|
13
|
+
dotenv_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env")
|
|
14
|
+
load_dotenv(dotenv_path=dotenv_path)
|
|
15
|
+
|
|
16
|
+
from core.file_limits import validate_file_limit_settings
|
|
17
|
+
|
|
18
|
+
# This module is itself a supported server entrypoint, so validate settings
|
|
19
|
+
# here rather than relying on main.main(), which FastMCP Cloud does not call.
|
|
20
|
+
validate_file_limit_settings()
|
|
21
|
+
|
|
22
|
+
from auth.oauth_config import reload_oauth_config, is_stateless_mode
|
|
23
|
+
from core.log_formatter import (
|
|
24
|
+
EnhancedLogFormatter,
|
|
25
|
+
configure_file_logging,
|
|
26
|
+
install_noisy_log_filters,
|
|
27
|
+
)
|
|
28
|
+
from core.utils import check_credentials_directory_permissions
|
|
29
|
+
from core.server import server, set_transport_mode, configure_server_for_http
|
|
30
|
+
from core.tool_registry import (
|
|
31
|
+
set_enabled_tools as set_enabled_tool_names,
|
|
32
|
+
resolve_disabled_tools,
|
|
33
|
+
set_disabled_tools,
|
|
34
|
+
wrap_server_tool_method,
|
|
35
|
+
filter_server_tools,
|
|
36
|
+
mark_always_load_tools,
|
|
37
|
+
)
|
|
38
|
+
from auth.scopes import set_enabled_tools
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def enforce_fastmcp_cloud_defaults():
|
|
42
|
+
"""Force FastMCP Cloud-compatible OAuth settings before initializing the server."""
|
|
43
|
+
enforced = []
|
|
44
|
+
|
|
45
|
+
required = {
|
|
46
|
+
"MCP_ENABLE_OAUTH21": "true",
|
|
47
|
+
"WORKSPACE_MCP_STATELESS_MODE": "true",
|
|
48
|
+
}
|
|
49
|
+
defaults = {
|
|
50
|
+
"MCP_SINGLE_USER_MODE": "false",
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
for key, target in required.items():
|
|
54
|
+
current = os.environ.get(key)
|
|
55
|
+
normalized = (current or "").lower()
|
|
56
|
+
if normalized != target:
|
|
57
|
+
os.environ[key] = target
|
|
58
|
+
enforced.append((key, current, target))
|
|
59
|
+
|
|
60
|
+
for key, target in defaults.items():
|
|
61
|
+
current = os.environ.get(key)
|
|
62
|
+
if current != target:
|
|
63
|
+
os.environ[key] = target
|
|
64
|
+
enforced.append((key, current, target))
|
|
65
|
+
|
|
66
|
+
return enforced
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
_fastmcp_cloud_overrides = enforce_fastmcp_cloud_defaults()
|
|
70
|
+
|
|
71
|
+
# Suppress googleapiclient discovery cache warning
|
|
72
|
+
logging.getLogger("googleapiclient.discovery_cache").setLevel(logging.ERROR)
|
|
73
|
+
|
|
74
|
+
# Suppress httpx/httpcore INFO logs that leak access tokens in URLs
|
|
75
|
+
# (e.g. tokeninfo?access_token=ya29.xxx). FastMCP 4 uses the httpx2 fork.
|
|
76
|
+
for _http_logger in ("httpx", "httpcore", "httpx2", "httpcore2"):
|
|
77
|
+
logging.getLogger(_http_logger).setLevel(logging.WARNING)
|
|
78
|
+
|
|
79
|
+
# Reload OAuth configuration after env vars loaded
|
|
80
|
+
reload_oauth_config()
|
|
81
|
+
|
|
82
|
+
# Configure basic logging
|
|
83
|
+
logging.basicConfig(
|
|
84
|
+
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
|
85
|
+
)
|
|
86
|
+
logger = logging.getLogger(__name__)
|
|
87
|
+
|
|
88
|
+
install_noisy_log_filters()
|
|
89
|
+
|
|
90
|
+
if _fastmcp_cloud_overrides:
|
|
91
|
+
for key, previous, new_value in _fastmcp_cloud_overrides:
|
|
92
|
+
if previous is None:
|
|
93
|
+
logger.info("FastMCP Cloud: set %s=%s", key, new_value)
|
|
94
|
+
else:
|
|
95
|
+
logger.warning(
|
|
96
|
+
"FastMCP Cloud: overriding %s from %s to %s", key, previous, new_value
|
|
97
|
+
)
|
|
98
|
+
else:
|
|
99
|
+
logger.info("FastMCP Cloud: OAuth 2.1 stateless defaults already satisfied")
|
|
100
|
+
|
|
101
|
+
# Configure file logging based on stateless mode
|
|
102
|
+
configure_file_logging()
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def configure_safe_logging():
|
|
106
|
+
"""Configure safe Unicode handling for logging."""
|
|
107
|
+
|
|
108
|
+
class SafeEnhancedFormatter(EnhancedLogFormatter):
|
|
109
|
+
"""Enhanced ASCII formatter with additional Windows safety."""
|
|
110
|
+
|
|
111
|
+
def format(self, record):
|
|
112
|
+
try:
|
|
113
|
+
return super().format(record)
|
|
114
|
+
except UnicodeEncodeError:
|
|
115
|
+
# Fallback to ASCII-safe formatting
|
|
116
|
+
service_prefix = self._get_ascii_prefix(record.name, record.levelname)
|
|
117
|
+
safe_msg = (
|
|
118
|
+
str(record.getMessage())
|
|
119
|
+
.encode("ascii", errors="replace")
|
|
120
|
+
.decode("ascii")
|
|
121
|
+
)
|
|
122
|
+
return f"{service_prefix} {safe_msg}"
|
|
123
|
+
|
|
124
|
+
# Replace all console handlers' formatters with safe enhanced ones
|
|
125
|
+
for handler in logging.root.handlers:
|
|
126
|
+
# Only apply to console/stream handlers, keep file handlers as-is
|
|
127
|
+
if isinstance(handler, logging.StreamHandler) and handler.stream.name in [
|
|
128
|
+
"<stderr>",
|
|
129
|
+
"<stdout>",
|
|
130
|
+
]:
|
|
131
|
+
safe_formatter = SafeEnhancedFormatter(use_colors=True)
|
|
132
|
+
handler.setFormatter(safe_formatter)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# Configure safe logging
|
|
136
|
+
configure_safe_logging()
|
|
137
|
+
|
|
138
|
+
# Check credentials directory permissions (skip in stateless mode)
|
|
139
|
+
if not is_stateless_mode():
|
|
140
|
+
try:
|
|
141
|
+
logger.info("Checking credentials directory permissions...")
|
|
142
|
+
check_credentials_directory_permissions()
|
|
143
|
+
logger.info("Credentials directory permissions verified")
|
|
144
|
+
except (PermissionError, OSError) as e:
|
|
145
|
+
logger.error(f"Credentials directory permission check failed: {e}")
|
|
146
|
+
logger.error(
|
|
147
|
+
" Please ensure the service has write permissions to create/access the credentials directory"
|
|
148
|
+
)
|
|
149
|
+
sys.exit(1)
|
|
150
|
+
else:
|
|
151
|
+
logger.info("🔍 Skipping credentials directory check (stateless mode)")
|
|
152
|
+
|
|
153
|
+
# Set transport mode for HTTP (FastMCP CLI defaults to streamable-http)
|
|
154
|
+
set_transport_mode("streamable-http")
|
|
155
|
+
|
|
156
|
+
# Import all tool modules to register their @server.tool() decorators
|
|
157
|
+
import gmail.gmail_tools
|
|
158
|
+
import gdrive.drive_tools
|
|
159
|
+
import gcalendar.calendar_tools
|
|
160
|
+
import gdocs.docs_tools
|
|
161
|
+
import gsheets.sheets_tools
|
|
162
|
+
import gchat.chat_tools
|
|
163
|
+
import gforms.forms_tools
|
|
164
|
+
import gslides.slides_tools
|
|
165
|
+
import gtasks.tasks_tools
|
|
166
|
+
import gsearch.search_tools
|
|
167
|
+
|
|
168
|
+
# Configure tool registration
|
|
169
|
+
wrap_server_tool_method(server)
|
|
170
|
+
|
|
171
|
+
# Enable all tools and services by default
|
|
172
|
+
all_services = [
|
|
173
|
+
"gmail",
|
|
174
|
+
"drive",
|
|
175
|
+
"calendar",
|
|
176
|
+
"docs",
|
|
177
|
+
"sheets",
|
|
178
|
+
"chat",
|
|
179
|
+
"forms",
|
|
180
|
+
"slides",
|
|
181
|
+
"tasks",
|
|
182
|
+
"search",
|
|
183
|
+
]
|
|
184
|
+
set_enabled_tools(all_services) # Set enabled services for scopes
|
|
185
|
+
set_enabled_tool_names(None) # Don't filter individual tools - enable all
|
|
186
|
+
# Env-only block list: this entrypoint has no CLI args
|
|
187
|
+
set_disabled_tools(resolve_disabled_tools())
|
|
188
|
+
|
|
189
|
+
# Filter tools based on configuration
|
|
190
|
+
filter_server_tools(server)
|
|
191
|
+
mark_always_load_tools(server)
|
|
192
|
+
|
|
193
|
+
# Configure authentication after scopes are known
|
|
194
|
+
configure_server_for_http()
|
|
195
|
+
|
|
196
|
+
# Export server instance for FastMCP CLI (looks for 'mcp', 'server', or 'app')
|
|
197
|
+
mcp = server
|
|
198
|
+
app = server
|