Skip to content

: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.

fix(mcp): exclude impersonated events from analytics (#102655)

danazou2e0879f922dd
diff --git a/services/mcp/src/cli/context.ts b/services/mcp/src/cli/context.ts
index 7f29cc48e87d..349fadff1eda 100644
--- a/services/mcp/src/cli/context.ts
+++ b/services/mcp/src/cli/context.ts
@@ -95,6 +95,7 @@ export async function buildCliContext(config: CliConfig): Promise<Context> {
...(analyticsContext ? buildMCPContextProperties(analyticsContext) : {}),
$session_id: await sessionManager.getSessionUuid(sessionId),
...properties,
+ is_impersonated: apiKey?.is_impersonated === true,
},
})
} catch {}
diff --git a/services/mcp/src/hono/analytics.ts b/services/mcp/src/hono/analytics.ts
index 7a3b33165349..0a844961e5eb 100644
--- a/services/mcp/src/hono/analytics.ts
+++ b/services/mcp/src/hono/analytics.ts
@@ -43,6 +43,7 @@ function buildBaseProperties(
const properties: Record<string, unknown> = {
$ai_product: 'mcp',
+ is_impersonated: state.isImpersonated === true,
// The same property `posthog/event_usage.py` stamps on product events, so an MCP call
// and the API work it causes land in one breakdown. Distinct from `$mcp_source`, which
// names the emitting SDK rather than the surface.
@@ -208,6 +209,7 @@ export async function trackToolCall(
// breakdown rather than a string split over `tool_name` in HogQL.
...(gatewayServer ? { mcp_gateway_server: gatewayServer } : {}),
...extraProperties,
+ is_impersonated: state.isImpersonated === true,
},
})
} catch {
diff --git a/services/mcp/src/hono/request-context.ts b/services/mcp/src/hono/request-context.ts
index a53b992b217d..a4f471fe282d 100644
--- a/services/mcp/src/hono/request-context.ts
+++ b/services/mcp/src/hono/request-context.ts
@@ -303,6 +303,7 @@ export class RequestContext {
try {
const resolvedDistinctId = distinctId ?? (await this.getDistinctId())
const clientName = await this.tokenCache.get('clientName')
+ const apiKey = await this.tokenCache.get('apiKey').catch(() => undefined)
const sessionUuid = await this.getEffectiveSessionUuid(this.requestContext)
const contextProperties = analyticsContext ? buildMCPContextProperties(analyticsContext) : {}
const previousContextProperties = previousContext
@@ -321,6 +322,7 @@ export class RequestContext {
...contextProperties,
...previousContextProperties,
...properties,
+ is_impersonated: apiKey?.is_impersonated === true,
},
})
} catch {
diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.ts
index ab1ee3583dd7..2678a6f44fca 100644
--- a/services/mcp/src/hono/request-state-resolver.ts
+++ b/services/mcp/src/hono/request-state-resolver.ts
@@ -42,6 +42,7 @@ export interface ResolvedState {
useSingleExec: boolean
toolFeatureFlags: EvaluatedFlags | undefined
apiKeyScopes: string[]
+ isImpersonated?: boolean
oauthClientId: string | undefined
clientProfile: MCPClientProfile
requestContext: MCPRequestContext
@@ -268,6 +269,7 @@ export class RequestStateResolver {
useSingleExec,
toolFeatureFlags,
apiKeyScopes,
+ isImpersonated: _apiKey?.is_impersonated === true,
oauthClientId,
clientProfile,
requestContext,
diff --git a/services/mcp/src/lib/StateManager.ts b/services/mcp/src/lib/StateManager.ts
index 44addf5d3b22..0fbdffa7db7c 100644
--- a/services/mcp/src/lib/StateManager.ts
+++ b/services/mcp/src/lib/StateManager.ts
@@ -60,6 +60,7 @@ export class StateManager {
scopes: scopes ?? [],
scoped_teams: scoped_teams ?? [],
scoped_organizations: scoped_organizations ?? [],
+ is_impersonated: false,
}
}
@@ -95,6 +96,7 @@ export class StateManager {
scopes: scope ? scope.split(' ') : [],
scoped_teams: scoped_teams ?? [],
scoped_organizations: scoped_organizations ?? [],
+ is_impersonated: introspectionResult.data.is_impersonated === true,
}
}
diff --git a/services/mcp/src/lib/posthog/client.ts b/services/mcp/src/lib/posthog/client.ts
index 57413ed91870..05898dc1f23c 100644
--- a/services/mcp/src/lib/posthog/client.ts
+++ b/services/mcp/src/lib/posthog/client.ts
@@ -20,6 +20,12 @@ export const getPostHogClient = (): PostHogMCP => {
// from fanning out a separate `$exception` event into Error Tracking.
enableExceptionAutocapture: false,
captureModel: true,
+ before_send: (event) => {
+ if (event?.properties?.is_impersonated === true) {
+ return null
+ }
+ return event
+ },
})
}
diff --git a/services/mcp/src/schema/api.ts b/services/mcp/src/schema/api.ts
index 81408bb39a41..a135fd973aaa 100644
--- a/services/mcp/src/schema/api.ts
+++ b/services/mcp/src/schema/api.ts
@@ -42,6 +42,7 @@ export interface ApiUser {
// at the wire boundary (see `StateManager._fetchApiKey`); this type represents
// the post-normalization shape that the rest of the codebase consumes.
export interface ApiRedactedPersonalApiKey {
+ is_impersonated?: boolean
scopes: string[]
scoped_teams: number[]
scoped_organizations: string[]
@@ -50,6 +51,7 @@ export interface ApiRedactedPersonalApiKey {
export type ApiOAuthIntrospection =
| {
active: true
+ is_impersonated?: boolean
scope: string
scoped_teams: number[]
scoped_organizations: string[]
diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.ts
index 79236a1363e6..d737ffd1aef7 100644
--- a/services/mcp/tests/hono/analytics.test.ts
+++ b/services/mcp/tests/hono/analytics.test.ts
@@ -1,8 +1,9 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-const { mockCaptureToolCall, mockCaptureInitialize, mockCapture } = vi.hoisted(() => ({
+const { mockCaptureToolCall, mockCaptureInitialize, mockCaptureToolsList, mockCapture } = vi.hoisted(() => ({
mockCaptureToolCall: vi.fn(),
mockCaptureInitialize: vi.fn(),
+ mockCaptureToolsList: vi.fn(),
// Raw `capture`; must never be used for the retired legacy `mcp_*` event names.
mockCapture: vi.fn(),
}))
@@ -11,6 +12,7 @@ vi.mock('@/lib/posthog', () => ({
getPostHogClient: vi.fn(() => ({
captureToolCall: mockCaptureToolCall,
captureInitialize: mockCaptureInitialize,
+ captureToolsList: mockCaptureToolsList,
capture: mockCapture,
})),
}))
@@ -20,6 +22,7 @@ import {
trackInitEvent,
trackSkillInvoked,
trackToolCall,
+ trackToolsList,
trackToolSpan,
} from '@/hono/analytics'
import { MCP_EXEC_SKILLS_FEATURE_FLAG } from '@/hono/constants'
@@ -89,6 +92,7 @@ describe('Hono MCP analytics contexts', () => {
beforeEach(() => {
mockCaptureToolCall.mockClear()
mockCaptureInitialize.mockClear()
+ mockCaptureToolsList.mockClear()
mockCapture.mockClear()
})
@@ -100,6 +104,32 @@ describe('Hono MCP analytics contexts', () => {
expect(mockCapture).not.toHaveBeenCalled()
})
+ it.each([
+ { impersonated: true, isError: false },
+ { impersonated: true, isError: true },
+ { impersonated: false, isError: false },
+ { impersonated: false, isError: true },
+ ])('passes impersonated=$impersonated to the SDK with isError=$isError', async ({ impersonated, isError }) => {
+ const state = makeState({ isImpersonated: impersonated })
+
+ await trackToolCall('user-get', 12, isError, state, { is_impersonated: !impersonated })
+ await trackInitEvent(state)
+ await trackToolsList(['user-get'], state)
+
+ expect(mockCaptureToolCall).toHaveBeenCalledWith(
+ expect.objectContaining({
+ toolName: 'user-get',
+ isError,
+ properties: expect.objectContaining({ is_impersonated: impersonated }),
+ })
+ )
+ for (const capture of [mockCaptureInitialize, mockCaptureToolsList]) {
+ expect(capture).toHaveBeenCalledWith(
+ expect.objectContaining({ properties: expect.objectContaining({ is_impersonated: impersonated }) })
+ )
+ }
+ })
+
it('emits request properties on $mcp fields and session properties on mcp_session fields', async () => {
await trackInitEvent(makeState())
diff --git a/services/mcp/tests/hono/request-context.test.ts b/services/mcp/tests/hono/request-context.test.ts
index cac9c3b6201b..e96ccdcbc84e 100644
--- a/services/mcp/tests/hono/request-context.test.ts
+++ b/services/mcp/tests/hono/request-context.test.ts
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
-const { mockMe, mockApiClientCtor } = vi.hoisted(() => {
+const { mockMe, mockApiClientCtor, mockCapture } = vi.hoisted(() => {
const mockMe = vi.fn()
const mockApiClientCtor = vi.fn().mockImplementation(function (config) {
return {
@@ -8,15 +8,20 @@ const { mockMe, mockApiClientCtor } = vi.hoisted(() => {
users: () => ({ me: mockMe }),
}
})
- return { mockMe, mockApiClientCtor }
+ return { mockMe, mockApiClientCtor, mockCapture: vi.fn() }
})
vi.mock('@/api/client', () => ({
ApiClient: mockApiClientCtor,
}))
+vi.mock('@/lib/posthog', () => ({
+ getPostHogClient: () => ({ capture: mockCapture }),
+}))
+
import type { RedisLike } from '@/hono/cache/RedisCache'
import { RequestContext } from '@/hono/request-context'
+import { AnalyticsEvent } from '@/lib/posthog/analytics'
import type { RequestProperties } from '@/lib/request-properties'
import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'
@@ -70,6 +75,34 @@ function makeProps(overrides: Partial<RequestProperties> = {}): RequestPropertie
}
describe('RequestContext', () => {
+ it.each([true, false, undefined])('passes cached impersonation=%s to captured events', async (impersonated) => {
+ mockCapture.mockClear()
+ const ctx = new RequestContext(fakeRedis(), env, makeProps())
+ if (impersonated !== undefined) {
+ await ctx.tokenCache.set('apiKey', {
+ scopes: [],
+ scoped_teams: [],
+ scoped_organizations: [],
+ is_impersonated: impersonated,
+ })
+ }
+
+ await ctx.trackEvent(
+ AnalyticsEvent.MCP_FEEDBACK_SUBMITTED,
+ { is_impersonated: !impersonated },
+ undefined,
+ undefined,
+ 'user-123'
+ )
+
+ expect(mockCapture).toHaveBeenCalledWith(
+ expect.objectContaining({
+ event: AnalyticsEvent.MCP_FEEDBACK_SUBMITTED,
+ properties: expect.objectContaining({ is_impersonated: impersonated === true }),
+ })
+ )
+ })
+
describe('ApiClient construction', () => {
const originalEnv = { ...process.env }
diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.ts
index 2b0948df80f8..d45eabde147c 100644
--- a/services/mcp/tests/hono/request-state-resolver.test.ts
+++ b/services/mcp/tests/hono/request-state-resolver.test.ts
@@ -4,7 +4,7 @@ const { mockSessionStore, mockTokenStore, mockApiKey, mockSessionScopedStores, m
() => ({
mockSessionStore: new Map<string, unknown>(),
mockTokenStore: new Map<string, unknown>(),
- mockApiKey: { scopes: ['*'], scoped_teams: [] },
+ mockApiKey: { scopes: ['*'], scoped_teams: [], is_impersonated: undefined as boolean | undefined },
mockSessionScopedStores: new Map<string, Map<string, unknown>>(),
// Records the keys passed to every session-scoped refreshTtl call (only the
// session cache refreshes, so any recorded call is a session refresh).
@@ -149,6 +149,15 @@ describe('RequestStateResolver MCP client contexts', () => {
mockSessionScopedStores.clear()
mockRefreshTtlCalls.length = 0
mockApiKey.scopes = ['*']
+ mockApiKey.is_impersonated = undefined
+ })
+
+ it.each([true, false, undefined])('passes token impersonation=%s to analytics', async (impersonated) => {
+ mockApiKey.is_impersonated = impersonated
+
+ const result = await makeResolver().resolve(makeProps())
+
+ expect(result.isImpersonated).toBe(impersonated === true)
})
it.each([
diff --git a/services/mcp/tests/unit/StateManager.test.ts b/services/mcp/tests/unit/StateManager.test.ts
index 1502f88880c4..c1956d665a56 100644
--- a/services/mcp/tests/unit/StateManager.test.ts
+++ b/services/mcp/tests/unit/StateManager.test.ts
@@ -82,7 +82,7 @@ describe('StateManager', () => {
})
describe('getApiKey', () => {
- function oauthApi(clientName: string | null): ApiClient {
+ function oauthApi(clientName: string | null, impersonated?: boolean): ApiClient {
return {
config: { apiToken: 'phx_test' },
apiKeys: () => ({
@@ -91,12 +91,46 @@ describe('StateManager', () => {
oauth: () => ({
introspect: async () => ({
success: true,
- data: { active: true, scope: 'insight:read', client_name: clientName },
+ data: {
+ active: true,
+ scope: 'insight:read',
+ client_name: clientName,
+ is_impersonated: impersonated,
+ },
}),
}),
} as unknown as ApiClient
}
+ it.each([true, false, undefined])(
+ 'fetches token metadata and caches impersonation=%s',
+ async (impersonated) => {
+ stateManager = new StateManager(cache, oauthApi(null, impersonated))
+
+ const result = await stateManager.getApiKey()
+
+ expect(result.is_impersonated).toBe(impersonated === true)
+ expect(await new StateManager(cache, {} as ApiClient).getApiKey()).toEqual(result)
+
+ const otherTokenCache = new MemoryCache<State>('other-token')
+ await otherTokenCache.clear()
+ const otherToken = new StateManager(otherTokenCache, oauthApi(null, false))
+ expect((await otherToken.getApiKey()).is_impersonated).toBe(false)
+ expect((await stateManager.getApiKey()).is_impersonated).toBe(impersonated === true)
+ }
+ )
+
+ it('caches personal API keys as not impersonated', async () => {
+ const api = {
+ apiKeys: () => ({ current: async () => ({ success: true, data: mockApiKey }) }),
+ } as unknown as ApiClient
+
+ const result = await new StateManager(cache, api).getApiKey()
+
+ expect(result).toEqual({ ...mockApiKey, is_impersonated: false })
+ expect(await new StateManager(cache, {} as ApiClient).getApiKey()).toEqual(result)
+ })
+
it.each([
{ label: 'an OAuth app name', clientName: 'Claude', expected: 'Claude' },
{ label: 'no OAuth app name', clientName: null, expected: undefined },
diff --git a/services/mcp/tests/unit/cli-context.test.ts b/services/mcp/tests/unit/cli-context.test.ts
index 24512bb4e8eb..442130bf6531 100644
--- a/services/mcp/tests/unit/cli-context.test.ts
+++ b/services/mcp/tests/unit/cli-context.test.ts
@@ -37,31 +37,75 @@ describe('CLI context', () => {
mocks.getApiKey.mockRejectedValue(new Error('offline'))
})
- it('uses an opaque analytics distinct ID when identity resolution fails', async () => {
+ it.each(['phx_secret-token', undefined])(
+ 'captures tool calls when identity resolution fails with API key %s',
+ async (apiKey) => {
+ const context = await buildCliContext({ apiKey, host: 'https://us.posthog.com', version: 2 })
+
+ await expect(context.trackEvent(AnalyticsEvent.MCP_TOOL_CALL)).resolves.toBeUndefined()
+
+ const expectedId = apiKey
+ ? `posthog-cli:${createHash('sha256').update(apiKey).digest('hex').slice(0, 16)}`
+ : 'posthog-cli:anonymous'
+ expect(mocks.capture).toHaveBeenCalledWith(
+ expect.objectContaining({
+ distinctId: expectedId,
+ event: AnalyticsEvent.MCP_TOOL_CALL,
+ properties: expect.objectContaining({ is_impersonated: false }),
+ })
+ )
+ if (apiKey) {
+ expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain(apiKey)
+ }
+ }
+ )
+
+ it('uses an opaque analytics distinct ID for feedback when identity resolution fails', async () => {
const apiKey = 'phx_secret-token'
const context = await buildCliContext({ apiKey, host: 'https://us.posthog.com', version: 2 })
- await context.trackEvent(AnalyticsEvent.MCP_TOOL_CALL)
+ await context.trackEvent(AnalyticsEvent.MCP_FEEDBACK_SUBMITTED)
const expectedHash = createHash('sha256').update(apiKey).digest('hex').slice(0, 16)
expect(mocks.capture).toHaveBeenCalledWith(
expect.objectContaining({
distinctId: `posthog-cli:${expectedHash}`,
+ event: AnalyticsEvent.MCP_FEEDBACK_SUBMITTED,
})
)
expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain(apiKey)
})
- it('uses an anonymous analytics distinct ID without an API key', async () => {
+ it('uses an anonymous analytics distinct ID for feedback without an API key', async () => {
const context = await buildCliContext({ host: 'https://us.posthog.com', version: 2 })
- await context.trackEvent(AnalyticsEvent.MCP_TOOL_CALL)
+ await context.trackEvent(AnalyticsEvent.MCP_FEEDBACK_SUBMITTED)
expect(mocks.capture).toHaveBeenCalledWith(
expect.objectContaining({
distinctId: 'posthog-cli:anonymous',
+ event: AnalyticsEvent.MCP_FEEDBACK_SUBMITTED,
properties: expect.objectContaining({ $mcp_scope_preset: 'user' }),
})
)
})
+
+ it.each(Object.values(AnalyticsEvent).flatMap((event) => [true, false].map((value) => [event, value] as const)))(
+ 'passes impersonation status to the SDK for %s with impersonation %s',
+ async (event, impersonated) => {
+ mocks.getDistinctId.mockResolvedValue('user-123')
+ mocks.getApiKey.mockResolvedValue({ scopes: [], is_impersonated: impersonated })
+ const context = await buildCliContext({ host: 'https://us.posthog.com', version: 2 })
+
+ await context.trackEvent(event, { is_impersonated: !impersonated })
+
+ expect(mocks.capture).toHaveBeenCalledWith(
+ expect.objectContaining({
+ distinctId: 'user-123',
+ event,
+ properties: expect.objectContaining({ is_impersonated: impersonated }),
+ })
+ )
+ }
+ )
})
diff --git a/services/mcp/tests/unit/posthog/client.test.ts b/services/mcp/tests/unit/posthog/client.test.ts
new file mode 100644
index 000000000000..63d65afb2e2c
--- /dev/null
+++ b/services/mcp/tests/unit/posthog/client.test.ts
@@ -0,0 +1,82 @@
+import { gunzipSync } from 'node:zlib'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { getPostHogClient } from '@/lib/posthog/client'
+
+vi.mock('@/lib/env', () => ({
+ env: {
+ POSTHOG_ANALYTICS_API_KEY: 'phc_test',
+ POSTHOG_ANALYTICS_HOST: 'https://example.com',
+ },
+}))
+
+describe('PostHog client', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ })
+
+ it.each([
+ ['capture', '$mcp_tool_call', false],
+ ['capture', '$mcp_tool_call', true],
+ ['captureToolCall', '$mcp_tool_call', false],
+ ['captureToolCall', '$mcp_tool_call', true],
+ ['captureInitialize', '$mcp_initialize', false],
+ ['captureToolsList', '$mcp_tools_list', false],
+ ['captureException', '$exception', true],
+ ['capture', '$identify', false],
+ ['capture', 'mcp feedback submitted', false],
+ ['capture', '$ai_generation', false],
+ ['capture', '$ai_span', false],
+ ] as const)('filters impersonated events through %s for %s with isError=%s', async (method, eventName, isError) => {
+ const events: { event: string; properties: Record<string, unknown> }[] = []
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (_url: string, options: RequestInit) => {
+ const body =
+ typeof options.body === 'string' ? options.body : gunzipSync(options.body as Uint8Array).toString()
+ events.push(...JSON.parse(body).batch)
+ return new Response('{}', { status: 200 })
+ })
+ )
+ const client = getPostHogClient()
+
+ for (const isImpersonated of [true, false, true, undefined]) {
+ const properties = {
+ ...(isImpersonated === undefined ? {} : { is_impersonated: isImpersonated }),
+ $mcp_is_error: isError,
+ }
+ if (method === 'captureToolCall') {
+ client.captureToolCall({
+ distinctId: 'user-123',
+ toolName: 'user-get',
+ durationMs: 12,
+ isError,
+ properties,
+ })
+ } else if (method === 'captureInitialize') {
+ client.captureInitialize({ distinctId: 'user-123', durationMs: 12, properties })
+ } else if (method === 'captureToolsList') {
+ client.captureToolsList({ distinctId: 'user-123', toolNames: ['user-get'], properties })
+ } else if (method === 'captureException') {
+ client.captureException(new Error('Test error'), 'user-123', properties)
+ } else {
+ client.capture({ distinctId: 'user-123', event: eventName, properties })
+ }
+ }
+ await client.flush()
+
+ expect(events).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ event: eventName,
+ properties: expect.objectContaining({ is_impersonated: false, $mcp_is_error: isError }),
+ }),
+ expect.objectContaining({
+ event: eventName,
+ properties: expect.not.objectContaining({ is_impersonated: expect.anything() }),
+ }),
+ ])
+ )
+ expect(events).toHaveLength(2)
+ })
+})