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 sessions api responses (#103009)

Lucas Fariad906b9cbf136
diff --git a/products/mcp_analytics/backend/facade/api.py b/products/mcp_analytics/backend/facade/api.py
index 9b74a06299e7..d887f4acc398 100644
--- a/products/mcp_analytics/backend/facade/api.py
+++ b/products/mcp_analytics/backend/facade/api.py
@@ -3,6 +3,8 @@ from datetime import datetime
from django.db import transaction
from django.utils import timezone
+from posthog.schema import AnyPropertyFilterDiscriminated
+
from posthog.hogql import ast
from posthog.hogql.parser import parse_expr
@@ -99,9 +101,21 @@ def list_mcp_sessions(
order_by: str = "",
date_from: str | None = None,
date_to: str | None = None,
+ properties: list[AnyPropertyFilterDiscriminated] | None = None,
+ filter_test_accounts: bool = False,
+ user: User | None = None,
) -> contracts.MCPSessionsPage:
return logic.list_mcp_sessions(
- team, limit=limit, offset=offset, search=search, order_by=order_by, date_from=date_from, date_to=date_to
+ team,
+ limit=limit,
+ offset=offset,
+ search=search,
+ order_by=order_by,
+ date_from=date_from,
+ date_to=date_to,
+ properties=properties,
+ filter_test_accounts=filter_test_accounts,
+ user=user,
)
@@ -111,8 +125,20 @@ def list_mcp_tool_calls(
limit: int,
offset: int,
date_from: datetime | None = None,
+ properties: list[AnyPropertyFilterDiscriminated] | None = None,
+ filter_test_accounts: bool = False,
+ user: User | None = None,
) -> contracts.MCPToolCallsPage:
- return logic.list_mcp_tool_calls(team, session_id=session_id, limit=limit, offset=offset, date_from=date_from)
+ return logic.list_mcp_tool_calls(
+ team,
+ session_id=session_id,
+ limit=limit,
+ offset=offset,
+ date_from=date_from,
+ properties=properties,
+ filter_test_accounts=filter_test_accounts,
+ user=user,
+ )
def generate_session_intent(team: Team, session_id: str, date_from: datetime | None = None) -> str:
@@ -136,13 +162,20 @@ def generate_intent_digest(team: Team) -> contracts.IntentDigest:
return logic.generate_intent_digest(team)
-def get_activity_overview(team: Team) -> contracts.ActivityOverview:
+def get_activity_overview(
+ team: Team,
+ properties: list[AnyPropertyFilterDiscriminated] | None = None,
+ filter_test_accounts: bool = False,
+ user: User | None = None,
+) -> contracts.ActivityOverview:
"""Compute the activity view's aggregates and recent-call feed in one pass.
Bounded to the last 30 days; always computed fresh (the view polls to watch
- data arrive).
+ data arrive). ``properties`` and ``filter_test_accounts`` are the tabs' shared filters.
"""
- return logic.get_activity_overview(team)
+ return logic.get_activity_overview(
+ team, properties=properties, filter_test_accounts=filter_test_accounts, user=user
+ )
def get_intent_cluster_snapshot(team: Team, tool: str | None = None) -> contracts.IntentClusterSnapshot:
diff --git a/products/mcp_analytics/backend/logic.py b/products/mcp_analytics/backend/logic.py
index 5bb843953ebc..cea1455b8c7d 100644
--- a/products/mcp_analytics/backend/logic.py
+++ b/products/mcp_analytics/backend/logic.py
@@ -8,7 +8,7 @@ from django.core.cache import cache
from django.db.models import QuerySet
from django.utils import timezone
-from posthog.schema import DateRange
+from posthog.schema import AnyPropertyFilterDiscriminated, DateRange, EventPropertyFilter
from posthog.hogql import ast
from posthog.hogql.parser import parse_select
@@ -31,6 +31,7 @@ from products.mcp_analytics.backend.constants import (
MCP_TOOL_CALL_EVENT,
)
from products.mcp_analytics.backend.facade import contracts, enums
+from products.mcp_analytics.backend.hogql_queries.base import shared_filter_exprs
from products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntentClusterSnapshot, MCPSession
# How long a snapshot may sit in COMPUTING before we assume the run died and
@@ -53,6 +54,7 @@ FROM events
WHERE event = {event}
AND timestamp >= {date_from}
AND $session_id = {session_id}
+ AND {shared_filters}
ORDER BY timestamp ASC, event_id ASC
LIMIT {limit}
OFFSET {offset}
@@ -63,6 +65,28 @@ def list_submissions(team: Team, kind: enums.SubmissionKind) -> QuerySet[MCPAnal
return MCPAnalyticsSubmission.objects.filter(team=team, kind=kind).order_by("-created_at")
+def shared_filters_expr(
+ team: Team,
+ properties: list[AnyPropertyFilterDiscriminated] | None,
+ filter_test_accounts: bool,
+) -> ast.Expr:
+ """The MCP analytics tabs' shared property filters as one event-level HogQL expression.
+
+ The raw SQL here ANDs a single placeholder into its WHERE, so the runners' list form is folded
+ into one expression, with ``true`` when nothing is selected.
+ """
+ exprs = shared_filter_exprs(team, properties, filter_test_accounts)
+ return ast.And(exprs=exprs) if exprs else ast.Constant(value=True)
+
+
+def _filters_cache_fragment(
+ team: Team, properties: list[AnyPropertyFilterDiscriminated] | None, filter_test_accounts: bool
+) -> str:
+ dumped = [prop.model_dump(mode="json", exclude_none=True) for prop in (properties or [])]
+ test_account_filters = team.test_account_filters if filter_test_accounts else []
+ return json.dumps([dumped, test_account_filters], sort_keys=True)
+
+
SESSION_SORT_FIELDS: frozenset[str] = frozenset(
{
"session_id",
@@ -80,15 +104,7 @@ DEFAULT_SESSION_SORT_COLUMN = "session_start"
# default so both tabs show the same set of sessions out of the box. The UI always
# sends an explicit range; this only covers param-less API/token callers.
DEFAULT_SESSIONS_DATE_FROM = "-7d"
-
-# A session that overlaps the window must be reported with its *full* stats (true
-# session_start/end/duration/tool count), not just its in-window slice. We get that
-# by scanning a window padded by this buffer on each side, then keeping only sessions
-# with at least one event actually inside the window. The buffer bounds the extra scan
-# while capturing the whole span of any realistically-long MCP session; a session whose
-# span exceeds it would have its stats clipped at the buffer edge (rare — agent
-# sessions are minutes-to-hours; a multi-day span usually means a reused session_id).
-SESSION_OVERLAP_BUFFER = timedelta(days=1)
+SESSION_OVERLAP_BUFFER = timedelta(days=7)
# Short TTL so concurrent dashboard tabs / auto-refreshes share one ClickHouse
# aggregation instead of each re-running it — long enough to absorb a burst,
@@ -101,11 +117,16 @@ SESSIONS_CACHE_TTL_SECONDS = 30
# validated structural fragments injected before parsing; {placeholders} are HogQL
# value placeholders.
#
-# Session-level windowing: aggregate over the buffered range [scan_from, scan_to] so
-# each session's stats span its *whole* set of events, then keep only sessions with an
-# event inside the requested [window_from, window_to] via the HAVING countIf. This is
-# why a session straddling the window boundary reports full (not clipped) start/end/
-# duration/count, and why its detail view (bounded by session_start) shows every event.
+# Session-level windowing: find sessions with a matching event inside the selected
+# window, then aggregate within a bounded overlap. The timestamp bound lets the
+# events sort key prune the scan. Longer sessions need a session-indexed source
+# for complete stats without reading the team's full event history.
+#
+# The shared filters are a per-event `matches` flag rather than a WHERE clause, so they
+# narrow *what the session did* (tool_call_count, tools_used, and which client and user
+# the row names) without moving *when it ran* within the scan. session_start must stay
+# the first scanned event, not the first matching call: it bounds the detail scan and
+# intent generation. A session with no matching event is dropped by the HAVING.
#
# NB: the session id reads from the `$session_id` field, NOT `properties.$session_id`.
# `$session_id` is a materialised events column; the `properties.` accessor renders it
@@ -114,26 +135,42 @@ SESSIONS_CACHE_TTL_SECONDS = 30
# column consistently across SELECT/GROUP/HAVING/ORDER.
_MCP_SESSIONS_SQL = """
SELECT
- $session_id AS session_id,
+ session_id,
min(timestamp) AS session_start,
max(timestamp) AS session_end,
dateDiff('second', min(timestamp), max(timestamp)) AS duration_seconds,
- count() AS tool_call_count,
- groupUniqArray(properties.$mcp_tool_name) AS tools_used,
- argMax(distinct_id, timestamp) AS distinct_id,
- argMax(properties.$mcp_client_name, timestamp) AS mcp_client_name
-FROM events
-WHERE event = {event}
- -- Buffered range so an overlapping session's events outside the window still
- -- aggregate into its full stats; the timestamp bounds keep the sort key pruning.
- AND timestamp >= {scan_from}
- AND timestamp <= {scan_to}
- -- $session_id is a materialised String column — '' (not NULL) for sessionless
- -- events — so a bare `!= ''` drops them without a coalesce.
- AND $session_id != ''
+ 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
+FROM (
+ SELECT
+ $session_id AS session_id,
+ timestamp,
+ distinct_id AS event_distinct_id,
+ properties.$mcp_tool_name AS tool_name,
+ properties.$mcp_client_name AS client_name,
+ {shared_filters} AS matches
+ FROM events
+ WHERE event = {event}
+ AND timestamp >= {scan_from}
+ AND timestamp <= {scan_to}
+ -- $session_id is a materialised String column — '' (not NULL) for sessionless
+ -- events — so a bare `!= ''` drops them without a coalesce.
+ AND $session_id != ''
+ AND $session_id IN (
+ SELECT $session_id
+ FROM events
+ WHERE event = {event}
+ AND timestamp >= {window_from}
+ AND timestamp <= {window_to}
+ AND $session_id != ''
+ AND {shared_filters}
+ )
+)
GROUP BY session_id
--- Session-level inclusion: at least one event inside the requested window.
-HAVING countIf(timestamp >= {window_from} AND timestamp <= {window_to}) > 0
+-- 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__
ORDER BY __ORDER__
LIMIT {limit}
@@ -169,9 +206,17 @@ def _normalise_order_by(order_by: str) -> tuple[str, bool]:
def _sessions_cache_key(
- team_id: int, limit: int, offset: int, search: str, order_by: str, date_from: str, date_to: str
+ team_id: int,
+ limit: int,
+ offset: int,
+ search: str,
+ order_by: str,
+ date_from: str,
+ date_to: str,
+ filters: str,
+ user_id: int | None,
) -> str:
- payload = f"mcp_sessions_{date_from}_{date_to}_{limit}_{offset}_{search}_{order_by}"
+ payload = f"mcp_sessions_{date_from}_{date_to}_{limit}_{offset}_{search}_{order_by}_{filters}_{user_id}"
return generate_cache_key(team_id, payload)
@@ -183,13 +228,15 @@ def list_mcp_sessions(
order_by: str = "",
date_from: str | None = None,
date_to: str | None = None,
+ properties: list[AnyPropertyFilterDiscriminated] | None = None,
+ filter_test_accounts: bool = False,
+ user: User | None = None,
) -> contracts.MCPSessionsPage:
"""List a page of MCP sessions for a team, aggregated on the fly from $mcp_tool_call events.
One row per $session_id whose session overlaps the selected window, grouped in ClickHouse and
- scoped to the team so the events sort key prunes the scan. Stats are full-session: a session
- that straddles the window boundary reports its true start/end/duration/tool count, not just the
- in-window slice (see ``_MCP_SESSIONS_SQL`` for the buffered-scan + ``countIf`` mechanism).
+ scoped to the team. Stats include calls up to ``SESSION_OVERLAP_BUFFER`` outside the window;
+ longer sessions are clipped so the events sort key can prune the scan.
Over-fetches one row to report ``has_next`` (replay-style) without a separate count query.
Results are cached briefly so concurrent dashboard refreshes share a single aggregation.
@@ -201,11 +248,32 @@ 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.
+ ``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
+ scanned session span, because those bound the detail and intent scans.
+
+ ``user`` is the caller. It carries through to ``execute_hogql_query`` so property-level access
+ control is evaluated for that member, not with the project defaults, because ``properties`` is
+ caller-supplied and would otherwise read restricted properties.
+
Person email/name are resolved from distinct_id via personhog. ``intent`` is
empty until the ad-hoc summary endpoint (separate PR) fills the intent seam.
"""
effective_date_from = date_from or DEFAULT_SESSIONS_DATE_FROM
- cache_key = _sessions_cache_key(team.id, limit, offset, search, order_by, effective_date_from, date_to or "")
+ cache_key = _sessions_cache_key(
+ team.id,
+ limit,
+ offset,
+ search,
+ order_by,
+ effective_date_from,
+ date_to or "",
+ _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.
+ user.pk if user is not None else None,
+ )
cached = cache.get(cache_key)
if cached is not None:
return cached
@@ -218,6 +286,9 @@ def list_mcp_sessions(
order_by=order_by,
date_from=effective_date_from,
date_to=date_to,
+ properties=properties,
+ filter_test_accounts=filter_test_accounts,
+ user=user,
)
# Don't cache empty results: a newly set-up team's first sessions would
# otherwise stay hidden for the full TTL.
@@ -234,6 +305,9 @@ def _query_mcp_sessions(
order_by: str,
date_from: str,
date_to: str | None,
+ properties: list[AnyPropertyFilterDiscriminated] | None,
+ filter_test_accounts: bool,
+ user: User | None,
) -> contracts.MCPSessionsPage:
column, descending = _normalise_order_by(order_by)
# Append the unique session_id as a tiebreaker so the sort is a *total* order.
@@ -243,8 +317,8 @@ def _query_mcp_sessions(
order_text = f"{column} {direction}" if column == "session_id" else f"{column} {direction}, session_id ASC"
# Resolve the date strings (relative like '-7d' or absolute ISO) to concrete bounds,
- # the same path the dashboard uses. We need both the window and a buffered scan range,
- # so resolve here rather than via the HogQL {filters} placeholder (which only yields one).
+ # the same path the dashboard uses. Resolve both bounds here rather than via the
+ # HogQL {filters} placeholder (which only yields one).
query_date_range = QueryDateRange(
date_range=DateRange(date_from=date_from, date_to=date_to),
team=team,
@@ -263,6 +337,7 @@ def _query_mcp_sessions(
"window_to": ast.Constant(value=window_to),
"limit": ast.Constant(value=limit + 1),
"offset": ast.Constant(value=offset),
+ "shared_filters": shared_filters_expr(team, properties, filter_test_accounts),
}
search_text = ""
@@ -279,7 +354,7 @@ def _query_mcp_sessions(
with tags_context(
product=Product.MCP_ANALYTICS, feature=Feature.QUERY, team_id=team.id, name="mcp_analytics_sessions_list"
):
- response = execute_hogql_query(query=query, team=team)
+ response = execute_hogql_query(query=query, team=team, user=user)
rows = [_row_to_session_dict(row) for row in (response.results or [])]
has_next = len(rows) > limit
@@ -424,22 +499,19 @@ ACTIVITY_RECENT_CALLS_LIMIT = 20
_ACTIVITY_STATS_SQL = f"""
SELECT
- countIf(is_tool_call) AS total_calls,
- uniqIf(tool, is_tool_call) AS distinct_tools,
- uniqIf(session_id, is_tool_call AND session_id != '') AS distinct_sessions,
+ count() AS total_calls,
+ uniq(tool) AS distinct_tools,
+ uniqIf(session_id, session_id != '') AS distinct_sessions,
-- Counted over the resolved *label*, not the token: one client can arrive under
-- several tokens (`codex-mcp-client` and the `openai-mcp … (Codex)` user-agent both
-- mean Codex), which the Clients card folds into one row, so counting tokens would
-- put "2 clients" next to a one-row card. The raw `$mcp_client_name` is absent from
-- every non-initialize call and cannot be counted here at all.
- uniqIf({mcp_harness.harness_label_or_token_sql("h")}, is_tool_call AND h != '') AS distinct_clients,
- countIf(is_tool_call AND has_intent) AS calls_with_intent,
- countIf(is_tool_call AND is_error) AS error_calls,
- countIf(is_missing_capability) AS missing_capability_reports
+ uniqIf({mcp_harness.harness_label_or_token_sql("h")}, h != '') AS distinct_clients,
+ countIf(has_intent) AS calls_with_intent,
+ countIf(is_error) AS error_calls
FROM (
SELECT
- event = {{tool_call_event}} AS is_tool_call,
- event = {{missing_capability_event}} AS is_missing_capability,
properties.$mcp_tool_name AS tool,
$session_id AS session_id,
coalesce(properties.$mcp_intent, '') != '' AS has_intent,
@@ -447,10 +519,18 @@ FROM (
{mcp_harness.HARNESS_TOKEN_SQL} AS h,
{mcp_harness.HARNESS_DISPLAY_NAME_SQL} AS client_display
FROM events
- WHERE event IN ({{tool_call_event}}, {{missing_capability_event}}) AND timestamp >= {{date_from}}
+ WHERE event = {{tool_call_event}} AND timestamp >= {{date_from}}
+ AND {{shared_filters}}
)
"""
+_ACTIVITY_MISSING_CAPABILITY_SQL = """
+SELECT count()
+FROM events
+WHERE event = {missing_capability_event} AND timestamp >= {date_from}
+ AND {missing_capability_filters}
+"""
+
_ACTIVITY_TOP_TOOLS_SQL = """
SELECT
properties.$mcp_tool_name AS tool,
@@ -458,6 +538,7 @@ SELECT
countIf(toString(properties.$mcp_is_error) IN ('true', '1')) AS errors
FROM events
WHERE event = {tool_call_event} AND properties.$mcp_tool_name IS NOT NULL AND timestamp >= {date_from}
+ AND {shared_filters}
GROUP BY tool
ORDER BY calls DESC
LIMIT {limit}
@@ -481,6 +562,7 @@ FROM (
{mcp_harness.HARNESS_DISPLAY_NAME_SQL} AS client_display
FROM events
WHERE event = {{tool_call_event}} AND timestamp >= {{date_from}}
+ AND {{shared_filters}}
)
GROUP BY client
ORDER BY calls DESC
@@ -511,6 +593,7 @@ FROM (
{mcp_harness.HARNESS_DISPLAY_NAME_SQL} AS client_display
FROM events
WHERE event = {{tool_call_event}} AND timestamp >= {{date_from}}
+ AND {{shared_filters}}
ORDER BY timestamp DESC
LIMIT {{limit}}
)
@@ -548,14 +631,21 @@ def _extract_error_message(raw: Any) -> str | None:
return value
-def _run_activity_query(team: Team, sql: str, name: str, placeholders: dict[str, ast.Constant]) -> list[Any]:
+def _run_activity_query(
+ team: Team, sql: str, name: str, placeholders: dict[str, ast.Expr], user: User | None
+) -> list[Any]:
query = parse_select(sql, placeholders={**placeholders})
with tags_context(product=Product.MCP_ANALYTICS, feature=Feature.QUERY, team_id=team.id, name=name):
- response = execute_hogql_query(query=query, team=team)
+ response = execute_hogql_query(query=query, team=team, user=user)
return response.results or []
-def get_activity_overview(team: Team) -> contracts.ActivityOverview:
+def get_activity_overview(
+ team: Team,
+ properties: list[AnyPropertyFilterDiscriminated] | None = None,
+ filter_test_accounts: bool = False,
+ user: User | None = None,
+) -> contracts.ActivityOverview:
"""Compute everything the activity view renders, bounded to ``ACTIVITY_WINDOW``.
Always computed fresh: the view's whole point is watching data arrive, so callers
@@ -565,19 +655,49 @@ def get_activity_overview(team: Team) -> contracts.ActivityOverview:
latency summed, which left the summary sentence landing long after the live feed
below it had rendered — the feed's own total is an index-only ``count()``, while
every query here reads properties across the whole window.
+
+ ``properties`` and ``filter_test_accounts`` are the tabs' shared filters. Event-property
+ filters narrow the tool-call sections. Person/session filters and test-account exclusions also
+ narrow missing-capability reports, whose events do not carry tool-call properties.
+
+ ``user`` is the caller. It carries through to ``execute_hogql_query`` so property-level access
+ control is evaluated for that member, not with the project defaults, because ``properties`` is
+ caller-supplied and would otherwise read restricted properties.
"""
date_from = ast.Constant(value=timezone.now() - ACTIVITY_WINDOW)
tool_call_event = ast.Constant(value=MCP_TOOL_CALL_EVENT)
+ shared_filters = shared_filters_expr(team, properties, filter_test_accounts)
+ missing_capability_filters = shared_filters_expr(
+ team,
+ [
+ property_filter
+ for property_filter in properties or []
+ if not isinstance(property_filter, EventPropertyFilter)
+ ],
+ filter_test_accounts,
+ )
- stats_rows, top_tools_rows, clients_rows, recent_calls_rows = map_in_caller_context(
- lambda spec: _run_activity_query(team, *spec),
+ def run_query(spec: tuple[str, str, object]) -> list[Any]:
+ assert isinstance(spec[2], dict)
+ return _run_activity_query(team, spec[0], spec[1], {**spec[2], "shared_filters": shared_filters}, user)
+
+ stats_rows, missing_capability_rows, top_tools_rows, clients_rows, recent_calls_rows = map_in_caller_context(
+ run_query,
[
(
_ACTIVITY_STATS_SQL,
"mcp_analytics_activity_stats",
{
"tool_call_event": tool_call_event,
+ "date_from": date_from,
+ },
+ ),
+ (
+ _ACTIVITY_MISSING_CAPABILITY_SQL,
+ "mcp_analytics_activity_missing_capabilities",
+ {
"missing_capability_event": ast.Constant(value=MCP_MISSING_CAPABILITY_EVENT),
+ "missing_capability_filters": missing_capability_filters,
"date_from": date_from,
},
),
@@ -612,7 +732,8 @@ def get_activity_overview(team: Team) -> contracts.ActivityOverview:
thread_name_prefix="mcp_activity",
)
- stats_row = stats_rows[0] if stats_rows else [0] * 7
+ stats_row = stats_rows[0] if stats_rows else [0] * 6
+ missing_capability_row = missing_capability_rows[0] if missing_capability_rows else [0]
stats = contracts.ActivityStats(
total_calls=_parse_int(stats_row[0]) or 0,
distinct_tools=_parse_int(stats_row[1]) or 0,
@@ -620,7 +741,7 @@ def get_activity_overview(team: Team) -> contracts.ActivityOverview:
distinct_clients=_parse_int(stats_row[3]) or 0,
calls_with_intent=_parse_int(stats_row[4]) or 0,
error_calls=_parse_int(stats_row[5]) or 0,
- missing_capability_reports=_parse_int(stats_row[6]) or 0,
+ missing_capability_reports=_parse_int(missing_capability_row[0]) or 0,
)
top_tools = [
@@ -694,6 +815,9 @@ def list_mcp_tool_calls(
limit: int,
offset: int,
date_from: datetime | None = None,
+ properties: list[AnyPropertyFilterDiscriminated] | None = None,
+ filter_test_accounts: bool = False,
+ user: User | None = None,
) -> contracts.MCPToolCallsPage:
"""List a page of a session's $mcp_tool_call events in chronological order.
@@ -704,6 +828,13 @@ def list_mcp_tool_calls(
``limit`` / ``offset`` page through the session's calls; over-fetch one row to report
``has_next`` without a separate count query.
+
+ ``properties`` and ``filter_test_accounts`` are the tabs' shared filters, so the detail view
+ shows the same calls the session list counted.
+
+ ``user`` is the caller. It carries through to ``execute_hogql_query`` so property-level access
+ control is evaluated for that member, not with the project defaults, because ``properties`` is
+ caller-supplied and would otherwise read restricted properties.
"""
query = parse_select(
_MCP_TOOL_CALLS_SQL,
@@ -713,12 +844,13 @@ def list_mcp_tool_calls(
"session_id": ast.Constant(value=session_id),
"limit": ast.Constant(value=limit + 1),
"offset": ast.Constant(value=offset),
+ "shared_filters": shared_filters_expr(team, properties, filter_test_accounts),
},
)
with tags_context(
product=Product.MCP_ANALYTICS, feature=Feature.QUERY, team_id=team.id, name="mcp_analytics_sessions_tool_calls"
):
- response = execute_hogql_query(query=query, team=team)
+ response = execute_hogql_query(query=query, team=team, user=user)
rows = response.results or []
has_next = len(rows) > limit
results = [
diff --git a/products/mcp_analytics/backend/presentation/serializers.py b/products/mcp_analytics/backend/presentation/serializers.py
index 3b30b318dafb..ea76d5a2e094 100644
--- a/products/mcp_analytics/backend/presentation/serializers.py
+++ b/products/mcp_analytics/backend/presentation/serializers.py
@@ -1,10 +1,58 @@
+import json
from datetime import datetime
from typing import Any
+import pydantic
from rest_framework import serializers
+from posthog.schema import (
+ AnyPropertyFilterDiscriminated,
+ EventPropertyFilter,
+ PersonPropertyFilter,
+ SessionPropertyFilter,
+)
+
from products.mcp_analytics.backend.models import MCPAnalyticsSubmission
+_PROPERTY_FILTERS_ADAPTER: pydantic.TypeAdapter[list[AnyPropertyFilterDiscriminated]] = pydantic.TypeAdapter(
+ list[AnyPropertyFilterDiscriminated]
+)
+_ALLOWED_PROPERTY_FILTERS = (EventPropertyFilter, PersonPropertyFilter, SessionPropertyFilter)
+
+PROPERTIES_HELP_TEXT = (
+ "Property filters that narrow the underlying $mcp_tool_call events, JSON-encoded. A list of "
+ "event, person, or session property filters, each with key, value, operator, and type. Example: "
+ '[{"key": "$mcp_tool_name", "value": ["query_run"], "operator": "exact", '
+ '"type": "event"}]'
+)
+
+FILTER_TEST_ACCOUNTS_HELP_TEXT = (
+ "Whether to also apply the project's internal and test user filters (its test_account_filters "
+ "setting) on top of `properties`."
+)
+
+
+class PropertyFiltersField(serializers.CharField):
+ """A JSON-encoded list of property filters in a query string, validated into schema types.
+
+ Follows the `properties` query-param convention of the person and cohort actor endpoints.
+ Subclasses CharField so drf-spectacular keeps advertising the plain string a query string can
+ carry, while the view receives the parsed filters.
+ """
+
+ def run_validation(self, data: Any = serializers.empty) -> list[AnyPropertyFilterDiscriminated]:
+ raw = super().run_validation(data)
+ if not raw:
+ return []
+ try:
+ filters = _PROPERTY_FILTERS_ADAPTER.validate_python(json.loads(raw))
+ except (json.JSONDecodeError, ValueError, pydantic.ValidationError) as error:
+ raise serializers.ValidationError(f"Properties are unparsable: {error}")
+ if any(not isinstance(property_filter, _ALLOWED_PROPERTY_FILTERS) for property_filter in filters):
+ raise serializers.ValidationError("Only event, person, and session property filters are supported.")
+ return filters
+
+
MAX_GOAL_LENGTH = 500
MAX_SUMMARY_LENGTH = 5_000
@@ -185,6 +233,17 @@ class MCPSessionListQuerySerializer(serializers.Serializer):
allow_blank=True,
help_text="End of the window. PostHog date string or absolute ISO timestamp. Defaults to now.",
)
+ properties = PropertyFiltersField(
+ required=False,
+ allow_blank=True,
+ default="",
+ help_text=PROPERTIES_HELP_TEXT,
+ )
+ filter_test_accounts = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text=FILTER_TEST_ACCOUNTS_HELP_TEXT,
+ )
limit = serializers.IntegerField(
required=False,
default=MCP_SESSION_LIST_DEFAULT_LIMIT,
@@ -229,6 +288,17 @@ class MCPSessionToolCallsQuerySerializer(serializers.Serializer):
"older sessions resolve. Defaults to a 7-day lookback when omitted or unparseable."
),
)
+ properties = PropertyFiltersField(
+ required=False,
+ allow_blank=True,
+ default="",
+ help_text=PROPERTIES_HELP_TEXT,
+ )
+ filter_test_accounts = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text=FILTER_TEST_ACCOUNTS_HELP_TEXT,
+ )
limit = serializers.IntegerField(
required=False,
default=MCP_TOOL_CALLS_DEFAULT_LIMIT,
@@ -415,6 +485,20 @@ class MCPActivityRecentCallSerializer(serializers.Serializer):
)
+class MCPActivityOverviewQuerySerializer(serializers.Serializer):
+ properties = PropertyFiltersField(
+ required=False,
+ allow_blank=True,
+ default="",
+ help_text=PROPERTIES_HELP_TEXT,
+ )
+ filter_test_accounts = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text=FILTER_TEST_ACCOUNTS_HELP_TEXT,
+ )
+
+
class MCPActivityOverviewSerializer(serializers.Serializer):
stats = MCPActivityStatsSerializer(read_only=True, help_text="Aggregate counters over the last 30 days.")
top_tools = MCPActivityToolRowSerializer(
diff --git a/products/mcp_analytics/backend/presentation/views.py b/products/mcp_analytics/backend/presentation/views.py
index 9376587d1676..a5a6f03d7c2c 100644
--- a/products/mcp_analytics/backend/presentation/views.py
+++ b/products/mcp_analytics/backend/presentation/views.py
@@ -25,6 +25,7 @@ from products.mcp_analytics.backend.models import MCPAnalyticsSubmission
from .serializers import (
MCP_SESSION_LIST_DEFAULT_LIMIT,
MCP_SESSION_LIST_MAX_LIMIT,
+ MCPActivityOverviewQuerySerializer,
MCPActivityOverviewSerializer,
MCPAnalyticsSubmissionSerializer,
MCPFeedbackCreateSerializer,
@@ -195,6 +196,9 @@ 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,
+ properties=params["properties"],
+ filter_test_accounts=params["filter_test_accounts"],
+ user=cast(User, request.user),
)
serializer = self.get_serializer(page.results, many=True)
# Instantiate the concrete class (not self.pagination_class()) so the typed
@@ -216,6 +220,9 @@ class MCPSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
limit=params["limit"],
offset=params["offset"],
date_from=params.get("date_from"),
+ properties=params["properties"],
+ filter_test_accounts=params["filter_test_accounts"],
+ user=cast(User, request.user),
)
serializer = MCPToolCallSerializer(page.results, many=True)
return MCPSessionPagination().get_paginated_response(serializer.data, has_next=page.has_next)
@@ -284,18 +291,25 @@ class MCPSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
return Response(MCPIntentDigestSerializer(digest).data)
- @extend_schema(
+ @validated_request(
+ query_serializer=MCPActivityOverviewQuerySerializer,
+ responses={200: OpenApiResponse(response=MCPActivityOverviewSerializer)},
operation_id="mcp_analytics_sessions_activity_overview",
description=(
"Aggregate counters, top tools, agent clients, and the most recent tool calls for the last 30 days, "
"computed in one request. Powers the dashboard's activity view; always computed fresh so polling "
"callers watch data arrive."
),
- responses={200: MCPActivityOverviewSerializer},
)
@action(detail=False, methods=["get"], url_path="activity_overview", pagination_class=None)
- def activity_overview(self, request: Request, *args: Any, **kwargs: Any) -> Response:
- overview = api.get_activity_overview(self.team)
+ def activity_overview(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
+ params = request.validated_query_data
+ overview = api.get_activity_overview(
+ self.team,
+ properties=params["properties"],
+ filter_test_accounts=params["filter_test_accounts"],
+ user=cast(User, request.user),
+ )
return Response(MCPActivityOverviewSerializer(overview).data)
diff --git a/products/mcp_analytics/backend/tests/test_api.py b/products/mcp_analytics/backend/tests/test_api.py
index 9099b8e9b1c3..e6a4664c5e5c 100644
--- a/products/mcp_analytics/backend/tests/test_api.py
+++ b/products/mcp_analytics/backend/tests/test_api.py
@@ -10,6 +10,8 @@ from django.test import SimpleTestCase
from parameterized import parameterized
+from posthog.schema import AnyPropertyFilterDiscriminated, EventPropertyFilter, PropertyOperator
+
from posthog.models.utils import uuid7
from posthog.utils import generate_cache_key
@@ -18,6 +20,13 @@ from products.mcp_analytics.backend.facade import api, contracts, enums
from products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPSession
from products.mcp_analytics.backend.tests import _MCPAnalyticsTeamScopedTestMixin
+INTERNAL_CLIENT = "internal-bot"
+TEST_ACCOUNT_FILTERS = [{"key": "$mcp_client_name", "value": [INTERNAL_CLIENT], "operator": "is_not", "type": "event"}]
+
+
+def _tool_name_filter(tool: str) -> list[AnyPropertyFilterDiscriminated]:
+ return [EventPropertyFilter(key="$mcp_tool_name", value=[tool], operator=PropertyOperator.EXACT)]
+
def _sorted_uuid7s(n: int) -> list[str]:
"""Generate ``n`` uuid7 strings sorted lexicographically.
@@ -122,6 +131,69 @@ class TestListMCPSessions(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin,
},
)
+ @parameterized.expand(
+ [
+ ("property_filter", _tool_name_filter("query_run"), False, {"kept"}),
+ ("test_accounts", None, True, {"kept"}),
+ ("both_together", _tool_name_filter("query_run"), True, {"kept"}),
+ ("neither", None, False, {"kept", "dropped"}),
+ ]
+ )
+ def test_shared_filters_narrow_the_session_list(
+ self,
+ _name: str,
+ properties: list[AnyPropertyFilterDiscriminated] | None,
+ filter_test_accounts: bool,
+ expected: set[str],
+ ) -> None:
+ self.team.test_account_filters = TEST_ACCOUNT_FILTERS
+ self.team.save()
+ by_name = {"kept": str(uuid7()), "dropped": str(uuid7())}
+ self._seed_session(by_name["kept"], ["query_run"])
+ self._seed_session(by_name["dropped"], ["docs_search"], client_name=INTERNAL_CLIENT)
+
+ def listed(props: list[AnyPropertyFilterDiscriminated] | None, test_accounts: bool) -> set[str]:
+ page = api.list_mcp_sessions(
+ self.team, limit=50, offset=0, properties=props, filter_test_accounts=test_accounts
+ )
+ return {name for name, sid in by_name.items() if sid in {s.session_id for s in page.results}}
+
+ assert listed(None, False) == {"kept", "dropped"}
+ assert listed(properties, filter_test_accounts) == expected
+
+ def test_test_account_filter_changes_invalidate_the_session_cache(self) -> None:
+ external_session_id = str(uuid7())
+ internal_session_id = str(uuid7())
+ self._seed_session(external_session_id, ["query_run"])
+ self._seed_session(internal_session_id, ["query_run"], client_name=INTERNAL_CLIENT)
+ self.team.test_account_filters = TEST_ACCOUNT_FILTERS
+
+ first_page = api.list_mcp_sessions(self.team, limit=50, offset=0, filter_test_accounts=True)
+ assert {session.session_id for session in first_page.results} == {external_session_id}
+
+ self.team.test_account_filters = []
+ second_page = api.list_mcp_sessions(self.team, limit=50, offset=0, filter_test_accounts=True)
+ assert {session.session_id for session in second_page.results} == {external_session_id, internal_session_id}
+
+ def test_shared_filters_narrow_the_calls_but_not_the_session_bounds(self) -> None:
+ session_id = str(uuid7())
+ now = datetime.now(tz=UTC)
+ started_at = now - timedelta(minutes=30)
+ self._seed_session(session_id, ["docs_search"], session_start=started_at, session_end=started_at)
+ self._seed_session(
+ session_id,
+ ["query_run", "query_run"],
+ session_start=now - timedelta(minutes=10),
+ session_end=now - timedelta(minutes=9),
+ )
+
+ page = api.list_mcp_sessions(self.team, limit=50, offset=0, properties=_tool_name_filter("query_run"))
+ session = next(s for s in page.results if s.session_id == session_id)
+
+ assert session.tool_calls == 2
+ assert session.tools_used == ["query_run"]
+ assert session.session_start < now - timedelta(minutes=20)
+
def test_lists_sessions_in_newest_first_order(self) -> None:
session_a = str(uuid7())
session_b = str(uuid7())
@@ -374,16 +446,14 @@ class TestListMCPSessions(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin,
assert old in results
assert new not in results
- def test_overlapping_session_reports_full_stats_not_clipped(self) -> None:
- # A session straddling the window start is included with its FULL stats: the event
- # before the window counts too, so start/duration/tool count span the whole session
- # rather than just the in-window slice.
+ @parameterized.expand([("within_one_day", timedelta(hours=2)), ("beyond_one_day", timedelta(days=3))])
+ def test_overlapping_session_reports_stats_within_scan_buffer(self, _name: str, session_age: timedelta) -> None:
session_id = str(uuid7())
now = datetime.now(tz=UTC)
self._seed_session(
session_id,
["query_run", "insight_get"],
- session_start=now - timedelta(hours=2), # before the window
+ session_start=now - session_age, # before the window
session_end=now - timedelta(minutes=10), # inside the window
)
@@ -399,11 +469,31 @@ class TestListMCPSessions(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin,
assert session.tool_calls == 2
assert sorted(session.tools_used) == ["insight_get", "query_run"]
# session_start is the pre-window event, not clipped up to the window start.
- assert session.session_start < now - timedelta(hours=1)
+ assert session.session_start < now - session_age + timedelta(minutes=1)
+
+ def test_overlapping_session_excludes_events_beyond_scan_buffer(self) -> None:
+ session_id = str(uuid7())
+ now = datetime.now(tz=UTC)
+ self._seed_session(
+ session_id,
+ ["outside_scan", "inside_window"],
+ session_start=now - timedelta(days=8),
+ session_end=now - timedelta(minutes=10),
+ )
+
+ one_hour_ago = (now - timedelta(hours=1)).isoformat()
+ sessions = [
+ s
+ for s in api.list_mcp_sessions(self.team, limit=50, offset=0, date_from=one_hour_ago).results
+ if s.session_id == session_id
+ ]
+
+ assert len(sessions) == 1
+ assert sessions[0].tool_calls == 1
+ assert sessions[0].tools_used == ["inside_window"]
+ assert sessions[0].session_start > now - timedelta(hours=1)
def test_session_entirely_outside_window_is_excluded(self) -> None:
- # The buffered scan reads events just outside the window, but a session with no event
- # *inside* the window must not leak in via the buffer.
session_id = str(uuid7())
now = datetime.now(tz=UTC)
self._seed_session(
@@ -704,6 +794,49 @@ class TestActivityOverview(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin
properties={"$session_id": str(uuid7()), "$mcp_tool_name": "query_run", **properties},
)
+ @parameterized.expand(
+ [
+ ("property_filter", _tool_name_filter("query_run"), False, 2),
+ ("test_accounts", None, True, 2),
+ ("neither", None, False, 3),
+ ]
+ )
+ def test_shared_filters_narrow_every_section(
+ self,
+ _name: str,
+ properties: list[AnyPropertyFilterDiscriminated] | None,
+ filter_test_accounts: bool,
+ expected_calls: int,
+ ) -> None:
+ self.team.test_account_filters = TEST_ACCOUNT_FILTERS
+ self.team.save()
+ self._emit_call({"$mcp_client_name": "claude-code"}, count=2)
+ self._emit_call({"$mcp_client_name": INTERNAL_CLIENT, "$mcp_tool_name": "docs_search"})
+
+ overview = api.get_activity_overview(
+ self.team, properties=properties, filter_test_accounts=filter_test_accounts
+ )
+
+ assert overview.stats.total_calls == expected_calls
+ assert sum(row.calls for row in overview.top_tools) == expected_calls
+ assert sum(row.calls for row in overview.clients) == expected_calls
+ assert len(overview.recent_calls) == expected_calls
+
+ def test_tool_filter_does_not_hide_missing_capability_reports(self) -> None:
+ self._emit_call({"$mcp_tool_name": "query_run"})
+ _create_event(
+ team=self.team,
+ event="$mcp_missing_capability",
+ distinct_id="agent-1",
+ timestamp=datetime.now(tz=UTC) - timedelta(minutes=5),
+ properties={},
+ )
+
+ overview = api.get_activity_overview(self.team, properties=_tool_name_filter("query_run"))
+
+ assert overview.stats.total_calls == 1
+ assert overview.stats.missing_capability_reports == 1
+
def test_merges_client_spellings_into_one_canonical_row(self) -> None:
# One client reaches us under several spellings — different casing, and a proxied
# name carrying mcp-remote's signature. Grouping on the raw property listed each as
@@ -875,6 +1008,49 @@ class TestListMCPToolCalls(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin
properties={"$session_id": session_id, "$mcp_tool_name": tool},
)
+ @parameterized.expand(
+ [
+ ("property_filter", _tool_name_filter("kept"), False, ["kept"]),
+ ("test_accounts", None, True, ["kept"]),
+ ("neither", None, False, ["dropped", "kept"]),
+ ]
+ )
+ def test_shared_filters_narrow_a_sessions_calls(
+ self,
+ _name: str,
+ properties: list[AnyPropertyFilterDiscriminated] | None,
+ filter_test_accounts: bool,
+ expected: list[str],
+ ) -> None:
+ self.team.test_account_filters = TEST_ACCOUNT_FILTERS
+ self.team.save()
+ session_id = str(uuid7())
+ start = datetime.now(tz=UTC) - timedelta(minutes=5)
+ _create_event(
+ team=self.team,
+ event="$mcp_tool_call",
+ distinct_id="seed",
+ timestamp=start,
+ properties={
+ "$session_id": session_id,
+ "$mcp_tool_name": "dropped",
+ "$mcp_client_name": INTERNAL_CLIENT,
+ },
+ )
+ self._seed_tool_call(session_id, timestamp=start + timedelta(seconds=1), tool="kept")
+
+ page = api.list_mcp_tool_calls(
+ self.team,
+ session_id=session_id,
+ limit=50,
+ offset=0,
+ date_from=start,
+ properties=properties,
+ filter_test_accounts=filter_test_accounts,
+ )
+
+ assert [c.tool_name for c in page.results] == expected
+
def test_has_next_signals_more_pages(self) -> None:
session_id = str(uuid7())
start = datetime.now(tz=UTC) - timedelta(minutes=5)
diff --git a/products/mcp_analytics/backend/tests/test_presentation.py b/products/mcp_analytics/backend/tests/test_presentation.py
index 8e219e348ae5..9b678a16c8c8 100644
--- a/products/mcp_analytics/backend/tests/test_presentation.py
+++ b/products/mcp_analytics/backend/tests/test_presentation.py
@@ -1,3 +1,4 @@
+import json
from datetime import UTC, datetime, timedelta
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event
@@ -7,7 +8,7 @@ from django.core.cache import cache
from django.test import SimpleTestCase
from parameterized import parameterized
-from rest_framework import status
+from rest_framework import serializers, status
from temporalio.exceptions import WorkflowAlreadyStartedError
from posthog.models import Organization, Team
@@ -26,6 +27,7 @@ from products.mcp_analytics.backend.presentation.serializers import (
MCP_SESSION_LIST_MAX_LIMIT,
MCP_TOOL_CALLS_DEFAULT_LIMIT,
MCP_TOOL_CALLS_MAX_LIMIT,
+ MCPActivityOverviewQuerySerializer,
MCPSessionListQuerySerializer,
MCPSessionToolCallsQuerySerializer,
)
@@ -722,6 +724,101 @@ class TestMCPSessionToolCallsEndpoint(_MCPAnalyticsTeamScopedTestMixin, Clickhou
# still include it after the round-trip — otherwise we'd get just ["last_tool"].
assert [c["tool_name"] for c in response.json()["results"]] == ["first_tool", "last_tool"]
+ @parameterized.expand(
+ [
+ ("sessions_list", "", {"date_from": "-7d"}),
+ ("tool_calls", "{session_id}/tool_calls/", {"date_from": "-7d"}),
+ ("activity_overview", "activity_overview/", {}),
+ ]
+ )
+ def test_shared_filters_reach_the_query(self, _name: str, suffix: str, extra: dict[str, str]) -> None:
+ session_id = str(uuid7())
+ for tool in ["kept_tool", "dropped_tool"]:
+ _create_event(
+ team=self.team,
+ event="$mcp_tool_call",
+ distinct_id="seed",
+ timestamp=datetime.now(tz=UTC) - timedelta(minutes=5),
+ properties={"$session_id": session_id, "$mcp_tool_name": tool},
+ )
+ path = f"/api/environments/{self.team.id}/mcp_analytics/sessions/{suffix.format(session_id=session_id)}"
+ properties = json.dumps(
+ [{"key": "$mcp_tool_name", "value": ["kept_tool"], "operator": "exact", "type": "event"}]
+ )
+
+ response = self.client.get(path, {**extra, "properties": properties})
+
+ assert response.status_code == status.HTTP_200_OK
+ assert "kept_tool" in response.content.decode()
+ assert "dropped_tool" not in response.content.decode()
+
+ @parameterized.expand(
+ [
+ ("sessions_list", "", {"date_from": "-7d"}),
+ ("tool_calls", "{session_id}/tool_calls/", {"date_from": "-7d"}),
+ ("activity_overview", "activity_overview/", {}),
+ ]
+ )
+ def test_property_restrictions_are_resolved_for_the_caller(
+ self, _name: str, suffix: str, extra: dict[str, str]
+ ) -> None:
+ path = f"/api/environments/{self.team.id}/mcp_analytics/sessions/{suffix.format(session_id=uuid7())}"
+ with patch(
+ "products.access_control.backend.property_access_control.get_restricted_properties_with_group_type_index_for_team",
+ return_value=set(),
+ ) as resolve_restrictions:
+ response = self.client.get(path, extra)
+
+ assert response.status_code == status.HTTP_200_OK
+ assert resolve_restrictions.call_count > 0
+ assert all(call.kwargs["user"] == self.user for call in resolve_restrictions.call_args_list)
+
+ def test_unparseable_properties_are_a_400(self) -> None:
+ response = self.client.get(
+ f"/api/environments/{self.team.id}/mcp_analytics/sessions/", {"properties": "{not json"}
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+
+class TestSharedFilterQueryParams(SimpleTestCase):
+ QUERY_SERIALIZERS = [
+ ("sessions_list", MCPSessionListQuerySerializer),
+ ("tool_calls", MCPSessionToolCallsQuerySerializer),
+ ("activity_overview", MCPActivityOverviewQuerySerializer),
+ ]
+
+ @parameterized.expand(QUERY_SERIALIZERS)
+ def test_shared_filters_default_to_off(self, _name: str, serializer_class: type[serializers.Serializer]) -> None:
+ serializer = serializer_class(data={})
+ assert serializer.is_valid(), serializer.errors
+ assert serializer.validated_data["properties"] == []
+ assert serializer.validated_data["filter_test_accounts"] is False
+
+ @parameterized.expand(QUERY_SERIALIZERS)
+ def test_properties_parse_into_schema_filters(
+ self, _name: str, serializer_class: type[serializers.Serializer]
+ ) -> None:
+ raw = json.dumps([{"key": "$mcp_tool_name", "value": ["query_run"], "operator": "exact", "type": "event"}])
+ serializer = serializer_class(data={"properties": raw})
+ assert serializer.is_valid(), serializer.errors
+ parsed = serializer.validated_data["properties"]
+ assert [(f.key, f.value) for f in parsed] == [("$mcp_tool_name", ["query_run"])]
+
+ @parameterized.expand(
+ [
+ ("not_json", "{definitely not json"),
+ ("not_a_list", '{"key": "$mcp_tool_name"}'),
+ ("unknown_filter_type", '[{"key": "a", "value": "b", "type": "nonsense"}]'),
+ ("hogql_filter", '[{"key": "1 = 1", "value": true, "type": "hogql"}]'),
+ ("cohort_filter", '[{"key": "id", "value": 1, "type": "cohort"}]'),
+ ]
+ )
+ def test_unparseable_properties_are_rejected(self, _name: str, raw: str) -> None:
+ serializer = MCPSessionListQuerySerializer(data={"properties": raw})
+ assert not serializer.is_valid()
+ assert "properties" in serializer.errors
+
class TestMCPSessionListQuerySerializer(SimpleTestCase):
def test_defaults_when_pagination_params_omitted(self) -> None:
diff --git a/products/mcp_analytics/frontend/generated/api.schemas.ts b/products/mcp_analytics/frontend/generated/api.schemas.ts
index edcdcc669373..1cdd620f7d33 100644
--- a/products/mcp_analytics/frontend/generated/api.schemas.ts
+++ b/products/mcp_analytics/frontend/generated/api.schemas.ts
@@ -672,6 +672,10 @@ export type McpAnalyticsSessionsListParams = {
* End of the window. PostHog date string or absolute ISO timestamp. Defaults to now.
*/
date_to?: string
+ /**
+ * 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
/**
* Maximum number of sessions to return per page. Defaults to 100; values above 500 are rejected.
* @minimum 1
@@ -687,6 +691,10 @@ export type McpAnalyticsSessionsListParams = {
* Sort column. Allowed: session_id, session_start, session_end, duration_seconds, tool_call_count, mcp_client_name, distinct_id. Prefix with '-' for descending. Defaults to '-session_start' (newest sessions first).
*/
order_by?: string
+ /**
+ * Property filters that narrow the underlying $mcp_tool_call events, JSON-encoded. A list of event, person, or session property filters, each with key, value, operator, and type. Example: [{"key": "$mcp_tool_name", "value": ["query_run"], "operator": "exact", "type": "event"}]
+ */
+ properties?: string
/**
* Case-insensitive substring filter matched against session_id, distinct_id, mcp_client_name, and tools_used.
*/
@@ -705,6 +713,10 @@ export type McpAnalyticsSessionsToolCallsParams = {
* Absolute ISO timestamp lower bound for the event scan — pass the session's start so older sessions resolve. Defaults to a 7-day lookback when omitted or unparseable.
*/
date_from?: string
+ /**
+ * 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
/**
* Maximum tool calls to return per page (1–500). Defaults to 500 — the whole page — so a session's calls come back in one request; pass a smaller value for a lighter response. Values above the cap are rejected.
* @minimum 1
@@ -716,4 +728,19 @@ export type McpAnalyticsSessionsToolCallsParams = {
* @minimum 0
*/
offset?: number
+ /**
+ * Property filters that narrow the underlying $mcp_tool_call events, JSON-encoded. A list of event, person, or session property filters, each with key, value, operator, and type. Example: [{"key": "$mcp_tool_name", "value": ["query_run"], "operator": "exact", "type": "event"}]
+ */
+ properties?: string
+}
+
+export type McpAnalyticsSessionsActivityOverviewParams = {
+ /**
+ * 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
+ /**
+ * Property filters that narrow the underlying $mcp_tool_call events, JSON-encoded. A list of event, person, or session property filters, each with key, value, operator, and type. Example: [{"key": "$mcp_tool_name", "value": ["query_run"], "operator": "exact", "type": "event"}]
+ */
+ properties?: string
}
diff --git a/products/mcp_analytics/frontend/generated/api.ts b/products/mcp_analytics/frontend/generated/api.ts
index d74428a3890e..93eacb875f7f 100644
--- a/products/mcp_analytics/frontend/generated/api.ts
+++ b/products/mcp_analytics/frontend/generated/api.ts
@@ -19,6 +19,7 @@ import type {
McpAnalyticsFeedbackListParams,
McpAnalyticsIntentClustersRetrieveParams,
McpAnalyticsMissingCapabilitiesListParams,
+ McpAnalyticsSessionsActivityOverviewParams,
McpAnalyticsSessionsGenerateIntentParams,
McpAnalyticsSessionsListParams,
McpAnalyticsSessionsToolCallsParams,
@@ -283,8 +284,23 @@ export const mcpAnalyticsSessionsToolCalls = async (
})
}
-export const getMcpAnalyticsSessionsActivityOverviewUrl = (projectId: string) => {
- return `/api/projects/${projectId}/mcp_analytics/sessions/activity_overview/`
+export const getMcpAnalyticsSessionsActivityOverviewUrl = (
+ projectId: string,
+ params?: McpAnalyticsSessionsActivityOverviewParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/mcp_analytics/sessions/activity_overview/?${stringifiedParams}`
+ : `/api/projects/${projectId}/mcp_analytics/sessions/activity_overview/`
}
/**
@@ -292,9 +308,10 @@ export const getMcpAnalyticsSessionsActivityOverviewUrl = (projectId: string) =>
*/
export const mcpAnalyticsSessionsActivityOverview = async (
projectId: string,
+ params?: McpAnalyticsSessionsActivityOverviewParams,
options?: RequestInit
): Promise<MCPActivityOverviewApi> => {
- return apiMutator<MCPActivityOverviewApi>(getMcpAnalyticsSessionsActivityOverviewUrl(projectId), {
+ return apiMutator<MCPActivityOverviewApi>(getMcpAnalyticsSessionsActivityOverviewUrl(projectId, params), {
...options,
method: 'GET',
})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ec91b93a5c20..37cead3d1fd0 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -111396,6 +111396,10 @@ export namespace Schemas {
* End of the window. PostHog date string or absolute ISO timestamp. Defaults to now.
*/
date_to?: string;
+ /**
+ * 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;
/**
* Maximum number of sessions to return per page. Defaults to 100; values above 500 are rejected.
* @minimum 1
@@ -111411,6 +111415,10 @@ export namespace Schemas {
* Sort column. Allowed: session_id, session_start, session_end, duration_seconds, tool_call_count, mcp_client_name, distinct_id. Prefix with '-' for descending. Defaults to '-session_start' (newest sessions first).
*/
order_by?: string;
+ /**
+ * Property filters that narrow the underlying $mcp_tool_call events, JSON-encoded. A list of event, person, or session property filters, each with key, value, operator, and type. Example: [{"key": "$mcp_tool_name", "value": ["query_run"], "operator": "exact", "type": "event"}]
+ */
+ properties?: string;
/**
* Case-insensitive substring filter matched against session_id, distinct_id, mcp_client_name, and tools_used.
*/
@@ -111429,6 +111437,10 @@ export namespace Schemas {
* Absolute ISO timestamp lower bound for the event scan — pass the session's start so older sessions resolve. Defaults to a 7-day lookback when omitted or unparseable.
*/
date_from?: string;
+ /**
+ * 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;
/**
* Maximum tool calls to return per page (1–500). Defaults to 500 — the whole page — so a session's calls come back in one request; pass a smaller value for a lighter response. Values above the cap are rejected.
* @minimum 1
@@ -111440,6 +111452,21 @@ export namespace Schemas {
* @minimum 0
*/
offset?: number;
+ /**
+ * Property filters that narrow the underlying $mcp_tool_call events, JSON-encoded. A list of event, person, or session property filters, each with key, value, operator, and type. Example: [{"key": "$mcp_tool_name", "value": ["query_run"], "operator": "exact", "type": "event"}]
+ */
+ properties?: string;
+ };
+
+ export type McpAnalyticsSessionsActivityOverviewParams = {
+ /**
+ * 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;
+ /**
+ * Property filters that narrow the underlying $mcp_tool_call events, JSON-encoded. A list of event, person, or session property filters, each with key, value, operator, and type. Example: [{"key": "$mcp_tool_name", "value": ["query_run"], "operator": "exact", "type": "event"}]
+ */
+ properties?: string;
};
export type McpGatewayAuditListParams = {
diff --git a/services/mcp/src/generated/mcp_analytics/api.ts b/services/mcp/src/generated/mcp_analytics/api.ts
index 7836aa34dbd8..ffa452a30ae8 100644
--- a/services/mcp/src/generated/mcp_analytics/api.ts
+++ b/services/mcp/src/generated/mcp_analytics/api.ts
@@ -138,6 +138,7 @@ export const McpAnalyticsSessionsListParams = () => zod.object({
),
})
+export const mcpAnalyticsSessionsListQueryFilterTestAccountsDefault = false
export const mcpAnalyticsSessionsListQueryLimitDefault = 100
export const mcpAnalyticsSessionsListQueryLimitMax = 500
@@ -145,6 +146,7 @@ export const mcpAnalyticsSessionsListQueryOffsetDefault = 0
export const mcpAnalyticsSessionsListQueryOffsetMin = 0
export const mcpAnalyticsSessionsListQueryOrderByDefault = ``
+export const mcpAnalyticsSessionsListQueryPropertiesDefault = ``
export const mcpAnalyticsSessionsListQuerySearchDefault = ``
export const McpAnalyticsSessionsListQueryParams = () => zod.object({
@@ -158,6 +160,12 @@ export const McpAnalyticsSessionsListQueryParams = () => zod.object({
.string()
.optional()
.describe('End of the window. PostHog date string or absolute ISO timestamp. Defaults to now.'),
+ filter_test_accounts: zod
+ .boolean()
+ .default(mcpAnalyticsSessionsListQueryFilterTestAccountsDefault)
+ .describe(
+ "Whether to also apply the project's internal and test user filters (its test_account_filters setting) on top of `properties`."
+ ),
limit: zod
.number()
.min(1)
@@ -177,6 +185,12 @@ export const McpAnalyticsSessionsListQueryParams = () => zod.object({
.describe(
"Sort column. Allowed: session_id, session_start, session_end, duration_seconds, tool_call_count, mcp_client_name, distinct_id. Prefix with '-' for descending. Defaults to '-session_start' (newest sessions first)."
),
+ properties: zod
+ .string()
+ .default(mcpAnalyticsSessionsListQueryPropertiesDefault)
+ .describe(
+ 'Property filters that narrow the underlying $mcp_tool_call events, JSON-encoded. A list of event, person, or session property filters, each with key, value, operator, and type. Example: [{\"key\": \"$mcp_tool_name\", \"value\": [\"query_run\"], \"operator\": \"exact\", \"type\": \"event\"}]'
+ ),
search: zod
.string()
.default(mcpAnalyticsSessionsListQuerySearchDefault)
@@ -218,12 +232,15 @@ export const McpAnalyticsSessionsToolCallsParams = () => zod.object({
),
})
+export const mcpAnalyticsSessionsToolCallsQueryFilterTestAccountsDefault = false
export const mcpAnalyticsSessionsToolCallsQueryLimitDefault = 500
export const mcpAnalyticsSessionsToolCallsQueryLimitMax = 500
export const mcpAnalyticsSessionsToolCallsQueryOffsetDefault = 0
export const mcpAnalyticsSessionsToolCallsQueryOffsetMin = 0
+export const mcpAnalyticsSessionsToolCallsQueryPropertiesDefault = ``
+
export const McpAnalyticsSessionsToolCallsQueryParams = () => zod.object({
date_from: zod.iso
.datetime({ offset: true })
@@ -231,6 +248,12 @@ export const McpAnalyticsSessionsToolCallsQueryParams = () => zod.object({
.describe(
"Absolute ISO timestamp lower bound for the event scan — pass the session's start so older sessions resolve. Defaults to a 7-day lookback when omitted or unparseable."
),
+ filter_test_accounts: zod
+ .boolean()
+ .default(mcpAnalyticsSessionsToolCallsQueryFilterTestAccountsDefault)
+ .describe(
+ "Whether to also apply the project's internal and test user filters (its test_account_filters setting) on top of `properties`."
+ ),
limit: zod
.number()
.min(1)
@@ -246,4 +269,10 @@ export const McpAnalyticsSessionsToolCallsQueryParams = () => zod.object({
.describe(
"Number of tool calls to skip before returning results. Combine with limit to page through a session's calls; the response's has_next flag indicates whether more remain."
),
+ properties: zod
+ .string()
+ .default(mcpAnalyticsSessionsToolCallsQueryPropertiesDefault)
+ .describe(
+ 'Property filters that narrow the underlying $mcp_tool_call events, JSON-encoded. A list of event, person, or session property filters, each with key, value, operator, and type. Example: [{\"key\": \"$mcp_tool_name\", \"value\": [\"query_run\"], \"operator\": \"exact\", \"type\": \"event\"}]'
+ ),
})
diff --git a/services/mcp/src/tools/generated/mcp_analytics.ts b/services/mcp/src/tools/generated/mcp_analytics.ts
index 5fa11bd1cd01..745bb4295a7d 100644
--- a/services/mcp/src/tools/generated/mcp_analytics.ts
+++ b/services/mcp/src/tools/generated/mcp_analytics.ts
@@ -98,9 +98,11 @@ const mcpAnalyticsSessionsList = (): ToolBase<
query: {
date_from: params.date_from,
date_to: params.date_to,
+ filter_test_accounts: params.filter_test_accounts,
limit: params.limit,
offset: params.offset,
order_by: params.order_by,
+ properties: params.properties,
search: params.search,
},
})
@@ -129,8 +131,10 @@ const mcpAnalyticsSessionsToolCalls = (): ToolBase<
path: `/api/projects/${encodeURIComponent(String(projectId))}/mcp_analytics/sessions/${encodeURIComponent(String(params.id))}/tool_calls/`,
query: {
date_from: params.date_from,
+ filter_test_accounts: params.filter_test_accounts,
limit: params.limit,
offset: params.offset,
+ properties: params.properties,
},
})
return await withPostHogUrl(context, result, '/mcp-analytics')