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.

feat(mcp): rate limiting (#59774)

Joshua Snyder8431b3e52189
diff --git a/services/mcp/src/hono/cache/RedisCache.ts b/services/mcp/src/hono/cache/RedisCache.ts
index 964e4b6da318..c5daa299c78c 100644
--- a/services/mcp/src/hono/cache/RedisCache.ts
+++ b/services/mcp/src/hono/cache/RedisCache.ts
@@ -8,6 +8,9 @@ export interface RedisLike {
del(...keys: string[]): Promise<number>
unlink?(...keys: string[]): Promise<number>
scan(cursor: string | number, ...args: (string | number)[]): Promise<[cursor: string, keys: string[]]>
+ incr(key: string): Promise<number>
+ expire(key: string, seconds: number): Promise<number>
+ ttl(key: string): Promise<number>
}
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 913b5f74f0df..9afd502ac968 100644
--- a/services/mcp/src/hono/metrics.ts
+++ b/services/mcp/src/hono/metrics.ts
@@ -69,6 +69,18 @@ export const authFailuresTotal = new Counter({
labelNames: ['reason'] as const,
})
+export const rateLimitChecksTotal = new Counter({
+ name: 'mcp_rate_limit_checks_total',
+ help: 'Rate limit checks on /mcp requests, by scope and outcome.',
+ labelNames: ['scope', 'result'] as const,
+})
+
+export const rateLimitErrorsTotal = new Counter({
+ name: 'mcp_rate_limit_errors_total',
+ help: 'Rate limit Redis op failures (request still served — fail-open).',
+ labelNames: ['scope'] as const,
+})
+
export function routeLabel(pathname: string): string {
if (pathname === '/mcp' || pathname.startsWith('/mcp/')) {
return '/mcp'
diff --git a/services/mcp/src/hono/rate-limiter.ts b/services/mcp/src/hono/rate-limiter.ts
new file mode 100644
index 000000000000..27e493b19a44
--- /dev/null
+++ b/services/mcp/src/hono/rate-limiter.ts
@@ -0,0 +1,125 @@
+import { rateLimitChecksTotal, rateLimitErrorsTotal } from './metrics'
+
+export interface RedisRateLimitOps {
+ incr(key: string): Promise<number>
+ expire(key: string, seconds: number): Promise<number>
+ ttl(key: string): Promise<number>
+}
+
+export interface RateLimitConfig {
+ scope: string
+ limit: number
+ windowSeconds: number
+}
+
+export interface RateLimitResult {
+ allowed: boolean
+ scope: string
+ limit: number
+ remaining: number
+ resetSeconds: number
+}
+
+// Match PostHog's default REST API throttle (BurstRateThrottle /
+// SustainedRateThrottle in posthog/rate_limit.py).
+export const DEFAULT_BURST_LIMIT: RateLimitConfig = {
+ scope: 'mcp_burst',
+ limit: 480,
+ windowSeconds: 60,
+}
+
+export const DEFAULT_SUSTAINED_LIMIT: RateLimitConfig = {
+ scope: 'mcp_sustained',
+ limit: 4800,
+ windowSeconds: 3600,
+}
+
+export class RateLimiter {
+ constructor(
+ private readonly redis: RedisRateLimitOps,
+ private readonly limits: RateLimitConfig[]
+ ) {}
+
+ // Fails open on per-limit Redis errors — serving traffic beats taking MCP
+ // down when Redis hiccups.
+ async check(identifier: string): Promise<RateLimitResult | null> {
+ const results = await Promise.all(
+ this.limits.map((limit) =>
+ this.checkOne(identifier, limit).catch((err) => {
+ rateLimitErrorsTotal.inc({ scope: limit.scope })
+ console.error(`[RateLimiter] check failed for ${limit.scope}:`, err)
+ return null
+ })
+ )
+ )
+
+ let blocked: RateLimitResult | null = null
+ let tightest: RateLimitResult | null = null
+ for (const r of results) {
+ if (!r) {
+ continue
+ }
+ if (!r.allowed && !blocked) {
+ blocked = r
+ }
+ if (!tightest || r.remaining < tightest.remaining) {
+ tightest = r
+ }
+ }
+ return blocked ?? tightest
+ }
+
+ private async checkOne(identifier: string, limit: RateLimitConfig): Promise<RateLimitResult> {
+ const key = `mcp:rl:${limit.scope}:${identifier}`
+ const count = await this.redis.incr(key)
+
+ // First request in window has no TTL — set it. Subsequent INCRs leave
+ // it alone so the window stays fixed rather than sliding.
+ if (count === 1) {
+ await this.redis.expire(key, limit.windowSeconds)
+ }
+
+ if (count <= limit.limit) {
+ rateLimitChecksTotal.inc({ scope: limit.scope, result: 'allowed' })
+ return {
+ allowed: true,
+ scope: limit.scope,
+ limit: limit.limit,
+ remaining: limit.limit - count,
+ resetSeconds: limit.windowSeconds,
+ }
+ }
+
+ // If EXPIRE was lost on the first request, re-set TTL so a stuck key
+ // can't lock the user out forever.
+ let ttl = await this.redis.ttl(key)
+ if (ttl < 0) {
+ await this.redis.expire(key, limit.windowSeconds)
+ ttl = limit.windowSeconds
+ }
+ rateLimitChecksTotal.inc({ scope: limit.scope, result: 'blocked' })
+ return {
+ allowed: false,
+ scope: limit.scope,
+ limit: limit.limit,
+ remaining: 0,
+ resetSeconds: Math.max(1, ttl),
+ }
+ }
+}
+
+// Plain-text body so MCP clients without JSON-RPC framing on non-2xx still
+// get a readable message.
+export function buildRateLimitResponse(result: RateLimitResult): Response {
+ return new Response(`Rate limit exceeded (${result.scope}). Retry after ${result.resetSeconds}s.`, {
+ status: 429,
+ headers: {
+ 'Content-Type': 'text/plain; charset=utf-8',
+ 'Retry-After': String(result.resetSeconds),
+ 'X-RateLimit-Limit': String(result.limit),
+ 'X-RateLimit-Remaining': String(result.remaining),
+ 'X-RateLimit-Reset': String(result.resetSeconds),
+ 'X-RateLimit-Scope': result.scope,
+ },
+ })
+}
diff --git a/services/mcp/src/hono/streamable-handler.ts b/services/mcp/src/hono/streamable-handler.ts
index 027ab584e624..ceba23b76b19 100644
--- a/services/mcp/src/hono/streamable-handler.ts
+++ b/services/mcp/src/hono/streamable-handler.ts
@@ -1,15 +1,21 @@
import type { Lifecycle } from './app'
import type { RedisLike } from './cache/RedisCache'
import { McpDispatcher } from './dispatcher'
+import { buildRateLimitResponse, DEFAULT_BURST_LIMIT, DEFAULT_SUSTAINED_LIMIT, RateLimiter } from './rate-limiter'
import { authenticateAndParse, handleCatchError } from './request-utils'
import { ToolCatalog } from './tool-catalog'
import type { HonoCtx } from './types'
export class StreamableMcpHandler {
private readonly dispatcher: McpDispatcher
+ private readonly rateLimiter: RateLimiter
- constructor(redis: RedisLike, private readonly lifecycle: Lifecycle) {
+ constructor(
+ redis: RedisLike,
+ private readonly lifecycle: Lifecycle
+ ) {
this.dispatcher = new McpDispatcher(new ToolCatalog(), redis)
+ this.rateLimiter = new RateLimiter(redis, [DEFAULT_BURST_LIMIT, DEFAULT_SUSTAINED_LIMIT])
}
async warmup(): Promise<void> {
@@ -29,6 +35,13 @@ export class StreamableMcpHandler {
return auth.error
}
+ // After auth so the bucket is keyed per token, not per IP — corporate
+ // NATs shouldn't share buckets across unrelated users.
+ const rateLimit = await this.rateLimiter.check(auth.props.userHash)
+ if (rateLimit && !rateLimit.allowed) {
+ return buildRateLimitResponse(rateLimit)
+ }
+
try {
return await this.dispatcher.handleRequest(c.req.raw, auth.props)
} catch (error) {
diff --git a/services/mcp/tests/hono/app-routes.test.ts b/services/mcp/tests/hono/app-routes.test.ts
index 40ba23f80202..767c80c1e723 100644
--- a/services/mcp/tests/hono/app-routes.test.ts
+++ b/services/mcp/tests/hono/app-routes.test.ts
@@ -4,6 +4,8 @@ import type { Mock } from 'vitest'
import { createApp } from '@/hono/app'
import type { RedisLike } from '@/hono/cache/RedisCache'
+import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'
+
interface MockRedis extends RedisLike {
ping: Mock<() => Promise<string>>
_store: Map<string, string>
@@ -19,6 +21,7 @@ function createMockRedis(): MockRedis {
}),
del: vi.fn(async (...keys: string[]) => keys.length),
scan: vi.fn(async () => ['0', []] as [string, string[]]),
+ ...makeRedisRateLimitStubs(),
ping: vi.fn(async () => 'PONG'),
_store: store,
}
diff --git a/services/mcp/tests/hono/helpers/redis-rate-limit-stubs.ts b/services/mcp/tests/hono/helpers/redis-rate-limit-stubs.ts
new file mode 100644
index 000000000000..6ff5f2fd9bae
--- /dev/null
+++ b/services/mcp/tests/hono/helpers/redis-rate-limit-stubs.ts
@@ -0,0 +1,21 @@
+export interface RedisRateLimitStubs {
+ incr: (key: string) => Promise<number>
+ expire: (key: string, seconds: number) => Promise<number>
+ ttl: (key: string) => Promise<number>
+}
+
+// Trivial in-memory stubs for the rate-limit ops on RedisLike. Test files that
+// only need to satisfy the interface (no rate-limit assertions of their own)
+// can spread the return value into their fake-redis builder.
+export function makeRedisRateLimitStubs(): RedisRateLimitStubs {
+ const counts = new Map<string, number>()
+ return {
+ incr: async (key) => {
+ const next = (counts.get(key) ?? 0) + 1
+ counts.set(key, next)
+ return next
+ },
+ expire: async () => 1,
+ ttl: async () => 60,
+ }
+}
diff --git a/services/mcp/tests/hono/mcp-protocol.test.ts b/services/mcp/tests/hono/mcp-protocol.test.ts
index 0a6800252e97..535fa23648ad 100644
--- a/services/mcp/tests/hono/mcp-protocol.test.ts
+++ b/services/mcp/tests/hono/mcp-protocol.test.ts
@@ -16,6 +16,7 @@ import {
type ProtocolTestHarness,
} from '../integration/mcp-protocol-suite'
import { handlers, contextMillHandler } from '../workers/fixtures/handlers'
+import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'
const mswServer = setupServer(...handlers, contextMillHandler)
@@ -40,6 +41,7 @@ function createInMemoryRedis(): RedisLike & { ping(): Promise<string> } {
const cur = String(cursor)
return [cur === '0' ? 'next' : '0', cur === '0' ? Array.from(store.keys()) : []] as [string, string[]]
},
+ ...makeRedisRateLimitStubs(),
ping: async () => 'PONG',
}
}
diff --git a/services/mcp/tests/hono/rate-limiter.test.ts b/services/mcp/tests/hono/rate-limiter.test.ts
new file mode 100644
index 000000000000..9d68cde917f1
--- /dev/null
+++ b/services/mcp/tests/hono/rate-limiter.test.ts
@@ -0,0 +1,160 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import {
+ buildRateLimitResponse,
+ DEFAULT_BURST_LIMIT,
+ DEFAULT_SUSTAINED_LIMIT,
+ RateLimiter,
+ type RedisRateLimitOps,
+} from '@/hono/rate-limiter'
+
+interface MockRedis extends RedisRateLimitOps {
+ _ttls: Map<string, number>
+}
+
+function createMockRedis(): MockRedis {
+ const counts = new Map<string, number>()
+ const ttls = new Map<string, number>()
+ return {
+ incr: vi.fn(async (key: string) => {
+ const next = (counts.get(key) ?? 0) + 1
+ counts.set(key, next)
+ return next
+ }),
+ expire: vi.fn(async (key: string, seconds: number) => {
+ ttls.set(key, seconds)
+ return 1
+ }),
+ ttl: vi.fn(async (key: string) => ttls.get(key) ?? -2),
+ _ttls: ttls,
+ }
+}
+
+describe('RateLimiter', () => {
+ let redis: MockRedis
+
+ beforeEach(() => {
+ redis = createMockRedis()
+ })
+
+ it('allows requests under the limit', async () => {
+ const limiter = new RateLimiter(redis, [{ scope: 'burst', limit: 3, windowSeconds: 60 }])
+ const r1 = await limiter.check('user-a')
+ const r2 = await limiter.check('user-a')
+ const r3 = await limiter.check('user-a')
+ expect(r1?.allowed).toBe(true)
+ expect(r2?.allowed).toBe(true)
+ expect(r3?.allowed).toBe(true)
+ expect(r3?.remaining).toBe(0)
+ })
+
+ it('sets EXPIRE on the first request of a window and not on subsequent', async () => {
+ const limiter = new RateLimiter(redis, [{ scope: 'burst', limit: 10, windowSeconds: 60 }])
+ await limiter.check('user-a')
+ await limiter.check('user-a')
+ await limiter.check('user-a')
+ expect(redis.expire).toHaveBeenCalledTimes(1)
+ expect(redis.expire).toHaveBeenCalledWith('mcp:rl:burst:user-a', 60)
+ })
+
+ it('blocks requests over the limit and returns Retry-After info', async () => {
+ const limiter = new RateLimiter(redis, [{ scope: 'burst', limit: 2, windowSeconds: 60 }])
+ await limiter.check('user-a')
+ await limiter.check('user-a')
+ const blocked = await limiter.check('user-a')
+ expect(blocked?.allowed).toBe(false)
+ expect(blocked?.scope).toBe('burst')
+ expect(blocked?.remaining).toBe(0)
+ expect(blocked?.resetSeconds).toBeGreaterThan(0)
+ })
+
+ it('keys buckets per identifier', async () => {
+ const limiter = new RateLimiter(redis, [{ scope: 'burst', limit: 1, windowSeconds: 60 }])
+ const a1 = await limiter.check('user-a')
+ const a2 = await limiter.check('user-a')
+ const b1 = await limiter.check('user-b')
+ expect(a1?.allowed).toBe(true)
+ expect(a2?.allowed).toBe(false)
+ expect(b1?.allowed).toBe(true)
+ })
+
+ it.each([
+ { burstLimit: 2, sustainedLimit: 100, expectedScope: 'burst' },
+ { burstLimit: 100, sustainedLimit: 2, expectedScope: 'sustained' },
+ ])(
+ 'blocks on whichever limit trips first (burst=$burstLimit, sustained=$sustainedLimit → $expectedScope)',
+ async ({ burstLimit, sustainedLimit, expectedScope }) => {
+ const limiter = new RateLimiter(redis, [
+ { scope: 'burst', limit: burstLimit, windowSeconds: 60 },
+ { scope: 'sustained', limit: sustainedLimit, windowSeconds: 3600 },
+ ])
+ await limiter.check('user-a')
+ await limiter.check('user-a')
+ const result = await limiter.check('user-a')
+ expect(result?.allowed).toBe(false)
+ expect(result?.scope).toBe(expectedScope)
+ }
+ )
+
+ it('reports the tightest remaining when all limits pass', async () => {
+ const limiter = new RateLimiter(redis, [
+ { scope: 'burst', limit: 10, windowSeconds: 60 },
+ { scope: 'sustained', limit: 5, windowSeconds: 3600 },
+ ])
+ const result = await limiter.check('user-a')
+ // burst remaining: 9, sustained remaining: 4 → sustained is tighter
+ expect(result?.allowed).toBe(true)
+ expect(result?.scope).toBe('sustained')
+ expect(result?.remaining).toBe(4)
+ })
+
+ it('fails open if Redis errors on incr', async () => {
+ const broken: RedisRateLimitOps = {
+ incr: vi.fn(async () => {
+ throw new Error('redis down')
+ }),
+ expire: vi.fn(async () => 1),
+ ttl: vi.fn(async () => -2),
+ }
+ const limiter = new RateLimiter(broken, [{ scope: 'burst', limit: 1, windowSeconds: 60 }])
+ const result = await limiter.check('user-a')
+ expect(result).toBeNull()
+ })
+
+ it('re-sets TTL if it got lost on a blocked request', async () => {
+ const limiter = new RateLimiter(redis, [{ scope: 'burst', limit: 1, windowSeconds: 60 }])
+ await limiter.check('user-a')
+ // Simulate the EXPIRE having failed: clear TTLs but keep the count.
+ redis._ttls.clear()
+ const blocked = await limiter.check('user-a')
+ expect(blocked?.allowed).toBe(false)
+ expect(blocked?.resetSeconds).toBe(60)
+ expect(redis.expire).toHaveBeenCalledWith('mcp:rl:burst:user-a', 60)
+ })
+
+ it('matches PostHog REST API default throttle (480/min, 4800/hour)', () => {
+ expect(DEFAULT_BURST_LIMIT).toEqual({ scope: 'mcp_burst', limit: 480, windowSeconds: 60 })
+ expect(DEFAULT_SUSTAINED_LIMIT).toEqual({ scope: 'mcp_sustained', limit: 4800, windowSeconds: 3600 })
+ })
+})
+
+describe('buildRateLimitResponse', () => {
+ it('returns 429 with rate-limit headers', async () => {
+ const response = buildRateLimitResponse({
+ allowed: false,
+ scope: 'burst',
+ limit: 1500,
+ remaining: 0,
+ resetSeconds: 42,
+ })
+ expect(response.status).toBe(429)
+ expect(response.headers.get('Retry-After')).toBe('42')
+ expect(response.headers.get('X-RateLimit-Limit')).toBe('1500')
+ expect(response.headers.get('X-RateLimit-Remaining')).toBe('0')
+ expect(response.headers.get('X-RateLimit-Reset')).toBe('42')
+ expect(response.headers.get('X-RateLimit-Scope')).toBe('burst')
+ const body = await response.text()
+ expect(body).toContain('burst')
+ expect(body).toContain('42s')
+ })
+})
diff --git a/services/mcp/tests/hono/redis-cache.test.ts b/services/mcp/tests/hono/redis-cache.test.ts
index c78bf9fee3c9..6d35a1298ef4 100644
--- a/services/mcp/tests/hono/redis-cache.test.ts
+++ b/services/mcp/tests/hono/redis-cache.test.ts
@@ -2,6 +2,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { RedisCache, type RedisLike } from '@/hono/cache/RedisCache'
+import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'
+
type TestState = {
region: string | undefined
projectId: string | undefined
@@ -40,6 +42,7 @@ function createMockRedis(): MockRedis {
})
return ['0', matching] as [string, string[]]
}),
+ ...makeRedisRateLimitStubs(),
_store: store,
}
}
diff --git a/services/mcp/tests/hono/request-context.test.ts b/services/mcp/tests/hono/request-context.test.ts
index 671b81e35ab2..ae06d54bf854 100644
--- a/services/mcp/tests/hono/request-context.test.ts
+++ b/services/mcp/tests/hono/request-context.test.ts
@@ -12,6 +12,8 @@ import type { RedisLike } from '@/hono/cache/RedisCache'
import { RequestContext } from '@/hono/request-context'
import type { RequestProperties } from '@/lib/request-properties'
+import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'
+
function fakeRedis(): RedisLike {
const store = new Map<string, string>()
return {
@@ -30,6 +32,7 @@ function fakeRedis(): RedisLike {
return n
},
scan: async () => ['0', [...store.keys()]],
+ ...makeRedisRateLimitStubs(),
}
}
@@ -55,11 +58,7 @@ describe('RequestContext', () => {
mockMe.mockResolvedValue({ success: true, data: { distinct_id: 'user-123' } })
const ctx = new RequestContext(fakeRedis(), env, makeProps())
- const [a, b, c] = await Promise.all([
- ctx.getDistinctId(),
- ctx.getDistinctId(),
- ctx.getDistinctId(),
- ])
+ const [a, b, c] = await Promise.all([ctx.getDistinctId(), ctx.getDistinctId(), ctx.getDistinctId()])
expect(a).toBe('user-123')
expect(b).toBe('user-123')
@@ -123,13 +122,17 @@ describe('RequestContext', () => {
describe('buildClientProperties', () => {
it('includes all request properties', () => {
- const ctx = new RequestContext(fakeRedis(), env, makeProps({
- mcpClientName: 'claude-code',
- mcpClientVersion: '2.0',
- mcpProtocolVersion: '2025-03-26',
- mcpConsumer: 'posthog-code',
- transport: 'streamable-http',
- }))
+ const ctx = new RequestContext(
+ fakeRedis(),
+ env,
+ makeProps({
+ mcpClientName: 'claude-code',
+ mcpClientVersion: '2.0',
+ mcpProtocolVersion: '2025-03-26',
+ mcpConsumer: 'posthog-code',
+ transport: 'streamable-http',
+ })
+ )
expect(ctx.buildClientProperties()).toEqual({
mcp_runtime: 'hono',
@@ -142,13 +145,17 @@ describe('RequestContext', () => {
})
it('omits undefined properties', () => {
- const ctx = new RequestContext(fakeRedis(), env, makeProps({
- mcpClientName: undefined,
- mcpClientVersion: undefined,
- mcpProtocolVersion: undefined,
- mcpConsumer: undefined,
- transport: undefined,
- }))
+ const ctx = new RequestContext(
+ fakeRedis(),
+ env,
+ makeProps({
+ mcpClientName: undefined,
+ mcpClientVersion: undefined,
+ mcpProtocolVersion: undefined,
+ mcpConsumer: undefined,
+ transport: undefined,
+ })
+ )
expect(ctx.buildClientProperties()).toEqual({ mcp_runtime: 'hono' })
})