:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp-analytics): MCP analytics skills + flag-gate feedback endpoints (#63886)
Paul D'Ambra71091d6c43c0
diff --git a/products/mcp_analytics/backend/presentation/views.py b/products/mcp_analytics/backend/presentation/views.pyindex 525c2bfc6119..b80589de38c7 100644--- a/products/mcp_analytics/backend/presentation/views.py+++ b/products/mcp_analytics/backend/presentation/views.py@@ -7,7 +7,6 @@ from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schefrom rest_framework import status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.pagination import LimitOffsetPagination-from rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Response@@ -15,7 +14,7 @@ from posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.event_usage import report_user_actionfrom posthog.models.user import User-from posthog.permissions import PostHogFeatureFlagPermission, SingleTenancyOrAdmin+from posthog.permissions import PostHogFeatureFlagPermissionfrom products.mcp_analytics.backend import logicfrom products.mcp_analytics.backend.facade import api, contracts, enums@@ -65,9 +64,12 @@ class MCPSessionPagination(LimitOffsetPagination):class BaseMCPAnalyticsSubmissionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):serializer_class = MCPAnalyticsSubmissionSerializer- # Keep these endpoints staff-only until the MCP tools and auth model are ready for customer traffic.- permission_classes = [IsAuthenticated, SingleTenancyOrAdmin]- scope_object = "INTERNAL"+ # Alpha product: gated behind the mcp-analytics feature flag at the API layer (matching+ # the UI flag) rather than hidden behind a staff-only lock. create -> write, list -> read+ # map to the default scope actions.+ scope_object = "mcp_analytics"+ posthog_feature_flag = "mcp-analytics"+ permission_classes = [PostHogFeatureFlagPermission]pagination_class = MCPAnalyticsPaginationuser_action_name: str = ""diff --git a/products/mcp_analytics/backend/tests/__init__.py b/products/mcp_analytics/backend/tests/__init__.pyindex ed249aad4e57..bdbea53c2a88 100644--- a/products/mcp_analytics/backend/tests/__init__.py+++ b/products/mcp_analytics/backend/tests/__init__.py@@ -1,13 +1,25 @@from contextlib import AbstractContextManager+from unittest.mock import patch+from posthog.models.scoping import team_scope+def _only_mcp_analytics_flag(flag_key: str, *args: object, **kwargs: object) -> bool:+ # Enable just the mcp-analytics alpha flag; leave every other flag at its default (off)+ # so tests don't silently mask unrelated flag-gated behavior.+ return flag_key == "mcp-analytics"++class _MCPAnalyticsTeamScopedTestMixin:- """Wrap setUp/tearDown with team_scope so direct queries against the- fail-closed MCPSession / MCPIntentClusterSnapshot managers find a scope.- Place this BEFORE the TestCase base in the MRO so its setUp creates- self.team first.+ """Shared setUp/tearDown for mcp_analytics presentation tests:++ - wraps the test in ``team_scope`` so direct queries against the fail-closed+ MCPSession / MCPIntentClusterSnapshot managers find a scope, and+ - enables the ``mcp-analytics`` feature flag (and only that flag) for the test,+ since the endpoints are gated behind it.++ Place this BEFORE the TestCase base in the MRO so its setUp creates self.team first."""_team_scope_cm: AbstractContextManager[None] | None = None@@ -17,6 +29,9 @@ class _MCPAnalyticsTeamScopedTestMixin:cm = team_scope(self.team.id) # type: ignore[attr-defined]cm.__enter__()self._team_scope_cm = cm+ flag_patcher = patch("posthoganalytics.feature_enabled", side_effect=_only_mcp_analytics_flag)+ flag_patcher.start()+ self.addCleanup(flag_patcher.stop) # type: ignore[attr-defined]def tearDown(self) -> None:if self._team_scope_cm is not None:diff --git a/products/mcp_analytics/backend/tests/test_presentation.py b/products/mcp_analytics/backend/tests/test_presentation.pyindex aca58f8b975a..bfb6119907fd 100644--- a/products/mcp_analytics/backend/tests/test_presentation.py+++ b/products/mcp_analytics/backend/tests/test_presentation.py@@ -4,12 +4,15 @@ from unittest.mock import patchfrom parameterized import parameterizedfrom rest_framework import status+from posthog.models import Organization, Team+from products.mcp_analytics.backend import intent_generationfrom products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntentClusterSnapshot, MCPSessionfrom products.mcp_analytics.backend.tests import _MCPAnalyticsTeamScopedTestMixinclass TestMCPAnalyticsPresentation(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest):+ # The mcp-analytics feature flag is enabled for the whole test by the mixin's setUp.@parameterized.expand([("feedback_create", "post", "feedback/", {"goal": "understand usage", "feedback": "Need clearer results"}),@@ -46,10 +49,10 @@ class TestMCPAnalyticsPresentation(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest("missing_capability_list", "get", "missing_capabilities/", None),])- def test_endpoints_are_staff_only_in_cloud(+ def test_endpoints_require_feature_flag(self, _name: str, method: str, path: str, payload: dict[str, str] | None) -> None:- with self.is_cloud(True):+ with patch("posthoganalytics.feature_enabled", return_value=False):request = getattr(self.client, method)response = request(f"/api/environments/{self.team.id}/mcp_analytics/{path}", payload, format="json")@@ -274,6 +277,7 @@ class TestMCPAnalyticsPresentation(_MCPAnalyticsTeamScopedTestMixin, APIBaseTestclass TestMCPSessionIntentEndpoint(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest):+ # The mcp-analytics feature flag is enabled for the whole test by the mixin's setUp.def _url(self, session_id: str) -> str:return f"/api/environments/{self.team.id}/mcp_analytics/sessions/{session_id}/generate_intent/"@@ -282,8 +286,8 @@ class TestMCPSessionIntentEndpoint(_MCPAnalyticsTeamScopedTestMixin, APIBaseTestresponse = self.client.post(self._url("abc"))assert response.status_code == status.HTTP_401_UNAUTHORIZED- def test_staff_only_in_cloud(self) -> None:- with self.is_cloud(True):+ def test_requires_feature_flag(self) -> None:+ with patch("posthoganalytics.feature_enabled", return_value=False):response = self.client.post(self._url("abc"))assert response.status_code == status.HTTP_403_FORBIDDEN@@ -327,3 +331,142 @@ class TestMCPSessionIntentEndpoint(_MCPAnalyticsTeamScopedTestMixin, APIBaseTestassert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE# Nothing persisted when generation fails.assert not MCPSession.objects.filter(team=self.team, session_id=session_id).exists()+++class TestMCPAnalyticsCrossTeamIsolation(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest):+ """Team A must never reach Team B's submissions. Now that the submission endpoints are+ reachable by anyone inside the mcp-analytics flag (no longer staff-only), pin the tenant+ boundary: another team's rows never appear in this team's list, and a user who is not a+ member of another team's org is denied when hitting that team's URL.+ """++ def setUp(self) -> None:+ super().setUp()+ # The mcp-analytics feature flag is enabled for the whole test by the mixin's setUp.+ # A team in a different organization that self.user is NOT a member of.+ self.other_org = Organization.objects.create(name="other-org")+ self.other_team = Team.objects.create(organization=self.other_org, name="other-team")++ self.other_feedback = MCPAnalyticsSubmission.objects.create(+ team=self.other_team,+ created_by=self.user,+ kind=MCPAnalyticsSubmission.Kind.FEEDBACK,+ goal="team B goal",+ summary="Team B feedback — must not leak",+ )+ self.other_missing_capability = MCPAnalyticsSubmission.objects.create(+ team=self.other_team,+ created_by=self.user,+ kind=MCPAnalyticsSubmission.Kind.MISSING_CAPABILITY,+ goal="team B goal",+ summary="Team B missing capability — must not leak",+ blocked=False,+ )++ @parameterized.expand(+ [+ ("feedback", "feedback/", "Team B feedback — must not leak"),+ ("missing_capabilities", "missing_capabilities/", "Team B missing capability — must not leak"),+ ]+ )+ def test_other_teams_submissions_never_appear_in_own_list(self, _name: str, path: str, leaked: str) -> None:+ response = self.client.get(f"/api/environments/{self.team.id}/mcp_analytics/{path}")++ assert response.status_code == status.HTTP_200_OK+ summaries = [entry["summary"] for entry in response.json()["results"]]+ assert leaked not in summaries+ assert summaries == []++ @parameterized.expand(+ [+ ("feedback_list", "get", "feedback/", None),+ ("missing_capability_list", "get", "missing_capabilities/", None),+ (+ "feedback_create",+ "post",+ "feedback/",+ {"goal": "understand usage", "feedback": "Need clearer results"},+ ),+ (+ "missing_capability_create",+ "post",+ "missing_capabilities/",+ {"goal": "debug surveys", "missing_capability": "Need an eligibility explainer"},+ ),+ ]+ )+ def test_cannot_reach_another_orgs_team_endpoint(+ self, _name: str, method: str, path: str, payload: dict[str, str] | None+ ) -> None:+ request = getattr(self.client, method)+ response = request(f"/api/environments/{self.other_team.id}/mcp_analytics/{path}", payload, format="json")++ # Not a member of the other org's team: the request is rejected before any data is read.+ assert response.status_code in (status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND)++ def test_creating_in_own_team_does_not_touch_other_team(self) -> None:+ self.client.post(+ f"/api/environments/{self.team.id}/mcp_analytics/feedback/",+ {"goal": "understand usage", "feedback": "My team's feedback"},+ format="json",+ )++ # The other team's submission count is untouched by writes to this team.+ assert MCPAnalyticsSubmission.objects.filter(team=self.other_team).count() == 2+ assert MCPAnalyticsSubmission.objects.filter(team=self.team).count() == 1+++class TestMCPAnalyticsPersonalAPIKeyAccess(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest):+ """The submission endpoints are now reachable by programmatic callers (Personal API+ Keys / OAuth) via the mcp_analytics scope — the previous INTERNAL lock blocked that+ entirely. Pin the scope mapping: the right scope works, the wrong/missing scope 403s.+ The default test client uses force_login and skips the scope check, so this must drive+ a real PAK to exercise the production auth path.+ """++ def _auth_with_pak(self, scopes: list[str]) -> None:+ key = self.create_personal_api_key_with_scopes(scopes)+ self.client.logout()+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {key}")++ def test_read_scope_can_list_submissions(self) -> None:+ self._auth_with_pak(["mcp_analytics:read"])+ response = self.client.get(f"/api/environments/{self.team.id}/mcp_analytics/feedback/")+ assert response.status_code == status.HTTP_200_OK, response.content++ def test_write_scope_can_create_submission(self) -> None:+ self._auth_with_pak(["mcp_analytics:write"])+ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_analytics/feedback/",+ {"goal": "understand usage", "feedback": "Need clearer results"},+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.content++ def test_read_scope_cannot_create_submission(self) -> None:+ self._auth_with_pak(["mcp_analytics:read"])+ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_analytics/feedback/",+ {"goal": "understand usage", "feedback": "Need clearer results"},+ format="json",+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content++ @parameterized.expand(+ [+ ("list", "get", "feedback/", None),+ (+ "create",+ "post",+ "feedback/",+ {"goal": "understand usage", "feedback": "Need clearer results"},+ ),+ ]+ )+ def test_missing_scope_is_forbidden(+ self, _name: str, method: str, path: str, payload: dict[str, str] | None+ ) -> None:+ self._auth_with_pak(["insight:read"])+ request = getattr(self.client, method)+ response = request(f"/api/environments/{self.team.id}/mcp_analytics/{path}", payload, format="json")+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.contentdiff --git a/products/mcp_analytics/mcp/tools.yaml b/products/mcp_analytics/mcp/tools.yamlindex fa34d72b72f5..18d5e93812ed 100644--- a/products/mcp_analytics/mcp/tools.yaml+++ b/products/mcp_analytics/mcp/tools.yaml@@ -67,7 +67,9 @@ tools:enabled: falsemcp-feedback-submit:operation: mcp_analytics_feedback_create- enabled: false+ enabled: true+ scopes:+ - mcp_analytics:writeannotations:readOnly: falsedestructive: false@@ -81,12 +83,15 @@ tools:- feedback- category- attempted_tool+ feature_flag: mcp-analyticsmcp-missing-capability-list:operation: mcp_analytics_missing_capabilities_listenabled: falsemcp-missing-capability-report:operation: mcp_analytics_missing_capabilities_create- enabled: false+ enabled: true+ scopes:+ - mcp_analytics:writeannotations:readOnly: falsedestructive: false@@ -100,3 +105,4 @@ tools:- missing_capability- blocked- attempted_tool+ feature_flag: mcp-analyticsdiff --git a/products/mcp_analytics/skills/exploring-mcp-intent-clusters/SKILL.md b/products/mcp_analytics/skills/exploring-mcp-intent-clusters/SKILL.mdnew file mode 100644index 000000000000..b1391dcefc6c--- /dev/null+++ b/products/mcp_analytics/skills/exploring-mcp-intent-clusters/SKILL.md@@ -0,0 +1,89 @@+---+name: exploring-mcp-intent-clusters+description: >+ Explore PostHog MCP intent clusters — agent goals grouped by semantic+ similarity, with each cluster's tool distribution and error rates. Use when the+ user asks "what are agents trying to do with the MCP?", "group the intents",+ "which goals fail most?", "what does each cluster route to?", wants to+ recompute the clustering, or pastes an MCP analytics intent-clustering URL.+---++# Exploring MCP intent clusters++Intent clustering takes the free-text `$mcp_intent` values agents attach to+their tool calls, embeds them, and groups semantically similar goals into+clusters. Each cluster carries its tool distribution, call counts, and error+rates — answering "what are people _trying_ to do, and does it work?" rather+than "which tool was called".++Unlike tool quality and sessions (which are plain HogQL over `mcp_tool_call`),+clustering needs embeddings and is **not expressible in SQL**. It is served by+two typed tools backed by a stored snapshot.++## Tools++| Tool | Purpose |+| ------------------------------------------------- | ------------------------------------------------- |+| `posthog:mcp-analytics-intent-clusters-retrieve` | Fetch the latest cluster snapshot for the project |+| `posthog:mcp-analytics-intent-clusters-recompute` | Trigger an async recompute of the snapshot |++## Workflow: read the current clusters++```json+posthog:mcp-analytics-intent-clusters-retrieve+{}+```++Returns a snapshot with `status`, `last_computed_at`, `computed_with` (the+embedding model and clustering parameters), and a `clusters` array. Each cluster+has a `label`, `intent_count`, `call_count`, `error_count`, `error_rate_pct`,+`routing_entropy`, a `tool_distribution` (which tools that goal routes to, with+per-tool error rates), and `sample_intents`.++Read clusters by `call_count` for "what are agents mostly doing", or by+`error_rate_pct` for "which goals are failing" — a high error rate on a cluster+points at a class of agent goals the tools serve badly.++`routing_entropy` is how spread-out a cluster's tool usage is: low entropy means+one goal reliably maps to one tool; high entropy means agents are casting around+for the right tool for that goal (often a missing-capability signal).++## Workflow: handle an empty or stale snapshot++- **Empty / idle with no clusters** (`status: idle`, `clusters: []`): no run has+ happened yet. Trigger one (below) and tell the user it computes in the+ background.+- **Stale `last_computed_at`**: offer to recompute.++## Workflow: recompute++```json+posthog:mcp-analytics-intent-clusters-recompute+{}+```++Returns immediately with `status: computing` (HTTP 202); the work runs in the+background. Poll `...-retrieve` until `status` returns to `idle` (done) or+`error`. Don't block waiting — tell the user to re-ask in a minute.++## Constructing UI links++- **Intent clustering**: `https://app.posthog.com/project/<project_id>/mcp-analytics/intent-clustering`++## Tips++- Clusters are only as good as the `$mcp_intent` coverage — if few calls carry+ an intent, clusters will be sparse; cross-check intent coverage with a quick+ `countIf(toString(properties.$mcp_intent) != '')` over `mcp_tool_call`+- A cluster with high `error_rate_pct` plus high `routing_entropy` is the+ strongest "the tools don't serve this goal well" signal — worth a closer look+ at its `sample_intents` and `tool_distribution`+- Recompute is throttled to one run at a time per project; a 202 while already+ computing just re-confirms the in-flight run++## Related skills++- [`exploring-mcp-tool-quality`](../exploring-mcp-tool-quality/SKILL.md) —+ per-tool error rates and latency+- [`exploring-mcp-sessions`](../exploring-mcp-sessions/SKILL.md) — the individual+ runs behind the intentsdiff --git a/products/mcp_analytics/skills/exploring-mcp-sessions/SKILL.md b/products/mcp_analytics/skills/exploring-mcp-sessions/SKILL.mdnew file mode 100644index 000000000000..f72f681b5e75--- /dev/null+++ b/products/mcp_analytics/skills/exploring-mcp-sessions/SKILL.md@@ -0,0 +1,112 @@+---+name: exploring-mcp-sessions+description: >+ Investigate individual PostHog MCP sessions — the sequence of tool calls a+ single agent made in one run, what it was trying to do, and where it went+ wrong. Use when the user asks "what did this MCP session do?", "show me the+ tool calls for session X", "what was the agent's goal?", "which sessions had+ errors?", or pastes an MCP analytics sessions URL.+---++# Exploring MCP sessions++An MCP session is one agent run, identified by `$mcp_session_id` on the+`mcp_tool_call` event. A session is just the set of `mcp_tool_call` events that+share a `$mcp_session_id`, ordered by `timestamp`. Listing sessions and reading+a session's tool calls are both plain HogQL over `events`; the full property+schema and recipes are in the shared reference:+[`products/posthog_ai/skills/querying-posthog-data/references/models-mcp.md`](../../../posthog_ai/skills/querying-posthog-data/references/models-mcp.md).++The one thing SQL cannot do is summarise the agent's _goal_ in prose — that is+the typed tool `posthog:mcp-analytics-sessions-generate-intent`.++## Tools++| Tool | Purpose |+| ------------------------------------------------ | ------------------------------------------------------------- |+| `posthog:execute-sql` | List sessions and read a session's tool-call sequence (HogQL) |+| `posthog:mcp-analytics-sessions-generate-intent` | Generate (or fetch cached) LLM summary of a session's goal |++## Workflow: list recent sessions++Group `mcp_tool_call` by `$mcp_session_id`, deriving start/end, duration, call+count, error count, and the harness:++```sql+posthog:execute-sql+SELECT+ toString(properties.$mcp_session_id) AS session_id,+ min(timestamp) AS session_start,+ max(timestamp) AS session_end,+ dateDiff('second', min(timestamp), max(timestamp)) AS duration_seconds,+ count() AS tool_calls,+ countIf(toBool(properties.$mcp_is_error)) AS errors,+ any(properties.$mcp_client_name) AS client+FROM events+WHERE event = 'mcp_tool_call'+ AND toString(properties.$mcp_session_id) != ''+ AND timestamp >= now() - INTERVAL 7 DAY+GROUP BY session_id+ORDER BY session_start DESC+LIMIT 50+```++Add `HAVING errors > 0` to surface only sessions that hit failures.++## Workflow: read one session's tool calls++The chronological sequence of what the agent did — the heart of debugging a run:++```sql+posthog:execute-sql+SELECT+ timestamp,+ coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name)) AS tool,+ toBool(properties.$mcp_is_error) AS is_error,+ toString(properties.$mcp_error_message) AS error_message,+ round(toFloat(properties.$mcp_duration_ms)) AS duration_ms,+ toString(properties.$mcp_intent) AS intent+FROM events+WHERE event = 'mcp_tool_call'+ AND toString(properties.$mcp_session_id) = '<session_id>'+ORDER BY timestamp ASC+```++Always use the effective-tool-name `coalesce(...)` so single-exec wrapper calls+resolve to the real tool. Read these top to bottom to reconstruct the run.++## Workflow: summarise the agent's goal++When the user wants the _intent_ of a session in prose (not the raw tool list),+call the typed tool — the first call summarises the recorded `$mcp_intent`+values via an LLM and persists the result; later calls return the cached summary:++```json+posthog:mcp-analytics-sessions-generate-intent+{ "id": "<session_id>" }+```++Returns `{ "session_id": ..., "intent": "<prose summary>" }`. If it returns 503,+LLM summarisation is unavailable — fall back to reading the raw `$mcp_intent`+values from the tool-call query above.++## Constructing UI links++- **Sessions list**: `https://app.posthog.com/project/<project_id>/mcp-analytics/sessions`++## Tips++- A session with many calls but no errors that ends abruptly often means the+ agent gave up — check whether the last call returned a large/empty result+- `$mcp_intent` is only present when the client supplied it; absence is common,+ so the generate-intent tool is the more reliable goal signal+- To go from a failing tool (see+ [`exploring-mcp-tool-quality`](../exploring-mcp-tool-quality/SKILL.md)) to the+ sessions that hit it, filter the sessions query on the effective tool name++## Related skills++- [`exploring-mcp-tool-quality`](../exploring-mcp-tool-quality/SKILL.md) — error+ rates and latency across all tools+- [`exploring-mcp-intent-clusters`](../exploring-mcp-intent-clusters/SKILL.md) —+ group goals across many sessionsdiff --git a/products/mcp_analytics/skills/exploring-mcp-tool-quality/SKILL.md b/products/mcp_analytics/skills/exploring-mcp-tool-quality/SKILL.mdnew file mode 100644index 000000000000..b1a405078bf9--- /dev/null+++ b/products/mcp_analytics/skills/exploring-mcp-tool-quality/SKILL.md@@ -0,0 +1,126 @@+---+name: exploring-mcp-tool-quality+description: >+ Investigate the quality of PostHog MCP tool calls — error rates, latency,+ reach, and which tools are failing or slow. Use when the user asks "which+ MCP tool has the highest error rate?", "what's the slowest tool?", "which+ tools fail most often?", "how reliable is tool X?", wants a tool-quality+ matrix, or pastes an MCP analytics tool-quality / dashboard URL and asks+ what it shows.+---++# Exploring MCP tool quality++Any MCP server instrumented with PostHog's MCP analytics SDK emits a+`mcp_tool_call` event on the shared `events` table every time an agent invokes a+tool. There is **no dedicated ClickHouse table** — every field lives as a+`$mcp_*` property on `events`, and every tool-quality metric (error rate, latency+percentiles, reach) is an aggregation over this one event. This is the data+behind the MCP analytics dashboard and tool-quality screens.++**HogQL via `posthog:execute-sql` is the primary path.** There are no typed+tools for tool quality — it is all SQL. The full property schema and the+canonical query recipes live in the shared MCP data reference:+[`products/posthog_ai/skills/querying-posthog-data/references/models-mcp.md`](../../../posthog_ai/skills/querying-posthog-data/references/models-mcp.md).+That reference is the single source of truth for the `$mcp_*` schema and the+effective-tool-name idiom used below — this skill inlines only the headline+"which tool errors most" query for convenience; pull the matrix, latency, and+harness recipes from the reference rather than re-deriving them. Read it before+writing queries.++## The two rules that matter most++- **Always use the effective tool name.** New-SDK events wrap the real tool in+ a single-exec call, so grouping on raw `$mcp_tool_name` collapses everything+ under the wrapper. Use:++ ```sql+ coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name))+ ```++- **Always read `$mcp_is_error` via `toBool(...)`** and cast+ `$mcp_duration_ms` via `toFloat(...)`. The properties are strings.++Always set a time range — these queries scan `events` otherwise.++## Workflow: which tool has the highest error rate++This is the canonical "which tool errors most" question. Rank tools by error+rate, but guard against small-sample noise with a `HAVING` floor on call volume:++```sql+posthog:execute-sql+SELECT+ coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name)) AS tool,+ count() AS total_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 coalesce(nullIf(toString(properties.$mcp_exec_tool_call_name), ''), toString(properties.$mcp_tool_name)) != ''+ AND timestamp >= now() - INTERVAL 30 DAY+GROUP BY tool+HAVING total_calls >= 20+ORDER BY error_rate_pct DESC, total_calls DESC+LIMIT 20+```++Report both **rate and volume** — a 100% error rate over 3 calls is rarely the+real story; a 12% rate over 50,000 calls is. Offer to pull the top+`$mcp_error_message` values for the worst tool (see below).++## Workflow: tool-quality matrix++One row per tool with error rate, latency percentiles, and reach — mirrors the+tool-quality screen. The ready-to-run query is in+[models-mcp.md](../../../posthog_ai/skills/querying-posthog-data/references/models-mcp.md)+under "Tool-quality matrix".++## Workflow: why is a tool failing++Pull the most common error messages for a tool, then correlate to richer+exception detail (`$exception` events carry `$exception_message`, joined by+`$mcp_session_id` / `$session_id` and timestamp):++```sql+posthog:execute-sql+SELECT toString(properties.$mcp_error_message) AS error, 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+```++## Workflow: slowest tools++Swap the aggregate for latency percentiles+(`quantile(0.95)(toFloat(properties.$mcp_duration_ms))`) and order by `p95_ms`.+The matrix query already returns `p50_ms` / `p95_ms`.++## Constructing UI links++- **Dashboard**: `https://app.posthog.com/project/<project_id>/mcp-analytics/dashboard`+- **Tool quality**: `https://app.posthog.com/project/<project_id>/mcp-analytics/tool-quality`++Always surface a UI link so the user can verify visually.++## Tips++- Report error rate **and** call volume together; a `HAVING total_calls >= N`+ floor stops tools with very few calls from topping the list spuriously+- Exclude errored calls from latency percentiles only when asked — failed calls+ are often the slow ones, and dropping them hides the problem+- `$mcp_client_name` lets you cut quality by harness (Claude Code vs Cursor vs+ …); the canonical bucketing `multiIf` is in+ [models-mcp.md](../../../posthog_ai/skills/querying-posthog-data/references/models-mcp.md)+- If the SQL contradicts the tool-quality screen, trust the screen and flag this+ skill for an update — the frontend bucketing logic is the source of truth++## Related skills++- [`exploring-mcp-sessions`](../exploring-mcp-sessions/SKILL.md) — drill into a+ single agent run and its tool sequence+- [`exploring-mcp-intent-clusters`](../exploring-mcp-intent-clusters/SKILL.md) —+ group agent goals and see which intents drive the errorsdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 649cdfe234a3..0d344e4ec3c3 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -4853,6 +4853,36 @@"requires_ai_consent": true,"feature_flag": "mcp-analytics"},+ "mcp-feedback-submit": {+ "description": "Submit qualitative feedback about the current MCP workflow, tool result, or product experience. Use this when the available tools worked but the experience was confusing, incomplete, or could be improved.",+ "category": "MCP analytics",+ "feature": "mcp_analytics",+ "summary": "Submit MCP feedback",+ "title": "Submit MCP feedback",+ "required_scopes": ["mcp_analytics:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "mcp-analytics"+ },+ "mcp-missing-capability-report": {+ "description": "Report that the current MCP tools are insufficient for the user's goal. Use this when a missing tool, missing workflow support, or missing explanation blocks progress.",+ "category": "MCP analytics",+ "feature": "mcp_analytics",+ "summary": "Report missing capability",+ "title": "Report missing capability",+ "required_scopes": ["mcp_analytics:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "mcp-analytics"+ },"notebooks-create": {"description": "Create a new notebook. Provide a title and content. Content is a JSON object representing the notebook's rich text document structure (ProseMirror-based). Returns the created notebook with its short_id.\nEmbedded charts use `{type: \"ph-query\", attrs: {nodeId, query}}` nodes. The `query` object must be one of: (a) `{kind: \"DataVisualizationNode\", source: {kind: \"HogQLQuery\", query: \"SELECT ...\"}, display: \"ActionsBar\", chartSettings: {...}}` for SQL charts — do NOT wrap this in an InsightVizNode; (b) `{kind: \"InsightVizNode\", source: <TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery>}` for product-analytics insights; or (c) `{kind: \"SavedInsightNode\", shortId: \"...\"}` to embed a saved insight. The server rejects other shapes and auto-corrects the common `InsightVizNode` wrapping a SQL chart.","category": "Notebooks",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 15299eeae20b..5b5a6e1c2e86 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -5261,6 +5261,36 @@"requires_ai_consent": true,"feature_flag": "mcp-analytics"},+ "mcp-feedback-submit": {+ "description": "Submit qualitative feedback about the current MCP workflow, tool result, or product experience. Use this when the available tools worked but the experience was confusing, incomplete, or could be improved.",+ "category": "MCP analytics",+ "feature": "mcp_analytics",+ "summary": "Submit MCP feedback",+ "title": "Submit MCP feedback",+ "required_scopes": ["mcp_analytics:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "mcp-analytics"+ },+ "mcp-missing-capability-report": {+ "description": "Report that the current MCP tools are insufficient for the user's goal. Use this when a missing tool, missing workflow support, or missing explanation blocks progress.",+ "category": "MCP analytics",+ "feature": "mcp_analytics",+ "summary": "Report missing capability",+ "title": "Report missing capability",+ "required_scopes": ["mcp_analytics:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "mcp-analytics"+ },"notebook-edit": {"description": "Edit part of a notebook's content. Use this for any change inside a notebook — text, headings, attributes, whole paragraphs. Call `notebooks-retrieve` first to see what to target.\n\nMatching is by content. The tool finds `old_value` anywhere in the notebook and swaps it for `new_value` in place.\n\nOn success, returns the updated notebook with the new content and bumped version. On a 409 or 410 error, the notebook has changed since you loaded it — call `notebooks-retrieve` and re-apply your edit against the latest content.","category": "Notebooks",diff --git a/services/mcp/src/generated/mcp_analytics/api.ts b/services/mcp/src/generated/mcp_analytics/api.tsindex 6de2a61fb888..8ff45bf79542 100644--- a/services/mcp/src/generated/mcp_analytics/api.ts+++ b/services/mcp/src/generated/mcp_analytics/api.ts@@ -3,11 +3,102 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 3 enabled ops+ * PostHog API - MCP 5 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'+/**+ * Create a new MCP feedback submission for the current project.+ */+export const McpAnalyticsFeedbackCreateParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const mcpAnalyticsFeedbackCreateBodyAttemptedToolDefault = ``+export const mcpAnalyticsFeedbackCreateBodyAttemptedToolMax = 200++export const mcpAnalyticsFeedbackCreateBodyMcpClientNameDefault = ``+export const mcpAnalyticsFeedbackCreateBodyMcpClientNameMax = 200++export const mcpAnalyticsFeedbackCreateBodyMcpClientVersionDefault = ``+export const mcpAnalyticsFeedbackCreateBodyMcpClientVersionMax = 100++export const mcpAnalyticsFeedbackCreateBodyMcpProtocolVersionDefault = ``+export const mcpAnalyticsFeedbackCreateBodyMcpProtocolVersionMax = 50++export const mcpAnalyticsFeedbackCreateBodyMcpTransportDefault = ``+export const mcpAnalyticsFeedbackCreateBodyMcpTransportMax = 50++export const mcpAnalyticsFeedbackCreateBodyMcpSessionIdDefault = ``+export const mcpAnalyticsFeedbackCreateBodyMcpSessionIdMax = 200++export const mcpAnalyticsFeedbackCreateBodyMcpTraceIdDefault = ``+export const mcpAnalyticsFeedbackCreateBodyMcpTraceIdMax = 200++export const mcpAnalyticsFeedbackCreateBodyGoalMax = 500++export const mcpAnalyticsFeedbackCreateBodyFeedbackMax = 5000++export const mcpAnalyticsFeedbackCreateBodyCategoryDefault = `other`++export const McpAnalyticsFeedbackCreateBody = /* @__PURE__ */ zod.object({+ attempted_tool: zod+ .string()+ .max(mcpAnalyticsFeedbackCreateBodyAttemptedToolMax)+ .default(mcpAnalyticsFeedbackCreateBodyAttemptedToolDefault)+ .describe('The tool the user tried before leaving feedback, if known.'),+ mcp_client_name: zod+ .string()+ .max(mcpAnalyticsFeedbackCreateBodyMcpClientNameMax)+ .default(mcpAnalyticsFeedbackCreateBodyMcpClientNameDefault)+ .describe('MCP client name, for example Claude Desktop or Cursor.'),+ mcp_client_version: zod+ .string()+ .max(mcpAnalyticsFeedbackCreateBodyMcpClientVersionMax)+ .default(mcpAnalyticsFeedbackCreateBodyMcpClientVersionDefault)+ .describe('Version string for the MCP client when available.'),+ mcp_protocol_version: zod+ .string()+ .max(mcpAnalyticsFeedbackCreateBodyMcpProtocolVersionMax)+ .default(mcpAnalyticsFeedbackCreateBodyMcpProtocolVersionDefault)+ .describe('MCP protocol version negotiated for the session when available.'),+ mcp_transport: zod+ .string()+ .max(mcpAnalyticsFeedbackCreateBodyMcpTransportMax)+ .default(mcpAnalyticsFeedbackCreateBodyMcpTransportDefault)+ .describe('Transport used for the MCP session, for example streamable_http or sse.'),+ mcp_session_id: zod+ .string()+ .max(mcpAnalyticsFeedbackCreateBodyMcpSessionIdMax)+ .default(mcpAnalyticsFeedbackCreateBodyMcpSessionIdDefault)+ .describe('Stable MCP session identifier when available.'),+ mcp_trace_id: zod+ .string()+ .max(mcpAnalyticsFeedbackCreateBodyMcpTraceIdMax)+ .default(mcpAnalyticsFeedbackCreateBodyMcpTraceIdDefault)+ .describe('Trace identifier for the surrounding MCP workflow when available.'),+ goal: zod+ .string()+ .max(mcpAnalyticsFeedbackCreateBodyGoalMax)+ .describe("The user's intended outcome when using MCP."),+ feedback: zod+ .string()+ .max(mcpAnalyticsFeedbackCreateBodyFeedbackMax)+ .describe('Concrete feedback about the MCP experience, tool result, or workflow friction.'),+ category: zod+ .enum(['results', 'usability', 'bug', 'docs', 'other'])+ .describe('* `results` - Results\n* `usability` - Usability\n* `bug` - Bug\n* `docs` - Docs\n* `other` - Other')+ .default(mcpAnalyticsFeedbackCreateBodyCategoryDefault)+ .describe(+ 'High-level category for the feedback.\n\n* `results` - Results\n* `usability` - Usability\n* `bug` - Bug\n* `docs` - Docs\n* `other` - Other'+ ),+})+/*** Return the most recent intent cluster snapshot for the current project. Returns an empty IDLE snapshot when no clustering run has happened yet.*/@@ -30,6 +121,94 @@ export const McpAnalyticsIntentClustersRecomputeParams = /* @__PURE__ */ zod.obj),})+/**+ * Create a new missing capability report for the current project.+ */+export const McpAnalyticsMissingCapabilitiesCreateParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const mcpAnalyticsMissingCapabilitiesCreateBodyAttemptedToolDefault = ``+export const mcpAnalyticsMissingCapabilitiesCreateBodyAttemptedToolMax = 200++export const mcpAnalyticsMissingCapabilitiesCreateBodyMcpClientNameDefault = ``+export const mcpAnalyticsMissingCapabilitiesCreateBodyMcpClientNameMax = 200++export const mcpAnalyticsMissingCapabilitiesCreateBodyMcpClientVersionDefault = ``+export const mcpAnalyticsMissingCapabilitiesCreateBodyMcpClientVersionMax = 100++export const mcpAnalyticsMissingCapabilitiesCreateBodyMcpProtocolVersionDefault = ``+export const mcpAnalyticsMissingCapabilitiesCreateBodyMcpProtocolVersionMax = 50++export const mcpAnalyticsMissingCapabilitiesCreateBodyMcpTransportDefault = ``+export const mcpAnalyticsMissingCapabilitiesCreateBodyMcpTransportMax = 50++export const mcpAnalyticsMissingCapabilitiesCreateBodyMcpSessionIdDefault = ``+export const mcpAnalyticsMissingCapabilitiesCreateBodyMcpSessionIdMax = 200++export const mcpAnalyticsMissingCapabilitiesCreateBodyMcpTraceIdDefault = ``+export const mcpAnalyticsMissingCapabilitiesCreateBodyMcpTraceIdMax = 200++export const mcpAnalyticsMissingCapabilitiesCreateBodyGoalMax = 500++export const mcpAnalyticsMissingCapabilitiesCreateBodyMissingCapabilityMax = 5000++export const mcpAnalyticsMissingCapabilitiesCreateBodyBlockedDefault = true++export const McpAnalyticsMissingCapabilitiesCreateBody = /* @__PURE__ */ zod.object({+ attempted_tool: zod+ .string()+ .max(mcpAnalyticsMissingCapabilitiesCreateBodyAttemptedToolMax)+ .default(mcpAnalyticsMissingCapabilitiesCreateBodyAttemptedToolDefault)+ .describe('The tool the user tried before leaving feedback, if known.'),+ mcp_client_name: zod+ .string()+ .max(mcpAnalyticsMissingCapabilitiesCreateBodyMcpClientNameMax)+ .default(mcpAnalyticsMissingCapabilitiesCreateBodyMcpClientNameDefault)+ .describe('MCP client name, for example Claude Desktop or Cursor.'),+ mcp_client_version: zod+ .string()+ .max(mcpAnalyticsMissingCapabilitiesCreateBodyMcpClientVersionMax)+ .default(mcpAnalyticsMissingCapabilitiesCreateBodyMcpClientVersionDefault)+ .describe('Version string for the MCP client when available.'),+ mcp_protocol_version: zod+ .string()+ .max(mcpAnalyticsMissingCapabilitiesCreateBodyMcpProtocolVersionMax)+ .default(mcpAnalyticsMissingCapabilitiesCreateBodyMcpProtocolVersionDefault)+ .describe('MCP protocol version negotiated for the session when available.'),+ mcp_transport: zod+ .string()+ .max(mcpAnalyticsMissingCapabilitiesCreateBodyMcpTransportMax)+ .default(mcpAnalyticsMissingCapabilitiesCreateBodyMcpTransportDefault)+ .describe('Transport used for the MCP session, for example streamable_http or sse.'),+ mcp_session_id: zod+ .string()+ .max(mcpAnalyticsMissingCapabilitiesCreateBodyMcpSessionIdMax)+ .default(mcpAnalyticsMissingCapabilitiesCreateBodyMcpSessionIdDefault)+ .describe('Stable MCP session identifier when available.'),+ mcp_trace_id: zod+ .string()+ .max(mcpAnalyticsMissingCapabilitiesCreateBodyMcpTraceIdMax)+ .default(mcpAnalyticsMissingCapabilitiesCreateBodyMcpTraceIdDefault)+ .describe('Trace identifier for the surrounding MCP workflow when available.'),+ goal: zod+ .string()+ .max(mcpAnalyticsMissingCapabilitiesCreateBodyGoalMax)+ .describe("The user's intended outcome when using MCP."),+ missing_capability: zod+ .string()+ .max(mcpAnalyticsMissingCapabilitiesCreateBodyMissingCapabilityMax)+ .describe('Capability, tool, or workflow support that is currently missing.'),+ blocked: zod+ .boolean()+ .default(mcpAnalyticsMissingCapabilitiesCreateBodyBlockedDefault)+ .describe("Whether the missing capability blocked the user's progress."),+})+/*** Generate (or return the cached) LLM summary of the agent's goal for a session, derived from its recorded $mcp_intents. The first call summarises and persists the result; subsequent calls return the stored summary.*/diff --git a/services/mcp/src/tools/generated/mcp_analytics.ts b/services/mcp/src/tools/generated/mcp_analytics.tsindex fe556c04be48..c6f35dddfee3 100644--- a/services/mcp/src/tools/generated/mcp_analytics.ts+++ b/services/mcp/src/tools/generated/mcp_analytics.ts@@ -2,7 +2,11 @@import { z } from 'zod'import type { Schemas } from '@/api/generated'-import { McpAnalyticsSessionsGenerateIntentParams } from '@/generated/mcp_analytics/api'+import {+ McpAnalyticsFeedbackCreateBody,+ McpAnalyticsMissingCapabilitiesCreateBody,+ McpAnalyticsSessionsGenerateIntentParams,+} from '@/generated/mcp_analytics/api'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'const McpAnalyticsIntentClustersRecomputeSchema = z.object({})@@ -61,8 +65,85 @@ const mcpAnalyticsSessionsGenerateIntent = (): ToolBase<},})+const McpFeedbackSubmitSchema = McpAnalyticsFeedbackCreateBody.omit({+ mcp_client_name: true,+ mcp_client_version: true,+ mcp_protocol_version: true,+ mcp_transport: true,+ mcp_session_id: true,+ mcp_trace_id: true,+})++const mcpFeedbackSubmit = (): ToolBase<typeof McpFeedbackSubmitSchema, Schemas.MCPAnalyticsSubmission> => ({+ name: 'mcp-feedback-submit',+ schema: McpFeedbackSubmitSchema,+ handler: async (context: Context, params: z.infer<typeof McpFeedbackSubmitSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.attempted_tool !== undefined) {+ body['attempted_tool'] = params.attempted_tool+ }+ if (params.goal !== undefined) {+ body['goal'] = params.goal+ }+ if (params.feedback !== undefined) {+ body['feedback'] = params.feedback+ }+ if (params.category !== undefined) {+ body['category'] = params.category+ }+ const result = await context.api.request<Schemas.MCPAnalyticsSubmission>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/mcp_analytics/feedback/`,+ body,+ })+ return result+ },+})++const McpMissingCapabilityReportSchema = McpAnalyticsMissingCapabilitiesCreateBody.omit({+ mcp_client_name: true,+ mcp_client_version: true,+ mcp_protocol_version: true,+ mcp_transport: true,+ mcp_session_id: true,+ mcp_trace_id: true,+})++const mcpMissingCapabilityReport = (): ToolBase<+ typeof McpMissingCapabilityReportSchema,+ Schemas.MCPAnalyticsSubmission+> => ({+ name: 'mcp-missing-capability-report',+ schema: McpMissingCapabilityReportSchema,+ handler: async (context: Context, params: z.infer<typeof McpMissingCapabilityReportSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.attempted_tool !== undefined) {+ body['attempted_tool'] = params.attempted_tool+ }+ if (params.goal !== undefined) {+ body['goal'] = params.goal+ }+ if (params.missing_capability !== undefined) {+ body['missing_capability'] = params.missing_capability+ }+ if (params.blocked !== undefined) {+ body['blocked'] = params.blocked+ }+ const result = await context.api.request<Schemas.MCPAnalyticsSubmission>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/mcp_analytics/missing_capabilities/`,+ body,+ })+ return result+ },+})+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'mcp-analytics-intent-clusters-recompute': mcpAnalyticsIntentClustersRecompute,'mcp-analytics-intent-clusters-retrieve': mcpAnalyticsIntentClustersRetrieve,'mcp-analytics-sessions-generate-intent': mcpAnalyticsSessionsGenerateIntent,+ 'mcp-feedback-submit': mcpFeedbackSubmit,+ 'mcp-missing-capability-report': mcpMissingCapabilityReport,}