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): token param for local testing in claude (#62219)

Georgiy Tarasovd69f18add405
diff --git a/services/mcp/src/hono/request-utils.ts b/services/mcp/src/hono/request-utils.ts
index 9b7f3d2567aa..da86b5b694b1 100644
--- a/services/mcp/src/hono/request-utils.ts
+++ b/services/mcp/src/hono/request-utils.ts
@@ -9,7 +9,7 @@ import {
type Transport,
} from '@/lib/request-properties'
import { getRegionFromRequest } from '@/lib/routing'
-import { sanitizeHeaderValue } from '@/lib/utils'
+import { extractBearerToken, sanitizeHeaderValue } from '@/lib/utils'
import { authFailuresTotal } from './metrics'
import type { HonoCtx } from './types'
@@ -53,7 +53,7 @@ function parseClientInfo(bodyText: string): ClientInfo {
}
function authenticate(c: HonoCtx): Response | null {
- const token = c.req.header('Authorization')?.split(' ')[1]
+ const token = extractBearerToken(c.req.raw)
const error = validateBearerToken(token, c.req.raw, getRegionFromRequest(c.req.raw))
if (error) {
const reason = !token ? 'missing_token' : 'invalid_token'
diff --git a/services/mcp/src/index.ts b/services/mcp/src/index.ts
index e45d8f119fc7..ecc0fd5ce973 100644
--- a/services/mcp/src/index.ts
+++ b/services/mcp/src/index.ts
@@ -2,9 +2,9 @@ import { MCP_DOCS_URL, OAUTH_SCOPES_SUPPORTED, getAuthorizationServerUrl } from
import { isIdJagAccessToken } from '@/lib/id-jag'
import { RequestLogger, withLogging } from '@/lib/logging'
import { extractClientInfoFromBody } from '@/lib/mcp-client-info'
-import { buildRedirectUrl, matchAuthServerRedirect } from '@/lib/routing'
import { RequestProperties } from '@/lib/request-properties'
-import { hash, parseMcpMode, sanitizeHeaderValue } from '@/lib/utils'
+import { buildRedirectUrl, matchAuthServerRedirect } from '@/lib/routing'
+import { extractBearerToken, hash, parseMcpMode, sanitizeHeaderValue } from '@/lib/utils'
import type { CloudRegion } from '@/tools/types'
import { proxyToHono, resolveProxyRegion } from './proxy'
@@ -179,7 +179,7 @@ const handleRequest = async (
)
}
- const token = request.headers.get('Authorization')?.split(' ')[1]
+ const token = extractBearerToken(request)
const sessionId = url.searchParams.get('sessionId')
if (!token) {
diff --git a/services/mcp/src/lib/request-properties.ts b/services/mcp/src/lib/request-properties.ts
index cc105ba90f3a..3fdfbc282853 100644
--- a/services/mcp/src/lib/request-properties.ts
+++ b/services/mcp/src/lib/request-properties.ts
@@ -1,7 +1,7 @@
// Shared request-properties extraction. Both runtimes parse the same headers
// and query params into the same shape, so the logic lives here.
-import { hash, parseMcpMode, sanitizeHeaderValue, type McpMode } from './utils'
+import { extractBearerToken, hash, parseMcpMode, sanitizeHeaderValue, type McpMode } from './utils'
export type Transport = 'streamable-http' | 'sse'
@@ -55,7 +55,7 @@ export function parseRequestProperties(
const url = new URL(request.url)
const params = url.searchParams
- const token = request.headers.get('Authorization')?.split(' ')[1] ?? ''
+ const token = extractBearerToken(request) ?? ''
const readOnlyRaw = header(request, 'x-posthog-read-only') || params.get('readonly')
return {
diff --git a/services/mcp/src/lib/utils.ts b/services/mcp/src/lib/utils.ts
index 2c13d92191a3..8151aa56fdb0 100644
--- a/services/mcp/src/lib/utils.ts
+++ b/services/mcp/src/lib/utils.ts
@@ -1,5 +1,7 @@
import crypto from 'node:crypto'
+import { env } from '@/lib/env'
+
export function hash(data: string): string {
// Use PBKDF2 with sufficient computational effort for security
// 100,000 iterations provides good security while maintaining reasonable performance
@@ -7,6 +9,23 @@ export function hash(data: string): string {
return crypto.pbkdf2Sync(data, salt, 100000, 32, 'sha256').toString('hex')
}
+// Extract the API token from a request. Prefers the `Authorization: Bearer
+// <token>` header. In dev/test only, falls back to a `?token=` query param for
+// clients that can only customize the URL, not request headers (e.g. MCP UI
+// apps in an iframe). The fallback uses a positive allowlist so it fails closed
+// when NODE_ENV is unset (e.g. on Cloudflare Workers) — keeping tokens out of
+// URLs (logs, referrers, history) in production.
+export function extractBearerToken(request: Request): string | undefined {
+ const headerToken = request.headers.get('Authorization')?.split(' ')[1]
+ if (headerToken) {
+ return headerToken
+ }
+ if (env.NODE_ENV === 'development' || env.NODE_ENV === 'test') {
+ return new URL(request.url).searchParams.get('token') || undefined
+ }
+ return undefined
+}
+
// Redact an API token for logs: keep only the last 4 chars, mask the rest.
// Tokens of 4 chars or fewer (or empty) are fully masked so nothing useful leaks.
export function redactToken(token: string): string {
diff --git a/services/mcp/tests/unit/utils.test.ts b/services/mcp/tests/unit/utils.test.ts
index a01da1017d0a..466822628563 100644
--- a/services/mcp/tests/unit/utils.test.ts
+++ b/services/mcp/tests/unit/utils.test.ts
@@ -1,9 +1,14 @@
-import { describe, expect, it } from 'vitest'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { formatPrompt, redactToken, sanitizeHeaderValue } from '@/lib/utils'
+import { env } from '@/lib/env'
+import { extractBearerToken, formatPrompt, redactToken, sanitizeHeaderValue } from '@/lib/utils'
import { omitResponseFields, pickResponseFields, withPostHogUrl } from '@/tools/tool-utils'
import type { Context } from '@/tools/types'
+// Mock the env proxy that the production code reads through, rather than poking
+// process.env — so the test exercises the same abstraction as extractBearerToken.
+vi.mock('@/lib/env', () => ({ env: { NODE_ENV: undefined as string | undefined } }))
+
describe('utils', () => {
describe('redactToken', () => {
it('keeps only the last 4 chars and masks the rest', () => {
@@ -20,6 +25,53 @@ describe('utils', () => {
})
})
+ describe('extractBearerToken', () => {
+ beforeEach(() => {
+ env.NODE_ENV = 'development'
+ })
+
+ const req = (opts: { header?: string; url?: string }): Request =>
+ new Request(opts.url ?? 'https://mcp.posthog.com/', {
+ headers: opts.header ? { Authorization: opts.header } : {},
+ })
+
+ it('prefers the Authorization bearer header', () => {
+ expect(extractBearerToken(req({ header: 'Bearer phx_header', url: 'https://x/?token=phx_query' }))).toBe(
+ 'phx_header'
+ )
+ })
+
+ it('falls back to the ?token query param in development', () => {
+ expect(extractBearerToken(req({ url: 'https://x/?token=phx_query' }))).toBe('phx_query')
+ })
+
+ it('falls back to the ?token query param in test', () => {
+ env.NODE_ENV = 'test'
+ expect(extractBearerToken(req({ url: 'https://x/?token=phx_query' }))).toBe('phx_query')
+ })
+
+ it('ignores the ?token query param in production', () => {
+ env.NODE_ENV = 'production'
+ expect(extractBearerToken(req({ url: 'https://x/?token=phx_query' }))).toBeUndefined()
+ })
+
+ // Fail closed: an unset NODE_ENV (e.g. no Cloudflare Workers binding) must
+ // not enable the query-param path.
+ it('ignores the ?token query param when NODE_ENV is unset', () => {
+ env.NODE_ENV = undefined
+ expect(extractBearerToken(req({ url: 'https://x/?token=phx_query' }))).toBeUndefined()
+ })
+
+ it('still reads the header in production', () => {
+ env.NODE_ENV = 'production'
+ expect(extractBearerToken(req({ header: 'Bearer phx_header' }))).toBe('phx_header')
+ })
+
+ it('returns undefined when no token is present', () => {
+ expect(extractBearerToken(req({}))).toBeUndefined()
+ })
+ })
+
describe('formatPrompt', () => {
it('substitutes placeholders with values', () => {
expect(formatPrompt('Hello {name}, welcome to {place}', { name: 'world', place: 'earth' })).toBe(