: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): keep mode for a session id (#60288)
Georgiy Tarasovd840216bf8b5
diff --git a/services/mcp/src/hono/analytics.ts b/services/mcp/src/hono/analytics.tsindex 3b4d5dff7681..c20fc7c1e837 100644--- a/services/mcp/src/hono/analytics.ts+++ b/services/mcp/src/hono/analytics.ts@@ -1,19 +1,19 @@import { MCP_ANALYTICS_SOURCE, MCP_SERVER_NAME, MCP_SERVER_VERSION } from '@/lib/constants'import { getPostHogClient } from '@/lib/posthog'import { buildMCPAnalyticsGroups, buildMCPContextProperties, type MCPAnalyticsContext } from '@/lib/posthog/analytics'-import type { RequestProperties } from '@/lib/request-properties'+import { buildMCPSessionAnalyticsProperties } from './mcp-context'import type { ResolvedState } from './request-state-resolver'function buildBaseProperties(state: ResolvedState,- props: RequestProperties,analyticsContext: MCPAnalyticsContext | undefined): {properties: Record<string, unknown>groups: Record<string, string>} {const groups = analyticsContext ? buildMCPAnalyticsGroups(analyticsContext) : {}+ const requestContext = state.requestContextconst properties: Record<string, unknown> = {$ai_product: 'mcp',@@ -21,16 +21,16 @@ function buildBaseProperties($mcp_server_name: MCP_SERVER_NAME,$mcp_server_version: MCP_SERVER_VERSION,$mcp_version: state.version,- $mcp_client_name: props.mcpClientName,- $mcp_client_version: props.mcpClientVersion,- $mcp_client_user_agent: props.clientUserAgent,- $mcp_protocol_version: props.mcpProtocolVersion,- $mcp_transport: props.transport,- $mcp_session_id: props.mcpSessionId,- $mcp_conversation_id: props.mcpConversationId,- $mcp_consumer: props.mcpConsumer,- $mcp_mode: props.mode,- $mcp_region: props.region,+ $mcp_client_name: requestContext.mcpClientName,+ $mcp_client_version: requestContext.mcpClientVersion,+ $mcp_client_user_agent: requestContext.clientUserAgent,+ $mcp_protocol_version: requestContext.mcpProtocolVersion,+ $mcp_transport: requestContext.transport,+ $mcp_session_id: requestContext.mcpSessionId,+ $mcp_conversation_id: requestContext.mcpConversationId,+ $mcp_consumer: requestContext.mcpConsumer,+ $mcp_mode: requestContext.mode,+ $mcp_region: requestContext.region,...(analyticsContext? {$mcp_organization_id: analyticsContext.organizationId,@@ -41,17 +41,24 @@ function buildBaseProperties(}: {}),mcp_runtime: 'hono',+ mcp_vendor_client: requestContext.mcpVendorClient,+ ...buildMCPSessionAnalyticsProperties(state.sessionContext),}return { properties, groups }}-export async function trackInitEvent(props: RequestProperties, state: ResolvedState): Promise<void> {+export async function trackInitEvent(state: ResolvedState): Promise<void> {try {const analyticsContext = await state.reqCtx.getAnalyticsContextSafe(state.context)- const initDurationMs = props.requestStartTime ? Date.now() - props.requestStartTime : undefined- const sessionUuid = props.sessionId ? await state.reqCtx.getSessionUuid(props.sessionId) : undefined+ const requestContext = state.requestContext+ const initDurationMs = requestContext.requestStartTime+ ? Date.now() - requestContext.requestStartTime+ : undefined+ const sessionUuid = requestContext.sessionId+ ? await state.reqCtx.getSessionUuid(requestContext.sessionId)+ : undefined- const { properties, groups } = buildBaseProperties(state, props, analyticsContext)+ const { properties, groups } = buildBaseProperties(state, analyticsContext)getPostHogClient().capture({distinctId: state.distinctId,@@ -62,10 +69,10 @@ export async function trackInitEvent(props: RequestProperties, state: ResolvedSt$mcp_duration_ms: initDurationMs ?? 0,$mcp_is_error: false,tool_count: state.allTools.length,- has_organization_id: !!props.organizationId,- has_project_id: !!props.projectId,- read_only: !!props.readOnly,- via_sse_redirect: !!props.viaSseRedirect,+ has_organization_id: !!requestContext.organizationId,+ has_project_id: !!requestContext.projectId,+ read_only: !!requestContext.readOnly,+ via_sse_redirect: !!requestContext.viaSseRedirect,...(sessionUuid ? { $session_id: sessionUuid } : {}),},})@@ -78,15 +85,17 @@ export async function trackToolCall(toolName: string,durationMs: number,isError: boolean,- props: RequestProperties,state: ResolvedState,extraProperties?: Record<string, unknown>): Promise<void> {try {const analyticsContext = await state.reqCtx.getAnalyticsContextSafe(state.context)- const sessionUuid = props.sessionId ? await state.reqCtx.getSessionUuid(props.sessionId) : undefined+ const requestContext = state.requestContext+ const sessionUuid = requestContext.sessionId+ ? await state.reqCtx.getSessionUuid(requestContext.sessionId)+ : undefined- const { properties, groups } = buildBaseProperties(state, props, analyticsContext)+ const { properties, groups } = buildBaseProperties(state, analyticsContext)getPostHogClient().capture({distinctId: state.distinctId,diff --git a/services/mcp/src/hono/dispatcher.ts b/services/mcp/src/hono/dispatcher.tsindex 26c66edb9eef..880b933175a4 100644--- a/services/mcp/src/hono/dispatcher.ts+++ b/services/mcp/src/hono/dispatcher.ts@@ -188,9 +188,9 @@ class McpDispatcher {case Method.Initialize:return jsonRpcResult(id, await this.handleInitialize(params, props, state!))case Method.ToolsList:- return jsonRpcResult(id, await this.toolExecutor.handleToolsList(state!, props))+ return jsonRpcResult(id, await this.toolExecutor.handleToolsList(state!))case Method.ToolsCall:- return jsonRpcResult(id, await this.toolExecutor.handleToolCall(params, props, state!))+ return jsonRpcResult(id, await this.toolExecutor.handleToolCall(params, state!))case Method.ResourcesList:return jsonRpcResult(id, this.resourceCatalog.getResourcesList())case Method.ResourcesRead:@@ -227,7 +227,7 @@ class McpDispatcher {initDurationSeconds.observe(props.requestStartTime ? (Date.now() - props.requestStartTime) / 1000 : 0)initTotal.inc({ status: 'success' })- void trackInitEvent(props, state)+ void trackInitEvent(state)return {protocolVersion,diff --git a/services/mcp/src/hono/instructions.ts b/services/mcp/src/hono/instructions.tsindex ad43b1925cfb..9970ce65dd4c 100644--- a/services/mcp/src/hono/instructions.ts+++ b/services/mcp/src/hono/instructions.ts@@ -1,3 +1,5 @@+import type { Tool as McpTool } from '@modelcontextprotocol/sdk/types.js'+import { hasScope } from '@/lib/api'import type { QueryToolInfo } from '@/lib/instructions'import { type InstructionsContext, InstructionsFormatter } from '@/lib/instructions-formatter'@@ -6,8 +8,6 @@ import { formatPrompt } from '@/lib/utils'import EXECUTE_SQL_PROMPT from '@/templates/execute-sql-prompt.md'import { getToolDefinition } from '@/tools/toolDefinitions'-import type { Tool as McpTool } from '@modelcontextprotocol/sdk/types.js'-import type { ResolvedState } from './request-state-resolver'export class InstructionsBuilder {@@ -69,7 +69,7 @@ export class InstructionsBuilder {}}- buildExecToolEntry(state: ResolvedState, _props: RequestProperties): McpTool {+ buildExecToolEntry(state: ResolvedState): McpTool {const supportsInstructions = state.clientProfile.capabilities.supportsInstructionsconst ctx = this.buildContext(state)const commandReference = this.formatter.buildExecCommandReference(ctx, {diff --git a/services/mcp/src/hono/mcp-context.ts b/services/mcp/src/hono/mcp-context.tsnew file mode 100644index 000000000000..c03bfd6e09e9--- /dev/null+++ b/services/mcp/src/hono/mcp-context.ts@@ -0,0 +1,74 @@+import type { RequestProperties } from '@/lib/request-properties'+import type { McpMode } from '@/lib/utils'++export interface MCPClientContext extends Pick<+ RequestProperties,+ 'mcpClientName' | 'mcpClientVersion' | 'mcpProtocolVersion' | 'mcpConsumer' | 'mcpVendorClient'+> {}++export interface MCPRequestContext+ extends+ MCPClientContext,+ Pick<+ RequestProperties,+ | 'sessionId'+ | 'organizationId'+ | 'projectId'+ | 'readOnly'+ | 'viaSseRedirect'+ | 'requestStartTime'+ | 'clientUserAgent'+ | 'transport'+ | 'mcpSessionId'+ | 'mcpConversationId'+ | 'region'+ > {+ mode?: McpMode | undefined+}++// Identical shape to MCPClientContext but tracked separately to mark values+// pinned to the MCP session id rather than the live request.+export interface MCPSessionContext extends MCPClientContext {}++export function buildMCPRequestContext(props: RequestProperties): MCPRequestContext {+ return {+ sessionId: props.sessionId,+ organizationId: props.organizationId,+ projectId: props.projectId,+ readOnly: props.readOnly,+ viaSseRedirect: props.viaSseRedirect,+ requestStartTime: props.requestStartTime,+ clientUserAgent: props.clientUserAgent,+ mcpClientName: props.mcpClientName,+ mcpClientVersion: props.mcpClientVersion,+ mcpProtocolVersion: props.mcpProtocolVersion,+ transport: props.transport,+ mcpSessionId: props.mcpSessionId,+ mcpConversationId: props.mcpConversationId,+ mcpConsumer: props.mcpConsumer,+ mode: props.mode,+ region: props.region,+ mcpVendorClient: props.mcpVendorClient,+ }+}++export function buildMCPSessionAnalyticsProperties(sessionContext: MCPSessionContext | null): Record<string, unknown> {+ if (!sessionContext) {+ return {}+ }++ return {+ mcp_session_client_name: sessionContext.mcpClientName,+ mcp_session_client_version: sessionContext.mcpClientVersion,+ mcp_session_protocol_version: sessionContext.mcpProtocolVersion,+ mcp_session_consumer: sessionContext.mcpConsumer,+ mcp_session_vendor_client: sessionContext.mcpVendorClient,+ }+}++export function getEffectiveMCPClientContext(+ requestContext: MCPRequestContext,+ sessionContext: MCPSessionContext | null+): MCPClientContext {+ return sessionContext ?? requestContext+}diff --git a/services/mcp/src/hono/request-context.ts b/services/mcp/src/hono/request-context.tsindex fa39b056c56d..ae3dc52be8b2 100644--- a/services/mcp/src/hono/request-context.ts+++ b/services/mcp/src/hono/request-context.ts@@ -1,21 +1,27 @@import { ApiClient } from '@/api/client'import { MCP_ANALYTICS_SOURCE, MCP_SERVER_NAME, MCP_SERVER_VERSION } from '@/lib/constants'import { wrapError } from '@/lib/errors'-import { hash } from '@/lib/utils'+import { getPostHogClient } from '@/lib/posthog'import {AnalyticsEvent,buildMCPAnalyticsGroups,buildMCPContextProperties,type MCPAnalyticsContext,} from '@/lib/posthog/analytics'-import { getPostHogClient } from '@/lib/posthog'import type { RequestProperties } from '@/lib/request-properties'import { SessionManager } from '@/lib/SessionManager'import { StateManager } from '@/lib/StateManager'+import { hash } from '@/lib/utils'import type { Context, Env, State } from '@/tools/types'import { RedisCache, type RedisLike } from './cache/RedisCache'import { getCustomApiBaseUrl } from './constants'+import {+ buildMCPRequestContext,+ buildMCPSessionAnalyticsProperties,+ type MCPRequestContext,+ type MCPSessionContext,+} from './mcp-context'export class RequestContext {private tokenCacheInstance: RedisCache<State> | undefined@@ -27,11 +33,19 @@ export class RequestContext {private readonly redis: RedisLikeprivate readonly env: Envprivate readonly props: RequestProperties+ private requestContext: MCPRequestContext+ private sessionContext: MCPSessionContext | null = null- constructor(redis: RedisLike, env: Env, props: RequestProperties) {+ constructor(+ redis: RedisLike,+ env: Env,+ props: RequestProperties,+ requestContext: MCPRequestContext = buildMCPRequestContext(props)+ ) {this.redis = redisthis.env = envthis.props = props+ this.requestContext = requestContext}get tokenCache(): RedisCache<State> {@@ -140,11 +154,16 @@ export class RequestContext {const trackEvent: Context['trackEvent'] = async (event, properties = {}) => {const analyticsContext = await this.getAnalyticsContextSafe(partialContext)const distinctId = await this.getDistinctId()- await this.trackEvent(event, properties, analyticsContext, undefined, distinctId, this.props)+ await this.trackEvent(event, properties, analyticsContext, undefined, distinctId)}return { ...partialContext, trackEvent }}+ setMcpContexts(requestContext: MCPRequestContext, sessionContext: MCPSessionContext | null): void {+ this.requestContext = requestContext+ this.sessionContext = sessionContext+ }+async getAnalyticsContextSafe(context: Pick<Context, 'stateManager'>): Promise<MCPAnalyticsContext | undefined> {try {return await context.stateManager.getAnalyticsContext()@@ -174,27 +193,31 @@ export class RequestContext {}const distinctId = await this.getDistinctId()- await this.trackEvent(event, {}, resolvedContext, previousContext, distinctId, this.props)+ await this.trackEvent(event, {}, resolvedContext, previousContext, distinctId)}- buildClientProperties(props?: RequestProperties): Record<string, unknown> {- const p = props ?? this.props+ buildClientProperties(+ requestContext: MCPRequestContext = this.requestContext,+ sessionContext: MCPSessionContext | null = this.sessionContext+ ): Record<string, unknown> {return {$ai_product: 'mcp',$mcp_source: MCP_ANALYTICS_SOURCE,$mcp_server_name: MCP_SERVER_NAME,$mcp_server_version: MCP_SERVER_VERSION,- $mcp_client_name: p.mcpClientName,- $mcp_client_version: p.mcpClientVersion,- $mcp_client_user_agent: p.clientUserAgent,- $mcp_protocol_version: p.mcpProtocolVersion,- $mcp_transport: p.transport,- $mcp_session_id: p.mcpSessionId,- $mcp_conversation_id: p.mcpConversationId,- $mcp_consumer: p.mcpConsumer,- $mcp_mode: p.mode,- $mcp_region: p.region,+ $mcp_client_name: requestContext.mcpClientName,+ $mcp_client_version: requestContext.mcpClientVersion,+ $mcp_client_user_agent: requestContext.clientUserAgent,+ $mcp_protocol_version: requestContext.mcpProtocolVersion,+ $mcp_transport: requestContext.transport,+ $mcp_session_id: requestContext.mcpSessionId,+ $mcp_conversation_id: requestContext.mcpConversationId,+ $mcp_consumer: requestContext.mcpConsumer,+ $mcp_mode: requestContext.mode,+ $mcp_region: requestContext.region,mcp_runtime: 'hono',+ mcp_vendor_client: requestContext.mcpVendorClient,+ ...buildMCPSessionAnalyticsProperties(sessionContext),}}@@ -203,12 +226,10 @@ export class RequestContext {properties: Record<string, unknown>,analyticsContext?: MCPAnalyticsContext,previousContext?: MCPAnalyticsContext,- distinctId?: string,- props?: RequestProperties+ distinctId?: string): Promise<void> {try {const resolvedDistinctId = distinctId ?? (await this.getDistinctId())- const resolvedProps = props ?? this.propsconst clientName = await this.tokenCache.get('clientName')const contextProperties = analyticsContext ? buildMCPContextProperties(analyticsContext) : {}const previousContextProperties = previousContext@@ -221,9 +242,9 @@ export class RequestContext {event,...(Object.keys(groups).length > 0 ? { groups } : {}),properties: {- ...this.buildClientProperties(resolvedProps),- ...(resolvedProps.sessionId- ? { $session_id: await this.getSessionUuid(resolvedProps.sessionId) }+ ...this.buildClientProperties(),+ ...(this.requestContext.sessionId+ ? { $session_id: await this.getSessionUuid(this.requestContext.sessionId) }: {}),...(clientName ? { $mcp_oauth_client_name: clientName } : {}),...contextProperties,diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.tsindex 2be14c131571..7639a68a37e2 100644--- a/services/mcp/src/hono/request-state-resolver.ts+++ b/services/mcp/src/hono/request-state-resolver.ts@@ -4,9 +4,15 @@ import { evaluateFeatureFlags, type FlagGroups } from '@/lib/posthog/flags'import type { RequestProperties } from '@/lib/request-properties'import type { McpMode } from '@/lib/utils'import { getRequiredFeatureFlags } from '@/tools/toolDefinitions'-import type { Context, Tool, Env, ZodObjectAny } from '@/tools/types'+import type { Context, Tool, Env, State, ZodObjectAny } from '@/tools/types'import type { RedisLike } from './cache/RedisCache'+import {+ buildMCPRequestContext,+ getEffectiveMCPClientContext,+ type MCPRequestContext,+ type MCPSessionContext,+} from './mcp-context'import { RequestContext } from './request-context'import type { ToolCatalog } from './tool-catalog'@@ -20,6 +26,8 @@ export interface ResolvedState {toolFeatureFlags: Record<string, boolean> | undefinedapiKeyScopes: string[]clientProfile: MCPClientProfile+ requestContext: MCPRequestContext+ sessionContext: MCPSessionContext | nullallTools: Tool<ZodObjectAny>[]distinctId: string}@@ -31,7 +39,7 @@ export function resolveModeAndVersion(args: {clientProfile: MCPClientProfileflagVersion: number | undefinedclientVersion: number | undefined-}): { useSingleExec: boolean; version: number } {+}): { mode: McpMode; useSingleExec: boolean; version: number } {const { mode, clientProfile, flagVersion, clientVersion } = argsconst useSingleExec =mode === 'cli' ||@@ -40,12 +48,21 @@ export function resolveModeAndVersion(args: {clientProfile.isPostHogCodeConsumer() ||clientProfile.isVibeCodingClient()))const version = useSingleExec ? 2 : (flagVersion ?? clientVersion ?? 1)- return { useSingleExec, version }+ return { mode: mode ?? (useSingleExec ? 'cli' : 'tools'), useSingleExec, version }}// ─── Resolver ───const SYSTEM_FLAGS = ['mcp-version-2'] as const+const SESSION_CONTEXT_KEYS = [+ 'mcpClientName',+ 'mcpClientVersion',+ 'mcpProtocolVersion',+ 'mcpConsumer',+ 'mcpVendorClient',+] as const+type SessionContextKey = (typeof SESSION_CONTEXT_KEYS)[number]+type SessionContextCache = Pick<State, SessionContextKey>export class RequestStateResolver {private readonly catalog: ToolCatalog@@ -59,24 +76,20 @@ export class RequestStateResolver {}async resolve(props: RequestProperties): Promise<ResolvedState> {- const reqCtx = new RequestContext(this.redis, this.env, props)+ const requestContext = buildMCPRequestContext(props)+ const reqCtx = new RequestContext(this.redis, this.env, props, requestContext)+ const sessionContext = await this.resolveSessionContext(reqCtx, requestContext)+ const clientContext = getEffectiveMCPClientContext(requestContext, sessionContext)+const context = await reqCtx.getContext()- const { features, tools, version: clientVersion, organizationId, projectId, readOnly, mode } = props+ const { features, tools, version: clientVersion, organizationId, projectId, readOnly } = propsawait reqCtx.tokenCache.setMany({...(organizationId ? { orgId: organizationId } : {}),...(projectId ? { projectId } : {}),})- if (props.mcpSessionId) {- await reqCtx.sessionCache.setMany({- ...(props.mcpClientName ? { mcpClientName: props.mcpClientName } : {}),- ...(props.mcpClientVersion ? { mcpClientVersion: props.mcpClientVersion } : {}),- ...(props.mcpProtocolVersion ? { mcpProtocolVersion: props.mcpProtocolVersion } : {}),- })- }-let cachedProjectId = projectId || (await reqCtx.tokenCache.get('projectId'))if (!cachedProjectId) {await context.stateManager.setDefaultOrganizationAndProject()@@ -101,40 +114,27 @@ export class RequestStateResolver {const oauthClientName = (await reqCtx.tokenCache.get('clientName')) || undefined- let mcpClientName = props.mcpClientName- let mcpClientVersion = props.mcpClientVersion- let mcpProtocolVersion = props.mcpProtocolVersion- if (props.mcpSessionId && (!mcpClientName || !mcpClientVersion || !mcpProtocolVersion)) {- const [cachedName, cachedVersion, cachedProto] = await Promise.all([- mcpClientName ? undefined : reqCtx.sessionCache.get('mcpClientName'),- mcpClientVersion ? undefined : reqCtx.sessionCache.get('mcpClientVersion'),- mcpProtocolVersion ? undefined : reqCtx.sessionCache.get('mcpProtocolVersion'),- ])- mcpClientName = mcpClientName || cachedName || undefined- mcpClientVersion = mcpClientVersion || cachedVersion || undefined- mcpProtocolVersion = mcpProtocolVersion || cachedProto || undefined- }-- props.mcpClientName = mcpClientName- props.mcpClientVersion = mcpClientVersion- props.mcpProtocolVersion = mcpProtocolVersionconst clientProfile = new MCPClientProfile({- clientName: mcpClientName,- clientVersion: mcpClientVersion,- consumer: props.mcpConsumer,+ clientName: clientContext.mcpClientName,+ clientVersion: clientContext.mcpClientVersion,+ consumer: clientContext.mcpConsumer,oauthClientName,+ vendorClient: clientContext.mcpVendorClient,})- const { useSingleExec, version } = resolveModeAndVersion({- mode,+ const {+ mode: resolvedMode,+ useSingleExec,+ version,+ } = resolveModeAndVersion({+ mode: requestContext.mode,clientProfile,flagVersion,clientVersion,})-- if (!props.mode) {- props.mode = useSingleExec ? 'cli' : 'tools'- }+ requestContext.mode = resolvedMode+ reqCtx.setMcpContexts(requestContext, sessionContext)+ props.mode = resolvedModeconst apiKeyScopes = _apiKey?.scopes ?? []const apiKeyScopedTeams = _apiKey?.scoped_teams ?? []@@ -167,11 +167,42 @@ export class RequestStateResolver {toolFeatureFlags,apiKeyScopes,clientProfile,+ requestContext,+ sessionContext,allTools,distinctId,}}+ private async resolveSessionContext(+ reqCtx: RequestContext,+ requestContext: MCPRequestContext+ ): Promise<MCPSessionContext | null> {+ if (!requestContext.mcpSessionId) {+ return null+ }++ const cachedEntries = await Promise.all(+ SESSION_CONTEXT_KEYS.map(async (key) => [key, await reqCtx.sessionCache.get(key)] as const)+ )+ const cachedContext = Object.fromEntries(cachedEntries) as Partial<SessionContextCache>++ const cacheUpdates: Partial<SessionContextCache> = {}+ for (const key of SESSION_CONTEXT_KEYS) {+ if (!cachedContext[key] && requestContext[key]) {+ cacheUpdates[key] = requestContext[key]+ }+ }++ if (Object.keys(cacheUpdates).length > 0) {+ await reqCtx.sessionCache.setMany(cacheUpdates)+ }++ return Object.fromEntries(+ SESSION_CONTEXT_KEYS.map((key) => [key, cachedContext[key] || requestContext[key] || undefined])+ ) as MCPSessionContext+ }+private async resolveAllFlags(reqCtx: RequestContext,flagKeys: string[],diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 57d8f835907e..182e5574fb0b 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -11,12 +11,12 @@ import {findRecoverableApiError,} from '@/lib/errors'import { AnalyticsEvent } from '@/lib/posthog/analytics'-import type { RequestProperties } from '@/lib/request-properties'import { createExecTool, type ExecInnerCallTracker } from '@/tools/exec'import type { Context, ZodObjectAny } from '@/tools/types'import { trackToolCall } from './analytics'import type { InstructionsBuilder } from './instructions'+import { getEffectiveMCPClientContext } from './mcp-context'import { toolCallDurationSeconds, toolCallsTotal, toolErrorsTotal } from './metrics'import type { ResolvedState } from './request-state-resolver'import type { ToolCatalog } from './tool-catalog'@@ -41,9 +41,9 @@ export class ToolExecutor {this.instructionsBuilder = instructionsBuilder}- async handleToolsList(state: ResolvedState, props: RequestProperties): Promise<ListToolsResult> {+ async handleToolsList(state: ResolvedState): Promise<ListToolsResult> {if (state.useSingleExec) {- return { tools: [this.instructionsBuilder.buildExecToolEntry(state, props)] }+ return { tools: [this.instructionsBuilder.buildExecToolEntry(state)] }}const nameSet = new Set(state.allTools.map((t) => t.name))@@ -61,18 +61,14 @@ export class ToolExecutor {return { tools: filteredTools }}- async handleToolCall(- params: Record<string, unknown> | undefined,- props: RequestProperties,- state: ResolvedState- ): Promise<unknown> {+ async handleToolCall(params: Record<string, unknown> | undefined, state: ResolvedState): Promise<unknown> {const toolName = params?.name as stringif (!toolName) {return { content: [{ type: 'text', text: 'Missing tool name' }], isError: true }}- if (state.useSingleExec && toolName === 'exec') {- return this.callExecTool(params, props, state)+ if (toolName === 'exec') {+ return this.callExecTool(params, state)}if (!state.allTools.some((t) => t.name === toolName)) {@@ -94,7 +90,6 @@ export class ToolExecutor {_meta: preBuilt.base._meta,},params,- props,state)}@@ -102,7 +97,6 @@ export class ToolExecutor {private async callTool(tool: ResolvedTool,params: Record<string, unknown> | undefined,- props: RequestProperties,state: ResolvedState): Promise<unknown> {const toolArgs = (params?.arguments ?? {}) as Record<string, unknown>@@ -130,7 +124,7 @@ export class ToolExecutor {toolCallsTotal.inc({ tool: tool.name, status: 'success' })stop({ status: 'success' })- void trackToolCall(tool.name, Date.now() - startMs, false, props, state)+ void trackToolCall(tool.name, Date.now() - startMs, false, state)if (isToolCallPayload(handlerResult)) {return handlerResult@@ -145,7 +139,7 @@ export class ToolExecutor {toolMeta: tool._meta,toolName: tool.name,params: validation.data,- clientName: props.mcpClientName,+ suppressStructuredContentForFormattedResults: state.clientProfile.isCodingAgent(),distinctId,})} catch (error: unknown) {@@ -153,20 +147,16 @@ export class ToolExecutor {stop({ status: 'error' })classifyToolError(error, tool.name)- void trackToolCall(tool.name, Date.now() - startMs, true, props, state)+ void trackToolCall(tool.name, Date.now() - startMs, true, state)- const sessionUuid = await state.reqCtx.getSessionUuid(props.sessionId)+ const sessionUuid = await state.reqCtx.getSessionUuid(state.requestContext.sessionId)return handleToolError(error, tool.name, state.distinctId, sessionUuid)}}- private async callExecTool(- params: Record<string, unknown> | undefined,- props: RequestProperties,- state: ResolvedState- ): Promise<unknown> {+ private async callExecTool(params: Record<string, unknown> | undefined, state: ResolvedState): Promise<unknown> {const execMetrics: ExecMetricState = { innerToolName: undefined }- const resolved = this.resolveExecTool(state, props, execMetrics)+ const resolved = this.resolveExecTool(state, execMetrics)const toolArgs = (params?.arguments ?? {}) as Record<string, unknown>const validation = resolved.schema.safeParse(toolArgs)@@ -180,7 +170,7 @@ export class ToolExecutor {try {const handlerResult = await resolved.handler(state.context, validation.data)- void trackToolCall('exec', Date.now() - startMs, false, props, state)+ void trackToolCall('exec', Date.now() - startMs, false, state)if (isToolCallPayload(handlerResult)) {return handlerResult@@ -191,7 +181,7 @@ export class ToolExecutor {toolMeta: resolved._meta,toolName: 'exec',params: validation.data,- clientName: props.mcpClientName,+ suppressStructuredContentForFormattedResults: state.clientProfile.isCodingAgent(),distinctId: undefined,})} catch (error: unknown) {@@ -201,18 +191,14 @@ export class ToolExecutor {}classifyToolError(error, metricTool)- void trackToolCall('exec', Date.now() - startMs, true, props, state)+ void trackToolCall('exec', Date.now() - startMs, true, state)- const sessionUuid = await state.reqCtx.getSessionUuid(props.sessionId)+ const sessionUuid = await state.reqCtx.getSessionUuid(state.requestContext.sessionId)return handleToolError(error, 'exec', state.distinctId, sessionUuid)}}- private resolveExecTool(- state: ResolvedState,- props: RequestProperties,- execMetrics: ExecMetricState- ): ResolvedTool {+ private resolveExecTool(state: ResolvedState, execMetrics: ExecMetricState): ResolvedTool {const commandReference = this.instructionsBuilder.buildExecCommandReference(state)const trackInnerCall: ExecInnerCallTracker = (toolName, properties) => {@@ -228,18 +214,18 @@ export class ToolExecutor {{ tool_name: toolName, ...properties },freshContext,undefined,- state.distinctId,- props+ state.distinctId)})().catch(() => {})}+ const clientContext = getEffectiveMCPClientContext(state.requestContext, state.sessionContext)const execTool = createExecTool(state.allTools,state.context,this.instructionsBuilder.buildExecToolDescription(),commandReference,- props.mcpConsumer,+ clientContext.mcpConsumer,trackInnerCall)diff --git a/services/mcp/src/index.ts b/services/mcp/src/index.tsindex eb6bbf9c7d1c..e36f92ad6655 100644--- a/services/mcp/src/index.ts+++ b/services/mcp/src/index.ts@@ -344,6 +344,13 @@ const handleRequest = async (// the same `requestProperties.mcpConversationId` slot.const mcpConversationId = sanitizeHeaderValue(request.headers.get('mcp-conversation-id') || undefined)+ // Anthropic-set per-request identifier for the inner upstream client (e.g.+ // `ClaudeCode`, `ClaudeAI`, `Cowork`). Distinct from `mcpClientName` (the+ // MCP `initialize` body's `clientInfo.name`) because Claude pools MCP+ // transports — the same `mcpSessionId` can carry requests from multiple+ // upstream products, and only this header tracks the live one.+ const mcpVendorClient = sanitizeHeaderValue(request.headers.get('x-anthropic-client') || undefined)+Object.assign(ctx.props, {apiToken: token,userHash: hash(token),@@ -357,6 +364,7 @@ const handleRequest = async (mcpClientName: clientInfo.clientName,mcpClientVersion: clientInfo.clientVersion,mcpProtocolVersion: clientInfo.protocolVersion,+ mcpVendorClient,requestStartTime: Date.now(),})diff --git a/services/mcp/src/lib/build-tool-result.ts b/services/mcp/src/lib/build-tool-result.tsindex 3671c3b45245..54d015b77bde 100644--- a/services/mcp/src/lib/build-tool-result.ts+++ b/services/mcp/src/lib/build-tool-result.ts@@ -1,6 +1,5 @@import { RESOURCE_URI_META_KEY } from '@modelcontextprotocol/ext-apps/server'-import { isCodingAgentClient } from '@/lib/client-detection'import { formatResponse } from '@/lib/response'import { POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY, POSTHOG_META_KEY } from '@/tools/types'import type { AnalyticsMetadata, WithAnalytics } from '@/ui-apps/types'@@ -19,8 +18,8 @@ export interface BuildToolResultOptions {toolName: string/** The input params passed to the tool (used to read `output_format=json` escape hatch). */params: unknown- /** The MCP `clientInfo.name` captured during `initialize`. */- clientName: string | undefined+ /** Whether formatted-result text should win over structuredContent for this client profile. */+ suppressStructuredContentForFormattedResults?: boolean | undefined/** PostHog distinctId for analytics metadata (only read when a UI resource is present). */distinctId?: string | undefined/**@@ -74,14 +73,22 @@ export function markExecPayload(payload: ToolResultPayload): ToolResultPayload {* 1. When the handler returns a primitive string, we pass it through to `formatResponse`* unchanged. Earlier, object-rest on a string exploded it into a character-indexed* dict ({"0":"{","1":"\""...}).- * 2. When `formattedResults` is present AND the client is a coding-agent- * (e.g. Claude Code) AND the caller didn't opt into JSON via `output_format=json`,- * we drop `structuredContent`. Coding agents surface `structuredContent` to the model- * in preference to `content[].text`, so keeping it would hide the formatted table+ * 2. When `formattedResults` is present AND the resolved client profile needs formatted+ * text to win AND the caller didn't opt into JSON via `output_format=json`, we drop+ * `structuredContent`. Coding agents surface `structuredContent` to the model in+ * preference to `content[].text`, so keeping it would hide the formatted table* behind raw JSON.*/export function buildToolResultPayload(opts: BuildToolResultOptions): ToolResultPayload {- const { handlerResult, toolMeta, toolName, params, clientName, distinctId, includeUiResponseMeta } = opts+ const {+ handlerResult,+ toolMeta,+ toolName,+ params,+ suppressStructuredContentForFormattedResults,+ distinctId,+ includeUiResponseMeta,+ } = optsconst isStringResult = typeof handlerResult === 'string'const formattedResults: string | undefined = isStringResult@@ -124,7 +131,7 @@ export function buildToolResultPayload(opts: BuildToolResultOptions): ToolResultconst text = formattedResults ?? (useJson ? JSON.stringify(rawResult) : formatResponse(rawResult))const suppressStructuredContent =- formattedResults !== undefined && !callerWantsJson && isCodingAgentClient(clientName)+ formattedResults !== undefined && !callerWantsJson && !!suppressStructuredContentForFormattedResultsconst payload: ToolResultPayload = {content: [{ type: 'text', text }],diff --git a/services/mcp/src/lib/client-detection.ts b/services/mcp/src/lib/client-detection.tsindex db8b03258fd9..a60a798bb4dd 100644--- a/services/mcp/src/lib/client-detection.ts+++ b/services/mcp/src/lib/client-detection.ts@@ -8,12 +8,11 @@** The `MCPClientProfile` class owns all per-client behavior decisions:*- * - `isCodingAgent()` matches coding agents that surface `structuredContent`- * to the model in preference to `content[].text`. Used to drop- * `structuredContent` when a `formatted_results` override is set, otherwise- * Claude Code (and friends) show raw JSON instead of the formatted table.- * Cursor is deliberately excluded — it reads text for the model and renders- * `structuredContent` in UI, so it does not need the workaround.+ * - `isCodingAgent()` matches coding agents that should default to single-exec+ * mode and drop `structuredContent` when a `formatted_results` override is+ * set. Cursor is deliberately excluded — it reads text for the model and+ * renders `structuredContent` in UI, so it does not need single-exec mode or+ * the formatted-results workaround.** - `isPostHogCodeConsumer()` matches the `x-posthog-mcp-consumer` header* sent by the PostHog Code Tasks wrapper.@@ -105,6 +104,10 @@ type MCPClientProfileInput = {clientVersion?: string | undefinedconsumer?: string | undefinedoauthClientName?: string | undefined+ // Per-request `x-anthropic-client` value (e.g. `ClaudeCode`, `ClaudeAI`).+ // Anthropic pools MCP transports across products, so the live inner client+ // can disagree with the session-pinned `clientName` from `initialize`.+ vendorClient?: string | undefined}export class MCPClientProfile {@@ -112,6 +115,7 @@ export class MCPClientProfile {readonly clientVersion: string | undefinedreadonly consumer: string | undefinedreadonly oauthClientName: string | undefined+ readonly vendorClient: string | undefinedprivate _capabilities: ClientCapabilities | undefined@@ -120,10 +124,11 @@ export class MCPClientProfile {this.clientVersion = input.clientVersionthis.consumer = input.consumerthis.oauthClientName = input.oauthClientName+ this.vendorClient = input.vendorClient}isCodingAgent(): boolean {- return matchesAnyFragment(this.clientName, CODING_AGENT_CLIENT_NAME_FRAGMENTS)+ return matchesAnyFragment(this.vendorClient ?? this.clientName, CODING_AGENT_CLIENT_NAME_FRAGMENTS)}isPostHogCodeConsumer(): boolean {diff --git a/services/mcp/src/lib/posthog/analytics.ts b/services/mcp/src/lib/posthog/analytics.tsindex bcb61ac2792d..d83035f287bd 100644--- a/services/mcp/src/lib/posthog/analytics.ts+++ b/services/mcp/src/lib/posthog/analytics.ts@@ -57,6 +57,9 @@ export type IdentityProvider = {getMcpClientName: () => Promise<string | undefined>getMcpClientVersion: () => Promise<string | undefined>getMcpProtocolVersion: () => Promise<string | undefined>+ // Per-request `x-anthropic-client` value. Distinct from `mcpClientName`:+ // tracks the live inner client on pooled MCP transports.+ getMcpVendorClient: () => Promise<string | undefined>getRegion: () => Promise<string | undefined>getAnalyticsContext: () => Promise<MCPAnalyticsContext | undefined>getClientUserAgent: () => Promise<string | undefined>@@ -146,6 +149,7 @@ export async function buildEventProperties(identity: IdentityProvider): Promise<mcpClientName,mcpClientVersion,mcpProtocolVersion,+ mcpVendorClient,mcpRegion,analyticsContext,oauthClientName,@@ -161,6 +165,7 @@ export async function buildEventProperties(identity: IdentityProvider): Promise<identity.getMcpClientName(),identity.getMcpClientVersion(),identity.getMcpProtocolVersion(),+ identity.getMcpVendorClient(),identity.getRegion(),identity.getAnalyticsContext(),identity.getOAuthClientName(),@@ -183,6 +188,7 @@ export async function buildEventProperties(identity: IdentityProvider): Promise<$mcp_client_user_agent: clientUserAgent,$mcp_client_name: mcpClientName,$mcp_client_version: mcpClientVersion,+ mcp_vendor_client: mcpVendorClient,$mcp_protocol_version: mcpProtocolVersion,$mcp_region: mcpRegion,$mcp_organization_id: analyticsContext?.organizationId,diff --git a/services/mcp/src/lib/request-properties.ts b/services/mcp/src/lib/request-properties.tsindex 369572a88fb1..2543c9ff7720 100644--- a/services/mcp/src/lib/request-properties.ts+++ b/services/mcp/src/lib/request-properties.ts@@ -20,6 +20,7 @@ export type RequestProperties = {mcpClientName?: string | undefinedmcpClientVersion?: string | undefinedmcpProtocolVersion?: string | undefined+ mcpVendorClient?: string | undefinedreadOnly?: boolean | undefinedmode?: McpMode | undefinedtransport?: Transport | undefined@@ -76,6 +77,7 @@ export function parseRequestProperties(mcpClientName: clientInfo.clientName,mcpClientVersion: clientInfo.clientVersion,mcpProtocolVersion: clientInfo.protocolVersion,+ mcpVendorClient: sanitizeHeaderValue(header(request, 'x-anthropic-client')),mode: parseMcpMode(header(request, 'x-posthog-mcp-mode') || params.get('mode')),transport,requestStartTime: Date.now(),diff --git a/services/mcp/src/mcp.ts b/services/mcp/src/mcp.tsindex 93cf35dbc841..1f6ff8700c96 100644--- a/services/mcp/src/mcp.ts+++ b/services/mcp/src/mcp.ts@@ -75,6 +75,10 @@ export type RequestProperties = {mcpClientName?: stringmcpClientVersion?: stringmcpProtocolVersion?: string+ // Per-request `x-anthropic-client` value. Identifies the live inner client+ // on pooled MCP transports — distinct from `mcpClientName` (session-pinned+ // from the initialize body's `clientInfo.name`).+ mcpVendorClient?: stringreadOnly?: booleanmode?: McpModetransport?: 'streamable-http' | 'sse'@@ -102,6 +106,8 @@ export class MCP extends McpAgent<Env> {mcpClientName: undefined,mcpClientVersion: undefined,mcpProtocolVersion: undefined,+ mcpConsumer: undefined,+ mcpVendorClient: undefined,}_cache: DurableObjectCache<State> | undefined@@ -392,6 +398,9 @@ export class MCP extends McpAgent<Env> {...(this.mcpClientName ? { mcp_client_name: this.mcpClientName } : {}),...(this.mcpClientVersion ? { mcp_client_version: this.mcpClientVersion } : {}),...(this.mcpProtocolVersion ? { mcp_protocol_version: this.mcpProtocolVersion } : {}),+ ...(this.requestProperties.mcpVendorClient+ ? { mcp_vendor_client: this.requestProperties.mcpVendorClient }+ : {}),...(this.requestProperties.mcpConsumer ? { mcp_consumer: this.requestProperties.mcpConsumer } : {}),...(this.requestProperties.transport ? { mcp_transport: this.requestProperties.transport } : {}),...(this.requestProperties.mcpSessionId@@ -494,7 +503,10 @@ export class MCP extends McpAgent<Env> {toolMeta: tool._meta,toolName: tool.name,params,- clientName: this.mcpClientName,+ suppressStructuredContentForFormattedResults: new MCPClientProfile({+ clientName: this.mcpClientName,+ vendorClient: this.requestProperties.mcpVendorClient,+ }).isCodingAgent(),distinctId,})} catch (error: any) {@@ -620,6 +632,7 @@ export class MCP extends McpAgent<Env> {clientVersion: this.mcpClientVersion,consumer: this.requestProperties.mcpConsumer,oauthClientName,+ vendorClient: this.requestProperties.mcpVendorClient,})const { useSingleExec, version } = this.resolveModeAndVersion({@@ -784,6 +797,7 @@ export class MCP extends McpAgent<Env> {getMcpClientName: async () => this.mcpClientName,getMcpClientVersion: async () => this.mcpClientVersion,getMcpProtocolVersion: async () => this.mcpProtocolVersion,+ getMcpVendorClient: async () => this.requestProperties.mcpVendorClient,// Prefer the cached region (set on init after detection) so we don't miss it// when the inbound request didn't include the `region` hint.getRegion: async () => (await this.cache.get('region')) ?? this.requestProperties.region,diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex 66ed4e7a265a..a02399f94a29 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -310,9 +310,9 @@ export function createExecTool(toolName: tool.name,params: useJson ? { ...input, output_format: 'json' } : input,// Consumer is the UI-apps host; keep `structuredContent` for the UI.- // Passing `undefined` bypasses the coding-agent suppression in+ // Passing `false` bypasses coding-agent suppression in// `buildToolResultPayload` because this path explicitly wants it.- clientName: undefined,+ suppressStructuredContentForFormattedResults: false,distinctId,includeUiResponseMeta: true,})diff --git a/services/mcp/src/tools/types.ts b/services/mcp/src/tools/types.tsindex 537508de5acd..a1d16338d0f0 100644--- a/services/mcp/src/tools/types.ts+++ b/services/mcp/src/tools/types.ts@@ -29,6 +29,8 @@ export type State = {mcpClientName: string | undefinedmcpClientVersion: string | undefinedmcpProtocolVersion: string | undefined+ mcpConsumer: string | undefined+ mcpVendorClient: string | undefined} & Record<PrefixedString<'session'>, SessionState> &Record<PrefixedString<'groupTypes'>, GroupType[] | undefined> &Record<PrefixedString<'groupTypesFetchedAt'>, number | undefined> &diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.tsnew file mode 100644index 000000000000..954742c518d9--- /dev/null+++ b/services/mcp/tests/hono/analytics.test.ts@@ -0,0 +1,99 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++const { mockCapture } = vi.hoisted(() => ({+ mockCapture: vi.fn(),+}))++vi.mock('@/lib/posthog', () => ({+ getPostHogClient: vi.fn(() => ({+ capture: mockCapture,+ })),+}))++import { trackInitEvent, trackToolCall } from '@/hono/analytics'+import type { ResolvedState } from '@/hono/request-state-resolver'++function makeState(overrides: Partial<ResolvedState> = {}): ResolvedState {+ return {+ reqCtx: {+ getAnalyticsContextSafe: vi.fn(async () => undefined),+ getSessionUuid: vi.fn(async () => 'session-uuid'),+ } as any,+ context: {+ stateManager: {},+ } as any,+ version: 2,+ useSingleExec: true,+ toolFeatureFlags: undefined,+ apiKeyScopes: [],+ clientProfile: {} as any,+ requestContext: {+ sessionId: 'sess-1',+ organizationId: 'org-request',+ projectId: 'project-request',+ readOnly: true,+ viaSseRedirect: true,+ requestStartTime: Date.now(),+ clientUserAgent: 'request-agent/1.0',+ mcpClientName: 'Claude Desktop',+ mcpClientVersion: '2.0',+ mcpProtocolVersion: '2025-03-26',+ transport: 'streamable-http',+ mcpSessionId: 'mcp-session-request',+ mcpConversationId: 'conversation-request',+ mcpConsumer: 'request-consumer',+ mode: 'cli',+ region: 'us',+ mcpVendorClient: 'ClaudeAI',+ },+ sessionContext: {+ mcpClientName: 'claude-code',+ mcpClientVersion: '1.0',+ mcpProtocolVersion: '2025-03-26',+ mcpConsumer: 'session-consumer',+ mcpVendorClient: 'ClaudeCode',+ },+ allTools: [],+ distinctId: 'distinct-id',+ ...overrides,+ }+}++describe('Hono MCP analytics contexts', () => {+ beforeEach(() => {+ mockCapture.mockClear()+ })++ it('emits request properties on $mcp fields and session properties on mcp_session fields', async () => {+ await trackInitEvent(makeState())++ expect(mockCapture).toHaveBeenCalledTimes(1)+ expect(mockCapture.mock.calls[0]![0].properties).toMatchObject({+ $mcp_client_name: 'Claude Desktop',+ $mcp_client_version: '2.0',+ $mcp_client_user_agent: 'request-agent/1.0',+ $mcp_protocol_version: '2025-03-26',+ $mcp_transport: 'streamable-http',+ $mcp_session_id: 'mcp-session-request',+ $mcp_conversation_id: 'conversation-request',+ $mcp_consumer: 'request-consumer',+ $mcp_mode: 'cli',+ $mcp_region: 'us',+ mcp_vendor_client: 'ClaudeAI',+ mcp_session_client_name: 'claude-code',+ mcp_session_client_version: '1.0',+ mcp_session_protocol_version: '2025-03-26',+ mcp_session_consumer: 'session-consumer',+ mcp_session_vendor_client: 'ClaudeCode',+ })+ })++ it('omits session properties when there is no MCP session context', async () => {+ await trackToolCall('user-get', 12, false, makeState({ sessionContext: null }))++ const properties = mockCapture.mock.calls[0]![0].properties+ expect(properties.$mcp_client_name).toBe('Claude Desktop')+ expect(properties.mcp_session_client_name).toBeUndefined()+ expect(properties.mcp_session_vendor_client).toBeUndefined()+ })+})diff --git a/services/mcp/tests/hono/request-context.test.ts b/services/mcp/tests/hono/request-context.test.tsindex 7533eab793df..37280ed0859a 100644--- a/services/mcp/tests/hono/request-context.test.ts+++ b/services/mcp/tests/hono/request-context.test.ts@@ -36,6 +36,16 @@ function fakeRedis(): RedisLike {}}+function spyRedis(): RedisLike {+ return {+ get: vi.fn(async () => null),+ set: vi.fn(async () => 'OK'),+ del: vi.fn(async () => 0),+ scan: vi.fn(async () => ['0', []] as [string, string[]]),+ ...makeRedisRateLimitStubs(),+ }+}+const env = {} as anyfunction makeProps(overrides: Partial<RequestProperties> = {}): RequestProperties {@@ -149,6 +159,52 @@ describe('RequestContext', () => {})})+ it('adds stable session properties without replacing request properties', () => {+ const ctx = new RequestContext(+ fakeRedis(),+ env,+ makeProps({+ mcpClientName: 'Claude Desktop',+ mcpClientVersion: '2.0',+ mcpProtocolVersion: '2025-03-26',+ mcpConsumer: 'request-consumer',+ mcpVendorClient: 'ClaudeAI',+ transport: 'streamable-http',+ })+ )+ ctx.setMcpContexts(+ {+ sessionId: 'sess-1',+ mcpClientName: 'Claude Desktop',+ mcpClientVersion: '2.0',+ mcpProtocolVersion: '2025-03-26',+ mcpConsumer: 'request-consumer',+ mcpVendorClient: 'ClaudeAI',+ transport: 'streamable-http',+ mode: 'cli',+ },+ {+ mcpClientName: 'claude-code',+ mcpClientVersion: '1.0',+ mcpProtocolVersion: '2025-03-26',+ mcpConsumer: 'session-consumer',+ mcpVendorClient: 'ClaudeCode',+ }+ )++ const result = ctx.buildClientProperties()+ expect(result).toMatchObject({+ $mcp_client_name: 'Claude Desktop',+ $mcp_client_version: '2.0',+ $mcp_consumer: 'request-consumer',+ mcp_vendor_client: 'ClaudeAI',+ mcp_session_client_name: 'claude-code',+ mcp_session_client_version: '1.0',+ mcp_session_consumer: 'session-consumer',+ mcp_session_vendor_client: 'ClaudeCode',+ })+ })+it('omits undefined properties', () => {const ctx = new RequestContext(fakeRedis(),@@ -186,5 +242,33 @@ describe('RequestContext', () => {const ctx = new RequestContext(fakeRedis(), env, makeProps())expect(ctx.cache).toBe(ctx.cache)})++ it('keeps MCP session cache entries on the default 7 day TTL', async () => {+ const redis = spyRedis()+ const ctx = new RequestContext(redis, env, makeProps({ mcpSessionId: 'mcp-session-1' }))++ await ctx.sessionCache.set('mcpClientName', 'claude-code')++ expect(redis.set).toHaveBeenCalledWith(+ expect.stringMatching(/^mcp:session:/),+ JSON.stringify('claude-code'),+ 'EX',+ 7 * 24 * 60 * 60+ )+ })++ it('keeps token cache entries on the default 7 day TTL', async () => {+ const redis = spyRedis()+ const ctx = new RequestContext(redis, env, makeProps())++ await ctx.tokenCache.set('distinctId', 'user-123')++ expect(redis.set).toHaveBeenCalledWith(+ 'mcp:token:test-user:distinctId',+ JSON.stringify('user-123'),+ 'EX',+ 7 * 24 * 60 * 60+ )+ })})})diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.tsnew file mode 100644index 000000000000..cbad64b66530--- /dev/null+++ b/services/mcp/tests/hono/request-state-resolver.test.ts@@ -0,0 +1,248 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++const { mockSessionStore, mockTokenStore } = vi.hoisted(() => ({+ mockSessionStore: new Map<string, unknown>(),+ mockTokenStore: new Map<string, unknown>(),+}))++vi.mock('@/lib/posthog/flags', () => ({+ evaluateFeatureFlags: vi.fn(async () => ({})),+}))++vi.mock('@/hono/request-context', () => {+ type MockCache = {+ get: (key: string) => Promise<unknown>+ set: (key: string, value: unknown) => Promise<void>+ setMany: (entries: Record<string, unknown>) => Promise<void>+ delete: (key: string) => Promise<void>+ clear: () => Promise<void>+ }++ const makeCache = (store: Map<string, unknown>): MockCache => ({+ get: vi.fn(async (key: string) => store.get(key)),+ set: vi.fn(async (key: string, value: unknown) => {+ store.set(key, value)+ }),+ setMany: vi.fn(async (entries: Record<string, unknown>) => {+ for (const [key, value] of Object.entries(entries)) {+ if (value !== undefined) {+ store.set(key, value)+ }+ }+ }),+ delete: vi.fn(async (key: string) => {+ store.delete(key)+ }),+ clear: vi.fn(async () => {+ store.clear()+ }),+ })++ return {+ RequestContext: vi.fn().mockImplementation((_redis, _env, props: { mcpSessionId?: string } = {}) => {+ const sessionCache = makeCache(mockSessionStore)+ return {+ tokenCache: makeCache(mockTokenStore),+ get sessionCache() {+ if (!props.mcpSessionId) {+ throw new Error('Session ID is required to use the session cache')+ }+ return sessionCache+ },+ getContext: vi.fn(async () => ({+ stateManager: {+ setDefaultOrganizationAndProject: vi.fn(async () => {}),+ getApiKey: vi.fn(async () => ({ scopes: ['*'], scoped_teams: [] })),+ getAiConsentGiven: vi.fn(async () => undefined),+ },+ })),+ getAnalyticsContextSafe: vi.fn(async () => undefined),+ getDistinctId: vi.fn(async () => 'distinct-id'),+ setMcpContexts: vi.fn(),+ }+ }),+ }+})++import type { RedisLike } from '@/hono/cache/RedisCache'+import { RequestStateResolver } from '@/hono/request-state-resolver'+import type { RequestProperties } from '@/lib/request-properties'+import type { Env } from '@/tools/types'++function makeProps(overrides: Partial<RequestProperties> = {}): RequestProperties {+ return {+ apiToken: 'phx_test',+ userHash: 'test-user',+ mcpSessionId: 'mcp-session-1',+ mcpClientName: 'claude-code',+ mcpClientVersion: '1.0',+ mcpProtocolVersion: '2025-03-26',+ projectId: '1',+ requestStartTime: Date.now(),+ transport: 'streamable-http',+ version: 1,+ ...overrides,+ }+}++function makeResolver(): RequestStateResolver {+ const catalog = {+ getFilteredTools: vi.fn(() => []),+ }+ return new RequestStateResolver(catalog as any, {} as RedisLike, {} as Env)+}++describe('RequestStateResolver MCP client contexts', () => {+ beforeEach(() => {+ mockSessionStore.clear()+ mockTokenStore.clear()+ })++ it('stores client props, but not resolved mode, for a new MCP session', async () => {+ const props = makeProps()+ const result = await makeResolver().resolve(props)++ expect(result.useSingleExec).toBe(true)+ expect(props.mode).toBe('cli')+ expect(result.requestContext).toMatchObject({+ mcpClientName: 'claude-code',+ mcpClientVersion: '1.0',+ mcpProtocolVersion: '2025-03-26',+ mode: 'cli',+ })+ expect(result.sessionContext).toMatchObject({+ mcpClientName: 'claude-code',+ mcpClientVersion: '1.0',+ mcpProtocolVersion: '2025-03-26',+ })+ expect(mockSessionStore.get('mcpClientName')).toBe('claude-code')+ expect(mockSessionStore.get('mcpClientVersion')).toBe('1.0')+ expect(mockSessionStore.get('mcpProtocolVersion')).toBe('2025-03-26')+ expect(mockSessionStore.get('mcpMode')).toBeUndefined()+ })++ it('does not store mode for a new MCP session when the mode was explicit', async () => {+ const props = makeProps({ mode: 'tools' })+ const result = await makeResolver().resolve(props)++ expect(result.useSingleExec).toBe(false)+ expect(props.mode).toBe('tools')+ expect(result.requestContext.mode).toBe('tools')+ expect(mockSessionStore.get('mcpMode')).toBeUndefined()+ })++ it('uses cached session client props when request client detection would resolve differently', async () => {+ await makeResolver().resolve(makeProps())++ const props = makeProps({ mcpClientName: 'Claude Desktop' })+ const result = await makeResolver().resolve(props)++ expect(result.useSingleExec).toBe(true)+ expect(props.mode).toBe('cli')+ expect(props.mcpClientName).toBe('Claude Desktop')+ expect(result.requestContext.mcpClientName).toBe('Claude Desktop')+ expect(result.sessionContext?.mcpClientName).toBe('claude-code')+ expect(result.clientProfile.clientName).toBe('claude-code')+ expect(result.clientProfile.isCodingAgent()).toBe(true)+ })++ it('uses cached session client props for instruction capabilities without overwriting request props', async () => {+ await makeResolver().resolve(makeProps({ mcpClientName: 'codex' }))++ const props = makeProps({ mcpClientName: 'Claude Desktop' })+ const result = await makeResolver().resolve(props)++ expect(props.mcpClientName).toBe('Claude Desktop')+ expect(result.requestContext.mcpClientName).toBe('Claude Desktop')+ expect(result.sessionContext?.mcpClientName).toBe('codex')+ expect(result.clientProfile.clientName).toBe('codex')+ expect(result.clientProfile.capabilities.supportsInstructions).toBe(false)+ })++ it('uses explicit mode when cached session client props would resolve differently', async () => {+ await makeResolver().resolve(makeProps())++ const props = makeProps({ mode: 'tools' })+ const result = await makeResolver().resolve(props)++ expect(result.useSingleExec).toBe(false)+ expect(props.mode).toBe('tools')+ })++ it('does not pin mode without an MCP session ID', async () => {+ const props = makeProps({ mcpSessionId: undefined })+ const result = await makeResolver().resolve(props)++ expect(props.mode).toBe('cli')+ expect(result.sessionContext).toBeNull()+ expect(result.requestContext.mcpClientName).toBe('claude-code')+ expect(mockSessionStore.get('mcpMode')).toBeUndefined()+ })++ it('uses cached vendor client when the live vendor header would resolve differently', async () => {+ await makeResolver().resolve(+ makeProps({+ mcpClientName: 'Anthropic/ClaudeAI',+ mcpVendorClient: 'ClaudeCode',+ })+ )+ expect(mockSessionStore.get('mcpVendorClient')).toBe('ClaudeCode')++ const pooled = makeProps({+ mcpClientName: 'Anthropic/ClaudeAI',+ mcpVendorClient: 'ClaudeAI',+ })+ const result = await makeResolver().resolve(pooled)++ expect(result.useSingleExec).toBe(true)+ expect(pooled.mode).toBe('cli')+ expect(pooled.mcpVendorClient).toBe('ClaudeAI')+ expect(result.requestContext.mcpVendorClient).toBe('ClaudeAI')+ expect(result.sessionContext?.mcpVendorClient).toBe('ClaudeCode')+ expect(result.clientProfile.vendorClient).toBe('ClaudeCode')+ })++ it('captures vendor client from a later request when initialize omitted the header', async () => {+ await makeResolver().resolve(+ makeProps({+ mcpClientName: 'Anthropic/ClaudeAI',+ mcpVendorClient: undefined,+ })+ )+ expect(mockSessionStore.get('mcpVendorClient')).toBeUndefined()++ const pooled = makeProps({+ mcpClientName: 'Anthropic/ClaudeAI',+ mcpVendorClient: 'ClaudeCode',+ })+ const result = await makeResolver().resolve(pooled)++ expect(result.useSingleExec).toBe(true)+ expect(pooled.mode).toBe('cli')+ expect(result.requestContext.mcpVendorClient).toBe('ClaudeCode')+ expect(result.sessionContext?.mcpVendorClient).toBe('ClaudeCode')+ expect(mockSessionStore.get('mcpVendorClient')).toBe('ClaudeCode')+ })++ it('captures consumer from a later request when initialize omitted the header', async () => {+ await makeResolver().resolve(+ makeProps({+ mcpClientName: 'Claude Desktop',+ mcpConsumer: undefined,+ })+ )+ expect(mockSessionStore.get('mcpConsumer')).toBeUndefined()++ const posthogCode = makeProps({+ mcpClientName: 'Claude Desktop',+ mcpConsumer: 'posthog-code',+ })+ const result = await makeResolver().resolve(posthogCode)++ expect(result.useSingleExec).toBe(true)+ expect(posthogCode.mode).toBe('cli')+ expect(result.requestContext.mcpConsumer).toBe('posthog-code')+ expect(result.sessionContext?.mcpConsumer).toBe('posthog-code')+ expect(mockSessionStore.get('mcpConsumer')).toBe('posthog-code')+ })+})diff --git a/services/mcp/tests/hono/session-mode-pool.test.ts b/services/mcp/tests/hono/session-mode-pool.test.tsnew file mode 100644index 000000000000..faac1eea40c9--- /dev/null+++ b/services/mcp/tests/hono/session-mode-pool.test.ts@@ -0,0 +1,173 @@+// Verifies the connection-pooling scenario observed in production: Anthropic+// reuses a single `Mcp-Session-Id` across multiple inner clients (Claude+// Code, Claude.ai, Cowork) and differentiates them via the per-request+// `x-anthropic-client` header. The server caches the initial raw session+// identity hints and derives mode from those cached-first hints; a later+// `tools/call` carrying a different vendor must NOT flip the resolved+// mode/version.+//+// To probe the resolved mode DIRECTLY via a `tools/call` (the user flow+// under test) we exploit tools that are gated by `mcpVersion` in the catalog.+// The state resolver filters `state.allTools` by the resolved `version`+// (`tool-catalog.ts:161-163`), and `handleToolCall` returns the guard+// "Tool <name> not found" (`tool-executor.ts:78-80`) when the requested+// tool is absent from `state.allTools`.+//+// cli mode pins `version=2`. A v2-only tool (e.g. `query-session-recordings-list`)+// is present iff this request resolved to v2; a v1-only tool+// (e.g. `accounts-list`) is absent iff this request resolved to v2.+//+// If cli mode survives the vendor flip on the pooled session, calling the+// v2-only tool dispatches (any non-"not found" response) and calling the+// v1-only tool returns the missing-tool guard. If mode flipped to v1, both+// outcomes reverse. That's a direct observable for "the resolved mode at+// headers_2 equals the resolved mode at headers_1".+import { Client } from '@modelcontextprotocol/sdk/client/index.js'+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'+import { setupServer } from 'msw/node'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'++import { createApp } from '@/hono/app'+import type { RedisLike } from '@/hono/cache/RedisCache'++import { contextMillHandler, handlers } from '../workers/fixtures/handlers'+import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'++const mswServer = setupServer(...handlers, contextMillHandler)++function createInMemoryRedis(): RedisLike & { ping(): Promise<string> } {+ const store = new Map<string, string>()+ return {+ get: async (key) => store.get(key) ?? null,+ set: async (key, value) => {+ store.set(key, String(value))+ return 'OK'+ },+ del: async (...keys) => {+ let removed = 0+ for (const key of keys) {+ if (store.delete(key)) {+ removed+++ }+ }+ return removed+ },+ scan: async (cursor) => {+ const cur = String(cursor)+ return [cur === '0' ? 'next' : '0', cur === '0' ? Array.from(store.keys()) : []] as [string, string[]]+ },+ ...makeRedisRateLimitStubs(),+ ping: async () => 'PONG',+ }+}++let app: ReturnType<typeof createApp>['app']+const TOKEN = 'phx_session_mode_pool_test'+const BASE_URL = new URL('http://hono.test')++// Tools chosen as version-specific probes (see file header for rationale).+const V1_ONLY_TOOL = 'accounts-list'+const V2_ONLY_TOOL = 'query-session-recordings-list'++beforeAll(async () => {+ process.env.TEST = '1'+ process.env.MCP_APPS_BASE_URL = 'https://apps.test'+ mswServer.listen({ onUnhandledRequest: 'bypass' })+ const created = createApp(createInMemoryRedis())+ app = created.app+ await created.warmup()+})++afterAll(() => {+ mswServer.close()+})++const fetchViaApp: typeof fetch = async (input, init) => {+ const url = input instanceof URL ? input : new URL(typeof input === 'string' ? input : input.url)+ return app.request(url.pathname + url.search, init ?? {})+}++type ConnectableTransport = Parameters<Client['connect']>[0]++interface ToolCallResponse {+ result?: { content?: Array<{ type: string; text: string }>; isError?: boolean }+}++async function callToolOnSession(sessionId: string, vendorClient: string, toolName: string): Promise<ToolCallResponse> {+ const res = await fetchViaApp(new URL('/mcp', BASE_URL), {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${TOKEN}`,+ 'Content-Type': 'application/json',+ Accept: 'application/json, text/event-stream',+ 'Mcp-Session-Id': sessionId,+ 'x-anthropic-client': vendorClient,+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 'pool-tools-call',+ method: 'tools/call',+ params: { name: toolName, arguments: {} },+ }),+ })+ expect(res.status).toBe(200)+ return (await res.json()) as ToolCallResponse+}++function firstText(resp: ToolCallResponse): string {+ return resp.result?.content?.[0]?.text ?? ''+}++describe('Resolved mode is preserved across pooled-transport vendor flips', () => {+ it('cli init via x-anthropic-client survives a non-coding-agent vendor on the same session', async () => {+ // headers_1 — clientInfo.name is the new Claude Desktop-style vendor-prefixed+ // shape (NOT a coding-agent fragment), while the per-request vendor header+ // identifies the inner client as Claude Code. This is the production-pool+ // scenario where the body identifies the transport-owner and the header+ // identifies the live consumer.+ //+ // Without reading the vendor header, the resolver picks tools mode at+ // init (because `Anthropic/ClaudeAI` doesn't match any coding-agent+ // fragment) and the SDK gets the full multi-tool roster. With vendor+ // reading + cached session hints, the resolver picks cli mode at init+ // and the SDK gets the wrapped `[exec]` roster.+ const transportA = new StreamableHTTPClientTransport(new URL('/mcp', BASE_URL), {+ fetch: fetchViaApp,+ requestInit: {+ headers: {+ Authorization: `Bearer ${TOKEN}`,+ 'x-anthropic-client': 'ClaudeCode',+ },+ },+ })+ const clientA = new Client({ name: 'Anthropic/ClaudeAI', version: '1.0.0' }, { capabilities: {} })+ await clientA.connect(transportA as ConnectableTransport)++ const sessionId = transportA.sessionId+ expect(sessionId).toBeTruthy()++ // Client caches the tools payload at init. cli mode collapses the wire+ // roster to a single `exec`.+ const cachedTools = await clientA.listTools()+ expect(cachedTools.tools).toHaveLength(1)+ expect(cachedTools.tools[0]!.name).toBe('exec')++ // headers_2 — pool member with a non-coding-agent vendor. If the+ // resolver re-derives mode from the live request, `vendorClient='ClaudeAI'`+ // + cached `clientName='Anthropic/ClaudeAI'` both miss the coding-agent+ // fragments -> resolves to tools mode (v1) -> the v2-only tool falls out+ // of `state.allTools` and the dispatcher returns "not found". With the+ // initial vendor hint cached, the request stays at v2 and the v2-only+ // tool dispatches.+ const probe = await callToolOnSession(sessionId!, 'ClaudeAI', V2_ONLY_TOOL)+ expect(firstText(probe)).not.toMatch(new RegExp(`Tool ${V2_ONLY_TOOL} not found`, 'i'))++ // Symmetric negative probe: a v1-only tool must STILL be absent under+ // the preserved cli/v2 mode.+ const negative = await callToolOnSession(sessionId!, 'ClaudeAI', V1_ONLY_TOOL)+ expect(negative.result?.isError).toBe(true)+ expect(firstText(negative)).toMatch(new RegExp(`Tool ${V1_ONLY_TOOL} not found`, 'i'))++ await clientA.close()+ })+})diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.tsindex 85182879dcfd..f6c6e59214ff 100644--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts@@ -36,25 +36,10 @@ vi.mock('@/resources', () => ({import { z } from 'zod'+import { InstructionsBuilder } from '@/hono/instructions'import type { ResolvedState } from '@/hono/request-state-resolver'import { ToolCatalog } from '@/hono/tool-catalog'import { ToolExecutor } from '@/hono/tool-executor'-import { InstructionsBuilder } from '@/hono/instructions'-import type { RequestProperties } from '@/lib/request-properties'--function makeProps(overrides: Partial<RequestProperties> = {}): RequestProperties {- return {- userHash: 'test-user',- apiToken: 'phx_test',- sessionId: 'sess-1',- mcpClientName: 'test',- mcpClientVersion: '1.0',- mcpProtocolVersion: '2025-03-26',- transport: 'streamable-http',- requestStartTime: Date.now(),- ...overrides,- }-}function makeState(tools: { name: string }[], overrides: Partial<ResolvedState> = {}): ResolvedState {return {@@ -78,7 +63,18 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>useSingleExec: false,toolFeatureFlags: undefined,apiKeyScopes: [],- clientProfile: { capabilities: { supportsInstructions: true } } as any,+ clientProfile: {+ capabilities: { supportsInstructions: true },+ isCodingAgent: vi.fn(() => false),+ } as any,+ requestContext: {+ sessionId: 'sess-1',+ mcpClientName: 'test',+ mcpClientVersion: '1.0',+ mcpProtocolVersion: '2025-03-26',+ transport: 'streamable-http',+ },+ sessionContext: null,allTools: tools as any,distinctId: 'test-distinct-id',...overrides,@@ -125,11 +121,7 @@ describe('ToolExecutor metrics', () => {it('records success counter and duration timer', async () => {vi.spyOn(catalog, 'getToolByName').mockReturnValue(makeFakeTool('my-tool') as any)- await executor.handleToolCall(- { name: 'my-tool', arguments: {} },- makeProps(),- makeState([{ name: 'my-tool' }])- )+ await executor.handleToolCall({ name: 'my-tool', arguments: {} }, makeState([{ name: 'my-tool' }]))expect(mockToolDurationStartTimer).toHaveBeenCalledWith({ tool: 'my-tool' })expect(mockToolCallsInc).toHaveBeenCalledWith({ tool: 'my-tool', status: 'success' })@@ -143,11 +135,7 @@ describe('ToolExecutor metrics', () => {}) as any)- await executor.handleToolCall(- { name: 'fail-tool', arguments: {} },- makeProps(),- makeState([{ name: 'fail-tool' }])- )+ await executor.handleToolCall({ name: 'fail-tool', arguments: {} }, makeState([{ name: 'fail-tool' }]))expect(mockToolCallsInc).toHaveBeenCalledWith({ tool: 'fail-tool', status: 'error' })expect(mockToolErrorsInc).toHaveBeenCalledWith({ tool: 'fail-tool', error_type: 'internal' })@@ -160,18 +148,14 @@ describe('ToolExecutor metrics', () => {base: { schema: z.object({ required_field: z.string() }), handler: vi.fn(), _meta: undefined },} as any)- await executor.handleToolCall(- { name: 'strict-tool', arguments: {} },- makeProps(),- makeState([{ name: 'strict-tool' }])- )+ await executor.handleToolCall({ name: 'strict-tool', arguments: {} }, makeState([{ name: 'strict-tool' }]))expect(mockToolCallsInc).toHaveBeenCalledWith({ tool: 'strict-tool', status: 'validation_error' })expect(mockToolDurationStartTimer).not.toHaveBeenCalled()})it('records error for unknown tool', async () => {- await executor.handleToolCall({ name: 'nonexistent', arguments: {} }, makeProps(), makeState([]))+ await executor.handleToolCall({ name: 'nonexistent', arguments: {} }, makeState([]))expect(mockToolCallsInc).toHaveBeenCalledWith({ tool: 'nonexistent', status: 'error' })})@@ -186,7 +170,7 @@ describe('ToolExecutor metrics', () => {}it('emits no exec-labelled counter or timer on success', async () => {- await executor.handleToolCall({ name: 'exec', arguments: { command: 'tools' } }, makeProps(), execState())+ await executor.handleToolCall({ name: 'exec', arguments: { command: 'tools' } }, execState())expect(callsFor(mockToolCallsInc, 'exec')).toHaveLength(0)expect(callsFor(mockToolDurationStartTimer, 'exec')).toHaveLength(0)@@ -195,7 +179,6 @@ describe('ToolExecutor metrics', () => {it('emits inner tool name for counter and duration on inner tool call', async () => {await executor.handleToolCall({ name: 'exec', arguments: { command: 'call docs-search {"query": "test"}' } },- makeProps(),execState())@@ -212,7 +195,6 @@ describe('ToolExecutor metrics', () => {it('classifies inner tool errors under the inner tool name, not exec', async () => {await executor.handleToolCall({ name: 'exec', arguments: { command: 'call docs-search {"query": "test"}' } },- makeProps(),execState())@@ -227,7 +209,6 @@ describe('ToolExecutor metrics', () => {it('emits exec-level error for framework failures before inner dispatch', async () => {await executor.handleToolCall({ name: 'exec', arguments: { command: 'call nonexistent-tool-xyz {}' } },- makeProps(),execState())diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.tsindex 070ee0122a30..80f11f0cf163 100644--- a/services/mcp/tests/hono/tool-executor.test.ts+++ b/services/mcp/tests/hono/tool-executor.test.ts@@ -11,26 +11,10 @@ vi.mock('@/resources', () => ({getPromptsFromManifest: vi.fn().mockResolvedValue([]),}))-import type { RequestProperties } from '@/lib/request-properties'+import { InstructionsBuilder } from '@/hono/instructions'import type { ResolvedState } from '@/hono/request-state-resolver'import { ToolCatalog } from '@/hono/tool-catalog'import { ToolExecutor } from '@/hono/tool-executor'-import { InstructionsBuilder } from '@/hono/instructions'-import type {} from '@/tools/types'--function makeProps(overrides: Partial<RequestProperties> = {}): RequestProperties {- return {- userHash: 'test-user',- apiToken: 'phx_test',- sessionId: 'sess-1',- mcpClientName: 'test',- mcpClientVersion: '1.0',- mcpProtocolVersion: '2025-03-26',- transport: 'streamable-http',- requestStartTime: Date.now(),- ...overrides,- }-}function makeState(tools: { name: string }[], overrides: Partial<ResolvedState> = {}): ResolvedState {return {@@ -53,7 +37,18 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>useSingleExec: false,toolFeatureFlags: undefined,apiKeyScopes: [],- clientProfile: { capabilities: { supportsInstructions: true } } as any,+ clientProfile: {+ capabilities: { supportsInstructions: true },+ isCodingAgent: vi.fn(() => false),+ } as any,+ requestContext: {+ sessionId: 'sess-1',+ mcpClientName: 'test',+ mcpClientVersion: '1.0',+ mcpProtocolVersion: '2025-03-26',+ transport: 'streamable-http',+ },+ sessionContext: null,allTools: tools as any,distinctId: 'test-distinct-id',...overrides,@@ -72,7 +67,7 @@ describe('ToolExecutor', () => {describe('handleToolCall', () => {it('returns error when tool name is missing', async () => {- const result = (await executor.handleToolCall({}, makeProps(), makeState([]))) as any+ const result = (await executor.handleToolCall({}, makeState([]))) as anyexpect(result.isError).toBe(true)expect(result.content[0].text).toContain('Missing tool name')})@@ -80,7 +75,6 @@ describe('ToolExecutor', () => {it('returns error when tool does not exist', async () => {const result = (await executor.handleToolCall({ name: 'nonexistent-tool', arguments: {} },- makeProps(),makeState([]))) as anyexpect(result.isError).toBe(true)@@ -92,11 +86,7 @@ describe('ToolExecutor', () => {const entries = catalog.getPreBuiltEntries()const tool = entries[0]!- const result = (await executor.handleToolCall(- { name: tool.name, arguments: {} },- makeProps(),- makeState([])- )) as any+ const result = (await executor.handleToolCall({ name: tool.name, arguments: {} }, makeState([]))) as anyexpect(result.isError).toBe(true)expect(result.content[0].text).toContain('not found')})@@ -109,7 +99,6 @@ describe('ToolExecutor', () => {const result = (await executor.handleToolCall({ name: knownTool.name, arguments: { __invalid_field_xyz: 'bad' } },- makeProps(),makeState([{ name: knownTool.name }]))) as any@@ -125,13 +114,29 @@ describe('ToolExecutor', () => {const result = (await executor.handleToolCall({ name: 'user-get', arguments: {} },- makeProps(),makeState([{ name: 'user-get' }]))) as anyexpect(result).not.toBeNull()expect(result.content).not.toBeNull()})++ it('accepts cached exec calls even when the current session is in tools mode', async () => {+ const filteredTools = catalog+ .getFilteredTools({ version: 2, scopes: ['*'] })+ .filter((tool) => tool.name === 'execute-sql' || tool.name === 'organization-get')++ const result = (await executor.handleToolCall(+ { name: 'exec', arguments: { command: 'tools' } },+ makeState(filteredTools, { useSingleExec: false, version: 2 })+ )) as any++ expect(result.isError).toBeFalsy()+ const text = result.content?.[0]?.text ?? ''+ expect(text).toContain('execute-sql')+ expect(text).toContain('organization-get')+ expect(text).not.toContain('feature-flag-get-all')+ })})describe('handleToolsList', () => {@@ -139,14 +144,14 @@ describe('ToolExecutor', () => {const allEntries = catalog.getPreBuiltEntries()const subset = allEntries.slice(0, 3)- const result = await executor.handleToolsList(makeState(subset.map((e) => ({ name: e.name }))), makeProps())+ const result = await executor.handleToolsList(makeState(subset.map((e) => ({ name: e.name }))))expect(result.tools).toHaveLength(3)expect(result.tools.map((t) => t.name)).toEqual(subset.map((e) => e.name))})it('returns empty list when allTools is empty', async () => {- const result = await executor.handleToolsList(makeState([]), makeProps())+ const result = await executor.handleToolsList(makeState([]))expect(result.tools).toEqual([])})@@ -159,7 +164,7 @@ describe('ToolExecutor', () => {{ useSingleExec: true, version: 2 })- const result = await executor.handleToolsList(state, makeProps())+ const result = await executor.handleToolsList(state)expect(result.tools).toHaveLength(1)expect(result.tools[0]!.name).toBe('exec')})diff --git a/services/mcp/tests/unit/build-tool-result.test.ts b/services/mcp/tests/unit/build-tool-result.test.tsindex 877c7aa4e1a6..a045a2bf487c 100644--- a/services/mcp/tests/unit/build-tool-result.test.ts+++ b/services/mcp/tests/unit/build-tool-result.test.ts@@ -54,7 +54,7 @@ describe('buildToolResultPayload — query-trends for Claude Code', () => {toolMeta: queryTrendsToolMeta,toolName: 'query-trends',params: { series: [{ event: '$pageview', kind: 'EventsNode' }] },- clientName: 'claude-code',+ suppressStructuredContentForFormattedResults: true,distinctId: 'test-distinct-id',})@@ -65,40 +65,13 @@ describe('buildToolResultPayload — query-trends for Claude Code', () => {expect(payload).not.toHaveProperty('structuredContent')})- it.each([- ['claude-code'],- ['Claude Code'], // whitespace variant — normalizer strips it- ['claude-code-cli'],- ['claude-code/1.2.3'],- ['cline'],- ['cline-bot'],- ['continue'],- ['codex'],- ['windsurf'],- ['zed'],- ['aider'],- ['github.copilot'],- ])('suppresses structuredContent for coding agent %s', (clientName) => {+ it('keeps structuredContent when suppression is false', () => {const payload = buildToolResultPayload({handlerResult: queryTrendsHandlerResult(),toolMeta: queryTrendsToolMeta,toolName: 'query-trends',params: {},- clientName,- distinctId: 'd',- })-- expect(payload.content[0]!.text).toBe(FORMATTED_TABLE)- expect(payload).not.toHaveProperty('structuredContent')- })-- it('keeps structuredContent for Cursor (it reads text for the model, structured for UI)', () => {- const payload = buildToolResultPayload({- handlerResult: queryTrendsHandlerResult(),- toolMeta: queryTrendsToolMeta,- toolName: 'query-trends',- params: {},- clientName: 'cursor',+ suppressStructuredContentForFormattedResults: false,distinctId: 'test-distinct-id',})@@ -112,22 +85,18 @@ describe('buildToolResultPayload — query-trends for Claude Code', () => {expect(payload.structuredContent).not.toHaveProperty(POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY)})- it.each([['Claude Desktop'], ['claude-desktop'], ['mcp-inspector'], [undefined]])(- 'keeps structuredContent for non-coding client %s',- (clientName) => {- const payload = buildToolResultPayload({- handlerResult: queryTrendsHandlerResult(),- toolMeta: queryTrendsToolMeta,- toolName: 'query-trends',- params: {},- clientName,- distinctId: 'd',- })+ it('keeps structuredContent when suppression is omitted', () => {+ const payload = buildToolResultPayload({+ handlerResult: queryTrendsHandlerResult(),+ toolMeta: queryTrendsToolMeta,+ toolName: 'query-trends',+ params: {},+ distinctId: 'd',+ })- expect(payload.content[0]!.text).toBe(FORMATTED_TABLE)- expect(payload.structuredContent).not.toBeUndefined()- }- )+ expect(payload.content[0]!.text).toBe(FORMATTED_TABLE)+ expect(payload.structuredContent).not.toBeUndefined()+ })it('keeps structuredContent when caller explicitly passes output_format=json (even on claude-code)', () => {const payload = buildToolResultPayload({@@ -135,7 +104,7 @@ describe('buildToolResultPayload — query-trends for Claude Code', () => {toolMeta: queryTrendsToolMeta,toolName: 'query-trends',params: { output_format: 'json' },- clientName: 'claude-code',+ suppressStructuredContentForFormattedResults: true,distinctId: 'd',})@@ -158,7 +127,7 @@ describe('buildToolResultPayload — query-trends for Claude Code', () => {toolMeta: queryTrendsToolMeta,toolName: 'query-trends',params: {},- clientName: 'claude-code',+ suppressStructuredContentForFormattedResults: true,distinctId: 'd',})@@ -174,7 +143,7 @@ describe('buildToolResultPayload — query-trends for Claude Code', () => {toolMeta: queryTrendsToolMeta,toolName: 'query-trends',params: {},- clientName: 'claude-desktop',+ suppressStructuredContentForFormattedResults: false,distinctId: 'user-abc-123',})@@ -194,7 +163,7 @@ describe('buildToolResultPayload — query-trends for Claude Code', () => {toolMeta: undefined,toolName: 'whatever',params: {},- clientName: 'cursor',+ suppressStructuredContentForFormattedResults: false,distinctId: 'd',})@@ -214,7 +183,7 @@ describe('buildToolResultPayload — non-query use cases', () => {toolMeta: undefined,toolName: 'execute-sql',params: {},- clientName: 'claude-code',+ suppressStructuredContentForFormattedResults: true,distinctId: undefined,})@@ -231,7 +200,7 @@ describe('buildToolResultPayload — non-query use cases', () => {toolMeta: { [POSTHOG_META_KEY]: { outputFormat: 'json' } },toolName: 'query-llm-traces-list',params: {},- clientName: 'claude-code',+ suppressStructuredContentForFormattedResults: true,distinctId: undefined,})diff --git a/services/mcp/tests/unit/client-detection.test.ts b/services/mcp/tests/unit/client-detection.test.tsindex 8e4daade6941..a5a98cc85893 100644--- a/services/mcp/tests/unit/client-detection.test.ts+++ b/services/mcp/tests/unit/client-detection.test.ts@@ -149,14 +149,27 @@ describe('isVibeCodingClient', () => {describe('MCPClientProfile', () => {describe('isCodingAgent()', () => {- it.each([['claude-code'], ['Codex CLI'], ['cline'], ['zed-editor'], ['GitHub Copilot Chat']])(- 'returns true for %s',- (clientName) => {- expect(new MCPClientProfile({ clientName }).isCodingAgent()).toBe(true)- }- )+ it.each([+ ['claude-code'],+ ['Claude Code'],+ ['claude-code-cli'],+ ['claude-code/1.2.3'],+ ['cline'],+ ['cline-bot'],+ ['continue'],+ ['codex'],+ ['Codex CLI'],+ ['windsurf'],+ ['zed'],+ ['zed-editor'],+ ['aider'],+ ['github.copilot'],+ ['GitHub Copilot Chat'],+ ])('returns true for %s', (clientName) => {+ expect(new MCPClientProfile({ clientName }).isCodingAgent()).toBe(true)+ })- it.each([['Claude Desktop'], ['cursor'], ['mcp-inspector'], [''], [' ']])(+ it.each([['Claude Desktop'], ['claude-desktop'], ['cursor'], ['mcp-inspector'], [''], [' ']])('returns false for %s',(clientName) => {expect(new MCPClientProfile({ clientName }).isCodingAgent()).toBe(false)@@ -166,6 +179,32 @@ describe('MCPClientProfile', () => {it('returns false when clientName is undefined', () => {expect(new MCPClientProfile({}).isCodingAgent()).toBe(false)})++ describe('vendorClient precedence', () => {+ it('prefers vendorClient over clientName for detection', () => {+ // Claude pools MCP transports: the initialize body says+ // `Anthropic/ClaudeAI` (the pool owner) but the live inner+ // client is `ClaudeCode` (a coding agent). The header wins.+ expect(+ new MCPClientProfile({+ clientName: 'Anthropic/ClaudeAI',+ vendorClient: 'ClaudeCode',+ }).isCodingAgent()+ ).toBe(true)+ })++ it('falls back to clientName when vendorClient is missing', () => {+ expect(new MCPClientProfile({ clientName: 'claude-code' }).isCodingAgent()).toBe(true)+ })++ it('treats coding-agent clientName as non-coding when vendorClient says otherwise', () => {+ // Inverse case: if a pool of coding-agent clients somehow+ // carries a non-coding request, the live header rules.+ expect(+ new MCPClientProfile({ clientName: 'claude-code', vendorClient: 'ClaudeAI' }).isCodingAgent()+ ).toBe(false)+ })+ })})describe('isPostHogCodeConsumer()', () => {@@ -251,11 +290,13 @@ describe('MCPClientProfile', () => {clientVersion: '1.2.3',consumer: POSTHOG_CODE_CONSUMER,oauthClientName: 'Lovable',+ vendorClient: 'ClaudeCode',})expect(profile.clientName).toBe('claude-code')expect(profile.clientVersion).toBe('1.2.3')expect(profile.consumer).toBe(POSTHOG_CODE_CONSUMER)expect(profile.oauthClientName).toBe('Lovable')+ expect(profile.vendorClient).toBe('ClaudeCode')})})diff --git a/services/mcp/tests/unit/posthog/analytics.test.ts b/services/mcp/tests/unit/posthog/analytics.test.tsindex 91f0cba0a2c2..912998677632 100644--- a/services/mcp/tests/unit/posthog/analytics.test.ts+++ b/services/mcp/tests/unit/posthog/analytics.test.ts@@ -76,6 +76,7 @@ describe('initMcpAnalytics', () => {getMcpClientName: vi.fn().mockResolvedValue('claude-code'),getMcpClientVersion: vi.fn().mockResolvedValue('1.2.3'),getMcpProtocolVersion: vi.fn().mockResolvedValue('2024-11-05'),+ getMcpVendorClient: vi.fn().mockResolvedValue('ClaudeCode'),getRegion: vi.fn().mockResolvedValue('us'),getAnalyticsContext: vi.fn().mockResolvedValue({organizationId: 'org-789',@@ -227,6 +228,7 @@ describe('initMcpAnalytics', () => {$mcp_client_user_agent: 'test-agent/1.0',$mcp_client_name: 'claude-code',$mcp_client_version: '1.2.3',+ mcp_vendor_client: 'ClaudeCode',$mcp_protocol_version: '2024-11-05',$mcp_region: 'us',$mcp_organization_id: 'org-789',diff --git a/services/mcp/tests/unit/protocol-types.test.ts b/services/mcp/tests/unit/protocol-types.test.tsindex 473f1af3ef1a..cea2ae51d5b0 100644--- a/services/mcp/tests/unit/protocol-types.test.ts+++ b/services/mcp/tests/unit/protocol-types.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from 'vitest'-import { MCPClientProfile } from '@/lib/client-detection'import { resolveModeAndVersion } from '@/hono/request-state-resolver'+import { MCPClientProfile } from '@/lib/client-detection'describe('resolveModeAndVersion', () => {function profile(overrides: Partial<ConstructorParameters<typeof MCPClientProfile>[0]> = {}): MCPClientProfile {@@ -16,11 +16,12 @@ describe('resolveModeAndVersion', () => {}it('defaults to version 1, no single exec', () => {- expect(resolveModeAndVersion(base)).toEqual({ useSingleExec: false, version: 1 })+ expect(resolveModeAndVersion(base)).toEqual({ mode: 'tools', useSingleExec: false, version: 1 })})it('explicit mode=cli forces single exec and version 2', () => {expect(resolveModeAndVersion({ ...base, mode: 'cli' })).toEqual({+ mode: 'cli',useSingleExec: true,version: 2,})@@ -40,7 +41,7 @@ describe('resolveModeAndVersion', () => {...base,clientProfile: profile({ clientName: 'claude-code' }),})- expect(result).toEqual({ useSingleExec: true, version: 2 })+ expect(result).toEqual({ mode: 'cli', useSingleExec: true, version: 2 })})it('non-coding agent does NOT activate single exec', () => {@@ -61,12 +62,12 @@ describe('resolveModeAndVersion', () => {it('uses flagVersion when not in single exec mode', () => {const result = resolveModeAndVersion({ ...base, flagVersion: 2 })- expect(result).toEqual({ useSingleExec: false, version: 2 })+ expect(result).toEqual({ mode: 'tools', useSingleExec: false, version: 2 })})it('clientVersion overrides default when no flagVersion', () => {const result = resolveModeAndVersion({ ...base, clientVersion: 2 })- expect(result).toEqual({ useSingleExec: false, version: 2 })+ expect(result).toEqual({ mode: 'tools', useSingleExec: false, version: 2 })})it('flagVersion takes precedence over clientVersion', () => {@@ -76,6 +77,6 @@ describe('resolveModeAndVersion', () => {it('single exec always forces version 2 regardless of flagVersion', () => {const result = resolveModeAndVersion({ ...base, mode: 'cli', flagVersion: 1 })- expect(result).toEqual({ useSingleExec: true, version: 2 })+ expect(result).toEqual({ mode: 'cli', useSingleExec: true, version: 2 })})})diff --git a/services/mcp/tests/unit/url-routing.test.ts b/services/mcp/tests/unit/url-routing.test.tsindex 410fc8972cfd..c418b37e04e8 100644--- a/services/mcp/tests/unit/url-routing.test.ts+++ b/services/mcp/tests/unit/url-routing.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest'+import { parseRequestProperties } from '@/lib/request-properties'import { parseMcpMode, sanitizeHeaderValue } from '@/lib/utils'function parseIdFromRequest(@@ -221,6 +222,38 @@ describe('URL Routing', () => {})})+ describe('shared request property mode parsing', () => {+ it('uses header mode before URL mode', () => {+ const request = new Request('https://example.com/mcp?mode=tools', {+ headers: {+ Authorization: 'Bearer phx_test',+ 'x-posthog-mcp-mode': 'cli',+ },+ })++ expect(parseRequestProperties(request, {}).mode).toBe('cli')+ })+ })++ describe('mcpVendorClient parsing', () => {+ it('captures x-anthropic-client into mcpVendorClient', () => {+ const request = new Request('https://example.com/mcp', {+ headers: {+ Authorization: 'Bearer phx_test',+ 'x-anthropic-client': 'ClaudeCode',+ },+ })+ expect(parseRequestProperties(request, {}).mcpVendorClient).toBe('ClaudeCode')+ })++ it('returns undefined when x-anthropic-client is missing', () => {+ const request = new Request('https://example.com/mcp', {+ headers: { Authorization: 'Bearer phx_test' },+ })+ expect(parseRequestProperties(request, {}).mcpVendorClient).toBeUndefined()+ })+ })+describe('MCP consumer parsing', () => {const consumerTests = [{