|
| 1 | +from unittest.mock import Mock |
| 2 | + |
| 3 | +from pydantic import AnyHttpUrl |
| 4 | +from starlette.applications import Starlette |
| 5 | +from starlette.middleware.authentication import AuthenticationMiddleware |
| 6 | + |
| 7 | +from mcp.server.auth.middleware.auth_context import AuthContextMiddleware |
| 8 | +from mcp.server.auth.provider import AccessToken |
| 9 | +from mcp.server.auth.settings import AuthSettings |
| 10 | +from mcp.server.lowlevel.server import Server |
| 11 | + |
| 12 | + |
| 13 | +class DummyTokenVerifier: |
| 14 | + async def verify_token(self, token: str) -> AccessToken | None: |
| 15 | + return None |
| 16 | + |
| 17 | + |
| 18 | +def route_paths(app: Starlette) -> set[str]: |
| 19 | + paths: set[str] = set() |
| 20 | + for route in app.routes: |
| 21 | + path = getattr(route, "path", None) |
| 22 | + if isinstance(path, str): |
| 23 | + paths.add(path) |
| 24 | + return paths |
| 25 | + |
| 26 | + |
| 27 | +def test_streamable_http_app_adds_auth_routes_without_token_verifier(): |
| 28 | + server = Server("test-server") |
| 29 | + |
| 30 | + app = server.streamable_http_app( |
| 31 | + host="testserver", |
| 32 | + auth=AuthSettings( |
| 33 | + issuer_url=AnyHttpUrl("https://auth.example.com"), |
| 34 | + resource_server_url=AnyHttpUrl("https://testserver/mcp"), |
| 35 | + ), |
| 36 | + auth_server_provider=Mock(), |
| 37 | + ) |
| 38 | + |
| 39 | + assert { |
| 40 | + "/mcp", |
| 41 | + "/authorize", |
| 42 | + "/token", |
| 43 | + "/.well-known/oauth-authorization-server", |
| 44 | + "/.well-known/oauth-protected-resource/mcp", |
| 45 | + }.issubset(route_paths(app)) |
| 46 | + |
| 47 | + |
| 48 | +def test_streamable_http_app_skips_resource_metadata_route_when_resource_server_url_missing(): |
| 49 | + server = Server("test-server") |
| 50 | + |
| 51 | + app = server.streamable_http_app( |
| 52 | + host="testserver", |
| 53 | + auth=AuthSettings( |
| 54 | + issuer_url=AnyHttpUrl("https://auth.example.com"), |
| 55 | + resource_server_url=None, |
| 56 | + ), |
| 57 | + token_verifier=DummyTokenVerifier(), |
| 58 | + ) |
| 59 | + |
| 60 | + paths = route_paths(app) |
| 61 | + middleware_classes = [middleware.cls for middleware in app.user_middleware] |
| 62 | + |
| 63 | + assert "/mcp" in paths |
| 64 | + assert "/.well-known/oauth-protected-resource/mcp" not in paths |
| 65 | + assert AuthenticationMiddleware in middleware_classes |
| 66 | + assert AuthContextMiddleware in middleware_classes |
0 commit comments