: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): add compact session cache migration (#76530)
Ben Whiteaa7af5e7e444
diff --git a/services/mcp/README.md b/services/mcp/README.mdindex aa66ac2f70c2..f51e14f30c89 100644--- a/services/mcp/README.md+++ b/services/mcp/README.md@@ -329,6 +329,17 @@ Then replace `https://mcp.posthog.com/mcp` with `http://localhost:8787/mcp` in tThe server defaults to port **8787**, reads config from `.env` (see `.env.example`), and expects a local Redis on port `6379` for session state; production deployments must set `REDIS_URL` to a TLS-encrypted `rediss://` endpoint.+### Session cache migration++Legacy MCP sessions store client context across five `mcp:session:*` keys with a seven-day expiry. The compact schema stores the same context in one `mcp:s:<id>:c` key with a 24-hour idle expiry.++The server writes and compares both schemas. Legacy keys remain authoritative unless one of these environment variables enables compact reads:++- `MCP_SESSION_CACHE_V2_READ_PROJECT_IDS`: comma-separated project IDs+- `MCP_SESSION_CACHE_V2_READ_ALL=true`: all projects++Monitor `mcp_session_cache_comparisons_total` for `match`, `mismatch`, and `compact_missing` before enabling reads. Monitor `mcp_session_cache_operations_total` for compact read or write errors. Compact read failures fall back to legacy state, so removing either environment variable rolls back the read path without deleting data.+### Edge-proxy worker (Cloudflare)In production, a thin Cloudflare Worker sits in front of the Hono deployments as a stateless edge router: it serves the OAuth metadata endpoints, validates tokens, resolves the caller's cloud region, and proxies `/mcp` traffic to `mcp.us.posthog.com` / `mcp.eu.posthog.com`.diff --git a/services/mcp/src/hono/cache/McpSessionRedisStore.ts b/services/mcp/src/hono/cache/McpSessionRedisStore.tsnew file mode 100644index 000000000000..f405ba8edaad--- /dev/null+++ b/services/mcp/src/hono/cache/McpSessionRedisStore.ts@@ -0,0 +1,158 @@+import { createHash } from 'node:crypto'++import { hash } from '@/lib/utils'++import type { MCPClientContext } from '../mcp-context'+import { sessionCacheComparisonsTotal, sessionCacheOperationsTotal } from '../metrics'+import type { RedisLike } from './RedisCache'++const LEGACY_TTL_SECONDS = 7 * 24 * 60 * 60+const COMPACT_IDLE_TTL_SECONDS = 24 * 60 * 60+const SESSION_CONTEXT_KEYS = [+ 'mcpClientName',+ 'mcpClientVersion',+ 'mcpProtocolVersion',+ 'mcpConsumer',+ 'mcpVendorClient',+] as const++type SessionContextKey = (typeof SESSION_CONTEXT_KEYS)[number]+type SessionContext = Pick<MCPClientContext, SessionContextKey>+type RedisWithEval = RedisLike & {+ eval(script: string, numberOfKeys: number, ...args: string[]): Promise<unknown>+}++const MERGE_COMPACT_CONTEXT_SCRIPT = `+local currentRaw = redis.call('GET', KEYS[1])+local current = currentRaw and cjson.decode(currentRaw) or {}+local cached = ARGV[1] ~= '' and cjson.decode(ARGV[1]) or nil+local desired = cjson.decode(ARGV[2])++for key, value in pairs(desired) do+ if current[key] == nil or (cached ~= nil and current[key] == cached[key]) then+ current[key] = value+ end+end++redis.call('SET', KEYS[1], cjson.encode(current), 'EX', ARGV[3])+return 1+`++export class McpSessionRedisStore {+ private readonly legacyPrefix: string+ private readonly compactKey: string++ constructor(+ private readonly redis: RedisLike,+ sessionId: string+ ) {+ this.legacyPrefix = `mcp:session:${hash(sessionId)}`+ const digest = createHash('sha256').update(sessionId).digest()+ this.compactKey = `mcp:s:${digest.subarray(0, 16).toString('base64url')}:c`+ }++ async resolve(liveContext: MCPClientContext, projectId: string | undefined): Promise<SessionContext> {+ const [legacyContext, compactContext] = await Promise.all([this.readLegacy(), this.readCompact()])+ this.recordComparison(legacyContext, compactContext)++ const readCompact = shouldReadCompact(projectId)+ const storedContext = readCompact && compactContext ? compactContext : legacyContext+ const resolvedContext = mergeContexts(storedContext, liveContext)++ await Promise.all([+ this.writeMissingLegacyValues(legacyContext, liveContext),+ this.refreshCompact(resolvedContext, compactContext),+ ])++ sessionCacheOperationsTotal.inc({ schema: readCompact ? 'compact' : 'legacy', operation: 'read' })+ return resolvedContext+ }++ private async readLegacy(): Promise<Partial<SessionContext>> {+ const entries = await Promise.all(+ SESSION_CONTEXT_KEYS.map(async (key) => {+ const raw = await this.redis.get(`${this.legacyPrefix}:${key}`)+ return [key, raw === null ? undefined : (JSON.parse(raw) as string)] as const+ })+ )+ return Object.fromEntries(entries)+ }++ private async readCompact(): Promise<SessionContext | null> {+ try {+ const raw = await this.redis.get(this.compactKey)+ return raw === null ? null : (JSON.parse(raw) as SessionContext)+ } catch {+ sessionCacheOperationsTotal.inc({ schema: 'compact', operation: 'read_error' })+ return null+ }+ }++ private async writeMissingLegacyValues(+ cached: Partial<SessionContext>,+ liveContext: MCPClientContext+ ): Promise<void> {+ await Promise.all(+ SESSION_CONTEXT_KEYS.flatMap((key) => {+ const value = liveContext[key]+ if (cached[key] !== undefined || value === undefined) {+ return []+ }+ return [this.redis.set(`${this.legacyPrefix}:${key}`, JSON.stringify(value), 'EX', LEGACY_TTL_SECONDS)]+ })+ )+ }++ private async refreshCompact(context: SessionContext, cached: SessionContext | null): Promise<void> {+ try {+ if (cached !== null && contextsEqual(context, cached)) {+ await this.redis.expire(this.compactKey, COMPACT_IDLE_TTL_SECONDS)+ sessionCacheOperationsTotal.inc({ schema: 'compact', operation: 'refresh' })+ } else {+ await (this.redis as RedisWithEval).eval(+ MERGE_COMPACT_CONTEXT_SCRIPT,+ 1,+ this.compactKey,+ cached === null ? '' : JSON.stringify(cached),+ JSON.stringify(context),+ String(COMPACT_IDLE_TTL_SECONDS)+ )+ sessionCacheOperationsTotal.inc({ schema: 'compact', operation: 'write' })+ }+ } catch {+ sessionCacheOperationsTotal.inc({ schema: 'compact', operation: 'write_error' })+ }+ }++ private recordComparison(legacy: Partial<SessionContext>, compact: SessionContext | null): void {+ if (compact === null) {+ sessionCacheComparisonsTotal.inc({ result: 'compact_missing' })+ return+ }+ sessionCacheComparisonsTotal.inc({ result: contextsEqual(legacy, compact) ? 'match' : 'mismatch' })+ }+}++function mergeContexts(stored: Partial<SessionContext>, live: MCPClientContext): SessionContext {+ return Object.fromEntries(SESSION_CONTEXT_KEYS.map((key) => [key, stored[key] ?? live[key]])) as SessionContext+}++function contextsEqual(left: Partial<SessionContext>, right: SessionContext): boolean {+ return SESSION_CONTEXT_KEYS.every((key) => left[key] === right[key])+}++function shouldReadCompact(projectId: string | undefined): boolean {+ if (process.env.MCP_SESSION_CACHE_V2_READ_ALL === 'true') {+ return true+ }+ if (!projectId) {+ return false+ }+ const projects = new Set(+ (process.env.MCP_SESSION_CACHE_V2_READ_PROJECT_IDS ?? '')+ .split(',')+ .map((value) => value.trim())+ .filter(Boolean)+ )+ return projects.has(projectId)+}diff --git a/services/mcp/src/hono/cache/RedisCache.ts b/services/mcp/src/hono/cache/RedisCache.tsindex 2af747650723..fd8643109319 100644--- a/services/mcp/src/hono/cache/RedisCache.ts+++ b/services/mcp/src/hono/cache/RedisCache.ts@@ -17,7 +17,7 @@ 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 type CachePrefix = 'token' | 'user'export class RedisCache<T extends Record<string, any>> extends ScopedCache<T> {private redis: RedisLikediff --git a/services/mcp/src/hono/metrics.ts b/services/mcp/src/hono/metrics.tsindex c06955983a11..c1c3233a518d 100644--- a/services/mcp/src/hono/metrics.ts+++ b/services/mcp/src/hono/metrics.ts@@ -63,6 +63,18 @@ export const redisOperationsTotal = new Counter({labelNames: ['operation', 'status'] as const,})+export const sessionCacheOperationsTotal = new Counter({+ name: 'mcp_session_cache_operations_total',+ help: 'MCP session cache operations by schema.',+ labelNames: ['schema', 'operation'] as const,+})++export const sessionCacheComparisonsTotal = new Counter({+ name: 'mcp_session_cache_comparisons_total',+ help: 'Comparison outcomes between legacy and compact MCP session state.',+ labelNames: ['result'] as const,+})+export const authFailuresTotal = new Counter({name: 'mcp_auth_failures_total',help: 'Authentication failures on /mcp requests.',diff --git a/services/mcp/src/hono/request-context.ts b/services/mcp/src/hono/request-context.tsindex 804cff1899ba..54e28013ec1d 100644--- a/services/mcp/src/hono/request-context.ts+++ b/services/mcp/src/hono/request-context.ts@@ -25,7 +25,6 @@ import {export class RequestContext {private tokenCacheInstance: RedisCache<State> | undefined- private sessionCacheInstance: RedisCache<State> | undefinedprivate userCacheInstance: RedisCache<State> | undefinedprivate apiInstance: ApiClient | undefinedprivate sessionManagerInstance: SessionManager | undefined@@ -58,16 +57,6 @@ export class RequestContext {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.sessionCacheInstance) {- this.sessionCacheInstance = new RedisCache<State>(hash(this.props.mcpSessionId), this.redis, 'session')- }- return this.sessionCacheInstance- }-getUserCache(distinctId: string): RedisCache<State> {if (!this.userCacheInstance) {this.userCacheInstance = new RedisCache<State>(hash(distinctId), this.redis, 'user')diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.tsindex 58532c09667e..bfaf618e22c1 100644--- a/services/mcp/src/hono/request-state-resolver.ts+++ b/services/mcp/src/hono/request-state-resolver.ts@@ -13,9 +13,10 @@ import type { RequestProperties } from '@/lib/request-properties'import { filterStaffOnlyTools } from '@/lib/staff-only-tools'import type { McpMode } from '@/lib/utils'import { getRequiredFeatureFlags, getScopeGatedTools, type ScopeGatedTool } from '@/tools/toolDefinitions'-import type { Context, Tool, Env, State, ZodObjectAny } from '@/tools/types'+import type { Context, Tool, Env, ZodObjectAny } from '@/tools/types'import type { RedisLike } from './cache/RedisCache'+import { McpSessionRedisStore } from './cache/McpSessionRedisStore'import {buildMCPRequestContext,getEffectiveMCPClientContext,@@ -87,16 +88,6 @@ export function switchToolsToExclude(pinned: { organizationId?: string | undefin// ─── Resolver ───-const SESSION_CONTEXT_KEYS = [- 'mcpClientName',- 'mcpClientVersion',- 'mcpProtocolVersion',- 'mcpConsumer',- 'mcpVendorClient',-] as const-type SessionContextKey = (typeof SESSION_CONTEXT_KEYS)[number]-type SessionContextCache = Pick<State, SessionContextKey>-export class RequestStateResolver {private readonly catalog: ToolCatalogprivate readonly redis: RedisLike@@ -111,12 +102,12 @@ export class RequestStateResolver {async resolve(props: RequestProperties): Promise<ResolvedState> {const requestContext = buildMCPRequestContext(props)const reqCtx = new RequestContext(this.redis, this.env, props, requestContext)- const sessionContext = await this.resolveSessionContext(reqCtx, requestContext)- const clientContext = getEffectiveMCPClientContext(requestContext, sessionContext)-- const context = await reqCtx.getContext()const { features, tools, organizationId, projectId, readOnly } = props+ const contextPromise = reqCtx.getContext()+ const pinnedSessionContextPromise = projectId+ ? this.resolveSessionContext(requestContext, projectId)+ : undefinedawait reqCtx.tokenCache.setMany({...(organizationId ? { orgId: organizationId } : {}),@@ -125,10 +116,17 @@ export class RequestStateResolver {let cachedProjectId = projectId || (await reqCtx.tokenCache.get('projectId'))if (!cachedProjectId) {- await context.stateManager.setDefaultOrganizationAndProject()+ const contextForDefault = await contextPromise+ await contextForDefault.stateManager.setDefaultOrganizationAndProject()cachedProjectId = (await reqCtx.tokenCache.get('projectId')) ?? undefined}+ const [context, sessionContext] = await Promise.all([+ contextPromise,+ pinnedSessionContextPromise ?? this.resolveSessionContext(requestContext, cachedProjectId),+ ])+ const clientContext = getEffectiveMCPClientContext(requestContext, sessionContext)+// PRODUCT_DATA_CATALOG_FLAG gates instructions content (the metric-discovery prompt// section), not a tool, so the tool-definition scan can't discover it.const allFlagKeys = [...new Set([...getRequiredFeatureFlags(), PRODUCT_DATA_CATALOG_FLAG])]@@ -232,32 +230,13 @@ export class RequestStateResolver {}private async resolveSessionContext(- reqCtx: RequestContext,- requestContext: MCPRequestContext+ requestContext: MCPRequestContext,+ projectId: string | undefined): Promise<MCPSessionContext | null> {if (!requestContext.mcpSessionId) {return null}-- const cachedEntries = await Promise.all(- SESSION_CONTEXT_KEYS.map(async (key) => [key, await reqCtx.sessionCache.get(key)] as const)- )- const cachedContext = Object.fromEntries(cachedEntries) as Partial<SessionContextCache>-- const cacheUpdates: Partial<SessionContextCache> = {}- for (const key of SESSION_CONTEXT_KEYS) {- if (!cachedContext[key] && requestContext[key]) {- cacheUpdates[key] = requestContext[key]- }- }-- if (Object.keys(cacheUpdates).length > 0) {- await reqCtx.sessionCache.setMany(cacheUpdates)- }-- return Object.fromEntries(- SESSION_CONTEXT_KEYS.map((key) => [key, cachedContext[key] || requestContext[key] || undefined])- ) as MCPSessionContext+ return new McpSessionRedisStore(this.redis, requestContext.mcpSessionId).resolve(requestContext, projectId)}private async resolveAllFlags(diff --git a/services/mcp/tests/hono/mcp-session-redis-store.test.ts b/services/mcp/tests/hono/mcp-session-redis-store.test.tsnew file mode 100644index 000000000000..66580df7eb86--- /dev/null+++ b/services/mcp/tests/hono/mcp-session-redis-store.test.ts@@ -0,0 +1,172 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { McpSessionRedisStore } from '@/hono/cache/McpSessionRedisStore'+import type { RedisLike } from '@/hono/cache/RedisCache'+import type { MCPClientContext } from '@/hono/mcp-context'+import { hash } from '@/lib/utils'++import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'++interface MockRedis extends RedisLike {+ store: Map<string, string>+ eval: ReturnType<typeof vi.fn>+}++function createRedis(): MockRedis {+ const store = new Map<string, string>()+ const rateLimitStubs = makeRedisRateLimitStubs()+ return {+ store,+ get: vi.fn(async (key: string) => store.get(key) ?? null),+ set: vi.fn(async (key: string, value: string) => {+ store.set(key, value)+ return 'OK'+ }),+ eval: vi.fn(+ async (_script: string, _numberOfKeys: number, key: string, cachedRaw: string, desiredRaw: string) => {+ const current = JSON.parse(store.get(key) ?? '{}') as Record<string, string>+ const cached = cachedRaw === '' ? null : (JSON.parse(cachedRaw) as Record<string, string>)+ const desired = JSON.parse(desiredRaw) as Record<string, string>+ for (const [field, value] of Object.entries(desired)) {+ if (current[field] === undefined || (cached !== null && current[field] === cached[field])) {+ current[field] = value+ }+ }+ store.set(key, JSON.stringify(current))+ return 1+ }+ ),+ del: vi.fn(async (...keys: string[]) => keys.filter((key) => store.delete(key)).length),+ scan: vi.fn(async () => ['0', []] as [string, string[]]),+ ...rateLimitStubs,+ expire: vi.fn(rateLimitStubs.expire),+ }+}++const liveContext: MCPClientContext = {+ mcpClientName: 'claude-code',+ mcpClientVersion: '1.2.3',+ mcpProtocolVersion: '2025-11-25',+ mcpConsumer: 'posthog-code',+ mcpVendorClient: 'ClaudeCode',+}++describe('McpSessionRedisStore', () => {+ beforeEach(() => {+ delete process.env.MCP_SESSION_CACHE_V2_READ_ALL+ delete process.env.MCP_SESSION_CACHE_V2_READ_PROJECT_IDS+ })++ it('dual-writes the legacy keys and one compact context key', async () => {+ const redis = createRedis()++ await new McpSessionRedisStore(redis, 'session-1').resolve(liveContext, '1')++ const keys = [...redis.store.keys()]+ expect(keys.filter((key) => key.startsWith('mcp:session:'))).toHaveLength(5)+ expect(keys.filter((key) => key.startsWith('mcp:s:'))).toHaveLength(1)+ expect(keys.find((key) => key.startsWith('mcp:s:'))).toMatch(/^mcp:s:[A-Za-z0-9_-]{22}:c$/)+ expect(JSON.parse(redis.store.get(keys.find((key) => key.startsWith('mcp:s:'))!)!)).toEqual(liveContext)+ })++ it('reads legacy keys written with the existing session hash', async () => {+ const redis = createRedis()+ redis.store.set(`mcp:session:${hash('session-1')}:mcpClientName`, JSON.stringify('legacy-client'))++ expect((await new McpSessionRedisStore(redis, 'session-1').resolve({}, '1')).mcpClientName).toBe(+ 'legacy-client'+ )+ })++ it('keeps legacy state authoritative until the project is enabled', async () => {+ const redis = createRedis()+ const store = new McpSessionRedisStore(redis, 'session-1')+ await store.resolve(liveContext, '1')+ const compactKey = [...redis.store.keys()].find((key) => key.startsWith('mcp:s:'))!+ redis.store.set(compactKey, JSON.stringify({ ...liveContext, mcpClientName: 'compact-client' }))++ expect((await store.resolve({}, '1')).mcpClientName).toBe('claude-code')++ redis.store.set(compactKey, JSON.stringify({ ...liveContext, mcpClientName: 'compact-client' }))+ process.env.MCP_SESSION_CACHE_V2_READ_PROJECT_IDS = '1,2'+ expect((await store.resolve({}, '1')).mcpClientName).toBe('compact-client')+ })++ it('falls back to legacy state when compact reads fail after cutover', async () => {+ const redis = createRedis()+ const store = new McpSessionRedisStore(redis, 'session-1')+ await store.resolve(liveContext, '1')+ process.env.MCP_SESSION_CACHE_V2_READ_ALL = 'true'+ vi.mocked(redis.get).mockImplementation(async (key: string) => {+ if (key.startsWith('mcp:s:')) {+ throw new Error('Valkey read failed')+ }+ return redis.store.get(key) ?? null+ })++ expect((await store.resolve({}, '1')).mcpClientName).toBe('claude-code')+ })++ it('refreshes the compact idle TTL without extending legacy keys', async () => {+ const redis = createRedis()+ const store = new McpSessionRedisStore(redis, 'session-1')+ await store.resolve(liveContext, '1')+ vi.mocked(redis.set).mockClear()++ await store.resolve({}, '1')++ const compactKey = [...redis.store.keys()].find((key) => key.startsWith('mcp:s:'))!+ expect(redis.expire).toHaveBeenCalledWith(compactKey, 24 * 60 * 60)+ expect(redis.set).not.toHaveBeenCalled()+ })++ it('adds client context first observed after initialize to both schemas', async () => {+ const redis = createRedis()+ const store = new McpSessionRedisStore(redis, 'session-1')+ await store.resolve({ ...liveContext, mcpVendorClient: undefined }, '1')++ await store.resolve({ mcpVendorClient: 'ClaudeCode' }, '1')++ const compactKey = [...redis.store.keys()].find((key) => key.startsWith('mcp:s:'))!+ expect(JSON.parse(redis.store.get(compactKey)!)).toMatchObject({ mcpVendorClient: 'ClaudeCode' })+ expect([...redis.store.entries()]).toContainEqual([+ expect.stringMatching(/^mcp:session:.*:mcpVendorClient$/),+ JSON.stringify('ClaudeCode'),+ ])+ })++ it('preserves fields added by concurrent compact writes', async () => {+ const redis = createRedis()+ const first = new McpSessionRedisStore(redis, 'session-1').resolve({ mcpClientName: 'claude-code' }, '1')+ const second = new McpSessionRedisStore(redis, 'session-1').resolve({ mcpConsumer: 'posthog-code' }, '1')++ await Promise.all([first, second])++ process.env.MCP_SESSION_CACHE_V2_READ_ALL = 'true'+ expect(await new McpSessionRedisStore(redis, 'session-1').resolve({}, '1')).toMatchObject({+ mcpClientName: 'claude-code',+ mcpConsumer: 'posthog-code',+ })+ })++ it('starts compact and legacy reads in parallel', async () => {+ const redis = createRedis()+ let releaseLegacyReads: (() => void) | undefined+ const legacyReads = new Promise<void>((resolve) => {+ releaseLegacyReads = resolve+ })+ vi.mocked(redis.get).mockImplementation(async (key: string) => {+ if (key.startsWith('mcp:session:')) {+ await legacyReads+ }+ return null+ })++ const resolution = new McpSessionRedisStore(redis, 'session-1').resolve(liveContext, '1')+ await vi.waitFor(() => {+ expect(redis.get).toHaveBeenCalledWith(expect.stringMatching(/^mcp:s:/))+ })+ releaseLegacyReads?.()+ await resolution+ })+})diff --git a/services/mcp/tests/hono/request-context.test.ts b/services/mcp/tests/hono/request-context.test.tsindex bb3dd8e7c8d9..f65737b7a67a 100644--- a/services/mcp/tests/hono/request-context.test.ts+++ b/services/mcp/tests/hono/request-context.test.ts@@ -321,20 +321,6 @@ describe('RequestContext', () => {expect(ctx.cache).toBe(ctx.cache)})- it('keeps MCP session cache entries on the default 7 day TTL', async () => {- const redis = spyRedis()- const ctx = new RequestContext(redis, env, makeProps({ mcpSessionId: 'mcp-session-1' }))-- await ctx.sessionCache.set('mcpClientName', 'claude-code')-- expect(redis.set).toHaveBeenCalledWith(- expect.stringMatching(/^mcp:session:/),- JSON.stringify('claude-code'),- 'EX',- 7 * 24 * 60 * 60- )- })-it('keeps token cache entries on the default 7 day TTL', async () => {const redis = spyRedis()const ctx = new RequestContext(redis, env, makeProps())diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.tsindex 21b1c48738f1..f33cee2506b4 100644--- a/services/mcp/tests/hono/request-state-resolver.test.ts+++ b/services/mcp/tests/hono/request-state-resolver.test.ts@@ -10,6 +10,23 @@ vi.mock('@/lib/posthog/flags', () => ({resolveFeatureFlagOverrides: vi.fn(() => ({})),}))+vi.mock('@/hono/cache/McpSessionRedisStore', () => ({+ McpSessionRedisStore: class {+ async resolve(requestContext: Record<string, unknown>): Promise<Record<string, unknown>> {+ const keys = ['mcpClientName', 'mcpClientVersion', 'mcpProtocolVersion', 'mcpConsumer', 'mcpVendorClient']+ const resolved = Object.fromEntries(+ keys.map((key) => [key, mockSessionStore.get(key) ?? requestContext[key]])+ )+ for (const key of keys) {+ if (!mockSessionStore.has(key) && requestContext[key] !== undefined) {+ mockSessionStore.set(key, requestContext[key])+ }+ }+ return resolved+ }+ },+}))+vi.mock('@/hono/request-context', () => {type MockCache = {get: (key: string) => Promise<unknown>@@ -40,16 +57,9 @@ vi.mock('@/hono/request-context', () => {})return {- RequestContext: vi.fn().mockImplementation(function (_redis, _env, props: { mcpSessionId?: string } = {}) {- const sessionCache = makeCache(mockSessionStore)+ RequestContext: vi.fn().mockImplementation(function () {return {tokenCache: makeCache(mockTokenStore),- get sessionCache() {- if (!props.mcpSessionId) {- throw new Error('Session ID is required to use the session cache')- }- return sessionCache- },getContext: vi.fn(async () => ({stateManager: {setDefaultOrganizationAndProject: vi.fn(async () => {}),