|
| 1 | +import time |
| 2 | + |
| 3 | +import mcp.types as mt |
| 4 | +import structlog |
| 5 | +from fastmcp.server.dependencies import get_http_headers |
| 6 | +from fastmcp.server.middleware import CallNext, Middleware, MiddlewareContext |
| 7 | +from fastmcp.tools.base import ToolResult |
| 8 | + |
| 9 | +from flagsmith_mcp import constants |
| 10 | + |
| 11 | +logger = structlog.get_logger("mcp") |
| 12 | + |
| 13 | + |
| 14 | +def get_user_agent() -> str: |
| 15 | + return get_http_headers(include={"user-agent"}).get("user-agent", "") |
| 16 | + |
| 17 | + |
| 18 | +def get_client_name(user_agent: str) -> str: |
| 19 | + """Map a User-Agent to a known MCP client name. |
| 20 | +
|
| 21 | + The product token (the part before the first slash) identifies |
| 22 | + the client, e.g. `claude-code/2.1 (cli)` -> `claude-code`. |
| 23 | + """ |
| 24 | + name = user_agent.partition("/")[0].strip().lower() |
| 25 | + if name in constants.MCP_KNOWN_CLIENTS: |
| 26 | + return name |
| 27 | + return constants.UNKNOWN_CLIENT |
| 28 | + |
| 29 | + |
| 30 | +class EventLoggingMiddleware(Middleware): |
| 31 | + """Emit structured product events for MCP sessions and tool calls.""" |
| 32 | + |
| 33 | + async def on_initialize( |
| 34 | + self, |
| 35 | + context: MiddlewareContext[mt.InitializeRequest], |
| 36 | + call_next: CallNext[mt.InitializeRequest, mt.InitializeResult | None], |
| 37 | + ) -> mt.InitializeResult | None: |
| 38 | + result = await call_next(context) |
| 39 | + user_agent = get_user_agent() |
| 40 | + client_name = get_client_name(user_agent) |
| 41 | + if client_name == constants.UNKNOWN_CLIENT: |
| 42 | + logger.info("client.unknown", client__user_agent=user_agent) |
| 43 | + logger.info( |
| 44 | + "session.opened", |
| 45 | + client__name=client_name, |
| 46 | + client__user_agent=user_agent, |
| 47 | + ) |
| 48 | + return result |
| 49 | + |
| 50 | + async def on_call_tool( |
| 51 | + self, |
| 52 | + context: MiddlewareContext[mt.CallToolRequestParams], |
| 53 | + call_next: CallNext[mt.CallToolRequestParams, ToolResult], |
| 54 | + ) -> ToolResult: |
| 55 | + client_name = get_client_name(get_user_agent()) |
| 56 | + start = time.perf_counter() |
| 57 | + try: |
| 58 | + result = await call_next(context) |
| 59 | + except Exception: |
| 60 | + duration_ms = (time.perf_counter() - start) * 1000 |
| 61 | + logger.info( |
| 62 | + "tool.called", |
| 63 | + tool__name=context.message.name, |
| 64 | + client__name=client_name, |
| 65 | + status="error", |
| 66 | + duration_ms=duration_ms, |
| 67 | + ) |
| 68 | + logger.exception( |
| 69 | + "tool.failed", |
| 70 | + tool__name=context.message.name, |
| 71 | + client__name=client_name, |
| 72 | + status="error", |
| 73 | + duration_ms=duration_ms, |
| 74 | + ) |
| 75 | + raise |
| 76 | + logger.info( |
| 77 | + "tool.called", |
| 78 | + tool__name=context.message.name, |
| 79 | + client__name=client_name, |
| 80 | + status="success", |
| 81 | + duration_ms=(time.perf_counter() - start) * 1000, |
| 82 | + ) |
| 83 | + return result |
0 commit comments