: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
feat(mcp): migrate hono analytics to PostHogMCP (@posthog/[email protected]) (#63280)
Lucas Faria2d64f4c64b41
diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.jsonindex 9b2ff85ebe61..ccb7d459066e 100644--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json@@ -3381,6 +3381,42 @@"description_llm": "Identifies an anonymous user. The event shows how many users used an account, so do not use it for active users metrics because a user may skip identification.","label": "Identify"},+ "$mcp_custom": {+ "description": "A custom MCP analytics event emitted by a server through the SDK's custom-event API. Properties depend on what the caller passed.",+ "label": "MCP custom event"+ },+ "$mcp_initialize": {+ "description": "Fires when an MCP client completes the handshake with the server. Carries the client and server name/version so you can break down usage by client. Canonical replacement for the legacy `mcp_initialize`.",+ "label": "MCP initialize"+ },+ "$mcp_missing_capability": {+ "description": "Fires when an agent reports functionality it couldn't find via the `get_more_tools` virtual tool (when `reportMissing` is enabled). Carries the agent's reasoning in `$mcp_intent` \u2014 a capability gap, not a tool invocation.",+ "label": "MCP missing capability"+ },+ "$mcp_prompt_get": {+ "description": "Fires when an MCP prompt is fetched by a client. Includes the prompt name.",+ "label": "MCP prompt fetched"+ },+ "$mcp_prompts_list": {+ "description": "Fires when an MCP client requests the list of available prompts.",+ "label": "MCP prompts listed"+ },+ "$mcp_resource_read": {+ "description": "Fires when an MCP resource is fetched by a client. Includes the resource name.",+ "label": "MCP resource read"+ },+ "$mcp_resources_list": {+ "description": "Fires when an MCP client requests the list of available resources.",+ "label": "MCP resources listed"+ },+ "$mcp_tool_call": {+ "description": "Fires every time an MCP server tool is invoked via @posthog/mcp. Includes the tool name, wall-clock duration, error state, and (when the client supplied a context argument) the agent's stated intent. Canonical replacement for the legacy `mcp_tool_call`.",+ "label": "MCP tool call"+ },+ "$mcp_tools_list": {+ "description": "Fires when an MCP client requests the list of available tools. Useful for measuring discovery \u2014 whether new clients are finding the server. Canonical replacement for the legacy `mcp_tools_list`.",+ "label": "MCP tools listed"+ },"$merge_dangerously": {"description": "An alias ID has been added to a user.","ignored_in_assistant": true,@@ -7583,4 +7619,4 @@"label": "Web vitals LCP"}}-}+}\ No newline at end of filediff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 16420a62cf8e..5b58a9f01499 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3912,8 +3912,8 @@ importers:specifier: ^1.29.0version: 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])'+ specifier: npm:@posthog/[email protected]+ version: '@posthog/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])''@posthog/quill':specifier: workspace:*version: link:../../packages/quill/packages/quill@@ -9242,8 +9242,8 @@ 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-vwOEMfZvGv5XxNWV7p9I52NSmvFNMhyW2IHpIoUHW5jLkgUrknzJW1H/qxVGSIrNNVQkfsoaDFzDhJdg10pgrA==}'@posthog/[email protected]':resolution: {integrity: sha512-xmc6JGLS+HK9gG354e3ws8wRQSQFaekI/QC/uwslokfG1csXjxW7xlGGipLS4juDJ1W1fVM6j2MeHyatmvF22w==}@@ -9282,11 +9282,12 @@ packages:react: 18.3.1react-dom: 18.3.1- '@posthog/[email protected]':- resolution: {integrity: sha512-Tcz5fGpG0ZCtA94jDhmQigHA49K4UVhkbBGgn+w7pZXiXPkDCPO0ZXtuRXdPgyO/l1WW9RB27D9pR2fvLmT+Mg==}- engines: {node: '>=22.22.0'}+ '@posthog/[email protected]':+ resolution: {integrity: sha512-G3+CuVSkm77wpuZlqcbLEaffezsIR4oJrR2ufctHnk1RcqJchU/0FzV5LA02oRuqj2mmB0bzd8F0BXSqBxbLug==}+ engines: {node: ^20.20.0 || >=22.22.0}peerDependencies:'@modelcontextprotocol/sdk': ^1.29.0+ posthog-node: ^5.0.0'@posthog/[email protected]':resolution: {integrity: sha512-lVdTsWT5+PtHBu44gSQ7QohbLjAYqHkFAIGAQ+HV8Eh9yj+OcnQ7mXCmyhaMlTBD3z7D0H1eWMp4vQaFnsIyWQ==}@@ -9301,8 +9302,8 @@ packages:'@posthog/[email protected]':resolution: {integrity: sha512-JUFk57H89fOnHpF62FDyFGw4uXeHAX20OPfkLL8/iqg/xrVp5Q21LvJUDijmS5wt0avgUwXF2bxYgaZ5iWRmAg==}- '@posthog/[email protected]':- resolution: {integrity: sha512-B7k9S+H9WUKHXxe1HOkQWbpWtMcrBvsodm5stZaLQ3pYxf9TowtwssdzTtX4hHjzSYqgrS1IpNnJX4vs1KgBzA==}+ '@posthog/[email protected]':+ resolution: {integrity: sha512-LqJoiQi2eyWn7rCUgnn+D+F3Efp6+04o72bjSX6kWHx0nFaYNC/nJuAIRliDTY/X7GPIUAaHAcSjbMI/9wfX1Q==}'@posthog/[email protected]':resolution: {integrity: sha512-UgE9+5+wkZg7yc2MpW5G32/6zYW8fAbXJkG8WGnrb4X8OKWzNa9cWeNCd82vKok+TSoRpM4qiYQFtBSpJS1dsw==}@@ -19397,15 +19398,6 @@ 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-Q+/tYsFU9r7xoOJ+y/ZTtdVQwTWfzjbiXBDMM/JKUux3+QPP02iUuIoeBQ+Ot6oEDlC+/PGjB/5A3K7KKb7hcw==}@@ -30165,9 +30157,9 @@ snapshots:dependencies:cross-spawn: 7.0.6- '@posthog/[email protected]':+ '@posthog/[email protected]':dependencies:- '@posthog/types': 1.372.9+ '@posthog/types': 1.386.3'@posthog/[email protected]':dependencies:@@ -30210,12 +30202,11 @@ snapshots:react: 18.3.1react-dom: 18.3.1([email protected])- '@posthog/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])':+ '@posthog/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])':dependencies:'@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])- posthog-node: 5.33.3([email protected])- transitivePeerDependencies:- - rxjs+ '@posthog/core': 1.32.3+ posthog-node: 5.25.0dependencies:@@ -30226,7 +30217,7 @@ snapshots:'@posthog/[email protected]': {}- '@posthog/[email protected]': {}+ '@posthog/[email protected]': {}'@posthog/[email protected]': {}@@ -43198,12 +43189,6 @@ snapshots:dependencies:'@posthog/core': 1.23.1- dependencies:- '@posthog/core': 1.28.3- optionalDependencies:- rxjs: 7.8.1-diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.pyindex 5c2ac4a4db99..e47437abf31f 100644--- a/posthog/taxonomy/taxonomy.py+++ b/posthog/taxonomy/taxonomy.py@@ -291,11 +291,50 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {"label": "Deep link opened","description": "When a user opens the mobile app via a deep link.",},- # Events emitted by the @posthog/mcp analytics SDK. @posthog/mcp is rolled out behind a- # feature flag (currently enabled only for some PostHog staff for internal testing). For- # traffic where it's enabled, these events fire *alongside* the older events further down;- # for traffic where it's not, only the older events fire. Once @posthog/mcp reaches general- # availability the older events will be retired.+ # Canonical events emitted by the @posthog/mcp analytics SDK. PostHog-owned events are+ # always `$`-prefixed, so these `$mcp_*` names are the final, going-forward names. They+ # fire alongside the legacy non-`$` names just below (which the server dual-emits during+ # the cutover so existing dashboards keep working) — those legacy names are being retired.+ "$mcp_tool_call": {+ "label": "MCP tool call",+ "description": "Fires every time an MCP server tool is invoked via @posthog/mcp. Includes the tool name, wall-clock duration, error state, and (when the client supplied a context argument) the agent's stated intent. Canonical replacement for the legacy `mcp_tool_call`.",+ },+ "$mcp_tools_list": {+ "label": "MCP tools listed",+ "description": "Fires when an MCP client requests the list of available tools. Useful for measuring discovery — whether new clients are finding the server. Canonical replacement for the legacy `mcp_tools_list`.",+ },+ "$mcp_initialize": {+ "label": "MCP initialize",+ "description": "Fires when an MCP client completes the handshake with the server. Carries the client and server name/version so you can break down usage by client. Canonical replacement for the legacy `mcp_initialize`.",+ },+ "$mcp_resources_list": {+ "label": "MCP resources listed",+ "description": "Fires when an MCP client requests the list of available resources.",+ },+ "$mcp_resource_read": {+ "label": "MCP resource read",+ "description": "Fires when an MCP resource is fetched by a client. Includes the resource name.",+ },+ "$mcp_prompts_list": {+ "label": "MCP prompts listed",+ "description": "Fires when an MCP client requests the list of available prompts.",+ },+ "$mcp_prompt_get": {+ "label": "MCP prompt fetched",+ "description": "Fires when an MCP prompt is fetched by a client. Includes the prompt name.",+ },+ "$mcp_custom": {+ "label": "MCP custom event",+ "description": "A custom MCP analytics event emitted by a server through the SDK's custom-event API. Properties depend on what the caller passed.",+ },+ "$mcp_missing_capability": {+ "label": "MCP missing capability",+ "description": "Fires when an agent reports functionality it couldn't find via the `get_more_tools` virtual tool (when `reportMissing` is enabled). Carries the agent's reasoning in `$mcp_intent` — a capability gap, not a tool invocation.",+ },+ # Legacy in-tree @posthog/mcp event names (non-`$`-prefixed). These were emitted by the+ # MCP server's hand-rolled analytics path before it moved onto the SDK. The server now+ # dual-emits them alongside the canonical `$mcp_*` names above so existing insights keep+ # working through the cutover; they will be removed once those insights are migrated."mcp_tool_call": {"label": "MCP tool call","description": "Fires every time an MCP server tool is invoked. Includes the tool name, wall-clock duration, error state, and (when the client supplied a context argument) the agent's stated intent.",diff --git a/services/mcp/package.json b/services/mcp/package.jsonindex e5d4fa0eb54f..96e19256a37a 100644--- a/services/mcp/package.json+++ b/services/mcp/package.json@@ -45,7 +45,7 @@"@hono/node-server": "^2.0.2","@modelcontextprotocol/ext-apps": "^1.5.0","@modelcontextprotocol/sdk": "^1.29.0",- "@posthog/mcp-analytics": "npm:@posthog/[email protected]",+ "@posthog/mcp-analytics": "npm:@posthog/[email protected]","@posthog/quill": "workspace:*","@posthog/quill-charts": "workspace:*","@toon-format/toon": "^2.1.0",diff --git a/services/mcp/src/hono/analytics.ts b/services/mcp/src/hono/analytics.tsindex 8a883e55f78b..3b688acb8d7f 100644--- a/services/mcp/src/hono/analytics.ts+++ b/services/mcp/src/hono/analytics.ts@@ -66,6 +66,28 @@ export async function trackInitEvent(state: ResolvedState): Promise<void> {const { properties, groups } = buildBaseProperties(state, analyticsContext)+ // Emits `$mcp_initialize`. The SDK maps `durationMs` → `$mcp_duration_ms`+ // and `sessionId` → `$session_id`; everything else rides on `properties`.+ getPostHogClient().captureInitialize({+ distinctId: state.distinctId,+ groups,+ durationMs: initDurationMs ?? 0,+ ...(sessionUuid ? { sessionId: sessionUuid } : {}),+ properties: {+ ...properties,+ $mcp_is_error: false,+ tool_count: state.allTools.length,+ has_organization_id: !!requestContext.organizationId,+ has_project_id: !!requestContext.projectId,+ read_only: !!requestContext.readOnly,+ via_sse_redirect: !!requestContext.viaSseRedirect,+ },+ })++ // TRANSITION SHIM — DELETE once the MCP insights + taxonomy are migrated to+ // the `$mcp_*` event names. `$mcp_initialize` (above) is the canonical event+ // going forward, but the existing dashboards/insights still key on the legacy+ // `mcp_initialize`, so we dual-emit it through the cutover to keep them working.getPostHogClient().capture({distinctId: state.distinctId,event: 'mcp_initialize',@@ -112,6 +134,29 @@ export async function trackToolCall(// buckets those as "Uncategorized".const toolCategory = getToolCategory(toolName)+ // Emits `$mcp_tool_call` (+ `$mcp_is_error`). The SDK maps `toolName` →+ // `$mcp_tool_name`, `durationMs` → `$mcp_duration_ms`, `isError` →+ // `$mcp_is_error`, and `sessionId` → `$session_id`. `$exception` fan-out+ // is disabled on the client, so an errored call stays a single event.+ getPostHogClient().captureToolCall({+ toolName,+ durationMs,+ isError,+ distinctId: state.distinctId,+ groups,+ ...(sessionUuid ? { sessionId: sessionUuid } : {}),+ properties: {+ ...properties,+ tool_name: toolName,+ ...(toolCategory ? { $mcp_tool_category: toolCategory } : {}),+ ...extraProperties,+ },+ })++ // TRANSITION SHIM — DELETE once the MCP insights + taxonomy are migrated to+ // the `$mcp_*` event names. `$mcp_tool_call` (above) is the canonical event+ // going forward, but the existing dashboards/insights still key on the legacy+ // `mcp_tool_call`, so we dual-emit it through the cutover to keep them working.getPostHogClient().capture({distinctId: state.distinctId,event: 'mcp_tool_call',diff --git a/services/mcp/src/lib/posthog/client.ts b/services/mcp/src/lib/posthog/client.tsindex c43066984335..6e49924eac79 100644--- a/services/mcp/src/lib/posthog/client.ts+++ b/services/mcp/src/lib/posthog/client.ts@@ -1,15 +1,24 @@-import { PostHog } from 'posthog-node'+import { PostHogMCP } from '@posthog/mcp-analytics'import { env } from '@/lib/env'-let _client: PostHog | undefined-export const getPostHogClient = (): PostHog => {+let _client: PostHogMCP | undefined++// `PostHogMCP` is a drop-in subclass of posthog-node's `PostHog` (capture /+// identify / flush / shutdown all inherited) that adds `captureToolCall` /+// `captureInitialize`. Using it for the shared client means every existing+// `.capture()` callsite keeps working while the hono analytics path gets the+// canonical `$mcp_*` event helpers.+export const getPostHogClient = (): PostHogMCP => {if (!_client) {- _client = new PostHog(env.POSTHOG_ANALYTICS_API_KEY ?? '', {+ _client = new PostHogMCP(env.POSTHOG_ANALYTICS_API_KEY ?? '', {disabled: !env.POSTHOG_ANALYTICS_API_KEY || !env.POSTHOG_ANALYTICS_HOST, // Disable if the API key or host is not set...(env.POSTHOG_ANALYTICS_HOST ? { host: env.POSTHOG_ANALYTICS_HOST } : {}),flushAt: 1,flushInterval: 0,+ // Tool errors already surface as `$mcp_is_error: true`; keep the SDK+ // from fanning out a separate `$exception` event into Error Tracking.+ enableExceptionAutocapture: false,})}diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.tsindex 8d99a4d2e03f..a481e7ee9d4c 100644--- a/services/mcp/tests/hono/analytics.test.ts+++ b/services/mcp/tests/hono/analytics.test.ts@@ -1,11 +1,16 @@import { beforeEach, describe, expect, it, vi } from 'vitest'-const { mockCapture } = vi.hoisted(() => ({+const { mockCaptureToolCall, mockCaptureInitialize, mockCapture } = vi.hoisted(() => ({+ mockCaptureToolCall: vi.fn(),+ mockCaptureInitialize: vi.fn(),+ // `capture` backs the temporary dual-emit of the legacy `mcp_*` event names.mockCapture: vi.fn(),}))vi.mock('@/lib/posthog', () => ({getPostHogClient: vi.fn(() => ({+ captureToolCall: mockCaptureToolCall,+ captureInitialize: mockCaptureInitialize,capture: mockCapture,})),}))@@ -62,14 +67,27 @@ function makeState(overrides: Partial<ResolvedState> = {}): ResolvedState {describe('Hono MCP analytics contexts', () => {beforeEach(() => {+ mockCaptureToolCall.mockClear()+ mockCaptureInitialize.mockClear()mockCapture.mockClear()})+ it('dual-emits the legacy mcp_tool_call / mcp_initialize names during the cutover', async () => {+ // TRANSITION SHIM coverage — delete alongside the dual-emit once insights+ // are migrated to the `$mcp_*` names.+ await trackInitEvent(makeState())+ await trackToolCall('user-get', 12, false, makeState())++ const legacyEvents = mockCapture.mock.calls.map((c) => c[0].event)+ expect(legacyEvents).toContain('mcp_initialize')+ expect(legacyEvents).toContain('mcp_tool_call')+ })+it('emits request properties on $mcp fields and session properties on mcp_session fields', async () => {await trackInitEvent(makeState())- expect(mockCapture).toHaveBeenCalledTimes(1)- expect(mockCapture.mock.calls[0]![0].properties).toMatchObject({+ expect(mockCaptureInitialize).toHaveBeenCalledTimes(1)+ expect(mockCaptureInitialize.mock.calls[0]![0].properties).toMatchObject({$mcp_client_name: 'Claude Desktop',$mcp_client_version: '2.0',$mcp_client_user_agent: 'request-agent/1.0',@@ -92,7 +110,7 @@ describe('Hono MCP analytics contexts', () => {it('omits session properties when there is no MCP session context', async () => {await trackToolCall('user-get', 12, false, makeState({ sessionContext: null }))- const properties = mockCapture.mock.calls[0]![0].properties+ const properties = mockCaptureToolCall.mock.calls[0]![0].propertiesexpect(properties.$mcp_client_name).toBe('Claude Desktop')expect(properties.mcp_session_client_name).toBeUndefined()expect(properties.mcp_session_vendor_client).toBeUndefined()@@ -101,12 +119,12 @@ describe('Hono MCP analytics contexts', () => {it('stamps $mcp_tool_category from the catalogued tool definition', async () => {await trackToolCall('query-logs', 5, false, makeState())- expect(mockCapture.mock.calls[0]![0].properties.$mcp_tool_category).toBe('Logs')+ expect(mockCaptureToolCall.mock.calls[0]![0].properties.$mcp_tool_category).toBe('Logs')})it('omits $mcp_tool_category for tools without a catalogued definition', async () => {await trackToolCall('exec', 5, false, makeState())- expect(mockCapture.mock.calls[0]![0].properties).not.toHaveProperty('$mcp_tool_category')+ expect(mockCaptureToolCall.mock.calls[0]![0].properties).not.toHaveProperty('$mcp_tool_category')})})diff --git a/services/mcp/tests/hono/setup.ts b/services/mcp/tests/hono/setup.tsindex 2369e257401d..1e27e7a4b90c 100644--- a/services/mcp/tests/hono/setup.ts+++ b/services/mcp/tests/hono/setup.ts@@ -28,10 +28,6 @@ vi.mock('@/resources/ui-apps', async (importOriginal) => {vi.mock('@/resources/ui-apps.generated', async (importOriginal) => importOriginal())-vi.mock('@posthog/mcp-analytics', () => ({- track: vi.fn(),-}))-// Mock template imports that may not existvi.mock('@/templates/cli-proxy-command.md', async () => {try {diff --git a/services/mcp/tests/setup.ts b/services/mcp/tests/setup.tsindex 220df02869df..4ad58961f811 100644--- a/services/mcp/tests/setup.ts+++ b/services/mcp/tests/setup.ts@@ -5,11 +5,6 @@ import { vi } from 'vitest'// Load .env.test fileconfig({ path: resolve(process.cwd(), '.env.test') })-// 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 environmentvi.mock('cloudflare:workers', () => ({env: {diff --git a/services/mcp/tests/unit/feature-flag-version.test.ts b/services/mcp/tests/unit/feature-flag-version.test.tsindex c97d5e7a79d5..382027379c0a 100644--- a/services/mcp/tests/unit/feature-flag-version.test.ts+++ b/services/mcp/tests/unit/feature-flag-version.test.ts@@ -2,12 +2,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'const mockIsFeatureEnabled = vi.fn()const mockGetAllFlags = vi.fn()-vi.mock('posthog-node', () => ({- PostHog: vi.fn().mockImplementation(function () {- return {- isFeatureEnabled: mockIsFeatureEnabled,- getAllFlags: mockGetAllFlags,- }+// Mock the client `flags.ts` consumes, not posthog-node directly: `getPostHogClient()`+// returns a `PostHogMCP` (a posthog-node subclass) from the externalized+// `@posthog/mcp-analytics`, whose internal posthog-node import a `vi.mock('posthog-node')`+// here would not intercept.+vi.mock('@/lib/posthog/client', () => ({+ getPostHogClient: () => ({+ isFeatureEnabled: mockIsFeatureEnabled,+ getAllFlags: mockGetAllFlags,}),}))