:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(mcp): add more metrics (#59615)
Joshua Snyder162439762a5c
diff --git a/services/mcp/src/hono/cache/RedisCache.ts b/services/mcp/src/hono/cache/RedisCache.tsindex ef2c21e54fae..964e4b6da318 100644--- a/services/mcp/src/hono/cache/RedisCache.ts+++ b/services/mcp/src/hono/cache/RedisCache.ts@@ -1,5 +1,7 @@import { ScopedCache } from '@/lib/cache/ScopedCache'+import { redisOperationsTotal } from '../metrics'+export interface RedisLike {get(key: string): Promise<string | null>set(key: string, value: string, ...args: (string | number)[]): Promise<string | null>@@ -9,9 +11,6 @@ export interface RedisLike {}const DEFAULT_TTL_SECONDS = 7 * 24 * 60 * 60 // 7 days-// Cap on clear()'s SCAN/UNLINK pass. A user with more than this many cache-// entries either deserves an explicit GC pass or is misbehaving — either way-// we don't want a single request to stall on an unbounded loop.const CLEAR_MAX_ITERATIONS = 50const CLEAR_SCAN_COUNT = 100@@ -31,16 +30,30 @@ export class RedisCache<T extends Record<string, any>> extends ScopedCache<T> {async get<K extends keyof T>(key: K): Promise<T[K] | undefined> {const scopedKey = this.getScopedKey(key as string)- const raw = await this.redis.get(scopedKey)- if (raw === null) {- return undefined+ try {+ const raw = await this.redis.get(scopedKey)+ if (raw === null) {+ redisOperationsTotal.inc({ operation: 'get', status: 'success' })+ return undefined+ }+ const result = JSON.parse(raw) as T[K]+ redisOperationsTotal.inc({ operation: 'get', status: 'success' })+ return result+ } catch (error) {+ redisOperationsTotal.inc({ operation: 'get', status: 'error' })+ throw error}- return JSON.parse(raw) as T[K]}async set<K extends keyof T>(key: K, value: T[K]): Promise<void> {const scopedKey = this.getScopedKey(key as string)- await this.redis.set(scopedKey, JSON.stringify(value), 'EX', this.ttl)+ try {+ await this.redis.set(scopedKey, JSON.stringify(value), 'EX', this.ttl)+ redisOperationsTotal.inc({ operation: 'set', status: 'success' })+ } catch (error) {+ redisOperationsTotal.inc({ operation: 'set', status: 'error' })+ throw error+ }}async delete<K extends keyof T>(key: K): Promise<void> {@@ -51,10 +64,6 @@ export class RedisCache<T extends Record<string, any>> extends ScopedCache<T> {async clear(): Promise<void> {const pattern = `mcp:user:${this.scope}:*`let cursor = '0'- // UNLINK lets Redis free memory in a background thread; falls back to DEL- // for clients that don't expose it. Iteration cap is a guard against- // pathological scans on outlier accounts — a partial clear is acceptable- // (the remaining entries will TTL-evict).const unlink = this.redis.unlink?.bind(this.redis) ?? this.redis.del.bind(this.redis)for (let i = 0; i < CLEAR_MAX_ITERATIONS; i += 1) {const [nextCursor, keys] = await this.redis.scan(cursor, 'MATCH', pattern, 'COUNT', CLEAR_SCAN_COUNT)diff --git a/services/mcp/src/hono/dispatcher.ts b/services/mcp/src/hono/dispatcher.tsindex 86a29d7ff9af..5f1cc5e11aea 100644--- a/services/mcp/src/hono/dispatcher.ts+++ b/services/mcp/src/hono/dispatcher.ts@@ -20,15 +20,14 @@ import type {import type { RequestProperties } from '@/lib/request-properties'+import { trackInitEvent } from './analytics'import type { RedisLike } from './cache/RedisCache'import { getEnv } from './constants'-import { initDurationSeconds } from './metrics'-import { ToolCatalog } from './tool-catalog'--import { trackInitEvent } from './analytics'import { InstructionsBuilder } from './instructions'+import { initDurationSeconds, initTotal } from './metrics'import { RequestStateResolver, type ResolvedState } from './request-state-resolver'import { ResourceCatalog } from './resource-catalog'+import { ToolCatalog } from './tool-catalog'import { ToolExecutor } from './tool-executor'export { McpDispatcher }@@ -69,11 +68,20 @@ const Method = {const TRACKED_METHODS: Set<string> = new Set([Method.Initialize, Method.ToolsList, Method.ToolsCall])function isRequest(msg: JSONRPCMessage): msg is JSONRPCRequest {- return typeof msg === 'object' && msg !== null && 'id' in msg && typeof (msg as { method?: unknown }).method === 'string'+ return (+ typeof msg === 'object' &&+ msg !== null &&+ 'id' in msg &&+ typeof (msg as { method?: unknown }).method === 'string'+ )}type JsonRpcResultResponse = { jsonrpc: typeof JSONRPC_VERSION; id: number | string; result: unknown }-type JsonRpcErrorResponse = { jsonrpc: typeof JSONRPC_VERSION; id: number | string; error: { code: number; message: string } }+type JsonRpcErrorResponse = {+ jsonrpc: typeof JSONRPC_VERSION+ id: number | string+ error: { code: number; message: string }+}type JsonRpcResponse = JsonRpcResultResponse | JsonRpcErrorResponsefunction jsonRpcResult(id: number | string, result: unknown): JsonRpcResultResponse {@@ -85,10 +93,10 @@ function jsonRpcMethodError(id: number | string, code: number, message: string):}function jsonRpcErrorResponse(id: unknown, code: number, message: string): Response {- return new Response(- JSON.stringify({ jsonrpc: JSONRPC_VERSION, id: id ?? null, error: { code, message } }),- { status: 200, headers: { 'Content-Type': 'application/json' } }- )+ return new Response(JSON.stringify({ jsonrpc: JSONRPC_VERSION, id: id ?? null, error: { code, message } }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' },+ })}class McpDispatcher {@@ -201,26 +209,32 @@ class McpDispatcher {props: RequestProperties,state: ResolvedState): Promise<InitializeResult> {- const requestedVersion = (params?.protocolVersion as string) ?? LATEST_PROTOCOL_VERSION- const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)- ? requestedVersion- : LATEST_PROTOCOL_VERSION-- const instructions = await this.instructionsBuilder.build(props, state)-- initDurationSeconds.observe(props.requestStartTime ? (Date.now() - props.requestStartTime) / 1000 : 0)-- void trackInitEvent(props, state)-- return {- protocolVersion,- capabilities: {- tools: { listChanged: false },- resources: { listChanged: false },- prompts: { listChanged: false },- },- serverInfo: { name: 'PostHog', version: '1.0.0' },- ...(instructions ? { instructions } : {}),+ try {+ const requestedVersion = (params?.protocolVersion as string) ?? LATEST_PROTOCOL_VERSION+ const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)+ ? requestedVersion+ : LATEST_PROTOCOL_VERSION++ const instructions = await this.instructionsBuilder.build(props, state)++ initDurationSeconds.observe(props.requestStartTime ? (Date.now() - props.requestStartTime) / 1000 : 0)+ initTotal.inc({ status: 'success' })++ void trackInitEvent(props, state)++ return {+ protocolVersion,+ capabilities: {+ tools: { listChanged: false },+ resources: { listChanged: false },+ prompts: { listChanged: false },+ },+ serverInfo: { name: 'PostHog', version: '1.0.0' },+ ...(instructions ? { instructions } : {}),+ }+ } catch (error) {+ initTotal.inc({ status: 'error' })+ throw error}}}diff --git a/services/mcp/src/hono/index.ts b/services/mcp/src/hono/index.tsindex bfe697fc4a8e..d06769f95b71 100644--- a/services/mcp/src/hono/index.ts+++ b/services/mcp/src/hono/index.ts@@ -2,6 +2,7 @@ import { serve } from '@hono/node-server'import Redis from 'ioredis'import { createApp } from './app'+import { redisOperationsTotal } from './metrics'import { registerShutdownHandlers } from './shutdown'const PORT = parseInt(process.env.PORT || '3001', 10)@@ -33,10 +34,12 @@ const redis = new Redis(resolveRedisUrl(), {redis.on('error', (err: Error) => {console.error('[MCP] Redis connection error:', err.message)+ redisOperationsTotal.inc({ operation: 'connect', status: 'error' })})redis.on('connect', () => {console.info('[MCP] Redis connected')+ redisOperationsTotal.inc({ operation: 'connect', status: 'success' })})async function main(): Promise<void> {diff --git a/services/mcp/src/hono/metrics.ts b/services/mcp/src/hono/metrics.tsindex 3bfef969a609..913b5f74f0df 100644--- a/services/mcp/src/hono/metrics.ts+++ b/services/mcp/src/hono/metrics.ts@@ -1,15 +1,7 @@-// Prometheus instrumentation for the Hono runtime. CF Workers can't host a-// scrape endpoint, so this lives Hono-side only. Metrics are registered on-// `prom-client`'s default registry (singleton) — the long-lived Node process-// is what makes that pattern fit; CF's per-request isolation does not.import { collectDefaultMetrics, Counter, Gauge, Histogram, register } from 'prom-client'-// Default process-level metrics: heap, GC, event-loop lag, file descriptors, etc.collectDefaultMetrics({ prefix: 'mcp_' })-// HTTP request volume by route + status. Path is normalized to a small set of-// known prefixes so cardinality stays bounded — raw URLs would blow up the-// metric (UI-app static asset paths, well-known per-resource paths).export const httpRequestsTotal = new Counter({name: 'mcp_http_requests_total',help: 'HTTP requests received by the Hono MCP server.',@@ -20,12 +12,9 @@ export const httpRequestDurationSeconds = new Histogram({name: 'mcp_http_request_duration_seconds',help: 'HTTP request duration by route.',labelNames: ['method', 'route', 'status'] as const,- // Wide range: health checks land in the 1ms bucket, tool calls in 100ms-10s.- buckets: [0.005, 0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30],+ buckets: [0.005, 0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120, 300],})-// MCP tool dispatch outcomes. `status` is `success` | `error` | `validation_error`.-// Cardinality on `tool` is bounded by the registered tool catalog.export const toolCallsTotal = new Counter({name: 'mcp_tool_calls_total',help: 'MCP tool dispatches.',@@ -36,27 +25,50 @@ export const toolCallDurationSeconds = new Histogram({name: 'mcp_tool_call_duration_seconds',help: 'MCP tool dispatch duration.',labelNames: ['tool', 'status'] as const,- buckets: [0.01, 0.05, 0.1, 0.5, 1, 2, 5, 10, 30, 60],+ buckets: [0.01, 0.05, 0.1, 0.5, 1, 2, 5, 10, 30, 60, 120, 300],})-// HonoMcpServer.init() — fans out to PostHog API + flag eval + cache reads on-// every cold session. Slow tail here is the single biggest cold-start signal.export const initDurationSeconds = new Histogram({name: 'mcp_init_duration_seconds',- help: 'HonoMcpServer.init() duration (cold-start cost per new session).',+ help: 'Session init duration (cold-start cost per new session).',buckets: [0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10],})-// 0 normally, flips to 1 the moment SIGTERM lands. Useful in dashboards to-// align deploy windows with traffic dips and to confirm the readiness flip-// actually fired before pods went away.export const shuttingDown = new Gauge({name: 'mcp_shutting_down',help: 'Set to 1 when the pod is draining for shutdown.',})-// Map a request URL to a low-cardinality label. Anything not matched falls-// into `other` so a pathological client can't fan out the histogram series.+export const initTotal = new Counter({+ name: 'mcp_init_total',+ help: 'MCP session init outcomes.',+ labelNames: ['status'] as const,+})++export const inflightRequests = new Gauge({+ name: 'mcp_inflight_requests',+ help: 'Number of in-flight HTTP requests.',+ labelNames: ['route'] as const,+})++export const toolErrorsTotal = new Counter({+ name: 'mcp_tool_errors_total',+ help: 'MCP tool errors by category.',+ labelNames: ['tool', 'error_type'] as const,+})++export const redisOperationsTotal = new Counter({+ name: 'mcp_redis_operations_total',+ help: 'Redis cache and connection operations by outcome.',+ labelNames: ['operation', 'status'] as const,+})++export const authFailuresTotal = new Counter({+ name: 'mcp_auth_failures_total',+ help: 'Authentication failures on /mcp requests.',+ labelNames: ['reason'] as const,+})+export function routeLabel(pathname: string): string {if (pathname === '/mcp' || pathname.startsWith('/mcp/')) {return '/mcp'diff --git a/services/mcp/src/hono/middleware.ts b/services/mcp/src/hono/middleware.tsindex 5882d124a585..dbcb7d06ebd4 100644--- a/services/mcp/src/hono/middleware.ts+++ b/services/mcp/src/hono/middleware.ts@@ -1,6 +1,6 @@import { type MiddlewareHandler } from 'hono'-import { httpRequestDurationSeconds, httpRequestsTotal, routeLabel } from './metrics'+import { httpRequestDurationSeconds, httpRequestsTotal, inflightRequests, routeLabel } from './metrics'export const securityHeaders: MiddlewareHandler = async (c, next) => {await next()@@ -16,9 +16,14 @@ export const httpMetrics: MiddlewareHandler = async (c, next) => {}const route = routeLabel(url.pathname)const method = c.req.method+ inflightRequests.inc({ route })const stop = httpRequestDurationSeconds.startTimer({ method, route })- await next()- const status = String(c.res.status)- httpRequestsTotal.inc({ method, route, status })- stop({ method, route, status })+ try {+ await next()+ } finally {+ const status = String(c.res.status)+ httpRequestsTotal.inc({ method, route, status })+ stop({ method, route, status })+ inflightRequests.dec({ route })+ }}diff --git a/services/mcp/src/hono/request-utils.ts b/services/mcp/src/hono/request-utils.tsindex 3ec4af67bb33..ffe3b67501d6 100644--- a/services/mcp/src/hono/request-utils.ts+++ b/services/mcp/src/hono/request-utils.ts@@ -11,6 +11,7 @@ import {import { getRegionFromRequest } from '@/lib/routing'import { sanitizeHeaderValue } from '@/lib/utils'+import { authFailuresTotal } from './metrics'import type { HonoCtx } from './types'const InitializeParamsSchema = z.object({@@ -53,7 +54,12 @@ function parseClientInfo(bodyText: string): ClientInfo {function authenticate(c: HonoCtx): Response | null {const token = c.req.header('Authorization')?.split(' ')[1]- return validateBearerToken(token, c.req.raw, getRegionFromRequest(c.req.raw))+ const error = validateBearerToken(token, c.req.raw, getRegionFromRequest(c.req.raw))+ if (error) {+ const reason = !token ? 'missing_token' : 'invalid_token'+ authFailuresTotal.inc({ reason })+ }+ return error}async function preserveBody(c: HonoCtx): Promise<string> {@@ -89,6 +95,8 @@ export function handleCatchError(error: unknown, props: RequestProperties): Respconsole.error('[handleCatchError]', error)const authResponse = mapErrorToAuthResponse(error)if (authResponse) {+ const reason = authResponse.status === 403 ? 'insufficient_scope' : 'invalid_token'+ authFailuresTotal.inc({ reason })return authResponse}try {diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 8a7683475454..f486b6ea4164 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -1,7 +1,15 @@import type { ListToolsResult } from '@modelcontextprotocol/sdk/types.js'import { buildToolResultPayload, isToolCallPayload } from '@/lib/build-tool-result'-import { handleToolError } from '@/lib/errors'+import {+ handleToolError,+ MissingOrganizationContextError,+ MissingProjectContextError,+ PostHogApiError,+ PostHogValidationError,+ findPostHogPermissionError,+ findRecoverableApiError,+} from '@/lib/errors'import { AnalyticsEvent } from '@/lib/posthog/analytics'import type { RequestProperties } from '@/lib/request-properties'import { createExecTool, type ExecInnerCallTracker } from '@/tools/exec'@@ -9,7 +17,7 @@ import type { Context, ZodObjectAny } from '@/tools/types'import { trackToolCall } from './analytics'import type { InstructionsBuilder } from './instructions'-import { toolCallDurationSeconds, toolCallsTotal } from './metrics'+import { toolCallDurationSeconds, toolCallsTotal, toolErrorsTotal } from './metrics'import type { ResolvedState } from './request-state-resolver'import type { ToolCatalog } from './tool-catalog'@@ -140,6 +148,8 @@ export class ToolExecutor {toolCallsTotal.inc({ tool: tool.name, status: 'error' })stop({ status: 'error' })+ classifyToolError(error, tool.name)+void trackToolCall(tool.name, Date.now() - startMs, true, props, state)const sessionUuid = await state.reqCtx.getSessionUuid(props.sessionId)@@ -181,3 +191,24 @@ export class ToolExecutor {}}}++function classifyToolError(error: unknown, toolName: string): void {+ if (error instanceof MissingProjectContextError || error instanceof MissingOrganizationContextError) {+ toolErrorsTotal.inc({ tool: toolName, error_type: 'missing_context' })+ } else if (findPostHogPermissionError(error)) {+ toolErrorsTotal.inc({ tool: toolName, error_type: 'permission' })+ } else if (error instanceof Error && error.name === 'TimeoutError') {+ toolErrorsTotal.inc({ tool: toolName, error_type: 'timeout' })+ } else {+ const apiError = findRecoverableApiError(error)+ if (apiError instanceof PostHogValidationError) {+ toolErrorsTotal.inc({ tool: toolName, error_type: 'validation' })+ } else if (apiError instanceof PostHogApiError && apiError.status >= 500) {+ toolErrorsTotal.inc({ tool: toolName, error_type: 'api_5xx' })+ } else if (apiError instanceof PostHogApiError) {+ toolErrorsTotal.inc({ tool: toolName, error_type: 'api_4xx' })+ } else {+ toolErrorsTotal.inc({ tool: toolName, error_type: 'internal' })+ }+ }+}