Skip to content

Update routing for streamable HTTP to avoid 307 redirect #1115

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Jul 11, 2025
Merged
Changes from 5 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
22 changes: 15 additions & 7 deletions src/mcp/server/fastmcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -828,7 +828,6 @@ async def sse_endpoint(request: Request) -> Response:
def streamable_http_app(self) -> Starlette:
"""Return an instance of the StreamableHTTP server app."""
from starlette.middleware import Middleware
from starlette.routing import Mount

# Create session manager on first call (lazy initialization)
if self._session_manager is None:
Expand All @@ -841,8 +840,7 @@ def streamable_http_app(self) -> Starlette:
)

# Create the ASGI handler
async def handle_streamable_http(scope: Scope, receive: Receive, send: Send) -> None:
await self.session_manager.handle_request(scope, receive, send)
streamable_http_app = StreamableHTTPASGIApp(self._session_manager)

# Create routes
routes: list[Route | Mount] = []
Expand Down Expand Up @@ -889,17 +887,17 @@ async def handle_streamable_http(scope: Scope, receive: Receive, send: Send) ->
)

routes.append(
Mount(
Route(
self.settings.streamable_http_path,
app=RequireAuthMiddleware(handle_streamable_http, required_scopes, resource_metadata_url),
endpoint=RequireAuthMiddleware(streamable_http_app, required_scopes, resource_metadata_url),
)
)
else:
# Auth is disabled, no wrapper needed
routes.append(
Mount(
Route(
self.settings.streamable_http_path,
app=handle_streamable_http,
endpoint=streamable_http_app,
)
)

Expand Down Expand Up @@ -971,6 +969,16 @@ async def get_prompt(self, name: str, arguments: dict[str, Any] | None = None) -
logger.exception(f"Error getting prompt {name}")
raise ValueError(str(e))

class StreamableHTTPASGIApp:
"""
ASGI application for Streamable HTTP server transport.
"""

def __init__(self, session_manager: StreamableHTTPSessionManager):
self.session_manager = session_manager

async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
await self.session_manager.handle_request(scope, receive, send)

class Context(BaseModel, Generic[ServerSessionT, LifespanContextT, RequestT]):
"""Context object providing access to MCP capabilities.
Expand Down
Loading