feat(mcp): send PostHog MCP Analytics events from the hosted server

Merged
RI
3d ago
+367-12

Summary

Adds PostHog MCP Analytics to the hosted MCP server (api.capgo.app/mcp), including compare tool quality by model.

The hosted server dispatches JSON-RPC itself on Workers, so instead of @posthog/mcp it sends the documented $mcp_tool_call event shape through the existing PostHog capture path. PostHog's dashboards key on $mcp_source, not on the sending library.

  • New mcp/analytics.ts: builds $mcp_tool_call with the required properties ($mcp_source, $mcp_tool_name, $mcp_is_error, $mcp_duration_ms, $session_id, $mcp_server_name), plus client name/version (from modern clientInfo metadata, otherwise the OAuth client), protocol version, user agent, x-anthropic-client, and a low-cardinality $mcp_error_type/$mcp_error_status. Names that match no tool are reported as unknown. Error messages, parameters and responses are never sent.
  • Model capture: like the SDK, every tool now advertises an optional llm_model string argument. The argument is stripped before validation, so tools never see it. Codex turn metadata (x-codex-turn-metadata.model) takes precedence (client_metadata); unknown and blank values are dropped. These values are unverified, so they're only used for analytics.
  • Sessions: the server is stateless, so each HTTP request gets a fresh ses_<UUIDv7>, as PostHog's manual contract specifies for per-request HTTP. Sessions are never grouped by credential.
  • Delivery: the existing Hosted MCP Tool Invoked event still goes out per call through trackPosthogEvent. The $mcp_tool_call events of one request share one /batch/ request. Both are sent in the background.

Test plan

  • New tests/mcp-analytics.unit.test.ts: schema injection, argument stripping (spies on the tool schema; fails without the strip), model resolution precedence, event shape, error classification, unknown tool bucketing, UUIDv7 session ids
  • tests/mcp-hosted-analytics.unit.test.ts covers both events through the HTTP route
  • Existing MCP unit suites pass
  • oxlint supabase, tsc --project tsconfig.backend.json clean

No UI change.

🤖 Generated with Claude Code