fastmcp 2.12.4__py3-none-any.whl → 2.13.0__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.
Files changed (72) hide show
  1. fastmcp/cli/cli.py +7 -6
  2. fastmcp/cli/install/claude_code.py +6 -6
  3. fastmcp/cli/install/claude_desktop.py +3 -3
  4. fastmcp/cli/install/cursor.py +7 -7
  5. fastmcp/cli/install/gemini_cli.py +3 -3
  6. fastmcp/cli/install/mcp_json.py +3 -3
  7. fastmcp/cli/run.py +13 -8
  8. fastmcp/client/auth/oauth.py +100 -208
  9. fastmcp/client/client.py +11 -11
  10. fastmcp/client/logging.py +18 -14
  11. fastmcp/client/oauth_callback.py +85 -171
  12. fastmcp/client/transports.py +77 -22
  13. fastmcp/contrib/component_manager/component_service.py +6 -6
  14. fastmcp/contrib/mcp_mixin/README.md +32 -1
  15. fastmcp/contrib/mcp_mixin/mcp_mixin.py +14 -2
  16. fastmcp/experimental/utilities/openapi/json_schema_converter.py +4 -0
  17. fastmcp/experimental/utilities/openapi/parser.py +23 -3
  18. fastmcp/prompts/prompt.py +13 -6
  19. fastmcp/prompts/prompt_manager.py +16 -101
  20. fastmcp/resources/resource.py +13 -6
  21. fastmcp/resources/resource_manager.py +5 -164
  22. fastmcp/resources/template.py +107 -17
  23. fastmcp/resources/types.py +30 -24
  24. fastmcp/server/auth/auth.py +40 -32
  25. fastmcp/server/auth/handlers/authorize.py +324 -0
  26. fastmcp/server/auth/jwt_issuer.py +236 -0
  27. fastmcp/server/auth/middleware.py +96 -0
  28. fastmcp/server/auth/oauth_proxy.py +1256 -242
  29. fastmcp/server/auth/oidc_proxy.py +23 -6
  30. fastmcp/server/auth/providers/auth0.py +40 -21
  31. fastmcp/server/auth/providers/aws.py +29 -3
  32. fastmcp/server/auth/providers/azure.py +178 -127
  33. fastmcp/server/auth/providers/descope.py +4 -6
  34. fastmcp/server/auth/providers/github.py +29 -8
  35. fastmcp/server/auth/providers/google.py +30 -9
  36. fastmcp/server/auth/providers/introspection.py +281 -0
  37. fastmcp/server/auth/providers/jwt.py +8 -2
  38. fastmcp/server/auth/providers/scalekit.py +179 -0
  39. fastmcp/server/auth/providers/supabase.py +172 -0
  40. fastmcp/server/auth/providers/workos.py +32 -14
  41. fastmcp/server/context.py +122 -36
  42. fastmcp/server/http.py +58 -18
  43. fastmcp/server/low_level.py +121 -2
  44. fastmcp/server/middleware/caching.py +469 -0
  45. fastmcp/server/middleware/error_handling.py +6 -2
  46. fastmcp/server/middleware/logging.py +48 -37
  47. fastmcp/server/middleware/middleware.py +28 -15
  48. fastmcp/server/middleware/rate_limiting.py +3 -3
  49. fastmcp/server/middleware/tool_injection.py +116 -0
  50. fastmcp/server/proxy.py +6 -6
  51. fastmcp/server/server.py +683 -207
  52. fastmcp/settings.py +24 -10
  53. fastmcp/tools/tool.py +7 -3
  54. fastmcp/tools/tool_manager.py +30 -112
  55. fastmcp/tools/tool_transform.py +3 -3
  56. fastmcp/utilities/cli.py +62 -22
  57. fastmcp/utilities/components.py +5 -0
  58. fastmcp/utilities/inspect.py +77 -21
  59. fastmcp/utilities/logging.py +118 -8
  60. fastmcp/utilities/mcp_server_config/v1/environments/uv.py +6 -6
  61. fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py +3 -3
  62. fastmcp/utilities/mcp_server_config/v1/schema.json +3 -0
  63. fastmcp/utilities/tests.py +87 -4
  64. fastmcp/utilities/types.py +1 -1
  65. fastmcp/utilities/ui.py +617 -0
  66. {fastmcp-2.12.4.dist-info → fastmcp-2.13.0.dist-info}/METADATA +10 -6
  67. {fastmcp-2.12.4.dist-info → fastmcp-2.13.0.dist-info}/RECORD +70 -63
  68. fastmcp/cli/claude.py +0 -135
  69. fastmcp/utilities/storage.py +0 -204
  70. {fastmcp-2.12.4.dist-info → fastmcp-2.13.0.dist-info}/WHEEL +0 -0
  71. {fastmcp-2.12.4.dist-info → fastmcp-2.13.0.dist-info}/entry_points.txt +0 -0
  72. {fastmcp-2.12.4.dist-info → fastmcp-2.13.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,324 @@
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
+ from typing import TYPE_CHECKING
17
+
18
+ from mcp.server.auth.handlers.authorize import (
19
+ AuthorizationHandler as SDKAuthorizationHandler,
20
+ )
21
+ from pydantic import AnyHttpUrl
22
+ from starlette.requests import Request
23
+ from starlette.responses import Response
24
+
25
+ from fastmcp.utilities.logging import get_logger
26
+ from fastmcp.utilities.ui import (
27
+ INFO_BOX_STYLES,
28
+ TOOLTIP_STYLES,
29
+ create_logo,
30
+ create_page,
31
+ create_secure_html_response,
32
+ )
33
+
34
+ if TYPE_CHECKING:
35
+ from mcp.server.auth.provider import OAuthAuthorizationServerProvider
36
+
37
+ logger = get_logger(__name__)
38
+
39
+
40
+ def create_unregistered_client_html(
41
+ client_id: str,
42
+ registration_endpoint: str,
43
+ discovery_endpoint: str,
44
+ server_name: str | None = None,
45
+ server_icon_url: str | None = None,
46
+ title: str = "Client Not Registered",
47
+ ) -> str:
48
+ """Create styled HTML error page for unregistered client attempts.
49
+
50
+ Args:
51
+ client_id: The unregistered client ID that was provided
52
+ registration_endpoint: URL of the registration endpoint
53
+ discovery_endpoint: URL of the OAuth metadata discovery endpoint
54
+ server_name: Optional server name for branding
55
+ server_icon_url: Optional server icon URL
56
+ title: Page title
57
+
58
+ Returns:
59
+ HTML string for the error page
60
+ """
61
+ import html as html_module
62
+
63
+ client_id_escaped = html_module.escape(client_id)
64
+
65
+ # Main error message
66
+ error_box = f"""
67
+ <div class="info-box error">
68
+ <p>The client ID <code>{client_id_escaped}</code> was not found in the server's client registry.</p>
69
+ </div>
70
+ """
71
+
72
+ # What to do - yellow warning box
73
+ warning_box = """
74
+ <div class="info-box warning">
75
+ <p>Your MCP client opened this page to complete OAuth authorization,
76
+ but the server did not recognize its client ID. To fix this:</p>
77
+ <ul>
78
+ <li>Close this browser window</li>
79
+ <li>Clear authentication tokens in your MCP client (or restart it)</li>
80
+ <li>Try connecting again - your client should automatically re-register</li>
81
+ </ul>
82
+ </div>
83
+ """
84
+
85
+ # Help link with tooltip (similar to consent screen)
86
+ help_link = """
87
+ <div class="help-link-container">
88
+ <span class="help-link">
89
+ Why am I seeing this?
90
+ <span class="tooltip">
91
+ OAuth 2.0 requires clients to register before authorization.
92
+ This server returned a 400 error because the provided client
93
+ ID was not found.
94
+ <br><br>
95
+ In browser-delegated OAuth flows, your application cannot
96
+ detect this error automatically; it's waiting for a
97
+ callback that will never arrive. You must manually clear
98
+ auth tokens and reconnect.
99
+ </span>
100
+ </span>
101
+ </div>
102
+ """
103
+
104
+ # Build page content
105
+ content = f"""
106
+ <div class="container">
107
+ {create_logo(icon_url=server_icon_url, alt_text=server_name or "FastMCP")}
108
+ <h1>{title}</h1>
109
+ {error_box}
110
+ {warning_box}
111
+ </div>
112
+ {help_link}
113
+ """
114
+
115
+ # Use same styles as consent page
116
+ additional_styles = (
117
+ INFO_BOX_STYLES
118
+ + TOOLTIP_STYLES
119
+ + """
120
+ /* Error variant for info-box */
121
+ .info-box.error {
122
+ background: #fef2f2;
123
+ border-color: #f87171;
124
+ }
125
+ .info-box.error strong {
126
+ color: #991b1b;
127
+ }
128
+ /* Warning variant for info-box (yellow) */
129
+ .info-box.warning {
130
+ background: #fffbeb;
131
+ border-color: #fbbf24;
132
+ }
133
+ .info-box.warning strong {
134
+ color: #92400e;
135
+ }
136
+ .info-box code {
137
+ background: rgba(0, 0, 0, 0.05);
138
+ padding: 2px 6px;
139
+ border-radius: 3px;
140
+ font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace;
141
+ font-size: 0.9em;
142
+ }
143
+ .info-box ul {
144
+ margin: 10px 0;
145
+ padding-left: 20px;
146
+ }
147
+ .info-box li {
148
+ margin: 6px 0;
149
+ }
150
+ """
151
+ )
152
+
153
+ return create_page(
154
+ content=content,
155
+ title=title,
156
+ additional_styles=additional_styles,
157
+ )
158
+
159
+
160
+ class AuthorizationHandler(SDKAuthorizationHandler):
161
+ """Authorization handler with enhanced error responses for unregistered clients.
162
+
163
+ This handler extends the MCP SDK's AuthorizationHandler to provide better UX
164
+ when clients attempt to authorize without being registered. It implements
165
+ content negotiation to return:
166
+
167
+ - HTML error pages for browser requests
168
+ - Enhanced JSON with registration hints for API clients
169
+ - Link headers pointing to registration endpoints
170
+
171
+ This maintains OAuth 2.1 compliance (returns 400 for invalid client_id)
172
+ while providing actionable guidance to fix the error.
173
+ """
174
+
175
+ def __init__(
176
+ self,
177
+ provider: OAuthAuthorizationServerProvider,
178
+ base_url: AnyHttpUrl | str,
179
+ server_name: str | None = None,
180
+ server_icon_url: str | None = None,
181
+ ):
182
+ """Initialize the enhanced authorization handler.
183
+
184
+ Args:
185
+ provider: OAuth authorization server provider
186
+ base_url: Base URL of the server for constructing endpoint URLs
187
+ server_name: Optional server name for branding
188
+ server_icon_url: Optional server icon URL for branding
189
+ """
190
+ super().__init__(provider)
191
+ self._base_url = str(base_url).rstrip("/")
192
+ self._server_name = server_name
193
+ self._server_icon_url = server_icon_url
194
+
195
+ async def handle(self, request: Request) -> Response:
196
+ """Handle authorization request with enhanced error responses.
197
+
198
+ This method extends the SDK's authorization handler and intercepts
199
+ errors for unregistered clients to provide better error responses
200
+ based on the client's Accept header.
201
+
202
+ Args:
203
+ request: The authorization request
204
+
205
+ Returns:
206
+ Response (redirect on success, error response on failure)
207
+ """
208
+ # Call the SDK handler
209
+ response = await super().handle(request)
210
+
211
+ # Check if this is a client not found error
212
+ if response.status_code == 400:
213
+ # Try to extract client_id from request for enhanced error
214
+ client_id = None
215
+ if request.method == "GET":
216
+ client_id = request.query_params.get("client_id")
217
+ else:
218
+ form = await request.form()
219
+ client_id = form.get("client_id")
220
+
221
+ # If we have a client_id and the error is about it not being found,
222
+ # enhance the response
223
+ if client_id:
224
+ try:
225
+ # Check if response body contains "not found" error
226
+ if hasattr(response, "body"):
227
+ import json
228
+
229
+ body = json.loads(response.body)
230
+ if (
231
+ body.get("error") == "invalid_request"
232
+ and "not found" in body.get("error_description", "").lower()
233
+ ):
234
+ return await self._create_enhanced_error_response(
235
+ request, client_id, body.get("state")
236
+ )
237
+ except Exception:
238
+ # If we can't parse the response, just return the original
239
+ pass
240
+
241
+ return response
242
+
243
+ async def _create_enhanced_error_response(
244
+ self, request: Request, client_id: str, state: str | None
245
+ ) -> Response:
246
+ """Create enhanced error response with content negotiation.
247
+
248
+ Args:
249
+ request: The original request
250
+ client_id: The unregistered client ID
251
+ state: The state parameter from the request
252
+
253
+ Returns:
254
+ HTML or JSON error response based on Accept header
255
+ """
256
+ registration_endpoint = f"{self._base_url}/register"
257
+ discovery_endpoint = f"{self._base_url}/.well-known/oauth-authorization-server"
258
+
259
+ # Extract server metadata from app state (same pattern as consent screen)
260
+ from fastmcp.server.server import FastMCP
261
+
262
+ fastmcp = getattr(request.app.state, "fastmcp_server", None)
263
+
264
+ if isinstance(fastmcp, FastMCP):
265
+ server_name = fastmcp.name
266
+ icons = fastmcp.icons
267
+ server_icon_url = icons[0].src if icons else None
268
+ else:
269
+ server_name = self._server_name
270
+ server_icon_url = self._server_icon_url
271
+
272
+ # Check Accept header for content negotiation
273
+ accept = request.headers.get("accept", "")
274
+
275
+ # Prefer HTML for browsers
276
+ if "text/html" in accept:
277
+ html = create_unregistered_client_html(
278
+ client_id=client_id,
279
+ registration_endpoint=registration_endpoint,
280
+ discovery_endpoint=discovery_endpoint,
281
+ server_name=server_name,
282
+ server_icon_url=server_icon_url,
283
+ )
284
+ response = create_secure_html_response(html, status_code=400)
285
+ else:
286
+ # Return enhanced JSON for API clients
287
+ from mcp.server.auth.handlers.authorize import AuthorizationErrorResponse
288
+
289
+ error_data = AuthorizationErrorResponse(
290
+ error="invalid_request",
291
+ error_description=(
292
+ f"Client ID '{client_id}' is not registered with this server. "
293
+ f"MCP clients should automatically re-register by sending a POST request to "
294
+ f"the registration_endpoint and retry authorization. "
295
+ f"If this persists, clear cached authentication tokens and reconnect."
296
+ ),
297
+ state=state,
298
+ )
299
+
300
+ # Add extra fields to help clients discover registration
301
+ error_dict = error_data.model_dump(exclude_none=True)
302
+ error_dict["registration_endpoint"] = registration_endpoint
303
+ error_dict["authorization_server_metadata"] = discovery_endpoint
304
+
305
+ from starlette.responses import JSONResponse
306
+
307
+ response = JSONResponse(
308
+ status_code=400,
309
+ content=error_dict,
310
+ headers={"Cache-Control": "no-store"},
311
+ )
312
+
313
+ # Add Link header for registration endpoint discovery
314
+ response.headers["Link"] = (
315
+ f'<{registration_endpoint}>; rel="http://oauth.net/core/2.1/#registration"'
316
+ )
317
+
318
+ logger.info(
319
+ "Unregistered client_id=%s, returned %s error response",
320
+ client_id,
321
+ "HTML" if "text/html" in accept else "JSON",
322
+ )
323
+
324
+ return response
@@ -0,0 +1,236 @@
1
+ """JWT token issuance and verification for FastMCP OAuth Proxy.
2
+
3
+ This module implements the token factory pattern for OAuth proxies, where the proxy
4
+ issues its own JWT tokens to clients instead of forwarding upstream provider tokens.
5
+ This maintains proper OAuth 2.0 token audience boundaries.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import base64
11
+ import time
12
+ from typing import Any, overload
13
+
14
+ from authlib.jose import JsonWebToken
15
+ from authlib.jose.errors import JoseError
16
+ from cryptography.hazmat.primitives import hashes
17
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
18
+ from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
19
+
20
+ from fastmcp.utilities.logging import get_logger
21
+
22
+ logger = get_logger(__name__)
23
+
24
+ KDF_ITERATIONS = 1000000
25
+
26
+
27
+ @overload
28
+ def derive_jwt_key(*, high_entropy_material: str, salt: str) -> bytes:
29
+ """Derive JWT signing key from a high-entropy key material and server salt."""
30
+
31
+
32
+ @overload
33
+ def derive_jwt_key(*, low_entropy_material: str, salt: str) -> bytes:
34
+ """Derive JWT signing key from a low-entropy key material and server salt."""
35
+
36
+
37
+ def derive_jwt_key(
38
+ *,
39
+ high_entropy_material: str | None = None,
40
+ low_entropy_material: str | None = None,
41
+ salt: str,
42
+ ) -> bytes:
43
+ """Derive JWT signing key from a high-entropy or low-entropy key material and server salt."""
44
+ if high_entropy_material is not None and low_entropy_material is not None:
45
+ raise ValueError(
46
+ "Either high_entropy_material or low_entropy_material must be provided, but not both"
47
+ )
48
+
49
+ if high_entropy_material is not None:
50
+ derived_key = HKDF(
51
+ algorithm=hashes.SHA256(),
52
+ length=32,
53
+ salt=salt.encode(),
54
+ info=b"Fernet",
55
+ ).derive(key_material=high_entropy_material.encode())
56
+
57
+ return base64.urlsafe_b64encode(derived_key)
58
+
59
+ if low_entropy_material is not None:
60
+ pbkdf2 = PBKDF2HMAC(
61
+ algorithm=hashes.SHA256(),
62
+ length=32,
63
+ salt=salt.encode(),
64
+ iterations=KDF_ITERATIONS,
65
+ ).derive(key_material=low_entropy_material.encode())
66
+
67
+ return base64.urlsafe_b64encode(pbkdf2)
68
+
69
+ raise ValueError(
70
+ "Either high_entropy_material or low_entropy_material must be provided"
71
+ )
72
+
73
+
74
+ class JWTIssuer:
75
+ """Issues and validates FastMCP-signed JWT tokens using HS256.
76
+
77
+ This issuer creates JWT tokens for MCP clients with proper audience claims,
78
+ maintaining OAuth 2.0 token boundaries. Tokens are signed with HS256 using
79
+ a key derived from the upstream client secret.
80
+ """
81
+
82
+ def __init__(
83
+ self,
84
+ issuer: str,
85
+ audience: str,
86
+ signing_key: bytes,
87
+ ):
88
+ """Initialize JWT issuer.
89
+
90
+ Args:
91
+ issuer: Token issuer (FastMCP server base URL)
92
+ audience: Token audience (typically {base_url}/mcp)
93
+ signing_key: HS256 signing key (32 bytes)
94
+ """
95
+ self.issuer = issuer
96
+ self.audience = audience
97
+ self._signing_key = signing_key
98
+ self._jwt = JsonWebToken(["HS256"])
99
+
100
+ def issue_access_token(
101
+ self,
102
+ client_id: str,
103
+ scopes: list[str],
104
+ jti: str,
105
+ expires_in: int = 3600,
106
+ ) -> str:
107
+ """Issue a minimal FastMCP access token.
108
+
109
+ FastMCP tokens are reference tokens containing only the minimal claims
110
+ needed for validation and lookup. The JTI maps to the upstream token
111
+ which contains actual user identity and authorization data.
112
+
113
+ Args:
114
+ client_id: MCP client ID
115
+ scopes: Token scopes
116
+ jti: Unique token identifier (maps to upstream token)
117
+ expires_in: Token lifetime in seconds
118
+
119
+ Returns:
120
+ Signed JWT token
121
+ """
122
+ now = int(time.time())
123
+
124
+ header = {"alg": "HS256", "typ": "JWT"}
125
+ payload = {
126
+ "iss": self.issuer,
127
+ "aud": self.audience,
128
+ "client_id": client_id,
129
+ "scope": " ".join(scopes),
130
+ "exp": now + expires_in,
131
+ "iat": now,
132
+ "jti": jti,
133
+ }
134
+
135
+ token_bytes = self._jwt.encode(header, payload, self._signing_key)
136
+ token = token_bytes.decode("utf-8")
137
+
138
+ logger.debug(
139
+ "Issued access token for client=%s jti=%s exp=%d",
140
+ client_id,
141
+ jti[:8],
142
+ payload["exp"],
143
+ )
144
+
145
+ return token
146
+
147
+ def issue_refresh_token(
148
+ self,
149
+ client_id: str,
150
+ scopes: list[str],
151
+ jti: str,
152
+ expires_in: int,
153
+ ) -> str:
154
+ """Issue a minimal FastMCP refresh token.
155
+
156
+ FastMCP refresh tokens are reference tokens containing only the minimal
157
+ claims needed for validation and lookup. The JTI maps to the upstream
158
+ token which contains actual user identity and authorization data.
159
+
160
+ Args:
161
+ client_id: MCP client ID
162
+ scopes: Token scopes
163
+ jti: Unique token identifier (maps to upstream token)
164
+ expires_in: Token lifetime in seconds (should match upstream refresh expiry)
165
+
166
+ Returns:
167
+ Signed JWT token
168
+ """
169
+ now = int(time.time())
170
+
171
+ header = {"alg": "HS256", "typ": "JWT"}
172
+ payload = {
173
+ "iss": self.issuer,
174
+ "aud": self.audience,
175
+ "client_id": client_id,
176
+ "scope": " ".join(scopes),
177
+ "exp": now + expires_in,
178
+ "iat": now,
179
+ "jti": jti,
180
+ "token_use": "refresh",
181
+ }
182
+
183
+ token_bytes = self._jwt.encode(header, payload, self._signing_key)
184
+ token = token_bytes.decode("utf-8")
185
+
186
+ logger.debug(
187
+ "Issued refresh token for client=%s jti=%s exp=%d",
188
+ client_id,
189
+ jti[:8],
190
+ payload["exp"],
191
+ )
192
+
193
+ return token
194
+
195
+ def verify_token(self, token: str) -> dict[str, Any]:
196
+ """Verify and decode a FastMCP token.
197
+
198
+ Validates JWT signature, expiration, issuer, and audience.
199
+
200
+ Args:
201
+ token: JWT token to verify
202
+
203
+ Returns:
204
+ Decoded token payload
205
+
206
+ Raises:
207
+ JoseError: If token is invalid, expired, or has wrong claims
208
+ """
209
+ try:
210
+ # Decode and verify signature
211
+ payload = self._jwt.decode(token, self._signing_key)
212
+
213
+ # Validate expiration
214
+ exp = payload.get("exp")
215
+ if exp and exp < time.time():
216
+ logger.debug("Token expired")
217
+ raise JoseError("Token has expired")
218
+
219
+ # Validate issuer
220
+ if payload.get("iss") != self.issuer:
221
+ logger.debug("Token has invalid issuer")
222
+ raise JoseError("Invalid token issuer")
223
+
224
+ # Validate audience
225
+ if payload.get("aud") != self.audience:
226
+ logger.debug("Token has invalid audience")
227
+ raise JoseError("Invalid token audience")
228
+
229
+ logger.debug(
230
+ "Token verified successfully for subject=%s", payload.get("sub")
231
+ )
232
+ return payload
233
+
234
+ except JoseError as e:
235
+ logger.debug("Token validation failed: %s", e)
236
+ raise
@@ -0,0 +1,96 @@
1
+ """Enhanced authentication middleware with better error messages.
2
+
3
+ This module provides enhanced versions of MCP SDK authentication middleware
4
+ that return more helpful error messages for developers troubleshooting
5
+ authentication issues.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+
12
+ from mcp.server.auth.middleware.bearer_auth import (
13
+ RequireAuthMiddleware as SDKRequireAuthMiddleware,
14
+ )
15
+ from starlette.types import Send
16
+
17
+ from fastmcp.utilities.logging import get_logger
18
+
19
+ logger = get_logger(__name__)
20
+
21
+
22
+ class RequireAuthMiddleware(SDKRequireAuthMiddleware):
23
+ """Enhanced authentication middleware with detailed error messages.
24
+
25
+ Extends the SDK's RequireAuthMiddleware to provide more actionable
26
+ error messages when authentication fails. This helps developers
27
+ understand what went wrong and how to fix it.
28
+ """
29
+
30
+ async def _send_auth_error(
31
+ self, send: Send, status_code: int, error: str, description: str
32
+ ) -> None:
33
+ """Send an authentication error response with enhanced error messages.
34
+
35
+ Overrides the SDK's _send_auth_error to provide more detailed
36
+ error descriptions that help developers troubleshoot authentication
37
+ issues.
38
+
39
+ Args:
40
+ send: ASGI send callable
41
+ status_code: HTTP status code (401 or 403)
42
+ error: OAuth error code
43
+ description: Base error description
44
+ """
45
+ # Enhance error descriptions based on error type
46
+ enhanced_description = description
47
+
48
+ if error == "invalid_token" and status_code == 401:
49
+ # This is the "Authentication required" error
50
+ enhanced_description = (
51
+ "Authentication failed. The provided bearer token is invalid, expired, or no longer recognized by the server. "
52
+ "To resolve: clear authentication tokens in your MCP client and reconnect. "
53
+ "Your client should automatically re-register and obtain new tokens."
54
+ )
55
+ elif error == "insufficient_scope":
56
+ # Scope error - already has good detail from SDK
57
+ pass
58
+
59
+ # Build WWW-Authenticate header value
60
+ www_auth_parts = [
61
+ f'error="{error}"',
62
+ f'error_description="{enhanced_description}"',
63
+ ]
64
+ if self.resource_metadata_url:
65
+ www_auth_parts.append(f'resource_metadata="{self.resource_metadata_url}"')
66
+
67
+ www_authenticate = f"Bearer {', '.join(www_auth_parts)}"
68
+
69
+ # Send response
70
+ body = {"error": error, "error_description": enhanced_description}
71
+ body_bytes = json.dumps(body).encode()
72
+
73
+ await send(
74
+ {
75
+ "type": "http.response.start",
76
+ "status": status_code,
77
+ "headers": [
78
+ (b"content-type", b"application/json"),
79
+ (b"content-length", str(len(body_bytes)).encode()),
80
+ (b"www-authenticate", www_authenticate.encode()),
81
+ ],
82
+ }
83
+ )
84
+
85
+ await send(
86
+ {
87
+ "type": "http.response.body",
88
+ "body": body_bytes,
89
+ }
90
+ )
91
+
92
+ logger.info(
93
+ "Auth error returned: %s (status=%d)",
94
+ error,
95
+ status_code,
96
+ )