: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): handle Redis timeouts during request setup (#107536)
Richard Solomou06949828f81c
diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.tsindex 0194c373660b..ac7d88ae3f27 100644--- a/services/mcp/src/hono/request-state-resolver.ts+++ b/services/mcp/src/hono/request-state-resolver.ts@@ -134,23 +134,20 @@ export class RequestStateResolver {const reqCtx = new RequestContext(this.redis, this.env, props, requestContext)const { features, tools, organizationId, projectId, readOnly } = props- const contextPromise = reqCtx.getContext()- const pinnedSessionContextPromise = projectId ? this.resolveSessionContext(requestContext) : undefined-await this.applyPinnedContext(reqCtx, { organizationId, projectId })+ // Start Redis reads only when Promise.all can observe their timeout rejections.// Read the active project back from the token cache (the source every tool// resolves through) rather than the request pin, so an in-session switch wins.- const cachedProjectId = (await reqCtx.tokenCache.get('projectId')) || projectId+ const [context, sessionContext, storedProjectId] = await Promise.all([+ reqCtx.getContext(),+ this.resolveSessionContext(requestContext),+ reqCtx.tokenCache.get('projectId'),+ ])+ const cachedProjectId = storedProjectId || projectIdif (!cachedProjectId) {- const contextForDefault = await contextPromise- await contextForDefault.stateManager.setDefaultOrganizationAndProject()+ await context.stateManager.setDefaultOrganizationAndProject()}-- const [context, sessionContext] = await Promise.all([- contextPromise,- pinnedSessionContextPromise ?? this.resolveSessionContext(requestContext),- ])const clientContext = getEffectiveMCPClientContext(requestContext, sessionContext)// MCP_GATEWAY_FLAG gates no tool of its own — it gates the third-party tools `exec`diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.tsindex 9487b9a6ed4f..ec310c4f72a8 100644--- a/services/mcp/tests/hono/request-state-resolver.test.ts+++ b/services/mcp/tests/hono/request-state-resolver.test.ts@@ -1,16 +1,26 @@import { beforeEach, describe, expect, it, vi } from 'vitest'-const { mockSessionStore, mockTokenStore, mockApiKey, mockSessionScopedStores, mockRefreshTtlCalls } = vi.hoisted(- () => ({- mockSessionStore: new Map<string, unknown>(),- mockTokenStore: new Map<string, unknown>(),- mockApiKey: { scopes: ['*'], scoped_teams: [], is_impersonated: undefined as boolean | undefined },- mockSessionScopedStores: new Map<string, Map<string, unknown>>(),- // Records the keys passed to every session-scoped refreshTtl call (only the- // session cache refreshes, so any recorded call is a session refresh).- mockRefreshTtlCalls: [] as string[][],- })-)+const {+ mockSessionStore,+ mockTokenStore,+ mockApiKey,+ mockSessionScopedStores,+ mockRefreshTtlCalls,+ mockRedisFailures,+} = vi.hoisted(() => ({+ mockSessionStore: new Map<string, unknown>(),+ mockTokenStore: new Map<string, unknown>(),+ mockApiKey: { scopes: ['*'], scoped_teams: [], is_impersonated: undefined as boolean | undefined },+ mockSessionScopedStores: new Map<string, Map<string, unknown>>(),+ // Records the keys passed to every session-scoped refreshTtl call (only the+ // session cache refreshes, so any recorded call is a session refresh).+ mockRefreshTtlCalls: [] as string[][],+ mockRedisFailures: {+ contextError: undefined as Error | undefined,+ pinWriteGate: undefined as Promise<void> | undefined,+ contextReads: 0,+ },+}))vi.mock('@/lib/posthog/flags', () => ({evaluateFeatureFlags: vi.fn(async () => ({})),@@ -50,6 +60,9 @@ vi.mock('@/hono/request-context', () => {store.set(key, value)}),setMany: vi.fn(async (entries: Record<string, unknown>) => {+ if (store === mockTokenStore) {+ await mockRedisFailures.pinWriteGate+ }for (const [key, value] of Object.entries(entries)) {if (value !== undefined) {store.set(key, value)@@ -82,14 +95,20 @@ vi.mock('@/hono/request-context', () => {return {tokenCache: makeCache(mockTokenStore),sessionScopedCache: props.mcpSessionId ? makeCache(sessionScopedStore(props.mcpSessionId)) : undefined,- getContext: vi.fn(async () => ({- stateManager: {- setDefaultOrganizationAndProject: vi.fn(async () => {}),- getApiKey: vi.fn(async () => mockApiKey),- getAiConsentGiven: vi.fn(async () => undefined),- getAvailableFeatures: vi.fn(async () => undefined),- },- })),+ getContext: vi.fn(async () => {+ mockRedisFailures.contextReads += 1+ if (mockRedisFailures.contextError) {+ throw mockRedisFailures.contextError+ }+ return {+ stateManager: {+ setDefaultOrganizationAndProject: vi.fn(async () => {}),+ getApiKey: vi.fn(async () => mockApiKey),+ getAiConsentGiven: vi.fn(async () => undefined),+ getAvailableFeatures: vi.fn(async () => undefined),+ },+ }+ }),safelyGetAnalyticsContext: vi.fn(async () => undefined),getDistinctId: vi.fn(async () => 'distinct-id'),setMcpContexts: vi.fn(),@@ -146,6 +165,9 @@ describe('RequestStateResolver MCP client contexts', () => {mockTokenStore.clear()mockSessionScopedStores.clear()mockRefreshTtlCalls.length = 0+ mockRedisFailures.contextError = undefined+ mockRedisFailures.pinWriteGate = undefined+ mockRedisFailures.contextReads = 0mockApiKey.scopes = ['*']mockApiKey.is_impersonated = undefined})@@ -158,6 +180,33 @@ describe('RequestStateResolver MCP client contexts', () => {expect(result.isImpersonated).toBe(impersonated === true)})+ it('handles a Redis context failure while a pinned-context write is pending', async () => {+ let releasePinWrite!: () => void+ mockRedisFailures.pinWriteGate = new Promise<void>((resolve) => {+ releasePinWrite = resolve+ })+ mockRedisFailures.contextError = new Error('Command timed out')+ const unhandled: unknown[] = []+ const onUnhandled = (error: unknown): void => {+ unhandled.push(error)+ }+ process.on('unhandledRejection', onUnhandled)++ try {+ const pending = makeResolver().resolve(makeProps())+ await new Promise<void>((resolve) => setImmediate(resolve))+ expect(mockRedisFailures.contextReads).toBe(0)+ expect(unhandled).toEqual([])+ releasePinWrite()+ await expect(pending).rejects.toThrow('Command timed out')+ await new Promise<void>((resolve) => setImmediate(resolve))+ expect(unhandled).toEqual([])+ } finally {+ releasePinWrite()+ process.off('unhandledRejection', onUnhandled)+ }+ })+it.each([['cli', false],['cli', true],