|
|
import contextlib |
|
|
from fastapi import FastAPI |
|
|
from fastapi.responses import HTMLResponse |
|
|
from echo_server import mcp as echo_mcp |
|
|
from math_server import mcp as math_mcp |
|
|
import os |
|
|
|
|
|
|
|
|
|
|
|
@contextlib.asynccontextmanager |
|
|
async def lifespan(app: FastAPI): |
|
|
async with contextlib.AsyncExitStack() as stack: |
|
|
await stack.enter_async_context(echo_mcp.session_manager.run()) |
|
|
await stack.enter_async_context(math_mcp.session_manager.run()) |
|
|
yield |
|
|
|
|
|
|
|
|
app = FastAPI(lifespan=lifespan) |
|
|
|
|
|
@app.get("/", response_class=HTMLResponse) |
|
|
async def index(): |
|
|
return """ |
|
|
<!doctype html> |
|
|
<html lang="en"> |
|
|
<head> |
|
|
<meta charset="utf-8" /> |
|
|
<meta name="viewport" content="width=device-width, initial-scale=1" /> |
|
|
<title>Multiple MCP Servers Template</title> |
|
|
<style> |
|
|
body { font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica, Arial, sans-serif; margin: 2rem; line-height: 1.5; } |
|
|
code, pre { background: #f6f8fa; padding: 0.2rem 0.4rem; border-radius: 4px; } |
|
|
a { color: #2563eb; text-decoration: none; } |
|
|
a:hover { text-decoration: underline; } |
|
|
.container { max-width: 800px; } |
|
|
h1 { margin-bottom: 0.5rem; } |
|
|
.routes { margin-top: 1rem; } |
|
|
</style> |
|
|
</head> |
|
|
<body> |
|
|
<div class="container"> |
|
|
<h1>Multiple MCP Servers Template</h1> |
|
|
<p>This FastAPI app demonstrates how to host multiple Model Context Protocol (MCP) servers on a single server instance.</p> |
|
|
<p>The following MCP servers are mounted under this app:</p> |
|
|
<ul class="routes"> |
|
|
<li><a href="/echo">/echo</a> — Echo MCP server</li> |
|
|
<li><a href="/math">/math</a> — Math MCP server</li> |
|
|
</ul> |
|
|
<p>Use these routes as sub-apps or as examples for adding more MCP servers.</p> |
|
|
</div> |
|
|
</body> |
|
|
</html> |
|
|
""" |
|
|
|
|
|
app.mount("/echo", echo_mcp.streamable_http_app()) |
|
|
app.mount("/math", math_mcp.streamable_http_app()) |
|
|
|
|
|
PORT = os.environ.get("PORT", 10000) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
import uvicorn |
|
|
uvicorn.run(app, host="0.0.0.0", port=PORT) |
|
|
|