: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): tag mcp_tool_call events with mcp session id (#58471)
Lucas Ricoy4be7a520b070
diff --git a/services/mcp/src/index.ts b/services/mcp/src/index.tsindex d63c2efaf34e..b24a1415a8e0 100644--- a/services/mcp/src/index.ts+++ b/services/mcp/src/index.ts@@ -346,10 +346,24 @@ const handleRequest = async (// synchronously via `RequestProperties`.const clientInfo = await extractClientInfoFromBody(request)+ // Streamable-HTTP transport session id, minted by the MCP server on+ // initialize and echoed back on every subsequent request. Absent on the+ // initialize call itself. Distinct from `sessionId` (above), which is the+ // wrapper-app-provided analytics correlation id.+ const mcpSessionId = sanitizeHeaderValue(request.headers.get('mcp-session-id') || undefined)+ // Agent-echoed conversation id from `@posthog/mcp-analytics` PR #14.+ // Caller-supplied for now (wrapper apps can pass it via the header even+ // before the SDK lands). Once the SDK is bumped with `enableConversationId`,+ // the same value will also flow in from tool args — both sources land on+ // the same `requestProperties.mcpConversationId` slot.+ const mcpConversationId = sanitizeHeaderValue(request.headers.get('mcp-conversation-id') || undefined)+Object.assign(ctx.props, {apiToken: token,userHash: hash(token),sessionId: sessionId || undefined,+ mcpSessionId,+ mcpConversationId,organizationId,projectId,clientUserAgent,diff --git a/services/mcp/src/lib/mcpcat.ts b/services/mcp/src/lib/mcpcat.tsindex 9cbc1a417aaa..0a0ad2c32d50 100644--- a/services/mcp/src/lib/mcpcat.ts+++ b/services/mcp/src/lib/mcpcat.ts@@ -7,6 +7,10 @@ import type { MCPAnalyticsContext } from '@/lib/analytics'/** Provider interface for resolving user/session identity and workspace context. */export type McpCatIdentityProvider = {getDistinctId: () => Promise<string>+ // PostHog-side session UUID. Resolved from the wrapper-app `?sessionId=`+ // query hint via `SessionManager.getSessionUuid()` and used as `$session_id`+ // / `$ai_session_id` to drive Session Replay and LLM Analytics grouping.+ // Only set when a wrapping consumer app supplied the hint.getSessionUuid: () => Promise<string | undefined>getMcpClientName: () => Promise<string | undefined>getMcpClientVersion: () => Promise<string | undefined>@@ -20,6 +24,18 @@ export type McpCatIdentityProvider = {getTransport: () => Promise<string | undefined>getMcpConsumer: () => Promise<string | undefined>getMcpMode: () => Promise<string | undefined>+ // Streamable-HTTP transport session id from the inbound `Mcp-Session-Id`+ // header. Distinct from `getSessionUuid()` above: this one is minted by+ // the MCP server per the protocol spec and is available on (almost) every+ // request, whereas `getSessionUuid()` only resolves when a wrapper app+ // also supplied a `?sessionId=` hint. Emitted on events as `mcp_session_id`.+ getMcpSessionId: () => Promise<string | undefined>+ // Agent-echoed conversation id from `@posthog/mcp-analytics` PR #14+ // (`enableConversationId: true`). Persists across transport reconnects.+ // Sourced from tool-call arguments by the SDK; we scaffold the property+ // here so it lands on events once the SDK is bumped. Returns undefined+ // until that wiring is in place.+ getMcpConversationId: () => Promise<string | undefined>}export function redactSensitiveInformation(text: string): string {@@ -79,6 +95,8 @@ export async function initMcpCatObservability(server: McpServer, identity: McpCatransport,mcpConsumer,mcpMode,+ mcpSessionId,+ mcpConversationId,] = await Promise.all([identity.getMcpVersion(),identity.getClientUserAgent(),@@ -92,6 +110,8 @@ export async function initMcpCatObservability(server: McpServer, identity: McpCaidentity.getTransport(),identity.getMcpConsumer(),identity.getMcpMode(),+ identity.getMcpSessionId(),+ identity.getMcpConversationId(),])// `$groups` is the raw event-payload key; mcpcat doesn't expose a typed@@ -118,6 +138,8 @@ export async function initMcpCatObservability(server: McpServer, identity: McpCamcp_transport: transport,mcp_consumer: mcpConsumer,mcp_mode: mcpMode,+ mcp_session_id: mcpSessionId,+ mcp_conversation_id: mcpConversationId,...(Object.keys(groups).length > 0 ? { $groups: groups } : {}),}},diff --git a/services/mcp/src/lib/posthog-mcp-analytics.ts b/services/mcp/src/lib/posthog-mcp-analytics.tsindex 230ca501ac74..d1bd7f8f79ce 100644--- a/services/mcp/src/lib/posthog-mcp-analytics.ts+++ b/services/mcp/src/lib/posthog-mcp-analytics.ts@@ -60,6 +60,8 @@ async function buildEventProperties(identity: PostHogMcpAnalyticsIdentityProvidetransport,mcpConsumer,mcpMode,+ mcpSessionId,+ mcpConversationId,] = await Promise.all([identity.getMcpVersion(),identity.getClientUserAgent(),@@ -73,6 +75,8 @@ async function buildEventProperties(identity: PostHogMcpAnalyticsIdentityProvideidentity.getTransport(),identity.getMcpConsumer(),identity.getMcpMode(),+ identity.getMcpSessionId(),+ identity.getMcpConversationId(),])const groups = {@@ -97,6 +101,8 @@ async function buildEventProperties(identity: PostHogMcpAnalyticsIdentityProvide$mcp_transport: transport,$mcp_consumer: mcpConsumer,$mcp_mode: mcpMode,+ $mcp_session_id: mcpSessionId,+ $mcp_conversation_id: mcpConversationId,...(Object.keys(groups).length > 0 ? { $groups: groups } : {}),}}diff --git a/services/mcp/src/mcp.ts b/services/mcp/src/mcp.tsindex 0fa0d972876e..6c914298573c 100644--- a/services/mcp/src/mcp.ts+++ b/services/mcp/src/mcp.ts@@ -53,7 +53,23 @@ type PostHogMcpAnalyticsFlagResult = {export type RequestProperties = {userHash: stringapiToken: string+ // Wrapper-app-provided hint from `?sessionId=` query param. Resolved to a+ // UUID via `SessionManager.getSessionUuid()` and emitted as `$session_id`+ // for Session Replay / LLM Analytics grouping. Only set by wrapping+ // consumer apps (setup wizard, sandbox, etc.).sessionId?: string+ // Streamable-HTTP transport session id (`Mcp-Session-Id` HTTP header).+ // Server-minted per the MCP protocol spec, present on every request after+ // initialize. Distinct from `sessionId` above — this is the transport's+ // own correlation key, available for direct MCP clients (Claude Code,+ // Cursor, …) that never set the wrapper-app `?sessionId=` hint.+ mcpSessionId?: string+ // Agent-echoed conversation id from `@posthog/mcp-analytics` PR #14+ // (`enableConversationId: true`). Plumbed alongside `mcpSessionId`+ // through every identity-provider + emitter path so the consumer side+ // is ready to read it; the producer-side source lands when that SDK+ // PR ships and a header read is wired into `index.ts`.+ mcpConversationId?: stringfeatures?: string[]tools?: string[]region?: string@@ -344,6 +360,12 @@ export class MCP extends McpAgent<Env> {...(this.mcpProtocolVersion ? { mcp_protocol_version: this.mcpProtocolVersion } : {}),...(this.requestProperties.mcpConsumer ? { mcp_consumer: this.requestProperties.mcpConsumer } : {}),...(this.requestProperties.transport ? { mcp_transport: this.requestProperties.transport } : {}),+ ...(this.requestProperties.mcpSessionId+ ? { mcp_session_id: this.requestProperties.mcpSessionId }+ : {}),+ ...(this.requestProperties.mcpConversationId+ ? { mcp_conversation_id: this.requestProperties.mcpConversationId }+ : {}),...(this.mcpMode ? { mcp_mode: this.mcpMode } : {}),...(this.mcpVersion !== undefined ? { mcp_version: this.mcpVersion } : {}),...contextProperties,@@ -741,6 +763,8 @@ export class MCP extends McpAgent<Env> {getTransport: async () => this.requestProperties.transport,getMcpConsumer: async () => this.requestProperties.mcpConsumer,getMcpMode: async () => this.mcpMode,+ getMcpSessionId: async () => this.requestProperties.mcpSessionId,+ getMcpConversationId: async () => this.requestProperties.mcpConversationId,}Object.assign(this.requestProperties, {diff --git a/services/mcp/tests/unit/mcpcat.test.ts b/services/mcp/tests/unit/mcpcat.test.tsindex 74e7eafe8724..b94eb47004c4 100644--- a/services/mcp/tests/unit/mcpcat.test.ts+++ b/services/mcp/tests/unit/mcpcat.test.ts@@ -60,6 +60,8 @@ describe('initMcpCatObservability', () => {getTransport: vi.fn().mockResolvedValue('streamable-http'),getMcpConsumer: vi.fn().mockResolvedValue('posthog-code'),getMcpMode: vi.fn().mockResolvedValue('cli'),+ getMcpSessionId: vi.fn().mockResolvedValue('mcp-session-abc'),+ getMcpConversationId: vi.fn().mockResolvedValue('mcp-conversation-xyz'),...overrides,}}@@ -190,6 +192,8 @@ describe('initMcpCatObservability', () => {mcp_transport: 'streamable-http',mcp_consumer: 'posthog-code',mcp_mode: 'cli',+ mcp_session_id: 'mcp-session-abc',+ mcp_conversation_id: 'mcp-conversation-xyz',$groups: {organization: 'org-789',project: 'proj-uuid-101',@@ -218,6 +222,8 @@ describe('initMcpCatObservability', () => {mcp_transport: 'streamable-http',mcp_consumer: 'posthog-code',mcp_mode: 'cli',+ mcp_session_id: 'mcp-session-abc',+ mcp_conversation_id: 'mcp-conversation-xyz',$groups: { organization: 'org-789' },},},@@ -236,6 +242,8 @@ describe('initMcpCatObservability', () => {getTransport: vi.fn().mockResolvedValue(undefined),getMcpConsumer: vi.fn().mockResolvedValue(undefined),getMcpMode: vi.fn().mockResolvedValue(undefined),+ getMcpSessionId: vi.fn().mockResolvedValue(undefined),+ getMcpConversationId: vi.fn().mockResolvedValue(undefined),},expected: {ai_product: 'mcp',@@ -254,6 +262,8 @@ describe('initMcpCatObservability', () => {mcp_transport: undefined,mcp_consumer: undefined,mcp_mode: undefined,+ mcp_session_id: undefined,+ mcp_conversation_id: undefined,},},])('eventProperties: $name', async ({ overrides, expected }) => {diff --git a/services/mcp/tests/unit/posthog-mcp-analytics.test.ts b/services/mcp/tests/unit/posthog-mcp-analytics.test.tsindex a05de6e73b42..3efdc5b310f6 100644--- a/services/mcp/tests/unit/posthog-mcp-analytics.test.ts+++ b/services/mcp/tests/unit/posthog-mcp-analytics.test.ts@@ -39,6 +39,8 @@ describe('initPostHogMcpAnalytics', () => {getTransport: vi.fn().mockResolvedValue('streamable-http'),getMcpConsumer: vi.fn().mockResolvedValue('posthog-code'),getMcpMode: vi.fn().mockResolvedValue('cli'),+ getMcpSessionId: vi.fn().mockResolvedValue('mcp-session-abc'),+ getMcpConversationId: vi.fn().mockResolvedValue('mcp-conversation-xyz'),...overrides,}}@@ -202,6 +204,8 @@ describe('initPostHogMcpAnalytics', () => {$mcp_transport: 'streamable-http',$mcp_consumer: 'posthog-code',$mcp_mode: 'cli',+ $mcp_session_id: 'mcp-session-abc',+ $mcp_conversation_id: 'mcp-conversation-xyz',$groups: {organization: 'org-789',project: 'proj-uuid-101',