feat: add MCP server module exposing search_regulations tool
- New backend/app/mcp/ module: MCPServer instance with a single search_regulations tool backed by the existing AgentConversationService. - MCPAuthMiddleware reuses existing JWT auth (no new auth mechanism). - Mounted at /mcp/ in api/main.py via Streamable HTTP transport; wired the MCP session manager into the existing lifespan() via AsyncExitStack (app.mount() does not propagate nested ASGI lifespans automatically). - Fixed a doubled /mcp/mcp path by setting streamable_http_path to "/" (MCPServer.streamable_http_app() defaults to registering its own /mcp route). - Verified end-to-end with the real mcp Python client: list_tools() returns search_regulations, auth correctly 401s without or with an invalid token. - 7 new tests, 76 total (up from 69), all passing. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
+23
-8
@@ -1,6 +1,6 @@
|
||||
"""FastAPI application entrypoint."""
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from contextlib import AsyncExitStack, asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
@@ -13,6 +13,7 @@ from app.api.models import ErrorResponse
|
||||
from app.api.routes import api_router
|
||||
from app.config.logging import setup_logging
|
||||
from app.config.settings import settings
|
||||
from app.mcp.server import build_mcp_asgi_app
|
||||
from app.shared.bootstrap import cleanup_runtime_dependencies, preload_runtime_dependencies
|
||||
from app.shared.errors import VectorStoreSchemaError
|
||||
# Keep module behavior explicit so the backend flow stays easy to audit.
|
||||
@@ -20,19 +21,32 @@ from app.shared.errors import VectorStoreSchemaError
|
||||
|
||||
setup_logging(level="INFO" if not settings.debug else "DEBUG")
|
||||
|
||||
# Built once at module scope so both lifespan() and app.mount() below reference
|
||||
# the same instance — mounting a second, separately-built instance would start
|
||||
# a second, unrelated MCP session manager.
|
||||
mcp_app = build_mcp_asgi_app()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Application lifecycle hooks."""
|
||||
logger.info(f"启动 {settings.app_name} v{settings.app_version}")
|
||||
logger.info(f"调试模式: {settings.debug}")
|
||||
logger.info("预加载LLM客户端...")
|
||||
preload_runtime_dependencies()
|
||||
# FastMCP-style servers own a session manager that only starts via its own
|
||||
# lifespan context. app.mount() does NOT propagate nested ASGI lifespans
|
||||
# automatically (confirmed Starlette/ASGI limitation) — without this,
|
||||
# every search_regulations call would fail because the MCP session
|
||||
# manager was never started.
|
||||
async with AsyncExitStack() as stack:
|
||||
await stack.enter_async_context(mcp_app.router.lifespan_context(mcp_app))
|
||||
|
||||
yield
|
||||
logger.info(f"启动 {settings.app_name} v{settings.app_version}")
|
||||
logger.info(f"调试模式: {settings.debug}")
|
||||
logger.info("预加载LLM客户端...")
|
||||
preload_runtime_dependencies()
|
||||
|
||||
logger.info("应用关闭,执行清理...")
|
||||
cleanup_runtime_dependencies()
|
||||
yield
|
||||
|
||||
logger.info("应用关闭,执行清理...")
|
||||
cleanup_runtime_dependencies()
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
@@ -65,6 +79,7 @@ app.add_middleware(
|
||||
app.add_middleware(AuditMiddleware)
|
||||
|
||||
app.include_router(api_router, prefix="/api/v1")
|
||||
app.mount("/mcp", mcp_app)
|
||||
|
||||
|
||||
@app.exception_handler(VectorStoreSchemaError)
|
||||
|
||||
Reference in New Issue
Block a user