: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-analytics): attribute MCP callers from every identity signal (#76953)
Lucas Fariac04c6a3e7c2c
diff --git a/products/mcp_analytics/backend/logic.py b/products/mcp_analytics/backend/logic.pyindex 9e15fed7fde2..02a17165bf52 100644--- a/products/mcp_analytics/backend/logic.py+++ b/products/mcp_analytics/backend/logic.py@@ -23,7 +23,7 @@ from posthog.models.user import Userfrom posthog.personhog_client.caller_tag import personhog_caller_tagfrom posthog.utils import generate_cache_key-from products.mcp_analytics.backend import intent_generation+from products.mcp_analytics.backend import intent_generation, mcp_harnessfrom products.mcp_analytics.backend.constants import (MAX_SNAPSHOT_CLUSTERS,MCP_MISSING_CAPABILITY_EVENT,@@ -421,17 +421,33 @@ ACTIVITY_TOP_TOOLS_LIMIT = 5ACTIVITY_CLIENTS_LIMIT = 6ACTIVITY_RECENT_CALLS_LIMIT = 20-_ACTIVITY_STATS_SQL = """+_ACTIVITY_STATS_SQL = f"""SELECT- countIf(event = {tool_call_event}) AS total_calls,- uniqIf(properties.$mcp_tool_name, event = {tool_call_event}) AS distinct_tools,- uniqIf($session_id, event = {tool_call_event} AND $session_id != '') AS distinct_sessions,- uniqIf(properties.$mcp_client_name, event = {tool_call_event} AND coalesce(properties.$mcp_client_name, '') != '') AS distinct_clients,- countIf(event = {tool_call_event} AND coalesce(properties.$mcp_intent, '') != '') AS calls_with_intent,- countIf(event = {tool_call_event} AND toString(properties.$mcp_is_error) IN ('true', '1')) AS error_calls,- countIf(event = {missing_capability_event}) AS missing_capability_reports-FROM events-WHERE event IN ({tool_call_event}, {missing_capability_event}) AND timestamp >= {date_from}+ countIf(is_tool_call) AS total_calls,+ uniqIf(tool, is_tool_call) AS distinct_tools,+ uniqIf(session_id, is_tool_call AND session_id != '') AS distinct_sessions,+ -- Counted over the resolved *label*, not the token: one client can arrive under+ -- several tokens (`codex-mcp-client` and the `openai-mcp … (Codex)` user-agent both+ -- mean Codex), which the Clients card folds into one row, so counting tokens would+ -- put "2 clients" next to a one-row card. The raw `$mcp_client_name` is absent from+ -- every non-initialize call and cannot be counted here at all.+ uniqIf({mcp_harness.harness_label_or_token_sql("h")}, is_tool_call AND h != '') AS distinct_clients,+ countIf(is_tool_call AND has_intent) AS calls_with_intent,+ countIf(is_tool_call AND is_error) AS error_calls,+ countIf(is_missing_capability) AS missing_capability_reports+FROM (+ SELECT+ event = {{tool_call_event}} AS is_tool_call,+ event = {{missing_capability_event}} AS is_missing_capability,+ properties.$mcp_tool_name AS tool,+ $session_id AS session_id,+ coalesce(properties.$mcp_intent, '') != '' AS has_intent,+ toString(properties.$mcp_is_error) IN ('true', '1') AS is_error,+ {mcp_harness.HARNESS_TOKEN_SQL} AS h,+ {mcp_harness.HARNESS_DISPLAY_NAME_SQL} AS client_display+ FROM events+ WHERE event IN ({{tool_call_event}}, {{missing_capability_event}}) AND timestamp >= {{date_from}}+)"""_ACTIVITY_TOP_TOOLS_SQL = """@@ -446,44 +462,58 @@ ORDER BY calls DESCLIMIT {limit}"""-# Agents report the same client under many spellings — "claude-code", "Claude Code",-# "CLAUDE_CODE" — so grouping on the raw property splits one client across several rows-# and lets each land below the top-N cut. Case and separators are both normalised away-# for grouping (matching the frontend's harness-label rules, which already treat-# `[ ._-]` as interchangeable), and the most-seen spelling becomes the display name.-_ACTIVITY_CLIENTS_SQL = """+# Resolved through the canonical classifier rather than the raw `$mcp_client_name`,+# which is absent on any call that isn't the session's `initialize` — reading it alone+# left the large majority of calls unattributed and lumped whole clients under one+# "unknown" row. `HARNESS_TOKEN_SQL` falls back through the other identity signals the+# same event already carries, and the label bucketing folds one client's variant spellings+# (differing case, or a name carrying mcp-remote's proxy signature) into a single row.+# Unrecognized clients are named verbatim: this is a ranked top-N list, so a+# self-reported name is more use than collapsing it into "Other".+_ACTIVITY_CLIENTS_SQL = f"""SELECT- argMax(client_name, spelling_calls) AS client,- sum(spelling_calls) AS calls+ {mcp_harness.harness_label_or_token_sql("h")} AS client,+ count() AS callsFROM (SELECT- properties.$mcp_client_name AS client_name,- replaceRegexpAll(lower(properties.$mcp_client_name), '[ ._-]+', '') AS client_key,- count() AS spelling_calls+ {mcp_harness.HARNESS_TOKEN_SQL} AS h,+ {mcp_harness.HARNESS_DISPLAY_NAME_SQL} AS client_displayFROM events- WHERE event = {tool_call_event} AND timestamp >= {date_from}- GROUP BY client_name, client_key+ WHERE event = {{tool_call_event}} AND timestamp >= {{date_from}})-GROUP BY client_key+GROUP BY clientORDER BY calls DESC-LIMIT {limit}+LIMIT {{limit}}"""-_ACTIVITY_RECENT_CALLS_SQL = """+_ACTIVITY_RECENT_CALLS_SQL = f"""SELECTtimestamp,- properties.$mcp_tool_name AS tool,- properties.$mcp_intent AS intent,- toString(properties.$mcp_is_error) IN ('true', '1') AS is_error,- if(toString(properties.$mcp_is_error) IN ('true', '1'),- coalesce(nullIf(toString(properties.$mcp_error_message), ''), toString(properties.$mcp_response)),- NULL) AS error_raw,- toFloat(properties.$mcp_duration_ms) AS duration_ms,- properties.$mcp_client_name AS client_name-FROM events-WHERE event = {tool_call_event} AND timestamp >= {date_from}+ tool,+ intent,+ is_error,+ error_raw,+ duration_ms,+ -- Resolved, not raw: the live feed showed a blank caller on most rows otherwise.+ {mcp_harness.harness_label_or_token_sql("h")} AS client_name+FROM (+ SELECT+ timestamp,+ properties.$mcp_tool_name AS tool,+ properties.$mcp_intent AS intent,+ toString(properties.$mcp_is_error) IN ('true', '1') AS is_error,+ if(toString(properties.$mcp_is_error) IN ('true', '1'),+ coalesce(nullIf(toString(properties.$mcp_error_message), ''), toString(properties.$mcp_response)),+ NULL) AS error_raw,+ toFloat(properties.$mcp_duration_ms) AS duration_ms,+ {mcp_harness.HARNESS_TOKEN_SQL} AS h,+ {mcp_harness.HARNESS_DISPLAY_NAME_SQL} AS client_display+ FROM events+ WHERE event = {{tool_call_event}} AND timestamp >= {{date_from}}+ ORDER BY timestamp DESC+ LIMIT {{limit}}+)ORDER BY timestamp DESC-LIMIT {limit}"""diff --git a/products/mcp_analytics/backend/mcp_harness.py b/products/mcp_analytics/backend/mcp_harness.pyindex 1fc56bbe12a2..414ed9f8d837 100644--- a/products/mcp_analytics/backend/mcp_harness.py+++ b/products/mcp_analytics/backend/mcp_harness.py@@ -12,14 +12,21 @@ query-time computation:MCP analytics SDK, or `mcp_session_client_name` as reported by PostHog's hostedMCP server — then the User-Agent product token, then the OAuth client name) —`HARNESS_TOKEN_SQL`.- 2. Bucket that token into a customer label — `harness_label_sql`.+ 2. Bucket that token into a customer label — `harness_label_sql` when the result must+ stay inside `HARNESS_LABELS`, or `harness_label_or_token_sql` when an unrecognized+ client is better named by its own self-report than collapsed into "Other".++Read the token, never a raw property: `$mcp_client_name` is absent on every call that+isn't the session's `initialize`, so anything grouping on it alone leaves the bulk of+traffic unattributed.This module is the single source of truth for harness classification. The frontend nolonger classifies — `products/mcp_analytics/frontend/dashboard/harnessRegistry.ts` keepsonly a label-to-logo/colour map (`HARNESS_BY_LABEL`), keyed by the labels this module-emits, and a cross-language test pins those keys to `HARNESS_LABELS`. The one remaining-copy that must move in lockstep is the documented query in the `querying-posthog-data`-skill's `models-mcp.md`.+emits, and a cross-language test pins those keys to `HARNESS_LABELS`. Two documented+copies must move in lockstep: the query in the `querying-posthog-data` skill's+`models-mcp.md`, and the vocabulary table in this product's `debugging-mcp-analytics`+skill.Because the token appears many times in the bucketing `multiIf`, callers computeit once as a column (`{HARNESS_TOKEN_SQL} AS h`, or `argMax(..., timestamp)` for a@@ -66,14 +73,60 @@ _RAW_TOKEN = f"""coalesce(# string parsing to reach RE2 as `\s` / `\(`.HARNESS_TOKEN_SQL = f"trim(replaceRegexpAll(lower({_RAW_TOKEN}), '\\\\s*\\\\(via mcp-remote[^)]*\\\\)\\\\s*', ''))"+# The same resolution and proxy-suffix strip, but with the client's own capitalization+# intact, so an unrecognized client can be shown under the name it actually reported+# rather than a lower-cased one. Matching still uses the token above; this is display+# only. `(?i)` does the case-insensitive strip that `lower()` made unnecessary there.+HARNESS_DISPLAY_NAME_SQL = f"trim(replaceRegexpAll({_RAW_TOKEN}, '(?i)\\\\s*\\\\(via mcp-remote[^)]*\\\\)\\\\s*', ''))"++# Shown by `harness_label_or_token_sql` when an event carries no identity signal at+# all — not a client anyone runs, unlike every other label this module emits.+UNIDENTIFIED_HARNESS_LABEL = "Unidentified client"++# Tokens are self-reported and unbounded; cap one before it can widen a grouping key.+_MAX_TOKEN_LABEL_LENGTH = 200+def harness_label_sql(token_col: str = "h") -> str:"""Bucket a normalized harness token column into a customer label.+ Every unrecognized token collapses into "Other", so the result is always one of+ `HARNESS_LABELS`. Callers that aggregate labels into a per-row array need that+ bound; callers that rank a top-N list should prefer `harness_label_or_token_sql`,+ which names an unrecognized client instead of discarding it.+`token_col` is the name of a column already holding `HARNESS_TOKEN_SQL`(or an argMax of it) — pass the alias, not the token expression itself.Surface-specific entries are listed before the generic prefix matches so`find`-style first-match precedence matches the frontend registry order.+ """+ return _label_multi_if(token_col, "'Other'")+++def harness_label_or_token_sql(token_col: str = "h", display_col: str = "client_display") -> str:+ """Same bucketing as `harness_label_sql`, but names unrecognized clients verbatim.++ An unrecognized token is not noise — it is the client's own self-reported name+ ("posthog-attribution-service", "openclaw-bundle-mcp"), which is strictly more+ useful in a ranked list of callers than "Other". `display_col` holds+ `HARNESS_DISPLAY_NAME_SQL` so that name keeps its own capitalization; matching still+ happens on the lower-cased `token_col`. The name is event-supplied and unbounded, so+ it is capped before it can reach a grouping key. Only a genuinely identity-free event+ (the empty token) falls through to a placeholder.++ Unlike `harness_label_sql`, the result is NOT confined to `HARNESS_LABELS` — never+ use this where labels accumulate into an array or an unbounded GROUP BY.+ """+ if not display_col.isidentifier():+ raise ValueError(f"display_col must be a SQL identifier, got {display_col!r}")+ fallback = (+ f"if({token_col} = '', '{UNIDENTIFIED_HARNESS_LABEL}', substring({display_col}, 1, {_MAX_TOKEN_LABEL_LENGTH}))"+ )+ return _label_multi_if(token_col, fallback)+++def _label_multi_if(token_col: str, fallback_sql: str) -> str:+ """The shared bucketing `multiIf`, parameterized by its final (else) arm.`token_col` is interpolated into SQL, so it must be a bare identifier — neverrequest input. The guard makes that impossible to violate by accident.@@ -92,6 +145,11 @@ def harness_label_sql(token_col: str = "h") -> str:{token_col} = 'openai-mcp chatgpt', 'ChatGPT',{token_col} = 'openai-mcp agent builder', 'OpenAI Agent Builder',{token_col} = 'openai-mcp responses api', 'OpenAI Responses API',+ -- Codex reports itself two ways: `codex-mcp-client` as its clientInfo.name, and+ -- the `openai-mcp/… (Codex)` User-Agent surface. The surface has to be matched+ -- before the generic `openai-mcp` prefix below, and the `codex` prefix further+ -- down can never catch it, so both spellings need their own branch.+ {token_col} = 'openai-mcp codex', 'OpenAI Codex',startsWith({token_col}, 'openai-mcp'), 'OpenAI',startsWith({token_col}, 'codex'), 'OpenAI Codex',startsWith({token_col}, 'grok'), 'Grok',@@ -111,13 +169,19 @@ def harness_label_sql(token_col: str = "h") -> str:{token_col} = 'opencode', 'opencode',startsWith({token_col}, 'kiro'), 'Kiro',startsWith({token_col}, 'desktop-commander'), 'Desktop Commander',- 'Other'+ -- PostHog's own CLI (`services/mcp/src/cli/context.ts` hard-codes this name).+ -- It is a wrapper, not a terminal client: agents are told to shell out to it by+ -- the AGENTS.md snippet it installs, and it forwards no identity for whoever+ -- invoked it, so these calls can only ever be attributed to the CLI itself.+ {token_col} = 'posthog-cli', 'PostHog CLI',+ {fallback_sql})"""# Every customer label `harness_label_sql` can emit. A unit test asserts this tuple# stays in step with the multiIf branches; the frontend registry's logo/colour keys# are cross-checked against it when the dashboard is rewired onto this runner.+# `harness_label_or_token_sql` can also emit a raw token or UNIDENTIFIED_HARNESS_LABEL.HARNESS_LABELS: tuple[str, ...] = ("Claude Desktop","Claude Code (VS Code)",@@ -149,5 +213,6 @@ HARNESS_LABELS: tuple[str, ...] = ("opencode","Kiro","Desktop Commander",+ "PostHog CLI","Other",)diff --git a/products/mcp_analytics/backend/tests/test_api.py b/products/mcp_analytics/backend/tests/test_api.pyindex 1656bdb1587c..d07e5fccd8c1 100644--- a/products/mcp_analytics/backend/tests/test_api.py+++ b/products/mcp_analytics/backend/tests/test_api.py@@ -1,5 +1,6 @@import hashlibfrom datetime import UTC, datetime, timedelta+from typing import Anyfrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_eventfrom unittest.mock import patch@@ -12,7 +13,7 @@ from parameterized import parameterizedfrom posthog.models.utils import uuid7from posthog.utils import generate_cache_key-from products.mcp_analytics.backend import intent_generation+from products.mcp_analytics.backend import intent_generation, mcp_harnessfrom products.mcp_analytics.backend.facade import api, contracts, enumsfrom products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPSessionfrom products.mcp_analytics.backend.tests import _MCPAnalyticsTeamScopedTestMixin@@ -637,7 +638,7 @@ class TestActivityOverview(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin"$session_id": session_id,"$mcp_tool_name": "query_run","$mcp_intent": "check signups",- "$mcp_client_name": "Claude Code",+ "$mcp_client_name": "claude-code","$mcp_duration_ms": 120,},)@@ -651,7 +652,7 @@ class TestActivityOverview(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin"$mcp_tool_name": "docs_search","$mcp_is_error": "true","$mcp_response": '{"content": [{"type": "text", "text": "index unavailable"}]}',- "$mcp_client_name": "Claude Code",+ "$mcp_client_name": "claude-code",},)_create_event(@@ -693,23 +694,83 @@ class TestActivityOverview(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixinassert overview.recent_calls[1].duration_ms == 120.0assert overview.recent_calls[1].intent == "check signups"- def test_merges_client_spellings_that_differ_only_by_case_or_separator(self) -> None:- # Agents report the same client under several spellings. Grouping on the raw property- # listed one client as several rows, each competing for the same top-N slots.- for client, count in [("claude-code", 3), ("Claude Code", 2), ("CLAUDE_CODE", 1)]:- for _ in range(count):- _create_event(- team=self.team,- event="$mcp_tool_call",- distinct_id="agent-1",- timestamp=datetime.now(tz=UTC) - timedelta(minutes=5),- properties={"$session_id": str(uuid7()), "$mcp_tool_name": "query_run", "$mcp_client_name": client},- )+ def _emit_call(self, properties: dict[str, Any], count: int = 1) -> None:+ for _ in range(count):+ _create_event(+ team=self.team,+ event="$mcp_tool_call",+ distinct_id="agent-1",+ timestamp=datetime.now(tz=UTC) - timedelta(minutes=5),+ properties={"$session_id": str(uuid7()), "$mcp_tool_name": "query_run", **properties},+ )++ def test_merges_client_spellings_into_one_canonical_row(self) -> None:+ # One client reaches us under several spellings — different casing, and a proxied+ # name carrying mcp-remote's signature. Grouping on the raw property listed each as+ # its own row, so one client competed with itself for the top-N slots.+ # Separator variants ("Claude Code", "CLAUDE_CODE") are deliberately not merged:+ # no client emits them, and collapsing `[ ._-]` would destroy the surface tokens+ # the classifier matches on ("claude-code cli", "visual studio code").+ for client, count in [+ ("claude-code", 3),+ ("Claude-Code", 2),+ ("claude-code (via mcp-remote 0.1.37)", 1),+ ]:+ self._emit_call({"$mcp_client_name": client}, count)++ overview = api.get_activity_overview(self.team)++ assert overview.clients == [contracts.ActivityClientRow(client="Claude Code", calls=6)]++ def test_counts_one_client_reached_by_two_identity_signals_once(self) -> None:+ # Codex arrives both as a session-pinned clientInfo name and as a user-agent+ # surface. Those are two different tokens but one client, so counting tokens+ # would report "2 clients" next to a Clients card showing a single row.+ self._emit_call({"mcp_session_client_name": "codex-mcp-client"}, count=3)+ self._emit_call({"$mcp_client_user_agent": "openai-mcp/1.0.0 (Codex)"}, count=2)++ overview = api.get_activity_overview(self.team)++ assert overview.clients == [contracts.ActivityClientRow(client="OpenAI Codex", calls=5)]+ assert overview.stats.distinct_clients == 1++ @parameterized.expand(+ [+ # `$mcp_client_name` rides on `initialize` only, so a mid-session tool call+ # carries the session-pinned name instead. Reading the raw property alone left+ # every one of these unattributed.+ ("session_pinned_name", {"mcp_session_client_name": "codex-mcp-client"}, "OpenAI Codex"),+ # Codex's other spelling: the User-Agent surface. The generic `openai-mcp`+ # prefix used to swallow this and report it as plain "OpenAI".+ ("codex_user_agent_surface", {"$mcp_client_user_agent": "openai-mcp/1.0 (Codex)"}, "OpenAI Codex"),+ ("vendor_header", {"mcp_vendor_client": "ClaudeCode"}, "Claude Code"),+ ("oauth_client_name", {"$mcp_oauth_client_name": "cursor-vscode"}, "Cursor"),+ # An unrecognized client is still named — its own self-report beats "Other".+ ("unrecognized_named_verbatim", {"$mcp_client_name": "openclaw-bundle-mcp"}, "openclaw-bundle-mcp"),+ # ...and keeps its own capitalization: matching lower-cases the token, but the+ # name shown back is the one the client reported.+ ("unrecognized_keeps_casing", {"$mcp_client_name": "NexusAgent"}, "NexusAgent"),+ (+ "unrecognized_keeps_casing_via_session",+ {"mcp_session_client_name": "Concept Connectors"},+ "Concept Connectors",+ ),+ ("no_identity_at_all", {}, mcp_harness.UNIDENTIFIED_HARNESS_LABEL),+ ]+ )+ def test_attributes_clients_from_every_identity_signal(+ self, _name: str, properties: dict[str, Any], expected: str+ ) -> None:+ self._emit_call(properties, count=2)overview = api.get_activity_overview(self.team)- # The most-seen spelling represents the merged row.- assert overview.clients == [contracts.ActivityClientRow(client="claude-code", calls=6)]+ assert overview.clients == [contracts.ActivityClientRow(client=expected, calls=2)]+ # The stat tile and the live feed resolve the caller the same way the card does,+ # so they can't disagree about who called: counting the raw property scored these+ # as zero known clients and left the feed's caller column blank.+ assert overview.stats.distinct_clients == (0 if expected == mcp_harness.UNIDENTIFIED_HARNESS_LABEL else 1)+ assert [call.client_name for call in overview.recent_calls] == [expected, expected]class TestGenerateSessionIntent(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):diff --git a/products/mcp_analytics/backend/tests/test_harness_breakdown.py b/products/mcp_analytics/backend/tests/test_harness_breakdown.pyindex 18f044807314..5b1f8025c9cf 100644--- a/products/mcp_analytics/backend/tests/test_harness_breakdown.py+++ b/products/mcp_analytics/backend/tests/test_harness_breakdown.py@@ -15,6 +15,8 @@ from posthog.schema import (PropertyOperator,)+from posthog.hogql.parser import parse_expr+from posthog.rbac.user_access_control import UserAccessControlErrorfrom products.mcp_analytics.backend import mcp_harness@@ -30,6 +32,31 @@ def test_harness_labels_tuple_matches_multiif_branches() -> None:assert emitted == set(mcp_harness.HARNESS_LABELS)+ [+ ("token", mcp_harness.HARNESS_TOKEN_SQL),+ ("display_name", mcp_harness.HARNESS_DISPLAY_NAME_SQL),+ ("label", mcp_harness.harness_label_sql("h")),+ ("label_or_token", mcp_harness.harness_label_or_token_sql("h")),+ ]+)+def test_harness_expressions_are_parseable_hogql(_name: str, sql: str) -> None:+ # These are assembled as f-strings and only ever reach the parser inside a query+ # runner, so a syntax slip (an inline comment the grammar rejects, an unbalanced+ # paren) would otherwise surface as a broken dashboard rather than a failing test.+ parse_expr(sql)+++def test_label_or_token_keeps_the_bounded_label_set_reachable() -> None:+ # The verbatim fallback must only replace the "Other" arm — if it shadowed a real+ # branch, recognized clients would start rendering as raw tokens.+ bounded = mcp_harness.harness_label_sql("h")+ verbatim = mcp_harness.harness_label_or_token_sql("h")+ assert verbatim.count("'Claude Code',") == bounded.count("'Claude Code',")+ assert "'Other'" not in verbatim+ assert mcp_harness.UNIDENTIFIED_HARNESS_LABEL in verbatim++class TestMCPHarnessBreakdownQueryRunner(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):def _emit(self,diff --git a/products/mcp_analytics/frontend/dashboard/harnessRegistry.ts b/products/mcp_analytics/frontend/dashboard/harnessRegistry.tsindex ea26e866cf49..717ef9bb0e1e 100644--- a/products/mcp_analytics/frontend/dashboard/harnessRegistry.ts+++ b/products/mcp_analytics/frontend/dashboard/harnessRegistry.ts@@ -65,6 +65,7 @@ export const HARNESS_BY_LABEL: Record<string, HarnessDescriptor> = {opencode: { logo: { src: opencodeLogo, alt: 'opencode logo' } },Kiro: {},'Desktop Commander': {},+ 'PostHog CLI': {},}export function harnessLogo(label: string): HarnessLogo | undefined {diff --git a/products/mcp_analytics/frontend/earlyData/MCPAnalyticsEarlyData.tsx b/products/mcp_analytics/frontend/earlyData/MCPAnalyticsEarlyData.tsxindex 85559c7f8363..6e5112e5c333 100644--- a/products/mcp_analytics/frontend/earlyData/MCPAnalyticsEarlyData.tsx+++ b/products/mcp_analytics/frontend/earlyData/MCPAnalyticsEarlyData.tsx@@ -18,25 +18,6 @@ import { METRICS_UNLOCK_LIFETIME_CALLS, mcpAnalyticsOnboardingLogic } from '../mimport type { ChecklistItem, EarlyRecentCall } from './mcpEarlyDataLogic'import { mcpEarlyDataLogic } from './mcpEarlyDataLogic'-// Raw `$mcp_client_name` values don't match the backend-resolved harness labels the-// logo registry is keyed by; this maps the common spellings so rows get a logo.-// Unknown clients fall back to HarnessLogo's neutral dot.-const CLIENT_LABEL_RULES: Array<[RegExp, string]> = [- [/claude[ ._-]?code/i, 'Claude Code'],- [/claude[ ._-]?desktop/i, 'Claude Desktop'],- [/claude[ ._-]?ai/i, 'Claude.ai'],- [/claude/i, 'Claude.ai'],- [/chatgpt/i, 'ChatGPT'],- [/codex/i, 'OpenAI Codex'],- [/openai/i, 'OpenAI'],- [/cursor/i, 'Cursor'],- [/windsurf/i, 'Windsurf'],-]--function guessHarnessLabel(clientName: string): string {- return CLIENT_LABEL_RULES.find(([pattern]) => pattern.test(clientName))?.[1] ?? clientName-}-/*** The Activity tab: answers "what are agents doing with my server?" — a* plain-language summary instead of KPI tiles, the live feed as the hero, an@@ -183,10 +164,7 @@ function LiveActivityCard(): JSX.Element {render: (_, row) =>row.clientName ? (<span className="flex items-center gap-1.5">- <HarnessLogo- category={guessHarnessLabel(row.clientName)}- className="h-3.5 w-3.5"- />+ <HarnessLogo category={row.clientName} className="h-3.5 w-3.5" /><span className="truncate">{row.clientName}</span></span>) : (@@ -318,7 +296,7 @@ function ClientsCard(): JSX.Element {<div key={row.client}><div className="flex justify-between text-base"><span className="flex items-center gap-1.5">- <HarnessLogo category={guessHarnessLabel(row.client)} className="h-3.5 w-3.5" />+ <HarnessLogo category={row.client} className="h-3.5 w-3.5" />{row.client}</span><span className="text-muted">{formatNumber(row.calls)}</span>diff --git a/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.ts b/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.tsindex bdae752f29d3..241c1727bbf1 100644--- a/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.ts+++ b/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.ts@@ -214,7 +214,7 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([clients: [(s) => [s.overview],(overview: MCPActivityOverviewApi | null): EarlyClientRow[] =>- (overview?.clients ?? []).map((row) => ({ client: row.client || 'Unknown client', calls: row.calls })),+ (overview?.clients ?? []).map((row) => ({ client: row.client, calls: row.calls })),],recentCalls: [(s) => [s.overview],diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.tsindex a4eacdde667d..6bb980b0c514 100644--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts@@ -82,6 +82,7 @@ describe('mcpDashboardOverviewLogic', () => {'opencode','Kiro','Desktop Commander',+ 'PostHog CLI',]it.each(EXPECTED_HARNESS_LABELS)('HARNESS_BY_LABEL has an entry for backend label %s', (label) => {diff --git a/products/mcp_analytics/skills/debugging-mcp-analytics/SKILL.md b/products/mcp_analytics/skills/debugging-mcp-analytics/SKILL.mdindex 36dcede32b99..0b4c4f4286ec 100644--- a/products/mcp_analytics/skills/debugging-mcp-analytics/SKILL.md+++ b/products/mcp_analytics/skills/debugging-mcp-analytics/SKILL.md@@ -152,8 +152,15 @@ Windsurf, and ~30 other buckets). It is resolved at query time only, with no sto`mcp_harness.py::HARNESS_TOKEN_SQL` picks the strongest available signal in priority order(`mcp_vendor_client` -> Claude Code user-agent surface -> Grok user-agent -> `$mcp_client_name`-> `mcp_session_client_name` -> generic user-agent token -> `$mcp_oauth_client_name`), then-`harness_label_sql()` buckets it. **`$mcp_client_name` is one mid-priority input, not a synonym-for harness** — grouping by it directly gives a different, messier answer.+`harness_label_sql()` buckets it (or `harness_label_or_token_sql()`, which names an+unrecognized client verbatim instead of collapsing it into "Other" — use it for ranked+top-N lists, never where labels feed an array or unbounded GROUP BY).++**`$mcp_client_name` is one mid-priority input, not a synonym for harness** — grouping by+it directly gives a different, messier answer. It rides on the session's `initialize` and+is absent from the tool calls that follow, so on its own it leaves most traffic+unattributed; `mcp_session_client_name` is the session-pinned fallback the token chain+reaches for next.For hand-written SQL, `models-mcp.md` (linked in the Repos table) carries the propertyreference and worked query examples.diff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.md b/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.mdindex 44f536f9f67b..ad6556aab8d9 100644--- a/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.md+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.md@@ -171,6 +171,10 @@ FROM (h = 'openai-mcp chatgpt', 'ChatGPT',h = 'openai-mcp agent builder', 'OpenAI Agent Builder',h = 'openai-mcp responses api', 'OpenAI Responses API',+ -- Codex has two spellings: the `codex-mcp-client` clientInfo.name caught by+ -- the prefix below, and this User-Agent surface. This branch must precede the+ -- generic `openai-mcp` prefix, which would otherwise report it as "OpenAI".+ h = 'openai-mcp codex', 'OpenAI Codex',startsWith(h, 'openai-mcp'), 'OpenAI',startsWith(h, 'codex'), 'OpenAI Codex',startsWith(h, 'grok'), 'Grok',@@ -190,6 +194,10 @@ FROM (h = 'opencode', 'opencode',startsWith(h, 'kiro'), 'Kiro',startsWith(h, 'desktop-commander'), 'Desktop Commander',+ h = 'posthog-cli', 'PostHog CLI',+ -- Ranked top-N lists name an unrecognized client verbatim instead+ -- (`harness_label_or_token_sql`); "Other" is for callers that need the label+ -- confined to the bounded set, e.g. one aggregated into a per-row array.'Other') AS harnessFROM (diff --git a/services/mcp/src/hono/analytics.ts b/services/mcp/src/hono/analytics.tsindex 16a18bb462c0..bde4c9718599 100644--- a/services/mcp/src/hono/analytics.ts+++ b/services/mcp/src/hono/analytics.ts@@ -13,7 +13,7 @@ import {import { EXECUTE_SQL_TOOL_NAME } from '@/tools/posthogAiTools/executeSql'import { MAX_CAPTURED_DESCRIPTION_LENGTH, getToolCategory, getToolDescription } from '@/tools/toolDefinitions'-import { buildMCPSessionAnalyticsProperties } from './mcp-context'+import { buildMCPSessionAnalyticsProperties, getEffectiveMCPClientIdentity } from './mcp-context'import type { ResolvedState } from './request-state-resolver'function buildBaseProperties(@@ -25,6 +25,13 @@ function buildBaseProperties(} {const groups = analyticsContext ? buildMCPAnalyticsGroups(analyticsContext) : {}const requestContext = state.requestContext+ // Live-first per-field: `clientInfo` only arrives on `initialize`, so a mid-session+ // `tools/call` has no live client identity of its own. Falls back to the+ // session-pinned value per field (not swapping in the whole session object) so a+ // live value from a concurrent request on the same server always wins. See+ // `getEffectiveMCPClientIdentity` for why this must differ from+ // `getEffectiveMCPClientContext`.+ const clientIdentity = getEffectiveMCPClientIdentity(requestContext, state.sessionContext)const properties: Record<string, unknown> = {$ai_product: 'mcp',@@ -32,14 +39,14 @@ function buildBaseProperties($mcp_server_name: MCP_SERVER_NAME,$mcp_server_version: MCP_SERVER_VERSION,$mcp_version: MCP_ANALYTICS_VERSION,- $mcp_client_name: requestContext.mcpClientName,- $mcp_client_version: requestContext.mcpClientVersion,+ $mcp_client_name: clientIdentity.mcpClientName,+ $mcp_client_version: clientIdentity.mcpClientVersion,$mcp_client_user_agent: requestContext.clientUserAgent,- $mcp_protocol_version: requestContext.mcpProtocolVersion,+ $mcp_protocol_version: clientIdentity.mcpProtocolVersion,$mcp_transport: requestContext.transport,$mcp_session_id: requestContext.mcpSessionId,$mcp_conversation_id: requestContext.mcpConversationId,- $mcp_consumer: requestContext.mcpConsumer,+ $mcp_consumer: clientIdentity.mcpConsumer,$mcp_mode: requestContext.mode,$mcp_region: requestContext.region,...(analyticsContext@@ -52,7 +59,7 @@ function buildBaseProperties(}: {}),mcp_runtime: 'hono',- mcp_vendor_client: requestContext.mcpVendorClient,+ mcp_vendor_client: clientIdentity.mcpVendorClient,...buildMCPSessionAnalyticsProperties(state.sessionContext),}return { properties, groups }diff --git a/services/mcp/src/hono/mcp-context.ts b/services/mcp/src/hono/mcp-context.tsindex c03bfd6e09e9..1250198e076a 100644--- a/services/mcp/src/hono/mcp-context.ts+++ b/services/mcp/src/hono/mcp-context.ts@@ -72,3 +72,32 @@ export function getEffectiveMCPClientContext(): 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,+ }+}diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.tsindex 94c2b5a8b010..dd5f9ded0e43 100644--- a/services/mcp/tests/hono/analytics.test.ts+++ b/services/mcp/tests/hono/analytics.test.ts@@ -117,6 +117,116 @@ describe('Hono MCP analytics contexts', () => {expect(properties.mcp_session_vendor_client).toBeUndefined()})+ describe('client identity live-first fallback', () => {+ // $mcp_client_name is the property this whole fix targets: `clientInfo` arrives+ // only on `initialize`, so it was empty on every tool call that followed. The+ // same live-first-then-session precedence applies to every field a live request+ // can carry.+ it.each([+ ['$mcp_client_name', 'mcpClientName'],+ ['$mcp_client_version', 'mcpClientVersion'],+ ['$mcp_protocol_version', 'mcpProtocolVersion'],+ ['$mcp_consumer', 'mcpConsumer'],+ ['mcp_vendor_client', 'mcpVendorClient'],+ ] as const)(+ '%s: live value wins when both live and session values are present',+ async (eventProp, contextField) => {+ const state = makeState({+ requestContext: { ...makeState().requestContext, [contextField]: 'live-value' },+ sessionContext: { ...makeState().sessionContext, [contextField]: 'session-value' },+ })+ await trackToolCall('user-get', 12, false, state)++ expect(mockCaptureToolCall.mock.calls[0]![0].properties[eventProp]).toBe('live-value')+ }+ )++ it.each([+ ['$mcp_client_name', 'mcpClientName'],+ ['$mcp_client_version', 'mcpClientVersion'],+ ['$mcp_protocol_version', 'mcpProtocolVersion'],+ ['$mcp_consumer', 'mcpConsumer'],+ ['mcp_vendor_client', 'mcpVendorClient'],+ ] as const)(+ '%s: falls back to the session-pinned value when the live request has none (the tools/call case)',+ async (eventProp, contextField) => {+ const state = makeState({+ requestContext: { ...makeState().requestContext, [contextField]: undefined },+ sessionContext: { ...makeState().sessionContext, [contextField]: 'session-value' },+ })+ await trackToolCall('user-get', 12, false, state)++ expect(mockCaptureToolCall.mock.calls[0]![0].properties[eventProp]).toBe('session-value')+ }+ )++ it.each([+ ['$mcp_client_name', 'mcpClientName'],+ ['$mcp_client_version', 'mcpClientVersion'],+ ['$mcp_protocol_version', 'mcpProtocolVersion'],+ ['$mcp_consumer', 'mcpConsumer'],+ ['mcp_vendor_client', 'mcpVendorClient'],+ ] as const)(+ '%s: stays undefined (never an empty string) when both live and session values are absent',+ async (eventProp, contextField) => {+ const state = makeState({+ requestContext: { ...makeState().requestContext, [contextField]: undefined },+ sessionContext: { ...makeState().sessionContext, [contextField]: undefined },+ })+ await trackToolCall('user-get', 12, false, state)++ expect(mockCaptureToolCall.mock.calls[0]![0].properties[eventProp]).toBeUndefined()+ }+ )++ it('initialize with no session context is unchanged: live request value is used as-is', async () => {+ await trackInitEvent(makeState({ sessionContext: null }))++ expect(mockCaptureInitialize.mock.calls[0]![0].properties).toMatchObject({+ $mcp_client_name: 'Claude Desktop',+ $mcp_client_version: '2.0',+ $mcp_protocol_version: '2025-03-26',+ $mcp_consumer: 'request-consumer',+ mcp_vendor_client: 'ClaudeAI',+ })+ })++ it('initialize with no session context and no live value stays undefined', async () => {+ const state = makeState({+ sessionContext: null,+ requestContext: { ...makeState().requestContext, mcpClientName: undefined },+ })+ await trackInitEvent(state)++ expect(mockCaptureInitialize.mock.calls[0]![0].properties.$mcp_client_name).toBeUndefined()+ })++ it.each([+ ['$mcp_client_user_agent', 'clientUserAgent'],+ ['$mcp_transport', 'transport'],+ ['$mcp_session_id', 'mcpSessionId'],+ ['$mcp_conversation_id', 'mcpConversationId'],+ ['$mcp_mode', 'mode'],+ ['$mcp_region', 'region'],+ ] as const)(+ '%s is per-request only: it stays undefined even when the live request has none, regardless of session context',+ async (eventProp, contextField) => {+ const state = makeState({+ requestContext: { ...makeState().requestContext, [contextField]: undefined },+ })+ await trackToolCall('user-get', 12, false, state)++ expect(mockCaptureToolCall.mock.calls[0]![0].properties[eventProp]).toBeUndefined()+ }+ )++ it('mcp_runtime is a static constant, unaffected by request or session context', async () => {+ await trackToolCall('user-get', 12, false, makeState())++ expect(mockCaptureToolCall.mock.calls[0]![0].properties.mcp_runtime).toBe('hono')+ })+ })+it('stamps $mcp_tool_category and $mcp_tool_description from the catalogued tool definition', async () => {await trackToolCall('query-logs', 5, false, makeState())