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): ask clients to re-authorize when their token is rejected (#114753)

posthog[bot]7698002dc6e5
diff --git a/services/mcp/src/index.ts b/services/mcp/src/index.ts
index 373aa6014a77..7e34624f11f0 100644
--- a/services/mcp/src/index.ts
+++ b/services/mcp/src/index.ts
@@ -1,3 +1,4 @@
+import { isRejectedTokenChallenge, withResourceMetadata } from '@/lib/auth-errors'
import { resolveEffectiveClientName } from '@/lib/client-detection'
import { MCP_DOCS_URL, getAuthorizationServerUrl } from '@/lib/constants'
import { isIdJagAccessToken } from '@/lib/id-jag'
@@ -273,7 +274,12 @@ const handleRequest = async (
if (url.pathname.startsWith('/mcp')) {
const region = await resolveProxyRegion(token, ctx.props.userHash, env.MCP_KV)
log.extend({ proxy: 'hono', region })
- return proxyToHono(request, region)
+ const response = await proxyToHono(request, region)
+ if (isRejectedTokenChallenge(response)) {
+ log.extend({ authError: 'rejected_token' })
+ return withResourceMetadata(response, request, effectiveRegion)
+ }
+ return response
}
log.extend({ error: 'route_not_found' })
diff --git a/services/mcp/src/lib/StateManager.ts b/services/mcp/src/lib/StateManager.ts
index ecad4b0133aa..0828a0160b08 100644
--- a/services/mcp/src/lib/StateManager.ts
+++ b/services/mcp/src/lib/StateManager.ts
@@ -111,7 +111,12 @@ export class StateManager {
const introspectionResult = await this._api.oauth().introspect({ token: this._api.config.apiToken })
if (!introspectionResult.success) {
- throw new Error(ErrorCode.INVALID_API_KEY)
+ // Only a 401 rejects the token. Any other failure means the check did not run, and a
+ // rejection would make the client discard a token that is still valid.
+ if (introspectionResult.error.message.includes(ErrorCode.INVALID_API_KEY)) {
+ throw new Error(ErrorCode.INVALID_API_KEY)
+ }
+ throw wrapError('Failed to introspect OAuth token', introspectionResult.error)
}
if (!introspectionResult.data.active) {
diff --git a/services/mcp/src/lib/auth-errors.ts b/services/mcp/src/lib/auth-errors.ts
index cd806f22a39a..e8e3856d47e0 100644
--- a/services/mcp/src/lib/auth-errors.ts
+++ b/services/mcp/src/lib/auth-errors.ts
@@ -75,31 +75,72 @@ export function classifyAuthFailure(error: unknown): McpAuthFailure {
// marker in the body (e.g. SDK transport wrappers).
export function mapKnownErrorMessage(text: string): Response | null {
if (text.includes(ErrorCode.INACTIVE_OAUTH_TOKEN)) {
- return new Response('OAuth token is inactive', { status: 401 })
+ return buildRejectedTokenResponse('OAuth token is inactive')
}
if (text.includes(ErrorCode.INVALID_API_KEY)) {
- return new Response('Invalid API key', { status: 401 })
+ return buildRejectedTokenResponse('Invalid API key')
}
return null
}
-// Build the RFC 9728 `WWW-Authenticate` response for an unauthenticated request.
-// The `resource_metadata` URL points clients at the protected-resource metadata so
-// they can discover the authorization server.
-export function buildMissingTokenResponse(request: Request, effectiveRegion: CloudRegion | null): Response {
- const url = new URL(request.url)
+// RFC 6750 requires a `WWW-Authenticate` challenge on every 401. Without `error="invalid_token"`,
+// an OAuth client reads the 401 as a plain failure and keeps sending the rejected token.
+// The challenge has no `resource_metadata`, because the Hono runtime sits behind the worker proxy
+// and does not know the origin the client connected to. The worker adds it, and a client that
+// connects to Hono directly discovers the metadata from its own server URL.
+function buildRejectedTokenResponse(description: string): Response {
+ return new Response(description, {
+ status: 401,
+ headers: { 'WWW-Authenticate': `Bearer error="invalid_token", error_description="${description}"` },
+ })
+}
+
+export function isRejectedTokenChallenge(response: Response): boolean {
+ return response.status === 401 && (response.headers.get('WWW-Authenticate') ?? '').includes('error="invalid_token"')
+}
+
+// The worker answers the protected-resource metadata request, so the metadata URL must name the
+// origin the client connected to, not the regional Hono origin that the proxy rewrites it to.
+export function withResourceMetadata(
+ response: Response,
+ request: Request,
+ effectiveRegion: CloudRegion | null
+): Response {
+ const challenge = response.headers.get('WWW-Authenticate')
+ if (!challenge) {
+ return response
+ }
+ const rewritten = new Response(response.body, response)
+ rewritten.headers.set(
+ 'WWW-Authenticate',
+ `${challenge}, resource_metadata="${buildResourceMetadataUrl(request, effectiveRegion)}"`
+ )
+ return rewritten
+}
+
+// Per RFC 9728, the well-known path goes between the host and the resource path:
+// resource /mcp has its metadata at /.well-known/oauth-protected-resource/mcp.
+function buildResourceMetadataUrl(request: Request, effectiveRegion: CloudRegion | null): string {
const metadataUrl = getPublicUrl(request)
- metadataUrl.pathname = `/.well-known/oauth-protected-resource${url.pathname}`
+ metadataUrl.pathname = `/.well-known/oauth-protected-resource${new URL(request.url).pathname}`
metadataUrl.search = ''
if (effectiveRegion) {
metadataUrl.searchParams.set('region', effectiveRegion)
}
+ return metadataUrl.toString()
+}
+// Build the RFC 9728 `WWW-Authenticate` response for an unauthenticated request.
+// The `resource_metadata` URL points clients at the protected-resource metadata so
+// they can discover the authorization server.
+export function buildMissingTokenResponse(request: Request, effectiveRegion: CloudRegion | null): Response {
return new Response(
`No token provided, please provide a valid API token. View the documentation for more information: ${MCP_DOCS_URL}`,
{
status: 401,
- headers: { 'WWW-Authenticate': `Bearer resource_metadata="${metadataUrl.toString()}"` },
+ headers: {
+ 'WWW-Authenticate': `Bearer resource_metadata="${buildResourceMetadataUrl(request, effectiveRegion)}"`,
+ },
}
)
}
diff --git a/services/mcp/tests/hono/auth-instrumentation.test.ts b/services/mcp/tests/hono/auth-instrumentation.test.ts
index c968c652357d..8bb48e8abc87 100644
--- a/services/mcp/tests/hono/auth-instrumentation.test.ts
+++ b/services/mcp/tests/hono/auth-instrumentation.test.ts
@@ -83,6 +83,7 @@ describe('MCP auth instrumentation', () => {
const response = handleCatchError(new Error(`boom ${ErrorCode.INVALID_API_KEY}`), makeProps())
expect(response.status).toBe(401)
+ expect(response.headers.get('WWW-Authenticate')).toContain('error="invalid_token"')
expect(mockCapture).toHaveBeenCalledTimes(1)
const call = mockCapture.mock.calls[0]![0]
expect(call.event).toBe('$mcp_auth_failed')
diff --git a/services/mcp/tests/unit/StateManager.test.ts b/services/mcp/tests/unit/StateManager.test.ts
index 572a87f380c9..c0a11a229162 100644
--- a/services/mcp/tests/unit/StateManager.test.ts
+++ b/services/mcp/tests/unit/StateManager.test.ts
@@ -220,6 +220,27 @@ describe('StateManager', () => {
}
})
+ it.each([
+ { label: 'a 401', message: 'INVALID_API_KEY: token revoked', rejected: true },
+ { label: 'an outage', message: 'Network error: fetch failed', rejected: false },
+ ])(
+ 'reports an introspection failure from $label as a rejection only for a 401',
+ async ({ message, rejected }) => {
+ const api = {
+ config: { apiToken: 'pha_test' },
+ apiKeys: () => ({
+ current: async () => ({ success: false, error: { message: 'not a personal key' } }),
+ }),
+ oauth: () => ({ introspect: async () => ({ success: false, error: new Error(message) }) }),
+ } as unknown as ApiClient
+
+ const error = await new StateManager(cache, api).getApiKey().catch((e: Error) => e)
+
+ expect(error).toBeInstanceOf(Error)
+ expect((error as Error).message.includes('INVALID_API_KEY')).toBe(rejected)
+ }
+ )
+
it.each([
{ label: 'an OAuth app name', clientName: 'Claude', expected: 'Claude' },
{ label: 'no OAuth app name', clientName: null, expected: undefined },
diff --git a/services/mcp/tests/unit/auth-errors.test.ts b/services/mcp/tests/unit/auth-errors.test.ts
new file mode 100644
index 000000000000..bc937a623567
--- /dev/null
+++ b/services/mcp/tests/unit/auth-errors.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest'
+
+import { isRejectedTokenChallenge, mapKnownErrorMessage, withResourceMetadata } from '@/lib/auth-errors'
+import { ErrorCode } from '@/lib/errors'
+
+describe('rejected token challenge', () => {
+ it.each([ErrorCode.INVALID_API_KEY, ErrorCode.INACTIVE_OAUTH_TOKEN])(
+ 'points a %s rejection at the metadata of the origin the client connected to',
+ (code) => {
+ const honoResponse = mapKnownErrorMessage(code)!
+ expect(isRejectedTokenChallenge(honoResponse)).toBe(true)
+
+ const response = withResourceMetadata(
+ honoResponse,
+ new Request('https://mcp.posthog.com/mcp?region=eu&features=insights'),
+ 'eu'
+ )
+
+ expect(response.status).toBe(401)
+ expect(response.headers.get('WWW-Authenticate')).toMatch(
+ /^Bearer error="invalid_token", .*resource_metadata="https:\/\/mcp\.posthog\.com\/\.well-known\/oauth-protected-resource\/mcp\?region=eu"$/
+ )
+ }
+ )
+})