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): fall back to mcp session id for $session_id (#64852)

Georgis Andonis690a64789a4f
diff --git a/services/mcp/src/hono/analytics.ts b/services/mcp/src/hono/analytics.ts
index 7365d0ad343f..969354c9fcf4 100644
--- a/services/mcp/src/hono/analytics.ts
+++ b/services/mcp/src/hono/analytics.ts
@@ -62,9 +62,7 @@ export async function trackInitEvent(state: ResolvedState): Promise<void> {
const initDurationMs = requestContext.requestStartTime
? Date.now() - requestContext.requestStartTime
: undefined
- const sessionUuid = requestContext.sessionId
- ? await state.reqCtx.getSessionUuid(requestContext.sessionId)
- : undefined
+ const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(requestContext)
const { properties, groups } = buildBaseProperties(state, analyticsContext)
@@ -129,9 +127,7 @@ export async function trackToolCall(
try {
const analyticsContext = await state.reqCtx.safelyGetAnalyticsContext(state.context)
const requestContext = state.requestContext
- const sessionUuid = requestContext.sessionId
- ? await state.reqCtx.getSessionUuid(requestContext.sessionId)
- : undefined
+ const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(requestContext)
const { properties, groups } = buildBaseProperties(state, analyticsContext)
@@ -196,9 +192,7 @@ export async function trackToolsList(toolNames: string[], state: ResolvedState):
try {
const analyticsContext = await state.reqCtx.safelyGetAnalyticsContext(state.context)
const requestContext = state.requestContext
- const sessionUuid = requestContext.sessionId
- ? await state.reqCtx.getSessionUuid(requestContext.sessionId)
- : undefined
+ const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(requestContext)
const { properties, groups } = buildBaseProperties(state, analyticsContext)
diff --git a/services/mcp/src/hono/request-context.ts b/services/mcp/src/hono/request-context.ts
index 9f2a922b8dea..03ea48254476 100644
--- a/services/mcp/src/hono/request-context.ts
+++ b/services/mcp/src/hono/request-context.ts
@@ -120,6 +120,18 @@ export class RequestContext {
return this.sessionManager.getSessionUuid(sessionId)
}
+ /**
+ * 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.
+ */
+ async getEffectiveSessionUuid(requestContext: MCPRequestContext): Promise<string | undefined> {
+ return this.getSessionUuid(requestContext.sessionId ?? requestContext.mcpSessionId)
+ }
+
getDistinctId(): Promise<string> {
if (!this.distinctIdPromise) {
this.distinctIdPromise = this.resolveDistinctId()
@@ -232,6 +244,7 @@ export class RequestContext {
try {
const resolvedDistinctId = distinctId ?? (await this.getDistinctId())
const clientName = await this.tokenCache.get('clientName')
+ const sessionUuid = await this.getEffectiveSessionUuid(this.requestContext)
const contextProperties = analyticsContext ? buildMCPContextProperties(analyticsContext) : {}
const previousContextProperties = previousContext
? buildMCPContextProperties(previousContext, { prefix: 'previous_' })
@@ -244,9 +257,7 @@ export class RequestContext {
...(Object.keys(groups).length > 0 ? { groups } : {}),
properties: {
...this.buildClientProperties(),
- ...(this.requestContext.sessionId
- ? { $session_id: await this.getSessionUuid(this.requestContext.sessionId) }
- : {}),
+ ...(sessionUuid ? { $session_id: sessionUuid } : {}),
...(clientName ? { $mcp_oauth_client_name: clientName } : {}),
...contextProperties,
...previousContextProperties,
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index f8d48a684005..5fe729f1e9a1 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -232,7 +232,7 @@ export class ToolExecutor {
void trackToolCall(tool.name, Date.now() - startMs, true, state, undefined, intentMeta)
- const sessionUuid = await state.reqCtx.getSessionUuid(state.requestContext.sessionId)
+ const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)
return handleToolError(error, tool.name, state.distinctId, sessionUuid)
}
}
@@ -294,7 +294,7 @@ export class ToolExecutor {
void trackToolCall('exec', Date.now() - startMs, true, state, undefined, intentMeta)
- const sessionUuid = await state.reqCtx.getSessionUuid(state.requestContext.sessionId)
+ const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)
// Attribute the failure to the inner tool that actually ran (e.g. `query-logs`),
// not the `exec` wrapper — so the agent-facing `[tool]` label and the 5xx
// exception fingerprint point at the real source instead of collapsing every
@@ -390,7 +390,7 @@ export class ToolExecutor {
stop({ status: 'error' })
classifyToolError(error, 'render-ui')
void trackToolCall('render-ui', Date.now() - startMs, true, state, undefined, intentMeta)
- const sessionUuid = await state.reqCtx.getSessionUuid(state.requestContext.sessionId)
+ const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)
return handleToolError(error, 'render-ui', state.distinctId, sessionUuid)
}
}
diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.ts
index 2807a4bd1bff..4b955c59c2c0 100644
--- a/services/mcp/tests/hono/analytics.test.ts
+++ b/services/mcp/tests/hono/analytics.test.ts
@@ -23,6 +23,7 @@ function makeState(overrides: Partial<ResolvedState> = {}): ResolvedState {
reqCtx: {
safelyGetAnalyticsContext: vi.fn(async () => undefined),
getSessionUuid: vi.fn(async () => 'session-uuid'),
+ getEffectiveSessionUuid: vi.fn(async () => 'session-uuid'),
} as any,
context: {
stateManager: {},
diff --git a/services/mcp/tests/hono/request-context.test.ts b/services/mcp/tests/hono/request-context.test.ts
index b2abeec39af7..c8afd3831062 100644
--- a/services/mcp/tests/hono/request-context.test.ts
+++ b/services/mcp/tests/hono/request-context.test.ts
@@ -173,6 +173,25 @@ describe('RequestContext', () => {
})
})
+ 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 },
+ ])(
+ 'sessionId=$sessionId mcpSessionId=$mcpSessionId → resolves via expectedKey=$expectedKey',
+ async ({ sessionId, mcpSessionId, expectedKey }) => {
+ const ctx = new RequestContext(fakeRedis(), env, makeProps())
+ const effective = await ctx.getEffectiveSessionUuid({ sessionId, mcpSessionId } as any)
+
+ expect(effective).toBe(expectedKey ? await ctx.getSessionUuid(expectedKey) : undefined)
+ if (expectedKey) {
+ expect(effective).toMatch(/^[0-9a-f-]{36}$/)
+ }
+ }
+ )
+ })
+
describe('buildClientProperties', () => {
it('includes all request properties', () => {
const ctx = new RequestContext(
diff --git a/services/mcp/tests/hono/tool-executor-intent.test.ts b/services/mcp/tests/hono/tool-executor-intent.test.ts
index da786f42ce53..bccbb001b748 100644
--- a/services/mcp/tests/hono/tool-executor-intent.test.ts
+++ b/services/mcp/tests/hono/tool-executor-intent.test.ts
@@ -34,6 +34,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
safelyGetAnalyticsContext: vi.fn().mockResolvedValue(undefined),
trackEvent: vi.fn(),
getSessionUuid: vi.fn().mockResolvedValue(undefined),
+ getEffectiveSessionUuid: vi.fn().mockResolvedValue(undefined),
} as any,
context: {
api: {},
diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.ts
index ffa5114dc2f0..57477259ff64 100644
--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts
+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts
@@ -50,6 +50,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
trackEvent: vi.fn(),
trackContextSwitchEvent: vi.fn(),
getSessionUuid: vi.fn().mockResolvedValue(undefined),
+ getEffectiveSessionUuid: vi.fn().mockResolvedValue(undefined),
} as any,
context: {
api: {},
diff --git a/services/mcp/tests/hono/tool-executor-tokens.test.ts b/services/mcp/tests/hono/tool-executor-tokens.test.ts
index 1bac87227589..46791b5dbab0 100644
--- a/services/mcp/tests/hono/tool-executor-tokens.test.ts
+++ b/services/mcp/tests/hono/tool-executor-tokens.test.ts
@@ -33,6 +33,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
trackEvent: vi.fn(),
trackContextSwitchEvent: vi.fn(),
getSessionUuid: vi.fn().mockResolvedValue(undefined),
+ getEffectiveSessionUuid: vi.fn().mockResolvedValue(undefined),
} as any,
context: {
api: {},
diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.ts
index 639fb8314df1..d513ca1ab7ed 100644
--- a/services/mcp/tests/hono/tool-executor.test.ts
+++ b/services/mcp/tests/hono/tool-executor.test.ts
@@ -31,6 +31,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
safelyGetAnalyticsContext: vi.fn().mockResolvedValue(undefined),
trackEvent: vi.fn(),
getSessionUuid: vi.fn().mockResolvedValue(undefined),
+ getEffectiveSessionUuid: vi.fn().mockResolvedValue(undefined),
} as any,
context: {
api: {},