**Scope:** Expose the existing compliance knowledge base as a standalone Model Context Protocol (MCP) server module, mounted into the existing FastAPI backend, so external MCP clients (Claude Desktop, GitHub Copilot, Cursor, etc.) can call a single `search_regulations` tool over the network.
**Relationship to existing roadmap:** This is the first half ("Direction A" — expose our data) of the MCP integration opportunity identified during the 2026-07-29 brainstorming session. "Direction B" (consuming external MCP servers, e.g. for US/UK regulatory data) was researched and explicitly rejected for this iteration — no existing open-source regulation MCP server covers this platform's actual sources (国标委/GB standards, CATARC, EUR-Lex); the closest match (`lamcearber-spec/eu-legal-mcp`) is a 0-star, month-old project that only duplicates EUR-Lex data this platform already crawls itself. Direction B is deferred until a concrete need for a jurisdiction this platform doesn't already cover arises.
---
## Goals
1. Expose exactly one MCP tool, `search_regulations`, backed by the **existing**`AgentConversationService.ask()` application service (`backend/app/application/agent/services.py`) — the same code path already used by the `/api/v1/agent/ask` REST endpoint. Zero new retrieval/answering logic.
2. Package the MCP server as its own self-contained module (`backend/app/mcp/`), then mount it into the existing FastAPI app (`backend/app/api/main.py`) so it ships with the current deployment — no new process, no new deployment pipeline.
3. Use the Streamable HTTP transport (not stdio) — the backend is deployed remotely (6.86.80.9), so external MCP clients must connect over the network, not via a locally-spawned subprocess.
4. Reuse the existing JWT auth mechanism — no new auth system. Any authenticated user (any of the four roles) may call `search_regulations`, matching the existing `/agent/ask` endpoint's access level and the `UserRole` docstring ("knowledge query" is available to all four roles including `READONLY`).
## Non-Goals
- Direction B (this platform's agent consuming external MCP servers) — deferred, see rejection rationale above.
- Additional tools beyond `search_regulations` (e.g. perception event queries, compliance checks) — explicit user decision to ship the minimal viable version first.
- Role-based restriction of the tool (e.g. ADMIN-only) — all four roles already have knowledge-query access per the existing RBAC model; no new restriction needed.
- stdio transport / local-only usage — not useful for a remotely-deployed backend.
- Rate limiting or per-client quotas on the MCP endpoint — no existing precedent in this codebase for any endpoint; out of scope until a concrete abuse case appears.
> **Implementation note (post-design correction):** the `mcp` PyPI package released version `2.0.0` shortly before implementation and renamed the `FastMCP` class referenced below to `MCPServer` (import path `mcp.server.MCPServer` instead of `mcp.server.fastmcp.FastMCP`). The `.tool()` / `.streamable_http_app()` API surface used throughout this doc is otherwise unchanged. `backend/app/mcp/server.py` uses the actual shipped `MCPServer` name — treat every `FastMCP` mention below as that rename. Two other corrections discovered during implementation: (1) `MCPServer.streamable_http_app()` registers its own internal route at a fixed `/mcp` path, so mounting it at `/mcp` in `api/main.py` would double the path to `/mcp/mcp` — fixed by calling `mcp.streamable_http_app(streamable_http_path="/")`; (2) the effective external URL for clients is `/mcp/` (**with** a trailing slash) — Starlette's `Mount` 307-redirects the bare `/mcp` to `/mcp/`, which most HTTP clients follow automatically, but it is more robust to configure clients with the trailing slash directly.
This sits as a new top-level package alongside `app/api/`, `app/application/`, `app/services/`, `app/shared/` — not nested inside `app/api/routes/`, because MCP tool registration (decorator-based schema binding) and its own sub-ASGI-app are a fundamentally different transport mechanism from the FastAPI `APIRouter` REST routes there. Keeping it as its own top-level module satisfies "list MCP as its own module" and keeps the REST route directory free of non-REST concerns.
`server.py` contains **zero new business logic** — it is a protocol adapter that calls the existing composition root (`app.shared.bootstrap.get_agent_conversation_service()`), the same function `backend/app/api/routes/agent.py` already calls. This is consistent with the architecture rule that new business orchestration belongs in `application/`, not scattered across transport adapters — there is no new orchestration here at all.
Calling `ask()`**without**`session_id` is intentional: it skips all `ConversationStore` reads/writes (see `AgentConversationService.ask()` — history/session logic is only engaged when `session_id` is passed), so each MCP tool call is stateless and side-effect-free, matching the "search" semantics (not a multi-turn chat).
### Transport & mounting
```python
# backend/app/mcp/server.py (continued)
defbuild_mcp_asgi_app():
"""Return the mounted MCP ASGI app (Streamable HTTP transport)."""
This is the one non-obvious infrastructure detail in this design: naively mounting `mcp.streamable_http_app()` via `app.mount()` without wiring its lifespan results in tool calls failing at runtime because the MCP session manager was never started — this is not a hypothetical, it is a confirmed, documented limitation of nested ASGI apps. Using stdlib `AsyncExitStack` inside the **existing**`lifespan()` function avoids adding any new dependency to solve it.
### Auth
The `/mcp` mount point is protected by a small ASGI middleware (not a FastAPI `Depends`, since the mounted app is not a `FastAPI`/`APIRouter` instance) that:
1. Reads the `Authorization: Bearer <token>` header from the incoming ASGI scope.
2. When `settings.auth_enabled` is `False` (dev mode) — passes through unchanged, matching the existing `get_current_user` dev bypass behavior.
3. When `settings.auth_enabled` is `True` — validates the token via the **existing**`get_jwt_handler().decode_token(token)` (`backend/app/infrastructure/auth/jwt_handler.py`). On `ValueError` (expired/invalid/missing), returns an HTTP 401 before the request ever reaches the MCP protocol handler. On success, the request proceeds — no role check, since all roles already have knowledge-query access.
**Operational consequence:** to connect an external MCP client (Claude Desktop, Copilot, etc.) to this server, the user must configure a static bearer token (a JWT obtained via the existing `/api/v1/auth/login` flow) in that client's MCP server config, e.g.:
JWTs expire after `expire_minutes` (480 by default, see `JWTHandler`) — long-lived external tool connections will need a token refresh story, but that is an existing limitation of the JWT scheme generally (not new to MCP), so it is not addressed differently here.
---
## Error Handling
- **Auth failure** (missing/expired/invalid token, when `auth_enabled=True`): HTTP 401 from `MCPAuthMiddleware`, before the MCP protocol layer is invoked at all.
- **Tool execution failure** (e.g. the underlying retrieval/LLM call raises): FastMCP's own tool-call error handling catches exceptions raised inside `@mcp.tool()`-decorated functions and returns them as a normal MCP tool-error result to the calling client — no special handling needed in `search_regulations` itself, consistent with how `/agent/ask`'s REST handler already lets the global FastAPI exception handler in `main.py` catch unexpected errors.
- **Lifespan startup failure** (e.g. `mcp_app`'s session manager fails to start): surfaces the same way any other `lifespan()` failure does today — the app fails to start, visible immediately in logs, not a silent partial-degradation.
## Testing
-`backend/tests/mcp/test_search_regulations_tool.py` — unit test for the tool function with a mocked `AgentConversationService` (same mocking style as existing `application/agent` tests): asserts `search_regulations()` calls `.ask(query=..., top_k=...)` with no `session_id`, and shapes the returned dict correctly (`answer`, `sources`).
-`backend/tests/mcp/test_mcp_auth_middleware.py` — unit test for `MCPAuthMiddleware`: no token → 401; invalid/expired token → 401; valid token → request passed through to the wrapped app; `auth_enabled=False` → always passed through. Uses Starlette's `TestClient` against a minimal dummy inner ASGI app, no real MCP protocol handshake needed.
- **Manual end-to-end verification** (not automated): use the official `mcp` Python client (`mcp.client.streamable_http.streamablehttp_client` + `mcp.ClientSession`) to connect to a locally running instance, call `list_tools()`, then call `search_regulations` with a real query, confirming a real answer + sources come back. This is a one-time manual check, not a CI test — full MCP protocol handshake testing would require standing up the `mcp` client SDK as a test dependency for marginal additional confidence beyond the two unit tests above.
## Dependencies
- Add `mcp` (official Model Context Protocol Python SDK, provides `mcp.server.fastmcp.FastMCP`) to `backend/requirements.txt`. No existing dependency implements the MCP protocol (JSON-RPC 2.0 framing + Streamable HTTP transport + capability negotiation); hand-rolling this would be substantially more code and more fragile than the official SDK.
## Out of Scope (deferred to future iterations)
- Direction B: consuming external MCP servers from this platform's own Agentic RAG pipeline.