: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp): attribute and CLI-mode Anthropic clients that omit the vendor header (#65812)
Georgiy Tarasovfa11f6a62300
diff --git a/services/mcp/src/index.ts b/services/mcp/src/index.tsindex fe92211c2536..3b92565beb2d 100644--- a/services/mcp/src/index.ts+++ b/services/mcp/src/index.ts@@ -1,3 +1,4 @@+import { resolveEffectiveClientName } from '@/lib/client-detection'import { MCP_DOCS_URL, getAuthorizationServerUrl } from '@/lib/constants'import { isIdJagAccessToken } from '@/lib/id-jag'import { RequestLogger, withLogging } from '@/lib/logging'@@ -269,7 +270,7 @@ const handleRequest = async (projectId,clientUserAgent,mcpConsumer,- mcpClientName: clientInfo.clientName,+ mcpClientName: resolveEffectiveClientName(clientInfo.clientName, mcpVendorClient),mcpClientVersion: clientInfo.clientVersion,mcpProtocolVersion: clientInfo.protocolVersion,mcpVendorClient,diff --git a/services/mcp/src/lib/client-detection.ts b/services/mcp/src/lib/client-detection.tsindex c7b467b5df08..aee212ffa748 100644--- a/services/mcp/src/lib/client-detection.ts+++ b/services/mcp/src/lib/client-detection.ts@@ -91,7 +91,42 @@ export const CODING_AGENT_CLIENT_NAME_FRAGMENTS = [// Every Anthropic product runs in CLI (single-exec) mode. Matched as normalized// substrings, so vendor-prefixed shapes like `Anthropic/ClaudeAI` resolve to// `claudeai`.-export const ANTHROPIC_CLIENT_NAME_FRAGMENTS = ['claudecode', 'claudeai', 'cowork'] as const+export const ANTHROPIC_CLIENT_NAME_FRAGMENTS = ['claudecode', 'claudeai', 'cowork', 'claudedesign'] as const++// Anthropic clients connect through a pooled MCP transport and usually omit the+// `initialize` body's `clientInfo.name`, reporting their live product only in the+// `x-anthropic-client` (`vendorClient`) header. Map that vendor value to the+// canonical client-name token the MCP analytics dashboard buckets on, so these+// sessions are attributed to a real client instead of falling into "Other".+// Mirrors the vendor→name mapping in the dashboard (harnessRegistry.ts and+// models-mcp.md) — keep the three in sync.+const VENDOR_CLIENT_TO_CLIENT_NAME: Readonly<Record<string, string>> = {+ claudecode: 'claude-code',+ claudeai: 'claude-ai',+ cowork: 'cowork',+ claudedesign: 'claude-design',+}++/**+ * Resolve the client name used for analytics (`$mcp_client_name`) and the API+ * client header. Prefers the self-reported `clientInfo.name`; when that's absent+ * — as it is for Anthropic clients on the pooled transport — it falls back to a+ * canonical name derived from the `x-anthropic-client` vendor header, keeping the+ * raw vendor value for any unrecognized Anthropic product. Returns undefined when+ * neither is available.+ */+export function resolveEffectiveClientName(+ clientName: string | undefined,+ vendorClient: string | undefined+): string | undefined {+ if (clientName) {+ return clientName+ }+ if (!vendorClient) {+ return undefined+ }+ return VENDOR_CLIENT_TO_CLIENT_NAME[normalizeClientName(vendorClient)] ?? vendorClient+}// Value sent in `x-posthog-mcp-consumer` by PostHog Code (the Tasks sandbox// wrapper around the Claude Agent SDK) when the task was launched from the@@ -121,7 +156,14 @@ export const VIBE_CODING_OAUTH_CLIENT_NAME_FRAGMENTS = ['lovable', 'replit', 'no// `clientInfo.name` is also `Anthropic/ClaudeAI`, and matching it would// misclassify Claude Code as a UI host.export const ANTHROPIC_UI_HOST_VENDOR_FRAGMENTS = ['claudeai'] as const-export const ANTHROPIC_UI_HOST_USER_AGENT_FRAGMENTS = ['claude-user'] as const++// User-Agent Anthropic clients send when they connect without the+// `x-anthropic-client` header (Claude.ai web/desktop and internal Anthropic+// tooling). It's a generic Anthropic signal — Claude Code and Cowork can send it+// too — so it drives CLI-mode detection; the UI-host check reuses it as its own+// user-agent fallback.+export const ANTHROPIC_USER_AGENT_FRAGMENTS = ['claude-user'] as const+export const ANTHROPIC_UI_HOST_USER_AGENT_FRAGMENTS = ANTHROPIC_USER_AGENT_FRAGMENTSexport type ClientCapabilities = {// MCP `initialize` response includes an `instructions` field that most@@ -179,17 +221,30 @@ export class MCPClientProfile {}isCliModeEnabled(): boolean {- // Every known Anthropic client (matched against the `x-anthropic-client`- // header) runs in CLI (single-exec) mode — Anthropic pools MCP transports- // across all its products (Claude Code, Claude.ai, Cowork, …) and reports- // the live product in that header.- if (matchesAnyFragment(this.vendorClient, ANTHROPIC_CLIENT_NAME_FRAGMENTS)) {+ // Every Anthropic product runs in CLI (single-exec) mode.+ if (this.isAnthropicClient()) {return true}// Otherwise fall back to the self-reported client name for coding agents.return matchesAnyFragment(this.clientName, CODING_AGENT_CLIENT_NAME_FRAGMENTS)}+ isAnthropicClient(): boolean {+ // Anthropic pools MCP transports across all its products (Claude Code,+ // Claude.ai, Cowork, Claude Design, …), so the `x-anthropic-client` header+ // is the reliable signal of the live product when present. Some surfaces+ // (Claude.ai web/desktop, internal tools) connect without that header, so+ // also accept the `Claude-User` user-agent and the pooled `Anthropic/…`+ // `clientInfo.name`. Unlike `isClaudeUiHost`, matching the pooled name here+ // is safe and intended: every Anthropic product belongs in CLI mode, so+ // there is nothing to misclassify.+ return (+ matchesAnyFragment(this.vendorClient, ANTHROPIC_CLIENT_NAME_FRAGMENTS) ||+ matchesAnyFragment(this.userAgent, ANTHROPIC_USER_AGENT_FRAGMENTS) ||+ normalizeClientName(this.clientName ?? '').startsWith('anthropic')+ )+ }+isPostHogCodeConsumer(): boolean {return this.consumer === POSTHOG_CODE_CONSUMER}diff --git a/services/mcp/src/lib/request-properties.ts b/services/mcp/src/lib/request-properties.tsindex af9b29161ed7..5c4f9088787b 100644--- a/services/mcp/src/lib/request-properties.ts+++ b/services/mcp/src/lib/request-properties.ts@@ -1,6 +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 { resolveEffectiveClientName } from './client-detection'import { extractBearerToken, hash, parseMcpMode, sanitizeHeaderValue, type McpMode } from './utils'export type Transport = 'streamable-http' | 'sse'@@ -64,6 +65,7 @@ export function parseRequestProperties(const token = extractBearerToken(request) ?? ''const readOnlyRaw = header(request, 'x-posthog-read-only') || params.get('readonly')+ const vendorClient = sanitizeHeaderValue(header(request, 'x-anthropic-client'))return {apiToken: token,@@ -79,10 +81,10 @@ export function parseRequestProperties(mcpConsumer: sanitizeHeaderValue(header(request, 'x-posthog-mcp-consumer') || params.get('consumer') || undefined),- mcpClientName: clientInfo.clientName,+ mcpClientName: resolveEffectiveClientName(clientInfo.clientName, vendorClient),mcpClientVersion: clientInfo.clientVersion,mcpProtocolVersion: clientInfo.protocolVersion,- mcpVendorClient: sanitizeHeaderValue(header(request, 'x-anthropic-client')),+ mcpVendorClient: vendorClient,mode: parseMcpMode(header(request, 'x-posthog-mcp-mode') || params.get('mode')),taskId: sanitizeHeaderValue(header(request, 'x-posthog-task-id')),transport,diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.tsindex 909f8c47feae..d8a9da981d20 100644--- a/services/mcp/tests/hono/request-state-resolver.test.ts+++ b/services/mcp/tests/hono/request-state-resolver.test.ts@@ -235,16 +235,31 @@ describe('RequestStateResolver MCP client contexts', () => {expect(props.mode).toBe('cli')})- it('keeps Claude web/desktop in tools mode when the render-ui flag is off', async () => {- // A `ClaudeAI` vendor header is unconditionally single-exec, so the render-ui- // gate only observably matters on the User-Agent-only path, where the client- // isn't otherwise a CLI-mode client.+ it('keeps Claude web/desktop in single-exec via the Claude-User user agent even when the render-ui flag is off', async () => {+ // Anthropic clients always run in CLI (single-exec) mode, so the+ // User-Agent-only path is single-exec regardless of the render-ui flag — the+ // flag only gates whether the `render-ui` tool itself is advertised.const props = makeProps({ mcpClientName: 'Claude Desktop', clientUserAgent: 'Claude-User' })const result = await makeResolver().resolve(props)expect(result.renderUiEnabled).toBe(false)- expect(result.useSingleExec).toBe(false)- expect(props.mode).toBe('tools')+ expect(result.useSingleExec).toBe(true)+ expect(props.mode).toBe('cli')+ })++ it('puts header-less Claude.ai (pooled Anthropic/* name + Claude-User UA, no vendor header) in single-exec', async () => {+ // The production gap: Claude.ai web/desktop sessions that omit the+ // x-anthropic-client header and report only clientInfo.name "Anthropic/ClaudeAI"+ // with a Claude-User user-agent previously fell into tools mode.+ const props = makeProps({+ mcpClientName: 'Anthropic/ClaudeAI',+ mcpVendorClient: undefined,+ clientUserAgent: 'Claude-User',+ })+ const result = await makeResolver().resolve(props)++ expect(result.useSingleExec).toBe(true)+ expect(props.mode).toBe('cli')})it('does not enable render-ui for Claude Code even when the flag is on', async () => {diff --git a/services/mcp/tests/unit/client-detection.test.ts b/services/mcp/tests/unit/client-detection.test.tsindex 19da6c38e014..a401a31829d9 100644--- a/services/mcp/tests/unit/client-detection.test.ts+++ b/services/mcp/tests/unit/client-detection.test.ts@@ -13,6 +13,7 @@ import {isCliModeEnabledClient,isPostHogCodeConsumer,isVibeCodingClient,+ resolveEffectiveClientName,} from '@/lib/client-detection'describe('isCliModeEnabledClient', () => {@@ -120,6 +121,38 @@ describe('isCliModeEnabledClient', () => {})})+describe('resolveEffectiveClientName', () => {+ it('prefers the self-reported clientName when present', () => {+ expect(resolveEffectiveClientName('Cursor', 'ClaudeCode')).toBe('Cursor')+ expect(resolveEffectiveClientName('claude-code', undefined)).toBe('claude-code')+ })++ it.each([+ ['ClaudeCode', 'claude-code'],+ ['ClaudeAI', 'claude-ai'],+ ['Cowork', 'cowork'],+ ['ClaudeDesign', 'claude-design'],+ // Case- and separator-insensitive, matching normalizeClientName.+ ['claudecode', 'claude-code'],+ ['CLAUDE-CODE', 'claude-code'],+ ])('maps vendor header %s to %s when clientName is absent', (vendorClient, expected) => {+ expect(resolveEffectiveClientName(undefined, vendorClient)).toBe(expected)+ })++ it('keeps an unrecognized vendor value rather than dropping it', () => {+ expect(resolveEffectiveClientName(undefined, 'SomeFutureAnthropicProduct')).toBe('SomeFutureAnthropicProduct')+ })++ it('returns undefined when neither clientName nor vendorClient is set', () => {+ expect(resolveEffectiveClientName(undefined, undefined)).toBeUndefined()+ expect(resolveEffectiveClientName('', undefined)).toBeUndefined()+ })++ it('falls back to the vendor header when clientName is empty', () => {+ expect(resolveEffectiveClientName('', 'ClaudeCode')).toBe('claude-code')+ })+})+describe('isPostHogCodeConsumer', () => {it('matches the exact PostHog Code consumer value', () => {expect(isPostHogCodeConsumer(POSTHOG_CODE_CONSUMER)).toBe(true)@@ -283,6 +316,29 @@ describe('MCPClientProfile', () => {it('uses clientName for non-Anthropic clients (no vendorClient)', () => {expect(new MCPClientProfile({ clientName: 'Claude Desktop' }).isCliModeEnabled()).toBe(false)})++ it('enables CLI mode for the ClaudeDesign vendor header', () => {+ expect(new MCPClientProfile({ vendorClient: 'ClaudeDesign' }).isCliModeEnabled()).toBe(true)+ })++ it.each([['Claude-User'], ['claude-user'], ['Claude_User']])(+ 'enables CLI mode via the %s user-agent when the vendor header is absent',+ (userAgent) => {+ // Claude.ai web/desktop and some internal Anthropic tools connect+ // without x-anthropic-client, identifying only via this user-agent.+ expect(new MCPClientProfile({ userAgent }).isCliModeEnabled()).toBe(true)+ }+ )++ it.each([['Anthropic/ClaudeAI'], ['Anthropic/Toolbox'], ['anthropic/claudeai']])(+ 'enables CLI mode via the pooled %s clientInfo.name when the vendor header is absent',+ (clientName) => {+ // Header-less Anthropic sessions report only the pooled Anthropic/*+ // pool-owner name. Matching it for CLI mode is safe (unlike UI-host+ // detection) because every Anthropic product belongs in CLI mode.+ expect(new MCPClientProfile({ clientName }).isCliModeEnabled()).toBe(true)+ }+ )})})diff --git a/services/mcp/tests/unit/protocol-types.test.ts b/services/mcp/tests/unit/protocol-types.test.tsindex d8a4487420d2..cc6594455d60 100644--- a/services/mcp/tests/unit/protocol-types.test.ts+++ b/services/mcp/tests/unit/protocol-types.test.ts@@ -81,16 +81,16 @@ describe('resolveMode', () => {expect(result.useSingleExec).toBe(true)})- it('Claude web/desktop detected via User-Agent stays in tools mode when render-ui is disabled', () => {- // A `ClaudeAI` vendor header is unconditionally single-exec, so the render-ui- // gate only observably matters on the User-Agent-only path, where the client- // isn't otherwise a CLI-mode client.+ it('Claude web/desktop detected via User-Agent stays single exec even when render-ui is disabled', () => {+ // Anthropic clients always run in CLI (single-exec) mode, so the Claude-User+ // user-agent resolves to single-exec regardless of the render-ui flag — the+ // flag only gates whether the `render-ui` tool itself is advertised.const result = resolveMode({...base,clientProfile: profile({ userAgent: 'Claude-User' }),renderUiFlagEnabled: false,})- expect(result.useSingleExec).toBe(false)+ expect(result.useSingleExec).toBe(true)})it('explicit mode=tools wins over Claude UI host even with render-ui enabled', () => {diff --git a/services/mcp/tests/unit/url-routing.test.ts b/services/mcp/tests/unit/url-routing.test.tsindex c418b37e04e8..7ac8e19177e3 100644--- a/services/mcp/tests/unit/url-routing.test.ts+++ b/services/mcp/tests/unit/url-routing.test.ts@@ -252,6 +252,29 @@ describe('URL Routing', () => {})expect(parseRequestProperties(request, {}).mcpVendorClient).toBeUndefined()})++ it('defaults mcpClientName from x-anthropic-client when clientInfo omits a name', () => {+ // Anthropic clients pool MCP transports and send no `clientInfo.name`, so+ // without this fallback `$mcp_client_name` is empty and the analytics+ // dashboard buckets the traffic as "Other".+ const request = new Request('https://example.com/mcp', {+ headers: {+ Authorization: 'Bearer phx_test',+ 'x-anthropic-client': 'ClaudeCode',+ },+ })+ expect(parseRequestProperties(request, {}).mcpClientName).toBe('claude-code')+ })++ it('keeps the self-reported clientName over the vendor header', () => {+ const request = new Request('https://example.com/mcp', {+ headers: {+ Authorization: 'Bearer phx_test',+ 'x-anthropic-client': 'ClaudeCode',+ },+ })+ expect(parseRequestProperties(request, { clientName: 'Cursor' }).mcpClientName).toBe('Cursor')+ })})describe('MCP consumer parsing', () => {