Skip to content

Add CORS middleware to Starlette app for frontend support #1201

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all 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
31 changes: 29 additions & 2 deletions src/mcp/server/fastmcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -847,7 +847,20 @@ async def sse_endpoint(request: Request) -> Response:
routes.extend(self._custom_starlette_routes)

# Create Starlette app with routes and middleware
return Starlette(debug=self.settings.debug, routes=routes, middleware=middleware)
app = Starlette(debug=self.settings.debug, routes=routes, middleware=middleware)

# Add CORS middleware for web frontend compatibility
from starlette.middleware.cors import CORSMiddleware

app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:*", "http://127.0.0.1:*", "https://localhost:*", "https://127.0.0.1:*"],
allow_credentials=True,
allow_methods=["GET", "POST", "OPTIONS"],
allow_headers=["Content-Type", "Authorization", "X-Requested-With", "Accept"],
)

return app

def streamable_http_app(self) -> Starlette:
"""Return an instance of the StreamableHTTP server app."""
Expand Down Expand Up @@ -949,13 +962,27 @@ def streamable_http_app(self) -> Starlette:

routes.extend(self._custom_starlette_routes)

return Starlette(
# Create Starlette app with routes and middleware
app = Starlette(
debug=self.settings.debug,
routes=routes,
middleware=middleware,
lifespan=lambda app: self.session_manager.run(),
)

# Add CORS middleware for web frontend compatibility
from starlette.middleware.cors import CORSMiddleware

app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:*", "http://127.0.0.1:*", "https://localhost:*", "https://127.0.0.1:*"],
allow_credentials=True,
allow_methods=["GET", "POST", "OPTIONS"],
allow_headers=["Content-Type", "Authorization", "X-Requested-With", "Accept"],
)

return app

async def list_prompts(self) -> list[MCPPrompt]:
"""List all available prompts."""
prompts = self._prompt_manager.list_prompts()
Expand Down
Loading