Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

5.2 KB
Raw Blame
import { classifyAuthMethod, type McpAuthMethod } from '@/lib/auth-method'
import type { RequestProperties } from '@/lib/request-properties'
import type { McpMode } from '@/lib/utils'

export interface MCPClientContext extends Pick<
    RequestProperties,
    | 'mcpClientName'
    | 'mcpClientVersion'
    | 'mcpProtocolVersion'
    | 'mcpConsumer'
    | 'mcpVendorClient'
    | 'mcpElicitationUrlSupported'
    | 'mcpUiSupported'
> {}

export interface MCPRequestContext
    extends
        MCPClientContext,
        Pick<
            RequestProperties,
            | 'sessionId'
            | 'organizationId'
            | 'projectId'
            | 'readOnly'
            | 'viaSseRedirect'
            | 'requestStartTime'
            | 'clientUserAgent'
            | 'transport'
            | 'mcpSessionId'
            | 'mcpConversationId'
            | 'region'
            | 'features'
            | 'tools'
            | 'excludeTools'
        > {
    mode?: McpMode | undefined
    authMethod: McpAuthMethod
}

// 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,
        mcpElicitationUrlSupported: props.mcpElicitationUrlSupported,
        mcpUiSupported: props.mcpUiSupported,
        transport: props.transport,
        mcpSessionId: props.mcpSessionId,
        mcpConversationId: props.mcpConversationId,
        mcpConsumer: props.mcpConsumer,
        mode: props.mode,
        region: props.region,
        features: props.features,
        tools: props.tools,
        excludeTools: props.excludeTools,
        mcpVendorClient: props.mcpVendorClient,
        authMethod: classifyAuthMethod(props.apiToken),
    }
}

/**
 * The id a request carries to group its events by, most specific first. MCP 2026-07-28
 * removed `initialize` and the `Mcp-Session-Id` header, so for those clients only the
 * agent's handle is ever present. `getEffectiveSessionUuid` turns this into `$session_id`.
 * Wrapper-only hints group analytics but do not replace conversation handles for context switches.
 */
export function resolveSessionKey(requestContext: MCPRequestContext): string | undefined {
    return requestContext.mcpConversationId ?? requestContext.sessionId ?? requestContext.mcpSessionId
}

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
}

/**
 * Per-field live-first coalesce for the identity properties captured on every MCP
 * analytics event. `clientInfo` only arrives on the `initialize` handshake (or, for
 * stateless requests, `params._meta['io.modelcontextprotocol/clientInfo']`), so a
 * `tools/call` in the middle of a session has no live client name — without a
 * fallback, `$mcp_client_name` goes out empty on every non-initialize event.
 *
 * This must stay per-field rather than whole-object (unlike
 * `getEffectiveMCPClientContext`, which is session-first and fine for that because
 * it drives session-scoped tool behavior): a single server multiplexes concurrent
 * requests from different clients, so a live value on this request always wins
 * over a possibly-stale session-pinned one, and only a genuinely absent field falls
 * back. Mirrors the `@posthog/mcp` SDK's own capture-side precedence
 * (`packages/mcp/src/extensions/capture.ts`) and the read-path classifier's field
 * order (`mcp_harness.py`: `$mcp_client_name` before `mcp_session_client_name`).
 */
export function getEffectiveMCPClientIdentity(
    requestContext: MCPRequestContext,
    sessionContext: MCPSessionContext | null
): MCPClientContext {
    return {
        mcpClientName: requestContext.mcpClientName ?? sessionContext?.mcpClientName,
        mcpClientVersion: requestContext.mcpClientVersion ?? sessionContext?.mcpClientVersion,
        mcpProtocolVersion: requestContext.mcpProtocolVersion ?? sessionContext?.mcpProtocolVersion,
        mcpConsumer: requestContext.mcpConsumer ?? sessionContext?.mcpConsumer,
        mcpVendorClient: requestContext.mcpVendorClient ?? sessionContext?.mcpVendorClient,
    }
}