Return an instance of the SSE server app.
(
self,
*,
sse_path: str = "/sse",
message_path: str = "/messages/",
transport_security: TransportSecuritySettings | None = None,
host: str = "127.0.0.1",
)
| 904 | await server.serve() |
| 905 | |
| 906 | def sse_app( |
| 907 | self, |
| 908 | *, |
| 909 | sse_path: str = "/sse", |
| 910 | message_path: str = "/messages/", |
| 911 | transport_security: TransportSecuritySettings | None = None, |
| 912 | host: str = "127.0.0.1", |
| 913 | ) -> Starlette: |
| 914 | """Return an instance of the SSE server app.""" |
| 915 | # Auto-enable DNS rebinding protection for localhost (IPv4 and IPv6) |
| 916 | if transport_security is None and host in ("127.0.0.1", "localhost", "::1"): |
| 917 | transport_security = TransportSecuritySettings( |
| 918 | enable_dns_rebinding_protection=True, |
| 919 | allowed_hosts=["127.0.0.1:*", "localhost:*", "[::1]:*"], |
| 920 | allowed_origins=["http://127.0.0.1:*", "http://localhost:*", "http://[::1]:*"], |
| 921 | ) |
| 922 | |
| 923 | sse = SseServerTransport(message_path, security_settings=transport_security) |
| 924 | |
| 925 | async def handle_sse(scope: Scope, receive: Receive, send: Send): # pragma: no cover |
| 926 | # Add client ID from auth context into request context if available |
| 927 | |
| 928 | async with sse.connect_sse(scope, receive, send) as streams: |
| 929 | await self._lowlevel_server.run( |
| 930 | streams[0], streams[1], self._lowlevel_server.create_initialization_options() |
| 931 | ) |
| 932 | return Response() |
| 933 | |
| 934 | # Create routes |
| 935 | routes: list[Route | Mount] = [] |
| 936 | middleware: list[Middleware] = [] |
| 937 | required_scopes: list[str] = [] |
| 938 | |
| 939 | # Set up auth if configured |
| 940 | if self.settings.auth: # pragma: no cover |
| 941 | required_scopes = self.settings.auth.required_scopes or [] |
| 942 | |
| 943 | # Add auth middleware if token verifier is available |
| 944 | if self._token_verifier: |
| 945 | middleware = [ |
| 946 | # extract auth info from request (but do not require it) |
| 947 | Middleware( |
| 948 | AuthenticationMiddleware, |
| 949 | backend=BearerAuthBackend(self._token_verifier), |
| 950 | ), |
| 951 | # Add the auth context middleware to store |
| 952 | # authenticated user in a contextvar |
| 953 | Middleware(AuthContextMiddleware), |
| 954 | ] |
| 955 | |
| 956 | # Add auth endpoints if auth server provider is configured |
| 957 | if self._auth_server_provider: |
| 958 | from mcp.server.auth.routes import create_auth_routes |
| 959 | |
| 960 | routes.extend( |
| 961 | create_auth_routes( |
| 962 | provider=self._auth_server_provider, |
| 963 | issuer_url=self.settings.auth.issuer_url, |