|
| 1 | +"""Centralized Mixpanel analytics for MCP tool invocations. |
| 2 | +
|
| 3 | +Tracking is enabled only when: |
| 4 | +- BLOCKSCOUT_MIXPANEL_TOKEN is set, and |
| 5 | +- server runs in HTTP mode (set via set_http_mode(True)). |
| 6 | +
|
| 7 | +Events are emitted via Mixpanel with a deterministic distinct_id based on a |
| 8 | +connection fingerprint composed of client IP, client name, and client version. |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +import logging |
| 14 | +import uuid |
| 15 | +from typing import Any |
| 16 | + |
| 17 | +try: |
| 18 | + # Import lazily; tests will mock this |
| 19 | + from mixpanel import Consumer, Mixpanel |
| 20 | +except ImportError: # pragma: no cover |
| 21 | + |
| 22 | + class _MissingMixpanel: # noqa: D401 - simple placeholder |
| 23 | + """Placeholder that raises if Mixpanel is actually used.""" |
| 24 | + |
| 25 | + def __init__(self, *args: Any, **kwargs: Any) -> None: # noqa: D401 - simple placeholder |
| 26 | + raise ImportError("Mixpanel library is not installed. Please install 'mixpanel' to use analytics features.") |
| 27 | + |
| 28 | + Consumer = _MissingMixpanel # type: ignore[assignment] |
| 29 | + Mixpanel = _MissingMixpanel # type: ignore[assignment] |
| 30 | + |
| 31 | +from blockscout_mcp_server.client_meta import ( |
| 32 | + ClientMeta, |
| 33 | + extract_client_meta_from_ctx, |
| 34 | + get_header_case_insensitive, |
| 35 | +) |
| 36 | +from blockscout_mcp_server.config import config |
| 37 | + |
| 38 | +logger = logging.getLogger(__name__) |
| 39 | + |
| 40 | + |
| 41 | +_is_http_mode_enabled: bool = False |
| 42 | +_mp_client: Any | None = None |
| 43 | + |
| 44 | + |
| 45 | +def set_http_mode(is_http: bool) -> None: |
| 46 | + """Enable or disable HTTP mode for analytics gating.""" |
| 47 | + global _is_http_mode_enabled |
| 48 | + _is_http_mode_enabled = bool(is_http) |
| 49 | + # Log enablement status once at startup (HTTP path only) |
| 50 | + if _is_http_mode_enabled: |
| 51 | + token = getattr(config, "mixpanel_token", "") |
| 52 | + if token: |
| 53 | + # Best-effort initialize client to validate configuration |
| 54 | + _ = _get_mixpanel_client() |
| 55 | + api_host = getattr(config, "mixpanel_api_host", "") or "default" |
| 56 | + logger.info("Mixpanel analytics enabled (api_host=%s)", api_host) |
| 57 | + else: |
| 58 | + logger.debug("Mixpanel analytics not enabled: BLOCKSCOUT_MIXPANEL_TOKEN is not set") |
| 59 | + |
| 60 | + |
| 61 | +def _get_mixpanel_client() -> Any | None: |
| 62 | + """Return a singleton Mixpanel client if token is configured.""" |
| 63 | + global _mp_client |
| 64 | + if _mp_client is not None: |
| 65 | + return _mp_client |
| 66 | + token = getattr(config, "mixpanel_token", "") |
| 67 | + if not token: |
| 68 | + return None |
| 69 | + try: |
| 70 | + api_host = getattr(config, "mixpanel_api_host", "") |
| 71 | + if api_host: |
| 72 | + consumer = Consumer(api_host=api_host) |
| 73 | + _mp_client = Mixpanel(token, consumer=consumer) |
| 74 | + else: |
| 75 | + _mp_client = Mixpanel(token) |
| 76 | + return _mp_client |
| 77 | + except Exception as exc: # pragma: no cover - defensive |
| 78 | + logger.debug("Failed to initialize Mixpanel client: %s", exc) |
| 79 | + return None |
| 80 | + |
| 81 | + |
| 82 | +def _extract_request_ip(ctx: Any) -> str: |
| 83 | + """Extract client IP address from context if possible.""" |
| 84 | + ip = "" |
| 85 | + try: |
| 86 | + request = getattr(getattr(ctx, "request_context", None), "request", None) |
| 87 | + if request is not None: |
| 88 | + headers = request.headers or {} |
| 89 | + # Prefer proxy-forwarded headers |
| 90 | + xff = get_header_case_insensitive(headers, "x-forwarded-for", "") or "" |
| 91 | + if xff: |
| 92 | + # left-most IP per standard |
| 93 | + ip = xff.split(",")[0].strip() |
| 94 | + else: |
| 95 | + x_real_ip = get_header_case_insensitive(headers, "x-real-ip", "") or "" |
| 96 | + if x_real_ip: |
| 97 | + ip = x_real_ip |
| 98 | + else: |
| 99 | + client = getattr(request, "client", None) |
| 100 | + if client and getattr(client, "host", None): |
| 101 | + ip = client.host |
| 102 | + except Exception: # pragma: no cover - tolerate all shapes |
| 103 | + pass |
| 104 | + return ip |
| 105 | + |
| 106 | + |
| 107 | +def _build_distinct_id(ip: str, client_name: str, client_version: str) -> str: |
| 108 | + # User-Agent is merged into client_name in extract_client_meta_from_ctx when name is unavailable. |
| 109 | + # Therefore composite requires only ip, client_name and client_version for a stable fingerprint. |
| 110 | + composite = "|".join([ip or "", client_name or "", client_version or ""]) |
| 111 | + return str(uuid.uuid5(uuid.NAMESPACE_URL, "https://blockscout.com/mcp/" + composite)) |
| 112 | + |
| 113 | + |
| 114 | +def _determine_call_source(ctx: Any) -> str: |
| 115 | + """Return 'mcp' for MCP calls, 'rest' for REST API, else 'unknown'. |
| 116 | +
|
| 117 | + Priority: |
| 118 | + 1) Explicit marker set by caller (e.g., REST mock context) via `call_source`. |
| 119 | + 2) Default to 'mcp' when no explicit marker is present (applies to MCP-over-HTTP). |
| 120 | + """ |
| 121 | + try: |
| 122 | + explicit = getattr(ctx, "call_source", None) |
| 123 | + if isinstance(explicit, str) and explicit: |
| 124 | + return explicit |
| 125 | + # No explicit marker: treat as MCP (covers MCP-over-HTTP) |
| 126 | + return "mcp" |
| 127 | + except Exception: # pragma: no cover |
| 128 | + pass |
| 129 | + return "unknown" |
| 130 | + |
| 131 | + |
| 132 | +def track_tool_invocation( |
| 133 | + ctx: Any, |
| 134 | + tool_name: str, |
| 135 | + tool_args: dict[str, Any], |
| 136 | + client_meta: ClientMeta | None = None, |
| 137 | +) -> None: |
| 138 | + """Track a tool invocation in Mixpanel, if enabled and in HTTP mode.""" |
| 139 | + if not _is_http_mode_enabled: |
| 140 | + return |
| 141 | + mp = _get_mixpanel_client() |
| 142 | + if mp is None: |
| 143 | + return |
| 144 | + |
| 145 | + try: |
| 146 | + ip = _extract_request_ip(ctx) |
| 147 | + |
| 148 | + # Prefer provided client metadata from the decorator; otherwise, fall back to context |
| 149 | + if client_meta is not None: |
| 150 | + client_name = client_meta.name |
| 151 | + client_version = client_meta.version |
| 152 | + protocol_version = client_meta.protocol |
| 153 | + user_agent = client_meta.user_agent |
| 154 | + else: |
| 155 | + meta = extract_client_meta_from_ctx(ctx) |
| 156 | + client_name = meta.name |
| 157 | + client_version = meta.version |
| 158 | + protocol_version = meta.protocol |
| 159 | + user_agent = meta.user_agent |
| 160 | + |
| 161 | + distinct_id = _build_distinct_id(ip, client_name, client_version) |
| 162 | + |
| 163 | + properties: dict[str, Any] = { |
| 164 | + "ip": ip, |
| 165 | + "client_name": client_name, |
| 166 | + "client_version": client_version, |
| 167 | + "user_agent": user_agent, |
| 168 | + "tool_args": tool_args, |
| 169 | + "protocol_version": protocol_version, |
| 170 | + "source": _determine_call_source(ctx), |
| 171 | + } |
| 172 | + |
| 173 | + # TODO: Remove this log after validating Mixpanel analytics end-to-end |
| 174 | + logger.info( |
| 175 | + "Mixpanel event prepared: distinct_id=%s tool=%s properties=%s", |
| 176 | + distinct_id, |
| 177 | + tool_name, |
| 178 | + properties, |
| 179 | + ) |
| 180 | + |
| 181 | + meta = {"ip": ip} if ip else None |
| 182 | + # Mixpanel Python SDK allows meta for IP geolocation mapping |
| 183 | + if meta is not None: |
| 184 | + mp.track(distinct_id, tool_name, properties, meta=meta) # type: ignore[call-arg] |
| 185 | + else: |
| 186 | + mp.track(distinct_id, tool_name, properties) |
| 187 | + except Exception as exc: # pragma: no cover - do not break tool flow |
| 188 | + logger.debug("Mixpanel tracking failed for %s: %s", tool_name, exc) |
0 commit comments