: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
fix(mcp): group sessionless tool calls by agent conversation id (#105279)
Georgis Andonis82bc08def513
diff --git a/services/mcp/src/hono/analytics.ts b/services/mcp/src/hono/analytics.tsindex 0a844961e5eb..79abef976b48 100644--- a/services/mcp/src/hono/analytics.ts+++ b/services/mcp/src/hono/analytics.ts@@ -63,7 +63,9 @@ function buildBaseProperties($mcp_protocol_version: clientIdentity.mcpProtocolVersion,$mcp_transport: requestContext.transport,$mcp_session_id: requestContext.mcpSessionId,- $mcp_conversation_id: requestContext.mcpConversationId,+ // Present only when there is a handle. An explicit `undefined` would erase the value the+ // SDK maps from its own `conversationId` field, because caller properties merge last.+ ...(requestContext.mcpConversationId ? { $mcp_conversation_id: requestContext.mcpConversationId } : {}),$mcp_consumer: clientIdentity.mcpConsumer,$mcp_mode: requestContext.mode,$mcp_region: requestContext.region,@@ -91,10 +93,10 @@ export async function trackInitEvent(state: ResolvedState): Promise<void> {try {const analyticsContext = await state.reqCtx.safelyGetAnalyticsContext(state.context)const requestContext = state.requestContext+ const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(requestContext)const initDurationMs = requestContext.requestStartTime? Date.now() - requestContext.requestStartTime: undefined- const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(requestContext)const { properties, groups } = buildBaseProperties(state, analyticsContext)@@ -105,6 +107,9 @@ export async function trackInitEvent(state: ResolvedState): Promise<void> {groups,durationMs: initDurationMs ?? 0,...(sessionUuid ? { sessionId: sessionUuid } : {}),+ // Omitted rather than set to `undefined`: the SDK applies caller properties last, so+ // an explicit `undefined` erases the value it maps from this field.+ ...(requestContext.mcpConversationId ? { conversationId: requestContext.mcpConversationId } : {}),properties: {...properties,$mcp_is_error: false,@@ -193,6 +198,9 @@ export async function trackToolCall(distinctId: state.distinctId,groups,...(sessionUuid ? { sessionId: sessionUuid } : {}),+ // Omitted rather than set to `undefined`: the SDK applies caller properties last, so+ // an explicit `undefined` erases the value it maps from this field.+ ...(requestContext.mcpConversationId ? { conversationId: requestContext.mcpConversationId } : {}),...(analyticsMeta?.intent ? { intent: analyticsMeta.intent } : {}),...(analyticsMeta?.intentSource ? { intentSource: analyticsMeta.intentSource } : {}),...(analyticsMeta?.llmModel ? { llmModel: analyticsMeta.llmModel } : {}),@@ -511,6 +519,7 @@ export function trackAuthFailure(props: RequestProperties, failure: McpAuthFailuexport async function trackToolsList(toolNames: string[], state: ResolvedState): Promise<void> {try {const analyticsContext = await state.reqCtx.safelyGetAnalyticsContext(state.context)+const requestContext = state.requestContextconst sessionUuid = await state.reqCtx.getEffectiveSessionUuid(requestContext)@@ -523,6 +532,9 @@ export async function trackToolsList(toolNames: string[], state: ResolvedState):distinctId: state.distinctId,groups,...(sessionUuid ? { sessionId: sessionUuid } : {}),+ // Omitted rather than set to `undefined`: the SDK applies caller properties last, so+ // an explicit `undefined` erases the value it maps from this field.+ ...(requestContext.mcpConversationId ? { conversationId: requestContext.mcpConversationId } : {}),properties: {...properties,tool_count: toolNames.length,diff --git a/services/mcp/src/hono/mcp-context.ts b/services/mcp/src/hono/mcp-context.tsindex 9fddb51ac776..b96feccbecbe 100644--- a/services/mcp/src/hono/mcp-context.ts+++ b/services/mcp/src/hono/mcp-context.ts@@ -55,6 +55,17 @@ export function buildMCPRequestContext(props: RequestProperties): MCPRequestCont}}+/**+ * The id a request carries to group its events by, most specific first. MCP 2026-07-28+ * removed `initialize` and the `Mcp-Session-Id` header, so for those clients only the+ * agent's handle is ever present. One definition because two callers must agree on the+ * order: `getEffectiveSessionUuid` turns this into `$session_id`, and the executor hands+ * the same value to the SDK, which mints a handle only when nothing was carried.+ */+export function resolveSessionKey(requestContext: MCPRequestContext): string | undefined {+ return requestContext.mcpConversationId ?? requestContext.sessionId ?? requestContext.mcpSessionId+}+export function buildMCPSessionAnalyticsProperties(sessionContext: MCPSessionContext | null): Record<string, unknown> {if (!sessionContext) {return {}diff --git a/services/mcp/src/hono/request-context.ts b/services/mcp/src/hono/request-context.tsindex 4c4c26c1733c..b0e4d271217e 100644--- a/services/mcp/src/hono/request-context.ts+++ b/services/mcp/src/hono/request-context.ts@@ -23,6 +23,7 @@ import {buildMCPSessionAnalyticsProperties,getEffectiveMCPClientContext,getEffectiveMCPClientIdentity,+ resolveSessionKey,type MCPRequestContext,type MCPSessionContext,} from './mcp-context'@@ -38,6 +39,7 @@ export class RequestContext {private apiInstance: ApiClient | undefinedprivate sessionManagerInstance: SessionManager | undefinedprivate distinctIdPromise: Promise<string> | undefined+ private readonly sessionUuidPromises = new Map<string, Promise<string>>()private readonly redis: RedisLikeprivate readonly env: Envprivate readonly props: RequestProperties@@ -148,23 +150,37 @@ export class RequestContext {return this.sessionManagerInstance}+ // Memoized per key because a tool call emits several events and each producer resolved+ // the same id, and because concurrent producers otherwise race to write the same mapping.async getSessionUuid(sessionId: string | undefined): Promise<string | undefined> {if (!sessionId) {return undefined}- return this.sessionManager.getSessionUuid(sessionId)+ const cached = this.sessionUuidPromises.get(sessionId)+ if (cached) {+ return cached+ }+ // Evicted on failure so a later lookup can retry. Three tool-error paths await this+ // outside a try, so a cached rejection would replace the tool's own error for the rest+ // of the request.+ const pending = this.sessionManager.getSessionUuid(sessionId).catch((error: unknown) => {+ this.sessionUuidPromises.delete(sessionId)+ throw error+ })+ this.sessionUuidPromises.set(sessionId, pending)+ return pending}/**- * Resolves the UUID emitted as `$session_id`. Prefers the explicit- * `?sessionId=` param and falls back to the MCP protocol session id, so- * sessions are still attributed for clients that don't pass an explicit- * session id. Without the fallback `$session_id` is absent on most events- * and the MCP analytics dashboard — which aggregates sessions on- * `$session_id` — counts zero.+ * Resolves the UUID emitted as `$session_id` from the first id the request+ * carried. The agent's `conversation_id` wins because MCP 2026-07-28 removed+ * `initialize` and the `Mcp-Session-Id` header, so for those clients the other+ * two are absent and every tool call would ship with no `$session_id` at all.+ * Every id here is caller-supplied, so `SessionManager` maps it to a UUID this+ * server minted instead of emitting it.*/async getEffectiveSessionUuid(requestContext: MCPRequestContext): Promise<string | undefined> {- return this.getSessionUuid(requestContext.sessionId ?? requestContext.mcpSessionId)+ return this.getSessionUuid(resolveSessionKey(requestContext))}getDistinctId(): Promise<string> {diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex b18fc9961c73..dc01f15002da 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -1,5 +1,7 @@import type { ListToolsResult } from '@modelcontextprotocol/sdk/types.js'+import type { PreparedToolCall } from '@posthog/mcp-analytics'+import {buildToolResultPayload,estimateResponseTokens,@@ -48,7 +50,7 @@ import {type ToolCallAnalyticsMeta,} from './analytics'import type { InstructionsBuilder } from './instructions'-import { getEffectiveMCPClientContext } from './mcp-context'+import { getEffectiveMCPClientContext, resolveSessionKey } from './mcp-context'import { toolCallDurationSeconds, toolCallsTotal, toolErrorsTotal } from './metrics'import type { ResolvedState } from './request-state-resolver'import type { SkillCatalogService } from './skill-catalog-service'@@ -198,12 +200,48 @@ export class ToolExecutor {rawRequestMeta && typeof rawRequestMeta === 'object' && !Array.isArray(rawRequestMeta)? (rawRequestMeta as Record<string, unknown>): undefined- const { analyticsMeta, args } = this.extractAnalyticsMetadata(toolName, rawArgs, originalTool, requestMeta)+ const { analyticsMeta, args, preparedCall } = this.extractAnalyticsMetadata(+ toolName,+ rawArgs,+ originalTool,+ requestMeta,+ state.requestContext+ )+ // In place, not copied: `RequestStateResolver` gives this one object to both the state+ // and `RequestContext`, so events emitted through `RequestContext.trackEvent` resolve the+ // same session. A batch never reaches here holding a handle, because the dispatcher+ // refuses a batch containing a modern message and a legacy client carries a session.+ if (preparedCall?.conversationId) {+ state.requestContext.mcpConversationId = preparedCall.conversationId+ }const callState = stateCarryingIntent(state, analyticsMeta.intent)const callParams = { ...params, arguments: args }+ const result = await this.dispatchToolCall(toolName, callParams, callState, analyticsMeta)+ return this.deliverConversationHandle(result, preparedCall)+ }++ // The agent can only echo a handle it has been given. One exit for every dispatch path,+ // and the SDK appends only on the call that minted the handle.+ private deliverConversationHandle(result: unknown, preparedCall: PreparedToolCall | undefined): unknown {+ if (!preparedCall?.conversationId) {+ return result+ }+ try {+ return getPostHogClient().prepareToolResult(result, preparedCall).result+ } catch {+ return result+ }+ }++ private async dispatchToolCall(+ toolName: string,+ callParams: Record<string, unknown>,+ state: ResolvedState,+ analyticsMeta: ToolCallAnalyticsMeta+ ): Promise<unknown> {if (toolName === 'exec') {- return this.callExecTool(callParams, callState, analyticsMeta)+ return this.callExecTool(callParams, state, analyticsMeta)}if (toolName === 'render-ui') {@@ -212,7 +250,7 @@ export class ToolExecutor {toolCallsTotal.inc({ tool: toolName, status: 'error' })return { content: [{ type: 'text', text: `Tool ${toolName} not found` }], isError: true }}- return this.callRenderUiTool(callParams, callState, analyticsMeta)+ return this.callRenderUiTool(callParams, state, analyticsMeta)}if (!state.allTools.some((t) => t.name === toolName)) {@@ -235,7 +273,7 @@ export class ToolExecutor {_meta: tool._meta,},callParams,- callState,+ state,analyticsMeta)}@@ -258,10 +296,21 @@ export class ToolExecutor {toolName: string,rawArgs: Record<string, unknown>,originalTool: ListToolsResult['tools'][number] | undefined,- requestMeta: Record<string, unknown> | undefined- ): { analyticsMeta: ToolCallAnalyticsMeta; args: Record<string, unknown> } {+ requestMeta: Record<string, unknown> | undefined,+ requestContext: ResolvedState['requestContext']+ ): {+ analyticsMeta: ToolCallAnalyticsMeta+ args: Record<string, unknown>+ preparedCall: PreparedToolCall | undefined+ } {try {- const prepared = getPostHogClient().prepareToolCall(toolName, rawArgs, { originalTool, requestMeta })+ const prepared = getPostHogClient().prepareToolCall(toolName, rawArgs, {+ originalTool,+ requestMeta,+ // The SDK mints a handle only when nothing was carried, so a client that already+ // has a session keeps it and never sees the prompt-back.+ sessionId: resolveSessionKey(requestContext),+ })return {analyticsMeta: {intent: prepared.intent,@@ -271,9 +320,14 @@ export class ToolExecutor {llmModelMissingReason: prepared.llmModel ? undefined : getModelMissingReason(rawArgs.llm_model),},args: prepared.args ?? rawArgs,+ preparedCall: prepared,}} catch {- return { analyticsMeta: { llmModelMissingReason: 'capture_error' }, args: rawArgs }+ return {+ analyticsMeta: { llmModelMissingReason: 'capture_error' },+ args: rawArgs,+ preparedCall: undefined,+ }}}diff --git a/services/mcp/src/index.ts b/services/mcp/src/index.tsindex 5f4f85c8ba67..373aa6014a77 100644--- a/services/mcp/src/index.ts+++ b/services/mcp/src/index.ts@@ -198,11 +198,9 @@ const handleRequest = async (// 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.+ // Agent-echoed conversation id, for wrapper apps that hold one already. Direct clients+ // carry it in the `conversation_id` tool argument instead, which the SDK reads in+ // `prepareToolCall`. Both land on the same `requestProperties.mcpConversationId` slot.const mcpConversationId = sanitizeHeaderValue(request.headers.get('mcp-conversation-id') || undefined)// Anthropic-set per-request identifier for the inner upstream client (e.g.diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.tsindex d737ffd1aef7..fe8c5f4ef34d 100644--- a/services/mcp/tests/hono/analytics.test.ts+++ b/services/mcp/tests/hono/analytics.test.ts@@ -134,6 +134,10 @@ describe('Hono MCP analytics contexts', () => {await trackInitEvent(makeState())expect(mockCaptureInitialize).toHaveBeenCalledTimes(1)+ // The SDK maps its own `conversationId` field, so the property is stamped only when a+ // handle exists. An explicit `undefined` would erase the SDK's value.+ expect(mockCaptureInitialize.mock.calls[0]![0].conversationId).toBe('conversation-request')+ expect(mockCaptureInitialize.mock.calls[0]![0].properties.$mcp_conversation_id).toBe('conversation-request')expect(mockCaptureInitialize.mock.calls[0]![0].properties).toMatchObject({$mcp_client_name: 'Claude Desktop',$mcp_client_version: '2.0',@@ -141,7 +145,6 @@ describe('Hono MCP analytics contexts', () => {$mcp_protocol_version: '2025-03-26',$mcp_transport: 'streamable-http',$mcp_session_id: 'mcp-session-request',- $mcp_conversation_id: 'conversation-request',$mcp_consumer: 'request-consumer',$mcp_mode: 'cli',$mcp_region: 'us',diff --git a/services/mcp/tests/hono/request-context.test.ts b/services/mcp/tests/hono/request-context.test.tsindex e96ccdcbc84e..af0c96ec2f70 100644--- a/services/mcp/tests/hono/request-context.test.ts+++ b/services/mcp/tests/hono/request-context.test.ts@@ -309,16 +309,43 @@ describe('RequestContext', () => {})})+ describe('getSessionUuid memoization', () => {+ it('serves one lookup per key and retries after a failure', async () => {+ const ctx = new RequestContext(fakeRedis(), env, makeProps())+ const spy = vi.spyOn(ctx.sessionManager, 'getSessionUuid')++ const first = await ctx.getSessionUuid('sess-memo')+ const second = await ctx.getSessionUuid('sess-memo')+ expect(second).toBe(first)+ expect(spy).toHaveBeenCalledTimes(1)++ // A cached rejection would outlive the blip that caused it, and three tool-error+ // paths await this outside a try.+ spy.mockRejectedValueOnce(new Error('redis down'))+ await expect(ctx.getSessionUuid('sess-retry')).rejects.toThrow('redis down')+ spy.mockRestore()+ await expect(ctx.getSessionUuid('sess-retry')).resolves.toMatch(/^[0-9a-f-]{36}$/)+ })+ })+describe('getEffectiveSessionUuid', () => {it.each([- { sessionId: 'sess-1', mcpSessionId: 'mcp-1', expectedKey: 'sess-1' },- { sessionId: undefined, mcpSessionId: 'mcp-1', expectedKey: 'mcp-1' },- { sessionId: undefined, mcpSessionId: undefined, expectedKey: undefined },+ { mcpConversationId: undefined, sessionId: 'sess-1', mcpSessionId: 'mcp-1', expectedKey: 'sess-1' },+ { mcpConversationId: undefined, sessionId: undefined, mcpSessionId: 'mcp-1', expectedKey: 'mcp-1' },+ { mcpConversationId: undefined, sessionId: undefined, mcpSessionId: undefined, expectedKey: undefined },+ { mcpConversationId: 'conv-1', sessionId: 'sess-1', mcpSessionId: 'mcp-1', expectedKey: 'conv-1' },+ // MCP 2026-07-28 sends neither of the other two, so without the handle these events+ // ship with no `$session_id`.+ { mcpConversationId: 'conv-1', sessionId: undefined, mcpSessionId: undefined, expectedKey: 'conv-1' },])(- 'sessionId=$sessionId mcpSessionId=$mcpSessionId → resolves via expectedKey=$expectedKey',- async ({ sessionId, mcpSessionId, expectedKey }) => {+ 'conversationId=$mcpConversationId sessionId=$sessionId mcpSessionId=$mcpSessionId → resolves via expectedKey=$expectedKey',+ async ({ mcpConversationId, sessionId, mcpSessionId, expectedKey }) => {const ctx = new RequestContext(fakeRedis(), env, makeProps())- const effective = await ctx.getEffectiveSessionUuid({ sessionId, mcpSessionId } as any)+ const effective = await ctx.getEffectiveSessionUuid({+ mcpConversationId,+ sessionId,+ mcpSessionId,+ } as any)expect(effective).toBe(expectedKey ? await ctx.getSessionUuid(expectedKey) : undefined)if (expectedKey) {diff --git a/services/mcp/tests/hono/tool-executor-intent.test.ts b/services/mcp/tests/hono/tool-executor-intent.test.tsindex 6267d8878dae..79c821ce2164 100644--- a/services/mcp/tests/hono/tool-executor-intent.test.ts+++ b/services/mcp/tests/hono/tool-executor-intent.test.ts@@ -306,4 +306,91 @@ describe('ToolExecutor analytics capture', () => {captureSpy.mockRestore()})++ // MCP 2026-07-28 carries no session of its own, so the agent's handle is the only one+ // these calls can group by.+ const statelessState = (): ReturnType<typeof makeToolExecutorState> =>+ makeToolExecutorState([], {+ useSingleExec: true,+ requestContext: { authMethod: 'personal_api_key', mcpProtocolVersion: '2026-07-28' } as any,+ })++ const readConversationHandle = (result: unknown): string | undefined => {+ const content = (result as { content?: { text?: string }[] }).content ?? []+ for (const part of content) {+ try {+ const parsed = JSON.parse(part.text ?? '')+ if (parsed && typeof parsed.conversation_id === 'string') {+ return parsed.conversation_id+ }+ } catch {+ continue+ }+ }+ return undefined+ }++ it('hands a session handle to a client that carries none, and groups the echoed call with it', async () => {+ const captureSpy = vi.spyOn(getPostHogClient(), 'captureToolCall').mockImplementation(() => {})+ const state = statelessState()+ await executor.handleToolsList(state)++ const first = await executor.handleToolCall({ name: 'exec', arguments: { command: 'tools' } }, state)+ const handle = readConversationHandle(first)++ expect(handle).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/)+ await vi.waitFor(() => expect(captureSpy).toHaveBeenCalledTimes(1))+ expect(captureSpy.mock.calls[0]![0].conversationId).toBe(handle)++ const second = await executor.handleToolCall(+ { name: 'exec', arguments: { command: 'tools', conversation_id: handle } },+ state+ )++ await vi.waitFor(() => expect(captureSpy).toHaveBeenCalledTimes(2))+ expect(captureSpy.mock.calls[1]![0].conversationId).toBe(handle)+ // `RequestContext` holds this same object; a copy would leave its events sessionless.+ expect(state.requestContext.mcpConversationId).toBe(handle)+ // Repeating it would spend tokens telling the agent what it just told us.+ expect(readConversationHandle(second)).toBeUndefined()+ expect((second as { isError?: boolean }).isError).toBeFalsy()++ captureSpy.mockRestore()+ })++ it('leaves a client that already has a session untouched', async () => {+ const captureSpy = vi.spyOn(getPostHogClient(), 'captureToolCall').mockImplementation(() => {})+ // `makeToolExecutorState` carries `sessionId: 'sess-1'`, the wrapper-app id.+ const state = makeToolExecutorState([], { useSingleExec: true })+ await executor.handleToolsList(state)++ const result = await executor.handleToolCall({ name: 'exec', arguments: { command: 'tools' } }, state)++ // Minting here would split the session these clients already group by, and append a+ // block to every first result, for the majority of today's traffic.+ expect(readConversationHandle(result)).toBeUndefined()+ await vi.waitFor(() => expect(captureSpy).toHaveBeenCalledTimes(1))+ expect(captureSpy.mock.calls[0]![0].conversationId).toBeUndefined()++ captureSpy.mockRestore()+ })++ it('keeps the handle a wrapper app sent on the conversation header', async () => {+ const captureSpy = vi.spyOn(getPostHogClient(), 'captureToolCall').mockImplementation(() => {})+ const state = makeToolExecutorState([], {+ useSingleExec: true,+ requestContext: { authMethod: 'personal_api_key', mcpConversationId: 'conv-from-header' } as any,+ })+ await executor.handleToolsList(state)++ const result = await executor.handleToolCall({ name: 'exec', arguments: { command: 'tools' } }, state)++ // The header is the app's own grouping. Minting over it would replace that app's+ // conversation with a fresh handle on every call.+ expect(readConversationHandle(result)).toBeUndefined()+ await vi.waitFor(() => expect(captureSpy).toHaveBeenCalledTimes(1))+ expect(captureSpy.mock.calls[0]![0].conversationId).toBe('conv-from-header')++ captureSpy.mockRestore()+ })})