@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
package/main.py
ADDED
|
@@ -0,0 +1,1170 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import socket
|
|
7
|
+
import sys
|
|
8
|
+
from functools import partial
|
|
9
|
+
from importlib import metadata, import_module
|
|
10
|
+
from typing import NoReturn
|
|
11
|
+
from urllib.parse import urlparse
|
|
12
|
+
from dotenv import load_dotenv
|
|
13
|
+
from core.startup_ui import StartupDisplay, collapse_home, wordmark_lines
|
|
14
|
+
|
|
15
|
+
# Prevent any stray startup output on macOS (e.g. platform identifiers) from
|
|
16
|
+
# corrupting the MCP JSON-RPC handshake on stdout. We capture anything written
|
|
17
|
+
# to stdout during module-level initialisation and replay it to stderr so that
|
|
18
|
+
# diagnostic information is not lost.
|
|
19
|
+
_original_stdout = sys.stdout
|
|
20
|
+
if sys.platform == "darwin":
|
|
21
|
+
sys.stdout = io.StringIO()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _load_startup_dependencies():
|
|
25
|
+
from auth.credential_store import get_credential_store, get_selected_backend
|
|
26
|
+
from auth.oauth_config import (
|
|
27
|
+
get_oauth_config,
|
|
28
|
+
reload_oauth_config,
|
|
29
|
+
is_stateless_mode,
|
|
30
|
+
is_service_account_enabled,
|
|
31
|
+
)
|
|
32
|
+
from core.log_formatter import (
|
|
33
|
+
EnhancedLogFormatter,
|
|
34
|
+
configure_file_logging,
|
|
35
|
+
install_noisy_log_filters,
|
|
36
|
+
)
|
|
37
|
+
from core.utils import check_credentials_directory_permissions
|
|
38
|
+
from core.server import (
|
|
39
|
+
server,
|
|
40
|
+
set_transport_mode,
|
|
41
|
+
configure_server_for_http,
|
|
42
|
+
get_stateless_http,
|
|
43
|
+
)
|
|
44
|
+
from core.tool_tier_loader import resolve_tools_from_tier
|
|
45
|
+
from core.tool_registry import (
|
|
46
|
+
set_enabled_tools as set_enabled_tool_names,
|
|
47
|
+
resolve_disabled_tools,
|
|
48
|
+
set_disabled_tools,
|
|
49
|
+
wrap_server_tool_method,
|
|
50
|
+
filter_server_tools,
|
|
51
|
+
mark_always_load_tools,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
return (
|
|
55
|
+
get_selected_backend,
|
|
56
|
+
get_credential_store,
|
|
57
|
+
get_oauth_config,
|
|
58
|
+
reload_oauth_config,
|
|
59
|
+
is_stateless_mode,
|
|
60
|
+
is_service_account_enabled,
|
|
61
|
+
EnhancedLogFormatter,
|
|
62
|
+
configure_file_logging,
|
|
63
|
+
install_noisy_log_filters,
|
|
64
|
+
check_credentials_directory_permissions,
|
|
65
|
+
server,
|
|
66
|
+
set_transport_mode,
|
|
67
|
+
configure_server_for_http,
|
|
68
|
+
get_stateless_http,
|
|
69
|
+
resolve_tools_from_tier,
|
|
70
|
+
set_enabled_tool_names,
|
|
71
|
+
resolve_disabled_tools,
|
|
72
|
+
set_disabled_tools,
|
|
73
|
+
wrap_server_tool_method,
|
|
74
|
+
filter_server_tools,
|
|
75
|
+
mark_always_load_tools,
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
dotenv_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env")
|
|
80
|
+
load_dotenv(dotenv_path=dotenv_path)
|
|
81
|
+
|
|
82
|
+
(
|
|
83
|
+
get_selected_backend,
|
|
84
|
+
get_credential_store,
|
|
85
|
+
get_oauth_config,
|
|
86
|
+
reload_oauth_config,
|
|
87
|
+
is_stateless_mode,
|
|
88
|
+
is_service_account_enabled,
|
|
89
|
+
EnhancedLogFormatter,
|
|
90
|
+
configure_file_logging,
|
|
91
|
+
install_noisy_log_filters,
|
|
92
|
+
check_credentials_directory_permissions,
|
|
93
|
+
server,
|
|
94
|
+
set_transport_mode,
|
|
95
|
+
configure_server_for_http,
|
|
96
|
+
get_stateless_http,
|
|
97
|
+
resolve_tools_from_tier,
|
|
98
|
+
set_enabled_tool_names,
|
|
99
|
+
resolve_disabled_tools,
|
|
100
|
+
set_disabled_tools,
|
|
101
|
+
wrap_server_tool_method,
|
|
102
|
+
filter_server_tools,
|
|
103
|
+
mark_always_load_tools,
|
|
104
|
+
) = _load_startup_dependencies()
|
|
105
|
+
|
|
106
|
+
# Suppress googleapiclient discovery cache warning
|
|
107
|
+
logging.getLogger("googleapiclient.discovery_cache").setLevel(logging.ERROR)
|
|
108
|
+
|
|
109
|
+
# Suppress httpx/httpcore INFO logs that leak access tokens in URLs
|
|
110
|
+
# (e.g. tokeninfo?access_token=ya29.xxx). FastMCP 4 uses the httpx2 fork.
|
|
111
|
+
for _http_logger in ("httpx", "httpcore", "httpx2", "httpcore2"):
|
|
112
|
+
logging.getLogger(_http_logger).setLevel(logging.WARNING)
|
|
113
|
+
|
|
114
|
+
reload_oauth_config()
|
|
115
|
+
|
|
116
|
+
# WORKSPACE_MCP_LOG_LEVEL=DEBUG surfaces the debug-level companion lines that
|
|
117
|
+
# carry user text (search queries, find/replace strings) which INFO deliberately
|
|
118
|
+
# omits — see tests/test_log_hygiene.py. Default stays INFO. Allowlisted, not
|
|
119
|
+
# getattr'd: getattr(logging, <arbitrary env value>) can resolve to a non-level
|
|
120
|
+
# attribute (e.g. BASIC_FORMAT) and crash basicConfig at startup.
|
|
121
|
+
_LOG_LEVEL_NAMES = {"CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"}
|
|
122
|
+
_log_level_name = os.environ.get("WORKSPACE_MCP_LOG_LEVEL", "INFO").upper()
|
|
123
|
+
_log_level = (
|
|
124
|
+
getattr(logging, _log_level_name)
|
|
125
|
+
if _log_level_name in _LOG_LEVEL_NAMES
|
|
126
|
+
else logging.INFO
|
|
127
|
+
)
|
|
128
|
+
logging.basicConfig(
|
|
129
|
+
level=_log_level,
|
|
130
|
+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
|
131
|
+
)
|
|
132
|
+
# Imports above may already have installed a root handler, which makes
|
|
133
|
+
# basicConfig a no-op. Set the level explicitly so the environment override
|
|
134
|
+
# works regardless of import order without replacing embedding-app handlers.
|
|
135
|
+
logging.getLogger().setLevel(_log_level)
|
|
136
|
+
logger = logging.getLogger(__name__)
|
|
137
|
+
|
|
138
|
+
install_noisy_log_filters()
|
|
139
|
+
configure_file_logging()
|
|
140
|
+
|
|
141
|
+
_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _loopback_redirect_port(redirect_uri: str | None) -> int | None:
|
|
145
|
+
"""Return the explicit port of an http loopback redirect URI, else None."""
|
|
146
|
+
if not redirect_uri:
|
|
147
|
+
return None
|
|
148
|
+
try:
|
|
149
|
+
parsed = urlparse(redirect_uri)
|
|
150
|
+
port = parsed.port
|
|
151
|
+
except ValueError:
|
|
152
|
+
return None
|
|
153
|
+
if parsed.scheme != "http" or parsed.hostname not in _LOOPBACK_HOSTS:
|
|
154
|
+
return None
|
|
155
|
+
return port
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def resolve_stdio_callback_port() -> None:
|
|
159
|
+
"""
|
|
160
|
+
Late-bind the legacy stdio OAuth callback port.
|
|
161
|
+
|
|
162
|
+
Streamable HTTP/OAuth 2.1 owns its main HTTP port directly and must keep the
|
|
163
|
+
normal PORT/WORKSPACE_MCP_PORT semantics. The fallback range only exists for
|
|
164
|
+
the standalone stdio callback listener, and only when no redirect URI pins it.
|
|
165
|
+
A busy port is logged rather than fatal because the listener binds lazily.
|
|
166
|
+
"""
|
|
167
|
+
from auth.port_resolver import resolve_port, NoAvailablePortError, PortConfigError
|
|
168
|
+
|
|
169
|
+
redirect_uri = os.getenv("GOOGLE_OAUTH_REDIRECT_URI")
|
|
170
|
+
pinned_port = _loopback_redirect_port(redirect_uri)
|
|
171
|
+
|
|
172
|
+
try:
|
|
173
|
+
resolve_port(preferred=pinned_port, allow_fallback=not redirect_uri)
|
|
174
|
+
except PortConfigError as exc:
|
|
175
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
176
|
+
sys.exit(1)
|
|
177
|
+
except NoAvailablePortError as exc:
|
|
178
|
+
if pinned_port is None:
|
|
179
|
+
logger.warning(
|
|
180
|
+
"%s Continuing; OAuth re-authorization will fail until the port frees up.",
|
|
181
|
+
exc,
|
|
182
|
+
)
|
|
183
|
+
os.environ.pop("WORKSPACE_MCP_RESOLVED_PORT", None)
|
|
184
|
+
else:
|
|
185
|
+
logger.warning(
|
|
186
|
+
"OAuth callback port %d required by GOOGLE_OAUTH_REDIRECT_URI is in "
|
|
187
|
+
"use. Continuing; OAuth re-authorization will fail until the port "
|
|
188
|
+
"frees up or GOOGLE_OAUTH_REDIRECT_URI is changed.",
|
|
189
|
+
pinned_port,
|
|
190
|
+
)
|
|
191
|
+
os.environ["WORKSPACE_MCP_PORT"] = str(pinned_port)
|
|
192
|
+
os.environ["WORKSPACE_MCP_RESOLVED_PORT"] = "1"
|
|
193
|
+
reload_oauth_config()
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def resolve_callback_port_for_transport(transport: str) -> None:
|
|
197
|
+
"""Apply callback port fallback only to legacy stdio transport."""
|
|
198
|
+
if transport == "stdio":
|
|
199
|
+
resolve_stdio_callback_port()
|
|
200
|
+
else:
|
|
201
|
+
os.environ.pop("WORKSPACE_MCP_RESOLVED_PORT", None)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
# Advisories raised while resolving configuration. They are queued rather than
|
|
205
|
+
# logged so the startup screen can present them as one block instead of letting
|
|
206
|
+
# them race ahead of the banner on stderr.
|
|
207
|
+
STARTUP_NOTICES: list[str] = []
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def add_startup_notice(message: str) -> None:
|
|
211
|
+
"""Queue an advisory for the startup screen, keeping it in the debug log."""
|
|
212
|
+
STARTUP_NOTICES.append(message)
|
|
213
|
+
logger.debug(message)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def resolve_bind_host_for_transport(transport: str) -> str:
|
|
217
|
+
"""Choose a safe default bind host for the selected transport/auth mode."""
|
|
218
|
+
configured_host = os.getenv("WORKSPACE_MCP_HOST")
|
|
219
|
+
host = configured_host or "0.0.0.0"
|
|
220
|
+
if transport != "streamable-http":
|
|
221
|
+
return host
|
|
222
|
+
|
|
223
|
+
config = get_oauth_config()
|
|
224
|
+
if config.is_oauth21_enabled():
|
|
225
|
+
return host
|
|
226
|
+
|
|
227
|
+
if configured_host:
|
|
228
|
+
if configured_host not in {"localhost", "127.0.0.1", "::1"}:
|
|
229
|
+
add_startup_notice(
|
|
230
|
+
f"Legacy streamable-http mode has no MCP-level auth provider and is "
|
|
231
|
+
f"bound to {configured_host} because WORKSPACE_MCP_HOST was explicitly "
|
|
232
|
+
f"set. Use MCP_ENABLE_OAUTH21=true for remotely reachable HTTP "
|
|
233
|
+
f"deployments."
|
|
234
|
+
)
|
|
235
|
+
return configured_host
|
|
236
|
+
|
|
237
|
+
add_startup_notice(
|
|
238
|
+
"Legacy streamable-http mode has no MCP-level auth provider; binding to "
|
|
239
|
+
"127.0.0.1 by default. Set WORKSPACE_MCP_HOST explicitly only for trusted "
|
|
240
|
+
"networks, or use MCP_ENABLE_OAUTH21=true for remote HTTP deployments."
|
|
241
|
+
)
|
|
242
|
+
return "127.0.0.1"
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def validate_streamable_http_auth(transport: str) -> None:
|
|
246
|
+
"""Reject misconfigured OAuth 2.1 HTTP before starting."""
|
|
247
|
+
if transport != "streamable-http":
|
|
248
|
+
return
|
|
249
|
+
|
|
250
|
+
config = get_oauth_config()
|
|
251
|
+
if config.is_oauth21_enabled() and not config.is_configured():
|
|
252
|
+
print(
|
|
253
|
+
"Error: streamable-http transport with MCP_ENABLE_OAUTH21=true requires "
|
|
254
|
+
"GOOGLE_OAUTH_CLIENT_ID so OAuth 2.1 protocol authentication can be "
|
|
255
|
+
"configured.",
|
|
256
|
+
file=sys.stderr,
|
|
257
|
+
)
|
|
258
|
+
sys.exit(1)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
# Single source of truth: service name -> module path.
|
|
262
|
+
# VALID_SERVICES is derived from this mapping.
|
|
263
|
+
SERVICE_MODULES = {
|
|
264
|
+
"gmail": "gmail.gmail_tools",
|
|
265
|
+
"drive": "gdrive.drive_tools",
|
|
266
|
+
"calendar": "gcalendar.calendar_tools",
|
|
267
|
+
"docs": "gdocs.docs_tools",
|
|
268
|
+
"sheets": "gsheets.sheets_tools",
|
|
269
|
+
"chat": "gchat.chat_tools",
|
|
270
|
+
"forms": "gforms.forms_tools",
|
|
271
|
+
"slides": "gslides.slides_tools",
|
|
272
|
+
"tasks": "gtasks.tasks_tools",
|
|
273
|
+
"contacts": "gcontacts.contacts_tools",
|
|
274
|
+
"search": "gsearch.search_tools",
|
|
275
|
+
"appscript": "gappsscript.apps_script_tools",
|
|
276
|
+
}
|
|
277
|
+
VALID_SERVICES = frozenset(SERVICE_MODULES)
|
|
278
|
+
|
|
279
|
+
# Every icon is a double-width emoji with no variation selector, so the startup
|
|
280
|
+
# service grid stays aligned across terminals.
|
|
281
|
+
SERVICE_ICONS = {
|
|
282
|
+
"gmail": "📧",
|
|
283
|
+
"drive": "📁",
|
|
284
|
+
"calendar": "📅",
|
|
285
|
+
"docs": "📄",
|
|
286
|
+
"sheets": "📊",
|
|
287
|
+
"chat": "💬",
|
|
288
|
+
"forms": "📝",
|
|
289
|
+
"slides": "🎥",
|
|
290
|
+
"tasks": "📋",
|
|
291
|
+
"contacts": "👤",
|
|
292
|
+
"search": "🔍",
|
|
293
|
+
"appscript": "📜",
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def safe_print(text):
|
|
298
|
+
"""Print to stderr, falling back to debug logging when running as an MCP server."""
|
|
299
|
+
# Don't print to stderr when running as MCP server via uvx to avoid JSON parsing errors
|
|
300
|
+
# Check if we're running as MCP server (no TTY and uvx in process name)
|
|
301
|
+
if not sys.stderr.isatty():
|
|
302
|
+
# Running as MCP server, suppress output to avoid JSON parsing errors
|
|
303
|
+
logger.debug(f"[MCP Server] {text}")
|
|
304
|
+
return
|
|
305
|
+
|
|
306
|
+
try:
|
|
307
|
+
print(text, file=sys.stderr)
|
|
308
|
+
except UnicodeEncodeError:
|
|
309
|
+
print(text.encode("ascii", errors="replace").decode(), file=sys.stderr)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def fatal(ui: StartupDisplay, text: str, *details: str) -> NoReturn:
|
|
313
|
+
"""Report an unrecoverable startup problem on every channel, then exit.
|
|
314
|
+
|
|
315
|
+
The startup screen is discarded when stderr is not a TTY (see safe_print),
|
|
316
|
+
which is exactly how an MCP client runs the server. Logging the same text at
|
|
317
|
+
ERROR keeps the reason on stderr for the client log and in
|
|
318
|
+
mcp_server_debug.log, so a failed launch is never indistinguishable from a
|
|
319
|
+
server that simply stopped talking.
|
|
320
|
+
"""
|
|
321
|
+
ui.step(text, state="fail")
|
|
322
|
+
for detail in details:
|
|
323
|
+
ui.detail(detail)
|
|
324
|
+
logger.error("Startup aborted: %s", ". ".join([text, *details]))
|
|
325
|
+
sys.exit(1)
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _local_ipv4_addresses() -> list[str]:
|
|
329
|
+
"""Best-effort list of this machine's IPv4 addresses, loopback first."""
|
|
330
|
+
try:
|
|
331
|
+
infos = socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET)
|
|
332
|
+
except (OSError, UnicodeError):
|
|
333
|
+
infos = []
|
|
334
|
+
return list(dict.fromkeys(["127.0.0.1", *(info[4][0] for info in infos)]))
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _http_port_conflict(host: str, port: int) -> str | None:
|
|
338
|
+
"""Return why uvicorn could not serve host:port, or None if it can."""
|
|
339
|
+
# macOS SO_REUSEADDR wildcard binds coexist with specific-address listeners.
|
|
340
|
+
connect_hosts = _local_ipv4_addresses() if host in ("", "0.0.0.0") else [host]
|
|
341
|
+
for connect_host in connect_hosts:
|
|
342
|
+
try:
|
|
343
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
344
|
+
s.settimeout(0.5)
|
|
345
|
+
if s.connect_ex((connect_host, port)) == 0:
|
|
346
|
+
return f"a server is already listening on {connect_host}:{port}"
|
|
347
|
+
except OSError:
|
|
348
|
+
pass
|
|
349
|
+
|
|
350
|
+
try:
|
|
351
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
352
|
+
if os.name != "nt": # matches asyncio's reuse_address default
|
|
353
|
+
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
354
|
+
s.bind((host, port))
|
|
355
|
+
except OSError as e:
|
|
356
|
+
return str(e)
|
|
357
|
+
return None
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def configure_safe_logging():
|
|
361
|
+
"""Replace console handlers with ASCII-safe formatters for Windows compatibility."""
|
|
362
|
+
|
|
363
|
+
class SafeEnhancedFormatter(EnhancedLogFormatter):
|
|
364
|
+
"""Enhanced ASCII formatter with additional Windows safety."""
|
|
365
|
+
|
|
366
|
+
def format(self, record):
|
|
367
|
+
"""Format a log record, falling back to ASCII if encoding fails."""
|
|
368
|
+
try:
|
|
369
|
+
return super().format(record)
|
|
370
|
+
except UnicodeEncodeError:
|
|
371
|
+
# Fallback to ASCII-safe formatting
|
|
372
|
+
service_prefix = self._get_ascii_prefix(record.name, record.levelname)
|
|
373
|
+
safe_msg = (
|
|
374
|
+
str(record.getMessage())
|
|
375
|
+
.encode("ascii", errors="replace")
|
|
376
|
+
.decode("ascii")
|
|
377
|
+
)
|
|
378
|
+
return f"{service_prefix} {safe_msg}"
|
|
379
|
+
|
|
380
|
+
# Replace all console handlers' formatters with safe enhanced ones
|
|
381
|
+
for handler in logging.root.handlers:
|
|
382
|
+
# Only apply to console/stream handlers, keep file handlers as-is
|
|
383
|
+
if isinstance(handler, logging.StreamHandler) and handler.stream.name in [
|
|
384
|
+
"<stderr>",
|
|
385
|
+
"<stdout>",
|
|
386
|
+
]:
|
|
387
|
+
safe_formatter = SafeEnhancedFormatter(use_colors=True)
|
|
388
|
+
handler.setFormatter(safe_formatter)
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def resolve_permissions_mode_selection(
|
|
392
|
+
permission_services: list[str], tool_tier: str | None
|
|
393
|
+
) -> tuple[list[str], set[str] | None]:
|
|
394
|
+
"""
|
|
395
|
+
Resolve service imports and optional tool-name filtering for --permissions mode.
|
|
396
|
+
|
|
397
|
+
When a tier is specified, both:
|
|
398
|
+
- imported services are narrowed to services with tier-matched tools
|
|
399
|
+
- registered tools are narrowed to the resolved tool names
|
|
400
|
+
"""
|
|
401
|
+
if tool_tier is None:
|
|
402
|
+
return permission_services, None
|
|
403
|
+
|
|
404
|
+
tier_tools, tier_services = resolve_tools_from_tier(tool_tier, permission_services)
|
|
405
|
+
return tier_services, set(tier_tools)
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def narrow_permissions_to_services(
|
|
409
|
+
permissions: dict[str, str], services: list[str]
|
|
410
|
+
) -> dict[str, str]:
|
|
411
|
+
"""Restrict permission entries to the provided service list order."""
|
|
412
|
+
return {
|
|
413
|
+
service: permissions[service] for service in services if service in permissions
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _optional_field(name: str, *, path: bool = False) -> tuple[str, str, str]:
|
|
418
|
+
"""Describe an optional env var as a (label, value, state) display row."""
|
|
419
|
+
value = os.getenv(name)
|
|
420
|
+
if not value:
|
|
421
|
+
return name, "not set", "off"
|
|
422
|
+
return name, collapse_home(os.path.expanduser(value)) if path else value, "on"
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _mode_field(
|
|
426
|
+
label: str, env_var: str, enabled: bool, *, warn_when_on: bool = False
|
|
427
|
+
) -> tuple[str, str, str]:
|
|
428
|
+
"""Describe a resolved mode as a (label, value, state) row naming its env var."""
|
|
429
|
+
if not enabled:
|
|
430
|
+
return label, f"off · {env_var}", "off"
|
|
431
|
+
return label, f"on · {env_var}", "warn" if warn_when_on else "on"
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def _disabled_tools_field(disabled_tools: set[str]) -> tuple[str, str, str]:
|
|
435
|
+
"""Describe the resolved per-tool block list as a display row."""
|
|
436
|
+
env_var = "WORKSPACE_MCP_DISABLED_TOOLS"
|
|
437
|
+
if not disabled_tools:
|
|
438
|
+
return "Disabled tools", f"none · {env_var}", "off"
|
|
439
|
+
return "Disabled tools", f"{', '.join(sorted(disabled_tools))} · {env_var}", "on"
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _client_secret_field() -> tuple[str, str, str]:
|
|
443
|
+
"""Describe the OAuth client secret without revealing it."""
|
|
444
|
+
name = "GOOGLE_OAUTH_CLIENT_SECRET"
|
|
445
|
+
secret = os.getenv(name)
|
|
446
|
+
if not secret:
|
|
447
|
+
# Report the resolved configuration rather than re-reading the file, so
|
|
448
|
+
# the banner cannot claim a secret the OAuth config declined to use.
|
|
449
|
+
config = get_oauth_config()
|
|
450
|
+
if config.client_secret and config.client_secrets_file:
|
|
451
|
+
return name, f"set · via {collapse_home(config.client_secrets_file)}", "on"
|
|
452
|
+
return name, "not set", "off"
|
|
453
|
+
if len(secret) <= 8:
|
|
454
|
+
return name, "set · unexpectedly short", "warn"
|
|
455
|
+
return name, f"{secret[:4]}…{secret[-4:]}", "on"
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _credentials_dir_field() -> tuple[str, str, str]:
|
|
459
|
+
"""Describe the credentials directory, mirroring credential_store resolution."""
|
|
460
|
+
for name in ("WORKSPACE_MCP_CREDENTIALS_DIR", "GOOGLE_MCP_CREDENTIALS_DIR"):
|
|
461
|
+
value = os.getenv(name)
|
|
462
|
+
if value:
|
|
463
|
+
return name, collapse_home(os.path.expanduser(value)), "on"
|
|
464
|
+
default = os.path.join(
|
|
465
|
+
os.path.expanduser("~"), ".google_workspace_mcp", "credentials"
|
|
466
|
+
)
|
|
467
|
+
return "WORKSPACE_MCP_CREDENTIALS_DIR", collapse_home(default), "off"
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def describe_credential_config() -> list[tuple[str, str, str]]:
|
|
471
|
+
"""Build the credential rows shown in the startup configuration section."""
|
|
472
|
+
return [
|
|
473
|
+
_optional_field("GOOGLE_OAUTH_CLIENT_ID"),
|
|
474
|
+
_client_secret_field(),
|
|
475
|
+
_optional_field("GOOGLE_CLIENT_SECRET_PATH", path=True),
|
|
476
|
+
_optional_field("GOOGLE_SERVICE_ACCOUNT_KEY_FILE", path=True),
|
|
477
|
+
_optional_field("USER_GOOGLE_EMAIL"),
|
|
478
|
+
_credentials_dir_field(),
|
|
479
|
+
]
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def describe_mode_config(
|
|
483
|
+
disabled_tools: set[str] = frozenset(), *, single_user: bool = False
|
|
484
|
+
) -> list[tuple[str, str, str]]:
|
|
485
|
+
"""Build the mode rows shown in the startup configuration section.
|
|
486
|
+
|
|
487
|
+
Rows report the modes the server resolved, not a re-parse of the env vars,
|
|
488
|
+
so the banner cannot disagree with how the server actually runs.
|
|
489
|
+
"""
|
|
490
|
+
config = get_oauth_config()
|
|
491
|
+
return [
|
|
492
|
+
_mode_field("OAuth 2.1", "MCP_ENABLE_OAUTH21", config.is_oauth21_enabled()),
|
|
493
|
+
_mode_field("Stateless", "WORKSPACE_MCP_STATELESS_MODE", config.stateless_mode),
|
|
494
|
+
_mode_field(
|
|
495
|
+
"Sessionless HTTP",
|
|
496
|
+
"WORKSPACE_MCP_STATELESS_HTTP",
|
|
497
|
+
config.stateless_mode or get_stateless_http(),
|
|
498
|
+
),
|
|
499
|
+
_mode_field(
|
|
500
|
+
"Single-user",
|
|
501
|
+
"MCP_SINGLE_USER_MODE",
|
|
502
|
+
single_user or os.getenv("MCP_SINGLE_USER_MODE") == "1",
|
|
503
|
+
),
|
|
504
|
+
# oauthlib treats any non-empty value as enabled, "false" included.
|
|
505
|
+
_mode_field(
|
|
506
|
+
"Insecure transport",
|
|
507
|
+
"OAUTHLIB_INSECURE_TRANSPORT",
|
|
508
|
+
bool(os.getenv("OAUTHLIB_INSECURE_TRANSPORT")),
|
|
509
|
+
warn_when_on=True,
|
|
510
|
+
),
|
|
511
|
+
_disabled_tools_field(disabled_tools),
|
|
512
|
+
]
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def _restore_stdout() -> None:
|
|
516
|
+
"""Restore the real stdout and replay any captured output to stderr."""
|
|
517
|
+
captured_stdout = sys.stdout
|
|
518
|
+
|
|
519
|
+
# Idempotent: if already restored, nothing to do.
|
|
520
|
+
if captured_stdout is _original_stdout:
|
|
521
|
+
return
|
|
522
|
+
|
|
523
|
+
captured = ""
|
|
524
|
+
required_stringio_methods = ("getvalue", "write", "flush")
|
|
525
|
+
try:
|
|
526
|
+
if all(
|
|
527
|
+
callable(getattr(captured_stdout, method_name, None))
|
|
528
|
+
for method_name in required_stringio_methods
|
|
529
|
+
):
|
|
530
|
+
captured = captured_stdout.getvalue()
|
|
531
|
+
finally:
|
|
532
|
+
sys.stdout = _original_stdout
|
|
533
|
+
|
|
534
|
+
if captured:
|
|
535
|
+
print(captured, end="", file=sys.stderr)
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def main():
|
|
539
|
+
"""
|
|
540
|
+
Main entry point for the Google Workspace MCP server.
|
|
541
|
+
Uses FastMCP's native streamable-http transport.
|
|
542
|
+
"""
|
|
543
|
+
_restore_stdout()
|
|
544
|
+
|
|
545
|
+
# Configure safe logging for Windows Unicode handling
|
|
546
|
+
configure_safe_logging()
|
|
547
|
+
|
|
548
|
+
# Enable OpenTelemetry tracing when an OTLP endpoint is configured.
|
|
549
|
+
from core.telemetry import configure_telemetry
|
|
550
|
+
|
|
551
|
+
configure_telemetry()
|
|
552
|
+
|
|
553
|
+
# Parse command line arguments
|
|
554
|
+
parser = argparse.ArgumentParser(description="Google Workspace MCP Server")
|
|
555
|
+
parser.add_argument(
|
|
556
|
+
"--single-user",
|
|
557
|
+
action="store_true",
|
|
558
|
+
help="Run in single-user mode - bypass session mapping and use any credentials from the credentials directory",
|
|
559
|
+
)
|
|
560
|
+
parser.add_argument(
|
|
561
|
+
"--tools",
|
|
562
|
+
nargs="*",
|
|
563
|
+
choices=sorted(VALID_SERVICES),
|
|
564
|
+
help="Specify which tools to register. If not provided, all tools are registered.",
|
|
565
|
+
)
|
|
566
|
+
parser.add_argument(
|
|
567
|
+
"--tool-tier",
|
|
568
|
+
choices=["core", "extended", "complete"],
|
|
569
|
+
help="Load tools based on tier level. Can be combined with --tools to filter services.",
|
|
570
|
+
)
|
|
571
|
+
parser.add_argument(
|
|
572
|
+
"--disabled-tools",
|
|
573
|
+
nargs="+",
|
|
574
|
+
metavar="TOOL_NAME",
|
|
575
|
+
help=(
|
|
576
|
+
"Block individual tools by name regardless of tier or permission selection. "
|
|
577
|
+
"Composes with every other filtering option. "
|
|
578
|
+
"Env var: WORKSPACE_MCP_DISABLED_TOOLS (comma-separated)."
|
|
579
|
+
),
|
|
580
|
+
)
|
|
581
|
+
parser.add_argument(
|
|
582
|
+
"--transport",
|
|
583
|
+
choices=["stdio", "streamable-http"],
|
|
584
|
+
default=None,
|
|
585
|
+
help="Transport mode: stdio (default; overridable via WORKSPACE_MCP_TRANSPORT) or streamable-http",
|
|
586
|
+
)
|
|
587
|
+
parser.add_argument(
|
|
588
|
+
"--read-only",
|
|
589
|
+
action="store_true",
|
|
590
|
+
help="Run in read-only mode - requests only read-only scopes and disables tools requiring write permissions",
|
|
591
|
+
)
|
|
592
|
+
parser.add_argument(
|
|
593
|
+
"--permissions",
|
|
594
|
+
nargs="+",
|
|
595
|
+
metavar="SERVICE:LEVEL",
|
|
596
|
+
help=(
|
|
597
|
+
"Granular per-service permission levels. Format: service:level. "
|
|
598
|
+
"Example: --permissions gmail:organize drive:readonly. "
|
|
599
|
+
"Gmail levels: readonly, organize, drafts, send, full (cumulative). "
|
|
600
|
+
"Other services: readonly, full. "
|
|
601
|
+
"Join levels with '+' to grant only the scopes each named level adds "
|
|
602
|
+
"(e.g. gmail:readonly+send). "
|
|
603
|
+
"Mutually exclusive with --read-only and --tools."
|
|
604
|
+
),
|
|
605
|
+
)
|
|
606
|
+
args = parser.parse_args()
|
|
607
|
+
|
|
608
|
+
# Validate the memory-safety settings once at startup. Tool helpers parse them
|
|
609
|
+
# defensively as well, but a deployment typo must not silently disable the
|
|
610
|
+
# configured limit.
|
|
611
|
+
from core.file_limits import validate_file_limit_settings
|
|
612
|
+
|
|
613
|
+
try:
|
|
614
|
+
validate_file_limit_settings()
|
|
615
|
+
except ValueError as exc:
|
|
616
|
+
parser.error(str(exc))
|
|
617
|
+
|
|
618
|
+
try:
|
|
619
|
+
stateless_http = get_stateless_http()
|
|
620
|
+
except ValueError as exc:
|
|
621
|
+
parser.error(str(exc))
|
|
622
|
+
|
|
623
|
+
# Env var fallbacks for plugin users who configure via userConfig.
|
|
624
|
+
# Non-empty but invalid values fail closed to prevent silent access widening.
|
|
625
|
+
# Skip env fallbacks for mutually exclusive flags that were set on the CLI
|
|
626
|
+
# to avoid conflicts (e.g. WORKSPACE_MCP_READ_ONLY=true + --permissions).
|
|
627
|
+
_cli_has_tools = args.tools is not None
|
|
628
|
+
_cli_has_permissions = args.permissions is not None
|
|
629
|
+
_cli_has_read_only = args.read_only
|
|
630
|
+
|
|
631
|
+
def _exit_with_env_error(name: str, value: str, expected: str) -> None:
|
|
632
|
+
print(f"Error: invalid {name} {value!r}; expected {expected}.", file=sys.stderr)
|
|
633
|
+
sys.exit(1)
|
|
634
|
+
|
|
635
|
+
if args.tools is None and not _cli_has_permissions:
|
|
636
|
+
_env_tools = os.getenv("WORKSPACE_MCP_TOOLS", "").strip()
|
|
637
|
+
if _env_tools:
|
|
638
|
+
_parsed = [t.strip().lower() for t in _env_tools.split(",")]
|
|
639
|
+
_invalid = [t for t in _parsed if not t or t not in VALID_SERVICES]
|
|
640
|
+
if _invalid:
|
|
641
|
+
_exit_with_env_error(
|
|
642
|
+
"WORKSPACE_MCP_TOOLS",
|
|
643
|
+
_env_tools,
|
|
644
|
+
"comma-separated valid service names",
|
|
645
|
+
)
|
|
646
|
+
args.tools = _parsed
|
|
647
|
+
elif _cli_has_permissions and os.getenv("WORKSPACE_MCP_TOOLS", "").strip():
|
|
648
|
+
logger.info(
|
|
649
|
+
"WORKSPACE_MCP_TOOLS ignored because --permissions was provided on the CLI"
|
|
650
|
+
)
|
|
651
|
+
if args.tool_tier is None:
|
|
652
|
+
_env_tier = os.getenv("WORKSPACE_MCP_TOOL_TIER", "").strip().lower()
|
|
653
|
+
if _env_tier:
|
|
654
|
+
if _env_tier not in {"core", "extended", "complete"}:
|
|
655
|
+
_exit_with_env_error(
|
|
656
|
+
"WORKSPACE_MCP_TOOL_TIER", _env_tier, "core, extended, or complete"
|
|
657
|
+
)
|
|
658
|
+
args.tool_tier = _env_tier
|
|
659
|
+
# Subtractive, so it needs no conflict handling against the allowlist flags.
|
|
660
|
+
disabled_tools = resolve_disabled_tools(args.disabled_tools)
|
|
661
|
+
set_disabled_tools(disabled_tools)
|
|
662
|
+
if not args.read_only and not _cli_has_permissions:
|
|
663
|
+
_env_ro = os.getenv("WORKSPACE_MCP_READ_ONLY", "").strip().lower()
|
|
664
|
+
if _env_ro:
|
|
665
|
+
if _env_ro in {"true", "1", "yes"}:
|
|
666
|
+
args.read_only = True
|
|
667
|
+
elif _env_ro not in {"false", "0", "no"}:
|
|
668
|
+
_exit_with_env_error(
|
|
669
|
+
"WORKSPACE_MCP_READ_ONLY", _env_ro, "true/1/yes or false/0/no"
|
|
670
|
+
)
|
|
671
|
+
elif _cli_has_permissions and os.getenv("WORKSPACE_MCP_READ_ONLY", "").strip():
|
|
672
|
+
logger.info(
|
|
673
|
+
"WORKSPACE_MCP_READ_ONLY ignored because --permissions was provided on the CLI"
|
|
674
|
+
)
|
|
675
|
+
if args.permissions is None and not _cli_has_read_only and not _cli_has_tools:
|
|
676
|
+
_env_perms = os.getenv("WORKSPACE_MCP_PERMISSIONS", "").strip()
|
|
677
|
+
if _env_perms:
|
|
678
|
+
args.permissions = [p.lower() for p in _env_perms.split()]
|
|
679
|
+
elif (_cli_has_read_only or _cli_has_tools) and os.getenv(
|
|
680
|
+
"WORKSPACE_MCP_PERMISSIONS", ""
|
|
681
|
+
).strip():
|
|
682
|
+
_conflicts = [
|
|
683
|
+
name
|
|
684
|
+
for name, present in (
|
|
685
|
+
("--read-only", _cli_has_read_only),
|
|
686
|
+
("--tools", _cli_has_tools),
|
|
687
|
+
)
|
|
688
|
+
if present
|
|
689
|
+
]
|
|
690
|
+
logger.info(
|
|
691
|
+
"WORKSPACE_MCP_PERMISSIONS ignored because %s was provided on the CLI",
|
|
692
|
+
" and ".join(_conflicts),
|
|
693
|
+
)
|
|
694
|
+
if args.transport is None:
|
|
695
|
+
_env_transport = os.getenv("WORKSPACE_MCP_TRANSPORT", "").strip().lower()
|
|
696
|
+
if _env_transport:
|
|
697
|
+
if _env_transport not in {"stdio", "streamable-http"}:
|
|
698
|
+
_exit_with_env_error(
|
|
699
|
+
"WORKSPACE_MCP_TRANSPORT",
|
|
700
|
+
_env_transport,
|
|
701
|
+
"stdio or streamable-http",
|
|
702
|
+
)
|
|
703
|
+
args.transport = _env_transport
|
|
704
|
+
else:
|
|
705
|
+
args.transport = "stdio"
|
|
706
|
+
|
|
707
|
+
_env_http_port = os.getenv("WORKSPACE_MCP_HTTP_PORT", "").strip()
|
|
708
|
+
http_port = None
|
|
709
|
+
if _env_http_port:
|
|
710
|
+
try:
|
|
711
|
+
http_port = int(_env_http_port)
|
|
712
|
+
if not 1 <= http_port <= 65535:
|
|
713
|
+
raise ValueError("must be between 1 and 65535")
|
|
714
|
+
except ValueError as exc:
|
|
715
|
+
print(
|
|
716
|
+
f"Error: invalid WORKSPACE_MCP_HTTP_PORT '{_env_http_port}': {exc}.",
|
|
717
|
+
file=sys.stderr,
|
|
718
|
+
)
|
|
719
|
+
sys.exit(1)
|
|
720
|
+
|
|
721
|
+
# Validate mutually exclusive flags (settings can come from CLI flags or WORKSPACE_MCP_* env vars).
|
|
722
|
+
if args.permissions and args.read_only:
|
|
723
|
+
print(
|
|
724
|
+
"Error: --permissions and --read-only are mutually exclusive "
|
|
725
|
+
"(via CLI flag or WORKSPACE_MCP_PERMISSIONS / WORKSPACE_MCP_READ_ONLY env var). "
|
|
726
|
+
"Use service:readonly within --permissions instead.",
|
|
727
|
+
file=sys.stderr,
|
|
728
|
+
)
|
|
729
|
+
sys.exit(1)
|
|
730
|
+
if args.permissions and args.tools is not None:
|
|
731
|
+
print(
|
|
732
|
+
"Error: --permissions and --tools cannot be combined "
|
|
733
|
+
"(via CLI flag or WORKSPACE_MCP_PERMISSIONS / WORKSPACE_MCP_TOOLS env var). "
|
|
734
|
+
"Select services via --permissions (optionally with --tool-tier).",
|
|
735
|
+
file=sys.stderr,
|
|
736
|
+
)
|
|
737
|
+
sys.exit(1)
|
|
738
|
+
|
|
739
|
+
validate_streamable_http_auth(args.transport)
|
|
740
|
+
resolve_callback_port_for_transport(args.transport)
|
|
741
|
+
|
|
742
|
+
# Set port and base URI once for reuse throughout the function
|
|
743
|
+
if os.getenv("WORKSPACE_MCP_RESOLVED_PORT") == "1":
|
|
744
|
+
port = int(os.getenv("WORKSPACE_MCP_PORT", os.getenv("PORT", "8000")))
|
|
745
|
+
else:
|
|
746
|
+
port = int(os.getenv("PORT", os.getenv("WORKSPACE_MCP_PORT", "8000")))
|
|
747
|
+
base_uri = os.getenv("WORKSPACE_MCP_BASE_URI", "http://localhost")
|
|
748
|
+
host = resolve_bind_host_for_transport(args.transport)
|
|
749
|
+
external_url = os.getenv("WORKSPACE_EXTERNAL_URL")
|
|
750
|
+
display_url = external_url if external_url else f"{base_uri}:{port}"
|
|
751
|
+
|
|
752
|
+
try:
|
|
753
|
+
version = metadata.version("workspace-mcp")
|
|
754
|
+
except metadata.PackageNotFoundError:
|
|
755
|
+
version = "dev"
|
|
756
|
+
|
|
757
|
+
mode = "single-user" if args.single_user else "multi-user"
|
|
758
|
+
pyver = sys.version.split()[0]
|
|
759
|
+
|
|
760
|
+
flags = []
|
|
761
|
+
if args.read_only:
|
|
762
|
+
flags.append("read-only")
|
|
763
|
+
if args.permissions:
|
|
764
|
+
flags.append("granular permissions")
|
|
765
|
+
|
|
766
|
+
ui = StartupDisplay(safe_print)
|
|
767
|
+
ui.blank()
|
|
768
|
+
ui.rule()
|
|
769
|
+
ui.blank()
|
|
770
|
+
ui.banner(
|
|
771
|
+
wordmark_lines(
|
|
772
|
+
ui,
|
|
773
|
+
version=version,
|
|
774
|
+
transport=args.transport,
|
|
775
|
+
mode=mode,
|
|
776
|
+
python_version=pyver,
|
|
777
|
+
url=display_url if args.transport == "streamable-http" else None,
|
|
778
|
+
flags=flags,
|
|
779
|
+
)
|
|
780
|
+
)
|
|
781
|
+
|
|
782
|
+
ui.section("Configuration")
|
|
783
|
+
ui.fields(
|
|
784
|
+
[
|
|
785
|
+
("Credentials", describe_credential_config()),
|
|
786
|
+
(
|
|
787
|
+
"Modes",
|
|
788
|
+
describe_mode_config(disabled_tools, single_user=args.single_user),
|
|
789
|
+
),
|
|
790
|
+
]
|
|
791
|
+
)
|
|
792
|
+
|
|
793
|
+
# Import tool modules to register them with the MCP server via decorators.
|
|
794
|
+
tool_imports = {
|
|
795
|
+
svc: partial(import_module, mod) for svc, mod in SERVICE_MODULES.items()
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
# Determine which tools to import based on arguments
|
|
799
|
+
perms = None
|
|
800
|
+
if args.permissions:
|
|
801
|
+
# Granular permissions mode — parse and activate before tool selection
|
|
802
|
+
from auth.permissions import parse_permissions_arg, set_permissions
|
|
803
|
+
|
|
804
|
+
try:
|
|
805
|
+
perms = parse_permissions_arg(args.permissions)
|
|
806
|
+
except ValueError as e:
|
|
807
|
+
print(f"Error: {e}", file=sys.stderr)
|
|
808
|
+
sys.exit(1)
|
|
809
|
+
# Permissions implicitly defines which services to load
|
|
810
|
+
tools_to_import = list(perms.keys())
|
|
811
|
+
set_enabled_tool_names(None)
|
|
812
|
+
|
|
813
|
+
if args.tool_tier is not None:
|
|
814
|
+
# Combine with tier filtering within the permission-selected services
|
|
815
|
+
try:
|
|
816
|
+
tools_to_import, tier_tool_filter = resolve_permissions_mode_selection(
|
|
817
|
+
tools_to_import, args.tool_tier
|
|
818
|
+
)
|
|
819
|
+
set_enabled_tool_names(tier_tool_filter)
|
|
820
|
+
perms = narrow_permissions_to_services(perms, tools_to_import)
|
|
821
|
+
except Exception as e:
|
|
822
|
+
print(
|
|
823
|
+
f"Error loading tools for tier '{args.tool_tier}': {e}",
|
|
824
|
+
file=sys.stderr,
|
|
825
|
+
)
|
|
826
|
+
sys.exit(1)
|
|
827
|
+
set_permissions(perms)
|
|
828
|
+
elif args.tool_tier is not None:
|
|
829
|
+
# Use tier-based tool selection, optionally filtered by services
|
|
830
|
+
try:
|
|
831
|
+
tier_tools, suggested_services = resolve_tools_from_tier(
|
|
832
|
+
args.tool_tier, args.tools
|
|
833
|
+
)
|
|
834
|
+
|
|
835
|
+
# If --tools specified, use those services; otherwise use all services that have tier tools
|
|
836
|
+
if args.tools is not None:
|
|
837
|
+
tools_to_import = args.tools
|
|
838
|
+
else:
|
|
839
|
+
tools_to_import = suggested_services
|
|
840
|
+
|
|
841
|
+
# Set the specific tools that should be registered
|
|
842
|
+
set_enabled_tool_names(set(tier_tools))
|
|
843
|
+
except Exception as e:
|
|
844
|
+
fatal(ui, f"Error loading tools for tier '{args.tool_tier}'", str(e))
|
|
845
|
+
elif args.tools is not None:
|
|
846
|
+
# Use explicit tool list without tier filtering
|
|
847
|
+
tools_to_import = args.tools
|
|
848
|
+
# Don't filter individual tools when using explicit service list only
|
|
849
|
+
set_enabled_tool_names(None)
|
|
850
|
+
else:
|
|
851
|
+
# Default: import all tools
|
|
852
|
+
tools_to_import = tool_imports.keys()
|
|
853
|
+
# Don't filter individual tools when importing all
|
|
854
|
+
set_enabled_tool_names(None)
|
|
855
|
+
|
|
856
|
+
wrap_server_tool_method(server)
|
|
857
|
+
|
|
858
|
+
from auth.scopes import set_enabled_tools, set_read_only
|
|
859
|
+
|
|
860
|
+
set_enabled_tools(list(tools_to_import))
|
|
861
|
+
if args.read_only:
|
|
862
|
+
set_read_only(True)
|
|
863
|
+
|
|
864
|
+
loaded = []
|
|
865
|
+
failed = []
|
|
866
|
+
for tool in tools_to_import:
|
|
867
|
+
try:
|
|
868
|
+
tool_imports[tool]()
|
|
869
|
+
loaded.append(tool)
|
|
870
|
+
except ModuleNotFoundError as exc:
|
|
871
|
+
logger.error("Failed to import tool '%s': %s", tool, exc, exc_info=True)
|
|
872
|
+
failed.append((tool, exc))
|
|
873
|
+
|
|
874
|
+
# Filter tools based on tier configuration (if tier-based loading is enabled)
|
|
875
|
+
tools_removed = filter_server_tools(server)
|
|
876
|
+
mark_always_load_tools(server)
|
|
877
|
+
|
|
878
|
+
ui.section("Services")
|
|
879
|
+
ui.grid([(SERVICE_ICONS.get(t, "🔧"), t.title()) for t in loaded])
|
|
880
|
+
ui.blank()
|
|
881
|
+
|
|
882
|
+
summary = f"{len(loaded)} of {len(tool_imports)} services loaded"
|
|
883
|
+
if args.tool_tier is not None:
|
|
884
|
+
summary += f" · tier {args.tool_tier}"
|
|
885
|
+
if tools_removed:
|
|
886
|
+
summary += f" · {tools_removed} tools filtered out"
|
|
887
|
+
ui.step(summary)
|
|
888
|
+
for tool, exc in failed:
|
|
889
|
+
ui.step(f"{tool.title()} failed to load", state="fail")
|
|
890
|
+
ui.detail(str(exc))
|
|
891
|
+
|
|
892
|
+
if perms:
|
|
893
|
+
ui.blank()
|
|
894
|
+
ui.heading("Permissions")
|
|
895
|
+
ui.grid(
|
|
896
|
+
[
|
|
897
|
+
(SERVICE_ICONS.get(service, "🔧"), f"{service}:{level}")
|
|
898
|
+
for service, level in sorted(perms.items())
|
|
899
|
+
],
|
|
900
|
+
columns=3,
|
|
901
|
+
)
|
|
902
|
+
|
|
903
|
+
ui.section("Startup")
|
|
904
|
+
|
|
905
|
+
# Set global single-user mode flag
|
|
906
|
+
if args.single_user:
|
|
907
|
+
# Check for incompatible OAuth 2.1 mode
|
|
908
|
+
if os.getenv("MCP_ENABLE_OAUTH21", "false").lower() == "true":
|
|
909
|
+
fatal(
|
|
910
|
+
ui,
|
|
911
|
+
"Single-user mode is incompatible with OAuth 2.1 mode",
|
|
912
|
+
"Single-user mode is for legacy clients that pass user emails",
|
|
913
|
+
"OAuth 2.1 mode is for multi-user scenarios with bearer tokens",
|
|
914
|
+
"Choose one: --single-user OR MCP_ENABLE_OAUTH21=true",
|
|
915
|
+
)
|
|
916
|
+
|
|
917
|
+
if is_stateless_mode():
|
|
918
|
+
fatal(
|
|
919
|
+
ui,
|
|
920
|
+
"Single-user mode is incompatible with stateless mode",
|
|
921
|
+
"Stateless mode requires OAuth 2.1, which is multi-user",
|
|
922
|
+
)
|
|
923
|
+
|
|
924
|
+
if is_service_account_enabled():
|
|
925
|
+
fatal(
|
|
926
|
+
ui,
|
|
927
|
+
"Single-user mode is incompatible with service account mode",
|
|
928
|
+
"Service account mode handles auth via domain-wide delegation",
|
|
929
|
+
"Choose one: --single-user OR GOOGLE_SERVICE_ACCOUNT_KEY_FILE",
|
|
930
|
+
)
|
|
931
|
+
|
|
932
|
+
os.environ["MCP_SINGLE_USER_MODE"] = "1"
|
|
933
|
+
ui.step("Single-user mode enabled")
|
|
934
|
+
|
|
935
|
+
# Service account mode startup validation
|
|
936
|
+
if is_service_account_enabled():
|
|
937
|
+
user_email = os.getenv("USER_GOOGLE_EMAIL")
|
|
938
|
+
if not user_email:
|
|
939
|
+
fatal(
|
|
940
|
+
ui,
|
|
941
|
+
"Service account mode requires USER_GOOGLE_EMAIL",
|
|
942
|
+
"Set USER_GOOGLE_EMAIL to the domain user to impersonate",
|
|
943
|
+
)
|
|
944
|
+
# Validate service account key material before advertising readiness
|
|
945
|
+
sa_config = get_oauth_config()
|
|
946
|
+
try:
|
|
947
|
+
if sa_config.service_account_key_file:
|
|
948
|
+
with open(sa_config.service_account_key_file) as f:
|
|
949
|
+
key_data = json.load(f)
|
|
950
|
+
else:
|
|
951
|
+
key_data = json.loads(sa_config.service_account_key_json)
|
|
952
|
+
required_fields = {"type", "project_id", "private_key", "client_email"}
|
|
953
|
+
missing = required_fields - set(key_data.keys())
|
|
954
|
+
if missing:
|
|
955
|
+
fatal(
|
|
956
|
+
ui,
|
|
957
|
+
"Service account key is missing required fields",
|
|
958
|
+
", ".join(sorted(missing)),
|
|
959
|
+
)
|
|
960
|
+
if key_data.get("type") != "service_account":
|
|
961
|
+
fatal(
|
|
962
|
+
ui,
|
|
963
|
+
"Service account key has unexpected type",
|
|
964
|
+
repr(key_data.get("type")),
|
|
965
|
+
)
|
|
966
|
+
except FileNotFoundError as e:
|
|
967
|
+
fatal(ui, "Service account key file not found", str(e))
|
|
968
|
+
except json.JSONDecodeError as e:
|
|
969
|
+
fatal(ui, "Service account key contains invalid JSON", str(e))
|
|
970
|
+
except (IOError, OSError) as e:
|
|
971
|
+
fatal(ui, "Failed to read service account key", str(e))
|
|
972
|
+
ui.step("Service account mode enabled", "domain-wide delegation")
|
|
973
|
+
ui.detail(f"impersonating {user_email}")
|
|
974
|
+
|
|
975
|
+
backend = get_selected_backend()
|
|
976
|
+
|
|
977
|
+
# Check local credentials directory permissions only when using the local backend.
|
|
978
|
+
if (
|
|
979
|
+
not is_stateless_mode()
|
|
980
|
+
and not is_service_account_enabled()
|
|
981
|
+
and backend != "gcs"
|
|
982
|
+
):
|
|
983
|
+
try:
|
|
984
|
+
check_credentials_directory_permissions()
|
|
985
|
+
ui.step("Credentials directory verified")
|
|
986
|
+
except (PermissionError, OSError) as e:
|
|
987
|
+
fatal(
|
|
988
|
+
ui,
|
|
989
|
+
"Credentials directory permission check failed",
|
|
990
|
+
str(e),
|
|
991
|
+
"Ensure the service can create and write to the credentials directory",
|
|
992
|
+
)
|
|
993
|
+
else:
|
|
994
|
+
if is_stateless_mode():
|
|
995
|
+
skip_reason = "stateless mode"
|
|
996
|
+
elif is_service_account_enabled():
|
|
997
|
+
skip_reason = "service account mode"
|
|
998
|
+
else:
|
|
999
|
+
skip_reason = "gcs backend"
|
|
1000
|
+
ui.step(f"Credentials directory check skipped ({skip_reason})", state="skip")
|
|
1001
|
+
|
|
1002
|
+
if (
|
|
1003
|
+
backend == "gcs"
|
|
1004
|
+
and not is_stateless_mode()
|
|
1005
|
+
and not is_service_account_enabled()
|
|
1006
|
+
):
|
|
1007
|
+
try:
|
|
1008
|
+
from auth.credential_store import GCSCredentialStore
|
|
1009
|
+
|
|
1010
|
+
credential_store = get_credential_store()
|
|
1011
|
+
if not isinstance(credential_store, GCSCredentialStore):
|
|
1012
|
+
raise TypeError(
|
|
1013
|
+
"Configured credential store backend is 'gcs' but the store instance is not GCSCredentialStore"
|
|
1014
|
+
)
|
|
1015
|
+
|
|
1016
|
+
if credential_store.require_cmek:
|
|
1017
|
+
credential_store.verify_cmek()
|
|
1018
|
+
ui.step("GCS credential store verified")
|
|
1019
|
+
else:
|
|
1020
|
+
ui.step(
|
|
1021
|
+
"GCS credential store verification skipped",
|
|
1022
|
+
"require_cmek=False",
|
|
1023
|
+
state="skip",
|
|
1024
|
+
)
|
|
1025
|
+
except Exception as e:
|
|
1026
|
+
fatal(ui, "GCS credential store verification failed", str(e))
|
|
1027
|
+
|
|
1028
|
+
try:
|
|
1029
|
+
# Set transport mode for OAuth callback handling
|
|
1030
|
+
set_transport_mode(args.transport)
|
|
1031
|
+
|
|
1032
|
+
# Configure auth initialization for FastMCP lifecycle events
|
|
1033
|
+
if args.transport == "streamable-http":
|
|
1034
|
+
configure_server_for_http()
|
|
1035
|
+
ui.step("HTTP server", f"{base_uri}:{port}")
|
|
1036
|
+
if external_url:
|
|
1037
|
+
ui.detail(f"external URL {external_url}")
|
|
1038
|
+
else:
|
|
1039
|
+
ui.step("STDIO server")
|
|
1040
|
+
# The OAuth callback / attachment server is started lazily — only when
|
|
1041
|
+
# an auth flow is initiated or an attachment URL is handed out — so
|
|
1042
|
+
# short-lived spawns (e.g. client health checks) never bind a port and
|
|
1043
|
+
# cannot exhaust the 8000-8004 fallback range (see issue #832).
|
|
1044
|
+
if not is_service_account_enabled():
|
|
1045
|
+
ui.detail(
|
|
1046
|
+
f"OAuth callback starts on demand at {display_url}/oauth2callback"
|
|
1047
|
+
)
|
|
1048
|
+
|
|
1049
|
+
ui.step("Ready for MCP connections")
|
|
1050
|
+
|
|
1051
|
+
if args.transport == "streamable-http" and _env_http_port:
|
|
1052
|
+
add_startup_notice(
|
|
1053
|
+
"WORKSPACE_MCP_HTTP_PORT is ignored when transport is "
|
|
1054
|
+
"'streamable-http'; the primary server already serves HTTP on "
|
|
1055
|
+
"WORKSPACE_MCP_PORT/PORT."
|
|
1056
|
+
)
|
|
1057
|
+
|
|
1058
|
+
if STARTUP_NOTICES:
|
|
1059
|
+
ui.section("Notices")
|
|
1060
|
+
for message in STARTUP_NOTICES:
|
|
1061
|
+
ui.notice(message)
|
|
1062
|
+
|
|
1063
|
+
ui.blank()
|
|
1064
|
+
ui.rule()
|
|
1065
|
+
ui.blank()
|
|
1066
|
+
|
|
1067
|
+
if args.transport == "streamable-http":
|
|
1068
|
+
# Check port availability before starting HTTP server
|
|
1069
|
+
conflict = _http_port_conflict(host, port)
|
|
1070
|
+
if conflict is not None:
|
|
1071
|
+
fatal(ui, f"Cannot start HTTP server on {host}:{port}", conflict)
|
|
1072
|
+
|
|
1073
|
+
server.run(
|
|
1074
|
+
transport="streamable-http",
|
|
1075
|
+
host=host,
|
|
1076
|
+
port=port,
|
|
1077
|
+
stateless_http=is_stateless_mode() or stateless_http,
|
|
1078
|
+
show_banner=False,
|
|
1079
|
+
)
|
|
1080
|
+
else:
|
|
1081
|
+
if http_port is not None:
|
|
1082
|
+
# Dual transport: stdio for MCP client + HTTP for workspace-cli
|
|
1083
|
+
import asyncio
|
|
1084
|
+
import uvicorn
|
|
1085
|
+
|
|
1086
|
+
# Bind sidecar to loopback only — auth provider is not initialized
|
|
1087
|
+
# in stdio mode, so exposing this on 0.0.0.0 would allow unauthenticated access.
|
|
1088
|
+
http_host = "127.0.0.1"
|
|
1089
|
+
|
|
1090
|
+
async def _run_dual() -> None:
|
|
1091
|
+
"""Run stdio and HTTP transports concurrently."""
|
|
1092
|
+
http_available = True
|
|
1093
|
+
conflict = _http_port_conflict(http_host, http_port)
|
|
1094
|
+
if conflict is not None:
|
|
1095
|
+
logger.warning(
|
|
1096
|
+
"workspace-cli HTTP endpoint unavailable on port %d: %s",
|
|
1097
|
+
http_port,
|
|
1098
|
+
conflict,
|
|
1099
|
+
)
|
|
1100
|
+
http_available = False
|
|
1101
|
+
|
|
1102
|
+
http_srv = None
|
|
1103
|
+
http_task = None
|
|
1104
|
+
if http_available:
|
|
1105
|
+
app = server.http_app(path="/mcp")
|
|
1106
|
+
config = uvicorn.Config(
|
|
1107
|
+
app,
|
|
1108
|
+
host=http_host,
|
|
1109
|
+
port=http_port,
|
|
1110
|
+
log_level="warning",
|
|
1111
|
+
# Match FastMCP's own uvicorn config: uvicorn's "auto"
|
|
1112
|
+
# default resolves to the deprecated legacy-websockets
|
|
1113
|
+
# implementation whenever `websockets` is installed.
|
|
1114
|
+
ws="websockets-sansio",
|
|
1115
|
+
)
|
|
1116
|
+
http_srv = uvicorn.Server(config)
|
|
1117
|
+
http_task = asyncio.create_task(http_srv.serve())
|
|
1118
|
+
logger.info(
|
|
1119
|
+
"workspace-cli endpoint: http://%s:%d/mcp",
|
|
1120
|
+
http_host,
|
|
1121
|
+
http_port,
|
|
1122
|
+
)
|
|
1123
|
+
|
|
1124
|
+
try:
|
|
1125
|
+
await server.run_stdio_async(show_banner=False)
|
|
1126
|
+
finally:
|
|
1127
|
+
if http_srv:
|
|
1128
|
+
http_srv.should_exit = True
|
|
1129
|
+
if http_task:
|
|
1130
|
+
try:
|
|
1131
|
+
await asyncio.wait_for(http_task, timeout=5.0)
|
|
1132
|
+
except asyncio.TimeoutError:
|
|
1133
|
+
logger.warning(
|
|
1134
|
+
"HTTP sidecar did not exit within 5s; cancelled"
|
|
1135
|
+
)
|
|
1136
|
+
except asyncio.CancelledError:
|
|
1137
|
+
raise
|
|
1138
|
+
except Exception as exc:
|
|
1139
|
+
logger.warning(
|
|
1140
|
+
"HTTP sidecar ended with exception: %s", exc
|
|
1141
|
+
)
|
|
1142
|
+
|
|
1143
|
+
asyncio.run(_run_dual())
|
|
1144
|
+
else:
|
|
1145
|
+
server.run(show_banner=False)
|
|
1146
|
+
except KeyboardInterrupt:
|
|
1147
|
+
safe_print("\n👋 Server shutdown requested")
|
|
1148
|
+
# Clean up OAuth callback server if running
|
|
1149
|
+
from auth.oauth_callback_server import cleanup_oauth_callback_server
|
|
1150
|
+
|
|
1151
|
+
cleanup_oauth_callback_server()
|
|
1152
|
+
sys.exit(0)
|
|
1153
|
+
except Exception as e:
|
|
1154
|
+
safe_print(f"\n❌ Server error: {e}")
|
|
1155
|
+
logger.error(f"Unexpected error running server: {e}", exc_info=True)
|
|
1156
|
+
# Clean up OAuth callback server if running
|
|
1157
|
+
from auth.oauth_callback_server import cleanup_oauth_callback_server
|
|
1158
|
+
|
|
1159
|
+
cleanup_oauth_callback_server()
|
|
1160
|
+
sys.exit(1)
|
|
1161
|
+
finally:
|
|
1162
|
+
# External OAuth owns a bounded validation executor. Close it on every
|
|
1163
|
+
# server exit path, including normal uvicorn shutdown and startup failure.
|
|
1164
|
+
from core.server import close_auth_provider
|
|
1165
|
+
|
|
1166
|
+
close_auth_provider()
|
|
1167
|
+
|
|
1168
|
+
|
|
1169
|
+
if __name__ == "__main__":
|
|
1170
|
+
main()
|