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.

feat(mcp): enable PostHog MCP analytics SDK (#58061)

Lucas Faria4c5df0690f98
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2a81557d8e8a..2861e4f97b04 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3430,6 +3430,9 @@ importers:
'@modelcontextprotocol/sdk':
specifier: ^1.29.0
version: 1.29.0(@cfworker/[email protected])([email protected])
+ '@posthog/mcp-analytics':
+ specifier: npm:@posthog/[email protected]
+ version: '@posthog/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])'
'@posthog/mosaic':
specifier: workspace:*
version: link:../../common/mosaic
@@ -9003,6 +9006,9 @@ packages:
'@posthog/[email protected]':
resolution: {integrity: sha512-GViD5mOv/mcbZcyzz3z9CS0R79JzxVaqEz4sP5Dsea178M/j3ZWe6gaHDZB9yuyGfcmIMQ/8K14yv+7QrK4sQQ==}
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-SOy0aphKawZzp8jxfeOpTcXPwi6ii0I2V6tX8YXnM+WbxKKR/R+BXLK0jS6LV8kZtW3H5YxmPAfuIbUP1UnGTw==}
+
'@posthog/[email protected]':
resolution: {integrity: sha512-wmtUYHYqA3zIAKDKvYWRNWAQsWOIBwxV08e+bWzVy0wQQzpaS/LzzRupXWRMRrLOk+1x3JKFxbqA3n0QGvpqsQ==}
@@ -9040,6 +9046,12 @@ packages:
react: 18.3.1
react-dom: 18.3.1
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-sK0/kY/wyPXzWaX14UrBjA2wTo+K9mUmRfzDBUSDFyyDeZgxEMK2JK/0CeuEI0yXdpTja6rsDlMkRZjYakTFVA==}
+ engines: {node: '>=22.22.0'}
+ peerDependencies:
+ '@modelcontextprotocol/sdk': ^1.29.0
+
'@posthog/[email protected]':
resolution: {integrity: sha512-lVdTsWT5+PtHBu44gSQ7QohbLjAYqHkFAIGAQ+HV8Eh9yj+OcnQ7mXCmyhaMlTBD3z7D0H1eWMp4vQaFnsIyWQ==}
peerDependencies:
@@ -9081,6 +9093,9 @@ packages:
'@posthog/[email protected]':
resolution: {integrity: sha512-KuT3vLu3LSFsNWCwasS4gqjH/ysAyIUcB/aJSmKyNhDd/85hAznHRz1eSSl0sMvtsDTYiQIq0I0ybduVbrpPew==}
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-B7k9S+H9WUKHXxe1HOkQWbpWtMcrBvsodm5stZaLQ3pYxf9TowtwssdzTtX4hHjzSYqgrS1IpNnJX4vs1KgBzA==}
+
'@protobufjs/[email protected]':
resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==}
@@ -20169,6 +20184,15 @@ packages:
resolution: {integrity: sha512-DFE5lZAoD6hk7RATuT8qVQ7KFgFP5YlFTJciMbU2qq6NX0A8eJxiJcmEsMnB3g30jJJ9suiwGIq4I8ESwf9bZg==}
engines: {node: ^20.20.0 || >=22.22.0}
+ resolution: {integrity: sha512-6BkdRtRKf/y/j6JGXLUDWpruL9Rebpe2EtbSU3EB+yaI9ukTwEGT8XJQDyM8wcsxu1HdOnvAwN7gnOOu5OgY2A==}
+ engines: {node: ^20.20.0 || >=22.22.0}
+ peerDependencies:
+ rxjs: ^7.0.0
+ peerDependenciesMeta:
+ rxjs:
+ optional: true
+
resolution: {integrity: sha512-QecJtfLekJbWVo/dMAA+OSwY79wpRmbqS5TeXvXSX+f0c6pW4/SE6inzZ2qkU7oAMCPqIDkZDvd/bQsSFUnKyw==}
engines: {node: '>=12'}
@@ -32119,6 +32143,10 @@ snapshots:
dependencies:
cross-spawn: 7.0.6
+ '@posthog/[email protected]':
+ dependencies:
+ '@posthog/types': 1.372.9
+
'@posthog/[email protected]':
dependencies:
'@posthog/types': 1.372.10
@@ -32160,6 +32188,13 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
+ dependencies:
+ '@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])
+ posthog-node: 5.33.3([email protected])
+ transitivePeerDependencies:
+ - rxjs
+
dependencies:
posthog-js: 1.372.10
@@ -32201,6 +32236,8 @@ snapshots:
'@posthog/[email protected]': {}
+ '@posthog/[email protected]': {}
+
'@protobufjs/[email protected]': {}
'@protobufjs/[email protected]': {}
@@ -46731,6 +46768,12 @@ snapshots:
dependencies:
'@posthog/core': 1.23.1
+ dependencies:
+ '@posthog/core': 1.28.3
+ optionalDependencies:
+ rxjs: 7.8.1
+
dependencies:
htmlparser2: 7.2.0
diff --git a/services/mcp/package.json b/services/mcp/package.json
index 727ca1616545..78854cb223d3 100644
--- a/services/mcp/package.json
+++ b/services/mcp/package.json
@@ -36,6 +36,7 @@
"dependencies": {
"@modelcontextprotocol/ext-apps": "^1.5.0",
"@modelcontextprotocol/sdk": "^1.29.0",
+ "@posthog/mcp-analytics": "npm:@posthog/[email protected]",
"@posthog/mosaic": "workspace:*",
"@toon-format/toon": "^2.1.0",
"agents": "0.10.2",
diff --git a/services/mcp/src/index.ts b/services/mcp/src/index.ts
index f95ce5adcde6..543a875ba15a 100644
--- a/services/mcp/src/index.ts
+++ b/services/mcp/src/index.ts
@@ -14,6 +14,36 @@ import type { CloudRegion } from '@/tools/types'
import { MCP, RequestProperties } from './mcp'
+function extendMcpServerLog(log: RequestLogger, props: RequestProperties): void {
+ const mcpServerLog: Record<string, unknown> = {
+ ...(props.mcpAnalyticsProvider ? { mcpAnalyticsProvider: props.mcpAnalyticsProvider } : {}),
+ ...(props.mcpAnalyticsFlagKey ? { mcpAnalyticsFlagKey: props.mcpAnalyticsFlagKey } : {}),
+ ...(props.mcpAnalyticsFlagEnabled !== undefined
+ ? { mcpAnalyticsFlagEnabled: props.mcpAnalyticsFlagEnabled }
+ : {}),
+ ...(props.mcpAnalyticsFlagErrorName ? { mcpAnalyticsFlagErrorName: props.mcpAnalyticsFlagErrorName } : {}),
+ ...(props.mcpAnalyticsFlagErrorMessage
+ ? { mcpAnalyticsFlagErrorMessage: props.mcpAnalyticsFlagErrorMessage }
+ : {}),
+ ...(props.posthogMcpAnalyticsInitAction
+ ? { posthogMcpAnalyticsInitAction: props.posthogMcpAnalyticsInitAction }
+ : {}),
+ ...(props.posthogMcpAnalyticsInitReason
+ ? { posthogMcpAnalyticsInitReason: props.posthogMcpAnalyticsInitReason }
+ : {}),
+ ...(props.posthogMcpAnalyticsInitErrorName
+ ? { posthogMcpAnalyticsInitErrorName: props.posthogMcpAnalyticsInitErrorName }
+ : {}),
+ ...(props.posthogMcpAnalyticsInitErrorMessage
+ ? { posthogMcpAnalyticsInitErrorMessage: props.posthogMcpAnalyticsInitErrorMessage }
+ : {}),
+ }
+
+ if (Object.keys(mcpServerLog).length > 0) {
+ log.extend(mcpServerLog)
+ }
+}
+
// Helper to get the public-facing URL, respecting reverse proxy headers
// This is needed for local development with ngrok/cloudflared where request.url
// shows http://localhost but the actual URL is https://...ngrok-free.dev
@@ -371,7 +401,16 @@ const handleRequest = async (
}
if (server !== null) {
- return server.then(onThenErrorHandler).catch((error: Error) => onCatchErrorHandler(error, log, ctx))
+ return server
+ .then(async (response) => {
+ const handledResponse = await onThenErrorHandler(response)
+ extendMcpServerLog(log, ctx.props)
+ return handledResponse
+ })
+ .catch((error: Error) => {
+ extendMcpServerLog(log, ctx.props)
+ return onCatchErrorHandler(error, log, ctx)
+ })
}
log.extend({ error: 'route_not_found' })
diff --git a/services/mcp/src/lib/posthog-mcp-analytics.ts b/services/mcp/src/lib/posthog-mcp-analytics.ts
new file mode 100644
index 000000000000..6b769d49061b
--- /dev/null
+++ b/services/mcp/src/lib/posthog-mcp-analytics.ts
@@ -0,0 +1,152 @@
+import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
+import { env } from 'cloudflare:workers'
+
+import { type McpCatIdentityProvider, redactSensitiveInformation } from '@/lib/mcpcat'
+
+export type PostHogMcpAnalyticsIdentityProvider = McpCatIdentityProvider
+
+export type PostHogMcpAnalyticsOptions = {
+ contextEnabled: boolean
+}
+
+export type PostHogMcpAnalyticsInitResult =
+ | {
+ action: 'initialized'
+ contextEnabled: boolean
+ tracingEnabled: true
+ aiTracingEnabled: true
+ reportMissingEnabled: true
+ }
+ | {
+ action: 'skipped'
+ reason: 'missing_config'
+ hasApiKey: boolean
+ hasHost: boolean
+ }
+ | {
+ action: 'failed'
+ errorName: string
+ errorMessage: string
+ }
+
+async function buildEventTags(identity: PostHogMcpAnalyticsIdentityProvider): Promise<Record<string, string>> {
+ const sessionUuid = await identity.getSessionUuid()
+ if (!sessionUuid) {
+ return {}
+ }
+
+ return {
+ $session_id: sessionUuid,
+ $ai_session_id: sessionUuid,
+ }
+}
+
+async function buildEventProperties(identity: PostHogMcpAnalyticsIdentityProvider): Promise<Record<string, unknown>> {
+ const [
+ mcpVersion,
+ clientUserAgent,
+ mcpClientName,
+ mcpClientVersion,
+ mcpProtocolVersion,
+ mcpRegion,
+ analyticsContext,
+ oauthClientName,
+ readOnly,
+ transport,
+ mcpConsumer,
+ mcpMode,
+ ] = await Promise.all([
+ identity.getMcpVersion(),
+ identity.getClientUserAgent(),
+ identity.getMcpClientName(),
+ identity.getMcpClientVersion(),
+ identity.getMcpProtocolVersion(),
+ identity.getRegion(),
+ identity.getAnalyticsContext(),
+ identity.getOAuthClientName(),
+ identity.getReadOnly(),
+ identity.getTransport(),
+ identity.getMcpConsumer(),
+ identity.getMcpMode(),
+ ])
+
+ const groups = {
+ ...(analyticsContext?.organizationId ? { organization: analyticsContext.organizationId } : {}),
+ ...(analyticsContext?.projectUuid ? { project: analyticsContext.projectUuid } : {}),
+ }
+
+ return {
+ $ai_product: 'mcp',
+ $mcp_version: mcpVersion,
+ $mcp_client_user_agent: clientUserAgent,
+ $mcp_client_name: mcpClientName,
+ $mcp_client_version: mcpClientVersion,
+ $mcp_protocol_version: mcpProtocolVersion,
+ $mcp_region: mcpRegion,
+ $mcp_organization_id: analyticsContext?.organizationId,
+ $mcp_project_id: analyticsContext?.projectId,
+ $mcp_project_uuid: analyticsContext?.projectUuid,
+ $mcp_project_name: analyticsContext?.projectName,
+ $mcp_oauth_client_name: oauthClientName,
+ $mcp_read_only: readOnly,
+ $mcp_transport: transport,
+ $mcp_consumer: mcpConsumer,
+ $mcp_mode: mcpMode,
+ ...(Object.keys(groups).length > 0 ? { $groups: groups } : {}),
+ }
+}
+
+export async function initPostHogMcpAnalytics(
+ server: McpServer,
+ identity: PostHogMcpAnalyticsIdentityProvider,
+ options: PostHogMcpAnalyticsOptions = { contextEnabled: false }
+): Promise<PostHogMcpAnalyticsInitResult> {
+ const posthogApiKey = env.POSTHOG_ANALYTICS_API_KEY
+ const posthogHost = env.POSTHOG_ANALYTICS_HOST
+ if (!posthogApiKey || !posthogHost) {
+ return {
+ action: 'skipped',
+ reason: 'missing_config',
+ hasApiKey: !!posthogApiKey,
+ hasHost: !!posthogHost,
+ }
+ }
+
+ try {
+ const { track } = await import('@posthog/mcp-analytics')
+ const distinctId = await identity.getDistinctId()
+ const identifyResult = { userId: distinctId }
+
+ track(server, {
+ apiKey: posthogApiKey,
+ context: options.contextEnabled,
+ enableAITracing: true,
+ enableTracing: true,
+ host: posthogHost,
+ identify: async () => identifyResult,
+ posthogOptions: {
+ flushAt: 1,
+ flushInterval: 0,
+ host: posthogHost,
+ },
+ reportMissing: true,
+ eventTags: async () => buildEventTags(identity),
+ eventProperties: async () => buildEventProperties(identity),
+ redactSensitiveInformation: (text) => Promise.resolve(redactSensitiveInformation(text)),
+ })
+
+ return {
+ action: 'initialized',
+ contextEnabled: options.contextEnabled,
+ tracingEnabled: true,
+ aiTracingEnabled: true,
+ reportMissingEnabled: true,
+ }
+ } catch (error) {
+ return {
+ action: 'failed',
+ errorName: error instanceof Error ? error.name : 'UnknownError',
+ errorMessage: error instanceof Error ? error.message : String(error),
+ }
+ }
+}
diff --git a/services/mcp/src/mcp.ts b/services/mcp/src/mcp.ts
index d673d1af41c1..24d641870512 100644
--- a/services/mcp/src/mcp.ts
+++ b/services/mcp/src/mcp.ts
@@ -29,6 +29,7 @@ import { handleToolError, wrapError } from '@/lib/errors'
import { type QueryToolInfo } from '@/lib/instructions'
import { InstructionsFormatter } from '@/lib/instructions-formatter'
import { initMcpCatObservability } from '@/lib/mcpcat'
+import { initPostHogMcpAnalytics, type PostHogMcpAnalyticsInitResult } from '@/lib/posthog-mcp-analytics'
import { SessionManager } from '@/lib/SessionManager'
import { StateManager } from '@/lib/StateManager'
import { formatPrompt, type McpMode, sanitizeHeaderValue } from '@/lib/utils'
@@ -41,6 +42,13 @@ import { getToolDefinition } from '@/tools/toolDefinitions'
import { type CloudRegion, type Context, type State, type Tool } from '@/tools/types'
const instructionsFormatter = new InstructionsFormatter()
+const POSTHOG_MCP_ANALYTICS_FLAG = 'mcp-posthog-analytics-sdk'
+type McpAnalyticsProvider = 'posthog_mcp_analytics' | 'mcpcat'
+type PostHogMcpAnalyticsFlagResult = {
+ enabled: boolean
+ errorName?: string
+ errorMessage?: string
+}
export type RequestProperties = {
userHash: string
@@ -62,6 +70,15 @@ export type RequestProperties = {
transport?: 'streamable-http' | 'sse'
viaSseRedirect?: boolean
requestStartTime?: number
+ mcpAnalyticsProvider?: McpAnalyticsProvider
+ mcpAnalyticsFlagKey?: string
+ mcpAnalyticsFlagEnabled?: boolean
+ mcpAnalyticsFlagErrorName?: string
+ mcpAnalyticsFlagErrorMessage?: string
+ posthogMcpAnalyticsInitAction?: PostHogMcpAnalyticsInitResult['action']
+ posthogMcpAnalyticsInitReason?: string
+ posthogMcpAnalyticsInitErrorName?: string
+ posthogMcpAnalyticsInitErrorMessage?: string
}
export class MCP extends McpAgent<Env> {
@@ -500,6 +517,7 @@ export class MCP extends McpAgent<Env> {
const flagPromise = this.resolveVersionFlag()
const toolFlagsPromise = this.resolveToolFeatureFlags(clientVersion)
const singleExecPromise = this.resolveSingleExecFlag()
+ const posthogMcpAnalyticsFlagPromise = this.resolvePostHogMcpAnalyticsFlag()
// Seed cache with header-provided IDs before any fetches
if (organizationId) {
@@ -528,13 +546,15 @@ export class MCP extends McpAgent<Env> {
await context.stateManager.setDefaultOrganizationAndProject()
}
- const [flagVersion, toolFeatureFlags, singleExecFlagOn] = await Promise.all([
+ const [flagVersion, toolFeatureFlags, singleExecFlagOn, posthogMcpAnalyticsFlag] = await Promise.all([
flagPromise,
toolFlagsPromise,
singleExecPromise,
+ posthogMcpAnalyticsFlagPromise,
// Trigger OAuth introspection so the OAuth client name is cached before the useSingleExec decision below
context.stateManager.getApiKey(),
])
+ const posthogMcpAnalyticsOn = posthogMcpAnalyticsFlag.enabled
const oauthClientName = (await this.cache.get('clientName')) || undefined
@@ -699,7 +719,7 @@ export class MCP extends McpAgent<Env> {
}
}
- await initMcpCatObservability(this.server, {
+ const mcpAnalyticsIdentity = {
getDistinctId: () => this.getDistinctId(),
getSessionUuid: async () =>
this.requestProperties.sessionId
@@ -714,15 +734,49 @@ export class MCP extends McpAgent<Env> {
getAnalyticsContext: async () => this.getAnalyticsContextSafe(await this.getContext()),
getClientUserAgent: async () => this.requestProperties.clientUserAgent,
// Server-resolved version (may differ from the client-reported one because of
- // the `mcp-version-2` feature flag), so mcpcat events line up with ours.
+ // the `mcp-version-2` feature flag), so observability events line up with ours.
getMcpVersion: async () => version,
getOAuthClientName: async () => (await this.cache.get('clientName')) || undefined,
getReadOnly: async () => readOnly,
getTransport: async () => this.requestProperties.transport,
getMcpConsumer: async () => this.requestProperties.mcpConsumer,
getMcpMode: async () => this.mcpMode,
+ }
+
+ Object.assign(this.requestProperties, {
+ mcpAnalyticsProvider: posthogMcpAnalyticsOn ? 'posthog_mcp_analytics' : 'mcpcat',
+ mcpAnalyticsFlagKey: POSTHOG_MCP_ANALYTICS_FLAG,
+ mcpAnalyticsFlagEnabled: posthogMcpAnalyticsOn,
+ ...(posthogMcpAnalyticsFlag.errorName
+ ? { mcpAnalyticsFlagErrorName: posthogMcpAnalyticsFlag.errorName }
+ : {}),
+ ...(posthogMcpAnalyticsFlag.errorMessage
+ ? { mcpAnalyticsFlagErrorMessage: posthogMcpAnalyticsFlag.errorMessage }
+ : {}),
})
+ // @posthog/mcp is based on the MCP Cat wrapper and keeps tool tracing,
+ // AI spans, context capture, and get_more_tools for flagged sessions.
+ // Avoid initializing both wrappers because both patch tool handlers and
+ // would double-capture every call.
+ if (posthogMcpAnalyticsOn) {
+ const initResult = await initPostHogMcpAnalytics(this.server, mcpAnalyticsIdentity, {
+ contextEnabled: true,
+ })
+ Object.assign(this.requestProperties, {
+ posthogMcpAnalyticsInitAction: initResult.action,
+ ...(initResult.action === 'skipped' ? { posthogMcpAnalyticsInitReason: initResult.reason } : {}),
+ ...(initResult.action === 'failed'
+ ? {
+ posthogMcpAnalyticsInitErrorName: initResult.errorName,
+ posthogMcpAnalyticsInitErrorMessage: initResult.errorMessage,
+ }
+ : {}),
+ })
+ } else {
+ await initMcpCatObservability(this.server, mcpAnalyticsIdentity)
+ }
+
const initDurationMs = this.requestProperties.requestStartTime
? Date.now() - this.requestProperties.requestStartTime
: undefined
@@ -750,7 +804,7 @@ export class MCP extends McpAgent<Env> {
/**
* Decide single-exec mode and the protocol version for this connection,
- * stashing both on the instance so `trackEvent` and the mcpcat identity
+ * stashing both on the instance so `trackEvent` and observability identity
* provider can emit `mcp_mode` / `mcp_version` on every downstream event
* without re-deriving them.
*
@@ -805,6 +859,19 @@ export class MCP extends McpAgent<Env> {
}
}
+ private async resolvePostHogMcpAnalyticsFlag(): Promise<PostHogMcpAnalyticsFlagResult> {
+ try {
+ const distinctId = await this.getDistinctId()
+ return { enabled: !!(await isFeatureFlagEnabled(POSTHOG_MCP_ANALYTICS_FLAG, distinctId)) }
+ } catch (error) {
+ return {
+ enabled: false,
+ errorName: error instanceof Error ? error.name : 'UnknownError',
+ errorMessage: error instanceof Error ? error.message : String(error),
+ }
+ }
+ }
+
private async resolveToolFeatureFlags(version?: number): Promise<Record<string, boolean> | undefined> {
try {
const { getRequiredFeatureFlags } = await import('@/tools/toolDefinitions')
diff --git a/services/mcp/tests/setup.ts b/services/mcp/tests/setup.ts
index 5a5329a51834..6b877f773b31 100644
--- a/services/mcp/tests/setup.ts
+++ b/services/mcp/tests/setup.ts
@@ -10,6 +10,11 @@ vi.mock('mcpcat', () => ({
track: vi.fn(),
}))
+// Mock PostHog MCP analytics module to avoid networked analytics in tests
+vi.mock('@posthog/mcp-analytics', () => ({
+ track: vi.fn(),
+}))
+
// Mock cloudflare:workers module for Node.js test environment
vi.mock('cloudflare:workers', () => ({
env: {
diff --git a/services/mcp/tests/unit/posthog-mcp-analytics.test.ts b/services/mcp/tests/unit/posthog-mcp-analytics.test.ts
new file mode 100644
index 000000000000..b2a722146c35
--- /dev/null
+++ b/services/mcp/tests/unit/posthog-mcp-analytics.test.ts
@@ -0,0 +1,214 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
+import { env } from 'cloudflare:workers'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { track } from '@posthog/mcp-analytics'
+
+import { initPostHogMcpAnalytics, type PostHogMcpAnalyticsIdentityProvider } from '@/lib/posthog-mcp-analytics'
+
+const TEST_API_KEY = 'test-api-key'
+const TEST_HOST = 'https://test.posthog.com'
+
+describe('initPostHogMcpAnalytics', () => {
+ beforeEach(() => {
+ vi.mocked(track).mockClear()
+ env.POSTHOG_ANALYTICS_API_KEY = TEST_API_KEY
+ env.POSTHOG_ANALYTICS_HOST = TEST_HOST
+ })
+
+ function createMockIdentity(
+ overrides: Partial<PostHogMcpAnalyticsIdentityProvider> = {}
+ ): PostHogMcpAnalyticsIdentityProvider {
+ return {
+ getDistinctId: vi.fn().mockResolvedValue('user-123'),
+ getSessionUuid: vi.fn().mockResolvedValue('session-uuid-456'),
+ getMcpClientName: vi.fn().mockResolvedValue('claude-code'),
+ getMcpClientVersion: vi.fn().mockResolvedValue('1.2.3'),
+ getMcpProtocolVersion: vi.fn().mockResolvedValue('2024-11-05'),
+ getRegion: vi.fn().mockResolvedValue('us'),
+ getAnalyticsContext: vi.fn().mockResolvedValue({
+ organizationId: 'org-789',
+ projectId: 'proj-101',
+ projectUuid: 'proj-uuid-101',
+ projectName: 'Project 101',
+ }),
+ getClientUserAgent: vi.fn().mockResolvedValue('test-agent/1.0'),
+ getMcpVersion: vi.fn().mockResolvedValue(2),
+ getOAuthClientName: vi.fn().mockResolvedValue('PostHog Code'),
+ getReadOnly: vi.fn().mockResolvedValue(true),
+ getTransport: vi.fn().mockResolvedValue('streamable-http'),
+ getMcpConsumer: vi.fn().mockResolvedValue('posthog-code'),
+ getMcpMode: vi.fn().mockResolvedValue('cli'),
+ ...overrides,
+ }
+ }
+
+ function getTrackOptions(): {
+ identify: () => Promise<unknown>
+ eventTags: () => Promise<Record<string, string>>
+ eventProperties: () => Promise<Record<string, unknown>>
+ } {
+ const call = vi.mocked(track).mock.calls[0]!
+ return call[1] as {
+ identify: () => Promise<unknown>
+ eventTags: () => Promise<Record<string, string>>
+ eventProperties: () => Promise<Record<string, unknown>>
+ }
+ }
+
+ it('calls PostHog MCP analytics track with safe defaults', async () => {
+ const server = new McpServer({ name: 'test', version: '1.0.0' })
+ const identity = createMockIdentity()
+
+ const result = await initPostHogMcpAnalytics(server, identity)
+
+ expect(track).toHaveBeenCalledWith(
+ server,
+ expect.objectContaining({
+ apiKey: TEST_API_KEY,
+ context: false,
+ enableAITracing: true,
+ enableTracing: true,
+ host: TEST_HOST,
+ identify: expect.any(Function),
+ eventTags: expect.any(Function),
+ eventProperties: expect.any(Function),
+ posthogOptions: {
+ flushAt: 1,
+ flushInterval: 0,
+ host: TEST_HOST,
+ },
+ reportMissing: true,
+ })
+ )
+ expect(result).toMatchObject({ action: 'initialized', contextEnabled: false })
+ })
+
+ it('enables required context only when explicitly requested', async () => {
+ const server = new McpServer({ name: 'test', version: '1.0.0' })
+ const identity = createMockIdentity()
+
+ const result = await initPostHogMcpAnalytics(server, identity, { contextEnabled: true })
+
+ expect(track).toHaveBeenCalledWith(
+ server,
+ expect.objectContaining({
+ context: true,
+ enableAITracing: true,
+ reportMissing: true,
+ })
+ )
+ expect(result).toMatchObject({ action: 'initialized', contextEnabled: true })
+ })
+
+ it.each(['POSTHOG_ANALYTICS_API_KEY', 'POSTHOG_ANALYTICS_HOST'] as const)(
+ 'skips initialization when %s is not set',
+ async (envKey) => {
+ env[envKey] = undefined as unknown as string
+ const server = new McpServer({ name: 'test', version: '1.0.0' })
+ const identity = createMockIdentity()
+
+ const result = await initPostHogMcpAnalytics(server, identity)
+
+ expect(track).not.toHaveBeenCalled()
+ expect(result).toMatchObject({ action: 'skipped', reason: 'missing_config' })
+ }
+ )
+
+ it('identify callback resolves identity from provider', async () => {
+ const server = new McpServer({ name: 'test', version: '1.0.0' })
+ const identity = createMockIdentity()
+
+ await initPostHogMcpAnalytics(server, identity)
+
+ expect(await getTrackOptions().identify()).toEqual({ userId: 'user-123' })
+ })
+
+ it('eventTags callback returns $session_id and $ai_session_id when available', async () => {
+ const server = new McpServer({ name: 'test', version: '1.0.0' })
+ const identity = createMockIdentity()
+
+ await initPostHogMcpAnalytics(server, identity)
+
+ expect(await getTrackOptions().eventTags()).toEqual({
+ $session_id: 'session-uuid-456',
+ $ai_session_id: 'session-uuid-456',
+ })
+ })
+
+ it('eventTags callback returns empty when session uuid is undefined', async () => {
+ const server = new McpServer({ name: 'test', version: '1.0.0' })
+ const identity = createMockIdentity({
+ getSessionUuid: vi.fn().mockResolvedValue(undefined),
+ })
+
+ await initPostHogMcpAnalytics(server, identity)
+
+ expect(await getTrackOptions().eventTags()).toEqual({})
+ })
+
+ it('eventProperties callback returns PostHog MCP context properties', async () => {
+ const server = new McpServer({ name: 'test', version: '1.0.0' })
+ const identity = createMockIdentity()
+
+ await initPostHogMcpAnalytics(server, identity)
+
+ expect(await getTrackOptions().eventProperties()).toEqual({
+ $ai_product: 'mcp',
+ $mcp_version: 2,
+ $mcp_client_user_agent: 'test-agent/1.0',
+ $mcp_client_name: 'claude-code',
+ $mcp_client_version: '1.2.3',
+ $mcp_protocol_version: '2024-11-05',
+ $mcp_region: 'us',
+ $mcp_organization_id: 'org-789',
+ $mcp_project_id: 'proj-101',
+ $mcp_project_uuid: 'proj-uuid-101',
+ $mcp_project_name: 'Project 101',
+ $mcp_oauth_client_name: 'PostHog Code',
+ $mcp_read_only: true,
+ $mcp_transport: 'streamable-http',
+ $mcp_consumer: 'posthog-code',
+ $mcp_mode: 'cli',
+ $groups: {
+ organization: 'org-789',
+ project: 'proj-uuid-101',
+ },
+ })
+ })
+
+ it('eventProperties callback omits $groups when analytics context is unavailable', async () => {
+ const server = new McpServer({ name: 'test', version: '1.0.0' })
+ const identity = createMockIdentity({
+ getAnalyticsContext: vi.fn().mockResolvedValue(undefined),
+ })
+
+ await initPostHogMcpAnalytics(server, identity)
+
+ const properties = await getTrackOptions().eventProperties()
+ expect(properties.$groups).toBeUndefined()
+ expect(properties.$mcp_organization_id).toBeUndefined()
+ expect(properties.$mcp_project_uuid).toBeUndefined()
+ })
+
+ it('swallows errors if PostHog MCP analytics track throws', async () => {
+ const server = new McpServer({ name: 'test', version: '1.0.0' })
+ const identity = createMockIdentity()
+
+ vi.mocked(track).mockImplementationOnce(() => {
+ throw new Error('PostHog MCP analytics init failed')
+ })
+
+ await expect(initPostHogMcpAnalytics(server, identity)).resolves.toMatchObject({ action: 'failed' })
+ })
+
+ it('swallows errors if analytics identity resolution throws', async () => {
+ const server = new McpServer({ name: 'test', version: '1.0.0' })
+ const identity = createMockIdentity({
+ getDistinctId: vi.fn().mockRejectedValue(new Error('identity unavailable')),
+ })
+
+ await expect(initPostHogMcpAnalytics(server, identity)).resolves.toMatchObject({ action: 'failed' })
+ expect(track).not.toHaveBeenCalled()
+ })
+})