diff --git a/src/fastmcp/server/auth/auth.py b/src/fastmcp/server/auth/auth.py index fcb85c1af..f86d2004f 100644 --- a/src/fastmcp/server/auth/auth.py +++ b/src/fastmcp/server/auth/auth.py @@ -21,6 +21,7 @@ class OAuthProvider( client_registration_options: ClientRegistrationOptions | None = None, revocation_options: RevocationOptions | None = None, required_scopes: list[str] | None = None, + resource_server_url: AnyHttpUrl | str | None = None, ): """ Initialize the OAuth provider. @@ -43,6 +44,9 @@ class OAuthProvider( self.client_registration_options = client_registration_options self.revocation_options = revocation_options self.required_scopes = required_scopes + self.resource_server_url = ( + AnyHttpUrl(resource_server_url) if resource_server_url else None + ) async def verify_token(self, token: str) -> AccessToken | None: """ diff --git a/src/fastmcp/server/auth/providers/bearer.py b/src/fastmcp/server/auth/providers/bearer.py index 3da91c94d..2d37198ac 100644 --- a/src/fastmcp/server/auth/providers/bearer.py +++ b/src/fastmcp/server/auth/providers/bearer.py @@ -167,6 +167,7 @@ class BearerAuthProvider(OAuthProvider): algorithm: str | None = None, audience: str | list[str] | None = None, required_scopes: list[str] | None = None, + resource_server: str | None = None, ): """ Initialize the provider. Either public_key or jwks_uri must be provided. @@ -210,11 +211,19 @@ class BearerAuthProvider(OAuthProvider): # Issuer is not a valid URL, use default for parent class issuer_url = "https://fastmcp.example.com" + try: + resource_server_url = ( + AnyHttpUrl(resource_server) if resource_server else None + ) + except ValidationError: + resource_server_url = None + super().__init__( issuer_url=issuer_url, client_registration_options=ClientRegistrationOptions(enabled=False), revocation_options=RevocationOptions(enabled=False), required_scopes=required_scopes, + resource_server_url=resource_server_url, ) self.algorithm = algorithm diff --git a/src/fastmcp/server/auth/providers/bearer_env.py b/src/fastmcp/server/auth/providers/bearer_env.py index dfbd96146..74c41c85c 100644 --- a/src/fastmcp/server/auth/providers/bearer_env.py +++ b/src/fastmcp/server/auth/providers/bearer_env.py @@ -37,6 +37,7 @@ class EnvBearerAuthProvider(BearerAuthProvider): algorithm: str | None | EllipsisType = ..., audience: str | None | EllipsisType = ..., required_scopes: list[str] | None | EllipsisType = ..., + resource_server: str | None | EllipsisType = ..., ): """ Initialize the provider. @@ -56,6 +57,7 @@ class EnvBearerAuthProvider(BearerAuthProvider): "algorithm": algorithm, "audience": audience, "required_scopes": required_scopes, + "resource_server": resource_server, } settings = EnvBearerAuthProviderSettings( **{k: v for k, v in kwargs.items() if v is not ...} diff --git a/src/fastmcp/server/auth/providers/in_memory.py b/src/fastmcp/server/auth/providers/in_memory.py index 92408b134..533813522 100644 --- a/src/fastmcp/server/auth/providers/in_memory.py +++ b/src/fastmcp/server/auth/providers/in_memory.py @@ -41,6 +41,7 @@ class InMemoryOAuthProvider(OAuthProvider): client_registration_options: ClientRegistrationOptions | None = None, revocation_options: RevocationOptions | None = None, required_scopes: list[str] | None = None, + resource_server_url: AnyHttpUrl | str | None = None, ): super().__init__( issuer_url=issuer_url or "http://fastmcp.example.com", @@ -48,6 +49,7 @@ class InMemoryOAuthProvider(OAuthProvider): client_registration_options=client_registration_options, revocation_options=revocation_options, required_scopes=required_scopes, + resource_server_url=resource_server_url, ) self.clients: dict[str, OAuthClientInformationFull] = {} self.auth_codes: dict[str, AuthorizationCode] = {} diff --git a/src/fastmcp/server/http.py b/src/fastmcp/server/http.py index 1b97702c4..d38e7ec15 100644 --- a/src/fastmcp/server/http.py +++ b/src/fastmcp/server/http.py @@ -15,6 +15,7 @@ from mcp.server.lowlevel.server import LifespanResultT from mcp.server.sse import SseServerTransport from mcp.server.streamable_http import EventStore from mcp.server.streamable_http_manager import StreamableHTTPSessionManager +from pydantic import AnyHttpUrl from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.middleware.authentication import AuthenticationMiddleware @@ -307,6 +308,14 @@ def create_streamable_http_app( # Add StreamableHTTP routes with or without auth if auth: + resource_metadata_url = None + + if auth.resource_server_url: + resource_metadata_url = AnyHttpUrl( + str(auth.resource_server_url).rstrip("/") + + "/.well-known/oauth-protected-resource" + ) + auth_middleware, auth_routes, required_scopes = ( setup_auth_middleware_and_routes(auth) ) @@ -318,7 +327,9 @@ def create_streamable_http_app( server_routes.append( Mount( streamable_http_path, - app=RequireAuthMiddleware(handle_streamable_http, required_scopes), + app=RequireAuthMiddleware( + handle_streamable_http, required_scopes, resource_metadata_url + ), ) ) else: diff --git a/tests/server/http/test_http_auth_middleware.py b/tests/server/http/test_http_auth_middleware.py new file mode 100644 index 000000000..54f6eb0f0 --- /dev/null +++ b/tests/server/http/test_http_auth_middleware.py @@ -0,0 +1,78 @@ +import pytest +from mcp.server.auth.middleware.bearer_auth import RequireAuthMiddleware +from starlette.routing import Mount + +from fastmcp.server import FastMCP +from fastmcp.server.auth.providers.bearer import BearerAuthProvider, RSAKeyPair +from fastmcp.server.http import create_streamable_http_app + + +class TestStreamableHTTPAppResourceMetadataURL: + """Test resource_metadata_url logic in create_streamable_http_app.""" + + @pytest.fixture + def rsa_key_pair(self) -> RSAKeyPair: + """Generate RSA key pair for testing.""" + return RSAKeyPair.generate() + + @pytest.fixture + def bearer_auth_provider(self, rsa_key_pair): + provider = BearerAuthProvider( + public_key=rsa_key_pair.public_key, + issuer="https://issuer", + audience="https://audience", + resource_server="https://resource.example.com", + ) + return provider + + def test_require_auth_middleware_receives_resource_metadata_url( + self, bearer_auth_provider + ): + server = FastMCP(name="TestServer") + + app = create_streamable_http_app( + server=server, + streamable_http_path="/mcp", + auth=bearer_auth_provider, + ) + + mount = next(r for r in app.routes if isinstance(r, Mount) and r.path == "/mcp") + + assert isinstance(mount.app, RequireAuthMiddleware) + assert ( + str(mount.app.resource_metadata_url) + == "https://resource.example.com/.well-known/oauth-protected-resource" + ) + + def test_trailing_slash_handling_in_resource_server_url(self, rsa_key_pair): + provider = BearerAuthProvider( + public_key=rsa_key_pair.public_key, + issuer="https://issuer", + audience="https://audience", + resource_server="https://resource.example.com/", + ) + server = FastMCP(name="TestServer") + app = create_streamable_http_app( + server=server, + streamable_http_path="/mcp", + auth=provider, + ) + mount = next(r for r in app.routes if isinstance(r, Mount) and r.path == "/mcp") + assert isinstance(mount.app, RequireAuthMiddleware) + # Should not have double slash + assert ( + str(mount.app.resource_metadata_url) + == "https://resource.example.com/.well-known/oauth-protected-resource" + ) + + def test_no_auth_provider_mounts_without_require_auth_middleware( + self, rsa_key_pair + ): + server = FastMCP(name="TestServer") + app = create_streamable_http_app( + server=server, + streamable_http_path="/mcp", + auth=None, + ) + mount = next(r for r in app.routes if isinstance(r, Mount) and r.path == "/mcp") + assert not isinstance(mount.app, RequireAuthMiddleware)