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): drop global outbound rate limiter, honor 429 retry-after (#62861)

Georgiy Tarasov1bdb90ef3e4f
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index 27263d913ef4..38c0dec3bc37 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -2,7 +2,14 @@ import { createParser } from 'eventsource-parser'
import { z } from 'zod'
import { getUserAgent } from '@/lib/constants'
-import { ErrorCode, PostHogApiError, PostHogPermissionError, PostHogValidationError } from '@/lib/errors'
+import {
+ ErrorCode,
+ parseRetryAfterSeconds,
+ PostHogApiError,
+ PostHogPermissionError,
+ PostHogRateLimitError,
+ PostHogValidationError,
+} from '@/lib/errors'
import { getSearchParamsFromRecord } from '@/lib/utils.js'
import type {
ApiEventDefinition,
@@ -21,7 +28,15 @@ import { buildMetricEntries, ExperimentExposureQuerySchema } from '@/schema/expe
import { isShortId } from '@/tools/insights/utils'
import type { Schemas } from './generated.js'
-import { globalRateLimiter } from './rate-limiter.js'
+
+// Outbound 429 retry policy. The API is the source of truth for rate limits
+// (per-scope, with per-team overrides), so we honor its Retry-After signal and
+// fall back to jittered exponential backoff when the header is missing or
+// invalid. The total wait budget bounds how long a throttled tool call can
+// hold the MCP client's request open across all retries combined.
+const RATE_LIMIT_MAX_RETRIES = 3
+const RATE_LIMIT_BASE_BACKOFF_MS = 2000
+const RATE_LIMIT_TOTAL_WAIT_BUDGET_MS = 30_000
// Default overall timeout for an SSE stream (wall-clock cap from connect to close).
// Sized to comfortably cover the slowest known caller (session summarization, ~5 min
@@ -130,7 +145,6 @@ export class ApiClient {
}
private async fetch(url: string, options?: RequestInit): Promise<Response> {
- // TODO: should we move rate limiting from `fetchJson` to here?
const defaultHeaders: HeadersInit = {
Authorization: `Bearer ${this.config.apiToken}`,
'User-Agent': getUserAgent({ clientUserAgent: this.config.clientUserAgent }),
@@ -174,7 +188,7 @@ export class ApiClient {
}
/**
- * Generic HTTP request with auth, rate limiting, and retries.
+ * Generic HTTP request with auth.
* Used by generated tool handlers to avoid duplicating endpoint-specific methods.
*/
async request<T = unknown>(opts: {
@@ -323,41 +337,52 @@ export class ApiClient {
}
private async fetchJson<T>(url: string, options?: RequestInit): Promise<Result<T>> {
- const maxRetries = 3
- const baseBackoffMs = 2000
const method = options?.method ?? 'GET'
+ let waitBudgetMs = RATE_LIMIT_TOTAL_WAIT_BUDGET_MS
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
+ for (let attempt = 0; attempt <= RATE_LIMIT_MAX_RETRIES; attempt++) {
try {
- // Apply rate limiting before making the request
- await globalRateLimiter.throttle()
-
const response = await this.fetch(url, options)
- // Handle rate limiting with exponential backoff
if (response.status === 429) {
- if (attempt < maxRetries) {
- // Check for Retry-After header
- const retryAfter = response.headers.get('Retry-After')
- const delayMs = retryAfter
- ? parseInt(retryAfter, 10) * 1000
- : baseBackoffMs * Math.pow(2, attempt)
+ const retryAfterSeconds = parseRetryAfterSeconds(response.headers.get('Retry-After'))
+ const rateLimitFailure = async (): Promise<Result<T>> => ({
+ success: false,
+ error: new PostHogRateLimitError({
+ body: await response.text(),
+ url,
+ method,
+ retryAfterSeconds,
+ }),
+ })
+ if (attempt === RATE_LIMIT_MAX_RETRIES) {
+ console.error(`[API] Rate limit (429) retries exhausted on ${method} ${url}`)
+ return rateLimitFailure()
+ }
+
+ // DRF rejects throttled requests before the view executes,
+ // so retrying is safe for mutations too.
+ const backoffMs = RATE_LIMIT_BASE_BACKOFF_MS * 2 ** attempt
+ const delayMs =
+ retryAfterSeconds !== null
+ ? retryAfterSeconds * 1000
+ : // Equal jitter so concurrent 429s don't retry in lockstep.
+ backoffMs / 2 + Math.random() * (backoffMs / 2)
+
+ if (delayMs > waitBudgetMs) {
console.warn(
- `[API] Rate limited (429) on ${method} ${url}. Retrying in ${delayMs}ms (attempt ${attempt + 1}/${maxRetries})`
+ `[API] Rate limited (429) on ${method} ${url}. Requested wait of ${Math.round(delayMs / 1000)}s exceeds the remaining ${Math.round(waitBudgetMs / 1000)}s retry budget; not retrying.`
)
- await new Promise((resolve) => setTimeout(resolve, delayMs))
- continue
- }
- // Max retries exceeded
- const errorText = await response.text()
- console.error(`[API] Rate limit exceeded after ${maxRetries} retries on ${method} ${url}`)
- return {
- success: false,
- error: new Error(
- `Rate limit exceeded after ${maxRetries} retries:\nURL: ${method} ${url}\nStatus Code: ${response.status}\nError Message: ${errorText}`
- ),
+ return rateLimitFailure()
}
+
+ waitBudgetMs -= delayMs
+ console.warn(
+ `[API] Rate limited (429) on ${method} ${url}. Retrying in ${Math.round(delayMs)}ms (attempt ${attempt + 1}/${RATE_LIMIT_MAX_RETRIES})`
+ )
+ await new Promise((resolve) => setTimeout(resolve, delayMs))
+ continue
}
if (!response.ok) {
@@ -439,19 +464,13 @@ export class ApiClient {
return { success: true, data: rawText as T }
}
} catch (error) {
- // Only retry on rate limit errors, not other errors
- if (error instanceof Error && error.message.includes('Rate limit')) {
- continue
- }
return { success: false, error: error as Error }
}
}
- // This should never be reached, but TypeScript needs it
- return {
- success: false,
- error: new Error('Unexpected error in retry logic'),
- }
+ // Unreachable: the final attempt always returns above, but TypeScript
+ // can't prove the loop is exhaustive.
+ return { success: false, error: new Error('Unexpected rate limit retry state') }
}
organizations(): Endpoint {
diff --git a/services/mcp/src/api/fetcher.ts b/services/mcp/src/api/fetcher.ts
deleted file mode 100644
index bf466f110325..000000000000
--- a/services/mcp/src/api/fetcher.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-import { getUserAgent } from '@/lib/constants'
-import { PostHogApiError } from '@/lib/errors'
-
-import type { ApiConfig } from './client'
-import { globalRateLimiter } from './rate-limiter'
-
-const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))
-
-export interface Fetcher {
- fetch: (input: {
- method: string
- url: URL
- urlSearchParams?: URLSearchParams
- parameters?: { body?: unknown; header?: Record<string, unknown> }
- path: string
- overrides?: RequestInit
- }) => Promise<Response>
-}
-
-export const buildApiFetcher: (config: ApiConfig) => Fetcher = (config) => {
- return {
- fetch: async (input) => {
- const maxRetries = 3
- const baseBackoffMs = 2000
-
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
- // Apply rate limiting before making the request
- await globalRateLimiter.throttle()
-
- const headers = new Headers()
- headers.set('Authorization', `Bearer ${config.apiToken}`)
- headers.set('User-Agent', getUserAgent({ clientUserAgent: config.clientUserAgent }))
- if (config.clientUserAgent) {
- // Forward the originating client's User-Agent so the PostHog API can
- // attach it to analytics events for MCP source attribution.
- headers.set('x-posthog-mcp-user-agent', config.clientUserAgent)
- }
- if (config.mcpConsumer) {
- headers.set('x-posthog-mcp-consumer', config.mcpConsumer)
- }
- if (config.oauthClientName) {
- headers.set('x-posthog-mcp-oauth-client-name', config.oauthClientName)
- }
-
- // Handle query parameters
- if (input.urlSearchParams) {
- input.url.search = input.urlSearchParams.toString()
- }
-
- // Handle request body for mutation methods
- const body = ['post', 'put', 'patch', 'delete'].includes(input.method.toLowerCase())
- ? JSON.stringify(input.parameters?.body)
- : undefined
-
- if (body) {
- headers.set('Content-Type', 'application/json')
- }
-
- // Add custom headers
- if (input.parameters?.header) {
- for (const [key, value] of Object.entries(input.parameters.header)) {
- if (value != null) {
- headers.set(key, String(value))
- }
- }
- }
-
- const response = await fetch(input.url, {
- method: input.method.toUpperCase(),
- ...(body && { body }),
- headers,
- ...input.overrides,
- })
-
- // Handle rate limiting with exponential backoff
- if (response.status === 429) {
- if (attempt < maxRetries) {
- // Check for Retry-After header
- const retryAfter = response.headers.get('Retry-After')
- const delayMs = retryAfter
- ? parseInt(retryAfter, 10) * 1000
- : baseBackoffMs * Math.pow(2, attempt)
-
- console.warn(
- `Rate limited (429). Retrying in ${delayMs}ms (attempt ${attempt + 1}/${maxRetries})`
- )
- await sleep(delayMs)
- continue
- }
- // Max retries exceeded
- const errorResponse = await response.json()
- throw new Error(
- `Rate limit exceeded after ${maxRetries} retries: [${response.status}] ${JSON.stringify(errorResponse)}`
- )
- }
-
- if (!response.ok) {
- const errorResponse = await response.json()
- const errorBody = JSON.stringify(errorResponse)
- throw new PostHogApiError({
- status: response.status,
- statusText: response.statusText,
- body: errorBody,
- url: input.url.toString(),
- method: input.method.toUpperCase(),
- message: `Failed request: [${response.status}] ${errorBody}`,
- })
- }
-
- return response
- }
-
- // This should never be reached, but TypeScript needs it
- throw new Error('Unexpected error in retry logic')
- },
- }
-}
diff --git a/services/mcp/src/api/rate-limiter.ts b/services/mcp/src/api/rate-limiter.ts
deleted file mode 100644
index ea5f7b6f28bc..000000000000
--- a/services/mcp/src/api/rate-limiter.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * Simple rate limiter to control request frequency
- * Uses a sliding window approach to limit requests per time period
- */
-export class RateLimiter {
- private requestTimestamps: number[] = []
- private readonly maxRequests: number
- private readonly windowMs: number
-
- constructor(maxRequests: number = 10, windowMs: number = 1000) {
- this.maxRequests = maxRequests
- this.windowMs = windowMs
- }
-
- /**
- * Wait if necessary to respect rate limits, then record the request
- */
- async throttle(): Promise<void> {
- const now = Date.now()
-
- // Remove timestamps outside the current window
- this.requestTimestamps = this.requestTimestamps.filter((timestamp) => now - timestamp < this.windowMs)
-
- // If we're at the limit, wait until the oldest request expires
- if (this.requestTimestamps.length >= this.maxRequests) {
- const oldestTimestamp = this.requestTimestamps[0]!
- const waitTime = this.windowMs - (now - oldestTimestamp) + 10 // Add 10ms buffer
-
- if (waitTime > 0) {
- await new Promise((resolve) => setTimeout(resolve, waitTime))
- }
-
- // Clean up again after waiting
- const newNow = Date.now()
- this.requestTimestamps = this.requestTimestamps.filter((timestamp) => newNow - timestamp < this.windowMs)
- }
-
- // Record this request
- this.requestTimestamps.push(Date.now())
- }
-
- /**
- * Reset the rate limiter state
- */
- reset(): void {
- this.requestTimestamps = []
- }
-}
-
-// Global rate limiter instance for API requests
-// Set to 10 requests per second to be conservative
-export const globalRateLimiter = new RateLimiter(10, 1000)
diff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.ts
index 8e45b27081ca..4ea79a0c60ed 100644
--- a/services/mcp/src/lib/errors.ts
+++ b/services/mcp/src/lib/errors.ts
@@ -178,6 +178,49 @@ function buildDefaultApiErrorMessage(options: PostHogApiErrorOptions): string {
return `Request failed:\nURL: ${options.method} ${options.url}\nStatus Code: ${options.status} (${options.statusText})\nError Message: ${options.body}`
}
+export interface PostHogRateLimitErrorOptions {
+ body: string
+ url: string
+ method: string
+ retryAfterSeconds: number | null
+}
+
+/**
+ * Thrown when the PostHog API responds with HTTP 429. Never retried inside the
+ * MCP server: sleeping here keeps the client's request open and lets pending
+ * work pile up behind it, so the rate limit is surfaced immediately with the
+ * server's Retry-After hint and the client decides when to retry.
+ */
+export class PostHogRateLimitError extends PostHogApiError {
+ public readonly retryAfterSeconds: number | null
+
+ constructor(options: PostHogRateLimitErrorOptions) {
+ const retryHint = options.retryAfterSeconds !== null ? ` Retry after ${options.retryAfterSeconds} seconds.` : ''
+ super({
+ status: 429,
+ statusText: 'Too Many Requests',
+ body: options.body,
+ url: options.url,
+ method: options.method,
+ message: `PostHog API rate limit exceeded (429) on ${options.method} ${options.url}.${retryHint}`,
+ })
+ this.name = 'PostHogRateLimitError'
+ this.retryAfterSeconds = options.retryAfterSeconds
+ }
+}
+
+/**
+ * Parses a Retry-After header into whole seconds. Returns null for missing
+ * headers, HTTP-date values, and bogus negatives.
+ */
+export function parseRetryAfterSeconds(header: string | null): number | null {
+ if (!header) {
+ return null
+ }
+ const seconds = Number.parseInt(header, 10)
+ return Number.isNaN(seconds) || seconds < 0 ? null : seconds
+}
+
export interface PostHogPermissionErrorOptions {
detail: string
missingScope?: string | undefined
diff --git a/services/mcp/tests/unit/fetcher.test.ts b/services/mcp/tests/unit/fetcher.test.ts
deleted file mode 100644
index 6651707292ba..000000000000
--- a/services/mcp/tests/unit/fetcher.test.ts
+++ /dev/null
@@ -1,343 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-
-import { buildApiFetcher, type Fetcher } from '@/api/fetcher'
-import { globalRateLimiter } from '@/api/rate-limiter'
-import { PostHogApiError } from '@/lib/errors'
-
-// Mock the global rate limiter
-vi.mock('@/api/rate-limiter', () => ({
- globalRateLimiter: {
- throttle: vi.fn().mockResolvedValue(undefined),
- },
-}))
-
-type FetchInput = Parameters<Fetcher['fetch']>[0]
-
-describe('buildApiFetcher', () => {
- const mockConfig = {
- apiToken: 'test-token-123',
- baseUrl: 'https://api.example.com',
- }
-
- const baseFetchInput: FetchInput = {
- url: new URL('https://api.example.com/test'),
- method: 'get',
- path: '/test',
- }
-
- beforeEach(() => {
- vi.clearAllMocks()
- vi.useFakeTimers()
- global.fetch = vi.fn()
- })
-
- afterEach(() => {
- vi.restoreAllMocks()
- })
-
- describe('successful requests', () => {
- it('should make a successful GET request', async () => {
- const mockResponse = new Response(JSON.stringify({ data: 'test' }), {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- })
- vi.mocked(global.fetch).mockResolvedValueOnce(mockResponse)
-
- const fetcher = buildApiFetcher(mockConfig)
- const response = await fetcher.fetch(baseFetchInput)
-
- expect(response.ok).toBe(true)
- expect(global.fetch).toHaveBeenCalledTimes(1)
- expect(globalRateLimiter.throttle).toHaveBeenCalledTimes(1)
- })
-
- it('should include authorization header', async () => {
- const mockResponse = new Response('{}', { status: 200 })
- vi.mocked(global.fetch).mockResolvedValueOnce(mockResponse)
-
- const fetcher = buildApiFetcher(mockConfig)
- await fetcher.fetch(baseFetchInput)
-
- const fetchCall = vi.mocked(global.fetch).mock.calls[0]!
- const headers = fetchCall[1]?.headers as Headers
- expect(headers.get('Authorization')).toBe('Bearer test-token-123')
- })
-
- it('should handle POST request with body', async () => {
- const mockResponse = new Response('{}', { status: 201 })
- vi.mocked(global.fetch).mockResolvedValueOnce(mockResponse)
-
- const fetcher = buildApiFetcher(mockConfig)
- await fetcher.fetch({
- ...baseFetchInput,
- method: 'post',
- parameters: {
- body: { name: 'test', value: 123 },
- },
- })
-
- const fetchCall = vi.mocked(global.fetch).mock.calls[0]!
- expect(fetchCall[1]?.method).toBe('POST')
- expect(fetchCall[1]?.body).toBe(JSON.stringify({ name: 'test', value: 123 }))
- const headers = fetchCall[1]?.headers as Headers
- expect(headers.get('Content-Type')).toBe('application/json')
- })
-
- it('should handle query parameters', async () => {
- const mockResponse = new Response('{}', { status: 200 })
- vi.mocked(global.fetch).mockResolvedValueOnce(mockResponse)
-
- const fetcher = buildApiFetcher(mockConfig)
- const url = new URL('https://api.example.com/test')
- const urlSearchParams = new URLSearchParams({ foo: 'bar', baz: 'qux' })
-
- await fetcher.fetch({
- ...baseFetchInput,
- url,
- urlSearchParams,
- })
-
- expect(url.search).toBe('?foo=bar&baz=qux')
- })
-
- it('should handle custom headers', async () => {
- const mockResponse = new Response('{}', { status: 200 })
- vi.mocked(global.fetch).mockResolvedValueOnce(mockResponse)
-
- const fetcher = buildApiFetcher(mockConfig)
- await fetcher.fetch({
- ...baseFetchInput,
- parameters: {
- header: {
- 'X-Custom-Header': 'custom-value',
- 'X-Another-Header': '123',
- },
- },
- })
-
- const fetchCall = vi.mocked(global.fetch).mock.calls[0]!
- const headers = fetchCall[1]?.headers as Headers
- expect(headers.get('X-Custom-Header')).toBe('custom-value')
- expect(headers.get('X-Another-Header')).toBe('123')
- })
- })
-
- describe('exponential backoff on 429 rate limit', () => {
- it('should retry with exponential backoff on 429 response', async () => {
- const mock429Response = new Response('{}', { status: 429 })
- const mockSuccessResponse = new Response('{}', { status: 200 })
-
- vi.mocked(global.fetch).mockResolvedValueOnce(mock429Response).mockResolvedValueOnce(mockSuccessResponse)
-
- const fetcher = buildApiFetcher(mockConfig)
- const promise = fetcher.fetch(baseFetchInput)
-
- // Advance time for first retry (2000ms * 2^0 = 2000ms)
- await vi.advanceTimersByTimeAsync(2000)
- await promise
-
- expect(global.fetch).toHaveBeenCalledTimes(2)
- expect(globalRateLimiter.throttle).toHaveBeenCalledTimes(2)
- })
-
- it('should use exponential backoff delays: 2s, 4s, 8s', async () => {
- const mock429Response = new Response('{}', { status: 429 })
- const mockSuccessResponse = new Response('{}', { status: 200 })
-
- vi.mocked(global.fetch)
- .mockResolvedValueOnce(mock429Response) // Attempt 0: retry after 2s
- .mockResolvedValueOnce(mock429Response) // Attempt 1: retry after 4s
- .mockResolvedValueOnce(mock429Response) // Attempt 2: retry after 8s
- .mockResolvedValueOnce(mockSuccessResponse) // Attempt 3: success
-
- const fetcher = buildApiFetcher(mockConfig)
- const promise = fetcher.fetch(baseFetchInput)
-
- // First retry: 2000ms * 2^0 = 2000ms
- await vi.advanceTimersByTimeAsync(2000)
-
- // Second retry: 2000ms * 2^1 = 4000ms
- await vi.advanceTimersByTimeAsync(4000)
-
- // Third retry: 2000ms * 2^2 = 8000ms
- await vi.advanceTimersByTimeAsync(8000)
-
- await promise
-
- expect(global.fetch).toHaveBeenCalledTimes(4)
- })
-
- it('should respect Retry-After header when present', async () => {
- const mock429Response = new Response('{}', {
- status: 429,
- headers: { 'Retry-After': '5' }, // 5 seconds
- })
- const mockSuccessResponse = new Response('{}', { status: 200 })
-
- vi.mocked(global.fetch).mockResolvedValueOnce(mock429Response).mockResolvedValueOnce(mockSuccessResponse)
-
- const fetcher = buildApiFetcher(mockConfig)
- const promise = fetcher.fetch(baseFetchInput)
-
- // Should wait 5000ms (from Retry-After header) instead of 2000ms
- await vi.advanceTimersByTimeAsync(5000)
- await promise
-
- expect(global.fetch).toHaveBeenCalledTimes(2)
- })
-
- it('should throw error after max retries exceeded', async () => {
- const mock429Response = new Response(JSON.stringify({ error: 'Rate limited' }), {
- status: 429,
- })
-
- vi.mocked(global.fetch).mockResolvedValue(mock429Response)
-
- const fetcher = buildApiFetcher(mockConfig)
-
- // Start the fetch and immediately wrap in expect to catch rejection
- const fetchPromise = expect(fetcher.fetch(baseFetchInput)).rejects.toThrow(
- 'Rate limit exceeded after 3 retries'
- )
-
- // Run all timers to completion
- await vi.runAllTimersAsync()
-
- // Wait for the assertion
- await fetchPromise
-
- expect(global.fetch).toHaveBeenCalledTimes(4) // Initial + 3 retries
- })
-
- it('should log warnings during retries', async () => {
- const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
- const mock429Response = new Response('{}', { status: 429 })
- const mockSuccessResponse = new Response('{}', { status: 200 })
-
- vi.mocked(global.fetch).mockResolvedValueOnce(mock429Response).mockResolvedValueOnce(mockSuccessResponse)
-
- const fetcher = buildApiFetcher(mockConfig)
- const promise = fetcher.fetch(baseFetchInput)
-
- await vi.advanceTimersByTimeAsync(2000)
- await promise
-
- expect(consoleWarnSpy).toHaveBeenCalledWith(
- expect.stringContaining('Rate limited (429). Retrying in 2000ms (attempt 1/3)')
- )
-
- consoleWarnSpy.mockRestore()
- })
- })
-
- describe('error handling', () => {
- it('should throw a typed PostHogApiError on non-429 4xx responses', async () => {
- vi.mocked(global.fetch).mockResolvedValueOnce(
- new Response(JSON.stringify({ error: 'Not found' }), {
- status: 404,
- statusText: 'Not Found',
- })
- )
-
- const fetcher = buildApiFetcher(mockConfig)
-
- const thrown = await fetcher.fetch(baseFetchInput).catch((err) => err)
- expect(thrown).toBeInstanceOf(PostHogApiError)
- expect(thrown).toMatchObject({
- status: 404,
- statusText: 'Not Found',
- })
- expect(thrown.message).toContain('Failed request: [404]')
-
- // Should not retry on non-429 errors
- expect(global.fetch).toHaveBeenCalledTimes(1)
- })
-
- it('should throw a typed PostHogApiError on 5xx responses without retry', async () => {
- vi.mocked(global.fetch).mockResolvedValueOnce(
- new Response(JSON.stringify({ error: 'Internal error' }), {
- status: 500,
- statusText: 'Internal Server Error',
- })
- )
-
- const fetcher = buildApiFetcher(mockConfig)
-
- const thrown = await fetcher.fetch(baseFetchInput).catch((err) => err)
- expect(thrown).toBeInstanceOf(PostHogApiError)
- expect(thrown.status).toBe(500)
- expect(thrown.message).toContain('Failed request: [500]')
-
- expect(global.fetch).toHaveBeenCalledTimes(1)
- })
- })
-
- describe('rate limiter integration', () => {
- it('should call rate limiter before each request', async () => {
- const mock429Response = new Response('{}', { status: 429 })
- const mockSuccessResponse = new Response('{}', { status: 200 })
-
- vi.mocked(global.fetch).mockResolvedValueOnce(mock429Response).mockResolvedValueOnce(mockSuccessResponse)
-
- const fetcher = buildApiFetcher(mockConfig)
- const promise = fetcher.fetch(baseFetchInput)
-
- await vi.advanceTimersByTimeAsync(2000)
- await promise
-
- // Should call throttle before initial request and before retry
- expect(globalRateLimiter.throttle).toHaveBeenCalledTimes(2)
- })
-
- it('should call rate limiter on all retry attempts', async () => {
- const mock429Response = new Response('{}', { status: 429 })
- const mockSuccessResponse = new Response('{}', { status: 200 })
-
- vi.mocked(global.fetch)
- .mockResolvedValueOnce(mock429Response)
- .mockResolvedValueOnce(mock429Response)
- .mockResolvedValueOnce(mockSuccessResponse)
-
- const fetcher = buildApiFetcher(mockConfig)
- const promise = fetcher.fetch(baseFetchInput)
-
- await vi.advanceTimersByTimeAsync(2000)
- await vi.advanceTimersByTimeAsync(4000)
- await promise
-
- // Initial + 2 retries = 3 calls
- expect(globalRateLimiter.throttle).toHaveBeenCalledTimes(3)
- })
- })
-
- describe('HTTP methods', () => {
- it.each(['post', 'put', 'patch', 'delete'] as const)('should include body for %s requests', async (method) => {
- const mockResponse = new Response('{}', { status: 200 })
- vi.mocked(global.fetch).mockResolvedValueOnce(mockResponse)
-
- const fetcher = buildApiFetcher(mockConfig)
- await fetcher.fetch({
- ...baseFetchInput,
- method,
- parameters: {
- body: { test: 'data' },
- },
- })
-
- const fetchCall = vi.mocked(global.fetch).mock.calls[0]!
- expect(fetchCall[1]?.body).toBe(JSON.stringify({ test: 'data' }))
- expect(fetchCall[1]?.method).toBe(method.toUpperCase())
- })
-
- it('should not include body for GET requests', async () => {
- const mockResponse = new Response('{}', { status: 200 })
- vi.mocked(global.fetch).mockResolvedValueOnce(mockResponse)
-
- const fetcher = buildApiFetcher(mockConfig)
- await fetcher.fetch(baseFetchInput)
-
- const fetchCall = vi.mocked(global.fetch).mock.calls[0]!
- expect(fetchCall[1]?.body).toBeUndefined()
- })
- })
-})
diff --git a/services/mcp/tests/unit/permission-errors.test.ts b/services/mcp/tests/unit/permission-errors.test.ts
index 842d50c8697c..df3171b1b6cf 100644
--- a/services/mcp/tests/unit/permission-errors.test.ts
+++ b/services/mcp/tests/unit/permission-errors.test.ts
@@ -12,12 +12,6 @@ import {
wrapError,
} from '@/lib/errors'
-vi.mock('@/api/rate-limiter', () => ({
- globalRateLimiter: {
- throttle: vi.fn().mockResolvedValue(undefined),
- },
-}))
-
const captureException = vi.fn()
vi.mock('@/lib/posthog', () => ({
getPostHogClient: () => ({ captureException }),
diff --git a/services/mcp/tests/unit/rate-limit-errors.test.ts b/services/mcp/tests/unit/rate-limit-errors.test.ts
new file mode 100644
index 000000000000..6cbc7cff40da
--- /dev/null
+++ b/services/mcp/tests/unit/rate-limit-errors.test.ts
@@ -0,0 +1,187 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { ApiClient, type Result } from '@/api/client'
+import { handleToolError, parseRetryAfterSeconds, PostHogApiError, PostHogRateLimitError } from '@/lib/errors'
+
+const captureException = vi.fn()
+vi.mock('@/lib/posthog', () => ({
+ getPostHogClient: () => ({ captureException }),
+}))
+vi.mock('@/lib/posthog/analytics', () => ({
+ AnalyticsEvent: { MCP_INIT: 'mcp init' },
+}))
+vi.mock('@/lib/posthog/flags', () => ({
+ isFeatureFlagEnabled: vi.fn().mockResolvedValue(false),
+}))
+
+describe('outbound 429 handling', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+ })
+
+ describe('parseRetryAfterSeconds', () => {
+ it.each([
+ { header: '5', expected: 5 },
+ { header: '0', expected: 0 },
+ { header: '-5', expected: null },
+ { header: 'Wed, 21 Oct 2026 07:28:00 GMT', expected: null },
+ { header: null, expected: null },
+ ])('parses $header as $expected', ({ header, expected }) => {
+ expect(parseRetryAfterSeconds(header)).toBe(expected)
+ })
+ })
+
+ describe('PostHogRateLimitError', () => {
+ it('includes the retry hint when seconds are known', () => {
+ const error = new PostHogRateLimitError({
+ body: '{}',
+ url: 'https://us.posthog.com/api/environments/2/query/',
+ method: 'POST',
+ retryAfterSeconds: 12,
+ })
+
+ expect(error).toBeInstanceOf(PostHogApiError)
+ expect(error.status).toBe(429)
+ expect(error.retryAfterSeconds).toBe(12)
+ expect(error.message).toContain('Retry after 12 seconds')
+ })
+
+ it('omits the retry hint when seconds are unknown', () => {
+ const error = new PostHogRateLimitError({
+ body: '{}',
+ url: 'https://us.posthog.com/api/users/@me/',
+ method: 'GET',
+ retryAfterSeconds: null,
+ })
+
+ expect(error.retryAfterSeconds).toBeNull()
+ expect(error.message).not.toContain('Retry after')
+ })
+ })
+
+ describe('ApiClient on 429', () => {
+ const build429 = (headers?: Record<string, string>): Response =>
+ new Response(JSON.stringify({ detail: 'Request was throttled.' }), { status: 429, headers })
+
+ const stubFetch = (...responses: Response[]): ReturnType<typeof vi.fn> => {
+ const mockFetch = vi.fn()
+ for (const response of responses) {
+ mockFetch.mockResolvedValueOnce(response)
+ }
+ // Persistent 429 once the scripted responses run out.
+ mockFetch.mockImplementation(() => Promise.resolve(build429({ 'Retry-After': '1' })))
+ vi.stubGlobal('fetch', mockFetch)
+ return mockFetch
+ }
+
+ const buildClient = (): ApiClient => new ApiClient({ apiToken: 'phx_test', baseUrl: 'https://us.posthog.com' })
+
+ const expectRateLimitFailure = (result: Result<unknown>): PostHogRateLimitError => {
+ expect(result.success).toBe(false)
+ if (result.success) {
+ throw new Error('expected failure')
+ }
+ expect(result.error).toBeInstanceOf(PostHogRateLimitError)
+ return result.error as PostHogRateLimitError
+ }
+
+ beforeEach(() => {
+ vi.useFakeTimers()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it('retries after the Retry-After delay and succeeds', async () => {
+ const mockFetch = stubFetch(build429({ 'Retry-After': '5' }), new Response('{}', { status: 200 }))
+
+ const resultPromise = buildClient().users().me()
+ await vi.advanceTimersByTimeAsync(5000)
+ const result = await resultPromise
+
+ expect(result.success).toBe(true)
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ })
+
+ it('falls back to jittered backoff when Retry-After is missing', async () => {
+ const mockFetch = stubFetch(build429(), new Response('{}', { status: 200 }))
+
+ const resultPromise = buildClient().users().me()
+ // Jittered first-retry delay falls in [1000, 2000]ms.
+ await vi.advanceTimersByTimeAsync(2000)
+ const result = await resultPromise
+
+ expect(result.success).toBe(true)
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ })
+
+ it('returns PostHogRateLimitError after exhausting retries', async () => {
+ const mockFetch = stubFetch()
+
+ const resultPromise = buildClient().users().me()
+ await vi.runAllTimersAsync()
+ const rateLimitError = expectRateLimitFailure(await resultPromise)
+
+ expect(rateLimitError.retryAfterSeconds).toBe(1)
+ expect(rateLimitError.message).toContain('Retry after 1 seconds')
+ expect(mockFetch).toHaveBeenCalledTimes(4)
+ })
+
+ it('fails fast without sleeping when Retry-After exceeds the wait budget', async () => {
+ const mockFetch = stubFetch(build429({ 'Retry-After': '3600' }))
+
+ const rateLimitError = expectRateLimitFailure(await buildClient().users().me())
+
+ expect(rateLimitError.retryAfterSeconds).toBe(3600)
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ })
+
+ it('stops retrying once cumulative waits exhaust the budget', async () => {
+ // 12s + 12s sleeps spend 24s of the 30s budget; the third 12s wait
+ // exceeds the remaining 6s, so the client gives up after 3 attempts.
+ const persistent429 = (): Promise<Response> => Promise.resolve(build429({ 'Retry-After': '12' }))
+ const mockFetch = vi.fn().mockImplementation(persistent429)
+ vi.stubGlobal('fetch', mockFetch)
+
+ const resultPromise = buildClient().users().me()
+ await vi.runAllTimersAsync()
+ const rateLimitError = expectRateLimitFailure(await resultPromise)
+
+ expect(rateLimitError.retryAfterSeconds).toBe(12)
+ expect(mockFetch).toHaveBeenCalledTimes(3)
+ })
+
+ it('propagates the error through ApiClient.request()', async () => {
+ stubFetch(build429({ 'Retry-After': '3600' }))
+
+ await expect(buildClient().request({ method: 'GET', path: '/api/users/@me/' })).rejects.toBeInstanceOf(
+ PostHogRateLimitError
+ )
+ })
+ })
+
+ describe('handleToolError on PostHogRateLimitError', () => {
+ it('returns the retry hint to the agent without capturing an exception', () => {
+ const error = new PostHogRateLimitError({
+ body: '{}',
+ url: 'https://us.posthog.com/api/environments/2/query/',
+ method: 'POST',
+ retryAfterSeconds: 12,
+ })
+
+ const result = handleToolError(error, 'query-run')
+
+ expect(result.isError).toBe(true)
+ const text = (result.content[0] as { text: string }).text
+ expect(text).toContain('Retry after 12 seconds')
+ expect(captureException).not.toHaveBeenCalled()
+ })
+ })
+})
diff --git a/services/mcp/tests/unit/rate-limiter.test.ts b/services/mcp/tests/unit/rate-limiter.test.ts
deleted file mode 100644
index 0e10b485f6fe..000000000000
--- a/services/mcp/tests/unit/rate-limiter.test.ts
+++ /dev/null
@@ -1,218 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-
-import { RateLimiter } from '@/api/rate-limiter'
-
-describe('RateLimiter', () => {
- beforeEach(() => {
- vi.useFakeTimers()
- })
-
- afterEach(() => {
- vi.restoreAllMocks()
- })
-
- it('should create RateLimiter with default config', () => {
- const limiter = new RateLimiter()
- expect(limiter).toBeInstanceOf(RateLimiter)
- })
-
- it('should create RateLimiter with custom config', () => {
- const limiter = new RateLimiter(5, 2000)
- expect(limiter).toBeInstanceOf(RateLimiter)
- })
-
- it('should allow requests under the limit', async () => {
- const limiter = new RateLimiter(3, 1000)
- const startTime = Date.now()
-
- await limiter.throttle()
- await limiter.throttle()
- await limiter.throttle()
-
- const endTime = Date.now()
- // Should complete almost immediately (within 50ms)
- expect(endTime - startTime).toBeLessThan(50)
- })
-
- it('should throttle requests when limit is exceeded', async () => {
- const limiter = new RateLimiter(2, 1000)
-
- // First two requests should go through immediately
- await limiter.throttle()
- await limiter.throttle()
-
- // Third request should be delayed
- const promise = limiter.throttle()
-
- // Advance time by 500ms - should still be waiting
- await vi.advanceTimersByTimeAsync(500)
-
- // Advance time by another 520ms (total 1020ms) - should now complete
- await vi.advanceTimersByTimeAsync(520)
- await promise
-
- // Verify the request completed
- expect(true).toBe(true)
- })
-
- it('should allow requests after window expires', async () => {
- const limiter = new RateLimiter(2, 1000)
-
- // Make 2 requests
- await limiter.throttle()
- await limiter.throttle()
-
- // Advance time past the window
- await vi.advanceTimersByTimeAsync(1100)
-
- // Next request should go through immediately
- const startTime = Date.now()
- await limiter.throttle()
- const endTime = Date.now()
-
- expect(endTime - startTime).toBeLessThan(50)
- })
-
- it('should handle multiple sequential throttled requests', async () => {
- const limiter = new RateLimiter(2, 1000)
-
- // Fill the limit
- await limiter.throttle()
- await limiter.throttle()
-
- // Queue up multiple requests
- const promise1 = limiter.throttle()
- const promise2 = limiter.throttle()
-
- // Advance time to allow first throttled request
- await vi.advanceTimersByTimeAsync(1020)
- await promise1
-
- // Advance time to allow second throttled request
- await vi.advanceTimersByTimeAsync(1020)
- await promise2
-
- expect(true).toBe(true)
- })
-
- it('should reset the rate limiter state', async () => {
- const limiter = new RateLimiter(2, 1000)
-
- // Fill the limit
- await limiter.throttle()
- await limiter.throttle()
-
- // Reset
- limiter.reset()
-
- // Should be able to make requests immediately
- const startTime = Date.now()
- await limiter.throttle()
- await limiter.throttle()
- const endTime = Date.now()
-
- expect(endTime - startTime).toBeLessThan(50)
- })
-
- it('should handle concurrent requests correctly', async () => {
- const limiter = new RateLimiter(3, 1000)
-
- // Start 5 concurrent requests
- const promises = [
- limiter.throttle(),
- limiter.throttle(),
- limiter.throttle(),
- limiter.throttle(),
- limiter.throttle(),
- ]
-
- // First 3 should complete immediately
- await vi.advanceTimersByTimeAsync(10)
-
- // Advance time to allow remaining requests
- await vi.advanceTimersByTimeAsync(1020)
-
- // All promises should resolve
- await Promise.all(promises)
- expect(true).toBe(true)
- })
-
- it('should maintain sliding window correctly', async () => {
- const limiter = new RateLimiter(3, 1000)
-
- // Request at t=0
- await limiter.throttle()
-
- // Advance 400ms, make 2 more requests (t=400)
- await vi.advanceTimersByTimeAsync(400)
- await limiter.throttle()
- await limiter.throttle()
-
- // Advance 700ms (t=1100, first request expired)
- await vi.advanceTimersByTimeAsync(700)
-
- // Should be able to make another request immediately
- const startTime = Date.now()
- await limiter.throttle()
- const endTime = Date.now()
-
- expect(endTime - startTime).toBeLessThan(50)
- })
-
- it('should add buffer time to prevent edge cases', async () => {
- const limiter = new RateLimiter(1, 1000)
-
- await limiter.throttle()
-
- const promise = limiter.throttle()
-
- // Advance exactly 1000ms - should still be waiting due to 10ms buffer
- await vi.advanceTimersByTimeAsync(1000)
-
- // Advance the buffer time
- await vi.advanceTimersByTimeAsync(20)
- await promise
-
- expect(true).toBe(true)
- })
-
- it('should handle zero wait time gracefully', async () => {
- const limiter = new RateLimiter(5, 1000)
-
- // Make requests that don't exceed limit
- await limiter.throttle()
-
- // Advance time past window
- await vi.advanceTimersByTimeAsync(1100)
-
- // Should handle the case where waitTime would be negative
- await limiter.throttle()
- expect(true).toBe(true)
- })
-
- it('should work with very short time windows', async () => {
- const limiter = new RateLimiter(2, 100)
-
- await limiter.throttle()
- await limiter.throttle()
-
- const promise = limiter.throttle()
-
- // Advance past the short window
- await vi.advanceTimersByTimeAsync(120)
- await promise
-
- expect(true).toBe(true)
- })
-
- it('should work with very high request limits', async () => {
- const limiter = new RateLimiter(100, 1000)
-
- // Make many requests
- const promises = Array.from({ length: 50 }, () => limiter.throttle())
-
- // All should complete quickly since we're under the limit
- await Promise.all(promises)
- expect(true).toBe(true)
- })
-})
diff --git a/services/mcp/tests/unit/requestSSE.test.ts b/services/mcp/tests/unit/requestSSE.test.ts
index 1d588d84b063..ae0e43e52d36 100644
--- a/services/mcp/tests/unit/requestSSE.test.ts
+++ b/services/mcp/tests/unit/requestSSE.test.ts
@@ -2,12 +2,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ApiClient } from '@/api/client'
-vi.mock('@/api/rate-limiter', () => ({
- globalRateLimiter: {
- throttle: vi.fn().mockResolvedValue(undefined),
- },
-}))
-
function createMockStream(chunks: string[]): ReadableStream<Uint8Array> {
const encoder = new TextEncoder()
let index = 0