Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(mcp-analytics): filter MCP sessions by errors (#106988)

Lucas Fariabc774a3cf715
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 4e244f51a3b3..b936e3f6a548 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10381,9 +10381,9 @@ snapshots:
scenes-app-mcp-analytics--intent-clustering--light:
hash: v1.k794b7964.82fd6a9108a34ff8808b23b9c1e9255dcbe4f38562bb9e99333877dd303c08b2.qjDLxTHFZT3vcTHmPeG35-orU88GSS277RR2DdXxBdw
scenes-app-mcp-analytics--sessions--dark:
- hash: v1.k794b7964.d7e2a435b3c2d3baa85c1eaae02324089794b2728e31a92b9dedfcb1d92e2858.s2HRNIx6nrjdi0xwEqEzhqoYODlq0JVCIHaHy5ha_Wk
+ hash: v1.k794b7964.4844553e3c8a7420f2b616a57ec3640545c0f282bf4ecb7bcc0ef93c7e7315d1.e6ry4ctQni75OaoudOxk_vuh93h9DggNcHS__akWzpI
scenes-app-mcp-analytics--sessions--light:
- hash: v1.k794b7964.d2363c5259b989b50bf770f821715c3782dbb35641a7f308555f31198583e392.OgecAQt-4DF27Tyv3e7qfOkwpT6kDr1sSuN-9OS0iAM
+ hash: v1.k794b7964.82d20edd75f9cb989d0cbdc1280171dbb274e6380a4d30d325bb2d4940283a32.H21JHgt3hDRHvfWnGbuwQhzPRH80oEkhfcYvhmKHnws
scenes-app-mcp-analytics--tool-quality--dark:
hash: v1.k794b7964.642dca04a5c6cb07edc0f125e9c7e0426a5a5dba0f2d121dd7b9bad9fd2709c9.a8J-gQWdL8aNFNlZuBxwf86m16C4h99rTH0vTEJE4Tc
scenes-app-mcp-analytics--tool-quality--light:
diff --git a/products/mcp_analytics/backend/facade/api.py b/products/mcp_analytics/backend/facade/api.py
index d887f4acc398..8e50cd043b1f 100644
--- a/products/mcp_analytics/backend/facade/api.py
+++ b/products/mcp_analytics/backend/facade/api.py
@@ -101,6 +101,7 @@ def list_mcp_sessions(
order_by: str = "",
date_from: str | None = None,
date_to: str | None = None,
+ has_errors: bool | None = None,
properties: list[AnyPropertyFilterDiscriminated] | None = None,
filter_test_accounts: bool = False,
user: User | None = None,
@@ -113,6 +114,7 @@ def list_mcp_sessions(
order_by=order_by,
date_from=date_from,
date_to=date_to,
+ has_errors=has_errors,
properties=properties,
filter_test_accounts=filter_test_accounts,
user=user,
diff --git a/products/mcp_analytics/backend/facade/contracts.py b/products/mcp_analytics/backend/facade/contracts.py
index 7771b8994115..a8ab79742cce 100644
--- a/products/mcp_analytics/backend/facade/contracts.py
+++ b/products/mcp_analytics/backend/facade/contracts.py
@@ -65,6 +65,7 @@ class CreateMissingCapabilitySubmission:
class MCPSession:
session_id: str
tool_calls: int
+ error_calls: int
session_start: datetime
session_end: datetime
distinct_id_count: int
diff --git a/products/mcp_analytics/backend/logic.py b/products/mcp_analytics/backend/logic.py
index cea1455b8c7d..1143bf572900 100644
--- a/products/mcp_analytics/backend/logic.py
+++ b/products/mcp_analytics/backend/logic.py
@@ -142,7 +142,8 @@ SELECT
countIf(matches) AS tool_call_count,
groupUniqArrayIf(tool_name, matches) AS tools_used,
argMaxIf(event_distinct_id, timestamp, matches) AS distinct_id,
- argMaxIf(client_name, timestamp, matches) AS mcp_client_name
+ argMaxIf(client_name, timestamp, matches) AS mcp_client_name,
+ countIf(matches AND is_error) AS error_calls
FROM (
SELECT
$session_id AS session_id,
@@ -150,6 +151,7 @@ FROM (
distinct_id AS event_distinct_id,
properties.$mcp_tool_name AS tool_name,
properties.$mcp_client_name AS client_name,
+ toString(properties.$mcp_is_error) IN ('true', '1') AS is_error,
{shared_filters} AS matches
FROM events
WHERE event = {event}
@@ -172,6 +174,7 @@ GROUP BY session_id
-- Session-level inclusion: at least one *matching* event inside the requested window.
HAVING countIf(matches AND timestamp >= {window_from} AND timestamp <= {window_to}) > 0
__SEARCH__
+ __HAS_ERRORS__
ORDER BY __ORDER__
LIMIT {limit}
OFFSET {offset}
@@ -187,6 +190,8 @@ _SESSION_SEARCH_FILTER = (
"OR arrayExists(t -> t ILIKE {search}, tools_used))"
)
+_SESSION_HAS_ERRORS_FILTER = {True: "AND error_calls > 0", False: "AND error_calls = 0"}
+
def _normalise_order_by(order_by: str) -> tuple[str, bool]:
"""Validate the order_by query param into ``(column, descending)``.
@@ -213,10 +218,13 @@ def _sessions_cache_key(
order_by: str,
date_from: str,
date_to: str,
+ has_errors: bool | None,
filters: str,
user_id: int | None,
) -> str:
- payload = f"mcp_sessions_{date_from}_{date_to}_{limit}_{offset}_{search}_{order_by}_{filters}_{user_id}"
+ payload = (
+ f"mcp_sessions_{date_from}_{date_to}_{limit}_{offset}_{search}_{order_by}_{has_errors}_{filters}_{user_id}"
+ )
return generate_cache_key(team_id, payload)
@@ -228,6 +236,7 @@ def list_mcp_sessions(
order_by: str = "",
date_from: str | None = None,
date_to: str | None = None,
+ has_errors: bool | None = None,
properties: list[AnyPropertyFilterDiscriminated] | None = None,
filter_test_accounts: bool = False,
user: User | None = None,
@@ -248,6 +257,9 @@ def list_mcp_sessions(
distinct_id, mcp_client_name, and any element of tools_used. ``order_by`` is a
whitelisted column name; prefix with '-' for descending.
+ ``has_errors`` keeps only sessions with at least one errored call (``True``) or none
+ (``False``); ``None`` keeps both. It counts the same matching calls as ``tool_call_count``.
+
``properties`` and ``filter_test_accounts`` are the tabs' shared filters. A session with no
matching event is dropped; a session that keeps some reports how many of *its* calls matched
(``tool_call_count``, ``tools_used``) while ``session_start`` / ``session_end`` describe the
@@ -269,6 +281,7 @@ def list_mcp_sessions(
order_by,
effective_date_from,
date_to or "",
+ has_errors,
_filters_cache_fragment(team, properties, filter_test_accounts),
# Property-level access control is evaluated per member, so two members can get different
# rows from the same filters. Key the cache by the caller to keep them apart.
@@ -286,6 +299,7 @@ def list_mcp_sessions(
order_by=order_by,
date_from=effective_date_from,
date_to=date_to,
+ has_errors=has_errors,
properties=properties,
filter_test_accounts=filter_test_accounts,
user=user,
@@ -305,6 +319,7 @@ def _query_mcp_sessions(
order_by: str,
date_from: str,
date_to: str | None,
+ has_errors: bool | None,
properties: list[AnyPropertyFilterDiscriminated] | None,
filter_test_accounts: bool,
user: User | None,
@@ -346,7 +361,12 @@ def _query_mcp_sessions(
search_text = _SESSION_SEARCH_FILTER
placeholders["search"] = ast.Constant(value=f"%{term}%")
- sql = _MCP_SESSIONS_SQL.replace("__SEARCH__", search_text).replace("__ORDER__", order_text)
+ has_errors_text = "" if has_errors is None else _SESSION_HAS_ERRORS_FILTER[has_errors]
+ sql = (
+ _MCP_SESSIONS_SQL.replace("__SEARCH__", search_text)
+ .replace("__HAS_ERRORS__", has_errors_text)
+ .replace("__ORDER__", order_text)
+ )
query = parse_select(sql, placeholders=placeholders)
# name matches the endpoint operation_id so the query is traceable in query_log
@@ -375,6 +395,7 @@ def _row_to_session_dict(row: tuple[Any, ...]) -> dict[str, Any]:
"tools_used": [tool for tool in (row[5] or []) if tool],
"distinct_id": row[6] or "",
"mcp_client_name": row[7] or "",
+ "error_calls": int(row[8] or 0),
}
@@ -797,6 +818,7 @@ def _to_session_contract(
return contracts.MCPSession(
session_id=row["session_id"],
tool_calls=row["tool_call_count"],
+ error_calls=row["error_calls"],
session_start=row["session_start"],
session_end=row["session_end"],
distinct_id_count=0,
diff --git a/products/mcp_analytics/backend/presentation/serializers.py b/products/mcp_analytics/backend/presentation/serializers.py
index ea76d5a2e094..f224347cfb46 100644
--- a/products/mcp_analytics/backend/presentation/serializers.py
+++ b/products/mcp_analytics/backend/presentation/serializers.py
@@ -233,6 +233,15 @@ class MCPSessionListQuerySerializer(serializers.Serializer):
allow_blank=True,
help_text="End of the window. PostHog date string or absolute ISO timestamp. Defaults to now.",
)
+ has_errors = serializers.BooleanField(
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text=(
+ "Filter by session outcome. true keeps sessions with at least one errored tool call "
+ "($mcp_is_error), false keeps sessions with none. Omit to list both."
+ ),
+ )
properties = PropertyFiltersField(
required=False,
allow_blank=True,
@@ -328,6 +337,13 @@ class MCPSessionSerializer(serializers.Serializer):
tool_calls = serializers.IntegerField(
read_only=True, help_text="Total number of $mcp_tool_call events in the session."
)
+ error_calls = serializers.IntegerField(
+ read_only=True,
+ help_text=(
+ "Number of the session's $mcp_tool_call events with $mcp_is_error true, "
+ "counted over the same properties / filter_test_accounts matches as tool_calls."
+ ),
+ )
session_start = serializers.DateTimeField(
read_only=True, help_text="Timestamp of the first $mcp_tool_call event in the session."
)
diff --git a/products/mcp_analytics/backend/presentation/views.py b/products/mcp_analytics/backend/presentation/views.py
index 5f4c2719dd6d..f64cec33b3a2 100644
--- a/products/mcp_analytics/backend/presentation/views.py
+++ b/products/mcp_analytics/backend/presentation/views.py
@@ -190,6 +190,7 @@ class MCPSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
order_by=params["order_by"],
date_from=params.get("date_from") or None,
date_to=params.get("date_to") or None,
+ has_errors=params["has_errors"],
properties=params["properties"],
filter_test_accounts=params["filter_test_accounts"],
user=cast(User, request.user),
diff --git a/products/mcp_analytics/backend/tests/test_api.py b/products/mcp_analytics/backend/tests/test_api.py
index d656b77225c7..775f72e326a7 100644
--- a/products/mcp_analytics/backend/tests/test_api.py
+++ b/products/mcp_analytics/backend/tests/test_api.py
@@ -111,6 +111,7 @@ class TestListMCPSessions(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin,
distinct_id: str = "anon_seed",
session_start: datetime | None = None,
session_end: datetime | None = None,
+ is_error: bool = False,
) -> None:
"""Seed one $mcp_tool_call event per element of ``tool_sequence``.
@@ -133,9 +134,59 @@ class TestListMCPSessions(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin,
"$session_id": session_id,
"$mcp_tool_name": tool,
"$mcp_client_name": client_name,
+ "$mcp_is_error": is_error,
},
)
+ @parameterized.expand(
+ [
+ (
+ "all_sessions",
+ None,
+ None,
+ {"clean": (2, 0), "partial": (2, 1), "all_fail": (1, 1), "docs_fail": (2, 1)},
+ ),
+ ("with_errors", True, None, {"partial": (2, 1), "all_fail": (1, 1), "docs_fail": (2, 1)}),
+ ("without_errors", False, None, {"clean": (2, 0)}),
+ (
+ "with_errors_among_filtered_calls",
+ True,
+ _tool_name_filter("query_run"),
+ {"partial": (2, 1), "all_fail": (1, 1)},
+ ),
+ (
+ "without_errors_among_filtered_calls",
+ False,
+ _tool_name_filter("query_run"),
+ {"clean": (2, 0), "docs_fail": (1, 0)},
+ ),
+ ]
+ )
+ def test_has_errors_filters_by_session_outcome(
+ self,
+ _name: str,
+ has_errors: bool | None,
+ properties: list[AnyPropertyFilterDiscriminated] | None,
+ expected: dict[str, tuple[int, int]],
+ ) -> None:
+ by_name = {name: str(uuid7()) for name in ("clean", "partial", "all_fail", "docs_fail")}
+ self._seed_session(by_name["clean"], ["query_run", "query_run"])
+ self._seed_session(by_name["partial"], ["query_run"])
+ self._seed_session(by_name["partial"], ["query_run"], is_error=True)
+ self._seed_session(by_name["all_fail"], ["query_run"], is_error=True)
+ self._seed_session(by_name["docs_fail"], ["query_run"])
+ self._seed_session(by_name["docs_fail"], ["docs_search"], is_error=True)
+ flush_persons_and_events()
+
+ page = api.list_mcp_sessions(self.team, limit=50, offset=0, has_errors=has_errors, properties=properties)
+
+ assert {
+ name: (s.tool_calls, s.error_calls)
+ for name, sid in by_name.items()
+ for s in page.results
+ if s.session_id == sid
+ } == expected
+
@parameterized.expand(
[
("property_filter", _tool_name_filter("query_run"), False, {"kept"}),
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
index b84c36ab7ec9..676dd40b9d28 100644
--- a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
+++ b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
@@ -87,6 +87,7 @@ const SESSION_LIST = {
{
session_id: '0193f2a1-aaaa-bbbb-cccc-000000000001',
tool_calls: 42,
+ error_calls: 1,
session_start: '2026-06-07T10:00:00Z',
session_end: '2026-06-07T10:10:10Z',
distinct_id_count: 1,
@@ -100,6 +101,7 @@ const SESSION_LIST = {
{
session_id: '0193f2a1-aaaa-bbbb-cccc-000000000002',
tool_calls: 6,
+ error_calls: 0,
session_start: '2026-06-07T09:30:00Z',
session_end: '2026-06-07T09:31:35Z',
distinct_id_count: 1,
@@ -113,6 +115,7 @@ const SESSION_LIST = {
{
session_id: '0193f2a1-aaaa-bbbb-cccc-000000000003',
tool_calls: 31,
+ error_calls: 4,
session_start: '2026-06-07T08:15:00Z',
session_end: '2026-06-07T08:19:00Z',
distinct_id_count: 1,
diff --git a/products/mcp_analytics/frontend/generated/api.schemas.ts b/products/mcp_analytics/frontend/generated/api.schemas.ts
index 1cdd620f7d33..466531aecb11 100644
--- a/products/mcp_analytics/frontend/generated/api.schemas.ts
+++ b/products/mcp_analytics/frontend/generated/api.schemas.ts
@@ -477,6 +477,8 @@ export interface MCPSessionApi {
readonly session_id: string
/** Total number of $mcp_tool_call events in the session. */
readonly tool_calls: number
+ /** Number of the session's $mcp_tool_call events with $mcp_is_error true, counted over the same properties / filter_test_accounts matches as tool_calls. */
+ readonly error_calls: number
/** Timestamp of the first $mcp_tool_call event in the session. */
readonly session_start: string
/** Timestamp of the most recent $mcp_tool_call event in the session. */
@@ -676,6 +678,11 @@ export type McpAnalyticsSessionsListParams = {
* Whether to also apply the project's internal and test user filters (its test_account_filters setting) on top of `properties`.
*/
filter_test_accounts?: boolean
+ /**
+ * Filter by session outcome. true keeps sessions with at least one errored tool call ($mcp_is_error), false keeps sessions with none. Omit to list both.
+ * @nullable
+ */
+ has_errors?: boolean | null
/**
* Maximum number of sessions to return per page. Defaults to 100; values above 500 are rejected.
* @minimum 1
diff --git a/products/mcp_analytics/frontend/mcpAnalyticsFiltersLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsFiltersLogic.ts
index 464ad8b6db3d..a3dbf56874ba 100644
--- a/products/mcp_analytics/frontend/mcpAnalyticsFiltersLogic.ts
+++ b/products/mcp_analytics/frontend/mcpAnalyticsFiltersLogic.ts
@@ -40,15 +40,14 @@ interface UrlFilters {
propertyFilters: AnyPropertyFilter[]
}
+// kea-router may hand a boolean param back already coerced, or as its string form.
+export function parseUrlBoolean(raw: unknown): boolean | null {
+ return raw === true || raw === 'true' ? true : raw === false || raw === 'false' ? false : null
+}
+
function parseUrlFilters(searchParams: Record<string, any>): UrlFilters {
- const rawFilter = searchParams.filter_test_accounts
return {
- filterTestAccountsOverride:
- rawFilter === true || rawFilter === 'true'
- ? true
- : rawFilter === false || rawFilter === 'false'
- ? false
- : null,
+ filterTestAccountsOverride: parseUrlBoolean(searchParams.filter_test_accounts),
propertyFilters: Array.isArray(searchParams.properties) ? searchParams.properties : [],
}
}
diff --git a/products/mcp_analytics/frontend/sessions/MCPSessionsPlaylist.tsx b/products/mcp_analytics/frontend/sessions/MCPSessionsPlaylist.tsx
index a449a7d1f5de..f6057d3b5edf 100644
--- a/products/mcp_analytics/frontend/sessions/MCPSessionsPlaylist.tsx
+++ b/products/mcp_analytics/frontend/sessions/MCPSessionsPlaylist.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { memo, useRef } from 'react'
-import { IconBolt, IconClock, IconSearch, IconSparkles } from '@posthog/icons'
+import { IconBolt, IconClock, IconSearch, IconSparkles, IconWarning } from '@posthog/icons'
import {
Button,
InputGroup,
@@ -28,6 +28,7 @@ import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'
import { McpDateFilter } from '../components/McpDateFilter'
import { McpSharedFilters } from '../components/McpSharedFilters'
import type { MCPSessionApi } from '../generated/api.schemas'
+import { parseUrlBoolean } from '../mcpAnalyticsFiltersLogic'
import { MCPSessionDetail } from './MCPSessionDetail'
import { type MCPSessionOrderBy, type MCPSessionSorting, mcpSessionsLogic, orderByParam } from './mcpSessionsLogic'
import { formatDuration, sessionDurationMs } from './utils'
@@ -39,6 +40,12 @@ const SORT_OPTIONS: { value: MCPSessionOrderBy; label: string }[] = [
{ value: '-tool_call_count', label: 'Most tool calls' },
]
+const OUTCOME_OPTIONS: { value: 'all' | 'true' | 'false'; label: string }[] = [
+ { value: 'all', label: 'All sessions' },
+ { value: 'true', label: 'With errors' },
+ { value: 'false', label: 'Without errors' },
+]
+
function sortingToValue(sorting: MCPSessionSorting | null): MCPSessionOrderBy {
return (orderByParam(sorting) ?? '-session_start') as MCPSessionOrderBy
}
@@ -148,7 +155,8 @@ function SessionDetailPanel({ className }: { className?: string }): JSX.Element
function SessionsListPanel(): JSX.Element {
const { setFilters, loadMoreSessions, setSorting, selectSession } = useActions(mcpSessionsLogic)
- const { sessions, sessionsLoading, filters, sorting, hasNext, selectedSessionId } = useValues(mcpSessionsLogic)
+ const { sessions, sessionsLoading, filters, sorting, hasNext, selectedSessionId, hasActiveFilters } =
+ useValues(mcpSessionsLogic)
return (
<div className="flex flex-col h-full min-h-0 overflow-hidden rounded border border-primary bg-surface-primary">
@@ -168,6 +176,23 @@ function SessionsListPanel(): JSX.Element {
value={filters.search}
/>
</InputGroup>
+ <Select
+ value={String(filters.hasErrors ?? 'all')}
+ onValueChange={(value) => setFilters({ hasErrors: parseUrlBoolean(value) })}
+ >
+ <SelectTrigger data-attr="mcp-sessions-outcome">
+ <SelectValue>
+ {(value: string) => OUTCOME_OPTIONS.find((o) => o.value === value)?.label ?? value}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {OUTCOME_OPTIONS.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
<Select
value={sortingToValue(sorting)}
onValueChange={(value) => setSorting(valueToSorting(value as MCPSessionOrderBy))}
@@ -198,7 +223,9 @@ function SessionsListPanel(): JSX.Element {
))}
</div>
) : sessions.length === 0 ? (
- <div className="p-4 text-center text-sm text-secondary">No MCP sessions yet</div>
+ <div className="p-4 text-center text-sm text-secondary">
+ {hasActiveFilters ? 'No sessions match these filters' : 'No MCP sessions yet'}
+ </div>
) : (
<>
<ul className="flex flex-col list-none pl-0 m-0 divide-y divide-primary">
@@ -276,6 +303,12 @@ const MCPSessionPreview = memo(function MCPSessionPreview({
<IconBolt />
{session.tool_calls}
</span>
+ {session.error_calls > 0 ? (
+ <span className="flex items-center gap-1 whitespace-nowrap text-danger">
+ <IconWarning />
+ {session.error_calls} {session.error_calls === 1 ? 'error' : 'errors'}
+ </span>
+ ) : null}
{session.mcp_client_name ? (
<span className="flex items-center gap-1 truncate">
<IconSparkles className="shrink-0" />
diff --git a/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.test.ts b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.test.ts
index 3c5722420e76..3fb2c6dbc24e 100644
--- a/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.test.ts
+++ b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.test.ts
@@ -1,5 +1,8 @@
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { urls } from 'scenes/urls'
+
import { initKeaTests } from '~/test/init'
import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
@@ -26,6 +29,13 @@ const toolCall = (eventId: string): any => ({
duration_ms: null,
})
+const TOOL_FILTER: AnyPropertyFilter = {
+ key: '$mcp_tool_name',
+ value: ['create_insight'],
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event,
+}
+
describe('mcpSessionsLogic', () => {
let logic: ReturnType<typeof mcpSessionsLogic.build>
@@ -63,6 +73,34 @@ describe('mcpSessionsLogic', () => {
expect(logic.values.selectedSessionToolCalls.calls.map((call) => call.event_id)).toEqual(['updated'])
})
+ it.each([true, false])('deep-links has_errors=%s into the sessions query and clears it', async (hasErrors) => {
+ await expectLogic(logic, () => {
+ router.actions.push(urls.mcpAnalyticsSessions(), { has_errors: String(hasErrors) })
+ }).toDispatchActions(['loadSessionsSuccess'])
+
+ expect(logic.values.filters.hasErrors).toBe(hasErrors)
+ expect(listMock).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ has_errors: hasErrors }))
+
+ await expectLogic(logic, () => logic.actions.setFilters({ hasErrors: null })).toDispatchActions([
+ 'loadSessionsSuccess',
+ ])
+
+ expect(router.values.searchParams).not.toHaveProperty('has_errors')
+ expect(listMock).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ has_errors: undefined }))
+ })
+
+ it.each([
+ ['nothing', () => {}, false],
+ ['search', () => logic.actions.setFilters({ search: 'abc' }), true],
+ ['has errors', () => logic.actions.setFilters({ hasErrors: false }), true],
+ ['date range', () => logic.actions.setDateFilter('-30d', null), true],
+ ['property filter', () => mcpAnalyticsFiltersLogic.actions.setPropertyFilters([TOOL_FILTER]), true],
+ ['test accounts', () => mcpAnalyticsFiltersLogic.actions.setFilterTestAccounts(true), true],
+ ])('hasActiveFilters with %s', (_name, apply, expected) => {
+ apply()
+ expect(logic.values.hasActiveFilters).toBe(expected)
+ })
+
it('ignores a failed request for a previously selected session', async () => {
let rejectFirst: (error: Error) => void = () => {}
toolCallsMock.mockImplementationOnce(
@@ -157,13 +195,6 @@ describe('mcpSessionsLogic', () => {
})
describe('shared filters', () => {
- const TOOL_FILTER: AnyPropertyFilter = {
- key: '$mcp_tool_name',
- value: ['create_insight'],
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Event,
- }
-
it.each([
[
'restored URL filters',
diff --git a/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts
index 2a24d1cf4897..8d03dd3f3779 100644
--- a/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts
+++ b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts
@@ -14,14 +14,22 @@ import {
mcpAnalyticsSessionsToolCalls,
} from '../generated/api'
import type { MCPSessionApi, MCPSessionIntentApi, MCPToolCallApi } from '../generated/api.schemas'
-import { type MCPSharedQueryFilters, mcpAnalyticsFiltersLogic, sharedFilterParams } from '../mcpAnalyticsFiltersLogic'
+import {
+ type MCPSharedQueryFilters,
+ mcpAnalyticsFiltersLogic,
+ parseUrlBoolean,
+ sharedFilterParams,
+} from '../mcpAnalyticsFiltersLogic'
export interface MCPSessionsFilters {
search: string
+ // true: sessions with at least one errored call; false: sessions with none; null: both.
+ hasErrors: boolean | null
}
const DEFAULT_FILTERS: MCPSessionsFilters = {
search: '',
+ hasErrors: null,
}
export interface MCPSessionsDateFilter {
@@ -103,6 +111,7 @@ export interface mcpSessionsLogicValues {
generatedIntent: MCPSessionIntentApi | null
generatedIntentLoading: boolean
generatingSessionId: string | null
+ hasActiveFilters: boolean
hasNext: boolean
intentOverrides: Record<string, string>
isSelectedSessionGenerating: boolean
@@ -259,6 +268,13 @@ export interface mcpSessionsLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpSessionsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
+ hasActiveFilters: (
+ filters: MCPSessionsFilters,
+ dateFilter: MCPSessionsDateFilter,
+ sharedQueryFilters: Required<
+ Pick<import('~/queries/schema').HogQLFilters, 'filterTestAccounts' | 'properties'>
+ >
+ ) => boolean
selectedSession: (sessions: MCPSessionApi[], selectedSessionId: string | null) => MCPSessionApi | null
selectedSessionIntent: (
selectedSession: MCPSessionApi | null,
@@ -330,6 +346,7 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
}
const response = await mcpAnalyticsSessionsList(String(values.currentProjectId), {
search: values.filters.search || undefined,
+ has_errors: values.filters.hasErrors ?? undefined,
order_by: orderByParam(values.sorting),
date_from: values.dateFilter.dateFrom || undefined,
date_to: values.dateFilter.dateTo || undefined,
@@ -356,13 +373,14 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
// page entirely if the query changed underneath us.
const baseSessions = values.sessions
const generation = cache.sessionsGeneration ?? 0
- const search = values.filters.search
+ const filters = values.filters
const orderBy = orderByParam(values.sorting)
const dateFrom = values.dateFilter.dateFrom
const dateTo = values.dateFilter.dateTo
const sharedFilters = values.sharedQueryFilters
const response = await mcpAnalyticsSessionsList(String(values.currentProjectId), {
- search: search || undefined,
+ search: filters.search || undefined,
+ has_errors: filters.hasErrors ?? undefined,
order_by: orderBy,
date_from: dateFrom || undefined,
date_to: dateTo || undefined,
@@ -372,7 +390,7 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
})
if (
generation !== cache.sessionsGeneration ||
- search !== values.filters.search ||
+ filters !== values.filters ||
orderBy !== orderByParam(values.sorting) ||
dateFrom !== values.dateFilter.dateFrom ||
dateTo !== values.dateFilter.dateTo ||
@@ -518,6 +536,20 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
],
}),
selectors({
+ hasActiveFilters: [
+ (s) => [s.filters, s.dateFilter, s.sharedQueryFilters],
+ (
+ filters: MCPSessionsFilters,
+ dateFilter: MCPSessionsDateFilter,
+ sharedQueryFilters: MCPSharedQueryFilters
+ ): boolean =>
+ !!filters.search ||
+ filters.hasErrors !== null ||
+ dateFilter.dateFrom !== DEFAULT_DATE_FILTER.dateFrom ||
+ dateFilter.dateTo !== DEFAULT_DATE_FILTER.dateTo ||
+ sharedQueryFilters.properties.length > 0 ||
+ sharedQueryFilters.filterTestAccounts,
+ ],
selectedSession: [
(s) => [s.sessions, s.selectedSessionId],
(sessions: MCPSessionApi[], selectedSessionId: string | null): MCPSessionApi | null => {
@@ -638,6 +670,7 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
date_from: values.dateFilter.dateFrom,
date_to: values.dateFilter.dateTo,
search: values.filters.search || null,
+ has_errors: values.filters.hasErrors === null ? null : String(values.filters.hasErrors),
}
for (const [key, value] of Object.entries(params)) {
if (value) {
@@ -661,16 +694,17 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
const dateChanged = dateFrom !== values.dateFilter.dateFrom || dateTo !== values.dateFilter.dateTo
const search = typeof searchParams.search === 'string' ? searchParams.search : ''
- const searchChanged = search !== values.filters.search
+ const hasErrors = parseUrlBoolean(searchParams.has_errors)
+ const filtersChanged = search !== values.filters.search || hasErrors !== values.filters.hasErrors
// setFilters / setDateFilter each reload via their listener; only load directly when
// neither changed and we haven't loaded yet.
- if (searchChanged) {
- actions.setFilters({ search })
+ if (filtersChanged) {
+ actions.setFilters({ search, hasErrors })
}
if (dateChanged) {
actions.setDateFilter(dateFrom, dateTo)
- } else if (!searchChanged && !cache.hasLoaded) {
+ } else if (!filtersChanged && !cache.hasLoaded) {
actions.loadSessions()
}
cache.hasLoaded = true
@@ -684,7 +718,8 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
const hasUrlParams =
typeof searchParams.date_from === 'string' ||
typeof searchParams.date_to === 'string' ||
- typeof searchParams.search === 'string'
+ typeof searchParams.search === 'string' ||
+ searchParams.has_errors !== undefined
if (!hasUrlParams && !cache.hasLoaded) {
cache.hasLoaded = true
actions.loadSessions()
diff --git a/products/mcp_analytics/mcp/tools.yaml b/products/mcp_analytics/mcp/tools.yaml
index 708e568ed6d3..04d07a9561e0 100644
--- a/products/mcp_analytics/mcp/tools.yaml
+++ b/products/mcp_analytics/mcp/tools.yaml
@@ -81,15 +81,16 @@ tools:
List an MCP project's agent sessions — one row per $mcp_session_id, aggregated from that session's
$mcp_tool_call events. Use it to see who is connecting and how active, long-lived, and tool-heavy sessions
are: "which clients are most active this week?", "which sessions called tool X?", "how long do sessions
- usually run?", "which person's sessions made the most calls?". Each row has session_id, tool_calls,
- session_start, session_end, tools_used, mcp_client_name, distinct_id (plus the resolved person_email /
- person_name when the distinct_id maps to a Person), distinct_id_count, and intent (empty until generated),
- newest session first. Sort with `order_by`, but note its keys are the underlying column names: sort
- tool_calls as `tool_call_count`, and `duration_seconds` (session length) is sortable even though it is not
- returned as a field; an unrecognised key silently falls back to newest-first. Also supports a
- case-insensitive `search`, a `date_from`/`date_to` window (default last 7 days), and `limit`/`offset` paging
- — see each parameter for the specifics. To then summarise a single session's goal, follow up with
- mcp-analytics-sessions-generate-intent.
+ usually run?", "which person's sessions made the most calls?", "which sessions hit errors?". Each row has
+ session_id, tool_calls, error_calls (errored calls among those counted in tool_calls), session_start,
+ session_end, tools_used, mcp_client_name, distinct_id (plus the resolved person_email / person_name when the
+ distinct_id maps to a Person), distinct_id_count, and intent (empty until generated), newest session first.
+ Sort with `order_by`, but note its keys are the underlying column names: sort tool_calls as
+ `tool_call_count`, and `duration_seconds` (session length) is sortable even though it is not returned as a
+ field; an unrecognised key silently falls back to newest-first. Also supports a case-insensitive `search`,
+ `has_errors` (true for sessions with at least one errored call, false for sessions with none), a
+ `date_from`/`date_to` window (default last 7 days), and `limit`/`offset` paging — see each parameter for the
+ specifics. To then summarise a single session's goal, follow up with mcp-analytics-sessions-generate-intent.
mcp-analytics-sessions-tool-calls:
operation: mcp_analytics_sessions_tool_calls
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index ea5b03f57e3b..1ebc097c2d9b 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -8882,7 +8882,7 @@
"requires_ai_consent": true
},
"mcp-analytics-sessions-list": {
- "description": "List an MCP project's agent sessions — one row per $mcp_session_id, aggregated from that session's $mcp_tool_call events. Use it to see who is connecting and how active, long-lived, and tool-heavy sessions are: \"which clients are most active this week?\", \"which sessions called tool X?\", \"how long do sessions usually run?\", \"which person's sessions made the most calls?\". Each row has session_id, tool_calls, session_start, session_end, tools_used, mcp_client_name, distinct_id (plus the resolved person_email / person_name when the distinct_id maps to a Person), distinct_id_count, and intent (empty until generated), newest session first. Sort with `order_by`, but note its keys are the underlying column names: sort tool_calls as `tool_call_count`, and `duration_seconds` (session length) is sortable even though it is not returned as a field; an unrecognised key silently falls back to newest-first. Also supports a case-insensitive `search`, a `date_from`/`date_to` window (default last 7 days), and `limit`/`offset` paging — see each parameter for the specifics. To then summarise a single session's goal, follow up with mcp-analytics-sessions-generate-intent.",
+ "description": "List an MCP project's agent sessions — one row per $mcp_session_id, aggregated from that session's $mcp_tool_call events. Use it to see who is connecting and how active, long-lived, and tool-heavy sessions are: \"which clients are most active this week?\", \"which sessions called tool X?\", \"how long do sessions usually run?\", \"which person's sessions made the most calls?\", \"which sessions hit errors?\". Each row has session_id, tool_calls, error_calls (errored calls among those counted in tool_calls), session_start, session_end, tools_used, mcp_client_name, distinct_id (plus the resolved person_email / person_name when the distinct_id maps to a Person), distinct_id_count, and intent (empty until generated), newest session first. Sort with `order_by`, but note its keys are the underlying column names: sort tool_calls as `tool_call_count`, and `duration_seconds` (session length) is sortable even though it is not returned as a field; an unrecognised key silently falls back to newest-first. Also supports a case-insensitive `search`, `has_errors` (true for sessions with at least one errored call, false for sessions with none), a `date_from`/`date_to` window (default last 7 days), and `limit`/`offset` paging — see each parameter for the specifics. To then summarise a single session's goal, follow up with mcp-analytics-sessions-generate-intent.",
"category": "MCP analytics",
"feature": "mcp_analytics",
"summary": "List MCP sessions",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 15f2132c28f4..f0d3ae0b333c 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -9279,7 +9279,7 @@
"requires_ai_consent": true
},
"mcp-analytics-sessions-list": {
- "description": "List an MCP project's agent sessions — one row per $mcp_session_id, aggregated from that session's $mcp_tool_call events. Use it to see who is connecting and how active, long-lived, and tool-heavy sessions are: \"which clients are most active this week?\", \"which sessions called tool X?\", \"how long do sessions usually run?\", \"which person's sessions made the most calls?\". Each row has session_id, tool_calls, session_start, session_end, tools_used, mcp_client_name, distinct_id (plus the resolved person_email / person_name when the distinct_id maps to a Person), distinct_id_count, and intent (empty until generated), newest session first. Sort with `order_by`, but note its keys are the underlying column names: sort tool_calls as `tool_call_count`, and `duration_seconds` (session length) is sortable even though it is not returned as a field; an unrecognised key silently falls back to newest-first. Also supports a case-insensitive `search`, a `date_from`/`date_to` window (default last 7 days), and `limit`/`offset` paging — see each parameter for the specifics. To then summarise a single session's goal, follow up with mcp-analytics-sessions-generate-intent.",
+ "description": "List an MCP project's agent sessions — one row per $mcp_session_id, aggregated from that session's $mcp_tool_call events. Use it to see who is connecting and how active, long-lived, and tool-heavy sessions are: \"which clients are most active this week?\", \"which sessions called tool X?\", \"how long do sessions usually run?\", \"which person's sessions made the most calls?\", \"which sessions hit errors?\". Each row has session_id, tool_calls, error_calls (errored calls among those counted in tool_calls), session_start, session_end, tools_used, mcp_client_name, distinct_id (plus the resolved person_email / person_name when the distinct_id maps to a Person), distinct_id_count, and intent (empty until generated), newest session first. Sort with `order_by`, but note its keys are the underlying column names: sort tool_calls as `tool_call_count`, and `duration_seconds` (session length) is sortable even though it is not returned as a field; an unrecognised key silently falls back to newest-first. Also supports a case-insensitive `search`, `has_errors` (true for sessions with at least one errored call, false for sessions with none), a `date_from`/`date_to` window (default last 7 days), and `limit`/`offset` paging — see each parameter for the specifics. To then summarise a single session's goal, follow up with mcp-analytics-sessions-generate-intent.",
"category": "MCP analytics",
"feature": "mcp_analytics",
"summary": "List MCP sessions",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index fe2afe4194bd..886632426a4b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -59513,6 +59513,8 @@ export namespace Schemas {
readonly session_id: string;
/** Total number of $mcp_tool_call events in the session. */
readonly tool_calls: number;
+ /** Number of the session's $mcp_tool_call events with $mcp_is_error true, counted over the same properties / filter_test_accounts matches as tool_calls. */
+ readonly error_calls: number;
/** Timestamp of the first $mcp_tool_call event in the session. */
readonly session_start: string;
/** Timestamp of the most recent $mcp_tool_call event in the session. */
@@ -115806,6 +115808,11 @@ export namespace Schemas {
* Whether to also apply the project's internal and test user filters (its test_account_filters setting) on top of `properties`.
*/
filter_test_accounts?: boolean;
+ /**
+ * Filter by session outcome. true keeps sessions with at least one errored tool call ($mcp_is_error), false keeps sessions with none. Omit to list both.
+ * @nullable
+ */
+ has_errors?: boolean | null;
/**
* Maximum number of sessions to return per page. Defaults to 100; values above 500 are rejected.
* @minimum 1
diff --git a/services/mcp/src/generated/mcp_analytics/api.ts b/services/mcp/src/generated/mcp_analytics/api.ts
index ffa452a30ae8..0eb2efcf8112 100644
--- a/services/mcp/src/generated/mcp_analytics/api.ts
+++ b/services/mcp/src/generated/mcp_analytics/api.ts
@@ -166,6 +166,12 @@ export const McpAnalyticsSessionsListQueryParams = () => zod.object({
.describe(
"Whether to also apply the project's internal and test user filters (its test_account_filters setting) on top of `properties`."
),
+ has_errors: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Filter by session outcome. true keeps sessions with at least one errored tool call ($mcp_is_error), false keeps sessions with none. Omit to list both.'
+ ),
limit: zod
.number()
.min(1)
diff --git a/services/mcp/src/tools/generated/mcp_analytics.ts b/services/mcp/src/tools/generated/mcp_analytics.ts
index fc90e437ce56..5e159e5744f2 100644
--- a/services/mcp/src/tools/generated/mcp_analytics.ts
+++ b/services/mcp/src/tools/generated/mcp_analytics.ts
@@ -99,6 +99,7 @@ const mcpAnalyticsSessionsList = (): ToolBase<
date_from: params.date_from,
date_to: params.date_to,
filter_test_accounts: params.filter_test_accounts,
+ has_errors: params.has_errors,
limit: params.limit,
offset: params.offset,
order_by: params.order_by,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/mcp-analytics-sessions-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/mcp-analytics-sessions-list.json
index f28873a30637..9514c6931666 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/mcp-analytics-sessions-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/mcp-analytics-sessions-list.json
@@ -14,6 +14,17 @@
"description": "Whether to also apply the project's internal and test user filters (its test_account_filters setting) on top of `properties`.",
"type": "boolean"
},
+ "has_errors": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Filter by session outcome. true keeps sessions with at least one errored tool call ($mcp_is_error), false keeps sessions with none. Omit to list both."
+ },
"limit": {
"default": 100,
"description": "Maximum number of sessions to return per page. Defaults to 100; values above 500 are rejected.",