Fix CORS middleware by running uvicorn directly
The previous fix added CORS middleware to the app, but mcp.run() creates a new app instance that doesn't include our middleware. Solution: - Import uvicorn - For streamable-http transport, run uvicorn directly with the middleware-enhanced app (mcp_app) - This ensures CORS middleware is actually applied - For other transports (SSE), fall back to mcp.run() with a warning This fixes the "OPTIONS /mcp HTTP/1.1 405 Method Not Allowed" error by ensuring CORS middleware handles preflight requests properly.
This commit is contained in:
parent
d35e12b6ae
commit
ef177147c4
1 changed files with 19 additions and 2 deletions
|
|
@ -8,6 +8,7 @@ with automatic API monitoring and dynamic schema adaptation.
|
||||||
import logging
|
import logging
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
|
import uvicorn
|
||||||
from mcp.server.fastmcp import FastMCP
|
from mcp.server.fastmcp import FastMCP
|
||||||
from starlette.middleware.cors import CORSMiddleware
|
from starlette.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
|
|
@ -103,8 +104,24 @@ def main():
|
||||||
"Users will need to login or provide a cookie."
|
"Users will need to login or provide a cookie."
|
||||||
)
|
)
|
||||||
|
|
||||||
# Run the server
|
# Run the server with the modified app (with middleware)
|
||||||
mcp.run(transport=settings.TRANSPORT)
|
# Note: We cannot use mcp.run() as it creates a new app instance without our middleware
|
||||||
|
if settings.TRANSPORT == "streamable-http":
|
||||||
|
# Run uvicorn directly with our middleware-enhanced app
|
||||||
|
uvicorn.run(
|
||||||
|
mcp_app,
|
||||||
|
host=settings.HOST,
|
||||||
|
port=settings.PORT,
|
||||||
|
log_level=settings.LOG_LEVEL.lower(),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# For other transports (SSE), use the default run method
|
||||||
|
# Note: SSE transport may not support custom middleware
|
||||||
|
logger.warning(
|
||||||
|
"Using mcp.run() for non-streamable-http transport. "
|
||||||
|
"CORS middleware may not be applied."
|
||||||
|
)
|
||||||
|
mcp.run(transport=settings.TRANSPORT)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue