fastmcp 2.12.1__py3-none-any.whl → 2.13.2__py3-none-any.whl
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.
- fastmcp/__init__.py +2 -2
- fastmcp/cli/cli.py +56 -36
- fastmcp/cli/install/__init__.py +2 -0
- fastmcp/cli/install/claude_code.py +7 -16
- fastmcp/cli/install/claude_desktop.py +4 -12
- fastmcp/cli/install/cursor.py +20 -30
- fastmcp/cli/install/gemini_cli.py +241 -0
- fastmcp/cli/install/mcp_json.py +4 -12
- fastmcp/cli/run.py +15 -94
- fastmcp/client/__init__.py +9 -9
- fastmcp/client/auth/oauth.py +117 -206
- fastmcp/client/client.py +123 -47
- fastmcp/client/elicitation.py +6 -1
- fastmcp/client/logging.py +18 -14
- fastmcp/client/oauth_callback.py +85 -171
- fastmcp/client/sampling.py +1 -1
- fastmcp/client/transports.py +81 -26
- fastmcp/contrib/component_manager/__init__.py +1 -1
- fastmcp/contrib/component_manager/component_manager.py +2 -2
- fastmcp/contrib/component_manager/component_service.py +7 -7
- fastmcp/contrib/mcp_mixin/README.md +35 -4
- fastmcp/contrib/mcp_mixin/__init__.py +2 -2
- fastmcp/contrib/mcp_mixin/mcp_mixin.py +54 -7
- fastmcp/experimental/sampling/handlers/openai.py +2 -2
- fastmcp/experimental/server/openapi/__init__.py +5 -8
- fastmcp/experimental/server/openapi/components.py +11 -7
- fastmcp/experimental/server/openapi/routing.py +2 -2
- fastmcp/experimental/utilities/openapi/__init__.py +10 -15
- fastmcp/experimental/utilities/openapi/director.py +16 -10
- fastmcp/experimental/utilities/openapi/json_schema_converter.py +6 -2
- fastmcp/experimental/utilities/openapi/models.py +3 -3
- fastmcp/experimental/utilities/openapi/parser.py +37 -16
- fastmcp/experimental/utilities/openapi/schemas.py +33 -7
- fastmcp/mcp_config.py +3 -4
- fastmcp/prompts/__init__.py +1 -1
- fastmcp/prompts/prompt.py +32 -27
- fastmcp/prompts/prompt_manager.py +16 -101
- fastmcp/resources/__init__.py +5 -5
- fastmcp/resources/resource.py +28 -20
- fastmcp/resources/resource_manager.py +9 -168
- fastmcp/resources/template.py +119 -27
- fastmcp/resources/types.py +30 -24
- fastmcp/server/__init__.py +1 -1
- fastmcp/server/auth/__init__.py +9 -5
- fastmcp/server/auth/auth.py +80 -47
- fastmcp/server/auth/handlers/authorize.py +326 -0
- fastmcp/server/auth/jwt_issuer.py +236 -0
- fastmcp/server/auth/middleware.py +96 -0
- fastmcp/server/auth/oauth_proxy.py +1556 -265
- fastmcp/server/auth/oidc_proxy.py +412 -0
- fastmcp/server/auth/providers/auth0.py +193 -0
- fastmcp/server/auth/providers/aws.py +263 -0
- fastmcp/server/auth/providers/azure.py +314 -129
- fastmcp/server/auth/providers/bearer.py +1 -1
- fastmcp/server/auth/providers/debug.py +114 -0
- fastmcp/server/auth/providers/descope.py +229 -0
- fastmcp/server/auth/providers/discord.py +308 -0
- fastmcp/server/auth/providers/github.py +31 -6
- fastmcp/server/auth/providers/google.py +50 -7
- fastmcp/server/auth/providers/in_memory.py +27 -3
- fastmcp/server/auth/providers/introspection.py +281 -0
- fastmcp/server/auth/providers/jwt.py +48 -31
- fastmcp/server/auth/providers/oci.py +233 -0
- fastmcp/server/auth/providers/scalekit.py +238 -0
- fastmcp/server/auth/providers/supabase.py +188 -0
- fastmcp/server/auth/providers/workos.py +37 -15
- fastmcp/server/context.py +194 -67
- fastmcp/server/dependencies.py +56 -16
- fastmcp/server/elicitation.py +1 -1
- fastmcp/server/http.py +57 -18
- fastmcp/server/low_level.py +121 -2
- fastmcp/server/middleware/__init__.py +1 -1
- fastmcp/server/middleware/caching.py +476 -0
- fastmcp/server/middleware/error_handling.py +14 -10
- fastmcp/server/middleware/logging.py +158 -116
- fastmcp/server/middleware/middleware.py +30 -16
- fastmcp/server/middleware/rate_limiting.py +3 -3
- fastmcp/server/middleware/tool_injection.py +116 -0
- fastmcp/server/openapi.py +15 -7
- fastmcp/server/proxy.py +22 -11
- fastmcp/server/server.py +744 -254
- fastmcp/settings.py +65 -15
- fastmcp/tools/__init__.py +1 -1
- fastmcp/tools/tool.py +173 -108
- fastmcp/tools/tool_manager.py +30 -112
- fastmcp/tools/tool_transform.py +13 -11
- fastmcp/utilities/cli.py +67 -28
- fastmcp/utilities/components.py +7 -2
- fastmcp/utilities/inspect.py +79 -23
- fastmcp/utilities/json_schema.py +21 -4
- fastmcp/utilities/json_schema_type.py +4 -4
- fastmcp/utilities/logging.py +182 -10
- fastmcp/utilities/mcp_server_config/__init__.py +3 -3
- fastmcp/utilities/mcp_server_config/v1/environments/base.py +1 -2
- fastmcp/utilities/mcp_server_config/v1/environments/uv.py +10 -45
- fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py +8 -7
- fastmcp/utilities/mcp_server_config/v1/schema.json +5 -1
- fastmcp/utilities/mcp_server_config/v1/sources/base.py +0 -1
- fastmcp/utilities/openapi.py +11 -11
- fastmcp/utilities/tests.py +93 -10
- fastmcp/utilities/types.py +87 -21
- fastmcp/utilities/ui.py +626 -0
- {fastmcp-2.12.1.dist-info → fastmcp-2.13.2.dist-info}/METADATA +141 -60
- fastmcp-2.13.2.dist-info/RECORD +144 -0
- {fastmcp-2.12.1.dist-info → fastmcp-2.13.2.dist-info}/WHEEL +1 -1
- fastmcp/cli/claude.py +0 -144
- fastmcp-2.12.1.dist-info/RECORD +0 -128
- {fastmcp-2.12.1.dist-info → fastmcp-2.13.2.dist-info}/entry_points.txt +0 -0
- {fastmcp-2.12.1.dist-info → fastmcp-2.13.2.dist-info}/licenses/LICENSE +0 -0
fastmcp/server/auth/auth.py
CHANGED
|
@@ -1,13 +1,9 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
-
from typing import Any
|
|
4
|
-
from urllib.parse import urljoin
|
|
3
|
+
from typing import Any, cast
|
|
5
4
|
|
|
6
5
|
from mcp.server.auth.middleware.auth_context import AuthContextMiddleware
|
|
7
|
-
from mcp.server.auth.middleware.bearer_auth import
|
|
8
|
-
BearerAuthBackend,
|
|
9
|
-
RequireAuthMiddleware,
|
|
10
|
-
)
|
|
6
|
+
from mcp.server.auth.middleware.bearer_auth import BearerAuthBackend
|
|
11
7
|
from mcp.server.auth.provider import (
|
|
12
8
|
AccessToken as _SDKAccessToken,
|
|
13
9
|
)
|
|
@@ -27,16 +23,20 @@ from mcp.server.auth.settings import (
|
|
|
27
23
|
ClientRegistrationOptions,
|
|
28
24
|
RevocationOptions,
|
|
29
25
|
)
|
|
30
|
-
from pydantic import AnyHttpUrl
|
|
26
|
+
from pydantic import AnyHttpUrl, Field
|
|
31
27
|
from starlette.middleware import Middleware
|
|
32
28
|
from starlette.middleware.authentication import AuthenticationMiddleware
|
|
33
29
|
from starlette.routing import Route
|
|
34
30
|
|
|
31
|
+
from fastmcp.utilities.logging import get_logger
|
|
32
|
+
|
|
33
|
+
logger = get_logger(__name__)
|
|
34
|
+
|
|
35
35
|
|
|
36
36
|
class AccessToken(_SDKAccessToken):
|
|
37
37
|
"""AccessToken that includes all JWT claims."""
|
|
38
38
|
|
|
39
|
-
claims: dict[str, Any] =
|
|
39
|
+
claims: dict[str, Any] = Field(default_factory=dict)
|
|
40
40
|
|
|
41
41
|
|
|
42
42
|
class AuthProvider(TokenVerifierProtocol):
|
|
@@ -82,10 +82,10 @@ class AuthProvider(TokenVerifierProtocol):
|
|
|
82
82
|
def get_routes(
|
|
83
83
|
self,
|
|
84
84
|
mcp_path: str | None = None,
|
|
85
|
-
mcp_endpoint: Any | None = None,
|
|
86
85
|
) -> list[Route]:
|
|
87
|
-
"""Get
|
|
86
|
+
"""Get all routes for this authentication provider.
|
|
88
87
|
|
|
88
|
+
This includes both well-known discovery routes and operational routes.
|
|
89
89
|
Each provider is responsible for creating whatever routes it needs:
|
|
90
90
|
- TokenVerifier: typically no routes (default implementation)
|
|
91
91
|
- RemoteAuthProvider: protected resource metadata routes
|
|
@@ -94,30 +94,45 @@ class AuthProvider(TokenVerifierProtocol):
|
|
|
94
94
|
|
|
95
95
|
Args:
|
|
96
96
|
mcp_path: The path where the MCP endpoint is mounted (e.g., "/mcp")
|
|
97
|
-
|
|
97
|
+
This is used to advertise the resource URL in metadata, but the
|
|
98
|
+
provider does not create the actual MCP endpoint route.
|
|
98
99
|
|
|
99
100
|
Returns:
|
|
100
|
-
List of routes for this provider
|
|
101
|
+
List of all routes for this provider (excluding the MCP endpoint itself)
|
|
101
102
|
"""
|
|
103
|
+
return []
|
|
102
104
|
|
|
103
|
-
|
|
105
|
+
def get_well_known_routes(
|
|
106
|
+
self,
|
|
107
|
+
mcp_path: str | None = None,
|
|
108
|
+
) -> list[Route]:
|
|
109
|
+
"""Get well-known discovery routes for this authentication provider.
|
|
104
110
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
resource_metadata_url = self._get_resource_url(
|
|
108
|
-
"/.well-known/oauth-protected-resource"
|
|
109
|
-
)
|
|
111
|
+
This is a utility method that filters get_routes() to return only
|
|
112
|
+
well-known discovery routes (those starting with /.well-known/).
|
|
110
113
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
mcp_endpoint, self.required_scopes, resource_metadata_url
|
|
116
|
-
),
|
|
117
|
-
)
|
|
118
|
-
)
|
|
114
|
+
Well-known routes provide OAuth metadata and discovery endpoints that
|
|
115
|
+
clients use to discover authentication capabilities. These routes should
|
|
116
|
+
be mounted at the root level of the application to comply with RFC 8414
|
|
117
|
+
and RFC 9728.
|
|
119
118
|
|
|
120
|
-
|
|
119
|
+
Common well-known routes:
|
|
120
|
+
- /.well-known/oauth-authorization-server (authorization server metadata)
|
|
121
|
+
- /.well-known/oauth-protected-resource/* (protected resource metadata)
|
|
122
|
+
|
|
123
|
+
Args:
|
|
124
|
+
mcp_path: The path where the MCP endpoint is mounted (e.g., "/mcp")
|
|
125
|
+
This is used to construct path-scoped well-known URLs.
|
|
126
|
+
|
|
127
|
+
Returns:
|
|
128
|
+
List of well-known discovery routes (typically mounted at root level)
|
|
129
|
+
"""
|
|
130
|
+
all_routes = self.get_routes(mcp_path)
|
|
131
|
+
return [
|
|
132
|
+
route
|
|
133
|
+
for route in all_routes
|
|
134
|
+
if isinstance(route, Route) and route.path.startswith("/.well-known/")
|
|
135
|
+
]
|
|
121
136
|
|
|
122
137
|
def get_middleware(self) -> list:
|
|
123
138
|
"""Get HTTP application-level middleware for this auth provider.
|
|
@@ -146,8 +161,9 @@ class AuthProvider(TokenVerifierProtocol):
|
|
|
146
161
|
return None
|
|
147
162
|
|
|
148
163
|
if path:
|
|
149
|
-
|
|
150
|
-
|
|
164
|
+
prefix = str(self.base_url).rstrip("/")
|
|
165
|
+
suffix = path.lstrip("/")
|
|
166
|
+
return AnyHttpUrl(f"{prefix}/{suffix}")
|
|
151
167
|
return self.base_url
|
|
152
168
|
|
|
153
169
|
|
|
@@ -225,14 +241,12 @@ class RemoteAuthProvider(AuthProvider):
|
|
|
225
241
|
def get_routes(
|
|
226
242
|
self,
|
|
227
243
|
mcp_path: str | None = None,
|
|
228
|
-
mcp_endpoint: Any | None = None,
|
|
229
244
|
) -> list[Route]:
|
|
230
|
-
"""Get
|
|
245
|
+
"""Get routes for this provider.
|
|
231
246
|
|
|
232
|
-
Creates protected resource metadata routes
|
|
247
|
+
Creates protected resource metadata routes (RFC 9728).
|
|
233
248
|
"""
|
|
234
|
-
|
|
235
|
-
routes = super().get_routes(mcp_path, mcp_endpoint)
|
|
249
|
+
routes = []
|
|
236
250
|
|
|
237
251
|
# Get the resource URL based on the MCP path
|
|
238
252
|
resource_url = self._get_resource_url(mcp_path)
|
|
@@ -284,20 +298,27 @@ class OAuthProvider(
|
|
|
284
298
|
required_scopes: Scopes that are required for all requests.
|
|
285
299
|
"""
|
|
286
300
|
|
|
287
|
-
# Convert URLs to proper types
|
|
288
|
-
if isinstance(base_url, str):
|
|
289
|
-
base_url = AnyHttpUrl(base_url)
|
|
290
|
-
|
|
291
301
|
super().__init__(base_url=base_url, required_scopes=required_scopes)
|
|
292
|
-
self.base_url = base_url
|
|
293
302
|
|
|
294
303
|
if issuer_url is None:
|
|
295
|
-
self.issuer_url = base_url
|
|
304
|
+
self.issuer_url = self.base_url
|
|
296
305
|
elif isinstance(issuer_url, str):
|
|
297
306
|
self.issuer_url = AnyHttpUrl(issuer_url)
|
|
298
307
|
else:
|
|
299
308
|
self.issuer_url = issuer_url
|
|
300
309
|
|
|
310
|
+
# Log if issuer_url and base_url differ (requires additional setup)
|
|
311
|
+
if (
|
|
312
|
+
self.base_url is not None
|
|
313
|
+
and self.issuer_url is not None
|
|
314
|
+
and str(self.base_url) != str(self.issuer_url)
|
|
315
|
+
):
|
|
316
|
+
logger.info(
|
|
317
|
+
f"OAuth endpoints at {self.base_url}, issuer at {self.issuer_url}. "
|
|
318
|
+
f"Ensure well-known routes are accessible at root ({self.issuer_url}/.well-known/). "
|
|
319
|
+
f"See: https://gofastmcp.com/deployment/http#mounting-authenticated-servers"
|
|
320
|
+
)
|
|
321
|
+
|
|
301
322
|
# Initialize OAuth Authorization Server Provider
|
|
302
323
|
OAuthAuthorizationServerProvider.__init__(self)
|
|
303
324
|
|
|
@@ -326,23 +347,29 @@ class OAuthProvider(
|
|
|
326
347
|
def get_routes(
|
|
327
348
|
self,
|
|
328
349
|
mcp_path: str | None = None,
|
|
329
|
-
mcp_endpoint: Any | None = None,
|
|
330
350
|
) -> list[Route]:
|
|
331
351
|
"""Get OAuth authorization server routes and optional protected resource routes.
|
|
332
352
|
|
|
333
353
|
This method creates the full set of OAuth routes including:
|
|
334
354
|
- Standard OAuth authorization server routes (/.well-known/oauth-authorization-server, /authorize, /token, etc.)
|
|
335
355
|
- Optional protected resource routes
|
|
336
|
-
- Protected MCP endpoints if provided
|
|
337
356
|
|
|
338
357
|
Returns:
|
|
339
358
|
List of OAuth routes
|
|
340
359
|
"""
|
|
341
360
|
|
|
342
361
|
# Create standard OAuth authorization server routes
|
|
362
|
+
# Pass base_url as issuer_url to ensure metadata declares endpoints where
|
|
363
|
+
# they're actually accessible (operational routes are mounted at
|
|
364
|
+
# base_url)
|
|
365
|
+
assert self.base_url is not None # typing check
|
|
366
|
+
assert (
|
|
367
|
+
self.issuer_url is not None
|
|
368
|
+
) # typing check (issuer_url defaults to base_url)
|
|
369
|
+
|
|
343
370
|
oauth_routes = create_auth_routes(
|
|
344
371
|
provider=self,
|
|
345
|
-
issuer_url=self.
|
|
372
|
+
issuer_url=self.base_url,
|
|
346
373
|
service_documentation_url=self.service_documentation_url,
|
|
347
374
|
client_registration_options=self.client_registration_options,
|
|
348
375
|
revocation_options=self.revocation_options,
|
|
@@ -353,14 +380,20 @@ class OAuthProvider(
|
|
|
353
380
|
|
|
354
381
|
# Add protected resource routes if this server is also acting as a resource server
|
|
355
382
|
if resource_url:
|
|
383
|
+
supported_scopes = (
|
|
384
|
+
self.client_registration_options.valid_scopes
|
|
385
|
+
if self.client_registration_options
|
|
386
|
+
and self.client_registration_options.valid_scopes
|
|
387
|
+
else self.required_scopes
|
|
388
|
+
)
|
|
356
389
|
protected_routes = create_protected_resource_routes(
|
|
357
390
|
resource_url=resource_url,
|
|
358
|
-
authorization_servers=[self.issuer_url],
|
|
359
|
-
scopes_supported=
|
|
391
|
+
authorization_servers=[cast(AnyHttpUrl, self.issuer_url)],
|
|
392
|
+
scopes_supported=supported_scopes,
|
|
360
393
|
)
|
|
361
394
|
oauth_routes.extend(protected_routes)
|
|
362
395
|
|
|
363
|
-
# Add
|
|
364
|
-
oauth_routes.extend(super().get_routes(mcp_path
|
|
396
|
+
# Add base routes
|
|
397
|
+
oauth_routes.extend(super().get_routes(mcp_path))
|
|
365
398
|
|
|
366
399
|
return oauth_routes
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
"""Enhanced authorization handler with improved error responses.
|
|
2
|
+
|
|
3
|
+
This module provides an enhanced authorization handler that wraps the MCP SDK's
|
|
4
|
+
AuthorizationHandler to provide better error messages when clients attempt to
|
|
5
|
+
authorize with unregistered client IDs.
|
|
6
|
+
|
|
7
|
+
The enhancement adds:
|
|
8
|
+
- Content negotiation: HTML for browsers, JSON for API clients
|
|
9
|
+
- Enhanced JSON responses with registration endpoint hints
|
|
10
|
+
- Styled HTML error pages with registration links/forms
|
|
11
|
+
- Link headers pointing to registration endpoints
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
from typing import TYPE_CHECKING
|
|
18
|
+
|
|
19
|
+
from mcp.server.auth.handlers.authorize import (
|
|
20
|
+
AuthorizationHandler as SDKAuthorizationHandler,
|
|
21
|
+
)
|
|
22
|
+
from pydantic import AnyHttpUrl
|
|
23
|
+
from starlette.requests import Request
|
|
24
|
+
from starlette.responses import Response
|
|
25
|
+
|
|
26
|
+
from fastmcp.utilities.logging import get_logger
|
|
27
|
+
from fastmcp.utilities.ui import (
|
|
28
|
+
INFO_BOX_STYLES,
|
|
29
|
+
TOOLTIP_STYLES,
|
|
30
|
+
create_logo,
|
|
31
|
+
create_page,
|
|
32
|
+
create_secure_html_response,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
if TYPE_CHECKING:
|
|
36
|
+
from mcp.server.auth.provider import OAuthAuthorizationServerProvider
|
|
37
|
+
|
|
38
|
+
logger = get_logger(__name__)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def create_unregistered_client_html(
|
|
42
|
+
client_id: str,
|
|
43
|
+
registration_endpoint: str,
|
|
44
|
+
discovery_endpoint: str,
|
|
45
|
+
server_name: str | None = None,
|
|
46
|
+
server_icon_url: str | None = None,
|
|
47
|
+
title: str = "Client Not Registered",
|
|
48
|
+
) -> str:
|
|
49
|
+
"""Create styled HTML error page for unregistered client attempts.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
client_id: The unregistered client ID that was provided
|
|
53
|
+
registration_endpoint: URL of the registration endpoint
|
|
54
|
+
discovery_endpoint: URL of the OAuth metadata discovery endpoint
|
|
55
|
+
server_name: Optional server name for branding
|
|
56
|
+
server_icon_url: Optional server icon URL
|
|
57
|
+
title: Page title
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
HTML string for the error page
|
|
61
|
+
"""
|
|
62
|
+
import html as html_module
|
|
63
|
+
|
|
64
|
+
client_id_escaped = html_module.escape(client_id)
|
|
65
|
+
|
|
66
|
+
# Main error message
|
|
67
|
+
error_box = f"""
|
|
68
|
+
<div class="info-box error">
|
|
69
|
+
<p>The client ID <code>{client_id_escaped}</code> was not found in the server's client registry.</p>
|
|
70
|
+
</div>
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
# What to do - yellow warning box
|
|
74
|
+
warning_box = """
|
|
75
|
+
<div class="info-box warning">
|
|
76
|
+
<p>Your MCP client opened this page to complete OAuth authorization,
|
|
77
|
+
but the server did not recognize its client ID. To fix this:</p>
|
|
78
|
+
<ul>
|
|
79
|
+
<li>Close this browser window</li>
|
|
80
|
+
<li>Clear authentication tokens in your MCP client (or restart it)</li>
|
|
81
|
+
<li>Try connecting again - your client should automatically re-register</li>
|
|
82
|
+
</ul>
|
|
83
|
+
</div>
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
# Help link with tooltip (similar to consent screen)
|
|
87
|
+
help_link = """
|
|
88
|
+
<div class="help-link-container">
|
|
89
|
+
<span class="help-link">
|
|
90
|
+
Why am I seeing this?
|
|
91
|
+
<span class="tooltip">
|
|
92
|
+
OAuth 2.0 requires clients to register before authorization.
|
|
93
|
+
This server returned a 400 error because the provided client
|
|
94
|
+
ID was not found.
|
|
95
|
+
<br><br>
|
|
96
|
+
In browser-delegated OAuth flows, your application cannot
|
|
97
|
+
detect this error automatically; it's waiting for a
|
|
98
|
+
callback that will never arrive. You must manually clear
|
|
99
|
+
auth tokens and reconnect.
|
|
100
|
+
</span>
|
|
101
|
+
</span>
|
|
102
|
+
</div>
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
# Build page content
|
|
106
|
+
content = f"""
|
|
107
|
+
<div class="container">
|
|
108
|
+
{create_logo(icon_url=server_icon_url, alt_text=server_name or "FastMCP")}
|
|
109
|
+
<h1>{title}</h1>
|
|
110
|
+
{error_box}
|
|
111
|
+
{warning_box}
|
|
112
|
+
</div>
|
|
113
|
+
{help_link}
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
# Use same styles as consent page
|
|
117
|
+
additional_styles = (
|
|
118
|
+
INFO_BOX_STYLES
|
|
119
|
+
+ TOOLTIP_STYLES
|
|
120
|
+
+ """
|
|
121
|
+
/* Error variant for info-box */
|
|
122
|
+
.info-box.error {
|
|
123
|
+
background: #fef2f2;
|
|
124
|
+
border-color: #f87171;
|
|
125
|
+
}
|
|
126
|
+
.info-box.error strong {
|
|
127
|
+
color: #991b1b;
|
|
128
|
+
}
|
|
129
|
+
/* Warning variant for info-box (yellow) */
|
|
130
|
+
.info-box.warning {
|
|
131
|
+
background: #fffbeb;
|
|
132
|
+
border-color: #fbbf24;
|
|
133
|
+
}
|
|
134
|
+
.info-box.warning strong {
|
|
135
|
+
color: #92400e;
|
|
136
|
+
}
|
|
137
|
+
.info-box code {
|
|
138
|
+
background: rgba(0, 0, 0, 0.05);
|
|
139
|
+
padding: 2px 6px;
|
|
140
|
+
border-radius: 3px;
|
|
141
|
+
font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace;
|
|
142
|
+
font-size: 0.9em;
|
|
143
|
+
}
|
|
144
|
+
.info-box ul {
|
|
145
|
+
margin: 10px 0;
|
|
146
|
+
padding-left: 20px;
|
|
147
|
+
}
|
|
148
|
+
.info-box li {
|
|
149
|
+
margin: 6px 0;
|
|
150
|
+
}
|
|
151
|
+
"""
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
return create_page(
|
|
155
|
+
content=content,
|
|
156
|
+
title=title,
|
|
157
|
+
additional_styles=additional_styles,
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class AuthorizationHandler(SDKAuthorizationHandler):
|
|
162
|
+
"""Authorization handler with enhanced error responses for unregistered clients.
|
|
163
|
+
|
|
164
|
+
This handler extends the MCP SDK's AuthorizationHandler to provide better UX
|
|
165
|
+
when clients attempt to authorize without being registered. It implements
|
|
166
|
+
content negotiation to return:
|
|
167
|
+
|
|
168
|
+
- HTML error pages for browser requests
|
|
169
|
+
- Enhanced JSON with registration hints for API clients
|
|
170
|
+
- Link headers pointing to registration endpoints
|
|
171
|
+
|
|
172
|
+
This maintains OAuth 2.1 compliance (returns 400 for invalid client_id)
|
|
173
|
+
while providing actionable guidance to fix the error.
|
|
174
|
+
"""
|
|
175
|
+
|
|
176
|
+
def __init__(
|
|
177
|
+
self,
|
|
178
|
+
provider: OAuthAuthorizationServerProvider,
|
|
179
|
+
base_url: AnyHttpUrl | str,
|
|
180
|
+
server_name: str | None = None,
|
|
181
|
+
server_icon_url: str | None = None,
|
|
182
|
+
):
|
|
183
|
+
"""Initialize the enhanced authorization handler.
|
|
184
|
+
|
|
185
|
+
Args:
|
|
186
|
+
provider: OAuth authorization server provider
|
|
187
|
+
base_url: Base URL of the server for constructing endpoint URLs
|
|
188
|
+
server_name: Optional server name for branding
|
|
189
|
+
server_icon_url: Optional server icon URL for branding
|
|
190
|
+
"""
|
|
191
|
+
super().__init__(provider)
|
|
192
|
+
self._base_url = str(base_url).rstrip("/")
|
|
193
|
+
self._server_name = server_name
|
|
194
|
+
self._server_icon_url = server_icon_url
|
|
195
|
+
|
|
196
|
+
async def handle(self, request: Request) -> Response:
|
|
197
|
+
"""Handle authorization request with enhanced error responses.
|
|
198
|
+
|
|
199
|
+
This method extends the SDK's authorization handler and intercepts
|
|
200
|
+
errors for unregistered clients to provide better error responses
|
|
201
|
+
based on the client's Accept header.
|
|
202
|
+
|
|
203
|
+
Args:
|
|
204
|
+
request: The authorization request
|
|
205
|
+
|
|
206
|
+
Returns:
|
|
207
|
+
Response (redirect on success, error response on failure)
|
|
208
|
+
"""
|
|
209
|
+
# Call the SDK handler
|
|
210
|
+
response = await super().handle(request)
|
|
211
|
+
|
|
212
|
+
# Check if this is a client not found error
|
|
213
|
+
if response.status_code == 400:
|
|
214
|
+
# Try to extract client_id from request for enhanced error
|
|
215
|
+
client_id: str | None = None
|
|
216
|
+
if request.method == "GET":
|
|
217
|
+
client_id = request.query_params.get("client_id")
|
|
218
|
+
else:
|
|
219
|
+
form = await request.form()
|
|
220
|
+
client_id_value = form.get("client_id")
|
|
221
|
+
# Ensure client_id is a string, not UploadFile
|
|
222
|
+
if isinstance(client_id_value, str):
|
|
223
|
+
client_id = client_id_value
|
|
224
|
+
|
|
225
|
+
# If we have a client_id and the error is about it not being found,
|
|
226
|
+
# enhance the response
|
|
227
|
+
if client_id:
|
|
228
|
+
try:
|
|
229
|
+
# Check if response body contains "not found" error
|
|
230
|
+
if hasattr(response, "body"):
|
|
231
|
+
body = json.loads(bytes(response.body))
|
|
232
|
+
if (
|
|
233
|
+
body.get("error") == "invalid_request"
|
|
234
|
+
and "not found" in body.get("error_description", "").lower()
|
|
235
|
+
):
|
|
236
|
+
return await self._create_enhanced_error_response(
|
|
237
|
+
request, client_id, body.get("state")
|
|
238
|
+
)
|
|
239
|
+
except Exception:
|
|
240
|
+
# If we can't parse the response, just return the original
|
|
241
|
+
pass
|
|
242
|
+
|
|
243
|
+
return response
|
|
244
|
+
|
|
245
|
+
async def _create_enhanced_error_response(
|
|
246
|
+
self, request: Request, client_id: str, state: str | None
|
|
247
|
+
) -> Response:
|
|
248
|
+
"""Create enhanced error response with content negotiation.
|
|
249
|
+
|
|
250
|
+
Args:
|
|
251
|
+
request: The original request
|
|
252
|
+
client_id: The unregistered client ID
|
|
253
|
+
state: The state parameter from the request
|
|
254
|
+
|
|
255
|
+
Returns:
|
|
256
|
+
HTML or JSON error response based on Accept header
|
|
257
|
+
"""
|
|
258
|
+
registration_endpoint = f"{self._base_url}/register"
|
|
259
|
+
discovery_endpoint = f"{self._base_url}/.well-known/oauth-authorization-server"
|
|
260
|
+
|
|
261
|
+
# Extract server metadata from app state (same pattern as consent screen)
|
|
262
|
+
from fastmcp.server.server import FastMCP
|
|
263
|
+
|
|
264
|
+
fastmcp = getattr(request.app.state, "fastmcp_server", None)
|
|
265
|
+
|
|
266
|
+
if isinstance(fastmcp, FastMCP):
|
|
267
|
+
server_name = fastmcp.name
|
|
268
|
+
icons = fastmcp.icons
|
|
269
|
+
server_icon_url = icons[0].src if icons else None
|
|
270
|
+
else:
|
|
271
|
+
server_name = self._server_name
|
|
272
|
+
server_icon_url = self._server_icon_url
|
|
273
|
+
|
|
274
|
+
# Check Accept header for content negotiation
|
|
275
|
+
accept = request.headers.get("accept", "")
|
|
276
|
+
|
|
277
|
+
# Prefer HTML for browsers
|
|
278
|
+
if "text/html" in accept:
|
|
279
|
+
html = create_unregistered_client_html(
|
|
280
|
+
client_id=client_id,
|
|
281
|
+
registration_endpoint=registration_endpoint,
|
|
282
|
+
discovery_endpoint=discovery_endpoint,
|
|
283
|
+
server_name=server_name,
|
|
284
|
+
server_icon_url=server_icon_url,
|
|
285
|
+
)
|
|
286
|
+
response = create_secure_html_response(html, status_code=400)
|
|
287
|
+
else:
|
|
288
|
+
# Return enhanced JSON for API clients
|
|
289
|
+
from mcp.server.auth.handlers.authorize import AuthorizationErrorResponse
|
|
290
|
+
|
|
291
|
+
error_data = AuthorizationErrorResponse(
|
|
292
|
+
error="invalid_request",
|
|
293
|
+
error_description=(
|
|
294
|
+
f"Client ID '{client_id}' is not registered with this server. "
|
|
295
|
+
f"MCP clients should automatically re-register by sending a POST request to "
|
|
296
|
+
f"the registration_endpoint and retry authorization. "
|
|
297
|
+
f"If this persists, clear cached authentication tokens and reconnect."
|
|
298
|
+
),
|
|
299
|
+
state=state,
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
# Add extra fields to help clients discover registration
|
|
303
|
+
error_dict = error_data.model_dump(exclude_none=True)
|
|
304
|
+
error_dict["registration_endpoint"] = registration_endpoint
|
|
305
|
+
error_dict["authorization_server_metadata"] = discovery_endpoint
|
|
306
|
+
|
|
307
|
+
from starlette.responses import JSONResponse
|
|
308
|
+
|
|
309
|
+
response = JSONResponse(
|
|
310
|
+
status_code=400,
|
|
311
|
+
content=error_dict,
|
|
312
|
+
headers={"Cache-Control": "no-store"},
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
# Add Link header for registration endpoint discovery
|
|
316
|
+
response.headers["Link"] = (
|
|
317
|
+
f'<{registration_endpoint}>; rel="http://oauth.net/core/2.1/#registration"'
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
logger.info(
|
|
321
|
+
"Unregistered client_id=%s, returned %s error response",
|
|
322
|
+
client_id,
|
|
323
|
+
"HTML" if "text/html" in accept else "JSON",
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
return response
|