Skip to content

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

Use the server's auth provider for component manager routes (#5425)

Jeremiah Lowindad8b32eb93f
diff --git a/fastmcp_slim/fastmcp/contrib/component_manager/README.md b/fastmcp_slim/fastmcp/contrib/component_manager/README.md
index 0cc99ad15..c8184b91a 100644
--- a/fastmcp_slim/fastmcp/contrib/component_manager/README.md
+++ b/fastmcp_slim/fastmcp/contrib/component_manager/README.md
@@ -9,7 +9,7 @@ The **Component Manager** provides a unified API for enabling and disabling tool
- Enable/disable **tools**, **resources**, and **prompts** via HTTP endpoints.
- Supports **local** and **mounted (server)** components.
- Customizable **API root path**.
-- Optional **Auth scopes** for secured access.
+- Uses the server's **authentication**, with optional extra **auth scopes**.
- Fully integrates with FastMCP with minimal configuration.
---
@@ -90,12 +90,18 @@ To mount the API under a different path:
set_up_component_manager(server=mcp, path="/admin")
```
-### Securing Endpoints with Auth Scopes
+### Authentication and Scopes
-If your server uses authentication:
+The routes require the same authentication as the server's MCP endpoint, so a server with `auth` needs no extra configuration:
```python
mcp = FastMCP(name="Component Manager", instructions="This is a test server with component manager.", auth=auth)
+set_up_component_manager(server=mcp)
+```
+
+Pass `required_scopes` to require scopes in addition to the ones the server's auth provider requires. An empty list requires a valid token without extra scopes:
+
+```python
set_up_component_manager(server=mcp, required_scopes=["write", "read"])
```
@@ -114,7 +120,7 @@ curl -X POST \
## 🧱 Working with Mounted Servers
-You can also combine different configurations when working with mounted servers β€” for example, using different scopes:
+A mounted server's routes use the parent server's auth provider. Each server can still require its own extra scopes:
```python
mcp = FastMCP(name="Component Manager", instructions="This is a test server with component manager.", auth=auth)
diff --git a/fastmcp_slim/fastmcp/contrib/component_manager/component_manager.py b/fastmcp_slim/fastmcp/contrib/component_manager/component_manager.py
index 099b9052f..02d238386 100644
--- a/fastmcp_slim/fastmcp/contrib/component_manager/component_manager.py
+++ b/fastmcp_slim/fastmcp/contrib/component_manager/component_manager.py
@@ -1,16 +1,20 @@
"""
HTTP routes for enabling/disabling components in FastMCP.
-Provides REST endpoints for controlling component enabled state with optional
-authentication scopes.
+Provides REST endpoints for controlling component enabled state. The routes
+use the authentication of the server whose HTTP app serves them.
"""
-from mcp.server.auth.middleware.bearer_auth import RequireAuthMiddleware
+from mcp.server.auth.routes import build_resource_metadata_url
from starlette.applications import Starlette
+from starlette.middleware import Middleware
from starlette.requests import Request
from starlette.responses import JSONResponse
-from starlette.routing import Mount, Route
+from starlette.routing import Route
+from starlette.types import ASGIApp, Receive, Scope, Send
+from fastmcp.server.auth import AuthProvider
+from fastmcp.server.auth.middleware import RequireAuthMiddleware
from fastmcp.server.server import FastMCP
@@ -19,11 +23,21 @@ def set_up_component_manager(
) -> None:
"""Set up HTTP routes for enabling/disabling tools, resources, and prompts.
+ The routes require the same authentication as the MCP endpoint of the
+ server whose HTTP app serves them. For a mounted server, that is the
+ parent server's auth provider. If the serving server has no auth provider
+ and `required_scopes` is omitted, the routes are unauthenticated, like the
+ MCP endpoint itself.
+
Args:
server: The FastMCP server instance.
path: Base path for component management routes.
- required_scopes: Optional list of scopes required for these routes.
- Applies only if authentication is enabled.
+ required_scopes: Scopes a token must have to use these routes, in
+ addition to the scopes the server's auth provider requires. An
+ empty list requires authentication without extra scopes. Omit it
+ to require exactly what the MCP endpoint requires. If the serving
+ server has no auth provider, routes with `required_scopes` reject
+ every request with 401.
Routes created:
POST /tools/{name}/enable[?version=v1]
@@ -33,58 +47,103 @@ def set_up_component_manager(
POST /prompts/{name}/enable[?version=v1]
POST /prompts/{name}/disable[?version=v1]
"""
- if required_scopes is None:
- # No auth - include path prefix in routes
- routes = _build_routes(server, path)
- server._additional_http_routes.extend(routes)
- else:
- # With auth - Mount handles path prefix, routes shouldn't have it
- routes = _build_routes(server, "/")
- mount = Mount(
- path if path != "/" else "",
- app=RequireAuthMiddleware(Starlette(routes=routes), required_scopes),
+ routes = _build_routes(server, path, required_scopes)
+ server._additional_http_routes.extend(routes)
+
+
+class _ComponentManagerAuth:
+ """Apply the serving server's authentication to a management route.
+
+ The auth provider is resolved for each request from the HTTP app that
+ serves it, so routes forwarded from a mounted server use the parent's
+ provider, and a provider assigned after setup still applies.
+ """
+
+ def __init__(
+ self, app: ASGIApp, server: FastMCP, required_scopes: list[str] | None
+ ) -> None:
+ self.app = app
+ self.server = server
+ self.required_scopes = required_scopes
+
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ auth, mcp_path = _serving_auth(scope, self.server)
+ if auth is None and self.required_scopes is None:
+ await self.app(scope, receive, send)
+ return
+
+ scopes = list(auth.required_scopes) if auth is not None else []
+ for scope_name in self.required_scopes or []:
+ if scope_name not in scopes:
+ scopes.append(scope_name)
+ challenge_scopes = (
+ auth.get_challenge_scopes(scopes) if auth is not None else None
+ )
+ resource_url = (
+ auth._get_resource_url(mcp_path)
+ if auth is not None and mcp_path is not None
+ else None
)
- server._additional_http_routes.append(mount)
+ resource_metadata_url = (
+ build_resource_metadata_url(resource_url) if resource_url else None
+ )
+ guarded = RequireAuthMiddleware(
+ self.app,
+ scopes,
+ resource_metadata_url=resource_metadata_url,
+ challenge_scopes=challenge_scopes,
+ )
+ await guarded(scope, receive, send)
+
+def _serving_auth(
+ scope: Scope, server: FastMCP
+) -> tuple[AuthProvider | None, str | None]:
+ """Return the auth provider and MCP path of the HTTP app serving this request.
+
+ FastMCP's HTTP app factories store the provider they were built with, and
+ the path of the MCP endpoint, on the app state. Routes served by any other
+ app use `server.auth` and have no known MCP path.
+ """
+ app = scope.get("app")
+ if isinstance(app, Starlette) and isinstance(
+ getattr(app.state, "fastmcp_server", None), FastMCP
+ ):
+ auth = getattr(app.state, "fastmcp_auth", None)
+ mcp_path = getattr(app.state, "path", None)
+ return (
+ auth if isinstance(auth, AuthProvider) else None,
+ mcp_path if isinstance(mcp_path, str) else None,
+ )
+ return server.auth, None
-def _build_routes(server: FastMCP, base_path: str) -> list[Route]:
+
+def _build_routes(
+ server: FastMCP, base_path: str, required_scopes: list[str] | None
+) -> list[Route]:
"""Build all component management routes."""
prefix = base_path.rstrip("/") if base_path != "/" else ""
+ middleware = [
+ Middleware(
+ _ComponentManagerAuth, server=server, required_scopes=required_scopes
+ )
+ ]
- return [
- # Tools
- Route(
- f"{prefix}/tools/{{name}}/enable",
- endpoint=_make_endpoint(server, "tool", "enable"),
- methods=["POST"],
- ),
- Route(
- f"{prefix}/tools/{{name}}/disable",
- endpoint=_make_endpoint(server, "tool", "disable"),
- methods=["POST"],
- ),
- # Resources
- Route(
- f"{prefix}/resources/{{uri:path}}/enable",
- endpoint=_make_endpoint(server, "resource", "enable"),
+ def route(route_path: str, component_type: str, action: str) -> Route:
+ return Route(
+ f"{prefix}{route_path}",
+ endpoint=_make_endpoint(server, component_type, action),
methods=["POST"],
- ),
- Route(
- f"{prefix}/resources/{{uri:path}}/disable",
- endpoint=_make_endpoint(server, "resource", "disable"),
- methods=["POST"],
- ),
- # Prompts
- Route(
- f"{prefix}/prompts/{{name}}/enable",
- endpoint=_make_endpoint(server, "prompt", "enable"),
- methods=["POST"],
- ),
- Route(
- f"{prefix}/prompts/{{name}}/disable",
- endpoint=_make_endpoint(server, "prompt", "disable"),
- methods=["POST"],
- ),
+ middleware=middleware,
+ )
+
+ return [
+ route("/tools/{name}/enable", "tool", "enable"),
+ route("/tools/{name}/disable", "tool", "disable"),
+ route("/resources/{uri:path}/enable", "resource", "enable"),
+ route("/resources/{uri:path}/disable", "resource", "disable"),
+ route("/prompts/{name}/enable", "prompt", "enable"),
+ route("/prompts/{name}/disable", "prompt", "disable"),
]
diff --git a/fastmcp_slim/fastmcp/server/http.py b/fastmcp_slim/fastmcp/server/http.py
index 9e3dc0dd6..70bb17438 100644
--- a/fastmcp_slim/fastmcp/server/http.py
+++ b/fastmcp_slim/fastmcp/server/http.py
@@ -537,6 +537,7 @@ def create_sse_app(
)
# Store the FastMCP server instance on the Starlette app state
app.state.fastmcp_server = server
+ app.state.fastmcp_auth = auth
app.state.path = sse_path
app.state.transport_type = "sse"
@@ -719,6 +720,7 @@ def create_streamable_http_app(
)
# Store the FastMCP server instance on the Starlette app state
app.state.fastmcp_server = server
+ app.state.fastmcp_auth = auth
app.state.path = streamable_http_path
app.state.transport_type = "streamable-http"
diff --git a/tests/contrib/test_component_manager.py b/tests/contrib/test_component_manager.py
index b31b0d0ee..51b1814d4 100644
--- a/tests/contrib/test_component_manager.py
+++ b/tests/contrib/test_component_manager.py
@@ -1,10 +1,17 @@
+from typing import Literal
+
import pytest
+from pydantic import AnyHttpUrl
from starlette import status
+from starlette.requests import Request
+from starlette.responses import PlainTextResponse
from starlette.testclient import TestClient
from fastmcp import FastMCP
from fastmcp.contrib.component_manager import set_up_component_manager
+from fastmcp.server.auth import RemoteAuthProvider
from fastmcp.server.auth.providers.jwt import JWTVerifier, RSAKeyPair
+from fastmcp.server.http import create_sse_app, create_streamable_http_app
class TestComponentManagementRoutes:
@@ -602,3 +609,400 @@ class TestComponentManagerWithPathAuth:
assert response.json() == {"message": "Enabled prompt: test_prompt"}
prompts = await self.mcp.list_prompts()
assert any(p.name == "test_prompt" for p in prompts)
+
+
+ComponentKind = Literal["tool", "resource", "template", "prompt"]
+
+ISSUER = "https://dev.example.com"
+AUDIENCE = "my-dev-server"
+
+ROUTE_CASES = [
+ pytest.param("tool", "test_tool", "/tools/test_tool", id="tool"),
+ pytest.param(
+ "resource",
+ "data://test_resource",
+ "/resources/data://test_resource",
+ id="resource",
+ ),
+ pytest.param(
+ "template",
+ "data://test_resource/{id}",
+ "/resources/data://test_resource/{id}",
+ id="template",
+ ),
+ pytest.param("prompt", "test_prompt", "/prompts/test_prompt", id="prompt"),
+]
+
+
+def _add_components(mcp: FastMCP) -> None:
+ @mcp.tool
+ def test_tool() -> str:
+ return "test_tool_result"
+
+ @mcp.resource("data://test_resource")
+ def test_resource() -> str:
+ return "test_resource_result"
+
+ @mcp.resource("data://test_resource/{id}")
+ def test_template(id: str) -> dict:
+ return {"id": id}
+
+ @mcp.prompt
+ def test_prompt() -> str:
+ return "test_prompt_result"
+
+
+async def _is_enabled(mcp: FastMCP, kind: ComponentKind, key: str) -> bool:
+ if kind == "tool":
+ return any(t.name == key for t in await mcp.list_tools())
+ if kind == "resource":
+ return any(str(r.uri) == key for r in await mcp.list_resources())
+ if kind == "template":
+ return any(t.uri_template == key for t in await mcp.list_resource_templates())
+ return any(p.name == key for p in await mcp.list_prompts())
+
+
+def _jwt_auth(
+ key_pair: RSAKeyPair, required_scopes: list[str] | None = None
+) -> JWTVerifier:
+ return JWTVerifier(
+ public_key=key_pair.public_key,
+ issuer=ISSUER,
+ audience=AUDIENCE,
+ required_scopes=required_scopes,
+ )
+
+
+def _bearer(key_pair: RSAKeyPair, scopes: list[str]) -> dict[str, str]:
+ token = key_pair.create_token(
+ subject="dev-user", issuer=ISSUER, audience=AUDIENCE, scopes=scopes
+ )
+ return {"Authorization": "Bearer " + token}
+
+
+def _server_with_disabled_tool(
+ name: str,
+ auth: JWTVerifier | None = None,
+ required_scopes: list[str] | None = None,
+) -> FastMCP:
+ mcp = FastMCP(name, auth=auth)
+ _add_components(mcp)
+ set_up_component_manager(server=mcp, required_scopes=required_scopes)
+ mcp.disable(names={"test_tool"}, components={"tool"})
+ return mcp
+
+
+class TestComponentManagerServerAuth:
+ """Routes require the server's token."""
+
+ @pytest.mark.parametrize("action", ["enable", "disable"])
+ @pytest.mark.parametrize(("kind", "key", "route"), ROUTE_CASES)
+ async def test_request_without_token_returns_401(
+ self,
+ rsa_key_pair: RSAKeyPair,
+ kind: ComponentKind,
+ key: str,
+ route: str,
+ action: str,
+ ):
+ mcp = FastMCP("AuthServer", auth=_jwt_auth(rsa_key_pair))
+ _add_components(mcp)
+ set_up_component_manager(server=mcp)
+ if action == "enable":
+ mcp.disable(names={key}, components={kind})
+ initially_enabled = await _is_enabled(mcp, kind, key)
+
+ response = TestClient(mcp.http_app()).post(f"{route}/{action}")
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ assert await _is_enabled(mcp, kind, key) == initially_enabled
+
+ @pytest.mark.parametrize("action", ["enable", "disable"])
+ @pytest.mark.parametrize(("kind", "key", "route"), ROUTE_CASES)
+ async def test_request_with_token_applies_change(
+ self,
+ rsa_key_pair: RSAKeyPair,
+ kind: ComponentKind,
+ key: str,
+ route: str,
+ action: str,
+ ):
+ mcp = FastMCP("AuthServer", auth=_jwt_auth(rsa_key_pair))
+ _add_components(mcp)
+ set_up_component_manager(server=mcp)
+ if action == "enable":
+ mcp.disable(names={key}, components={kind})
+
+ response = TestClient(mcp.http_app()).post(
+ f"{route}/{action}", headers=_bearer(rsa_key_pair, scopes=[])
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert await _is_enabled(mcp, kind, key) == (action == "enable")
+
+ async def test_token_without_server_scope_returns_401(
+ self, rsa_key_pair: RSAKeyPair
+ ):
+ mcp = _server_with_disabled_tool(
+ "AuthServer", auth=_jwt_auth(rsa_key_pair, ["mcp:read"])
+ )
+
+ response = TestClient(mcp.http_app()).post(
+ "/tools/test_tool/enable", headers=_bearer(rsa_key_pair, scopes=[])
+ )
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ assert not await _is_enabled(mcp, "tool", "test_tool")
+
+ async def test_token_with_server_scope_allowed(self, rsa_key_pair: RSAKeyPair):
+ mcp = _server_with_disabled_tool(
+ "AuthServer", auth=_jwt_auth(rsa_key_pair, ["mcp:read"])
+ )
+
+ response = TestClient(mcp.http_app()).post(
+ "/tools/test_tool/enable",
+ headers=_bearer(rsa_key_pair, scopes=["mcp:read"]),
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert await _is_enabled(mcp, "tool", "test_tool")
+
+ async def test_auth_assigned_after_setup_applies(self, rsa_key_pair: RSAKeyPair):
+ mcp = _server_with_disabled_tool("LateAuthServer")
+ mcp.auth = _jwt_auth(rsa_key_pair)
+
+ response = TestClient(mcp.http_app()).post("/tools/test_tool/enable")
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ assert not await _is_enabled(mcp, "tool", "test_tool")
+
+ async def test_streamable_http_app_auth_argument_applies(
+ self, rsa_key_pair: RSAKeyPair
+ ):
+ mcp = _server_with_disabled_tool("FactoryAuthServer")
+ app = create_streamable_http_app(
+ server=mcp, streamable_http_path="/mcp", auth=_jwt_auth(rsa_key_pair)
+ )
+
+ response = TestClient(app).post("/tools/test_tool/enable")
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ assert not await _is_enabled(mcp, "tool", "test_tool")
+
+ async def test_sse_app_auth_argument_applies(self, rsa_key_pair: RSAKeyPair):
+ mcp = _server_with_disabled_tool("FactoryAuthServer")
+ app = create_sse_app(
+ server=mcp,
+ message_path="/messages/",
+ sse_path="/sse",
+ auth=_jwt_auth(rsa_key_pair),
+ )
+
+ response = TestClient(app).post("/tools/test_tool/enable")
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ assert not await _is_enabled(mcp, "tool", "test_tool")
+
+
+class TestComponentManagerMountedServer:
+ """Mounted routes use the parent server's auth."""
+
+ async def test_request_without_token_returns_401(self, rsa_key_pair: RSAKeyPair):
+ parent = FastMCP("Parent", auth=_jwt_auth(rsa_key_pair))
+ child = _server_with_disabled_tool("Child")
+ parent.mount(child)
+
+ response = TestClient(parent.http_app()).post("/tools/test_tool/enable")
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ assert not await _is_enabled(child, "tool", "test_tool")
+
+ async def test_parent_token_applies_change(self, rsa_key_pair: RSAKeyPair):
+ parent = FastMCP("Parent", auth=_jwt_auth(rsa_key_pair))
+ child = _server_with_disabled_tool("Child")
+ parent.mount(child)
+
+ response = TestClient(parent.http_app()).post(
+ "/tools/test_tool/enable", headers=_bearer(rsa_key_pair, scopes=[])
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert await _is_enabled(child, "tool", "test_tool")
+
+ @pytest.mark.parametrize(
+ ("token_scopes", "expected_status"),
+ [
+ pytest.param([], status.HTTP_403_FORBIDDEN, id="missing-scope"),
+ pytest.param(["admin"], status.HTTP_200_OK, id="has-scope"),
+ ],
+ )
+ async def test_child_required_scopes_checked_against_parent_token(
+ self,
+ rsa_key_pair: RSAKeyPair,
+ token_scopes: list[str],
+ expected_status: int,
+ ):
+ parent = FastMCP("Parent", auth=_jwt_auth(rsa_key_pair))
+ child = _server_with_disabled_tool("Child", required_scopes=["admin"])
+ parent.mount(child)
+
+ response = TestClient(parent.http_app()).post(
+ "/tools/test_tool/enable",
+ headers=_bearer(rsa_key_pair, scopes=token_scopes),
+ )
+
+ assert response.status_code == expected_status
+ assert await _is_enabled(child, "tool", "test_tool") == (
+ expected_status == status.HTTP_200_OK
+ )
+
+
+class TestComponentManagerExplicitScopes:
+ """`required_scopes` adds to the server's required scopes."""
+
+ async def test_token_with_only_server_scopes_returns_403(
+ self, rsa_key_pair: RSAKeyPair
+ ):
+ mcp = _server_with_disabled_tool(
+ "AuthServer",
+ auth=_jwt_auth(rsa_key_pair, ["mcp:read"]),
+ required_scopes=["admin"],
+ )
+
+ response = TestClient(mcp.http_app()).post(
+ "/tools/test_tool/enable",
+ headers=_bearer(rsa_key_pair, scopes=["mcp:read"]),
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert not await _is_enabled(mcp, "tool", "test_tool")
+
+ async def test_token_with_only_extra_scopes_returns_401(
+ self, rsa_key_pair: RSAKeyPair
+ ):
+ mcp = _server_with_disabled_tool(
+ "AuthServer",
+ auth=_jwt_auth(rsa_key_pair, ["mcp:read"]),
+ required_scopes=["admin"],
+ )
+
+ response = TestClient(mcp.http_app()).post(
+ "/tools/test_tool/enable", headers=_bearer(rsa_key_pair, scopes=["admin"])
+ )
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ assert not await _is_enabled(mcp, "tool", "test_tool")
+
+ async def test_token_with_server_and_extra_scopes_applies_change(
+ self, rsa_key_pair: RSAKeyPair
+ ):
+ mcp = _server_with_disabled_tool(
+ "AuthServer",
+ auth=_jwt_auth(rsa_key_pair, ["mcp:read"]),
+ required_scopes=["admin"],
+ )
+
+ response = TestClient(mcp.http_app()).post(
+ "/tools/test_tool/enable",
+ headers=_bearer(rsa_key_pair, scopes=["mcp:read", "admin"]),
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert await _is_enabled(mcp, "tool", "test_tool")
+
+ async def test_empty_scopes_require_a_token(self, rsa_key_pair: RSAKeyPair):
+ mcp = _server_with_disabled_tool(
+ "AuthServer", auth=_jwt_auth(rsa_key_pair), required_scopes=[]
+ )
+
+ response = TestClient(mcp.http_app()).post("/tools/test_tool/enable")
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ assert not await _is_enabled(mcp, "tool", "test_tool")
+
+ async def test_empty_scopes_accept_any_valid_token(self, rsa_key_pair: RSAKeyPair):
+ mcp = _server_with_disabled_tool(
+ "AuthServer", auth=_jwt_auth(rsa_key_pair), required_scopes=[]
+ )
+
+ response = TestClient(mcp.http_app()).post(
+ "/tools/test_tool/enable", headers=_bearer(rsa_key_pair, scopes=[])
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert await _is_enabled(mcp, "tool", "test_tool")
+
+ @pytest.mark.parametrize("required_scopes", [["admin"], []])
+ async def test_scopes_on_server_without_auth_return_401(
+ self, required_scopes: list[str]
+ ):
+ mcp = _server_with_disabled_tool(
+ "NoAuthServer", required_scopes=required_scopes
+ )
+
+ response = TestClient(mcp.http_app()).post("/tools/test_tool/enable")
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ assert not await _is_enabled(mcp, "tool", "test_tool")
+
+ async def test_custom_route_after_component_manager_stays_reachable(
+ self, rsa_key_pair: RSAKeyPair
+ ):
+ mcp = FastMCP("AuthServer", auth=_jwt_auth(rsa_key_pair))
+ set_up_component_manager(server=mcp, required_scopes=["admin"])
+
+ @mcp.custom_route("/health", methods=["GET"])
+ async def health(request: Request) -> PlainTextResponse:
+ return PlainTextResponse("ok")
+
+ response = TestClient(mcp.http_app()).get("/health")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.text == "ok"
+
+
+class TestComponentManagerChallenge:
+ """Challenges match the MCP endpoint's challenges."""
+
+ @pytest.mark.parametrize(
+ ("base_url", "resource_base_url"),
+ [
+ ("https://api.example.com", None),
+ ("https://auth-host.example.com", "https://api.example.com"),
+ ],
+ )
+ async def test_challenge_includes_resource_metadata(
+ self, rsa_key_pair: RSAKeyPair, base_url: str, resource_base_url: str | None
+ ):
+ auth = RemoteAuthProvider(
+ token_verifier=_jwt_auth(rsa_key_pair),
+ authorization_servers=[AnyHttpUrl("https://auth.example.com")],
+ base_url=base_url,
+ resource_base_url=resource_base_url,
+ )
+ mcp = _server_with_disabled_tool("OAuthServer")
+ mcp.auth = auth
+ client = TestClient(mcp.http_app(path="/mcp"))
+
+ mcp_response = client.post("/mcp")
+ response = client.post("/tools/test_tool/enable")
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ assert (
+ 'resource_metadata="https://api.example.com/.well-known/oauth-protected-resource/mcp"'
+ in response.headers["www-authenticate"]
+ )
+ assert (
+ response.headers["www-authenticate"]
+ == mcp_response.headers["www-authenticate"]
+ )
+
+ async def test_challenge_without_base_url_has_no_resource_metadata(
+ self, rsa_key_pair: RSAKeyPair
+ ):
+ mcp = _server_with_disabled_tool("VerifierServer", auth=_jwt_auth(rsa_key_pair))
+
+ response = TestClient(mcp.http_app(path="/mcp")).post("/tools/test_tool/enable")
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ assert "resource_metadata" not in response.headers["www-authenticate"]