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): expire cached personal API key scopes after 2 minutes (#105927)

posthog[bot]197c9ca460a4
diff --git a/services/mcp/src/lib/StateManager.ts b/services/mcp/src/lib/StateManager.ts
index ced7c85e4e36..157fa264e756 100644
--- a/services/mcp/src/lib/StateManager.ts
+++ b/services/mcp/src/lib/StateManager.ts
@@ -1,6 +1,7 @@
import type { ApiClient, GroupType } from '@/api/client'
import type { Schemas } from '@/api/generated'
import { hasScope } from '@/lib/api'
+import { classifyAuthMethod } from '@/lib/auth-method'
import type { ScopedCache } from '@/lib/cache/ScopedCache'
import {
ErrorCode,
@@ -15,6 +16,9 @@ import type { ApiUser } from '@/schema/api'
import type { CachedOrg, CachedProject, CachedUser, State } from '@/tools/types'
const CACHE_TTL_MS = 10 * 60 * 1000 // 10 minutes
+// A personal API key keeps its value when its scopes change, and the cache is keyed by token, so
+// its scopes are read again after this delay. Reconnecting the client does not help: same token.
+export const API_KEY_CACHE_TTL_MS = 2 * 60 * 1000 // 2 minutes
const GATEWAY_TOOLS_CACHE_TTL_MS = 2 * 60 * 1000 // 2 minutes
// Entitlement-related fields shared by both org shapes we read from — the
@@ -100,14 +104,34 @@ export class StateManager {
}
async getApiKey(): Promise<NonNullable<State['apiKey']>> {
- let _apiKey = await this._cache.get('apiKey')
+ // An OAuth token gets a new value, and so a new cache entry, whenever its scopes change.
+ const refreshable = classifyAuthMethod(this._api.config.apiToken) !== 'oauth'
+ const [cached, fetchedAt] = await Promise.all([
+ this._cache.get('apiKey'),
+ refreshable ? this._cache.get('apiKeyFetchedAt') : undefined,
+ ])
- if (!_apiKey) {
- _apiKey = await this._fetchApiKey()
- await this._cache.set('apiKey', _apiKey)
+ if (cached && (!refreshable || !this.isCacheStale(fetchedAt, API_KEY_CACHE_TTL_MS))) {
+ return cached
}
- return _apiKey
+ try {
+ const apiKey = await this._fetchApiKey()
+ await Promise.all([
+ this._cache.set('apiKey', apiKey),
+ refreshable ? this._cache.set('apiKeyFetchedAt', Date.now()) : undefined,
+ ])
+ return apiKey
+ } catch (error) {
+ if (!cached) {
+ throw error
+ }
+ // A failed refresh must not end a live session. Every API call is authorized again
+ // server-side, so the last known scopes cannot grant access the key does not hold.
+ this._reportException(error, 'api_key_refresh_failed')
+ await this._cache.set('apiKeyFetchedAt', Date.now()).catch(() => {})
+ return cached
+ }
}
async getDistinctId(): Promise<NonNullable<State['distinctId']>> {
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index 9f41dabeff99..5895d2a63145 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -1,6 +1,7 @@
import { stringify as stringifyYaml } from 'yaml'
import { z } from 'zod'
+import { classifyAuthMethod } from '@/lib/auth-method'
import { markExecPayload, buildToolResultPayload, estimateResponseTokens } from '@/lib/build-tool-result'
import { isPostHogCodeConsumer } from '@/lib/client-detection'
import { isEmptyToolResult } from '@/lib/discovery-hints'
@@ -14,6 +15,7 @@ import {
import { estimateTokens } from '@/lib/estimate-tokens'
import { GATEWAY_TOOL_SEPARATOR, isGatewayToolName } from '@/lib/gateway-tools'
import { formatResponse } from '@/lib/response'
+import { API_KEY_CACHE_TTL_MS } from '@/lib/StateManager'
import { APP_DATA_META_KEY } from '@/ui-apps/types'
import { type ExecLearnCatalog, QUALIFIED_IDENTIFIER, tokenizeLearnInput } from './exec-learn'
@@ -1578,11 +1580,23 @@ function flagGatedToolMessage(gated: FlagGatedTool, tools: Tool<ZodObjectAny>[])
return `Tool "${gated.name}" is retired on this PostHog connection. Use ${successors} instead.${hint}`
}
+function missingScopeRecovery(context: Context | undefined): string {
+ switch (classifyAuthMethod(context?.api.config.apiToken)) {
+ case 'oauth':
+ return 'Reauthorize the PostHog MCP connection and approve these scopes.'
+ case 'personal_api_key':
+ return `Add these scopes to the personal API key. The change reaches this connection within ${API_KEY_CACHE_TTL_MS / 60_000} minutes, and reconnecting the client does not make it faster.`
+ default:
+ return 'Reauthorize the PostHog MCP connection, or add these scopes to the personal API key.'
+ }
+}
+
function findTool(
tools: Tool<ZodObjectAny>[],
scopeGatedTools: ScopeGatedTool[],
flagGatedTools: FlagGatedTool[],
- name: string
+ name: string,
+ context: Context | undefined
): Tool<ZodObjectAny> {
const tool = tools.find((t) => t.name === name)
if (!tool) {
@@ -1597,7 +1611,7 @@ function findTool(
const scopeGatedTool = scopeGatedTools.find((candidate) => candidate.name === name)
if (scopeGatedTool) {
throw new ExecCommandError(
- `Tool "${name}" exists, but this MCP connection is missing the required scope(s): ${scopeGatedTool.missingScopes.join(', ')}. Reconnect or reauthorize the PostHog MCP connection and approve these scopes. Logging in to PostHog in a browser does not update MCP permissions.`,
+ `Tool "${name}" exists, but this MCP connection is missing the required scope(s): ${scopeGatedTool.missingScopes.join(', ')}. ${missingScopeRecovery(context)} Logging in to PostHog in a browser does not update MCP permissions.`,
'missing_scope'
)
}
@@ -1756,7 +1770,7 @@ export function createExecTool(
})),
hint:
`These tools also match but are hidden because the API key is missing the ` +
- `required scope(s): ${requiredScopes.join(', ')}. The user needs to re-authenticate the MCP or connector, if the harness supports OAuth, or add the scopes to the personal API key to use these tools.`,
+ `required scope(s): ${requiredScopes.join(', ')}. ${missingScopeRecovery(context)}`,
})
}
if (matches.length === 0) {
@@ -1794,7 +1808,7 @@ export function createExecTool(
if (!infoArgs) {
throw new ExecCommandError('Usage: info [--json] <tool_name>', 'usage')
}
- const tool = findTool(await resolveTools(), scopeGatedTools, flagGatedTools, infoArgs)
+ const tool = findTool(await resolveTools(), scopeGatedTools, flagGatedTools, infoArgs, context)
// `io: 'input'` mirrors the advertised `tools/list` schema and the executor's
// validation: fields with a Zod `.default()` (e.g. a query `kind` discriminator)
// are optional and auto-filled. The default `io: 'output'` would list them as
@@ -1839,7 +1853,13 @@ export function createExecTool(
throw new ExecCommandError('Usage: schema <tool_name> [field_path]', 'usage')
}
const { verb: schemaToolName, rest: fieldPath } = parseCommand(rest)
- const schemaTool = findTool(await resolveTools(), scopeGatedTools, flagGatedTools, schemaToolName)
+ const schemaTool = findTool(
+ await resolveTools(),
+ scopeGatedTools,
+ flagGatedTools,
+ schemaToolName,
+ context
+ )
// See the `info` command: `io: 'input'` keeps this in sync with the advertised
// schema and validation, so `.default()` fields aren't shown as required.
const fullJsonSchema =
@@ -1896,7 +1916,7 @@ export function createExecTool(
throw new ExecCommandError(CALL_USAGE, 'usage')
}
const { verb: toolName, rest: jsonBody } = parseCommand(callArgs)
- const tool = findTool(await resolveTools(), scopeGatedTools, flagGatedTools, toolName)
+ const tool = findTool(await resolveTools(), scopeGatedTools, flagGatedTools, toolName, context)
if (options.requireDestructiveConfirmation && tool.annotations.destructiveHint && !confirmed) {
throw new ExecCommandError(
`Tool "${tool.name}" is destructive. Re-run with "call --confirm ${tool.name} ..." after verifying the target IDs. Use "info ${tool.name}" to inspect the tool first.`,
diff --git a/services/mcp/src/tools/types.ts b/services/mcp/src/tools/types.ts
index 0edfe15fa340..c76e0660368f 100644
--- a/services/mcp/src/tools/types.ts
+++ b/services/mcp/src/tools/types.ts
@@ -37,6 +37,7 @@ export type State = {
distinctId: string | undefined
region: CloudRegion | undefined
apiKey: ApiRedactedPersonalApiKey | undefined
+ apiKeyFetchedAt: number | undefined
clientName: string | undefined
oauthClientId: string | undefined
mcpClientName: string | undefined
diff --git a/services/mcp/tests/unit/StateManager.test.ts b/services/mcp/tests/unit/StateManager.test.ts
index 85121bc9129c..251d2a8cb908 100644
--- a/services/mcp/tests/unit/StateManager.test.ts
+++ b/services/mcp/tests/unit/StateManager.test.ts
@@ -82,9 +82,11 @@ describe('StateManager', () => {
})
describe('getApiKey', () => {
+ const cacheOnlyApi = { config: { apiToken: 'phx_test' } } as unknown as ApiClient
+
function oauthApi(clientName: string | null, impersonated?: boolean): ApiClient {
return {
- config: { apiToken: 'phx_test' },
+ config: { apiToken: 'pha_test' },
apiKeys: () => ({
current: async () => ({ success: false, error: { message: 'not a personal key' } }),
}),
@@ -110,7 +112,7 @@ describe('StateManager', () => {
const result = await stateManager.getApiKey()
expect(result.is_impersonated).toBe(impersonated === true)
- expect(await new StateManager(cache, {} as ApiClient).getApiKey()).toEqual(result)
+ expect(await new StateManager(cache, cacheOnlyApi).getApiKey()).toEqual(result)
const otherTokenCache = new MemoryCache<State>('other-token')
await otherTokenCache.clear()
@@ -122,13 +124,63 @@ describe('StateManager', () => {
it('caches personal API keys as not impersonated', async () => {
const api = {
+ config: { apiToken: 'phx_test' },
apiKeys: () => ({ current: async () => ({ success: true, data: mockApiKey }) }),
} as unknown as ApiClient
const result = await new StateManager(cache, api).getApiKey()
expect(result).toEqual({ ...mockApiKey, is_impersonated: false })
- expect(await new StateManager(cache, {} as ApiClient).getApiKey()).toEqual(result)
+ expect(await new StateManager(cache, cacheOnlyApi).getApiKey()).toEqual(result)
+ })
+
+ it.each([
+ { apiToken: 'phx_test', expectedScopes: ['user:read', 'cdp:read'] },
+ { apiToken: 'unrecognized-token', expectedScopes: ['user:read', 'cdp:read'] },
+ { apiToken: 'pha_test', expectedScopes: mockApiKey.scopes },
+ ])(
+ 're-reads expired scopes only for a token that keeps its value ($apiToken)',
+ async ({ apiToken, expectedScopes }) => {
+ vi.useFakeTimers()
+ try {
+ const current = vi
+ .fn()
+ .mockResolvedValueOnce({ success: true, data: mockApiKey })
+ .mockResolvedValue({
+ success: true,
+ data: { ...mockApiKey, scopes: ['user:read', 'cdp:read'] },
+ })
+ const api = { config: { apiToken }, apiKeys: () => ({ current }) } as unknown as ApiClient
+
+ expect((await new StateManager(cache, api).getApiKey()).scopes).toEqual(mockApiKey.scopes)
+
+ vi.advanceTimersByTime(60 * 1000)
+ expect((await new StateManager(cache, api).getApiKey()).scopes).toEqual(mockApiKey.scopes)
+
+ vi.advanceTimersByTime(2 * 60 * 1000)
+ expect((await new StateManager(cache, api).getApiKey()).scopes).toEqual(expectedScopes)
+ } finally {
+ vi.useRealTimers()
+ }
+ }
+ )
+
+ it('keeps the cached scopes when a refresh fails', async () => {
+ vi.useFakeTimers()
+ try {
+ const current = vi
+ .fn()
+ .mockResolvedValueOnce({ success: true, data: mockApiKey })
+ .mockRejectedValue(new Error('API unreachable'))
+ const api = { config: { apiToken: 'phx_test' }, apiKeys: () => ({ current }) } as unknown as ApiClient
+
+ await new StateManager(cache, api).getApiKey()
+ vi.advanceTimersByTime(3 * 60 * 1000)
+
+ expect((await new StateManager(cache, api).getApiKey()).scopes).toEqual(mockApiKey.scopes)
+ } finally {
+ vi.useRealTimers()
+ }
})
it.each([
@@ -907,7 +959,7 @@ describe('StateManager', () => {
it('returns undefined without calling the API when the key lacks integration:read', async () => {
await cache.set('apiKey', { scopes: ['project:read'], scoped_organizations: [], scoped_teams: [] })
const request = vi.fn()
- ;(stateManager as any)._api = { request }
+ ;(stateManager as any)._api = { config: { apiToken: 'phx_test' }, request }
const result = await stateManager.getOrFetchIntegrationKinds(projectId)
@@ -920,7 +972,7 @@ describe('StateManager', () => {
const request = vi.fn().mockResolvedValue({
results: [{ kind: 'slack' }, { kind: 'github' }, { kind: 'github' }],
})
- ;(stateManager as any)._api = { request }
+ ;(stateManager as any)._api = { config: { apiToken: 'phx_test' }, request }
const result = await stateManager.getOrFetchIntegrationKinds(projectId)
diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.ts
index cfc3d03e88c0..a7f1460739a8 100644
--- a/services/mcp/tests/unit/exec.test.ts
+++ b/services/mcp/tests/unit/exec.test.ts
@@ -56,6 +56,7 @@ function makeMockTool(overrides: Partial<Tool<ZodObjectAny>> = {}): Tool<ZodObje
const mockContext = {
getDistinctId: async () => 'test-distinct-id',
+ api: { config: { apiToken: 'phx_test' } },
} as unknown as Context
function createExec(
@@ -1824,11 +1825,44 @@ describe('exec tool', () => {
])
await expect(exec.handler(mockContext, { command })).rejects.toThrow(
- /exists[\s\S]*endpoint:write[\s\S]*reauthorize[\s\S]*browser does not update MCP permissions/i
+ /exists[\s\S]*endpoint:write[\s\S]*browser does not update MCP permissions/i
)
}
)
+ it.each([
+ { apiToken: 'pha_test', recovery: 'Reauthorize the PostHog MCP connection and approve these scopes.' },
+ {
+ apiToken: 'phx_test',
+ recovery:
+ 'Add these scopes to the personal API key. The change reaches this connection within 2 minutes, and reconnecting the client does not make it faster.',
+ },
+ {
+ apiToken: 'unrecognized-token',
+ recovery: 'Reauthorize the PostHog MCP connection, or add these scopes to the personal API key.',
+ },
+ ])(
+ 'gives the scope recovery step for the connection credential ($apiToken)',
+ async ({ apiToken, recovery }) => {
+ const context = { ...mockContext, api: { config: { apiToken } } } as unknown as Context
+ const scopeGated = [
+ {
+ name: 'endpoint-create',
+ title: 'Create endpoint',
+ description: 'Create a new endpoint',
+ missingScopes: ['endpoint:write'],
+ },
+ ]
+ const exec = createExecTool([makeMockTool()], context, 'desc', 'cmd', undefined, undefined, scopeGated)
+
+ await expect(exec.handler(context, { command: 'call endpoint-create {}' })).rejects.toThrow(recovery)
+ const search = JSON.parse(
+ (await exec.handler(context, { command: 'search endpoint-create' })) as string
+ )
+ expect(search.hint).toContain(recovery)
+ }
+ )
+
it('directs unknown tool names back to catalog search', async () => {
const exec = createExec()