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.

refactor(mcp): retire the legacy session cache write path (#78899)

Ben White458b8f2ac349
diff --git a/services/mcp/README.md b/services/mcp/README.md
index f51e14f30c89..603df9da1a9d 100644
--- a/services/mcp/README.md
+++ b/services/mcp/README.md
@@ -329,16 +329,14 @@ Then replace `https://mcp.posthog.com/mcp` with `http://localhost:8787/mcp` in t
The 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
+### Session cache
-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.
+A session's client context lives in one `mcp:s:<id>:c` key with a 24-hour idle expiry, refreshed on every request in the session.
+Concurrent requests merge their fields through a Lua compare-and-merge, so a field first seen mid-session is never lost to an overlapping write.
-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.
+Monitor `mcp_session_cache_operations_total` for `read_error` and `write_error`.
+Both are non-blocking: a failed read serves whatever context the current request carries, so attribution degrades rather than the call failing.
+Each also logs a warning prefixed `[McpSessionRedisStore]`, so a Redis failure on this path is greppable in logs and not only visible on the metrics counter.
### Edge-proxy worker (Cloudflare)
diff --git a/services/mcp/src/hono/cache/McpSessionRedisStore.ts b/services/mcp/src/hono/cache/McpSessionRedisStore.ts
index f405ba8edaad..6ae49d0546a0 100644
--- a/services/mcp/src/hono/cache/McpSessionRedisStore.ts
+++ b/services/mcp/src/hono/cache/McpSessionRedisStore.ts
@@ -1,12 +1,9 @@
import { createHash } from 'node:crypto'
-import { hash } from '@/lib/utils'
-
import type { MCPClientContext } from '../mcp-context'
-import { sessionCacheComparisonsTotal, sessionCacheOperationsTotal } from '../metrics'
+import { 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',
@@ -18,9 +15,6 @@ const SESSION_CONTEXT_KEYS = [
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])
@@ -39,77 +33,46 @@ 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)
+ async resolve(liveContext: MCPClientContext): Promise<SessionContext> {
+ const cachedContext = await this.readCompact()
+ const resolvedContext = mergeContexts(cachedContext ?? {}, liveContext)
- const readCompact = shouldReadCompact(projectId)
- const storedContext = readCompact && compactContext ? compactContext : legacyContext
- const resolvedContext = mergeContexts(storedContext, liveContext)
+ await this.refreshCompact(resolvedContext, cachedContext)
- await Promise.all([
- this.writeMissingLegacyValues(legacyContext, liveContext),
- this.refreshCompact(resolvedContext, compactContext),
- ])
-
- sessionCacheOperationsTotal.inc({ schema: readCompact ? 'compact' : 'legacy', operation: 'read' })
+ sessionCacheOperationsTotal.inc({ schema: 'compact', 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 {
+ } catch (err) {
+ // Session context is enrichment, not authorization — a Valkey blip degrades
+ // attribution to whatever this request carries rather than failing the call.
+ console.warn('[McpSessionRedisStore] compact read failed:', err)
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(
+ await this.redis.eval(
MERGE_COMPACT_CONTEXT_SCRIPT,
1,
this.compactKey,
@@ -119,18 +82,13 @@ export class McpSessionRedisStore {
)
sessionCacheOperationsTotal.inc({ schema: 'compact', operation: 'write' })
}
- } catch {
+ } catch (err) {
+ // A lost merge means this session's context stops persisting for the rest of
+ // its life, so the request still succeeds while attribution silently decays.
+ console.warn('[McpSessionRedisStore] compact write failed:', err)
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 {
@@ -140,19 +98,3 @@ function mergeContexts(stored: Partial<SessionContext>, live: MCPClientContext):
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.ts
index fd8643109319..f775bdb52b96 100644
--- a/services/mcp/src/hono/cache/RedisCache.ts
+++ b/services/mcp/src/hono/cache/RedisCache.ts
@@ -11,6 +11,10 @@ export interface RedisLike {
incr(key: string): Promise<number>
expire(key: string, seconds: number): Promise<number>
ttl(key: string): Promise<number>
+ // Session context persists only through a Lua compare-and-merge, so a client
+ // that can't EVAL loses it silently. Declaring it here makes that a type error
+ // instead of a caught exception behind a write_error counter.
+ eval(script: string, numberOfKeys: number, ...args: (string | number)[]): Promise<unknown>
}
const DEFAULT_TTL_SECONDS = 7 * 24 * 60 * 60 // 7 days
diff --git a/services/mcp/src/hono/metrics.ts b/services/mcp/src/hono/metrics.ts
index c1c3233a518d..af499de15c58 100644
--- a/services/mcp/src/hono/metrics.ts
+++ b/services/mcp/src/hono/metrics.ts
@@ -69,12 +69,6 @@ export const sessionCacheOperationsTotal = new Counter({
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-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.ts
index 660841a28191..aa4328550f09 100644
--- a/services/mcp/src/hono/request-state-resolver.ts
+++ b/services/mcp/src/hono/request-state-resolver.ts
@@ -122,9 +122,7 @@ export class RequestStateResolver {
const { features, tools, organizationId, projectId, readOnly } = props
const contextPromise = reqCtx.getContext()
- const pinnedSessionContextPromise = projectId
- ? this.resolveSessionContext(requestContext, projectId)
- : undefined
+ const pinnedSessionContextPromise = projectId ? this.resolveSessionContext(requestContext) : undefined
await reqCtx.tokenCache.setMany({
...(organizationId ? { orgId: organizationId } : {}),
@@ -140,7 +138,7 @@ export class RequestStateResolver {
const [context, sessionContext] = await Promise.all([
contextPromise,
- pinnedSessionContextPromise ?? this.resolveSessionContext(requestContext, cachedProjectId),
+ pinnedSessionContextPromise ?? this.resolveSessionContext(requestContext),
])
const clientContext = getEffectiveMCPClientContext(requestContext, sessionContext)
@@ -251,14 +249,11 @@ export class RequestStateResolver {
}
}
- private async resolveSessionContext(
- requestContext: MCPRequestContext,
- projectId: string | undefined
- ): Promise<MCPSessionContext | null> {
+ private async resolveSessionContext(requestContext: MCPRequestContext): Promise<MCPSessionContext | null> {
if (!requestContext.mcpSessionId) {
return null
}
- return new McpSessionRedisStore(this.redis, requestContext.mcpSessionId).resolve(requestContext, projectId)
+ return new McpSessionRedisStore(this.redis, requestContext.mcpSessionId).resolve(requestContext)
}
private async resolveAllFlags(
diff --git a/services/mcp/tests/hono/helpers/redis-rate-limit-stubs.ts b/services/mcp/tests/hono/helpers/redis-rate-limit-stubs.ts
index e53ad566359a..defb6caa719a 100644
--- a/services/mcp/tests/hono/helpers/redis-rate-limit-stubs.ts
+++ b/services/mcp/tests/hono/helpers/redis-rate-limit-stubs.ts
@@ -3,13 +3,18 @@ export interface RedisRateLimitStubs {
incrby: (key: string, increment: number) => Promise<number>
expire: (key: string, seconds: number) => Promise<number>
ttl: (key: string) => Promise<number>
+ eval: (script: string, numberOfKeys: number, ...args: (string | number)[]) => Promise<unknown>
}
// Trivial in-memory stubs for the counter ops on RedisLike (rate limiting and
// the confirmed-action stash quota). Test files that only need to satisfy the
// interface (no counter assertions of their own) can spread the return value
// into their fake-redis builder.
-export function makeRedisRateLimitStubs(): RedisRateLimitStubs {
+//
+// Pass `store` when the test exercises session context: the service's only EVAL is
+// McpSessionRedisStore's compare-and-merge, and without a store-backed stub the
+// merge silently no-ops, so session context never persists across requests.
+export function makeRedisRateLimitStubs(store?: Map<string, string>): RedisRateLimitStubs {
const counts = new Map<string, number>()
return {
incr: async (key) => {
@@ -24,5 +29,21 @@ export function makeRedisRateLimitStubs(): RedisRateLimitStubs {
},
expire: async () => 1,
ttl: async () => 60,
+ eval: async (_script, _numberOfKeys, ...args) => {
+ if (!store) {
+ return null
+ }
+ const [key, cachedRaw, desiredRaw] = args.map(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
+ },
}
}
diff --git a/services/mcp/tests/hono/mcp-protocol.test.ts b/services/mcp/tests/hono/mcp-protocol.test.ts
index 0c2002375064..f0b1a04fff8c 100644
--- a/services/mcp/tests/hono/mcp-protocol.test.ts
+++ b/services/mcp/tests/hono/mcp-protocol.test.ts
@@ -47,7 +47,7 @@ function createInMemoryRedis(): RedisLike & {
const cur = String(cursor)
return [cur === '0' ? 'next' : '0', cur === '0' ? Array.from(store.keys()) : []] as [string, string[]]
},
- ...makeRedisRateLimitStubs(),
+ ...makeRedisRateLimitStubs(store),
ping: async () => 'PONG',
}
}
diff --git a/services/mcp/tests/hono/mcp-session-redis-store.test.ts b/services/mcp/tests/hono/mcp-session-redis-store.test.ts
index 66580df7eb86..70ed997ee944 100644
--- a/services/mcp/tests/hono/mcp-session-redis-store.test.ts
+++ b/services/mcp/tests/hono/mcp-session-redis-store.test.ts
@@ -1,20 +1,19 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { beforeEach, describe, expect, it, type Mock, 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>
+ eval: Mock<RedisLike['eval']>
}
function createRedis(): MockRedis {
const store = new Map<string, string>()
- const rateLimitStubs = makeRedisRateLimitStubs()
+ const rateLimitStubs = makeRedisRateLimitStubs(store)
return {
store,
get: vi.fn(async (key: string) => store.get(key) ?? null),
@@ -22,24 +21,11 @@ function createRedis(): MockRedis {
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),
+ eval: vi.fn(rateLimitStubs.eval),
}
}
@@ -51,122 +37,67 @@ const liveContext: MCPClientContext = {
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()
+function compactKeyIn(redis: MockRedis): string {
+ return [...redis.store.keys()].find((key) => key.startsWith('mcp:s:'))!
+}
- await new McpSessionRedisStore(redis, 'session-1').resolve(liveContext, '1')
+describe('McpSessionRedisStore', () => {
+ let redis: MockRedis
- 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)
+ beforeEach(() => {
+ redis = createRedis()
})
- 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'))
+ it('stores the whole context under one compacted key', async () => {
+ await new McpSessionRedisStore(redis, 'session-1').resolve(liveContext)
- expect((await new McpSessionRedisStore(redis, 'session-1').resolve({}, '1')).mcpClientName).toBe(
- 'legacy-client'
- )
+ expect([...redis.store.keys()]).toHaveLength(1)
+ expect(compactKeyIn(redis)).toMatch(/^mcp:s:[A-Za-z0-9_-]{22}:c$/)
+ expect(JSON.parse(redis.store.get(compactKeyIn(redis))!)).toEqual(liveContext)
})
- it('keeps legacy state authoritative until the project is enabled', async () => {
- const redis = createRedis()
+ it('serves stored context back to a later request that carries none', async () => {
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')
+ await store.resolve(liveContext)
- 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')
+ expect(await store.resolve({})).toEqual(liveContext)
})
- 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
- })
+ it('serves live context instead of throwing when the compact read fails', async () => {
+ vi.mocked(redis.get).mockRejectedValue(new Error('Valkey read failed'))
- expect((await store.resolve({}, '1')).mcpClientName).toBe('claude-code')
+ expect(await new McpSessionRedisStore(redis, 'session-1').resolve(liveContext)).toEqual(liveContext)
})
- it('refreshes the compact idle TTL without extending legacy keys', async () => {
- const redis = createRedis()
+ it('refreshes the idle TTL rather than rewriting an unchanged context', async () => {
const store = new McpSessionRedisStore(redis, 'session-1')
- await store.resolve(liveContext, '1')
- vi.mocked(redis.set).mockClear()
+ await store.resolve(liveContext)
+ vi.mocked(redis.eval).mockClear()
- await store.resolve({}, '1')
+ await store.resolve({})
- const compactKey = [...redis.store.keys()].find((key) => key.startsWith('mcp:s:'))!
- expect(redis.expire).toHaveBeenCalledWith(compactKey, 24 * 60 * 60)
- expect(redis.set).not.toHaveBeenCalled()
+ expect(redis.expire).toHaveBeenCalledWith(compactKeyIn(redis), 24 * 60 * 60)
+ expect(redis.eval).not.toHaveBeenCalled()
})
- it('adds client context first observed after initialize to both schemas', async () => {
- const redis = createRedis()
+ it('persists a client field first observed after initialize', async () => {
const store = new McpSessionRedisStore(redis, 'session-1')
- await store.resolve({ ...liveContext, mcpVendorClient: undefined }, '1')
+ await store.resolve({ ...liveContext, mcpVendorClient: undefined })
- await store.resolve({ mcpVendorClient: 'ClaudeCode' }, '1')
+ await store.resolve({ mcpVendorClient: 'ClaudeCode' })
- 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'),
- ])
+ expect(JSON.parse(redis.store.get(compactKeyIn(redis))!)).toMatchObject({ mcpVendorClient: '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])
+ it('preserves fields added by concurrent writes', async () => {
+ await Promise.all([
+ new McpSessionRedisStore(redis, 'session-1').resolve({ mcpClientName: 'claude-code' }),
+ new McpSessionRedisStore(redis, 'session-1').resolve({ mcpConsumer: 'posthog-code' }),
+ ])
- process.env.MCP_SESSION_CACHE_V2_READ_ALL = 'true'
- expect(await new McpSessionRedisStore(redis, 'session-1').resolve({}, '1')).toMatchObject({
+ expect(await new McpSessionRedisStore(redis, 'session-1').resolve({})).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/session-mode-pool.test.ts b/services/mcp/tests/hono/session-mode-pool.test.ts
index 19688d8ff6a1..a0a08b1bbe0c 100644
--- a/services/mcp/tests/hono/session-mode-pool.test.ts
+++ b/services/mcp/tests/hono/session-mode-pool.test.ts
@@ -49,7 +49,7 @@ function createInMemoryRedis(): RedisLike & {
const cur = String(cursor)
return [cur === '0' ? 'next' : '0', cur === '0' ? Array.from(store.keys()) : []] as [string, string[]]
},
- ...makeRedisRateLimitStubs(),
+ ...makeRedisRateLimitStubs(store),
ping: async () => 'PONG',
}
}