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.

fix(mcp-analytics): source tool failures from $mcp_is_error not $exception (#70135)

Daniel Viscab0110dd7c88a
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 2efbae6f1c63..8aba07803f47 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -28505,10 +28505,10 @@
},
"MCPToolFailureItem": {
"additionalProperties": false,
- "description": "One row of the per-tool \"Failures\" table: an exception message paired with a tool.",
+ "description": "One row of the per-tool \"Failures\" table: a failure bucket (error type/status) for a tool.",
"properties": {
"harnesses": {
- "description": "Resolved harness labels seen for this exception, deduped and sorted.",
+ "description": "Resolved harness labels seen for this failure, deduped and sorted.",
"items": {
"type": "string"
},
@@ -28518,6 +28518,7 @@
"type": "string"
},
"message": {
+ "description": "Failure label composed from $mcp_error_type and, when present, $mcp_error_status (e.g. \"api_5xx (HTTP 500)\").",
"type": "string"
},
"occurrences": {
@@ -28529,7 +28530,7 @@
},
"MCPToolFailuresQuery": {
"additionalProperties": false,
- "description": "Top exception messages paired with a single MCP tool, with server-resolved harness labels.",
+ "description": "Errored calls of a single MCP tool grouped by error type/status, with server-resolved harness labels.",
"properties": {
"dateRange": {
"$ref": "#/definitions/DateRange"
@@ -28549,7 +28550,7 @@
"$ref": "#/definitions/QueryLogTags"
},
"toolName": {
- "description": "The raw $mcp_tool_name to scope $exception events to.",
+ "description": "The effective tool name to scope to (matched against the single-exec-resolved tool name).",
"type": "string"
},
"version": {
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index d5216f48b4b5..0952a854670c 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -2723,12 +2723,13 @@ export interface MCPToolTopUsersQuery extends DataNode<MCPToolTopUsersQueryRespo
export type CachedMCPToolTopUsersQueryResponse = CachedQueryResponse<MCPToolTopUsersQueryResponse>
-/** One row of the per-tool "Failures" table: an exception message paired with a tool. */
+/** One row of the per-tool "Failures" table: a failure bucket (error type/status) for a tool. */
export interface MCPToolFailureItem {
+ /** Failure label composed from $mcp_error_type and, when present, $mcp_error_status (e.g. "api_5xx (HTTP 500)"). */
message: string
occurrences: integer
last_seen: string
- /** Resolved harness labels seen for this exception, deduped and sorted. */
+ /** Resolved harness labels seen for this failure, deduped and sorted. */
harnesses: string[]
}
@@ -2736,10 +2737,10 @@ export interface MCPToolFailuresQueryResponse extends AnalyticsQueryResponseBase
results: MCPToolFailureItem[]
}
-/** Top exception messages paired with a single MCP tool, with server-resolved harness labels. */
+/** Errored calls of a single MCP tool grouped by error type/status, with server-resolved harness labels. */
export interface MCPToolFailuresQuery extends DataNode<MCPToolFailuresQueryResponse> {
kind: NodeKind.MCPToolFailuresQuery
- /** The raw $mcp_tool_name to scope $exception events to. */
+ /** The effective tool name to scope to (matched against the single-exec-resolved tool name). */
toolName: string
dateRange?: DateRange
}
diff --git a/posthog/schema.py b/posthog/schema.py
index 2ad01307f35b..8104d78fa6c7 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -5280,10 +5280,16 @@ class MCPToolFailureItem(BaseModel):
)
harnesses: list[str] = Field(
...,
- description=("Resolved harness labels seen for this exception, deduped and sorted."),
+ description=("Resolved harness labels seen for this failure, deduped and sorted."),
)
last_seen: str
- message: str
+ message: str = Field(
+ ...,
+ description=(
+ "Failure label composed from $mcp_error_type and, when present,"
+ ' $mcp_error_status (e.g. "api_5xx (HTTP 500)").'
+ ),
+ )
occurrences: int
@@ -24193,7 +24199,10 @@ class MCPToolFailuresQuery(BaseModel):
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
response: MCPToolFailuresQueryResponse | None = None
tags: QueryLogTags | None = None
- toolName: str = Field(..., description="The raw $mcp_tool_name to scope $exception events to.")
+ toolName: str = Field(
+ ...,
+ description=("The effective tool name to scope to (matched against the single-exec-resolved tool name)."),
+ )
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
diff --git a/products/mcp_analytics/backend/hogql_queries/tool_tables.py b/products/mcp_analytics/backend/hogql_queries/tool_tables.py
index 0aa1051396c4..5c8beb0b1a9c 100644
--- a/products/mcp_analytics/backend/hogql_queries/tool_tables.py
+++ b/products/mcp_analytics/backend/hogql_queries/tool_tables.py
@@ -76,6 +76,21 @@ _EFFECTIVE_DESCRIPTION = (
# token only has to be materialized once as `h`.
_HARNESS_LABELS_AGG = f"arraySort(arrayDistinct(groupArray({mcp_harness.harness_label_sql('h')})))"
+# Human-readable failure label for an errored $mcp_tool_call. There is no free-text error
+# message on tool-call events — the SDK stamps a semantic bucket ($mcp_error_type: internal,
+# validation, api_4xx, api_5xx, permission, timeout, rate_limited, missing_context) plus an
+# optional HTTP status ($mcp_error_status). We compose the two into one label, falling back to
+# "unknown" when neither is present (older SDKs / server paths that only set $mcp_is_error).
+# Both properties are event-supplied and unbounded, so the query caps the label at 200 chars
+# before grouping on it.
+_FAILURE_LABEL = (
+ "concat("
+ "coalesce(nullIf(toString(properties.$mcp_error_type), ''), 'unknown'), "
+ "if(empty(coalesce(toString(properties.$mcp_error_status), '')), '', "
+ "concat(' (HTTP ', coalesce(toString(properties.$mcp_error_status), ''), ')'))"
+ ")"
+)
+
def _display_properties(*, email: str, name: str) -> str:
"""JSON of only the person fields the Top-users cell renders, omitting blanks."""
@@ -197,23 +212,14 @@ class MCPToolFailuresQueryRunner(AnalyticsQueryRunner[MCPToolFailuresQueryRespon
return mcp_query_date_range(self.team, self.query.dateRange)
def _where(self) -> ast.Expr:
- # $exception events don't carry the new-SDK markers ($mcp_source / $mcp_exec_tool_call_name),
- # so this matches the raw $mcp_tool_name rather than the effective tool name.
- return ast.And(
- exprs=[
- parse_expr("event = {event}", placeholders={"event": ast.Constant(value="$exception")}),
- 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()}
- ),
- parse_expr(
- "toString(properties.$mcp_tool_name) = {tool}",
- placeholders={"tool": ast.Constant(value=self.query.toolName)},
- ),
- parse_expr("notEmpty(toString(properties.$exception_message))"),
- ]
+ # Failures share the tool-call source with every other tool-detail table, so they use the
+ # effective tool name and the same $mcp_source scoping as the stats/error-rate query — the
+ # two can never disagree. (Previously this read $exception events, which don't carry MCP
+ # tool markers, so the table was always empty while the error rate showed failures.)
+ return _tool_call_where(
+ self.query.toolName,
+ self.query_date_range,
+ extra=[parse_expr("toBool(properties.$mcp_is_error)")],
)
def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:
@@ -226,7 +232,7 @@ class MCPToolFailuresQueryRunner(AnalyticsQueryRunner[MCPToolFailuresQueryRespon
{_HARNESS_LABELS_AGG} AS harnesses
FROM (
SELECT
- substring(toString(properties.$exception_message), 1, 200) AS message,
+ substring({_FAILURE_LABEL}, 1, 200) AS message,
timestamp,
{token} AS h
FROM events
@@ -238,6 +244,7 @@ class MCPToolFailuresQueryRunner(AnalyticsQueryRunner[MCPToolFailuresQueryRespon
""",
placeholders={
"_HARNESS_LABELS_AGG": parse_expr(_HARNESS_LABELS_AGG),
+ "_FAILURE_LABEL": parse_expr(_FAILURE_LABEL),
"token": parse_expr(mcp_harness.HARNESS_TOKEN_SQL),
"where": self._where(),
},
diff --git a/products/mcp_analytics/backend/tests/test_tool_tables.py b/products/mcp_analytics/backend/tests/test_tool_tables.py
index 9949685ab034..9f34f6df0e4e 100644
--- a/products/mcp_analytics/backend/tests/test_tool_tables.py
+++ b/products/mcp_analytics/backend/tests/test_tool_tables.py
@@ -130,21 +130,34 @@ class TestMCPToolTopUsersQueryRunner(_MCPAnalyticsTeamScopedTestMixin, Clickhous
class TestMCPToolFailuresQueryRunner(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):
- def _emit_exception(
+ def _emit(
self,
*,
tool_name: str = "query_run",
- message: str = "boom",
+ distinct_id: str = "d1",
client_name: str | None = None,
+ source: str | None = NEW_SDK_SOURCE,
+ is_error: bool = True,
+ error_type: str | None = None,
+ error_status: str | None = None,
+ exec_tool: str | None = None,
timestamp: datetime | None = None,
) -> None:
- properties: dict[str, Any] = {"$mcp_tool_name": tool_name, "$exception_message": message}
+ properties: dict[str, Any] = {"$mcp_tool_name": tool_name, "$mcp_is_error": is_error}
+ if source is not None:
+ properties["$mcp_source"] = source
if client_name is not None:
properties["$mcp_client_name"] = client_name
+ if error_type is not None:
+ properties["$mcp_error_type"] = error_type
+ if error_status is not None:
+ properties["$mcp_error_status"] = error_status
+ if exec_tool is not None:
+ properties["$mcp_exec_tool_call_name"] = exec_tool
_create_event(
team=self.team,
- event="$exception",
- distinct_id="d1",
+ event="$mcp_tool_call",
+ distinct_id=distinct_id,
timestamp=timestamp or datetime.now(tz=UTC),
properties=properties,
)
@@ -158,48 +171,67 @@ class TestMCPToolFailuresQueryRunner(_MCPAnalyticsTeamScopedTestMixin, Clickhous
@parameterized.expand(
[
- ("sdk_claudeai", "claude-ai", ["Claude.ai"]),
- ("sdk_mcp_remote_stripped", "claude-ai (via mcp-remote 0.1.37)", ["Claude.ai"]),
- ("sdk_unknown_to_other", "weird-client", ["Other"]),
+ ("type_and_status", "api_5xx", "500", "api_5xx (HTTP 500)"),
+ ("type_only", "validation", None, "validation"),
+ ("neither_falls_back_to_unknown", None, None, "unknown"),
+ # Event-supplied fields are unbounded; the label must be capped so an attacker
+ # emitting huge unique values can't inflate the grouping key and response size.
+ ("long_type_truncated_to_200_chars", "x" * 300, None, "x" * 200),
]
)
- def test_resolves_harness_labels(self, _name: str, client_name: str, expected: list[str]) -> None:
- self._emit_exception(client_name=client_name)
+ def test_composes_failure_label(
+ self, _name: str, error_type: str | None, error_status: str | None, expected: str
+ ) -> None:
+ self._emit(error_type=error_type, error_status=error_status, client_name="claude-ai")
flush_persons_and_events()
rows = self._run()
assert len(rows) == 1
- assert rows[0].harnesses == expected
+ assert rows[0].message == expected
- def test_groups_by_message_and_counts_occurrences(self) -> None:
- self._emit_exception(message="boom", client_name="claude-ai")
- self._emit_exception(message="boom", client_name="cursor-vscode")
- self._emit_exception(message="other", client_name="claude-ai")
+ def test_only_counts_errored_calls(self) -> None:
+ # The fix's core behavior: failures are sourced from $mcp_is_error on $mcp_tool_call,
+ # so successful calls must never appear (they did when the table read $exception events).
+ self._emit(is_error=False, error_type="validation", client_name="claude-ai")
+ self._emit(is_error=True, error_type="internal", client_name="claude-ai")
flush_persons_and_events()
- rows = self._run()
- by_message = {r.message: r for r in rows}
+ assert [r.message for r in self._run()] == ["internal"]
+
+ def test_groups_by_label_dedupes_harnesses_and_counts(self) -> None:
+ self._emit(error_type="internal", client_name="claude-ai")
+ self._emit(error_type="internal", client_name="cursor-vscode")
+ self._emit(error_type="validation", client_name="claude-ai")
+ flush_persons_and_events()
- assert by_message["boom"].occurrences == 2
- assert by_message["boom"].harnesses == ["Claude.ai", "Cursor"]
- assert by_message["other"].occurrences == 1
+ by_label = {r.message: r for r in self._run()}
- def test_excludes_other_tools(self) -> None:
- self._emit_exception(tool_name="other_tool", message="boom", client_name="claude-ai")
+ assert by_label["internal"].occurrences == 2
+ assert by_label["internal"].harnesses == ["Claude.ai", "Cursor"]
+ assert by_label["validation"].occurrences == 1
+
+ def test_excludes_other_tools_and_resolves_effective_tool_name(self) -> None:
+ self._emit(tool_name="other_tool", error_type="internal", client_name="claude-ai")
+ # Single-exec wrapper: the effective tool is in $mcp_exec_tool_call_name, not $mcp_tool_name.
+ self._emit(tool_name="exec", exec_tool="query_run", error_type="validation", client_name="cursor-vscode")
flush_persons_and_events()
- assert self._run(tool_name="query_run") == []
+ assert [r.message for r in self._run(tool_name="query_run")] == ["validation"]
+
+ def test_excludes_events_without_new_sdk_source(self) -> None:
+ self._emit(source=None, error_type="internal", client_name="claude-ai")
+ flush_persons_and_events()
+
+ assert self._run() == []
def test_date_range_excludes_older_events(self) -> None:
now = datetime.now(tz=UTC)
- self._emit_exception(message="old", client_name="claude-ai", timestamp=now - timedelta(days=30))
- self._emit_exception(message="recent", client_name="claude-ai", timestamp=now)
+ self._emit(error_type="internal", timestamp=now - timedelta(days=30))
+ self._emit(error_type="validation", timestamp=now)
flush_persons_and_events()
- rows = self._run()
-
- assert {r.message for r in rows} == {"recent"}
+ assert {r.message for r in self._run()} == {"validation"}
def _emit_tool_call(
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
index 1931f218d901..245b6a649d96 100644
--- a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
@@ -640,13 +640,13 @@ function MCPAnalyticsToolDetailContent({ toolName }: { toolName: string }): JSX.
<div className="flex flex-col gap-3 px-4 pb-4">
<ResultTable
title="Failures"
- description="Top exception messages paired with this tool. Sourced from $exception events."
+ description="Errored calls of this tool grouped by error type and HTTP status. Sourced from the $mcp_is_error flag on $mcp_tool_call events, the same source as the error rate above."
rows={failureRows}
loading={failureRowsLoading}
- emptyMessage="No exceptions recorded for this tool in the last 7 days."
+ emptyMessage="No errored calls recorded for this tool in the last 7 days."
columns={[
{
- header: 'Message',
+ header: 'Error type',
expand: true,
render: (r) => <span className="font-mono text-xs">{String(r[0] ?? '')}</span>,
},
diff --git a/products/mcp_analytics/mcp/tools.yaml b/products/mcp_analytics/mcp/tools.yaml
index 8c4a90eae8f9..d9ec93d7a4fc 100644
--- a/products/mcp_analytics/mcp/tools.yaml
+++ b/products/mcp_analytics/mcp/tools.yaml
@@ -233,12 +233,13 @@ wrappers:
idempotent: true
title: Top errors for one MCP tool
description: >
- Return the most common error messages for a single MCP tool, each with the resolved client harness it came
- from. Pass toolName as the raw $mcp_tool_name (the registered tool name) — failures are matched on
- $exception events, which don't carry the new-SDK effective-tool markers, so unlike the other tool-detail
- tools this one does NOT resolve the inner tool of a single-exec wrapper call. Also pass a dateRange. Use to
- answer "why is tool X failing?" or "what errors does tool X throw, and on which clients?".
- system_prompt_hint: One MCP tool's top error messages, by harness (scoped by raw tool name)
+ Return the most common failure buckets for a single MCP tool, each with the resolved client harness it came
+ from. Failures are the errored $mcp_tool_call events ($mcp_is_error = true) — the same source as the error
+ rate — grouped by $mcp_error_type and HTTP $mcp_error_status (there is no free-text error message on tool
+ calls). Pass toolName (effective tool name, resolved server-side, matching the other tool-detail tools) and
+ a dateRange. Use to answer "why is tool X failing?" or "what errors does tool X throw, and on which
+ clients?".
+ system_prompt_hint: One MCP tool's top failure buckets, by harness (error type + HTTP status)
exclude_properties:
- response
- modifiers
diff --git a/products/mcp_analytics/skills/exploring-mcp-tool-quality/SKILL.md b/products/mcp_analytics/skills/exploring-mcp-tool-quality/SKILL.md
index bd9f789a43b9..d201a14415ba 100644
--- a/products/mcp_analytics/skills/exploring-mcp-tool-quality/SKILL.md
+++ b/products/mcp_analytics/skills/exploring-mcp-tool-quality/SKILL.md
@@ -86,27 +86,34 @@ under "Tool-quality matrix".
## Workflow: why is a tool failing
-For one tool's top error messages (grouped by harness), call
+For one tool's top failure buckets (grouped by harness), call
`posthog:query-mcp-tool-failures` with the `toolName` — it's the typed equivalent of the
-query below. Pass the **raw** `$mcp_tool_name` (the registered tool name), not
-the effective inner tool: failures match `$exception` events, which don't carry
-the new-SDK effective-tool markers. Drop to SQL only to correlate to richer
-exception detail (`$exception` events carry `$exception_message`, joined by
-`$session_id` and timestamp) — that session join is approximate: it surfaces
-every exception in the session, not only this tool's, so treat it as a lead, not
-exact attribution:
+query below. Failures come from the **same source as the error rate**: errored
+`$mcp_tool_call` events (`$mcp_is_error`), scoped by the effective tool name. There is no
+free-text error message on tool calls, so failures are grouped by `$mcp_error_type` (a
+semantic bucket: `internal`, `validation`, `api_4xx`, `api_5xx`, `permission`, `timeout`,
+`rate_limited`, `missing_context`) and the HTTP `$mcp_error_status` when present:
```sql
posthog:execute-sql
-SELECT toString(properties.$mcp_error_message) AS error, count() AS n
+SELECT
+ concat(
+ coalesce(nullIf(toString(properties.$mcp_error_type), ''), 'unknown'),
+ if(empty(coalesce(toString(properties.$mcp_error_status), '')), '',
+ concat(' (HTTP ', coalesce(toString(properties.$mcp_error_status), ''), ')'))
+ ) AS failure,
+ count() AS n
FROM events
WHERE event = '$mcp_tool_call'
AND toBool(properties.$mcp_is_error)
AND coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name)) = '<tool>'
AND timestamp >= now() - INTERVAL 30 DAY
-GROUP BY error ORDER BY n DESC LIMIT 10
+GROUP BY failure ORDER BY n DESC LIMIT 10
```
+`$mcp_error_type` is only populated on newer SDK/server paths — a chunk of errored calls
+carry neither type nor status and fall into the `unknown` bucket.
+
## Workflow: slowest tools
Swap the aggregate for latency percentiles
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.md
index 8e1916af5943..bc78ad11833e 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
@@ -4,17 +4,17 @@ Any MCP server instrumented with the `@posthog/mcp` SDK — and PostHog's own MC
Query the canonical `$`-prefixed event name. Servers instrumented with the `@posthog/mcp` SDK emit only `$mcp_tool_call` / `$mcp_initialize`; PostHog's own hosted server additionally dual-emits legacy un-prefixed `mcp_tool_call` / `mcp_initialize` aliases through a transition shim. Match the canonical name only — an `event IN ('mcp_tool_call', '$mcp_tool_call')` would double-count PostHog's own server.
-**For a single tool, prefer the typed tools.** Each takes a `toolName` plus a `dateRange`, runs the same query runner the tool-detail UI uses, and is gated behind the `mcp-analytics` flag, so results match the UI exactly and you don't re-derive the SQL below. For all of them **except `posthog:query-mcp-tool-failures`**, `toolName` is the effective name (resolved server-side — the inner tool of a single-exec wrapper call). `posthog:query-mcp-tool-failures` is the exception: it matches `$exception` events, which don't carry the new-SDK effective-tool markers, so it takes the **raw** `$mcp_tool_name` (the registered tool name):
-
-| question about one tool | tool |
-| ------------------------------------------------------------------- | -------------------------------------------------------- |
-| headline numbers (calls, errors, p50/p95, users, sessions, intents) | `posthog:query-mcp-tool-stats` |
-| day-by-day trend | `posthog:query-mcp-tool-daily-stats` |
-| top error messages, by harness | `posthog:query-mcp-tool-failures` (raw `$mcp_tool_name`) |
-| top callers (incl. person email/name) | `posthog:query-mcp-tool-top-users` |
-| tools called before/after it (`neighborDirection: before`/`after`) | `posthog:query-mcp-tool-neighbors` |
-| recent agent intents | `posthog:query-mcp-tool-sample-intents` |
-| distinct descriptions seen | `posthog:query-mcp-tool-descriptions` |
+**For a single tool, prefer the typed tools.** Each takes a `toolName` plus a `dateRange`, runs the same query runner the tool-detail UI uses, and is gated behind the `mcp-analytics` flag, so results match the UI exactly and you don't re-derive the SQL below. `toolName` is the effective name (resolved server-side — the inner tool of a single-exec wrapper call) for all of them, including `posthog:query-mcp-tool-failures`:
+
+| question about one tool | tool |
+| ------------------------------------------------------------------- | --------------------------------------- |
+| headline numbers (calls, errors, p50/p95, users, sessions, intents) | `posthog:query-mcp-tool-stats` |
+| day-by-day trend | `posthog:query-mcp-tool-daily-stats` |
+| top failure buckets, by harness | `posthog:query-mcp-tool-failures` |
+| top callers (incl. person email/name) | `posthog:query-mcp-tool-top-users` |
+| tools called before/after it (`neighborDirection: before`/`after`) | `posthog:query-mcp-tool-neighbors` |
+| recent agent intents | `posthog:query-mcp-tool-sample-intents` |
+| distinct descriptions seen | `posthog:query-mcp-tool-descriptions` |
And `posthog:query-mcp-harness-breakdown` for the cross-tool harness cut (see below).
@@ -22,18 +22,19 @@ And `posthog:query-mcp-harness-breakdown` for the cross-tool harness cut (see be
## Key properties
-| Property | Meaning |
-| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
-| `$mcp_tool_name` | Registered tool name. |
-| `$mcp_exec_tool_call_name` | Inner tool name when the call went through the new-SDK single-exec wrapper. See effective-tool-name note below. |
-| `$mcp_is_error` | Whether the call failed. Always read via `toBool(properties.$mcp_is_error)`. |
-| `$mcp_error_message` | Error text when `$mcp_is_error` is true. |
-| `$mcp_duration_ms` | Wall-clock duration; cast with `toFloat(...)`. |
-| `$session_id` | Session/conversation id — the grouping key for a single agent run. Use the bare `$session_id` field, not `properties.$session_id`. |
-| `$mcp_intent` | The agent's stated intent for the call, when supplied. |
-| `$mcp_client_name` | Raw client string (e.g. `claude-code/1.2.3`). The dashboard buckets these into harnesses in the frontend; there is no `category` column. |
-| `$mcp_tool_category` | Tool category, when tagged. |
-| `$mcp_tool_description` | Tool description as seen by the agent (revisions over time). |
+| Property | Meaning |
+| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `$mcp_tool_name` | Registered tool name. |
+| `$mcp_exec_tool_call_name` | Inner tool name when the call went through the new-SDK single-exec wrapper. See effective-tool-name note below. |
+| `$mcp_is_error` | Whether the call failed. Always read via `toBool(properties.$mcp_is_error)`. |
+| `$mcp_error_type` | Semantic failure bucket when `$mcp_is_error` is true (`internal`, `validation`, `api_4xx`, `api_5xx`, `permission`, `timeout`, `rate_limited`, `missing_context`). Only newer SDK/server paths set it. |
+| `$mcp_error_status` | HTTP status code for an errored call, when the failure came from an HTTP call. |
+| `$mcp_duration_ms` | Wall-clock duration; cast with `toFloat(...)`. |
+| `$session_id` | Session/conversation id — the grouping key for a single agent run. Use the bare `$session_id` field, not `properties.$session_id`. |
+| `$mcp_intent` | The agent's stated intent for the call, when supplied. |
+| `$mcp_client_name` | Raw client string (e.g. `claude-code/1.2.3`). The dashboard buckets these into harnesses in the frontend; there is no `category` column. |
+| `$mcp_tool_category` | Tool category, when tagged. |
+| `$mcp_tool_description` | Tool description as seen by the agent (revisions over time). |
**Effective tool name.** New-SDK events wrap the real tool in a single-exec call, so to filter/group by the tool the agent actually invoked, use:
@@ -41,7 +42,7 @@ And `posthog:query-mcp-harness-breakdown` for the cross-tool harness cut (see be
coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name))
```
-**Failures with detail.** `$mcp_tool_call` carries `$mcp_is_error` + `$mcp_error_message`; richer stack/exception data is on `$exception` events (`$exception_message`), correlated by `$mcp_session_id` / `$session_id` and timestamp.
+**Failures with detail.** `$mcp_tool_call` carries `$mcp_is_error` plus a semantic `$mcp_error_type` and, for HTTP failures, `$mcp_error_status`. `posthog:query-mcp-tool-failures` groups errored tool calls by these two fields. A free-text `$mcp_error_message` / `$mcp_response` exists in the SDK schema but PostHog's hosted server leaves both empty, so don't rely on them for tool-failure detail. PostHog's own tool calls also don't emit `$exception` events — those only exist for separately-instrumented MCP servers.
## Example queries
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index cf2a56e6acae..0e15f62739db 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -6498,7 +6498,7 @@
"system_prompt_hint": "Distinct effective descriptions seen for one MCP tool"
},
"query-mcp-tool-failures": {
- "description": "Return the most common error messages for a single MCP tool, each with the resolved client harness it came from. Pass toolName as the raw $mcp_tool_name (the registered tool name) — failures are matched on $exception events, which don't carry the new-SDK effective-tool markers, so unlike the other tool-detail tools this one does NOT resolve the inner tool of a single-exec wrapper call. Also pass a dateRange. Use to answer \"why is tool X failing?\" or \"what errors does tool X throw, and on which clients?\".",
+ "description": "Return the most common failure buckets for a single MCP tool, each with the resolved client harness it came from. Failures are the errored $mcp_tool_call events ($mcp_is_error = true) — the same source as the error rate — grouped by $mcp_error_type and HTTP $mcp_error_status (there is no free-text error message on tool calls). Pass toolName (effective tool name, resolved server-side, matching the other tool-detail tools) and a dateRange. Use to answer \"why is tool X failing?\" or \"what errors does tool X throw, and on which clients?\".",
"category": "MCP analytics",
"feature": "mcp_analytics",
"summary": "Top errors for one MCP tool",
@@ -6511,7 +6511,7 @@
"readOnlyHint": true
},
"feature_flag": "mcp-analytics",
- "system_prompt_hint": "One MCP tool's top error messages, by harness (scoped by raw tool name)"
+ "system_prompt_hint": "One MCP tool's top failure buckets, by harness (error type + HTTP status)"
},
"query-mcp-tool-neighbors": {
"description": "Return the tools most often called immediately before or after a single MCP tool within the same conversation. Pass toolName (effective tool name, resolved server-side), a dateRange, and neighborDirection ('before' or 'after'). Use to answer \"what does an agent call around tool X?\" — revealing common tool sequences and which tools pair up.",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index c2c061363a0c..3be853296f69 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6962,7 +6962,7 @@
"system_prompt_hint": "Distinct effective descriptions seen for one MCP tool"
},
"query-mcp-tool-failures": {
- "description": "Return the most common error messages for a single MCP tool, each with the resolved client harness it came from. Pass toolName as the raw $mcp_tool_name (the registered tool name) — failures are matched on $exception events, which don't carry the new-SDK effective-tool markers, so unlike the other tool-detail tools this one does NOT resolve the inner tool of a single-exec wrapper call. Also pass a dateRange. Use to answer \"why is tool X failing?\" or \"what errors does tool X throw, and on which clients?\".",
+ "description": "Return the most common failure buckets for a single MCP tool, each with the resolved client harness it came from. Failures are the errored $mcp_tool_call events ($mcp_is_error = true) — the same source as the error rate — grouped by $mcp_error_type and HTTP $mcp_error_status (there is no free-text error message on tool calls). Pass toolName (effective tool name, resolved server-side, matching the other tool-detail tools) and a dateRange. Use to answer \"why is tool X failing?\" or \"what errors does tool X throw, and on which clients?\".",
"category": "MCP analytics",
"feature": "mcp_analytics",
"summary": "Top errors for one MCP tool",
@@ -6975,7 +6975,7 @@
"readOnlyHint": true
},
"feature_flag": "mcp-analytics",
- "system_prompt_hint": "One MCP tool's top error messages, by harness (scoped by raw tool name)"
+ "system_prompt_hint": "One MCP tool's top failure buckets, by harness (error type + HTTP status)"
},
"query-mcp-tool-neighbors": {
"description": "Return the tools most often called immediately before or after a single MCP tool within the same conversation. Pass toolName (effective tool name, resolved server-side), a dateRange, and neighborDirection ('before' or 'after'). Use to answer \"what does an agent call around tool X?\" — revealing common tool sequences and which tools pair up.",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 02ba6b2761e3..4001ebcf60f6 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -30241,9 +30241,10 @@ export namespace Schemas {
}
export interface MCPToolFailureItem {
- /** Resolved harness labels seen for this exception, deduped and sorted. */
+ /** Resolved harness labels seen for this failure, deduped and sorted. */
harnesses: string[];
last_seen: string;
+ /** Failure label composed from $mcp_error_type and, when present, $mcp_error_status (e.g. "api_5xx (HTTP 500)"). */
message: string;
occurrences: number;
}
@@ -30275,7 +30276,7 @@ export namespace Schemas {
modifiers?: HogQLQueryModifiers | null;
response?: MCPToolFailuresQueryResponse | null;
tags?: QueryLogTags | null;
- /** The raw $mcp_tool_name to scope $exception events to. */
+ /** The effective tool name to scope to (matched against the single-exec-resolved tool name). */
toolName: string;
/** version of the node, used for schema migrations */
version?: number | null;
diff --git a/services/mcp/src/tools/generated/mcp_analytics.ts b/services/mcp/src/tools/generated/mcp_analytics.ts
index b1cc19651113..d01071f0d769 100644
--- a/services/mcp/src/tools/generated/mcp_analytics.ts
+++ b/services/mcp/src/tools/generated/mcp_analytics.ts
@@ -544,7 +544,9 @@ const MCPToolDailyStatsQuery = z.object({
const MCPToolFailuresQuery = z.object({
dateRange: DateRange.optional(),
kind: z.literal('MCPToolFailuresQuery').default('MCPToolFailuresQuery'),
- toolName: z.string().describe('The raw $mcp_tool_name to scope $exception events to.'),
+ toolName: z
+ .string()
+ .describe('The effective tool name to scope to (matched against the single-exec-resolved tool name).'),
})
const MCPToolTopUsersQuery = z.object({