|
10 | 10 | from fastapi.routing import APIRoute |
11 | 11 | from fastapi.staticfiles import StaticFiles |
12 | 12 | from fastapi_mcp import FastApiMCP |
| 13 | +from starlette.datastructures import MutableHeaders |
13 | 14 | from starlette.exceptions import HTTPException as StarletteHTTPException |
14 | 15 | from starlette.middleware.cors import CORSMiddleware |
| 16 | +from starlette.middleware.base import BaseHTTPMiddleware |
15 | 17 |
|
16 | 18 | from alembic import command |
17 | 19 | from apps.api import api_router |
@@ -77,6 +79,20 @@ def custom_generate_unique_id(route: APIRoute) -> str: |
77 | 79 | redoc_url=None |
78 | 80 | ) |
79 | 81 |
|
| 82 | + |
| 83 | +class McpClientIpForwardMiddleware(BaseHTTPMiddleware): |
| 84 | + async def dispatch(self, request: Request, call_next): |
| 85 | + client_host = request.client.host if request.client else None |
| 86 | + if client_host: |
| 87 | + headers = MutableHeaders(scope=request.scope) |
| 88 | + if not headers.get("x-real-ip"): |
| 89 | + headers["x-real-ip"] = client_host |
| 90 | + if not headers.get("x-forwarded-for"): |
| 91 | + headers["x-forwarded-for"] = client_host |
| 92 | + if not headers.get("x-client-ip"): |
| 93 | + headers["x-client-ip"] = client_host |
| 94 | + return await call_next(request) |
| 95 | + |
80 | 96 | # cache docs for different text |
81 | 97 | _openapi_cache: Dict[str, Dict[str, Any]] = {} |
82 | 98 |
|
@@ -174,6 +190,7 @@ async def custom_swagger_ui(request: Request): |
174 | 190 |
|
175 | 191 |
|
176 | 192 | mcp_app = FastAPI() |
| 193 | +mcp_app.add_middleware(McpClientIpForwardMiddleware) |
177 | 194 | # mcp server, images path |
178 | 195 | images_path = settings.MCP_IMAGE_PATH |
179 | 196 | os.makedirs(images_path, exist_ok=True) |
|
0 commit comments