feat: add system log in mcp_start

This commit is contained in:
ulleo
2026-07-13 13:55:00 +08:00
committed by ulleo
parent 8a10be0970
commit 74a0382c52
2 changed files with 44 additions and 5 deletions
@@ -127,12 +127,34 @@ class SystemLogger:
user_agent = None
if request:
# Obtain IP address
if request.client:
# Prefer real client IP headers, then fallback to socket peer IP.
header_candidates = [
"x-forwarded-for",
"x-real-ip",
"cf-connecting-ip",
"x-client-ip",
"x-forwarded",
"forwarded",
]
for key in header_candidates:
value = request.headers.get(key)
if value:
if key == "x-forwarded-for":
ip_address = value.split(",")[0].strip()
elif key == "forwarded":
# RFC 7239 format, e.g. for=203.0.113.43;proto=https;by=203.0.113.1
parts = [part.strip() for part in value.split(";")]
for part in parts:
if part.lower().startswith("for="):
ip_address = part.split("=", 1)[1].strip().strip('"')
break
else:
ip_address = value.strip()
if ip_address:
break
if not ip_address and request.client:
ip_address = request.client.host
# Attempt to obtain the real IP from X-Forwarded-For
if "x-forwarded-for" in request.headers:
ip_address = request.headers["x-forwarded-for"].split(",")[0].strip()
# Get User Agent
user_agent = request.headers.get("user-agent")
+17
View File
@@ -10,8 +10,10 @@ from fastapi.responses import JSONResponse
from fastapi.routing import APIRoute
from fastapi.staticfiles import StaticFiles
from fastapi_mcp import FastApiMCP
from starlette.datastructures import MutableHeaders
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.base import BaseHTTPMiddleware
from alembic import command
from apps.api import api_router
@@ -77,6 +79,20 @@ app = FastAPI(
redoc_url=None
)
class McpClientIpForwardMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
client_host = request.client.host if request.client else None
if client_host:
headers = MutableHeaders(scope=request.scope)
if not headers.get("x-real-ip"):
headers["x-real-ip"] = client_host
if not headers.get("x-forwarded-for"):
headers["x-forwarded-for"] = client_host
if not headers.get("x-client-ip"):
headers["x-client-ip"] = client_host
return await call_next(request)
# cache docs for different text
_openapi_cache: Dict[str, Dict[str, Any]] = {}
@@ -174,6 +190,7 @@ if settings.SQLBOT_DOC_ENABLED:
mcp_app = FastAPI()
mcp_app.add_middleware(McpClientIpForwardMiddleware)
# mcp server, images path
images_path = settings.MCP_IMAGE_PATH
os.makedirs(images_path, exist_ok=True)