Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 31 additions & 12 deletions src/mcp/server/mcpserver/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import Mount, Route
from starlette.types import Receive, Scope, Send
from starlette.types import ASGIApp, Receive, Scope, Send

from mcp.server.auth.middleware.auth_context import AuthContextMiddleware
from mcp.server.auth.middleware.bearer_auth import BearerAuthBackend, RequireAuthMiddleware
Expand Down Expand Up @@ -99,7 +99,11 @@
StreamableHTTPSessionManager,
)
from mcp.server.subscriptions import InMemorySubscriptionBus, ListenHandler, SubscriptionBus
from mcp.server.transport_security import DEFAULT_MAX_REQUEST_BODY_SIZE, TransportSecuritySettings
from mcp.server.transport_security import (
DEFAULT_MAX_REQUEST_BODY_SIZE,
TransportSecurityMiddleware,
TransportSecuritySettings,
)
from mcp.shared.exceptions import MCPError
from mcp.shared.uri_template import UriTemplate

Expand Down Expand Up @@ -1172,14 +1176,23 @@ def sse_app(
message_path, security_settings=transport_security, max_request_body_size=max_request_body_size
)

async def handle_sse(scope: Scope, receive: Receive, send: Send): # pragma: no cover
# Add client ID from auth context into request context if available
security = TransportSecurityMiddleware(transport_security)

async with sse.connect_sse(scope, receive, send) as streams:
async def handle_sse(scope: Scope, receive: Receive, send: Send) -> None:
if scope["method"] == "HEAD":
response = await security.validate_request(Request(scope, receive))
if response is None:
# GET's headers without its never-ending stream; a Content-Length would claim an empty one.
response = Response(
media_type="text/event-stream", headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"}
)
del response.headers["content-length"]
await response(scope, receive, send)
return
async with sse.connect_sse(scope, receive, send) as streams: # pragma: no cover
await self._lowlevel_server.run(
streams[0], streams[1], self._lowlevel_server.create_initialization_options()
)
return Response()

# Create routes
routes: list[Route | Mount] = []
Expand Down Expand Up @@ -1249,15 +1262,10 @@ async def handle_sse(scope: Scope, receive: Receive, send: Send): # pragma: no
)
else:
# Auth is disabled, no need for RequireAuthMiddleware
# Since handle_sse is an ASGI app, we need to create a compatible endpoint
async def sse_endpoint(request: Request) -> Response: # pragma: no cover
# Convert the Starlette request to ASGI parameters
return await handle_sse(request.scope, request.receive, request._send) # type: ignore[reportPrivateUsage]

routes.append(
Route(
sse_path,
endpoint=sse_endpoint,
endpoint=_ASGIEndpoint(handle_sse),
methods=["GET"],
)
)
Expand Down Expand Up @@ -1421,3 +1429,14 @@ def require_client_extension(ctx: ServerRequestContext[Any, Any], identifier: st
message=f"Client did not declare required extension {identifier!r}",
data=data.model_dump(by_alias=True, mode="json", exclude_none=True),
)


class _ASGIEndpoint:
"""Hands a `Route` a raw ASGI app; a plain function would be wrapped as a request/response endpoint,
which sends a second response after the SSE stream has already completed."""

def __init__(self, app: ASGIApp) -> None:
self.app = app

async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
await self.app(scope, receive, send)
5 changes: 5 additions & 0 deletions src/mcp/server/sse.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@

# Define handler functions
async def handle_sse(request):
# Starlette also routes HEAD here: answer with GET's headers, not its never-ending stream
if request.method == "HEAD":
response = Response(media_type="text/event-stream", headers={"Cache-Control": "no-store"})
Comment thread
Kludex marked this conversation as resolved.
Resolved
del response.headers["content-length"]
return response
async with sse.connect_sse(
request.scope, request.receive, request._send
) as streams:
Expand Down
9 changes: 9 additions & 0 deletions tests/interaction/_requirements.py
Original file line number Diff line number Diff line change
Expand Up @@ -2705,6 +2705,15 @@ def __post_init__(self) -> None:
transports=("sse",),
note="Only observable over the legacy SSE transport.",
),
"transport:sse:head": Requirement(
source="issue:#3736",
behavior=(
"A HEAD request to the SSE endpoint of `MCPServer.sse_app()` is answered at once with the "
"headers a GET would get, no body and no Content-Length, after the same Host/Origin checks as a GET."
Comment thread
Kludex marked this conversation as resolved.
Resolved
),
transports=("sse",),
note="Only observable over the legacy SSE transport.",
),
"transport:stdio": Requirement(
source=f"{SPEC_BASE_URL}/basic/transports#stdio",
behavior=(
Expand Down
34 changes: 34 additions & 0 deletions tests/interaction/transports/test_sse.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
from mcp.client.client import Client
from mcp.client.sse import sse_client
from mcp.server import Server
from mcp.server.mcpserver import MCPServer
from mcp.server.transport_security import TransportSecuritySettings
from tests.interaction._connect import BASE_URL, build_sse_app
from tests.interaction._requirements import requirement
from tests.interaction.transports._bridge import StreamingASGITransport
Expand Down Expand Up @@ -88,3 +90,35 @@ async def test_post_for_an_unknown_session_is_rejected() -> None:
"/messages/", params={"session_id": uuid4().hex}, json={"jsonrpc": "2.0", "method": "ping", "id": 1}
)
assert (response.status_code, response.text) == snapshot((404, "Could not find session"))


@requirement("transport:sse:head")
async def test_head_on_the_sse_endpoint_is_answered_with_headers_only() -> None:
"""`MCPServer.sse_app()` answers HEAD at once with GET's headers and no body instead of streaming forever."""
app = MCPServer("legacy").sse_app(
transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=False)
)
async with httpx2.AsyncClient(transport=StreamingASGITransport(app), base_url=BASE_URL) as http:
with anyio.fail_after(5):
response = await http.head("/sse")
assert (response.status_code, dict(response.headers), response.content) == snapshot(
(
200,
{
"cache-control": "no-store",
"x-accel-buffering": "no",
"content-type": "text/event-stream; charset=utf-8",
},
b"",
)
)


@requirement("transport:sse:head")
async def test_head_on_the_sse_endpoint_is_subject_to_dns_rebinding_protection() -> None:
"""A HEAD from a Host the transport security settings reject gets the same refusal a GET would."""
app = MCPServer("legacy").sse_app(host="127.0.0.1")
async with httpx2.AsyncClient(transport=StreamingASGITransport(app), base_url="http://evil.example") as http:
with anyio.fail_after(5):
response = await http.head("/sse")
assert response.status_code == snapshot(421)
Loading