fastmcp 2.5.1__py3-none-any.whl → 2.6.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.
fastmcp/cli/cli.py CHANGED
@@ -50,9 +50,7 @@ def _get_npx_command():
50
50
  def _parse_env_var(env_var: str) -> tuple[str, str]:
51
51
  """Parse environment variable string in format KEY=VALUE."""
52
52
  if "=" not in env_var:
53
- logger.error(
54
- f"Invalid environment variable format: {env_var}. Must be KEY=VALUE"
55
- )
53
+ logger.error("Invalid environment variable format. Must be KEY=VALUE")
56
54
  sys.exit(1)
57
55
  key, value = env_var.split("=", 1)
58
56
  return key.strip(), value.strip()
@@ -11,6 +11,7 @@ from .transports import (
11
11
  FastMCPTransport,
12
12
  StreamableHttpTransport,
13
13
  )
14
+ from .auth import OAuth, BearerAuth
14
15
 
15
16
  __all__ = [
16
17
  "Client",
@@ -24,4 +25,6 @@ __all__ = [
24
25
  "NpxStdioTransport",
25
26
  "FastMCPTransport",
26
27
  "StreamableHttpTransport",
28
+ "OAuth",
29
+ "BearerAuth",
27
30
  ]
@@ -0,0 +1,4 @@
1
+ from .bearer import BearerAuth
2
+ from .oauth import OAuth
3
+
4
+ __all__ = ["BearerAuth", "OAuth"]
@@ -0,0 +1,17 @@
1
+ import httpx
2
+ from pydantic import SecretStr
3
+
4
+ from fastmcp.utilities.logging import get_logger
5
+
6
+ __all__ = ["BearerAuth"]
7
+
8
+ logger = get_logger(__name__)
9
+
10
+
11
+ class BearerAuth(httpx.Auth):
12
+ def __init__(self, token: str):
13
+ self.token = SecretStr(token)
14
+
15
+ def auth_flow(self, request):
16
+ request.headers["Authorization"] = f"Bearer {self.token.get_secret_value()}"
17
+ yield request
@@ -0,0 +1,394 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import json
5
+ import webbrowser
6
+ from pathlib import Path
7
+ from typing import Any, Literal
8
+ from urllib.parse import urljoin, urlparse
9
+
10
+ import anyio
11
+ import httpx
12
+ from mcp.client.auth import OAuthClientProvider as _MCPOAuthClientProvider
13
+ from mcp.client.auth import TokenStorage
14
+ from mcp.shared.auth import (
15
+ OAuthClientInformationFull,
16
+ OAuthClientMetadata,
17
+ )
18
+ from mcp.shared.auth import (
19
+ OAuthMetadata as _MCPServerOAuthMetadata,
20
+ )
21
+ from mcp.shared.auth import (
22
+ OAuthToken as OAuthToken,
23
+ )
24
+ from pydantic import AnyHttpUrl, ValidationError
25
+
26
+ from fastmcp.client.oauth_callback import (
27
+ create_oauth_callback_server,
28
+ )
29
+ from fastmcp.settings import settings as fastmcp_global_settings
30
+ from fastmcp.utilities.http import find_available_port
31
+ from fastmcp.utilities.logging import get_logger
32
+
33
+ __all__ = ["OAuth"]
34
+
35
+ logger = get_logger(__name__)
36
+
37
+
38
+ def default_cache_dir() -> Path:
39
+ return fastmcp_global_settings.home / "oauth-mcp-client-cache"
40
+
41
+
42
+ # Flexible OAuth models for real-world compatibility
43
+ class ServerOAuthMetadata(_MCPServerOAuthMetadata):
44
+ """
45
+ More flexible OAuth metadata model that accepts broader ranges of values
46
+ than the restrictive MCP standard model.
47
+
48
+ This handles real-world OAuth servers like PayPal that may support
49
+ additional methods not in the MCP specification.
50
+ """
51
+
52
+ # Allow any code challenge methods, not just S256
53
+ code_challenge_methods_supported: list[str] | None = None
54
+
55
+ # Allow any token endpoint auth methods
56
+ token_endpoint_auth_methods_supported: list[str] | None = None
57
+
58
+ # Allow any grant types
59
+ grant_types_supported: list[str] | None = None
60
+
61
+ # Allow any response types
62
+ response_types_supported: list[str] = ["code"]
63
+
64
+ # Allow any response modes
65
+ response_modes_supported: list[str] | None = None
66
+
67
+
68
+ class OAuthClientProvider(_MCPOAuthClientProvider):
69
+ """
70
+ OAuth client provider with more flexible OAuth metadata discovery.
71
+
72
+ This subclass handles real-world OAuth servers that may not conform
73
+ strictly to the MCP OAuth specification but are still valid OAuth 2.0 servers.
74
+ """
75
+
76
+ async def _discover_oauth_metadata(
77
+ self, server_url: str
78
+ ) -> ServerOAuthMetadata | None:
79
+ """
80
+ Discover OAuth metadata with flexible validation.
81
+
82
+ This is nearly identical to the parent implementation but uses
83
+ ServerOAuthMetadata instead of the restrictive MCP OAuthMetadata.
84
+ """
85
+ # Extract base URL per MCP spec
86
+ auth_base_url = self._get_authorization_base_url(server_url)
87
+ url = urljoin(auth_base_url, "/.well-known/oauth-authorization-server")
88
+
89
+ from mcp.types import LATEST_PROTOCOL_VERSION
90
+
91
+ headers = {"MCP-Protocol-Version": LATEST_PROTOCOL_VERSION}
92
+
93
+ async with httpx.AsyncClient() as client:
94
+ try:
95
+ response = await client.get(url, headers=headers)
96
+ if response.status_code == 404:
97
+ return None
98
+ response.raise_for_status()
99
+ metadata_json = response.json()
100
+ logger.debug(f"OAuth metadata discovered: {metadata_json}")
101
+ return ServerOAuthMetadata.model_validate(metadata_json)
102
+ except Exception:
103
+ # Retry without MCP header for CORS compatibility
104
+ try:
105
+ response = await client.get(url)
106
+ if response.status_code == 404:
107
+ return None
108
+ response.raise_for_status()
109
+ metadata_json = response.json()
110
+ logger.debug(
111
+ f"OAuth metadata discovered (no MCP header): {metadata_json}"
112
+ )
113
+ return ServerOAuthMetadata.model_validate(metadata_json)
114
+ except Exception:
115
+ logger.exception("Failed to discover OAuth metadata")
116
+ return None
117
+
118
+
119
+ class FileTokenStorage(TokenStorage):
120
+ """
121
+ File-based token storage implementation for OAuth credentials and tokens.
122
+ Implements the mcp.client.auth.TokenStorage protocol.
123
+
124
+ Each instance is tied to a specific server URL for proper token isolation.
125
+ """
126
+
127
+ def __init__(self, server_url: str, cache_dir: Path | None = None):
128
+ """Initialize storage for a specific server URL."""
129
+ self.server_url = server_url
130
+ self.cache_dir = cache_dir or default_cache_dir()
131
+ self.cache_dir.mkdir(exist_ok=True, parents=True)
132
+
133
+ @staticmethod
134
+ def get_base_url(url: str) -> str:
135
+ """Extract the base URL (scheme + host) from a URL."""
136
+ parsed = urlparse(url)
137
+ return f"{parsed.scheme}://{parsed.netloc}"
138
+
139
+ def get_cache_key(self) -> str:
140
+ """Generate a safe filesystem key from the server's base URL."""
141
+ base_url = self.get_base_url(self.server_url)
142
+ return (
143
+ base_url.replace("://", "_")
144
+ .replace(".", "_")
145
+ .replace("/", "_")
146
+ .replace(":", "_")
147
+ )
148
+
149
+ def _get_file_path(self, file_type: Literal["client_info", "tokens"]) -> Path:
150
+ """Get the file path for the specified cache file type."""
151
+ key = self.get_cache_key()
152
+ return self.cache_dir / f"{key}_{file_type}.json"
153
+
154
+ async def get_tokens(self) -> OAuthToken | None:
155
+ """Load tokens from file storage."""
156
+ path = self._get_file_path("tokens")
157
+
158
+ try:
159
+ tokens = OAuthToken.model_validate_json(path.read_text())
160
+ # now = datetime.datetime.now(datetime.timezone.utc)
161
+ # if tokens.expires_at is not None and tokens.expires_at <= now:
162
+ # logger.debug(f"Token expired for {self.get_base_url(self.server_url)}")
163
+ # return None
164
+ return tokens
165
+ except (FileNotFoundError, json.JSONDecodeError, ValidationError) as e:
166
+ logger.debug(
167
+ f"Could not load tokens for {self.get_base_url(self.server_url)}: {e}"
168
+ )
169
+ return None
170
+
171
+ async def set_tokens(self, tokens: OAuthToken) -> None:
172
+ """Save tokens to file storage."""
173
+ path = self._get_file_path("tokens")
174
+ path.write_text(tokens.model_dump_json(indent=2))
175
+ logger.debug(f"Saved tokens for {self.get_base_url(self.server_url)}")
176
+
177
+ async def get_client_info(self) -> OAuthClientInformationFull | None:
178
+ """Load client information from file storage."""
179
+ path = self._get_file_path("client_info")
180
+ try:
181
+ client_info = OAuthClientInformationFull.model_validate_json(
182
+ path.read_text()
183
+ )
184
+ # Check if we have corresponding valid tokens
185
+ # If no tokens exist, the OAuth flow was incomplete and we should
186
+ # force a fresh client registration
187
+ tokens = await self.get_tokens()
188
+ if tokens is None:
189
+ logger.debug(
190
+ f"No tokens found for client info at {self.get_base_url(self.server_url)}. "
191
+ "OAuth flow may have been incomplete. Clearing client info to force fresh registration."
192
+ )
193
+ # Clear the incomplete client info
194
+ client_info_path = self._get_file_path("client_info")
195
+ client_info_path.unlink(missing_ok=True)
196
+ return None
197
+
198
+ return client_info
199
+ except (FileNotFoundError, json.JSONDecodeError, ValidationError) as e:
200
+ logger.debug(
201
+ f"Could not load client info for {self.get_base_url(self.server_url)}: {e}"
202
+ )
203
+ return None
204
+
205
+ async def set_client_info(self, client_info: OAuthClientInformationFull) -> None:
206
+ """Save client information to file storage."""
207
+ path = self._get_file_path("client_info")
208
+ path.write_text(client_info.model_dump_json(indent=2))
209
+ logger.debug(f"Saved client info for {self.get_base_url(self.server_url)}")
210
+
211
+ def clear(self) -> None:
212
+ """Clear all cached data for this server."""
213
+ file_types: list[Literal["client_info", "tokens"]] = ["client_info", "tokens"]
214
+ for file_type in file_types:
215
+ path = self._get_file_path(file_type)
216
+ path.unlink(missing_ok=True)
217
+ logger.info(f"Cleared OAuth cache for {self.get_base_url(self.server_url)}")
218
+
219
+ @classmethod
220
+ def clear_all(cls, cache_dir: Path | None = None) -> None:
221
+ """Clear all cached data for all servers."""
222
+ cache_dir = cache_dir or default_cache_dir()
223
+ if not cache_dir.exists():
224
+ return
225
+
226
+ file_types: list[Literal["client_info", "tokens"]] = ["client_info", "tokens"]
227
+ for file_type in file_types:
228
+ for file in cache_dir.glob(f"*_{file_type}.json"):
229
+ file.unlink(missing_ok=True)
230
+ logger.info("Cleared all OAuth client cache data.")
231
+
232
+
233
+ async def discover_oauth_metadata(
234
+ server_base_url: str, httpx_kwargs: dict[str, Any] | None = None
235
+ ) -> _MCPServerOAuthMetadata | None:
236
+ """
237
+ Discover OAuth metadata from the server using RFC 8414 well-known endpoint.
238
+
239
+ Args:
240
+ server_base_url: Base URL of the OAuth server (e.g., "https://example.com")
241
+ httpx_kwargs: Additional kwargs for httpx client
242
+
243
+ Returns:
244
+ OAuth metadata if found, None otherwise
245
+ """
246
+ well_known_url = urljoin(server_base_url, "/.well-known/oauth-authorization-server")
247
+ logger.debug(f"Discovering OAuth metadata from: {well_known_url}")
248
+
249
+ async with httpx.AsyncClient(**(httpx_kwargs or {})) as client:
250
+ try:
251
+ response = await client.get(well_known_url, timeout=10.0)
252
+ if response.status_code == 200:
253
+ logger.debug("Successfully discovered OAuth metadata")
254
+ return _MCPServerOAuthMetadata.model_validate(response.json())
255
+ elif response.status_code == 404:
256
+ logger.debug(
257
+ "OAuth metadata not found (404) - server may not require auth"
258
+ )
259
+ return None
260
+ else:
261
+ logger.warning(f"OAuth metadata request failed: {response.status_code}")
262
+ return None
263
+ except (httpx.RequestError, json.JSONDecodeError, ValidationError) as e:
264
+ logger.debug(f"OAuth metadata discovery failed: {e}")
265
+ return None
266
+
267
+
268
+ async def check_if_auth_required(
269
+ mcp_url: str, httpx_kwargs: dict[str, Any] | None = None
270
+ ) -> bool:
271
+ """
272
+ Check if the MCP endpoint requires authentication by making a test request.
273
+
274
+ Returns:
275
+ True if auth appears to be required, False otherwise
276
+ """
277
+ async with httpx.AsyncClient(**(httpx_kwargs or {})) as client:
278
+ try:
279
+ # Try a simple request to the endpoint
280
+ response = await client.get(mcp_url, timeout=5.0)
281
+
282
+ # If we get 401/403, auth is likely required
283
+ if response.status_code in (401, 403):
284
+ return True
285
+
286
+ # Check for WWW-Authenticate header
287
+ if "WWW-Authenticate" in response.headers:
288
+ return True
289
+
290
+ # If we get a successful response, auth may not be required
291
+ return False
292
+
293
+ except httpx.RequestError:
294
+ # If we can't connect, assume auth might be required
295
+ return True
296
+
297
+
298
+ def OAuth(
299
+ mcp_url: str,
300
+ scopes: str | list[str] | None = None,
301
+ client_name: str = "FastMCP Client",
302
+ token_storage_cache_dir: Path | None = None,
303
+ additional_client_metadata: dict[str, Any] | None = None,
304
+ ) -> _MCPOAuthClientProvider:
305
+ """
306
+ Create an OAuthClientProvider for an MCP server.
307
+
308
+ This is intended to be provided to the `auth` parameter of an
309
+ httpx.AsyncClient (or appropriate FastMCP client/transport instance)
310
+
311
+ Args:
312
+ mcp_url: Full URL to the MCP endpoint (e.g.,
313
+ "http://host/mcp/sse")
314
+ scopes: OAuth scopes to request. Can be a
315
+ space-separated string or a list of strings.
316
+ client_name: Name for this client during registration
317
+ token_storage_cache_dir: Directory for FileTokenStorage
318
+ additional_client_metadata: Extra fields for OAuthClientMetadata
319
+
320
+ Returns:
321
+ OAuthClientProvider
322
+ """
323
+ parsed_url = urlparse(mcp_url)
324
+ server_base_url = f"{parsed_url.scheme}://{parsed_url.netloc}"
325
+
326
+ # Setup OAuth client
327
+ redirect_port = find_available_port()
328
+ redirect_uri = f"http://127.0.0.1:{redirect_port}/callback"
329
+
330
+ if isinstance(scopes, list):
331
+ scopes = " ".join(scopes)
332
+
333
+ client_metadata = OAuthClientMetadata(
334
+ client_name=client_name,
335
+ redirect_uris=[AnyHttpUrl(redirect_uri)],
336
+ grant_types=["authorization_code", "refresh_token"],
337
+ response_types=["code"],
338
+ token_endpoint_auth_method="client_secret_post",
339
+ scope=scopes,
340
+ **(additional_client_metadata or {}),
341
+ )
342
+
343
+ # Create server-specific token storage
344
+ storage = FileTokenStorage(
345
+ server_url=server_base_url, cache_dir=token_storage_cache_dir
346
+ )
347
+
348
+ # Define OAuth handlers
349
+ async def redirect_handler(authorization_url: str) -> None:
350
+ """Open browser for authorization."""
351
+ logger.info(f"OAuth authorization URL: {authorization_url}")
352
+ webbrowser.open(authorization_url)
353
+
354
+ async def callback_handler() -> tuple[str, str | None]:
355
+ """Handle OAuth callback and return (auth_code, state)."""
356
+ # Create a future to capture the OAuth response
357
+ response_future = asyncio.get_running_loop().create_future()
358
+
359
+ # Create server with the future
360
+ server = create_oauth_callback_server(
361
+ port=redirect_port,
362
+ server_url=server_base_url,
363
+ response_future=response_future,
364
+ )
365
+
366
+ # Run server until response is received with timeout logic
367
+ async with anyio.create_task_group() as tg:
368
+ tg.start_soon(server.serve)
369
+ logger.info(
370
+ f"🎧 OAuth callback server started on http://127.0.0.1:{redirect_port}"
371
+ )
372
+
373
+ TIMEOUT = 300.0 # 5 minute timeout
374
+ try:
375
+ with anyio.fail_after(TIMEOUT):
376
+ auth_code, state = await response_future
377
+ return auth_code, state
378
+ except TimeoutError:
379
+ raise TimeoutError(f"OAuth callback timed out after {TIMEOUT} seconds")
380
+ finally:
381
+ server.should_exit = True
382
+ await asyncio.sleep(0.1) # Allow server to shutdown gracefully
383
+ tg.cancel_scope.cancel()
384
+
385
+ # Create OAuth provider
386
+ oauth_provider = OAuthClientProvider(
387
+ server_url=server_base_url,
388
+ client_metadata=client_metadata,
389
+ storage=storage,
390
+ redirect_handler=redirect_handler,
391
+ callback_handler=callback_handler,
392
+ )
393
+
394
+ return oauth_provider