Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

fix: advertise resource_metadata only when a route serves it (#5363)

Aleksandr Filippov93b491442da7
diff --git a/fastmcp_slim/fastmcp/server/http.py b/fastmcp_slim/fastmcp/server/http.py
index c56d572a7..d78c48bd1 100644
--- a/fastmcp_slim/fastmcp/server/http.py
+++ b/fastmcp_slim/fastmcp/server/http.py
@@ -17,6 +17,7 @@ from mcp.server.streamable_http import (
)
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
from mcp.server.transport_security import TransportSecuritySettings
+from pydantic import AnyHttpUrl
from starlette.applications import Starlette
from starlette.datastructures import Headers
from starlette.middleware import Middleware
@@ -440,6 +441,28 @@ def create_base_app(
)
+def _served_resource_metadata_url(
+ auth: AuthProvider, auth_routes: Sequence[BaseRoute], mcp_path: str
+) -> AnyHttpUrl | None:
+ """Return the RFC 9728 metadata URL that auth challenges may advertise.
+
+ The URL is derived from the provider's resource URL and is advertised only
+ when the provider contributes a route at that URL's path. A provider that
+ verifies tokens without serving protected resource metadata, such as a bare
+ `TokenVerifier` or a `MultiAuth` without a server, yields None so that the
+ challenge does not point clients at a URL that answers 404.
+ """
+ resource_url = auth._get_resource_url(mcp_path)
+ if resource_url is None:
+ return None
+ metadata_url = build_resource_metadata_url(resource_url)
+ metadata_path = urlsplit(str(metadata_url)).path
+ for route in auth_routes:
+ if isinstance(route, Route) and route.path == metadata_path:
+ return metadata_url
+ return None
+
+
def create_sse_app(
server: FastMCP[LifespanResultT],
message_path: str,
@@ -512,10 +535,9 @@ def create_sse_app(
server_routes.extend(auth_routes)
server_middleware.extend(auth_middleware)
- # Build RFC 9728-compliant metadata URL
- resource_url = auth._get_resource_url(sse_path)
- resource_metadata_url = (
- build_resource_metadata_url(resource_url) if resource_url else None
+ # Advertise the RFC 9728 metadata URL only when the provider serves it
+ resource_metadata_url = _served_resource_metadata_url(
+ auth, auth_routes, sse_path
)
# Create protected SSE endpoint route
@@ -659,10 +681,9 @@ def create_streamable_http_app(
server_routes.extend(auth_routes)
server_middleware.extend(auth_middleware)
- # Build RFC 9728-compliant metadata URL
- resource_url = auth._get_resource_url(streamable_http_path)
- resource_metadata_url = (
- build_resource_metadata_url(resource_url) if resource_url else None
+ # Advertise the RFC 9728 metadata URL only when the provider serves it
+ resource_metadata_url = _served_resource_metadata_url(
+ auth, auth_routes, streamable_http_path
)
# Create protected HTTP endpoint route
diff --git a/tests/server/http/test_http_auth_middleware.py b/tests/server/http/test_http_auth_middleware.py
index 12c1c9f54..907af4178 100644
--- a/tests/server/http/test_http_auth_middleware.py
+++ b/tests/server/http/test_http_auth_middleware.py
@@ -1,16 +1,30 @@
from collections.abc import MutableMapping
from typing import Any, Literal
+import httpx2
import pytest
from mcp.server.auth.middleware.bearer_auth import RequireAuthMiddleware
+from pydantic import AnyHttpUrl
from starlette.responses import Response
from starlette.routing import Route
from starlette.testclient import TestClient
from starlette.types import Receive, Scope, Send
from fastmcp.server import FastMCP
+from fastmcp.server.auth import (
+ AuthProvider,
+ MultiAuth,
+ RemoteAuthProvider,
+ TokenVerifier,
+)
+from fastmcp.server.auth.auth import AccessToken
from fastmcp.server.auth.providers.jwt import JWTVerifier
-from fastmcp.server.http import HostOriginGuardMiddleware, create_streamable_http_app
+from fastmcp.server.http import (
+ HostOriginGuardMiddleware,
+ StarletteWithLifespan,
+ create_sse_app,
+ create_streamable_http_app,
+)
INITIALIZE_REQUEST = {
"jsonrpc": "2.0",
@@ -158,6 +172,101 @@ class TestStreamableHTTPAppResourceMetadataURL:
assert "www-authenticate" in response.headers
+class _VerifierOnly(TokenVerifier):
+ """A token verifier that serves no routes and accepts no token."""
+
+ async def verify_token(self, token: str) -> AccessToken | None:
+ return None
+
+
+_PROTECTED_PATH = {"http": "/mcp", "sse": "/sse"}
+
+
+def _auth_app(
+ transport: Literal["http", "sse"], auth: AuthProvider
+) -> StarletteWithLifespan:
+ server = FastMCP(name="TestServer")
+ if transport == "sse":
+ return create_sse_app(
+ server=server, message_path="/messages/", sse_path="/sse", auth=auth
+ )
+ return create_streamable_http_app(
+ server=server, streamable_http_path="/mcp", auth=auth
+ )
+
+
+class TestAuthChallengeResourceMetadata:
+ """The 401 challenge names protected resource metadata only when it is served."""
+
+ @pytest.mark.parametrize("transport", ["http", "sse"])
+ @pytest.mark.parametrize("url_parameter", ["base_url", "resource_base_url"])
+ @pytest.mark.parametrize("shape", ["verifier", "multi_auth"])
+ async def test_verifier_only_challenge_omits_unserved_resource_metadata(
+ self,
+ transport: Literal["http", "sse"],
+ url_parameter: str,
+ shape: str,
+ ):
+ url = "https://resource.example.com"
+ base_url = url if url_parameter == "base_url" else None
+ resource_base_url = url if url_parameter == "resource_base_url" else None
+ auth: AuthProvider
+ if shape == "verifier":
+ auth = _VerifierOnly(base_url=base_url, resource_base_url=resource_base_url)
+ else:
+ auth = MultiAuth(
+ verifiers=[_VerifierOnly()],
+ base_url=base_url,
+ resource_base_url=resource_base_url,
+ )
+ app = _auth_app(transport, auth)
+ path = _PROTECTED_PATH[transport]
+
+ async with httpx2.AsyncClient(
+ transport=httpx2.ASGITransport(app=app),
+ base_url="https://resource.example.com",
+ ) as client:
+ missing = await client.get(path)
+ invalid = await client.get(path, headers={"Authorization": "Bearer x"})
+ metadata = await client.get(f"/.well-known/oauth-protected-resource{path}")
+
+ assert missing.status_code == 401
+ assert missing.headers["www-authenticate"] == "Bearer"
+ assert invalid.status_code == 401
+ assert "resource_metadata=" not in invalid.headers["www-authenticate"]
+ assert metadata.status_code == 404
+
+ @pytest.mark.parametrize("transport", ["http", "sse"])
+ async def test_challenge_names_resource_metadata_the_provider_serves(
+ self, transport: Literal["http", "sse"]
+ ):
+ auth = RemoteAuthProvider(
+ token_verifier=_VerifierOnly(),
+ authorization_servers=[AnyHttpUrl("https://auth.example.com")],
+ base_url="https://resource.example.com",
+ )
+ app = _auth_app(transport, auth)
+ path = _PROTECTED_PATH[transport]
+ metadata_url = (
+ f"https://resource.example.com/.well-known/oauth-protected-resource{path}"
+ )
+
+ async with httpx2.AsyncClient(
+ transport=httpx2.ASGITransport(app=app),
+ base_url="https://resource.example.com",
+ ) as client:
+ missing = await client.get(path)
+ metadata = await client.get(metadata_url)
+
+ assert missing.status_code == 401
+ assert (
+ missing.headers["www-authenticate"]
+ == f'Bearer resource_metadata="{metadata_url}"'
+ )
+ assert metadata.status_code == 200
+ assert metadata.json()["resource"] == f"https://resource.example.com{path}"
+
+
class TestStreamableHTTPHostOriginProtection:
"""Test host and origin validation for streamable HTTP apps."""