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): retry oauth token introspection after a dropped connection (#115155)

posthog[bot]d2cb8a118542
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index b9e0f7ea9758..7cad300b022f 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -612,8 +612,15 @@ export class ApiClient {
})
}
- private async fetchJson<T>(url: string, options?: RequestInit): Promise<Result<T>> {
+ /** Pass `idempotent` for a non-GET request that has no upstream effect, so
+ * a transport fault retries it like a safe method. */
+ private async fetchJson<T>(
+ url: string,
+ options?: RequestInit,
+ { idempotent = false }: { idempotent?: boolean } = {}
+ ): 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
@@ -627,7 +634,6 @@ export class ApiClient {
// short throws here, and that failure is transport, not a bad response.
bodyText = await response.text()
} catch (error) {
- const isSafeMethod = SAFE_HTTP_METHODS.has(method.toUpperCase())
const canRetry = !isAbortError(error) && isSafeMethod && transportRetries < TRANSPORT_MAX_RETRIES
if (!canRetry) {
console.error(`[API] Transport failure on ${method} ${url}: ${String(error)}`)
@@ -757,14 +763,19 @@ export class ApiClient {
oauth(): Endpoint {
return {
introspect: async ({ token }: { token: string }): Promise<Result<ApiOAuthIntrospection>> => {
- return this.fetchJson<ApiOAuthIntrospection>(`${this.baseUrl}/oauth/introspect`, {
- method: 'POST',
- body: JSON.stringify({ token }),
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${token}`,
+ // RFC 7662 introspection only reads the token state.
+ return this.fetchJson<ApiOAuthIntrospection>(
+ `${this.baseUrl}/oauth/introspect`,
+ {
+ method: 'POST',
+ body: JSON.stringify({ token }),
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${token}`,
+ },
},
- })
+ { idempotent: true }
+ )
},
}
}
diff --git a/services/mcp/tests/unit/api-client.test.ts b/services/mcp/tests/unit/api-client.test.ts
index 573daae72f88..ae7767035c4a 100644
--- a/services/mcp/tests/unit/api-client.test.ts
+++ b/services/mcp/tests/unit/api-client.test.ts
@@ -592,6 +592,20 @@ describe('ApiClient', () => {
expect(mockFetch).toHaveBeenCalledTimes(3)
})
+ it('retries a token introspection that fails to connect', async () => {
+ const mockFetch = stubFetch(
+ networkError(),
+ new Response(JSON.stringify({ active: true, scope: 'query:read' }), { status: 200 })
+ )
+ const client = new ApiClient({ apiToken: 'pha_test', baseUrl: 'https://us.posthog.com' })
+
+ const result = await settle(client.oauth().introspect({ token: 'pha_test' }))
+
+ expect(result).toEqual({ success: true, data: { active: true, scope: 'query:read' } })
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ expect(mockFetch.mock.calls[1]![1]).toMatchObject({ method: 'POST' })
+ })
+
it('does not repeat a write whose outcome is unknown', async () => {
const mockFetch = stubFetch()
const client = new ApiClient({ apiToken: 'phx_test', baseUrl: 'https://us.posthog.com' })