@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,330 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Granular per-service permission levels.
|
|
3
|
+
|
|
4
|
+
Each service has named permission levels (cumulative), mapping to a list of
|
|
5
|
+
OAuth scopes. The levels for a service are ordered from least to most
|
|
6
|
+
permissive — requesting level N implicitly includes all scopes from levels < N.
|
|
7
|
+
|
|
8
|
+
Usage:
|
|
9
|
+
--permissions gmail:organize drive:readonly
|
|
10
|
+
|
|
11
|
+
Gmail levels: readonly, organize, drafts, send, full
|
|
12
|
+
Tasks levels: readonly, manage, full
|
|
13
|
+
Other services: readonly, full (extensible by adding entries to SERVICE_PERMISSION_LEVELS)
|
|
14
|
+
|
|
15
|
+
Joining levels with ``+`` (``gmail:readonly+send``) grants only the scopes each
|
|
16
|
+
named level adds, without the levels in between.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import logging
|
|
20
|
+
from typing import Dict, FrozenSet, Iterable, List, Optional, Tuple
|
|
21
|
+
|
|
22
|
+
from auth.scopes import (
|
|
23
|
+
GMAIL_READONLY_SCOPE,
|
|
24
|
+
GMAIL_LABELS_SCOPE,
|
|
25
|
+
GMAIL_MODIFY_SCOPE,
|
|
26
|
+
GMAIL_COMPOSE_SCOPE,
|
|
27
|
+
GMAIL_SEND_SCOPE,
|
|
28
|
+
GMAIL_SETTINGS_BASIC_SCOPE,
|
|
29
|
+
DRIVE_READONLY_SCOPE,
|
|
30
|
+
DRIVE_FILE_SCOPE,
|
|
31
|
+
DRIVE_SCOPE,
|
|
32
|
+
CALENDAR_READONLY_SCOPE,
|
|
33
|
+
CALENDAR_EVENTS_SCOPE,
|
|
34
|
+
CALENDAR_SCOPE,
|
|
35
|
+
DOCS_READONLY_SCOPE,
|
|
36
|
+
DOCS_WRITE_SCOPE,
|
|
37
|
+
SHEETS_READONLY_SCOPE,
|
|
38
|
+
SHEETS_WRITE_SCOPE,
|
|
39
|
+
CHAT_READONLY_SCOPE,
|
|
40
|
+
CHAT_WRITE_SCOPE,
|
|
41
|
+
CHAT_SPACES_SCOPE,
|
|
42
|
+
CHAT_SPACES_READONLY_SCOPE,
|
|
43
|
+
CHAT_MEMBERSHIPS_READONLY_SCOPE,
|
|
44
|
+
FORMS_BODY_SCOPE,
|
|
45
|
+
FORMS_BODY_READONLY_SCOPE,
|
|
46
|
+
FORMS_RESPONSES_READONLY_SCOPE,
|
|
47
|
+
SLIDES_SCOPE,
|
|
48
|
+
SLIDES_READONLY_SCOPE,
|
|
49
|
+
TASKS_SCOPE,
|
|
50
|
+
TASKS_READONLY_SCOPE,
|
|
51
|
+
CONTACTS_SCOPE,
|
|
52
|
+
CONTACTS_READONLY_SCOPE,
|
|
53
|
+
CONTACTS_OTHER_READONLY_SCOPE,
|
|
54
|
+
CUSTOM_SEARCH_SCOPE,
|
|
55
|
+
SCRIPT_PROJECTS_SCOPE,
|
|
56
|
+
SCRIPT_PROJECTS_READONLY_SCOPE,
|
|
57
|
+
SCRIPT_DEPLOYMENTS_SCOPE,
|
|
58
|
+
SCRIPT_DEPLOYMENTS_READONLY_SCOPE,
|
|
59
|
+
SCRIPT_PROCESSES_READONLY_SCOPE,
|
|
60
|
+
SCRIPT_METRICS_SCOPE,
|
|
61
|
+
SCRIPT_EXTERNAL_REQUEST_SCOPE,
|
|
62
|
+
SCRIPT_SCRIPTAPP_SCOPE,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
logger = logging.getLogger(__name__)
|
|
66
|
+
|
|
67
|
+
# Ordered permission levels per service.
|
|
68
|
+
# Each entry is (level_name, [additional_scopes_at_this_level]).
|
|
69
|
+
# Scopes are CUMULATIVE: level N includes all scopes from levels 0..N.
|
|
70
|
+
SERVICE_PERMISSION_LEVELS: Dict[str, List[Tuple[str, List[str]]]] = {
|
|
71
|
+
"gmail": [
|
|
72
|
+
("readonly", [GMAIL_READONLY_SCOPE]),
|
|
73
|
+
("organize", [GMAIL_LABELS_SCOPE, GMAIL_MODIFY_SCOPE]),
|
|
74
|
+
("drafts", [GMAIL_COMPOSE_SCOPE]),
|
|
75
|
+
("send", [GMAIL_SEND_SCOPE]),
|
|
76
|
+
("full", [GMAIL_SETTINGS_BASIC_SCOPE]),
|
|
77
|
+
],
|
|
78
|
+
"drive": [
|
|
79
|
+
("readonly", [DRIVE_READONLY_SCOPE]),
|
|
80
|
+
("full", [DRIVE_SCOPE, DRIVE_FILE_SCOPE]),
|
|
81
|
+
],
|
|
82
|
+
"calendar": [
|
|
83
|
+
("readonly", [CALENDAR_READONLY_SCOPE]),
|
|
84
|
+
("full", [CALENDAR_SCOPE, CALENDAR_EVENTS_SCOPE]),
|
|
85
|
+
],
|
|
86
|
+
"docs": [
|
|
87
|
+
("readonly", [DOCS_READONLY_SCOPE, DRIVE_READONLY_SCOPE]),
|
|
88
|
+
("full", [DOCS_WRITE_SCOPE, DRIVE_READONLY_SCOPE, DRIVE_FILE_SCOPE]),
|
|
89
|
+
],
|
|
90
|
+
"sheets": [
|
|
91
|
+
("readonly", [SHEETS_READONLY_SCOPE, DRIVE_READONLY_SCOPE]),
|
|
92
|
+
("full", [SHEETS_WRITE_SCOPE, DRIVE_READONLY_SCOPE, DRIVE_FILE_SCOPE]),
|
|
93
|
+
],
|
|
94
|
+
"chat": [
|
|
95
|
+
(
|
|
96
|
+
"readonly",
|
|
97
|
+
[
|
|
98
|
+
CHAT_READONLY_SCOPE,
|
|
99
|
+
CHAT_SPACES_READONLY_SCOPE,
|
|
100
|
+
CHAT_MEMBERSHIPS_READONLY_SCOPE,
|
|
101
|
+
CONTACTS_READONLY_SCOPE,
|
|
102
|
+
],
|
|
103
|
+
),
|
|
104
|
+
("full", [CHAT_WRITE_SCOPE, CHAT_SPACES_SCOPE]),
|
|
105
|
+
],
|
|
106
|
+
"forms": [
|
|
107
|
+
("readonly", [FORMS_BODY_READONLY_SCOPE, FORMS_RESPONSES_READONLY_SCOPE]),
|
|
108
|
+
("full", [FORMS_BODY_SCOPE, FORMS_RESPONSES_READONLY_SCOPE]),
|
|
109
|
+
],
|
|
110
|
+
"slides": [
|
|
111
|
+
("readonly", [SLIDES_READONLY_SCOPE]),
|
|
112
|
+
("full", [SLIDES_SCOPE]),
|
|
113
|
+
],
|
|
114
|
+
"tasks": [
|
|
115
|
+
("readonly", [TASKS_READONLY_SCOPE]),
|
|
116
|
+
("manage", [TASKS_SCOPE]),
|
|
117
|
+
("full", []),
|
|
118
|
+
],
|
|
119
|
+
"contacts": [
|
|
120
|
+
("readonly", [CONTACTS_READONLY_SCOPE, CONTACTS_OTHER_READONLY_SCOPE]),
|
|
121
|
+
("full", [CONTACTS_SCOPE]),
|
|
122
|
+
],
|
|
123
|
+
"search": [
|
|
124
|
+
("readonly", [CUSTOM_SEARCH_SCOPE]),
|
|
125
|
+
("full", [CUSTOM_SEARCH_SCOPE]),
|
|
126
|
+
],
|
|
127
|
+
"appscript": [
|
|
128
|
+
(
|
|
129
|
+
"readonly",
|
|
130
|
+
[
|
|
131
|
+
SCRIPT_PROJECTS_READONLY_SCOPE,
|
|
132
|
+
SCRIPT_DEPLOYMENTS_READONLY_SCOPE,
|
|
133
|
+
SCRIPT_PROCESSES_READONLY_SCOPE,
|
|
134
|
+
SCRIPT_METRICS_SCOPE,
|
|
135
|
+
DRIVE_READONLY_SCOPE,
|
|
136
|
+
],
|
|
137
|
+
),
|
|
138
|
+
(
|
|
139
|
+
"full",
|
|
140
|
+
[
|
|
141
|
+
SCRIPT_PROJECTS_SCOPE,
|
|
142
|
+
SCRIPT_DEPLOYMENTS_SCOPE,
|
|
143
|
+
SCRIPT_PROCESSES_READONLY_SCOPE,
|
|
144
|
+
SCRIPT_METRICS_SCOPE,
|
|
145
|
+
SCRIPT_EXTERNAL_REQUEST_SCOPE,
|
|
146
|
+
SCRIPT_SCRIPTAPP_SCOPE,
|
|
147
|
+
DRIVE_SCOPE,
|
|
148
|
+
],
|
|
149
|
+
),
|
|
150
|
+
],
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
# Actions denied at specific permission levels.
|
|
154
|
+
# Maps service -> level -> frozenset of denied action names.
|
|
155
|
+
# Levels not listed here (or services without entries) deny nothing.
|
|
156
|
+
SERVICE_DENIED_ACTIONS: Dict[str, Dict[str, FrozenSet[str]]] = {
|
|
157
|
+
"tasks": {
|
|
158
|
+
"manage": frozenset({"delete", "clear_completed"}),
|
|
159
|
+
},
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def is_action_denied(service: str, action: str) -> bool:
|
|
164
|
+
"""Check whether *action* is denied for *service* under current permissions.
|
|
165
|
+
|
|
166
|
+
Returns ``False`` when granular permissions mode is not active, when the
|
|
167
|
+
service has no permission entry, or when the configured level does not
|
|
168
|
+
deny the action. A ``+`` union uses the denials of its highest level.
|
|
169
|
+
"""
|
|
170
|
+
if _PERMISSIONS is None:
|
|
171
|
+
return False
|
|
172
|
+
level = _PERMISSIONS.get(service)
|
|
173
|
+
if level is None:
|
|
174
|
+
return False
|
|
175
|
+
if "+" in level:
|
|
176
|
+
level = max(level.split("+"), key=get_valid_levels(service).index)
|
|
177
|
+
denied = SERVICE_DENIED_ACTIONS.get(service, {}).get(level, frozenset())
|
|
178
|
+
return action in denied
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
# Module-level state: parsed --permissions config
|
|
182
|
+
# Dict mapping service_name -> level_name, e.g. {"gmail": "organize"}
|
|
183
|
+
_PERMISSIONS: Optional[Dict[str, str]] = None
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def set_permissions(permissions: Optional[Dict[str, str]]) -> None:
|
|
187
|
+
"""Set granular permissions from parsed --permissions argument."""
|
|
188
|
+
global _PERMISSIONS
|
|
189
|
+
_PERMISSIONS = permissions
|
|
190
|
+
if permissions is not None:
|
|
191
|
+
# Debug level: the startup screen lists the per-service levels.
|
|
192
|
+
logger.debug("Granular permissions set: %s", permissions)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def get_permissions() -> Optional[Dict[str, str]]:
|
|
196
|
+
"""Return current permissions dict, or None if not using granular mode."""
|
|
197
|
+
return _PERMISSIONS
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def is_permissions_mode() -> bool:
|
|
201
|
+
"""Check if granular permissions mode is active."""
|
|
202
|
+
return _PERMISSIONS is not None
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def get_scopes_for_permission(service: str, level: str) -> List[str]:
|
|
206
|
+
"""
|
|
207
|
+
Get scopes for a service at a given permission level.
|
|
208
|
+
|
|
209
|
+
Returns all scopes up to and including the named level, or only the named
|
|
210
|
+
levels' own scopes for a ``+`` union.
|
|
211
|
+
Raises ValueError if service or level is unknown.
|
|
212
|
+
"""
|
|
213
|
+
if "+" in level:
|
|
214
|
+
return get_scopes_for_union(service, level.split("+"))
|
|
215
|
+
|
|
216
|
+
levels = SERVICE_PERMISSION_LEVELS.get(service)
|
|
217
|
+
if levels is None:
|
|
218
|
+
raise ValueError(f"Unknown service: '{service}'")
|
|
219
|
+
|
|
220
|
+
cumulative: List[str] = []
|
|
221
|
+
found = False
|
|
222
|
+
for level_name, level_scopes in levels:
|
|
223
|
+
cumulative.extend(level_scopes)
|
|
224
|
+
if level_name == level:
|
|
225
|
+
found = True
|
|
226
|
+
break
|
|
227
|
+
|
|
228
|
+
if not found:
|
|
229
|
+
valid = [name for name, _ in levels]
|
|
230
|
+
raise ValueError(
|
|
231
|
+
f"Unknown permission level '{level}' for service '{service}'. "
|
|
232
|
+
f"Valid levels: {valid}"
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
return sorted(set(cumulative))
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def get_scopes_for_union(service: str, levels: Iterable[str]) -> List[str]:
|
|
239
|
+
"""Get only the scopes each named level adds. Raises ValueError if any is unknown."""
|
|
240
|
+
service_levels = SERVICE_PERMISSION_LEVELS.get(service)
|
|
241
|
+
if service_levels is None:
|
|
242
|
+
raise ValueError(f"Unknown service: '{service}'")
|
|
243
|
+
requested = set(levels)
|
|
244
|
+
if not requested:
|
|
245
|
+
raise ValueError(f"Empty level set for service '{service}'")
|
|
246
|
+
|
|
247
|
+
additive_scopes = dict(service_levels)
|
|
248
|
+
unknown = sorted(requested.difference(additive_scopes))
|
|
249
|
+
if unknown:
|
|
250
|
+
raise ValueError(
|
|
251
|
+
f"Unknown permission level '{unknown[0]}' for service '{service}'. "
|
|
252
|
+
f"Valid levels: {list(additive_scopes)}"
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
return sorted({scope for level in requested for scope in additive_scopes[level]})
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def get_all_permission_scopes() -> List[str]:
|
|
259
|
+
"""
|
|
260
|
+
Get the combined scopes for all services at their configured permission levels.
|
|
261
|
+
|
|
262
|
+
Only meaningful when is_permissions_mode() is True.
|
|
263
|
+
"""
|
|
264
|
+
if _PERMISSIONS is None:
|
|
265
|
+
return []
|
|
266
|
+
|
|
267
|
+
all_scopes: set[str] = set()
|
|
268
|
+
for service, level in _PERMISSIONS.items():
|
|
269
|
+
all_scopes.update(get_scopes_for_permission(service, level))
|
|
270
|
+
return list(all_scopes)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def get_allowed_scopes_set() -> Optional[set[str]]:
|
|
274
|
+
"""
|
|
275
|
+
Get the set of allowed scopes under permissions mode (for tool filtering).
|
|
276
|
+
|
|
277
|
+
Returns None if permissions mode is not active.
|
|
278
|
+
"""
|
|
279
|
+
if _PERMISSIONS is None:
|
|
280
|
+
return None
|
|
281
|
+
return set(get_all_permission_scopes())
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def get_valid_levels(service: str) -> List[str]:
|
|
285
|
+
"""Get valid permission level names for a service."""
|
|
286
|
+
levels = SERVICE_PERMISSION_LEVELS.get(service)
|
|
287
|
+
if levels is None:
|
|
288
|
+
return []
|
|
289
|
+
return [name for name, _ in levels]
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def parse_permissions_arg(permissions_list: List[str]) -> Dict[str, str]:
|
|
293
|
+
"""
|
|
294
|
+
Parse --permissions arguments like ["gmail:organize", "drive:full"] or
|
|
295
|
+
["gmail:readonly+send"].
|
|
296
|
+
|
|
297
|
+
Returns dict mapping service -> level.
|
|
298
|
+
Raises ValueError on parse errors (unknown service, invalid level, bad format).
|
|
299
|
+
"""
|
|
300
|
+
result: Dict[str, str] = {}
|
|
301
|
+
for entry in permissions_list:
|
|
302
|
+
if ":" not in entry:
|
|
303
|
+
raise ValueError(
|
|
304
|
+
f"Invalid permission format: '{entry}'. "
|
|
305
|
+
f"Expected 'service:level' (e.g., 'gmail:organize', 'drive:readonly')"
|
|
306
|
+
)
|
|
307
|
+
service, level = entry.split(":", 1)
|
|
308
|
+
if service in result:
|
|
309
|
+
raise ValueError(f"Duplicate service in permissions: '{service}'")
|
|
310
|
+
if service not in SERVICE_PERMISSION_LEVELS:
|
|
311
|
+
raise ValueError(
|
|
312
|
+
f"Unknown service: '{service}'. "
|
|
313
|
+
f"Valid services: {sorted(SERVICE_PERMISSION_LEVELS.keys())}"
|
|
314
|
+
)
|
|
315
|
+
valid = get_valid_levels(service)
|
|
316
|
+
parts = level.split("+")
|
|
317
|
+
if len(parts) > 1 and not all(parts):
|
|
318
|
+
raise ValueError(
|
|
319
|
+
f"Invalid union spec for service '{service}': '{level}'. "
|
|
320
|
+
f"Expected non-empty level names separated by '+' "
|
|
321
|
+
f"(e.g., 'gmail:readonly+send')"
|
|
322
|
+
)
|
|
323
|
+
for part in parts:
|
|
324
|
+
if part not in valid:
|
|
325
|
+
raise ValueError(
|
|
326
|
+
f"Unknown level '{part}' for service '{service}'. "
|
|
327
|
+
f"Valid levels: {valid}"
|
|
328
|
+
)
|
|
329
|
+
result[service] = level
|
|
330
|
+
return result
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Port resolver for late-binding the workspace-mcp OAuth callback server.
|
|
3
|
+
|
|
4
|
+
Probes a preferred port plus a small fallback range at process start;
|
|
5
|
+
the first available port is bound and surfaced through startup logs so
|
|
6
|
+
redirect URIs are composed from the actual bound port.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import errno
|
|
12
|
+
import logging
|
|
13
|
+
import os
|
|
14
|
+
import socket
|
|
15
|
+
from typing import List, Optional
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
DEFAULT_PREFERRED_PORT = 8000
|
|
20
|
+
DEFAULT_FALLBACK_COUNT = 4
|
|
21
|
+
RESOLVED_PORT_ENV = "WORKSPACE_MCP_RESOLVED_PORT"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class NoAvailablePortError(RuntimeError):
|
|
25
|
+
"""Raised when no port in the preferred + fallback range is free."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class PortConfigError(RuntimeError):
|
|
29
|
+
"""Raised when a port-related env var contains a non-integer value."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _candidate_ports(preferred: int, fallback_count: int) -> List[int]:
|
|
33
|
+
return [preferred] + [preferred + i for i in range(1, max(0, fallback_count) + 1)]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _is_port_free(host: str, port: int) -> bool:
|
|
37
|
+
"""
|
|
38
|
+
Test whether a TCP port is genuinely free for the OAuth callback server.
|
|
39
|
+
|
|
40
|
+
Two-stage probe:
|
|
41
|
+
1. CONNECT to 127.0.0.1:port -- detects an existing listener regardless of
|
|
42
|
+
which interface they bound to (on macOS, SO_REUSEADDR lets a 0.0.0.0
|
|
43
|
+
bind succeed even when 127.0.0.1 is already listening, so a bind probe
|
|
44
|
+
alone gives a false-negative). Since the OAuth callback URI is always
|
|
45
|
+
http://localhost:port, anything listening on loopback is a collision.
|
|
46
|
+
2. BIND with SO_REUSEADDR=0 (default) on the requested host -- catches
|
|
47
|
+
TIME_WAIT and BSD-style local conflicts.
|
|
48
|
+
"""
|
|
49
|
+
try:
|
|
50
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
51
|
+
s.settimeout(0.5)
|
|
52
|
+
if s.connect_ex(("127.0.0.1", port)) == 0:
|
|
53
|
+
logger.debug(
|
|
54
|
+
"Port resolver: port %d rejected -- existing listener on 127.0.0.1",
|
|
55
|
+
port,
|
|
56
|
+
)
|
|
57
|
+
return False
|
|
58
|
+
except OSError:
|
|
59
|
+
pass
|
|
60
|
+
|
|
61
|
+
try:
|
|
62
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
63
|
+
s.bind((host, port))
|
|
64
|
+
return True
|
|
65
|
+
except OSError as exc:
|
|
66
|
+
logger.debug(
|
|
67
|
+
"Port resolver: bind %s:%d failed -- %s (%s)",
|
|
68
|
+
host,
|
|
69
|
+
port,
|
|
70
|
+
errno.errorcode.get(exc.errno, exc.errno),
|
|
71
|
+
exc.strerror,
|
|
72
|
+
)
|
|
73
|
+
return False
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def resolve_port(
|
|
77
|
+
preferred: Optional[int] = None,
|
|
78
|
+
fallback_count: Optional[int] = None,
|
|
79
|
+
host: Optional[str] = None,
|
|
80
|
+
allow_fallback: bool = True,
|
|
81
|
+
) -> int:
|
|
82
|
+
"""
|
|
83
|
+
Resolve the first available port in [preferred, preferred+1, ..., preferred+fallback_count].
|
|
84
|
+
|
|
85
|
+
Reads defaults from env when args are None:
|
|
86
|
+
WORKSPACE_MCP_PORT (default 8000) -- preferred port
|
|
87
|
+
WORKSPACE_MCP_PORT_FALLBACK_COUNT (default 4) -- fallback slots
|
|
88
|
+
WORKSPACE_MCP_HOST (default 0.0.0.0) -- bind host
|
|
89
|
+
|
|
90
|
+
Side effect: mutates os.environ["WORKSPACE_MCP_PORT"] to the resolved port,
|
|
91
|
+
so every downstream reader (auth.oauth_config singleton on next reload,
|
|
92
|
+
core.config.WORKSPACE_MCP_PORT after explicit refresh, attachment_storage)
|
|
93
|
+
sees the bound port. Callers should call reload_oauth_config() after this
|
|
94
|
+
function to pick up the new value in the OAuthConfig singleton.
|
|
95
|
+
|
|
96
|
+
Returns the first-available port. Raises NoAvailablePortError if every
|
|
97
|
+
candidate is in use, or PortConfigError if a port env var is invalid.
|
|
98
|
+
"""
|
|
99
|
+
if preferred is None:
|
|
100
|
+
raw = os.getenv(
|
|
101
|
+
"PORT", os.getenv("WORKSPACE_MCP_PORT", str(DEFAULT_PREFERRED_PORT))
|
|
102
|
+
)
|
|
103
|
+
try:
|
|
104
|
+
preferred = int(raw)
|
|
105
|
+
except ValueError as exc:
|
|
106
|
+
env_name = "PORT" if os.getenv("PORT") else "WORKSPACE_MCP_PORT"
|
|
107
|
+
raise PortConfigError(
|
|
108
|
+
f"{env_name} must be an integer, got {raw!r}"
|
|
109
|
+
) from exc
|
|
110
|
+
if fallback_count is None:
|
|
111
|
+
raw = os.getenv(
|
|
112
|
+
"WORKSPACE_MCP_PORT_FALLBACK_COUNT", str(DEFAULT_FALLBACK_COUNT)
|
|
113
|
+
)
|
|
114
|
+
try:
|
|
115
|
+
fallback_count = int(raw)
|
|
116
|
+
except ValueError as exc:
|
|
117
|
+
raise PortConfigError(
|
|
118
|
+
f"WORKSPACE_MCP_PORT_FALLBACK_COUNT must be an integer, got {raw!r}"
|
|
119
|
+
) from exc
|
|
120
|
+
if host is None:
|
|
121
|
+
host = os.getenv("WORKSPACE_MCP_HOST", "0.0.0.0")
|
|
122
|
+
if not allow_fallback:
|
|
123
|
+
fallback_count = 0
|
|
124
|
+
|
|
125
|
+
candidates = _candidate_ports(preferred, fallback_count)
|
|
126
|
+
logger.debug(
|
|
127
|
+
"Port resolver: probing %s on host %s (fallback %s)",
|
|
128
|
+
candidates,
|
|
129
|
+
host,
|
|
130
|
+
"enabled" if allow_fallback else "disabled",
|
|
131
|
+
)
|
|
132
|
+
for port in candidates:
|
|
133
|
+
if _is_port_free(host, port):
|
|
134
|
+
if port == preferred:
|
|
135
|
+
# Debug level: the startup screen shows the resolved callback URL.
|
|
136
|
+
logger.debug("Port resolver: bound preferred port %d", port)
|
|
137
|
+
else:
|
|
138
|
+
logger.warning(
|
|
139
|
+
"Port resolver: preferred port %d unavailable; falling back to %d "
|
|
140
|
+
"(checked range %s)",
|
|
141
|
+
preferred,
|
|
142
|
+
port,
|
|
143
|
+
candidates,
|
|
144
|
+
)
|
|
145
|
+
os.environ["WORKSPACE_MCP_PORT"] = str(port)
|
|
146
|
+
os.environ[RESOLVED_PORT_ENV] = "1"
|
|
147
|
+
return port
|
|
148
|
+
|
|
149
|
+
raise NoAvailablePortError(
|
|
150
|
+
f"No available port in range {candidates}; all in use. "
|
|
151
|
+
f"Set WORKSPACE_MCP_PORT to a different preferred port, or "
|
|
152
|
+
f"increase WORKSPACE_MCP_PORT_FALLBACK_COUNT."
|
|
153
|
+
)
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Request-scoped authenticated identity for the active MCP request.
|
|
2
|
+
|
|
3
|
+
``AuthInfoMiddleware`` re-derives the caller's identity on every tool and prompt
|
|
4
|
+
call and records it here. Both keys are written with ``serializable=False``, which
|
|
5
|
+
keeps them in FastMCP's request-scoped dict (``Context._request_state``) rather
|
|
6
|
+
than the session-scoped state store. That matters twice over:
|
|
7
|
+
|
|
8
|
+
* Identity cannot outlive the request it was derived from. A client that opens a
|
|
9
|
+
fresh MCP session per tool call no longer accumulates state-store keys, and a
|
|
10
|
+
request that fails authentication cannot observe an earlier request's principal.
|
|
11
|
+
* Concurrent requests sharing one MCP session each get their own identity instead
|
|
12
|
+
of racing over a single session-scoped key.
|
|
13
|
+
|
|
14
|
+
``reset_request_identity`` shadows both keys with ``None`` at request entry.
|
|
15
|
+
``Context.get_state`` tests membership in the request-scoped dict before falling
|
|
16
|
+
back to the session store, so a ``None`` shadow neutralises any legacy
|
|
17
|
+
session-scoped identity without deleting it. Nothing in this module reclaims store
|
|
18
|
+
memory: residue left in a caller-supplied ``session_state_store`` stays put and
|
|
19
|
+
expires on FastMCP's own TTL. It simply cannot be read while a request is in
|
|
20
|
+
flight.
|
|
21
|
+
|
|
22
|
+
Every identity write goes through this module so that no authentication path can
|
|
23
|
+
accidentally choose session scope.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
import logging
|
|
27
|
+
from typing import NamedTuple
|
|
28
|
+
|
|
29
|
+
from fastmcp import Context
|
|
30
|
+
from fastmcp.server.dependencies import get_context
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
# The only two identity keys any code reads. Deliberately not a general-purpose
|
|
35
|
+
# auth-state bag: extra keys were removed because nothing consumed them.
|
|
36
|
+
_REQUEST_IDENTITY_STATE_KEYS = ("authenticated_user_email", "authenticated_via")
|
|
37
|
+
_EMAIL_KEY, _VIA_KEY = _REQUEST_IDENTITY_STATE_KEYS
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class RequestIdentity(NamedTuple):
|
|
41
|
+
"""The principal resolved for the current request, if any."""
|
|
42
|
+
|
|
43
|
+
email: str | None
|
|
44
|
+
via: str | None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
async def reset_request_identity(ctx: Context) -> None:
|
|
48
|
+
"""Shadow any inherited identity with request-scoped ``None``.
|
|
49
|
+
|
|
50
|
+
Call once at request entry, before any authentication path runs, so a request
|
|
51
|
+
that resolves no principal reads ``None`` instead of falling through to a
|
|
52
|
+
session-scoped value left by an earlier request.
|
|
53
|
+
"""
|
|
54
|
+
for key in _REQUEST_IDENTITY_STATE_KEYS:
|
|
55
|
+
await ctx.set_state(key, None, serializable=False)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
async def set_request_identity(ctx: Context, *, email: str, via: str) -> None:
|
|
59
|
+
"""Record the verified principal for the current request only.
|
|
60
|
+
|
|
61
|
+
``via`` names the authentication path that resolved ``email`` and is itself
|
|
62
|
+
security-relevant: ``require_gateway_principal`` accepts a principal only when
|
|
63
|
+
it came from ``gateway_assertion``.
|
|
64
|
+
"""
|
|
65
|
+
await ctx.set_state(_EMAIL_KEY, email, serializable=False)
|
|
66
|
+
await ctx.set_state(_VIA_KEY, via, serializable=False)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
async def get_request_identity(ctx: Context | None = None) -> RequestIdentity | None:
|
|
70
|
+
"""Return the current request's principal, or ``None`` outside an MCP request.
|
|
71
|
+
|
|
72
|
+
``ctx`` defaults to the ambient FastMCP context. ``None`` is returned when
|
|
73
|
+
there is no usable request context at all -- either no active ``Context``, or
|
|
74
|
+
one whose MCP session is not yet established -- which lets callers raise their
|
|
75
|
+
own domain error rather than leaking a FastMCP ``RuntimeError``. A live request
|
|
76
|
+
that simply failed to authenticate yields ``RequestIdentity(None, None)``.
|
|
77
|
+
"""
|
|
78
|
+
try:
|
|
79
|
+
if ctx is None:
|
|
80
|
+
ctx = get_context()
|
|
81
|
+
return RequestIdentity(
|
|
82
|
+
email=await ctx.get_state(_EMAIL_KEY),
|
|
83
|
+
via=await ctx.get_state(_VIA_KEY),
|
|
84
|
+
)
|
|
85
|
+
except RuntimeError as exc:
|
|
86
|
+
# FastMCP raises RuntimeError both for "no active context" and for
|
|
87
|
+
# "session not established yet" (state keys are session-prefixed).
|
|
88
|
+
logger.debug("No usable MCP request context for identity lookup: %s", exc)
|
|
89
|
+
return None
|