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(signals): add MCP tool-call quality scout (#67504)

Daniel Viscacfd88c3db48f
diff --git a/products/signals/skills/AGENTS.md b/products/signals/skills/AGENTS.md
index 90735fdb4da5..2db0aa504986 100644
--- a/products/signals/skills/AGENTS.md
+++ b/products/signals/skills/AGENTS.md
@@ -213,6 +213,17 @@ agent-enabled team's `LLMSkill` rows by `scout_harness/lazy_seed.py` — see
`revenue-analytics` watches the lagging revenue/MRR signal; neither scores an
individual account's engagement trajectory. Acquisition is the web-analytics
scout's territory.
+- `signals-scout-mcp-tool-calls/` — tool-quality watcher for PostHog MCP usage. Reads
+ `$mcp_tool_call` telemetry for tools that need improvement: high, broad-reach failure
+ rates, per-session retry/hammering that betrays a confusing schema, slow or
+ context-bloating responses, and undiagnosable failures (an instrumentation gap). Its
+ discriminator is rate/struggle weighted by volume and reach, concentrated in a
+ consistent shape — not raw counts. Coverage-aware: it first probes which enrichment
+ fields the project captures (they split by regime — PostHog's own hono server vs
+ external SDK servers) and picks lenses to match, resting detection only on always-present
+ fields (error flag, duration, tool name, session). Emits one `emit_signal` finding per
+ tool for the pipeline to diagnose and fix; bundles `references/queries.md`, a HogQL
+ cookbook validated against real telemetry.
### How the coordinator decides what runs
diff --git a/products/signals/skills/signals-scout-mcp-tool-calls/SKILL.md b/products/signals/skills/signals-scout-mcp-tool-calls/SKILL.md
new file mode 100644
index 000000000000..5ba756fb420d
--- /dev/null
+++ b/products/signals/skills/signals-scout-mcp-tool-calls/SKILL.md
@@ -0,0 +1,225 @@
+---
+name: signals-scout-mcp-tool-calls
+description: >
+ Signals scout for PostHog MCP tool calls. Watches $mcp_tool_call telemetry for tools that
+ need improvement — high, broad-reach failure rates, retry/hammering that betrays a confusing
+ schema, slow or context-bloating responses — and emits a signal per tool so the pipeline can
+ diagnose it and suggest a fix. Adapts to which fields the project actually captures.
+compatibility: >
+ Designed for the PostHog Signals agent in a Claude sandbox with PostHog MCP scopes
+ (read-only analytics plus signal_scout_internal:write for scratchpad + emit-signal).
+ Assumes the signals-scout MCP family (project-profile-get, runs-list, runs-retrieve,
+ scratchpad-search, scratchpad-remember, scratchpad-forget, emit-signal) plus execute-sql,
+ read-data-schema, and inbox-reports-list. The SQL cookbook lives in references/queries.md
+ (read it on demand); deep-dives into posthog:exploring-mcp-tool-quality and
+ posthog:querying-posthog-data.
+metadata:
+ owner_team: signals
+ scope: mcp_analytics
+---
+
+# Signals scout: MCP tool calls
+
+You are a focused MCP tool-quality scout. Find the PostHog MCP tools that **need improvement**
+for this project's agents, and emit one signal per tool. The grouping + research pipeline
+downstream diagnoses the cause and suggests a fix; your job is to surface the _right_ tool with
+enough evidence that the diagnosis has somewhere to start. An empty run is a real outcome;
+re-emitting a tool a prior run already flagged is worse than emitting nothing.
+
+**"Needs improvement" is broader than "fails a lot."** A tool earns a signal when agents can't
+use it cleanly, which shows up as any of:
+
+1. **Failures** — a high `$mcp_is_error` rate over meaningful volume and reach.
+2. **Struggle** — agents call it repeatedly within a session, or fail-then-retry it, which
+ almost always means a confusing schema/description even when calls eventually succeed.
+3. **Slowness** — high p95 `$mcp_duration_ms` (and, in the hono regime, `timeout` failures).
+4. **Context bloat** — oversized responses (hono regime only).
+5. **Un-diagnosable failures** — it fails but the project captures no error detail, so the fix
+ is to add instrumentation.
+
+**Signal-vs-noise discriminator (internalize this):** rate/struggle **weighted by volume and
+reach**, concentrated in a consistent shape. Raw counts are noise (a high-traffic tool fails
+and repeats more in absolute terms while being healthy); a high _rate_ or _per-session
+struggle_ across _many distinct users/sessions_ is the signal. A tool at 40% failure on 2,000
+calls across 30 users, or one agents call 4× per session in 60% of sessions, is a strong
+finding; the same shape on 12 calls from one session is not.
+
+## The data + reliability tiers (this is the key discipline)
+
+MCP tool calls land on the `$mcp_tool_call` event, emitted by both PostHog's own hono server
+**and** external customer servers instrumented with the SDK. Crucially, **the two regimes
+capture different fields**, so never hardcode a field's presence — check coverage first
+(query 0) and pick lenses to match.
+
+**Tier 1 — always present (build detection on these):**
+
+| Field | Access | Use |
+| ------------ | ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
+| failure flag | `toBool(properties.$mcp_is_error)` | failure rate |
+| duration | `toFloat(properties.$mcp_duration_ms)` | latency |
+| tool name | `coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name))` | grouping key (unwraps the single-exec `exec` dispatcher) |
+| reach | `distinct_id`, `$session_id` | reject single-user noise; compute per-session struggle |
+| client | `properties.$mcp_client_name` | localize a client-specific break (most reliable harness field) |
+
+**Tier 2 — sometimes present (enrichment; localizes the cause, gate on coverage):**
+
+| Field | Present when | Use |
+| ---------------------------------------------------- | ---------------------------------------------------------------------- | --------------------------------------- |
+| `$mcp_error_type` (+ `$mcp_error_status`) | **hono server only** | failure class → fix hypothesis |
+| `$mcp_error_message` | **external SDK only** (hono omits it to avoid capturing query content) | cluster raw failure text |
+| `$mcp_tool_category` | hono only | category rollup |
+| `$mcp_mode` (`cli`/`tools`) | hono / CLI only | is it broken only via the exec wrapper? |
+| `input_tokens` / `output_tokens` (bare keys, no `$`) | hono only | response bloat |
+| `$mcp_intent` / `$mcp_intent_source` | sparse, opt-in (agent-supplied) | tie failures to what the agent wanted |
+
+Two consequences to remember, both verified against real data:
+
+- **Presence = `isNotNull(properties.X)`; never `!= ''` or `NOT IN ('', 'None')`** (both return
+ garbage/>100% coverage for the MCP props). `$mcp_error_type` is especially quirky — bare value
+ equality gives contradictory counts across query shapes, so define _classified_ failures by a positive
+ `toString(...) IN (<known classes>)` whitelist and _unclassified_ by subtraction (failures − classified),
+ never by `NOT IN`. Token fields are numeric (`isNotNull`). The cookbook queries encode all of this —
+ use them verbatim, don't hand-write comparisons.
+- **`$mcp_error_type` existing ≠ failures being classified.** Even on PostHog's own hono data, most
+ `$mcp_is_error` failures are _tool-result_ errors (the handler returned `{isError:true}`) that never
+ get a class — `error_type` stays `'None'`. On PostHog's own project only ~4% of failures carry a real
+ class. So when the coverage probe shows low `pct_failures_classified`, the **unclassified-failure
+ bucket is the main story** — rank with failure rate (query 1) + struggle (query 2), and treat the
+ missing detail as an observability-gap finding rather than assuming the class breakdown will explain it.
+ On an **external customer's** MCP data it's the reverse regime: no classes, but `$mcp_error_message`
+ may carry raw text.
+
+The full SQL cookbook is in [`references/queries.md`](references/queries.md) — read it rather
+than reinventing the queries. Also read `posthog:exploring-mcp-tool-quality` and
+`posthog:querying-posthog-data` (both baked into the sandbox; `models-mcp` is the schema
+source of truth) when you go deep.
+
+## Quick close-out: is MCP even in use?
+
+If `$mcp_tool_call` is absent from the profile's `top_events` (or a 7-day `count()` is ~0),
+this project isn't using the PostHog MCP. Write one scratchpad entry and stop:
+
+- key: `not-in-use:mcp_analytics:team{team_id}`
+- content: brief note ("checked at {timestamp}, no $mcp_tool_call events in 7d")
+
+## Orient
+
+- `signals-scout-scratchpad-search` (`text=mcp`) — durable steering from past runs. `pattern:`
+ entries hold the baseline rates and the captured **regime** (hono vs external-SDK) so you
+ don't re-probe it cold; `noise:` / `addressed:` / `dedupe:` say what's benign, fixed, or
+ already emitted.
+- `signals-scout-runs-list` (last 7d) — what prior MCP runs found and ruled out.
+- `signals-scout-project-profile-get` — confirm `$mcp_tool_call` reach off `top_events`.
+- `inbox-reports-list` (`search=mcp` or a tool name, `ordering=-updated_at`) — tools you've
+ already surfaced land under `source_product=signals_scout`; don't re-emit a live one.
+
+## Field-coverage probe
+
+Run **query 0** from the cookbook (unless a fresh `pattern:mcp_analytics:regime` scratchpad
+entry already records it). It tells you the regime and which Tier-2 lenses are usable this
+run — record the answer in memory so future runs skip the probe. Everything after this adapts
+to what it returns.
+
+## Lenses
+
+Pick what the profile/probe flags as interesting and rotate across runs — don't run every lens
+every tick. Each maps to a cookbook query.
+
+| Lens | Detects | Reliability | Query |
+| ------------------- | ------------------------------------------------ | ------------------------------- | ----- |
+| Failure leaderboard | high error-rate tools | Tier 1 (always) | 1 |
+| Struggle / retry | schema/UX confusion (hammering, fail-then-retry) | Tier 1 (always) | 2 |
+| Latency | slow tools | Tier 1 (always) | 4 |
+| Error class | fix hypothesis from failure taxonomy | hono only | 3a |
+| Error messages | fix hypothesis from raw text | external SDK only | 3b |
+| Intent | what the agent wanted the tool to do | if `pct_with_intent` ≥ ~20 | 5 |
+| Client / mode split | universal break vs one-harness break | Tier 1 (client); mode hono only | 6 |
+| Observability gap | failures with no detail → add instrumentation | Tier 1 (always) | 7 |
+| Output bloat | oversized responses | hono only | 8 |
+| Category rollup | tools ranked within category (low priority) | hono only | 9 |
+
+The workflow for a candidate is **detect → localize → hypothesize**: query 1/2/4 detect a tool
+worth attention using only reliable fields; then use whichever Tier-2 lens the probe said is
+available (3a or 3b, plus 5/6) to localize the cause and form a fix hypothesis. If no Tier-2
+lens is available, query 7 turns that absence into its own finding.
+
+## Save memory as you go
+
+Encode the category in the key prefix so future runs find it with one `text=mcp` search:
+
+- key `pattern:mcp_analytics:regime` — _"hono regime: $mcp_error_type populated, no messages, mode+tokens present."_ (or the external-SDK inverse) — saves the probe next run.
+- key `pattern:mcp_analytics:baseline` — _"~4k calls/day, project-wide error rate ~6%; query-run and execute-sql carry most volume; avg 1.4 calls/session/tool."_
+- key `noise:mcp_analytics:<tool>` — _"<tool> ~15% validation chronically; agents recover on retry. Skip unless rate clears 30% or reach broadens past 20 users."_
+- key `dedupe:mcp_analytics:<tool>` — gates re-emitting a tool you surfaced; record date + window.
+- key `addressed:mcp_analytics:<tool>` — _"<tool> 5xx fixed 2026-06-30; back to baseline."_
+
+## Decide
+
+Cross-check `inbox-reports-list` and your `dedupe:` entries first — a tool with a live report
+is a **skip**. Then:
+
+- **Emit** via `signals-scout-emit-signal`, **one signal per tool** (aggregated over the
+ window), never one per failed call. A **strong finding**: confidence ≥ 0.85, the problem
+ (failure / struggle / latency / bloat) high over the volume floor with reach across multiple
+ users/sessions, and — when a Tier-2 lens is available — localized to a class/message/intent
+ with counts in the `evidence`. Confidence ≥ 0.65 is the emit gate; below that, write memory.
+ - `description`: Hook (tool + the quantified problem + volume + reach) → Pattern (the shape:
+ dominant error class, the retry loop, the p95, the intent that fails) → Hypothesis (likely
+ cause + fix direction, keyed off the Tier-2 lens) → Recommendation. Write for an engineer
+ who's never seen this tool. **State which regime the evidence came from** so the diagnosis
+ knows what it's working with.
+ - `dedupe_keys`: `mcp-tool-failure:<tool>` (add `:<error_type>` or `:latency` / `:struggle`
+ when tracking a specific cause separately).
+ - `severity`: P2 for a high-rate/high-struggle, broad-reach, clearly-localized problem; P3 otherwise.
+ - `finding_id`: `mcp-tool-<tool>-<date>` (a trace id, not an idempotency key — reusing it
+ writes a second signal).
+ - After emitting, write a `dedupe:mcp_analytics:<tool>` entry.
+- **Emit an observability-gap signal** (query 7) when a tool fails materially (≥50 errors) but
+ ≥90% of failures are unclassified (`$mcp_error_type IN ('', 'None')` and no message). The finding is:
+ "tool X fails at N% but failures aren't diagnosable — add error-type/message instrumentation
+ to its MCP handler." dedupe `mcp-observability-gap:<tool>`, severity P3. This is a real,
+ actionable improvement the pipeline can turn into an instrumentation task.
+- **Remember** if below the bar or to record what you ruled out.
+- **Skip** with a one-line note if a `noise:` / `addressed:` / `dedupe:` entry or a live inbox
+ report already covers it.
+
+## Disqualifiers (skip these)
+
+- **Single-user / single-session** — a tool "failing" or "hammered" from one `distinct_id` or
+ one `$session_id` is one developer, not a fleet problem. Always weigh `users` / `sessions`.
+- **Low absolute volume** — below the project's floor, both rate and struggle are noise.
+- **Self-recovering validation** — agents routinely malform the first call and succeed on
+ retry; some `sessions_error_then_more_calls` is normal. Weigh the _persistent / high-share_
+ case, not baseline first-tries. The struggle signal is the _elevated_ tail, not its presence.
+- **The bare `exec` wrapper** — the single-exec dispatcher has empty category; the
+ effective-tool-name coalesce unwraps it, but don't emit for a raw `exec` row.
+- **`rate_limited` alone** — throttling is a quota story unless sustained and broad.
+- **Errors during a known PostHog incident** — an `api_5xx` surge across _many_ tools at once
+ is an upstream outage, not a per-tool bug; check timing before attributing it to one tool.
+- **Structurally-slow tools** — some tools are legitimately long-running (large exports); a high
+ p95 alone isn't a bug. Weigh it against `timeout` failures and the tool's nature; record the
+ expected band in `pattern:` memory.
+- **Chronically-noisy tools recorded in scratchpad** — respect `noise:` thresholds.
+
+When in doubt, write memory instead of emitting. A false MCP-quality signal erodes trust fast.
+
+## MCP tools
+
+- `execute-sql` — the workhorse for every cookbook query over `$mcp_tool_call`.
+- `read-data-schema` — confirm which `$mcp_*` properties exist for this project before relying on them.
+- `inbox-reports-list` / `inbox-reports-retrieve` — what's already surfaced; check before emitting.
+- `signals-scout-project-profile-get` — cold orientation snapshot.
+- `signals-scout-scratchpad-search` / `-remember` / `-forget` — durable steering (regime, baselines, dedupe).
+- `signals-scout-runs-list` / `-runs-retrieve` — what prior runs found.
+- `signals-scout-emit-signal` — emit a per-tool signal (the emit contract rides in the harness prompt).
+
+Deep-dive skills baked into the sandbox: `posthog:exploring-mcp-tool-quality`,
+`posthog:exploring-mcp-tool-usage`, `posthog:querying-posthog-data`.
+
+## Close out
+
+One paragraph: the regime you found, which lenses you ran, which tools you emitted for and why
+(failure / struggle / latency / bloat / gap), what you remembered, what you ruled out. The
+harness saves this as the run summary; future runs read it via `signals-scout-runs-list`. Don't
+write a separate "run metadata" scratchpad entry. "Looked but found nothing meaningful" is a
+real outcome.
diff --git a/products/signals/skills/signals-scout-mcp-tool-calls/references/queries.md b/products/signals/skills/signals-scout-mcp-tool-calls/references/queries.md
new file mode 100644
index 000000000000..fee72e4f2fdc
--- /dev/null
+++ b/products/signals/skills/signals-scout-mcp-tool-calls/references/queries.md
@@ -0,0 +1,343 @@
+# MCP tool-call query cookbook
+
+All queries run via `execute-sql` over the `$mcp_tool_call` event. Conventions used
+throughout:
+
+- Use **only** `event = '$mcp_tool_call'` — never `IN ('$mcp_tool_call', 'mcp_tool_call')`,
+ which double-counts via the transition-shim alias.
+- Filter `properties.$mcp_source = 'posthog_mcp_analytics'` — keeps SDK-instrumented events
+ (both PostHog's hono server and external customer servers), excludes pre-SDK legacy events.
+ If a project's counts look suspiciously low, re-run the coverage probe without this filter
+ to check for legacy-only instrumentation.
+- Effective tool name (always use this — unwraps the single-exec `exec` dispatcher):
+ `coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name))`
+- **Presence check = `isNotNull(properties.X)`.** This is the one reliable way to test whether an
+ enrichment field is populated. Do **not** use `!= ''` or `NOT IN ('', 'None')` as a presence test —
+ both resolve unreliably in HogQL for the MCP props (verified: they returned >100% coverage and
+ query-shape-dependent counts). `isNotNull` gives clean, consistent coverage.
+- **`$mcp_error_type` is quirky — never do value equality on the bare property.** It gives
+ _contradictory_ counts across query shapes (a bare `= 'internal'` matched 67k rows a `toString()`
+ group showed as absent). Two formulations tested consistent and are the only ones to use:
+ - **Classified failures (positive membership):**
+ `toString(properties.$mcp_error_type) IN ('internal', 'validation', 'api_4xx', 'api_5xx', 'permission', 'timeout', 'rate_limited', 'missing_context')`.
+ On PostHog's own data only ~4% of failures are classified.
+ - **Unclassified failures:** compute by **subtraction**, not `NOT IN` (which mishandles the absent
+ value): `countIf(toBool($mcp_is_error)) - countIf(toBool($mcp_is_error) AND <the IN whitelist>)`.
+ The remainder are tool-result errors (handler returned `{isError:true}` without a class) — ~96% here.
+- **Sampling real values:** wrap in `toString(...)` and `GROUP BY` — the absent bucket shows as `'None'`
+ in grouped output (safe to read there; just don't turn it into a `WHERE ... IN/NOT IN` predicate).
+- **Token fields are numeric, not strings.** `input_tokens` / `output_tokens` (bare keys, no `$`) are
+ typed as numbers — test presence with `isNotNull(...)`, never `!= ''` (which errors trying to cast
+ `''` to Float64). Read them with `toFloat(...)`.
+- The `$mcp_exec_tool_call_name` fallback is genuinely empty/NULL when absent, so the coalesce above is
+ correct as written.
+- **`$mcp_error_message` does not exist on PostHog's own (hono) data** — it's an external-SDK-only field.
+ Referencing it there yields a taxonomy warning and empty results, not an error.
+- Tune the `HAVING` volume floors to the project's traffic (read the profile / probe first).
+
+---
+
+## 0. Field-coverage probe (run this first, every run)
+
+Determines the project's regime and which enrichment lenses are usable. `$mcp_is_error` and
+`$mcp_duration_ms` are always present; everything below is conditional. Note the `'None'`-aware
+absence tests and the `isNotNull` check for the numeric token field.
+
+```sql
+SELECT
+ count() AS calls,
+ countIf(toBool(properties.$mcp_is_error)) AS failures,
+ countIf(toBool(properties.$mcp_is_error) AND toString(properties.$mcp_error_type) IN ('internal', 'validation', 'api_4xx', 'api_5xx', 'permission', 'timeout', 'rate_limited', 'missing_context')) AS classified_failures,
+ round(countIf(toBool(properties.$mcp_is_error) AND toString(properties.$mcp_error_type) IN ('internal', 'validation', 'api_4xx', 'api_5xx', 'permission', 'timeout', 'rate_limited', 'missing_context')) * 100.0 / nullIf(countIf(toBool(properties.$mcp_is_error)), 0), 1) AS pct_failures_classified,
+ round(countIf(toBool(properties.$mcp_is_error) AND isNotNull(properties.$mcp_error_message)) * 100.0 / nullIf(countIf(toBool(properties.$mcp_is_error)), 0), 1) AS pct_failures_with_message,
+ round(countIf(isNotNull(properties.$mcp_tool_category)) * 100.0 / count(), 1) AS pct_with_category,
+ round(countIf(isNotNull(properties.$mcp_intent)) * 100.0 / count(), 1) AS pct_with_intent,
+ round(countIf(isNotNull(properties.$mcp_mode)) * 100.0 / count(), 1) AS pct_with_mode,
+ round(countIf(isNotNull(properties.input_tokens)) * 100.0 / count(), 1) AS pct_with_tokens,
+ uniqIf(toString(properties.$mcp_client_name), isNotNull(properties.$mcp_client_name)) AS distinct_clients
+FROM events
+WHERE event = '$mcp_tool_call'
+ AND properties.$mcp_source = 'posthog_mcp_analytics'
+ AND timestamp >= now() - INTERVAL 7 DAY
+```
+
+Read the result:
+
+- `pct_failures_classified` high → **hono regime with useful classes**: use query 3a. But don't assume
+ this is high just because you're on PostHog's own data — most `$mcp_is_error` failures are _tool-result_
+ errors (the handler returned `{isError:true}` gracefully) which never get classified, so `error_type`
+ stays `'None'`. On PostHog's own project only ~4% of failures carry a real class. When
+ `pct_failures_classified` is low, the **unclassified-failure bucket is the main story** — lean on
+ query 1 (rate), query 2 (struggle), and query 7 (the gap), not the class breakdown.
+- `pct_failures_with_message` high (and classified ~0) → **external-SDK regime**: use query 3b to sample messages.
+- Both ~0 on a project with real failures → **observability gap**: you can still detect _which_ tools fail
+ (query 1) and how agents struggle (query 2), but not _why_ from the taxonomy. That gap is itself
+ emittable (see the scout's Decide section).
+- `pct_with_intent` ≥ ~20 → intent lens (query 5) is worth running. (On PostHog's own data this is ~100%.)
+- `distinct_clients` > 1 → the per-client split (query 6) can localize a client-specific break.
+
+---
+
+## 1. Failure leaderboard (Tier-1 detection — always available)
+
+Ranks tools by failures over a volume floor, with rate and reach. Uses only always-on fields.
+
+```sql
+SELECT
+ coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name)) AS tool,
+ any(properties.$mcp_tool_category) AS category,
+ count() AS calls,
+ countIf(toBool(properties.$mcp_is_error)) AS errors,
+ round(countIf(toBool(properties.$mcp_is_error)) * 100.0 / count(), 1) AS error_rate_pct,
+ uniq(distinct_id) AS users,
+ uniqIf($session_id, $session_id != '') AS sessions
+FROM events
+WHERE event = '$mcp_tool_call'
+ AND properties.$mcp_source = 'posthog_mcp_analytics'
+ AND timestamp >= now() - INTERVAL 7 DAY
+GROUP BY tool
+HAVING calls >= 50 AND error_rate_pct >= 10
+ORDER BY errors DESC
+LIMIT 50
+```
+
+A tool clearing the floor with a high rate **and** reach across many users/sessions is a
+candidate. `category` is `any()` here so it surfaces when populated and is harmless (empty)
+when not.
+
+## 2. Struggle / retry leaderboard (Tier-1 detection — always available, high value)
+
+The signal pure error-rate misses: tools that technically succeed but agents **hammer** or
+**retry** within a session, which almost always means a confusing schema or description.
+Built from the always-on fields since no retry runner exists.
+
+```sql
+SELECT
+ tool,
+ count() AS sessions_using_tool,
+ countIf(calls >= 3) AS sessions_3plus_calls,
+ round(countIf(calls >= 3) * 100.0 / count(), 1) AS pct_sessions_3plus,
+ countIf(errors > 0 AND calls > errors) AS sessions_error_then_more_calls,
+ round(avg(calls), 1) AS avg_calls_per_session,
+ round(avg(errors), 2) AS avg_errors_per_session
+FROM (
+ SELECT
+ $session_id AS session,
+ coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name)) AS tool,
+ count() AS calls,
+ countIf(toBool(properties.$mcp_is_error)) AS errors
+ FROM events
+ WHERE event = '$mcp_tool_call'
+ AND properties.$mcp_source = 'posthog_mcp_analytics'
+ AND $session_id != ''
+ AND timestamp >= now() - INTERVAL 7 DAY
+ GROUP BY session, tool
+)
+GROUP BY tool
+HAVING sessions_using_tool >= 20
+ORDER BY pct_sessions_3plus DESC
+LIMIT 50
+```
+
+Read it:
+
+- `pct_sessions_3plus` high → agents repeatedly re-call the tool in one session — schema/args
+ confusion or the tool not returning what was asked. A strong "needs improvement" signal even
+ at a low error rate.
+- `sessions_error_then_more_calls` high → fail-then-retry loops (the tool errors, the agent
+ reshapes the call and tries again). Points at a misleading schema/description or bad error
+ messaging that doesn't tell the agent how to fix the call.
+
+## 3a. Error-class composition — HONO regime (`pct_failures_classified` non-trivial)
+
+For a candidate tool, split failures by class — this is the fix hypothesis. Keep the `'None'`
+bucket in the result (don't filter it) so you can see how much of the tool's failure is
+_unclassified_ (tool-result errors) vs a nameable class.
+
+```sql
+SELECT
+ toString(properties.$mcp_error_type) AS error_type, -- 'None' = unclassified (tool-result error)
+ count() AS errors,
+ topK(3)(toString(properties.$mcp_error_status)) AS statuses
+FROM events
+WHERE event = '$mcp_tool_call'
+ AND properties.$mcp_source = 'posthog_mcp_analytics'
+ 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 7 DAY
+GROUP BY error_type
+ORDER BY errors DESC
+```
+
+Class → fix hypothesis:
+
+- `None` (unclassified — usually the biggest bucket) → the tool _returned_ an error result to the
+ agent (not found, invalid input handled gracefully, empty result treated as error). These are prime
+ "improve the tool" candidates but carry no server-side detail; pair with query 2 (struggle) and
+ query 5 (intent) to infer what the agent wanted, or treat as an observability gap (query 7).
+- `validation` / `api_4xx` → schema or description misleads agents into malformed calls (docs/schema fix).
+- `permission` → a scope/RBAC gap agents keep hitting.
+- `timeout` → tool too slow (performance/pagination fix).
+- `api_5xx` / `internal` → server-side bug in the tool handler.
+- `missing_context` → the tool needs context the agent isn't reliably supplying.
+- `rate_limited` → capacity/quota (usually a disqualifier unless sustained + broad).
+
+## 3b. Error-message sampling — EXTERNAL-SDK regime (`pct_failures_with_message` high)
+
+When there's no `$mcp_error_type` but messages are present, cluster the raw text instead.
+
+```sql
+SELECT properties.$mcp_error_message AS message, count() AS n
+FROM events
+WHERE event = '$mcp_tool_call'
+ AND properties.$mcp_source = 'posthog_mcp_analytics'
+ AND toBool(properties.$mcp_is_error)
+ AND coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name)) = '<tool>'
+ AND properties.$mcp_error_message != ''
+ AND timestamp >= now() - INTERVAL 7 DAY
+GROUP BY message
+ORDER BY n DESC
+LIMIT 15
+```
+
+## 4. Latency leaderboard (Tier-1 — always available)
+
+Slow tools need improvement even at 0% error rate; sustained high p95 also drives `timeout`
+failures in the hono regime.
+
+```sql
+SELECT
+ coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name)) AS tool,
+ count() AS calls,
+ round(quantile(0.5)(toFloat(properties.$mcp_duration_ms))) AS p50_ms,
+ round(quantile(0.95)(toFloat(properties.$mcp_duration_ms))) AS p95_ms,
+ round(quantile(0.99)(toFloat(properties.$mcp_duration_ms))) AS p99_ms
+FROM events
+WHERE event = '$mcp_tool_call'
+ AND properties.$mcp_source = 'posthog_mcp_analytics'
+ AND timestamp >= now() - INTERVAL 7 DAY
+GROUP BY tool
+HAVING calls >= 50
+ORDER BY p95_ms DESC
+LIMIT 30
+```
+
+## 5. Intent lens (coverage-gated — only if `pct_with_intent` ≥ ~20)
+
+Ties a tool's failures/struggles to what the agent was actually trying to do — the most
+direct route to "what should this tool do differently." Mirrors `MCPToolSampleIntentsQueryRunner`.
+
+```sql
+SELECT
+ toString(properties.$mcp_intent) AS intent,
+ toString(properties.$mcp_intent_source) AS source,
+ count() AS n,
+ countIf(toBool(properties.$mcp_is_error)) AS errors
+FROM events
+WHERE event = '$mcp_tool_call'
+ AND properties.$mcp_source = 'posthog_mcp_analytics'
+ AND coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name)) = '<tool>'
+ AND isNotNull(properties.$mcp_intent)
+ AND timestamp >= now() - INTERVAL 7 DAY
+GROUP BY intent, source
+ORDER BY errors DESC, n DESC
+LIMIT 15
+```
+
+## 6. Per-client / per-mode split (localize a partial break)
+
+Use `$mcp_client_name` (the most reliable cross-platform harness field) to check whether a
+tool is broken universally or only for one client/harness — a different improvement.
+
+```sql
+SELECT
+ coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name)) AS tool,
+ coalesce(nullIf(nullIf(toString(properties.$mcp_client_name), ''), 'None'), 'unknown') AS client,
+ count() AS calls,
+ countIf(toBool(properties.$mcp_is_error)) AS errors,
+ round(countIf(toBool(properties.$mcp_is_error)) * 100.0 / count(), 1) AS error_rate_pct
+FROM events
+WHERE event = '$mcp_tool_call'
+ AND properties.$mcp_source = 'posthog_mcp_analytics'
+ AND coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name)) = '<tool>'
+ AND timestamp >= now() - INTERVAL 7 DAY
+GROUP BY tool, client
+HAVING calls >= 20
+ORDER BY error_rate_pct DESC
+```
+
+In the hono regime you can additionally split by `properties.$mcp_mode` (`'cli'` = single-exec,
+`'tools'` = multi-tool): a tool that fails only in `cli` mode points at the `exec`-wrapper
+schema rather than the tool itself.
+
+## 7. Observability-gap detection (an emittable finding)
+
+Tools that fail materially but carry no diagnosable detail — the improvement is to add error
+instrumentation (or a clearer returned-error message) so failures become debuggable. The
+"no detail" marker is `error_type IN ('', 'None')` **and** no message — on PostHog's own data
+this is the _majority_ of failures (tool-result errors), so tune the ratio/floor to surface the
+worst offenders rather than every tool.
+
+```sql
+SELECT
+ coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name)) AS tool,
+ count() AS calls,
+ countIf(toBool(properties.$mcp_is_error)) AS errors,
+ countIf(toBool(properties.$mcp_is_error)) - countIf(toBool(properties.$mcp_is_error) AND toString(properties.$mcp_error_type) IN ('internal', 'validation', 'api_4xx', 'api_5xx', 'permission', 'timeout', 'rate_limited', 'missing_context')) AS undiagnosable_errors
+FROM events
+WHERE event = '$mcp_tool_call'
+ AND properties.$mcp_source = 'posthog_mcp_analytics'
+ AND timestamp >= now() - INTERVAL 7 DAY
+GROUP BY tool
+HAVING errors >= 50 AND undiagnosable_errors * 1.0 / errors >= 0.9
+ORDER BY undiagnosable_errors DESC
+LIMIT 30
+```
+
+`undiagnosable_errors` = failures minus classified failures (computed by subtraction — a robust
+`NOT IN` on `$mcp_error_type` is not reliable). It also assumes no message; where `$mcp_error_message`
+is populated (external-SDK regime), subtract those too or lower the ratio.
+
+## 8. Output-size bloat — HONO regime only (`pct_with_tokens` high)
+
+Tools that return oversized responses bloat agent context — a pagination/summarization
+improvement. Token fields are the bare keys `input_tokens` / `output_tokens` (no `$` prefix),
+and are estimates, hono-only.
+
+```sql
+SELECT
+ coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name)) AS tool,
+ count() AS calls,
+ round(quantile(0.5)(toFloat(properties.output_tokens))) AS p50_output_tokens,
+ round(quantile(0.95)(toFloat(properties.output_tokens))) AS p95_output_tokens
+FROM events
+WHERE event = '$mcp_tool_call'
+ AND properties.$mcp_source = 'posthog_mcp_analytics'
+ AND isNotNull(properties.output_tokens)
+ AND timestamp >= now() - INTERVAL 7 DAY
+GROUP BY tool
+HAVING calls >= 50
+ORDER BY p95_output_tokens DESC
+LIMIT 30
+```
+
+## 9. By-category rollup (optional, low priority)
+
+For the eventual "tools ranked within category" view. `$mcp_tool_category` is hono-only, so
+gate this on `pct_with_category` being high.
+
+```sql
+SELECT
+ toString(properties.$mcp_tool_category) AS category,
+ count() AS calls,
+ countIf(toBool(properties.$mcp_is_error)) AS errors,
+ round(countIf(toBool(properties.$mcp_is_error)) * 100.0 / count(), 1) AS error_rate_pct
+FROM events
+WHERE event = '$mcp_tool_call'
+ AND properties.$mcp_source = 'posthog_mcp_analytics'
+ AND isNotNull(properties.$mcp_tool_category)
+ AND timestamp >= now() - INTERVAL 7 DAY
+GROUP BY category
+HAVING calls >= 100
+ORDER BY errors DESC
+```