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): bound the integration kinds lookup in switch-project (#121828)

posthog[bot]09263dca4a1f
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index 1ece3ba95e90..9d869406662b 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -341,6 +341,8 @@ export class ApiClient {
query?: Record<string, unknown>
headers?: Record<string, string>
responseType?: 'json' | 'text'
+ /** Per-attempt deadline for a JSON response. Defaults to the path-based deadline. */
+ timeoutMs?: number
}): Promise<T> {
const pathname = opts.path.split(/[?#]/, 1)[0]!
if (
@@ -393,7 +395,7 @@ export class ApiClient {
return (await response.text()) as T
}
- const result = await this.fetchJson<T>(url, fetchOptions)
+ const result = await this.fetchJson<T>(url, fetchOptions, { timeoutMs: opts.timeoutMs })
if (!result.success) {
// Re-throw the original error instance so callers can instanceof-check
@@ -638,18 +640,19 @@ export class ApiClient {
}
/** Pass `idempotent` for a non-GET request that has no upstream effect, so
- * a transport fault retries it like a safe method. */
+ * a transport fault retries it like a safe method. Pass `timeoutMs` to
+ * override the per-attempt deadline. */
private async fetchJson<T>(
url: string,
options?: RequestInit,
- { idempotent = false }: { idempotent?: boolean } = {}
+ { idempotent = false, timeoutMs: timeoutOverrideMs }: { idempotent?: boolean; timeoutMs?: number } = {}
): Promise<Result<T>> {
const method = options?.method ?? 'GET'
const isSafeMethod = idempotent || SAFE_HTTP_METHODS.has(method.toUpperCase())
let waitBudgetMs = RATE_LIMIT_TOTAL_WAIT_BUDGET_MS
let rateLimitRetries = 0
let transportRetries = 0
- const timeoutMs = apiRequestTimeoutMs(url)
+ const timeoutMs = timeoutOverrideMs ?? apiRequestTimeoutMs(url)
for (;;) {
let response: Response
diff --git a/services/mcp/src/lib/StateManager.ts b/services/mcp/src/lib/StateManager.ts
index 318803164a35..48a5caf67660 100644
--- a/services/mcp/src/lib/StateManager.ts
+++ b/services/mcp/src/lib/StateManager.ts
@@ -6,6 +6,7 @@ import type { ScopedCache } from '@/lib/cache/ScopedCache'
import { StateLookupCache } from '@/lib/cache/StateLookupCache'
import {
ErrorCode,
+ hasTimeoutCause,
MissingOrganizationContextError,
MissingProjectContextError,
PostHogApiError,
@@ -32,6 +33,9 @@ const GATEWAY_TOOLS_CACHE_TTL_MS = 2 * 60 * 1000 // 2 minutes
// shows up within a minute. `ingested_event` never returns to false and warehouse sources are
// rarely removed, so a positive answer keeps the default TTL.
export const NO_DATA_CACHE_TTL_MS = 60 * 1000 // 1 minute
+// The integration list only adds a line to the environment prompt, so a slow response must not
+// hold `switch-project` for the full default request deadline. The caller serves the cached list.
+const INTEGRATION_KINDS_TIMEOUT_MS = 10 * 1000
// Cached for the short TTL like an empty answer, so an unreadable list is not requested on every call.
const UNKNOWN_WAREHOUSE_COUNT = -1
@@ -506,6 +510,8 @@ export class StateManager {
fetchedAtKey: F
fetcher: () => Promise<NonNullable<State[D]>>
ttlMs?: number | ((cached: State[D]) => number)
+ /** Skip the error report when the fetch hits its deadline. Use it for optional data with a short timeout. */
+ expectTimeouts?: boolean
}): Promise<State[D]> {
const [cached, fetchedAt] = (await Promise.all([
this._cache.get(opts.cacheKey),
@@ -529,7 +535,9 @@ export class StateManager {
])
return data as State[D]
} catch (error) {
- this._reportException(error, `get_or_fetch_${opts.name}`)
+ if (!(opts.expectTimeouts && hasTimeoutCause(error))) {
+ this._reportException(error, `get_or_fetch_${opts.name}`)
+ }
await this._cache.set(opts.fetchedAtKey, Date.now() as State[F]).catch(() => {})
return cached
}
@@ -668,9 +676,11 @@ export class StateManager {
method: 'GET',
path: `/api/projects/${encodeURIComponent(projectId)}/integrations/`,
query: { limit: 100 },
+ timeoutMs: INTEGRATION_KINDS_TIMEOUT_MS,
})
return [...new Set((result.results ?? []).map((integration) => String(integration.kind)))].sort()
},
+ expectTimeouts: true,
})
}
diff --git a/services/mcp/tests/unit/StateManager.test.ts b/services/mcp/tests/unit/StateManager.test.ts
index ad060487396d..573b47dcd2a8 100644
--- a/services/mcp/tests/unit/StateManager.test.ts
+++ b/services/mcp/tests/unit/StateManager.test.ts
@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { ApiClient } from '@/api/client'
import { MemoryCache } from '@/lib/cache/MemoryCache'
import { StateLookupCache } from '@/lib/cache/StateLookupCache'
-import { PostHogApiError } from '@/lib/errors'
+import { PostHogApiError, PostHogTransportError } from '@/lib/errors'
import { getPostHogClient } from '@/lib/posthog'
import { StateManager } from '@/lib/StateManager'
import type { ApiRedactedPersonalApiKey, ApiUser } from '@/schema/api'
@@ -1351,9 +1351,52 @@ describe('StateManager', () => {
expect(result).toEqual(['github', 'slack'])
expect(request).toHaveBeenCalledWith(
- expect.objectContaining({ method: 'GET', path: `/api/projects/${projectId}/integrations/` })
+ expect.objectContaining({
+ method: 'GET',
+ path: `/api/projects/${projectId}/integrations/`,
+ timeoutMs: 10 * 1000,
+ })
)
})
+
+ it.each([
+ [
+ 'a timeout',
+ new PostHogTransportError({
+ url: 'https://us.posthog.com/api/projects/42/integrations/',
+ method: 'GET',
+ attempts: 1,
+ retryable: true,
+ cause: new DOMException('No response within 10 seconds', 'TimeoutError'),
+ }),
+ false,
+ ],
+ [
+ 'an HTTP 500',
+ new PostHogApiError({
+ status: 500,
+ statusText: 'Internal Server Error',
+ body: '',
+ url: 'https://us.posthog.com/api/projects/42/integrations/',
+ method: 'GET',
+ }),
+ true,
+ ],
+ ])('returns the cached kinds on %s', async (_name, error, reported) => {
+ await cache.set('apiKey', { scopes: ['integration:read'], scoped_organizations: [], scoped_teams: [] })
+ await cache.set('apiKeyFetchedAt', Date.now())
+ await cache.set(`integrationKinds:${projectId}` as any, ['github'] as any)
+ const reportSpy = vi.spyOn(stateManager as any, '_reportException').mockImplementation(() => {})
+ ;(stateManager as any)._api = {
+ config: { apiToken: 'phx_test' },
+ request: vi.fn().mockRejectedValue(error),
+ }
+
+ const result = await stateManager.getOrFetchIntegrationKinds(projectId)
+
+ expect(result).toEqual(['github'])
+ expect(reportSpy).toHaveBeenCalledTimes(reported ? 1 : 0)
+ })
})
describe('getAnalyticsContext', () => {
diff --git a/services/mcp/tests/unit/api-client.test.ts b/services/mcp/tests/unit/api-client.test.ts
index 710874bc763b..45df49b6684c 100644
--- a/services/mcp/tests/unit/api-client.test.ts
+++ b/services/mcp/tests/unit/api-client.test.ts
@@ -790,5 +790,17 @@ describe('ApiClient', () => {
expect(await pending).toMatchObject({ timedOut: true })
}
)
+
+ it('ends a request at its own shorter deadline', async () => {
+ stubStalledFetch()
+ const client = new ApiClient({ apiToken: 'phx_test', baseUrl: 'https://us.posthog.com' })
+ const pending = client
+ .request({ method: 'GET', path: '/api/projects/17/integrations/', timeoutMs: 10 * 1000 })
+ .catch((error) => error)
+
+ await vi.advanceTimersByTimeAsync(10 * 1000)
+
+ expect(await pending).toMatchObject({ timedOut: true })
+ })
})
})