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.

chore(mcp): add per team rate limit metrics (#61690)

Joshua Snyder95cae5196ed0
diff --git a/services/mcp/src/hono/metrics.ts b/services/mcp/src/hono/metrics.ts
index 5893b068e457..06bd615043aa 100644
--- a/services/mcp/src/hono/metrics.ts
+++ b/services/mcp/src/hono/metrics.ts
@@ -81,6 +81,12 @@ export const rateLimitErrorsTotal = new Counter({
labelNames: ['scope'] as const,
})
+export const rateLimitBlockedByTeam = new Counter({
+ name: 'mcp_rate_limit_blocked_by_team_total',
+ help: 'Rate limit blocks on /mcp requests, by scope and team.',
+ labelNames: ['scope', 'team_id'] as const,
+})
+
export const contextMillRevalidationsTotal = new Counter({
name: 'mcp_context_mill_revalidations_total',
help: 'Context-mill resource revalidation attempts by caller and result.',
diff --git a/services/mcp/src/hono/rate-limit-telemetry.ts b/services/mcp/src/hono/rate-limit-telemetry.ts
new file mode 100644
index 000000000000..480d26344c17
--- /dev/null
+++ b/services/mcp/src/hono/rate-limit-telemetry.ts
@@ -0,0 +1,52 @@
+import type { RequestProperties } from '@/lib/request-properties'
+import type { State } from '@/tools/types'
+
+import { RedisCache, type RedisLike } from './cache/RedisCache'
+import { rateLimitBlockedByTeam } from './metrics'
+import type { RateLimitResult } from './rate-limiter'
+
+const UNRESOLVED_TEAM = 'unresolved'
+const OVERFLOW_TEAM = 'other'
+
+// team_id ultimately derives from the client-controlled x-posthog-project-id
+// header, and this runs on the blocked path — so an attacker past the limit
+// could otherwise mint an unbounded number of label series and exhaust the heap.
+// Only accept a plausible numeric project id, and hard-cap distinct values.
+const VALID_TEAM_ID = /^\d{1,19}$/
+const MAX_TRACKED_TEAMS = 1000
+const trackedTeamIds = new Set<string>()
+
+function normalizeTeamId(teamId: string | undefined): string {
+ if (!teamId || !VALID_TEAM_ID.test(teamId)) {
+ return UNRESOLVED_TEAM
+ }
+ if (trackedTeamIds.has(teamId)) {
+ return teamId
+ }
+ if (trackedTeamIds.size >= MAX_TRACKED_TEAMS) {
+ return OVERFLOW_TEAM
+ }
+ trackedTeamIds.add(teamId)
+ return teamId
+}
+
+export async function recordRateLimitBlock(
+ redis: RedisLike,
+ props: RequestProperties,
+ result: RateLimitResult
+): Promise<void> {
+ let teamId = props.projectId
+ if (!teamId) {
+ try {
+ teamId = (await new RedisCache<State>(props.userHash, redis, 'token').get('projectId')) ?? undefined
+ } catch {
+ // best-effort identity
+ }
+ }
+ rateLimitBlockedByTeam.inc({ scope: result.scope, team_id: normalizeTeamId(teamId) })
+}
+
+// test-only: reset the process-lifetime cardinality cap between cases
+export function __resetTrackedTeamIds(): void {
+ trackedTeamIds.clear()
+}
diff --git a/services/mcp/src/hono/streamable-handler.ts b/services/mcp/src/hono/streamable-handler.ts
index ceba23b76b19..cfbfed0ee5e7 100644
--- a/services/mcp/src/hono/streamable-handler.ts
+++ b/services/mcp/src/hono/streamable-handler.ts
@@ -1,6 +1,7 @@
import type { Lifecycle } from './app'
import type { RedisLike } from './cache/RedisCache'
import { McpDispatcher } from './dispatcher'
+import { recordRateLimitBlock } from './rate-limit-telemetry'
import { buildRateLimitResponse, DEFAULT_BURST_LIMIT, DEFAULT_SUSTAINED_LIMIT, RateLimiter } from './rate-limiter'
import { authenticateAndParse, handleCatchError } from './request-utils'
import { ToolCatalog } from './tool-catalog'
@@ -11,7 +12,7 @@ export class StreamableMcpHandler {
private readonly rateLimiter: RateLimiter
constructor(
- redis: RedisLike,
+ private readonly redis: RedisLike,
private readonly lifecycle: Lifecycle
) {
this.dispatcher = new McpDispatcher(new ToolCatalog(), redis)
@@ -39,6 +40,7 @@ export class StreamableMcpHandler {
// NATs shouldn't share buckets across unrelated users.
const rateLimit = await this.rateLimiter.check(auth.props.userHash)
if (rateLimit && !rateLimit.allowed) {
+ void recordRateLimitBlock(this.redis, auth.props, rateLimit).catch(() => {})
return buildRateLimitResponse(rateLimit)
}
diff --git a/services/mcp/tests/hono/rate-limit-telemetry.test.ts b/services/mcp/tests/hono/rate-limit-telemetry.test.ts
new file mode 100644
index 000000000000..93fc65996a78
--- /dev/null
+++ b/services/mcp/tests/hono/rate-limit-telemetry.test.ts
@@ -0,0 +1,78 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { rateLimitBlockedByTeam } from '@/hono/metrics'
+import { __resetTrackedTeamIds, recordRateLimitBlock } from '@/hono/rate-limit-telemetry'
+import type { RateLimitResult } from '@/hono/rate-limiter'
+import type { RequestProperties } from '@/lib/request-properties'
+
+function blocked(scope = 'mcp_sustained'): RateLimitResult {
+ return { allowed: false, scope, limit: 4800, remaining: 0, resetSeconds: 60 }
+}
+
+function makeProps(overrides: Partial<RequestProperties> = {}): RequestProperties {
+ return { apiToken: 'token', userHash: 'hash-a', ...overrides } as RequestProperties
+}
+
+async function teamValue(teamId: string, scope = 'mcp_sustained'): Promise<number> {
+ const data = await rateLimitBlockedByTeam.get()
+ const match = data.values.find((v) => v.labels.team_id === teamId && v.labels.scope === scope)
+ return match?.value ?? 0
+}
+
+describe('recordRateLimitBlock', () => {
+ beforeEach(() => {
+ rateLimitBlockedByTeam.reset()
+ __resetTrackedTeamIds()
+ })
+
+ async function totalSeries(): Promise<number> {
+ return (await rateLimitBlockedByTeam.get()).values.length
+ }
+
+ it('labels by the client-supplied project id without touching redis', async () => {
+ const get = vi.fn()
+ await recordRateLimitBlock({ get } as never, makeProps({ projectId: '123' }), blocked())
+ expect(await teamValue('123')).toBe(1)
+ expect(get).not.toHaveBeenCalled()
+ })
+
+ it('falls back to the cached team id when no header is present', async () => {
+ const get = vi.fn(async (key: string) => (key === 'mcp:token:hash-a:projectId' ? JSON.stringify('456') : null))
+ await recordRateLimitBlock({ get } as never, makeProps(), blocked())
+ expect(await teamValue('456')).toBe(1)
+ })
+
+ it('uses the unresolved bucket when the team is unknown', async () => {
+ const get = vi.fn(async () => null)
+ await recordRateLimitBlock({ get } as never, makeProps(), blocked())
+ expect(await teamValue('unresolved')).toBe(1)
+ })
+
+ it('never throws and still records when the cache read fails', async () => {
+ const get = vi.fn(async () => {
+ throw new Error('redis down')
+ })
+ await expect(recordRateLimitBlock({ get } as never, makeProps(), blocked())).resolves.toBeUndefined()
+ expect(await teamValue('unresolved')).toBe(1)
+ })
+
+ it.each([['not-a-number'], ['12345678901234567890'], ['1; DROP']])(
+ 'buckets a non-numeric or oversized project id %j as unresolved',
+ async (projectId) => {
+ const get = vi.fn()
+ await recordRateLimitBlock({ get } as never, makeProps({ projectId }), blocked())
+ expect(await teamValue('unresolved')).toBe(1)
+ expect(get).not.toHaveBeenCalled()
+ }
+ )
+
+ it('caps distinct team series and routes the overflow to other', async () => {
+ const get = vi.fn()
+ for (let i = 0; i < 1500; i += 1) {
+ await recordRateLimitBlock({ get } as never, makeProps({ projectId: String(i) }), blocked())
+ }
+ // 1000 real teams + the "other" overflow bucket = 1001 series, never 1500
+ expect(await totalSeries()).toBe(1001)
+ expect(await teamValue('other')).toBe(500)
+ })
+})