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.

feat(mcp-analytics): show a tool's share of calls and sessions (#106038)

Lucas Fariaa9ecca8c139a
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index fe758b4998f0..6f9094a2a952 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10384,6 +10384,18 @@ snapshots:
hash: v1.k794b7964.b33c74ffb5531cf86afcd5fa718200c83a0863450ca85a5c94d026264f81dc4c.awlyXScQ759I0zP7I5rQA8PEIunmftZStWnJ90q-tpw
scenes-app-mcp-analytics-notification-types-table--nothing-set-up--light:
hash: v1.k794b7964.d0cb2086e12994284977aa2d895e1214c0261d2505022d9df4aef0d15c6562c6.fKwM2EVKz22cubQjamzL4YJN2CWRvtdpvYIifmijXtA
+ scenes-app-mcp-analytics-tool-detail--tool-detail--medium--dark:
+ hash: v1.k794b7964.e58395cb8a2827fc6dc6f95a7758eee7e72d0ee902de43db257a2e53012e1b0b.zQ8oyEjDSPkbT4yXup07uT_zvITN1oMbJzAJFp-7vIA
+ scenes-app-mcp-analytics-tool-detail--tool-detail--medium--light:
+ hash: v1.k794b7964.ecbcffe340418fdb5a281cce408ffab725ea1566f2c5b6bb570c6835f3f17fcf.uoJ3Spy9KCqXxZ3l-9Fz1p9yHNuxnOl8efYY9EJqZvg
+ scenes-app-mcp-analytics-tool-detail--tool-detail--narrow--dark:
+ hash: v1.k794b7964.d86efef4af126caf22ff4c5918d7bfa25ecfda0c1063bf9fd859f6c4c4f246a3.jJ52LeAW-6WxLZAgwJKoSe8we01xh-svaIN1Q0-v8KQ
+ scenes-app-mcp-analytics-tool-detail--tool-detail--narrow--light:
+ hash: v1.k794b7964.95d48e2e2ffb0606c6b3a6df79e7d03073e4d936edc534de726abad8c8391f6a.3g0HZ5-M6X0bR86EIhbcS1naeNLsF-zVDeJQ-uWzjak
+ scenes-app-mcp-analytics-tool-detail--tool-detail--wide--dark:
+ hash: v1.k794b7964.0361c34a529e803a7a6b105aa981cb722b3143a3797f7088ea4de681b61cb801.kmXMUjJP2l5EFrzAtPuRgh5EWGDe1NOzmi4Q10fYl3g
+ scenes-app-mcp-analytics-tool-detail--tool-detail--wide--light:
+ hash: v1.k794b7964.1af359c865f9532909208363f5d283c56b2c8843780882f15f85ca0fd4a749de.Y9NfRtIffh0rVjYnf5fMiWL0pVlTpGbtAFQB0QEhVJg
scenes-app-mcp-analytics-tool-quality-charts--in-progress-bucket--dark:
hash: v1.k794b7964.6dd3665d59b7590cdbba24e83fb952ffc45f74dc15e5811b5bfe004af314ead6.sGmDMl0-TraAucPmgpjftNcfxWrhDZXgFgxRNVUFp1Y
scenes-app-mcp-analytics-tool-quality-charts--in-progress-bucket--light:
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index c9a8ad77829b..a3de9e9639e5 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -31761,6 +31761,10 @@
"description": "Customer-facing harness label, e.g. \"Claude Agent SDK\", \"OpenAI Codex\", \"Cursor\", \"Other\".",
"type": "string"
},
+ "harness_sessions": {
+ "$ref": "#/definitions/integer",
+ "description": "Distinct sessions in this harness across all tools, in the same window and filters. The denominator for the tool's session share within the harness. Set only when the query has toolName."
+ },
"sessions": {
"$ref": "#/definitions/integer"
},
@@ -33923,6 +33927,14 @@
"p95_ms": {
"type": ["number", "null"]
},
+ "total_calls": {
+ "$ref": "#/definitions/integer",
+ "description": "Calls to any tool in the same window and filters. The denominator for the tool's call share."
+ },
+ "total_conversations": {
+ "$ref": "#/definitions/integer",
+ "description": "Conversations with a call to any tool in the same window and filters. The denominator for the tool's session share."
+ },
"users": {
"$ref": "#/definitions/integer"
},
@@ -33931,7 +33943,17 @@
"description": "Calls carrying a non-empty intent payload; the coverage denominator is `calls`."
}
},
- "required": ["calls", "errors", "p50_ms", "p95_ms", "users", "conversations", "with_intent"],
+ "required": [
+ "calls",
+ "errors",
+ "p50_ms",
+ "p95_ms",
+ "users",
+ "conversations",
+ "with_intent",
+ "total_calls",
+ "total_conversations"
+ ],
"type": "object"
},
"MCPToolStatsQuery": {
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 14ed7b7f39b4..6f75d289560b 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -3518,6 +3518,8 @@ export interface MCPHarnessBreakdownItem {
errors: integer
error_rate_pct: number
sessions: integer
+ /** Distinct sessions in this harness across all tools, in the same window and filters. The denominator for the tool's session share within the harness. Set only when the query has toolName. */
+ harness_sessions?: integer
}
export interface MCPHarnessBreakdownQueryResponse extends AnalyticsQueryResponseBase {
@@ -3676,6 +3678,10 @@ export interface MCPToolStatsItem {
conversations: integer
/** Calls carrying a non-empty intent payload; the coverage denominator is `calls`. */
with_intent: integer
+ /** Calls to any tool in the same window and filters. The denominator for the tool's call share. */
+ total_calls: integer
+ /** Conversations with a call to any tool in the same window and filters. The denominator for the tool's session share. */
+ total_conversations: integer
}
export interface MCPToolStatsQueryResponse extends AnalyticsQueryResponseBase {
diff --git a/posthog/schema.py b/posthog/schema.py
index 696be586eab1..5a584b0631a0 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -5955,6 +5955,14 @@ class MCPHarnessBreakdownItem(BaseModel):
...,
description=('Customer-facing harness label, e.g. "Claude Agent SDK", "OpenAI Codex", "Cursor", "Other".'),
)
+ harness_sessions: int | None = Field(
+ default=None,
+ description=(
+ "Distinct sessions in this harness across all tools, in the same window and"
+ " filters. The denominator for the tool's session share within the harness."
+ " Set only when the query has toolName."
+ ),
+ )
sessions: int
total_calls: int
@@ -6096,6 +6104,17 @@ class MCPToolStatsItem(BaseModel):
errors: int
p50_ms: float | None = None
p95_ms: float | None = None
+ total_calls: int = Field(
+ ...,
+ description=("Calls to any tool in the same window and filters. The denominator for the tool's call share."),
+ )
+ total_conversations: int = Field(
+ ...,
+ description=(
+ "Conversations with a call to any tool in the same window and filters. The"
+ " denominator for the tool's session share."
+ ),
+ )
users: int
with_intent: int = Field(
...,
diff --git a/products/mcp_analytics/backend/hogql_queries/base.py b/products/mcp_analytics/backend/hogql_queries/base.py
index 1a165649e935..fa199a685320 100644
--- a/products/mcp_analytics/backend/hogql_queries/base.py
+++ b/products/mcp_analytics/backend/hogql_queries/base.py
@@ -41,22 +41,39 @@ EFFECTIVE_DESCRIPTION_SQL = (
"coalesce(nullIf(toString(properties.$mcp_exec_tool_call_description), ''), "
"toString(properties.$mcp_tool_description))"
)
+# One MCP conversation: the SDK's own session id, falling back to the PostHog session id.
+CONVERSATION_ID_SQL = "coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id))"
# Marker the posthog-node MCP analytics SDK stamps on the events it sends.
NEW_SDK_SOURCE = "posthog_mcp_analytics"
+def mcp_source_expr() -> ast.Expr:
+ """The `$mcp_source = NEW_SDK_SOURCE` predicate alone, without the tool-name predicate.
+
+ Used where a query must scan every tool's new-SDK calls (e.g. a share denominator)
+ instead of scoping to one effective tool.
+ """
+ return parse_expr("properties.$mcp_source = {source}", placeholders={"source": ast.Constant(value=NEW_SDK_SOURCE)})
+
+
+def effective_tool_expr(tool: str) -> ast.Expr:
+ """The effective-tool equality predicate alone, bound as ast.Constant.
+
+ Used to materialize a per-row boolean column so one scan can produce both a
+ tool-scoped aggregate and an all-tools total in the same query.
+ """
+ return parse_expr(
+ "{EFFECTIVE_TOOL_SQL} = {tool}",
+ placeholders={"EFFECTIVE_TOOL_SQL": parse_expr(EFFECTIVE_TOOL_SQL), "tool": ast.Constant(value=tool)},
+ )
+
+
def tool_scope_exprs(tool: str) -> list[ast.Expr]:
"""Predicates scoping new-SDK $mcp_tool_call events to one effective tool.
`tool` is bound as an ast.Constant, never string-interpolated.
"""
- return [
- parse_expr(
- "{EFFECTIVE_TOOL_SQL} = {tool}",
- placeholders={"EFFECTIVE_TOOL_SQL": parse_expr(EFFECTIVE_TOOL_SQL), "tool": ast.Constant(value=tool)},
- ),
- parse_expr("properties.$mcp_source = {source}", placeholders={"source": ast.Constant(value=NEW_SDK_SOURCE)}),
- ]
+ return [effective_tool_expr(tool), mcp_source_expr()]
def shared_filter_exprs(
diff --git a/products/mcp_analytics/backend/hogql_queries/harness_breakdown.py b/products/mcp_analytics/backend/hogql_queries/harness_breakdown.py
index 25846feccffb..346acd91c69b 100644
--- a/products/mcp_analytics/backend/hogql_queries/harness_breakdown.py
+++ b/products/mcp_analytics/backend/hogql_queries/harness_breakdown.py
@@ -19,9 +19,11 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from products.mcp_analytics.backend import mcp_harness
from products.mcp_analytics.backend.constants import MCP_TOOL_CALL_EVENT
from products.mcp_analytics.backend.hogql_queries.base import (
+ CONVERSATION_ID_SQL,
+ effective_tool_expr,
mcp_query_date_range,
+ mcp_source_expr,
shared_filter_exprs,
- tool_scope_exprs,
validate_mcp_analytics_access,
)
@@ -49,22 +51,67 @@ class MCPHarnessBreakdownQueryRunner(AnalyticsQueryRunner[MCPHarnessBreakdownQue
def query_date_range(self) -> QueryDateRange:
return mcp_query_date_range(self.team, self.query.dateRange)
- def _where(self) -> ast.Expr:
- exprs: list[ast.Expr] = [
+ def _base_exprs(self) -> list[ast.Expr]:
+ return [
parse_expr("event = {event}", placeholders={"event": ast.Constant(value=MCP_TOOL_CALL_EVENT)}),
parse_expr(
"timestamp >= {date_from}", placeholders={"date_from": self.query_date_range.date_from_as_hogql()}
),
parse_expr("timestamp <= {date_to}", placeholders={"date_to": self.query_date_range.date_to_as_hogql()}),
]
- if self.query.toolName:
- exprs.extend(tool_scope_exprs(self.query.toolName))
- exprs.extend(shared_filter_exprs(self.team, self.query.properties, self.query.filterTestAccounts))
+
+ def _where(self) -> ast.Expr:
+ exprs = [
+ *self._base_exprs(),
+ *shared_filter_exprs(self.team, self.query.properties, self.query.filterTestAccounts),
+ ]
+ return ast.And(exprs=exprs)
+
+ def _where_scoped_to_source(self) -> ast.Expr:
+ # Scoped to the new-SDK source but not to one effective tool, so the outer query
+ # can compute this tool's own aggregates via `is_tool` alongside the harness's
+ # all-tool session total (the session-share denominator) in a single scan.
+ exprs = [
+ *self._base_exprs(),
+ mcp_source_expr(),
+ *shared_filter_exprs(self.team, self.query.properties, self.query.filterTestAccounts),
+ ]
return ast.And(exprs=exprs)
def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:
# The harness label and token are HogQL fragments from mcp_harness; parse them
# to AST and inject as placeholders (like {where}) so nothing is string-interpolated.
+ if self.query.toolName:
+ return parse_select(
+ """
+ SELECT
+ {label} AS harness,
+ countIf(is_tool) AS total_calls,
+ countIf(is_tool AND is_error) AS errors,
+ round(countIf(is_tool AND is_error) * 100.0 / countIf(is_tool), 1) AS error_rate_pct,
+ countDistinctIf(session_id, session_id != '' AND is_tool) AS sessions,
+ countDistinctIf(session_id, session_id != '') AS harness_sessions
+ FROM (
+ SELECT
+ {token} AS h,
+ {conversation_id} AS session_id,
+ toBool(properties.$mcp_is_error) AS is_error,
+ {is_tool} AS is_tool
+ FROM events
+ WHERE {where}
+ )
+ GROUP BY harness
+ HAVING countIf(is_tool) > 0
+ ORDER BY total_calls DESC
+ """,
+ placeholders={
+ "label": parse_expr(mcp_harness.harness_label_sql("h")),
+ "token": parse_expr(mcp_harness.HARNESS_TOKEN_SQL),
+ "is_tool": effective_tool_expr(self.query.toolName),
+ "conversation_id": parse_expr(CONVERSATION_ID_SQL),
+ "where": self._where_scoped_to_source(),
+ },
+ )
return parse_select(
"""
SELECT
@@ -76,7 +123,7 @@ class MCPHarnessBreakdownQueryRunner(AnalyticsQueryRunner[MCPHarnessBreakdownQue
FROM (
SELECT
{token} AS h,
- $session_id AS session_id,
+ {conversation_id} AS session_id,
toBool(properties.$mcp_is_error) AS is_error
FROM events
WHERE {where}
@@ -87,6 +134,7 @@ class MCPHarnessBreakdownQueryRunner(AnalyticsQueryRunner[MCPHarnessBreakdownQue
placeholders={
"label": parse_expr(mcp_harness.harness_label_sql("h")),
"token": parse_expr(mcp_harness.HARNESS_TOKEN_SQL),
+ "conversation_id": parse_expr(CONVERSATION_ID_SQL),
"where": self._where(),
},
)
@@ -115,6 +163,7 @@ class MCPHarnessBreakdownQueryRunner(AnalyticsQueryRunner[MCPHarnessBreakdownQue
errors=int(row[2] or 0),
error_rate_pct=float(row[3] or 0),
sessions=int(row[4] or 0),
+ harness_sessions=int(row[5] or 0) if self.query.toolName else None,
)
for row in (response.results or [])
]
diff --git a/products/mcp_analytics/backend/hogql_queries/missing_capabilities.py b/products/mcp_analytics/backend/hogql_queries/missing_capabilities.py
index f63f4274b98f..af85895732d8 100644
--- a/products/mcp_analytics/backend/hogql_queries/missing_capabilities.py
+++ b/products/mcp_analytics/backend/hogql_queries/missing_capabilities.py
@@ -29,6 +29,7 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from products.mcp_analytics.backend import mcp_harness
from products.mcp_analytics.backend.constants import MCP_MISSING_CAPABILITY_EVENT
from products.mcp_analytics.backend.hogql_queries.base import (
+ CONVERSATION_ID_SQL,
display_person_properties,
mcp_query_date_range,
validate_mcp_analytics_access,
@@ -44,10 +45,6 @@ MAX_LIMIT = 500
# Both the result column and search expression use this property so they cannot drift.
_REPORT_TEXT = "toString(properties.$mcp_intent)"
-# Conversation id, same resolution as the tool-call surfaces: the SDK's own
-# $mcp_session_id when set, else the ambient $session_id.
-_CONVERSATION_ID = "coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id))"
-
class MCPMissingCapabilitiesQueryRunner(AnalyticsQueryRunner[MCPMissingCapabilitiesQueryResponse]):
"""Chronological feed of the capabilities agents asked for and could not get.
@@ -139,7 +136,7 @@ class MCPMissingCapabilitiesQueryRunner(AnalyticsQueryRunner[MCPMissingCapabilit
"token": parse_expr(mcp_harness.HARNESS_TOKEN_SQL),
"display_name": parse_expr(mcp_harness.HARNESS_DISPLAY_NAME_SQL),
"report_text": parse_expr(_REPORT_TEXT),
- "conversation_id": parse_expr(_CONVERSATION_ID),
+ "conversation_id": parse_expr(CONVERSATION_ID_SQL),
"where": self._where(),
# Over-fetch one row to detect the next page without a separate count query.
"limit": ast.Constant(value=self.limit + 1),
diff --git a/products/mcp_analytics/backend/hogql_queries/tool_tables.py b/products/mcp_analytics/backend/hogql_queries/tool_tables.py
index 087a0f553962..49a89a8715b8 100644
--- a/products/mcp_analytics/backend/hogql_queries/tool_tables.py
+++ b/products/mcp_analytics/backend/hogql_queries/tool_tables.py
@@ -55,11 +55,14 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from products.mcp_analytics.backend import mcp_harness
from products.mcp_analytics.backend.constants import MCP_TOOL_CALL_EVENT
from products.mcp_analytics.backend.hogql_queries.base import (
+ CONVERSATION_ID_SQL,
EFFECTIVE_DESCRIPTION_SQL,
EFFECTIVE_TOOL_SQL,
NEW_SDK_SOURCE,
display_person_properties,
+ effective_tool_expr,
mcp_query_date_range,
+ mcp_source_expr,
shared_filter_exprs,
tool_scope_exprs,
validate_mcp_analytics_access,
@@ -109,18 +112,20 @@ def _tool_call_where(
date_range: QueryDateRange,
team: "Team",
*,
+ scope_to_tool: bool = True,
extra: list[ast.Expr] | None = None,
) -> ast.Expr:
"""WHERE for new-SDK $mcp_tool_call events scoped to one effective tool and window.
- The tool name is bound as an ast.Constant, never interpolated. `extra` appends
- query-specific predicates (e.g. notEmpty(description)).
+ The tool name is bound as an ast.Constant, never interpolated. `scope_to_tool=False` keeps
+ every tool's calls, for queries that mark this tool with a column to compute its share.
+ `extra` appends query-specific predicates (e.g. notEmpty(description)).
"""
exprs: list[ast.Expr] = [
parse_expr("event = {event}", placeholders={"event": ast.Constant(value=MCP_TOOL_CALL_EVENT)}),
parse_expr("timestamp >= {date_from}", placeholders={"date_from": date_range.date_from_as_hogql()}),
parse_expr("timestamp <= {date_to}", placeholders={"date_to": date_range.date_to_as_hogql()}),
- *tool_scope_exprs(query.toolName),
+ *(tool_scope_exprs(query.toolName) if scope_to_tool else [mcp_source_expr()]),
*shared_filter_exprs(team, query.properties, query.filterTestAccounts),
]
if extra:
@@ -305,8 +310,6 @@ class MCPToolFailuresQueryRunner(AnalyticsQueryRunner[MCPToolFailuresQueryRespon
)
-_CONVERSATION_ID = "coalesce(nullIf(toString(properties.$mcp_session_id), ''), toString(properties.$session_id))"
-
# Mirrors the capture-side MAX_ERROR_MESSAGE_LENGTH (services/mcp); event-supplied, so
# re-capped here in case a non-PostHog server emits an unbounded value.
_ERROR_MESSAGE = "substring(coalesce(toString(properties.$mcp_error_message), ''), 1, 2048)"
@@ -379,7 +382,7 @@ class MCPToolFailureOccurrencesQueryRunner(AnalyticsQueryRunner[MCPToolFailureOc
""",
placeholders={
"harness_label": parse_expr(mcp_harness.harness_label_sql("h")),
- "_CONVERSATION_ID": parse_expr(_CONVERSATION_ID),
+ "_CONVERSATION_ID": parse_expr(CONVERSATION_ID_SQL),
"_ERROR_MESSAGE": parse_expr(_ERROR_MESSAGE),
"_RAW_ERROR_STATUS": parse_expr(_RAW_ERROR_STATUS),
"token": parse_expr(mcp_harness.HARNESS_TOKEN_SQL),
@@ -444,22 +447,31 @@ class MCPToolStatsQueryRunner(AnalyticsQueryRunner[MCPToolStatsQueryResponse]):
return parse_select(
"""
SELECT
- count() AS calls,
- {_IS_ERROR} AS errors,
- {_P50} AS p50_ms,
- {_P95} AS p95_ms,
- uniq(distinct_id) AS users,
- uniq({_CONVERSATION_ID}) AS conversations,
- countIf(notEmpty(toString(properties.$mcp_intent)) AND toString(properties.$mcp_intent) != '{}') AS with_intent
- FROM events
- WHERE {where}
+ countIf(is_tool) AS calls,
+ countIf(is_tool AND is_error) AS errors,
+ round(quantileIf(0.5)(duration_ms, is_tool)) AS p50_ms,
+ round(quantileIf(0.95)(duration_ms, is_tool)) AS p95_ms,
+ uniqIf(distinct_id, is_tool) AS users,
+ uniqIf(conversation_id, is_tool) AS conversations,
+ countIf(is_tool AND has_intent) AS with_intent,
+ count() AS total_calls,
+ uniq(conversation_id) AS total_conversations
+ FROM (
+ SELECT
+ distinct_id,
+ nullIf({_CONVERSATION_ID}, '') AS conversation_id,
+ toBool(properties.$mcp_is_error) AS is_error,
+ toFloat(properties.$mcp_duration_ms) AS duration_ms,
+ notEmpty(toString(properties.$mcp_intent)) AND toString(properties.$mcp_intent) != '{}' AS has_intent,
+ {is_tool} AS is_tool
+ FROM events
+ WHERE {where}
+ )
""",
placeholders={
- "_CONVERSATION_ID": parse_expr(_CONVERSATION_ID),
- "_IS_ERROR": parse_expr(_IS_ERROR),
- "_P50": parse_expr(_P50),
- "_P95": parse_expr(_P95),
- "where": _tool_call_where(self.query, self.query_date_range, self.team),
+ "_CONVERSATION_ID": parse_expr(CONVERSATION_ID_SQL),
+ "is_tool": effective_tool_expr(self.query.toolName),
+ "where": _tool_call_where(self.query, self.query_date_range, self.team, scope_to_tool=False),
},
)
@@ -490,6 +502,8 @@ class MCPToolStatsQueryRunner(AnalyticsQueryRunner[MCPToolStatsQueryResponse]):
users=int(row[4] or 0),
conversations=int(row[5] or 0),
with_intent=int(row[6] or 0),
+ total_calls=int(row[7] or 0),
+ total_conversations=int(row[8] or 0),
)
]
if row and int(row[0] or 0) > 0
@@ -531,7 +545,7 @@ class MCPToolDailyStatsQueryRunner(AnalyticsQueryRunner[MCPToolDailyStatsQueryRe
{_P50} AS p50,
{_P95} AS p95,
uniq(distinct_id) AS users,
- uniq({_CONVERSATION_ID}) AS sessions
+ uniq(nullIf({_CONVERSATION_ID}, '')) AS sessions
FROM events
WHERE {where}
GROUP BY day
@@ -540,7 +554,7 @@ class MCPToolDailyStatsQueryRunner(AnalyticsQueryRunner[MCPToolDailyStatsQueryRe
""",
placeholders={
"interval": ast.Constant(value=interval),
- "_CONVERSATION_ID": parse_expr(_CONVERSATION_ID),
+ "_CONVERSATION_ID": parse_expr(CONVERSATION_ID_SQL),
"_IS_ERROR": parse_expr(_IS_ERROR),
"_P50": parse_expr(_P50),
"_P95": parse_expr(_P95),
@@ -767,7 +781,7 @@ class MCPToolNeighborsQueryRunner(AnalyticsQueryRunner[MCPToolNeighborsQueryResp
parse_expr(
"properties.$mcp_source = {source}", placeholders={"source": ast.Constant(value=NEW_SDK_SOURCE)}
),
- parse_expr("notEmpty({conv_id})", placeholders={"conv_id": parse_expr(_CONVERSATION_ID)}),
+ parse_expr("notEmpty({conv_id})", placeholders={"conv_id": parse_expr(CONVERSATION_ID_SQL)}),
# In the CTE so a filtered-out call cannot count as a neighbour either.
*shared_filter_exprs(self.team, self.query.properties, self.query.filterTestAccounts),
]
@@ -795,7 +809,7 @@ class MCPToolNeighborsQueryRunner(AnalyticsQueryRunner[MCPToolNeighborsQueryResp
LIMIT 5
""",
placeholders={
- "_CONVERSATION_ID": parse_expr(_CONVERSATION_ID),
+ "_CONVERSATION_ID": parse_expr(CONVERSATION_ID_SQL),
"effective_tool": parse_expr(EFFECTIVE_TOOL_SQL),
"neighbor_expr": parse_expr(neighbor_expr),
"cte_where": cte_where,
diff --git a/products/mcp_analytics/backend/tests/test_harness_breakdown.py b/products/mcp_analytics/backend/tests/test_harness_breakdown.py
index 18252fe222ef..bd0ffdc1c0af 100644
--- a/products/mcp_analytics/backend/tests/test_harness_breakdown.py
+++ b/products/mcp_analytics/backend/tests/test_harness_breakdown.py
@@ -246,3 +246,63 @@ class TestMCPHarnessBreakdownQueryRunner(_MCPAnalyticsTeamScopedTestMixin, Click
assert "OpenAI Codex" in by_harness
assert "Cursor" not in by_harness
+
+ @parameterized.expand([("posthog_session_id", "$session_id"), ("mcp_session_id", "$mcp_session_id")])
+ def test_sessions_count_either_session_id_without_tool_name(self, _name: str, session_key: str) -> None:
+ self._emit(session_id="", properties={"$mcp_client_name": "codex-mcp-client", session_key: "a"})
+ flush_persons_and_events()
+
+ assert self._breakdown()["OpenAI Codex"].sessions == 1
+
+ def test_harness_sessions_is_none_when_tool_name_unset(self) -> None:
+ self._emit(properties={"$mcp_client_name": "codex-mcp-client"})
+ flush_persons_and_events()
+
+ row = self._breakdown()["OpenAI Codex"]
+
+ assert row.harness_sessions is None
+
+ @parameterized.expand([("posthog_session_id", "$session_id"), ("mcp_session_id", "$mcp_session_id")])
+ def test_harness_sessions_counts_all_tools_when_tool_name_set(self, _name: str, session_key: str) -> None:
+ new_sdk = {"$mcp_source": "posthog_mcp_analytics"}
+ self._emit(
+ distinct_id="d1",
+ session_id="",
+ properties={"$mcp_client_name": "codex-mcp-client", session_key: "a", **new_sdk},
+ )
+ # A different tool, same harness, different session: counts toward harness_sessions
+ # but not toward this tool's own `sessions`.
+ self._emit(
+ distinct_id="d2",
+ session_id="",
+ properties={
+ "$mcp_tool_name": "other_tool",
+ "$mcp_client_name": "codex-mcp-client",
+ session_key: "b",
+ **new_sdk,
+ },
+ )
+ flush_persons_and_events()
+
+ runner = MCPHarnessBreakdownQueryRunner(
+ query=MCPHarnessBreakdownQuery(dateRange=DateRange(date_from="-90d"), toolName="query_run"),
+ team=self.team,
+ )
+ row = {row.harness: row for row in runner.calculate().results}["OpenAI Codex"]
+
+ assert row.sessions == 1
+ assert row.harness_sessions == 2
+
+ def test_harness_omitted_when_tool_never_ran_there_but_shown_without_tool_name(self) -> None:
+ new_sdk = {"$mcp_source": "posthog_mcp_analytics"}
+ self._emit(
+ properties={"$mcp_tool_name": "other_tool", "$mcp_client_name": "codex-mcp-client", **new_sdk},
+ )
+ flush_persons_and_events()
+
+ runner = MCPHarnessBreakdownQueryRunner(
+ query=MCPHarnessBreakdownQuery(dateRange=DateRange(date_from="-90d"), toolName="query_run"),
+ team=self.team,
+ )
+ assert "OpenAI Codex" not in {row.harness for row in runner.calculate().results}
+ assert "OpenAI Codex" in self._breakdown()
diff --git a/products/mcp_analytics/backend/tests/test_tool_tables.py b/products/mcp_analytics/backend/tests/test_tool_tables.py
index 3243ea926c58..39a35b8581c2 100644
--- a/products/mcp_analytics/backend/tests/test_tool_tables.py
+++ b/products/mcp_analytics/backend/tests/test_tool_tables.py
@@ -480,6 +480,50 @@ class TestMCPToolStatsQueryRunner(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTe
assert self._run() == []
+ def test_totals_include_other_tools_calls_and_sessions(self) -> None:
+ _emit_tool_call(self.team, distinct_id="d1", session_id="s1")
+ _emit_tool_call(self.team, distinct_id="d1", session_id="s1")
+ _emit_tool_call(self.team, distinct_id="d2", tool_name="other", session_id="s2")
+ _emit_tool_call(self.team, distinct_id="d2", tool_name="other", session_id="s2")
+ _emit_tool_call(self.team, distinct_id="d3", tool_name="other")
+ flush_persons_and_events()
+
+ row = self._run()[0]
+
+ assert row.calls == 2
+ assert row.conversations == 1
+ assert row.total_calls == 5
+ # The call without any session id adds a call but no conversation.
+ assert row.total_conversations == 2
+
+ def test_shared_property_filter_narrows_totals_not_just_this_tool(self) -> None:
+ _emit_tool_call(self.team, distinct_id="d1", session_id="s1", client_name="claude-ai")
+ _emit_tool_call(self.team, distinct_id="d2", tool_name="other", session_id="s2", client_name="claude-ai")
+ _emit_tool_call(self.team, distinct_id="d3", tool_name="other", session_id="s3", client_name="cursor-vscode")
+ flush_persons_and_events()
+
+ runner = MCPToolStatsQueryRunner(
+ query=MCPToolStatsQuery(
+ toolName="query_run",
+ dateRange=DateRange(date_from="-7d"),
+ properties=[
+ EventPropertyFilter(key="$mcp_client_name", value=["claude-ai"], operator=PropertyOperator.EXACT)
+ ],
+ ),
+ team=self.team,
+ )
+ row = runner.calculate().results[0]
+
+ # The cursor-vscode event is excluded from the total, not just from this tool's own numbers.
+ assert row.total_calls == 2
+ assert row.total_conversations == 2
+
+ def test_empty_when_no_calls_for_this_tool_even_if_other_tools_have_calls(self) -> None:
+ _emit_tool_call(self.team, distinct_id="d1", tool_name="other")
+ flush_persons_and_events()
+
+ assert self._run("query_run") == []
+
class TestMCPToolDailyStatsQueryRunner(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):
def _run(self, tool_name: str = "query_run") -> list[Any]:
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.stories.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.stories.tsx
new file mode 100644
index 000000000000..3fe597f0401e
--- /dev/null
+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.stories.tsx
@@ -0,0 +1,191 @@
+import { MOCK_DEFAULT_USER } from '~/lib/api.mock'
+
+import { Meta, StoryObj } from '@storybook/react'
+
+import { App } from 'scenes/App'
+import { urls } from 'scenes/urls'
+
+import { mswDecorator } from '~/mocks/browser'
+
+const TOOL_NAME = 'execute-sql'
+
+// This tool's share of all MCP activity in the window: enough calls and sessions to exercise the
+// call-share and session-share subtitles on the Calls and Sessions tiles with a realistic percentage.
+const STATS = {
+ calls: 5563,
+ errors: 214,
+ p50_ms: 820,
+ p95_ms: 3525,
+ users: 412,
+ conversations: 3959,
+ with_intent: 4890,
+ total_calls: 13500000,
+ total_conversations: 60000,
+}
+
+const DESCRIPTIONS = [
+ {
+ description: 'Run a ClickHouse SQL query against events, persons, and warehouse tables.',
+ last_seen: '2026-06-07T10:04:00Z',
+ },
+ { description: 'Run a SQL query against the project.', last_seen: '2026-05-20T09:00:00Z' },
+]
+
+const DAILY_STATS = [
+ { day: '2026-06-01', calls: 720, errors: 28, p50: 780, p95: 3300, users: 90, sessions: 540 },
+ { day: '2026-06-02', calls: 760, errors: 31, p50: 800, p95: 3400, users: 95, sessions: 560 },
+ { day: '2026-06-03', calls: 745, errors: 24, p50: 790, p95: 3350, users: 92, sessions: 555 },
+ { day: '2026-06-04', calls: 810, errors: 36, p50: 850, p95: 3600, users: 101, sessions: 590 },
+ { day: '2026-06-05', calls: 790, errors: 30, p50: 830, p95: 3500, users: 98, sessions: 575 },
+ { day: '2026-06-06', calls: 830, errors: 33, p50: 840, p95: 3550, users: 104, sessions: 600 },
+ { day: '2026-06-07', calls: 908, errors: 32, p50: 860, p95: 3700, users: 110, sessions: 620 },
+]
+
+const SAMPLE_INTENTS = [
+ {
+ timestamp: '2026-06-07T10:04:42Z',
+ intent: 'Retry the tuned query with a shorter time range.',
+ intent_source: 'context_parameter',
+ harness: 'Claude Code',
+ },
+ {
+ timestamp: '2026-06-07T09:41:10Z',
+ intent: 'Break down tool errors by client to find which harness fails most.',
+ intent_source: 'inferred',
+ harness: 'Cursor',
+ },
+ {
+ timestamp: '2026-06-07T08:15:00Z',
+ intent: 'Corroborate homepage INP p75 with its actual seven-day sample count.',
+ intent_source: 'context_parameter',
+ harness: 'Claude Code',
+ },
+]
+
+const NEIGHBORS_BEFORE = [
+ { neighbor_tool: 'read-data-schema', co_occurrences: 2840 },
+ { neighbor_tool: 'exec', co_occurrences: 610 },
+]
+
+const NEIGHBORS_AFTER = [
+ { neighbor_tool: 'insight-create', co_occurrences: 1120 },
+ { neighbor_tool: 'dashboard-create', co_occurrences: 340 },
+]
+
+// Session share on the "By harness" table: this tool's sessions within the harness, out of the
+// harness's total sessions across all tools, spanning a high, mid, and low share.
+const BY_HARNESS = [
+ {
+ harness: 'PostHog AI',
+ total_calls: 3100,
+ errors: 98,
+ error_rate_pct: 3.2,
+ sessions: 1200,
+ harness_sessions: 1480,
+ },
+ { harness: 'Slack', total_calls: 1680, errors: 74, error_rate_pct: 4.4, sessions: 800, harness_sessions: 1600 },
+ { harness: 'Claude Code', total_calls: 783, errors: 42, error_rate_pct: 5.4, sessions: 50, harness_sessions: 9000 },
+]
+
+const TOP_USERS = [
+ {
+ distinct_id: 'user-1-distinct-id',
+ person_properties: JSON.stringify({ email: '[email protected]', name: 'Annika Hansen' }),
+ calls: 890,
+ errors: 22,
+ error_rate_pct: 2.5,
+ harnesses: ['PostHog AI', 'Claude Code'],
+ last_seen: '2026-06-07T10:04:00Z',
+ },
+ {
+ distinct_id: 'user-2-distinct-id',
+ person_properties: JSON.stringify({ email: '[email protected]' }),
+ calls: 640,
+ errors: 41,
+ error_rate_pct: 6.4,
+ harnesses: ['Slack'],
+ last_seen: '2026-06-06T18:20:00Z',
+ },
+]
+
+const FAILURE_BUCKETS = [
+ {
+ message: 'api_5xx (HTTP 500)',
+ error_type: 'api_5xx',
+ error_status: '500',
+ occurrences: 96,
+ last_seen: '2026-06-07T09:41:10Z',
+ harnesses: ['PostHog AI', 'Slack'],
+ },
+ {
+ message: 'timeout',
+ error_type: 'timeout',
+ error_status: '',
+ occurrences: 54,
+ last_seen: '2026-06-06T22:10:00Z',
+ harnesses: ['Claude Code'],
+ },
+]
+
+interface MockQueryBody {
+ query?: { kind?: string; neighborDirection?: 'before' | 'after' }
+}
+
+const meta: Meta = {
+ component: App,
+ title: 'Scenes-App/MCP Analytics/Tool Detail',
+ decorators: [
+ (Story, context) =>
+ mswDecorator({
+ get: { '/api/users/@me/': { ...MOCK_DEFAULT_USER, theme_mode: context.globals.theme ?? 'light' } },
+ })(Story, context),
+ mswDecorator({
+ post: {
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as MockQueryBody
+ switch (body?.query?.kind) {
+ case 'MCPToolStatsQuery':
+ return [200, { results: [STATS] }]
+ case 'MCPToolDescriptionsQuery':
+ return [200, { results: DESCRIPTIONS }]
+ case 'MCPToolDailyStatsQuery':
+ return [200, { results: DAILY_STATS }]
+ case 'MCPToolSampleIntentsQuery':
+ return [200, { results: SAMPLE_INTENTS }]
+ case 'MCPToolNeighborsQuery':
+ return [
+ 200,
+ {
+ results:
+ body.query.neighborDirection === 'before' ? NEIGHBORS_BEFORE : NEIGHBORS_AFTER,
+ },
+ ]
+ case 'MCPHarnessBreakdownQuery':
+ return [200, { results: BY_HARNESS }]
+ case 'MCPToolTopUsersQuery':
+ return [200, { results: TOP_USERS }]
+ case 'MCPToolFailuresQuery':
+ return [200, { results: FAILURE_BUCKETS }]
+ case 'MCPToolFailureOccurrencesQuery':
+ return [200, { results: [] }]
+ default:
+ return [200, { results: [] }]
+ }
+ },
+ },
+ }),
+ ],
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ mockDate: '2026-06-07T12:00:00Z',
+ pageUrl: urls.mcpAnalyticsTool(TOOL_NAME),
+ },
+}
+export default meta
+
+type Story = StoryObj<{}>
+
+export const ToolDetail: Story = {
+ parameters: { testOptions: { viewportWidths: ['narrow', 'medium', 'wide'] } },
+}
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
index ed7054700028..4a9ac07004ad 100644
--- a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
@@ -31,6 +31,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { formatPercentage } from 'lib/utils/numbers'
import { teamLogic } from 'scenes/teamLogic'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
@@ -108,6 +109,9 @@ interface ResultColumn {
header: string
align?: 'left' | 'right'
expand?: boolean
+ // Applied to both the header and cell, e.g. `@max-2xl:hidden` to drop a lower-priority column
+ // once the card narrows past a container breakpoint instead of letting the table overflow it.
+ className?: string
render: (row: unknown[]) => React.ReactNode
}
@@ -137,7 +141,7 @@ function ResultTable({
onRowClick?: (rowIndex: number) => void
}): JSX.Element {
return (
- <Card size="sm" className="gap-0">
+ <Card size="sm" className="@container gap-0">
{title != null && (
<CardHeader
className={`border-b border-border pb-3${
@@ -153,7 +157,7 @@ function ResultTable({
<TableHeader>
<TableRow>
{columns.map((col, i) => (
- <TableHead key={i} align={col.align} expand={col.expand}>
+ <TableHead key={i} align={col.align} expand={col.expand} className={col.className}>
{col.header}
</TableHead>
))}
@@ -196,7 +200,7 @@ function ResultTable({
}
>
{columns.map((col, ci) => (
- <TableCell key={ci} align={col.align} expand={col.expand}>
+ <TableCell key={ci} align={col.align} expand={col.expand} className={col.className}>
{col.render(row)}
</TableCell>
))}
@@ -223,6 +227,31 @@ function spark(values: number[]): number[] {
return values.map((v) => (Number.isFinite(v) ? v : 0))
}
+// formatPercentage keeps two significant digits, so a tiny share would read like "0.00004%".
+const MIN_DISPLAYED_SHARE_PCT = 0.01
+
+// undefined when there's nothing to divide by, so the caller can fall back to the date range subtitle.
+function formatShare(part: number, total: number): string | undefined {
+ if (total === 0) {
+ return undefined
+ }
+ const pct = (part / total) * 100
+ if (pct > 0 && pct < MIN_DISPLAYED_SHARE_PCT) {
+ return `<${MIN_DISPLAYED_SHARE_PCT}%`
+ }
+ return formatPercentage(pct, { compact: true })
+}
+
+function formatCallShare(calls: number, totalCalls: number): string | undefined {
+ const share = formatShare(calls, totalCalls)
+ return share === undefined ? undefined : `${share} of all calls`
+}
+
+function formatSessionShare(sessions: number, totalSessions: number): string | undefined {
+ const share = formatShare(sessions, totalSessions)
+ return share === undefined ? undefined : `In ${share} of sessions`
+}
+
function StatTiles({
summary,
loading,
@@ -255,6 +284,7 @@ function StatTiles({
data: number[]
color: string
goodDirection: 'up' | 'down'
+ subtitle?: string
}[] = [
{
label: 'Calls',
@@ -263,6 +293,7 @@ function StatTiles({
data: spark(daily.calls),
color: theme.colors[0],
goodDirection: 'up',
+ subtitle: formatCallShare(calls, summary?.total_calls ?? 0),
},
{
label: 'Error rate',
@@ -303,6 +334,7 @@ function StatTiles({
data: spark(daily.sessions),
color: theme.colors[6],
goodDirection: 'up',
+ subtitle: formatSessionShare(summary?.conversations ?? 0, summary?.total_conversations ?? 0),
},
]
@@ -316,7 +348,7 @@ function StatTiles({
labels={daily.labels}
interval={interval}
theme={theme}
- restingSubtitle={dateRangeLabel}
+ restingSubtitle={tile.subtitle ?? dateRangeLabel}
sparklineHeight={40}
sparklineDashedFromIndex={incompleteTail ? daily.labels.length - 1 : undefined}
/>
@@ -686,14 +718,21 @@ export function MCPAnalyticsToolDetail({ toolName }: { toolName: string }): JSX.
{
header: 'Errors',
align: 'right',
+ className: '@max-2xl:hidden',
render: (r) => formatNumber(Number(r[2] ?? 0)),
},
{ header: 'Error rate', align: 'right', render: (r) => `${Number(r[3] ?? 0)}%` },
{
header: 'Sessions',
align: 'right',
+ className: '@max-2xl:hidden',
render: (r) => formatNumber(Number(r[4] ?? 0)),
},
+ {
+ header: 'Session share',
+ align: 'right',
+ render: (r) => formatShare(Number(r[4] ?? 0), Number(r[5] ?? 0)) ?? '-',
+ },
]}
/>
<ResultTable
@@ -710,6 +749,7 @@ export function MCPAnalyticsToolDetail({ toolName }: { toolName: string }): JSX.
{
header: 'Errors',
align: 'right',
+ className: '@max-2xl:hidden',
render: (r) => formatNumber(Number(r[2] ?? 0)),
},
{ header: 'Error rate', align: 'right', render: (r) => `${Number(r[3] ?? 0)}%` },
@@ -717,7 +757,11 @@ export function MCPAnalyticsToolDetail({ toolName }: { toolName: string }): JSX.
header: 'Harnesses',
render: (r) => <HarnessLogos labels={(r[4] as string[]) ?? []} />,
},
- { header: 'Last seen', render: (r) => <TZLabel time={String(r[5])} /> },
+ {
+ header: 'Last seen',
+ className: '@max-2xl:hidden',
+ render: (r) => <TZLabel time={String(r[5])} />,
+ },
]}
/>
</div>
diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
index a373887f2226..d497ca67af4e 100644
--- a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
@@ -39,6 +39,8 @@ export interface ToolSummary {
p95_ms: number | null
users: number
conversations: number
+ total_calls: number
+ total_conversations: number
}
export interface DescriptionRevision {
@@ -453,6 +455,8 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(
p95_ms: row.p95_ms,
users: row.users,
conversations: row.conversations,
+ total_calls: row.total_calls,
+ total_conversations: row.total_conversations,
}
},
},
@@ -628,6 +632,7 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(
r.errors,
r.error_rate_pct,
r.sessions,
+ r.harness_sessions ?? null,
])
},
},
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 49afb60efcc7..22c7c9076908 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -52793,6 +52793,8 @@ export namespace Schemas {
errors: number;
/** Customer-facing harness label, e.g. "Claude Agent SDK", "OpenAI Codex", "Cursor", "Other". */
harness: string;
+ /** Distinct sessions in this harness across all tools, in the same window and filters. The denominator for the tool's session share within the harness. Set only when the query has toolName. */
+ harness_sessions?: number | null;
sessions: number;
total_calls: number;
}
@@ -53043,6 +53045,10 @@ export namespace Schemas {
errors: number;
p50_ms?: number | null;
p95_ms?: number | null;
+ /** Calls to any tool in the same window and filters. The denominator for the tool's call share. */
+ total_calls: number;
+ /** Conversations with a call to any tool in the same window and filters. The denominator for the tool's session share. */
+ total_conversations: number;
users: number;
/** Calls carrying a non-empty intent payload; the coverage denominator is `calls`. */
with_intent: number;