Skip to content

Commit 2792992

Browse files
committed
Add CORS middleware to Starlette app for frontend support
Introduces CORS middleware to the Starlette app instances in FastMCP to allow requests from local web frontends. This enables compatibility with web clients running on localhost and related origins, supporting credentials and common HTTP methods and headers.
1 parent 959d4e3 commit 2792992

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

src/mcp/server/fastmcp/server.py

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -847,7 +847,19 @@ async def sse_endpoint(request: Request) -> Response:
847847
routes.extend(self._custom_starlette_routes)
848848

849849
# Create Starlette app with routes and middleware
850-
return Starlette(debug=self.settings.debug, routes=routes, middleware=middleware)
850+
app = Starlette(debug=self.settings.debug, routes=routes, middleware=middleware)
851+
852+
# Add CORS middleware for web frontend compatibility
853+
from starlette.middleware.cors import CORSMiddleware
854+
app.add_middleware(
855+
CORSMiddleware,
856+
allow_origins=["http://localhost:*", "http://127.0.0.1:*", "https://localhost:*", "https://127.0.0.1:*"],
857+
allow_credentials=True,
858+
allow_methods=["GET", "POST", "OPTIONS"],
859+
allow_headers=["Content-Type", "Authorization", "X-Requested-With", "Accept"],
860+
)
861+
862+
return app
851863

852864
def streamable_http_app(self) -> Starlette:
853865
"""Return an instance of the StreamableHTTP server app."""
@@ -949,12 +961,25 @@ def streamable_http_app(self) -> Starlette:
949961

950962
routes.extend(self._custom_starlette_routes)
951963

952-
return Starlette(
964+
# Create Starlette app with routes and middleware
965+
app = Starlette(
953966
debug=self.settings.debug,
954967
routes=routes,
955968
middleware=middleware,
956969
lifespan=lambda app: self.session_manager.run(),
957970
)
971+
972+
# Add CORS middleware for web frontend compatibility
973+
from starlette.middleware.cors import CORSMiddleware
974+
app.add_middleware(
975+
CORSMiddleware,
976+
allow_origins=["http://localhost:*", "http://127.0.0.1:*", "https://localhost:*", "https://127.0.0.1:*"],
977+
allow_credentials=True,
978+
allow_methods=["GET", "POST", "OPTIONS"],
979+
allow_headers=["Content-Type", "Authorization", "X-Requested-With", "Accept"],
980+
)
981+
982+
return app
958983

959984
async def list_prompts(self) -> list[MCPPrompt]:
960985
"""List all available prompts."""

0 commit comments

Comments
 (0)