: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): split caches + session tracking (#59900)
Joshua Snyder760a505f34b5
diff --git a/services/mcp/src/hono/cache/RedisCache.ts b/services/mcp/src/hono/cache/RedisCache.tsindex c5daa299c78c..105bd01d2060 100644--- a/services/mcp/src/hono/cache/RedisCache.ts+++ b/services/mcp/src/hono/cache/RedisCache.ts@@ -17,18 +17,22 @@ const DEFAULT_TTL_SECONDS = 7 * 24 * 60 * 60 // 7 daysconst CLEAR_MAX_ITERATIONS = 50const CLEAR_SCAN_COUNT = 100+export type CachePrefix = 'token' | 'session' | 'user'+export class RedisCache<T extends Record<string, any>> extends ScopedCache<T> {private redis: RedisLikeprivate ttl: number+ private prefix: CachePrefix- constructor(scope: string, redis: RedisLike, ttlSeconds: number = DEFAULT_TTL_SECONDS) {+ constructor(scope: string, redis: RedisLike, prefix: CachePrefix = 'token', ttlSeconds: number = DEFAULT_TTL_SECONDS) {super(scope)this.redis = redis+ this.prefix = prefixthis.ttl = ttlSeconds}private getScopedKey(key: string): string {- return `mcp:user:${this.scope}:${key}`+ return `mcp:${this.prefix}:${this.scope}:${key}`}async get<K extends keyof T>(key: K): Promise<T[K] | undefined> {@@ -65,7 +69,7 @@ export class RedisCache<T extends Record<string, any>> extends ScopedCache<T> {}async clear(): Promise<void> {- const pattern = `mcp:user:${this.scope}:*`+ const pattern = `mcp:${this.prefix}:${this.scope}:*`let cursor = '0'const unlink = this.redis.unlink?.bind(this.redis) ?? this.redis.del.bind(this.redis)for (let i = 0; i < CLEAR_MAX_ITERATIONS; i += 1) {diff --git a/services/mcp/src/hono/dispatcher.ts b/services/mcp/src/hono/dispatcher.tsindex 43a1d90f083e..83882a1c9856 100644--- a/services/mcp/src/hono/dispatcher.ts+++ b/services/mcp/src/hono/dispatcher.ts@@ -18,6 +18,8 @@ import type {ReadResourceRequest,} from '@modelcontextprotocol/sdk/types.js'+import { randomUUID } from 'node:crypto'+import { MCP_SERVER_NAME, MCP_SERVER_VERSION } from '@/lib/constants'import type { RequestProperties } from '@/lib/request-properties'@@ -153,22 +155,26 @@ class McpDispatcher {return new Response(null, { status: 202 })}+ const hasInit = requests.some((r) => r.method === Method.Initialize)+ if (hasInit) {+ props.mcpSessionId = randomUUID()+ }+const needsState = requests.some((r) => TRACKED_METHODS.has(r.method))const state = needsState ? await this.stateResolver.resolve(props) : undefined+ const headers: Record<string, string> = { 'Content-Type': 'application/json' }+ if (props.mcpSessionId) {+ headers['Mcp-Session-Id'] = props.mcpSessionId+ }+if (!wasArray && requests.length === 1) {const result = await this.dispatch(requests[0]!, props, state)- return new Response(JSON.stringify(result), {- status: 200,- headers: { 'Content-Type': 'application/json' },- })+ return new Response(JSON.stringify(result), { status: 200, headers })}const results = await Promise.all(requests.map((r) => this.dispatch(r, props, state)))- return new Response(JSON.stringify(results), {- status: 200,- headers: { 'Content-Type': 'application/json' },- })+ return new Response(JSON.stringify(results), { status: 200, headers })}private async dispatch(diff --git a/services/mcp/src/hono/request-context.ts b/services/mcp/src/hono/request-context.tsindex 45b37fb91943..fa39b056c56d 100644--- a/services/mcp/src/hono/request-context.ts+++ b/services/mcp/src/hono/request-context.ts@@ -1,6 +1,7 @@import { ApiClient } from '@/api/client'import { MCP_ANALYTICS_SOURCE, MCP_SERVER_NAME, MCP_SERVER_VERSION } from '@/lib/constants'import { wrapError } from '@/lib/errors'+import { hash } from '@/lib/utils'import {AnalyticsEvent,buildMCPAnalyticsGroups,@@ -17,7 +18,9 @@ import { RedisCache, type RedisLike } from './cache/RedisCache'import { getCustomApiBaseUrl } from './constants'export class RequestContext {- private cacheInstance: RedisCache<State> | undefined+ private tokenCacheInstance: RedisCache<State> | undefined+ private sessionCacheInstance: RedisCache<State> | undefined+ private userCacheInstance: RedisCache<State> | undefinedprivate apiInstance: ApiClient | undefinedprivate sessionManagerInstance: SessionManager | undefinedprivate distinctIdPromise: Promise<string> | undefined@@ -31,14 +34,35 @@ export class RequestContext {this.props = props}- get cache(): RedisCache<State> {+ get tokenCache(): RedisCache<State> {if (!this.props.userHash) {- throw new Error('User hash is required to use the cache')+ throw new Error('User hash is required to use the token cache')+ }+ if (!this.tokenCacheInstance) {+ this.tokenCacheInstance = new RedisCache<State>(this.props.userHash, this.redis, 'token')+ }+ return this.tokenCacheInstance+ }++ get sessionCache(): RedisCache<State> {+ if (!this.props.mcpSessionId) {+ throw new Error('Session ID is required to use the session cache')}- if (!this.cacheInstance) {- this.cacheInstance = new RedisCache<State>(this.props.userHash, this.redis)+ if (!this.sessionCacheInstance) {+ this.sessionCacheInstance = new RedisCache<State>(hash(this.props.mcpSessionId), this.redis, 'session')}- return this.cacheInstance+ return this.sessionCacheInstance+ }++ getUserCache(distinctId: string): RedisCache<State> {+ if (!this.userCacheInstance) {+ this.userCacheInstance = new RedisCache<State>(hash(distinctId), this.redis, 'user')+ }+ return this.userCacheInstance+ }++ get cache(): RedisCache<State> {+ return this.tokenCache}private async api(): Promise<ApiClient> {@@ -69,7 +93,7 @@ export class RequestContext {get sessionManager(): SessionManager {if (!this.sessionManagerInstance) {- this.sessionManagerInstance = new SessionManager(this.cache)+ this.sessionManagerInstance = new SessionManager(this.tokenCache)}return this.sessionManagerInstance}@@ -89,7 +113,7 @@ export class RequestContext {}private async resolveDistinctId(): Promise<string> {- const cached = await this.cache.get('distinctId')+ const cached = await this.tokenCache.get('distinctId')if (cached) {return cached}@@ -97,16 +121,17 @@ export class RequestContext {if (!userResult.success) {throw wrapError(`Failed to get user: ${userResult.error.message}`, userResult.error)}- await this.cache.set('distinctId', userResult.data.distinct_id)- return userResult.data.distinct_id as string+ const distinctId = userResult.data.distinct_id as string+ await this.tokenCache.set('distinctId', distinctId)+ return distinctId}async getContext(): Promise<Context> {const api = await this.api()- const stateManager = new StateManager(this.cache, api)+ const stateManager = new StateManager(this.tokenCache, api)const partialContext: Omit<Context, 'trackEvent'> = {api,- cache: this.cache,+ cache: this.tokenCache,env: this.env,stateManager,sessionManager: this.sessionManager,@@ -184,7 +209,7 @@ export class RequestContext {try {const resolvedDistinctId = distinctId ?? (await this.getDistinctId())const resolvedProps = props ?? this.props- const clientName = await this.cache.get('clientName')+ const clientName = await this.tokenCache.get('clientName')const contextProperties = analyticsContext ? buildMCPContextProperties(analyticsContext) : {}const previousContextProperties = previousContext? buildMCPContextProperties(previousContext, { prefix: 'previous_' })diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.tsindex b6bd08d77371..23b7b9550018 100644--- a/services/mcp/src/hono/request-state-resolver.ts+++ b/services/mcp/src/hono/request-state-resolver.ts@@ -64,18 +64,23 @@ export class RequestStateResolver {const { features, tools, version: clientVersion, organizationId, projectId, readOnly, mode } = props- await reqCtx.cache.setMany({+ await reqCtx.tokenCache.setMany({...(organizationId ? { orgId: organizationId } : {}),...(projectId ? { projectId } : {}),- ...(props.mcpClientName ? { mcpClientName: props.mcpClientName } : {}),- ...(props.mcpClientVersion ? { mcpClientVersion: props.mcpClientVersion } : {}),- ...(props.mcpProtocolVersion ? { mcpProtocolVersion: props.mcpProtocolVersion } : {}),})- let cachedProjectId = projectId || (await reqCtx.cache.get('projectId'))+ if (props.mcpSessionId) {+ await reqCtx.sessionCache.setMany({+ ...(props.mcpClientName ? { mcpClientName: props.mcpClientName } : {}),+ ...(props.mcpClientVersion ? { mcpClientVersion: props.mcpClientVersion } : {}),+ ...(props.mcpProtocolVersion ? { mcpProtocolVersion: props.mcpProtocolVersion } : {}),+ })+ }++ let cachedProjectId = projectId || (await reqCtx.tokenCache.get('projectId'))if (!cachedProjectId) {await context.stateManager.setDefaultOrganizationAndProject()- cachedProjectId = (await reqCtx.cache.get('projectId')) ?? undefined+ cachedProjectId = (await reqCtx.tokenCache.get('projectId')) ?? undefined}const toolFlagKeys = getRequiredFeatureFlags(clientVersion)@@ -94,11 +99,21 @@ export class RequestStateResolver {const toolFeatureFlags =toolFlagKeys.length > 0 ? Object.fromEntries(toolFlagKeys.map((k) => [k, !!allFlags[k]])) : undefined- const oauthClientName = (await reqCtx.cache.get('clientName')) || undefined- const mcpClientName = props.mcpClientName || (await reqCtx.cache.get('mcpClientName')) || undefined- const mcpClientVersion = props.mcpClientVersion || (await reqCtx.cache.get('mcpClientVersion')) || undefined- const mcpProtocolVersion =- props.mcpProtocolVersion || (await reqCtx.cache.get('mcpProtocolVersion')) || undefined+ const oauthClientName = (await reqCtx.tokenCache.get('clientName')) || undefined++ let mcpClientName = props.mcpClientName+ let mcpClientVersion = props.mcpClientVersion+ let mcpProtocolVersion = props.mcpProtocolVersion+ if (props.mcpSessionId && (!mcpClientName || !mcpClientVersion || !mcpProtocolVersion)) {+ const [cachedName, cachedVersion, cachedProto] = await Promise.all([+ mcpClientName ? undefined : reqCtx.sessionCache.get('mcpClientName'),+ mcpClientVersion ? undefined : reqCtx.sessionCache.get('mcpClientVersion'),+ mcpProtocolVersion ? undefined : reqCtx.sessionCache.get('mcpProtocolVersion'),+ ])+ mcpClientName = mcpClientName || cachedName || undefined+ mcpClientVersion = mcpClientVersion || cachedVersion || undefined+ mcpProtocolVersion = mcpProtocolVersion || cachedProto || undefined+ }props.mcpClientName = mcpClientNameprops.mcpClientVersion = mcpClientVersiondiff --git a/services/mcp/tests/hono/mcp-protocol.test.ts b/services/mcp/tests/hono/mcp-protocol.test.tsindex a08d2a8613ec..9af093e64ffb 100644--- a/services/mcp/tests/hono/mcp-protocol.test.ts+++ b/services/mcp/tests/hono/mcp-protocol.test.ts@@ -14,6 +14,7 @@ import {defineResilienceTests,defineResourceCatalogTests,defineSessionLifecycleTests,+ defineSessionTrackingTests,type ProtocolTestHarness,} from '../integration/mcp-protocol-suite'import { handlers, contextMillHandler } from '../workers/fixtures/handlers'@@ -85,3 +86,4 @@ defineSessionLifecycleTests('Hono', harness)defineResourceCatalogTests('Hono', harness)defineCatalogFilterTests('Hono', harness)defineExecModeTests('Hono', harness)+defineSessionTrackingTests('Hono', harness)diff --git a/services/mcp/tests/hono/redis-cache.test.ts b/services/mcp/tests/hono/redis-cache.test.tsindex 6d35a1298ef4..8736aa88a186 100644--- a/services/mcp/tests/hono/redis-cache.test.ts+++ b/services/mcp/tests/hono/redis-cache.test.ts@@ -60,19 +60,19 @@ describe('RedisCache', () => {it('should return undefined for missing keys', async () => {const result = await cache.get('region')expect(result).toBeUndefined()- expect(mockRedis.get).toHaveBeenCalledWith('mcp:user:test-user-hash:region')+ expect(mockRedis.get).toHaveBeenCalledWith('mcp:token:test-user-hash:region')})it('should return parsed JSON values', async () => {- mockRedis._store.set('mcp:user:test-user-hash:region', '"us"')+ mockRedis._store.set('mcp:token:test-user-hash:region', '"us"')expect(await cache.get('region')).toBe('us')})it('should not read another user keys', async () => {const cacheA = new RedisCache<TestState>('user-a', mockRedis)const cacheB = new RedisCache<TestState>('user-b', mockRedis)- mockRedis._store.set('mcp:user:user-a:region', '"us"')- mockRedis._store.set('mcp:user:user-b:region', '"eu"')+ mockRedis._store.set('mcp:token:user-a:region', '"us"')+ mockRedis._store.set('mcp:token:user-b:region', '"eu"')expect(await cacheA.get('region')).toBe('us')expect(await cacheB.get('region')).toBe('eu')@@ -82,7 +82,7 @@ describe('RedisCache', () => {describe('set', () => {it('should store JSON-serialized values with scoped key', async () => {await cache.set('region', 'eu')- expect(mockRedis.set).toHaveBeenCalledWith('mcp:user:test-user-hash:region', '"eu"', 'EX', 7 * 24 * 60 * 60)+ expect(mockRedis.set).toHaveBeenCalledWith('mcp:token:test-user-hash:region', '"eu"', 'EX', 7 * 24 * 60 * 60)})it('should isolate different users', async () => {@@ -91,17 +91,17 @@ describe('RedisCache', () => {await cacheA.set('projectId', '111')await cacheB.set('projectId', '222')- expect(mockRedis._store.get('mcp:user:user-a:projectId')).toBe('"111"')- expect(mockRedis._store.get('mcp:user:user-b:projectId')).toBe('"222"')+ expect(mockRedis._store.get('mcp:token:user-a:projectId')).toBe('"111"')+ expect(mockRedis._store.get('mcp:token:user-b:projectId')).toBe('"222"')})})describe('delete', () => {it('should only delete the targeted user key', async () => {- mockRedis._store.set('mcp:user:test-user-hash:region', '"us"')- mockRedis._store.set('mcp:user:other-user:region', '"eu"')+ mockRedis._store.set('mcp:token:test-user-hash:region', '"us"')+ mockRedis._store.set('mcp:token:other-user:region', '"eu"')await cache.delete('region')- expect(mockRedis._store.has('mcp:user:other-user:region')).toBe(true)+ expect(mockRedis._store.has('mcp:token:other-user:region')).toBe(true)})})@@ -151,17 +151,17 @@ describe('RedisCache', () => {describe('clear', () => {it('should only clear keys for the scoped user', async () => {- mockRedis._store.set('mcp:user:test-user-hash:region', '"us"')- mockRedis._store.set('mcp:user:test-user-hash:projectId', '"123"')- mockRedis._store.set('mcp:user:other-user:region', '"eu"')+ mockRedis._store.set('mcp:token:test-user-hash:region', '"us"')+ mockRedis._store.set('mcp:token:test-user-hash:projectId', '"123"')+ mockRedis._store.set('mcp:token:other-user:region', '"eu"')await cache.clear()expect(mockRedis.del).toHaveBeenCalledWith(- 'mcp:user:test-user-hash:region',- 'mcp:user:test-user-hash:projectId'+ 'mcp:token:test-user-hash:region',+ 'mcp:token:test-user-hash:projectId')- expect(mockRedis._store.has('mcp:user:other-user:region')).toBe(true)+ expect(mockRedis._store.has('mcp:token:other-user:region')).toBe(true)})})})diff --git a/services/mcp/tests/hono/request-context.test.ts b/services/mcp/tests/hono/request-context.test.tsindex 51150bad0bac..7533eab793df 100644--- a/services/mcp/tests/hono/request-context.test.ts+++ b/services/mcp/tests/hono/request-context.test.ts@@ -68,7 +68,7 @@ describe('RequestContext', () => {it('returns cached distinctId without calling API', async () => {const redis = fakeRedis()- await redis.set('mcp:user:test-user:distinctId', JSON.stringify('cached-id'))+ await redis.set('mcp:token:test-user:distinctId', JSON.stringify('cached-id'))mockMe.mockClear()const ctx = new RequestContext(redis, env, makeProps())@@ -84,7 +84,7 @@ describe('RequestContext', () => {const ctx = new RequestContext(redis, env, makeProps())await ctx.getDistinctId()- const cached = await redis.get('mcp:user:test-user:distinctId')+ const cached = await redis.get('mcp:token:test-user:distinctId')expect(JSON.parse(cached!)).toBe('fresh-id')})diff --git a/services/mcp/tests/integration/mcp-protocol-suite.ts b/services/mcp/tests/integration/mcp-protocol-suite.tsindex 2afdf2746040..1383e57c50f6 100644--- a/services/mcp/tests/integration/mcp-protocol-suite.ts+++ b/services/mcp/tests/integration/mcp-protocol-suite.ts@@ -422,6 +422,108 @@ export function defineResilienceTests(})}+// Session ID tracking: the server mints an `Mcp-Session-Id` on initialize and+// echoes it on every response. Clients echo it back so the server can correlate+// requests to a logical session for analytics and cache scoping.+//+// These tests use the real MCP SDK client to verify the session ID flows through+// the full transport lifecycle — the SDK's StreamableHTTPClientTransport+// automatically captures the header from the init response and echoes it on+// every subsequent request.+export function defineSessionTrackingTests(+ label: string,+ getHarness: () => Promise<ProtocolTestHarness> | ProtocolTestHarness+): void {+ describe(`MCP session tracking (${label})`, () => {+ let client: Client+ let transport: StreamableHTTPClientTransport++ afterEach(async () => {+ await safeClose(client)+ })++ async function connectClient(+ harness: ProtocolTestHarness,+ extraHeaders: Record<string, string> = {}+ ): Promise<void> {+ transport = new StreamableHTTPClientTransport(new URL('/mcp', harness.baseUrl), {+ fetch: harness.fetch,+ requestInit: {+ headers: {+ Authorization: `Bearer ${harness.token}`,+ ...extraHeaders,+ },+ },+ })+ client = new Client({ name: 'session-tracking-test', version: '0.0.1' }, { capabilities: {} })+ await client.connect(transport as ConnectableTransport)+ }++ it('SDK transport captures a UUID session ID after init', async () => {+ const harness = await getHarness()+ await connectClient(harness)++ expect(transport.sessionId).toBeTruthy()+ expect(transport.sessionId).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)+ })++ it('session ID persists through tools/list after init', async () => {+ const harness = await getHarness()+ await connectClient(harness)+ const sessionId = transport.sessionId++ const { tools } = await client.listTools()+ expect(tools.length).toBeGreaterThan(0)+ expect(transport.sessionId).toBe(sessionId)+ })++ it('session ID persists through a tool call', async () => {+ const harness = await getHarness()+ await connectClient(harness)+ const sessionId = transport.sessionId++ await client.callTool({ name: 'organization-get', arguments: {} })+ expect(transport.sessionId).toBe(sessionId)+ })++ it('session ID persists through multiple sequential tool calls', async () => {+ const harness = await getHarness()+ await connectClient(harness)+ const sessionId = transport.sessionId++ await client.listTools()+ await client.callTool({ name: 'organization-get', arguments: {} })+ await client.listResources()+ expect(transport.sessionId).toBe(sessionId)+ })++ it('exec mode gets a session ID that persists through calls', async () => {+ const harness = await getHarness()+ await connectClient(harness, { 'x-posthog-mcp-mode': 'cli' })+ const sessionId = transport.sessionId++ expect(sessionId).toBeTruthy()+ await client.callTool({ name: 'exec', arguments: { command: 'tools' } })+ expect(transport.sessionId).toBe(sessionId)+ })++ it('two independent clients get different session IDs', async () => {+ const harness = await getHarness()++ await connectClient(harness)+ const sessionId1 = transport.sessionId+ await safeClose(client)++ await connectClient(harness)+ const sessionId2 = transport.sessionId++ expect(sessionId1).toBeTruthy()+ expect(sessionId2).toBeTruthy()+ expect(sessionId1).not.toBe(sessionId2)+ })+ })+}+// Raw JSON-RPC dispatcher behavior that bypasses the SDK client. The SDK// normalizes / hides a lot of the wire format, so we drop down to fetch() to// assert on the contract MCP clients in the wild actually depend on: