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): paginate sessions list with load-more (#59888)

Georgis Andonisc684c6e9e598
diff --git a/products/mcp_analytics/backend/facade/api.py b/products/mcp_analytics/backend/facade/api.py
index a82ee297a3cb..2dbd93fe3e55 100644
--- a/products/mcp_analytics/backend/facade/api.py
+++ b/products/mcp_analytics/backend/facade/api.py
@@ -50,7 +50,7 @@ def create_missing_capability_submission(
def list_mcp_sessions(
team: Team, limit: int, offset: int, search: str = "", order_by: str = ""
-) -> list[contracts.MCPSession]:
+) -> contracts.MCPSessionsPage:
return logic.list_mcp_sessions(team, limit=limit, offset=offset, search=search, order_by=order_by)
diff --git a/products/mcp_analytics/backend/facade/contracts.py b/products/mcp_analytics/backend/facade/contracts.py
index 1d3329443a61..847f4d4e37dc 100644
--- a/products/mcp_analytics/backend/facade/contracts.py
+++ b/products/mcp_analytics/backend/facade/contracts.py
@@ -66,6 +66,12 @@ class MCPSession:
intent: str
+@dataclass(frozen=True)
+class MCPSessionsPage:
+ results: list[MCPSession]
+ has_next: bool
+
+
@dataclass(frozen=True)
class MCPToolCall:
event_id: str
diff --git a/products/mcp_analytics/backend/logic.py b/products/mcp_analytics/backend/logic.py
index 2c5e593b1211..afd486385ed7 100644
--- a/products/mcp_analytics/backend/logic.py
+++ b/products/mcp_analytics/backend/logic.py
@@ -58,7 +58,7 @@ SESSION_SORT_FIELDS: frozenset[str] = frozenset(
"distinct_id",
}
)
-DEFAULT_SESSION_SORT_COLUMN = "session_end"
+DEFAULT_SESSION_SORT_COLUMN = "session_start"
# PR1 aggregates the last 24h of mcp_tool_call events on the fly, scoped to the
# team. Wider windows (7d/30d) land in PR2. See
@@ -138,12 +138,13 @@ def list_mcp_sessions(
offset: int,
search: str = "",
order_by: str = "",
-) -> list[contracts.MCPSession]:
- """List MCP sessions for a team, aggregated on the fly from mcp_tool_call events.
+) -> contracts.MCPSessionsPage:
+ """List a page of MCP sessions for a team, aggregated on the fly from mcp_tool_call events.
One row per $mcp_session_id over the last 24h, grouped in ClickHouse and
- scoped to the team so the events sort key prunes the scan. Results are cached
- briefly so concurrent dashboard refreshes share a single aggregation.
+ scoped to the team so the events sort key prunes 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.
``search`` does case-insensitive substring matching across session_id,
distinct_id, mcp_client_name, and any element of tools_used. ``order_by`` is a
@@ -157,12 +158,12 @@ def list_mcp_sessions(
if cached is not None:
return cached
- sessions = _query_mcp_sessions(team, limit=limit, offset=offset, search=search, order_by=order_by)
+ page = _query_mcp_sessions(team, limit=limit, offset=offset, search=search, order_by=order_by)
# Don't cache empty results: a newly set-up team's first sessions would
# otherwise stay hidden for the full TTL.
- if sessions:
- cache.set(cache_key, sessions, SESSIONS_CACHE_TTL_SECONDS)
- return sessions
+ if page.results:
+ cache.set(cache_key, page, SESSIONS_CACHE_TTL_SECONDS)
+ return page
def _query_mcp_sessions(
@@ -171,14 +172,19 @@ def _query_mcp_sessions(
offset: int,
search: str,
order_by: str,
-) -> list[contracts.MCPSession]:
+) -> contracts.MCPSessionsPage:
column, descending = _normalise_order_by(order_by)
- order_text = f"{column} {'DESC' if descending else 'ASC'}"
+ # Append the unique session_id as a tiebreaker so the sort is a *total* order.
+ # Without it, ties on the sort column (e.g. equal session_end) make offset
+ # pagination drop or repeat rows across pages.
+ direction = "DESC" if descending else "ASC"
+ order_text = f"{column} {direction}" if column == "session_id" else f"{column} {direction}, session_id ASC"
+ # Over-fetch one row to learn whether a next page exists, without a count query.
placeholders: dict[str, ast.Expr] = {
"event": ast.Constant(value=MCP_TOOL_CALL_EVENT),
"date_from": ast.Constant(value=timezone.now() - MCP_SESSIONS_LOOKBACK),
- "limit": ast.Constant(value=limit),
+ "limit": ast.Constant(value=limit + 1),
"offset": ast.Constant(value=offset),
}
@@ -199,9 +205,12 @@ def _query_mcp_sessions(
response = execute_hogql_query(query=query, team=team)
rows = [_row_to_session_dict(row) for row in (response.results or [])]
+ has_next = len(rows) > limit
+ rows = rows[:limit]
persons_by_distinct_id = _resolve_persons(team.id, [row["distinct_id"] for row in rows])
intents_by_session = _attach_intents(team, [row["session_id"] for row in rows])
- return [_to_session_contract(row, persons_by_distinct_id, intents_by_session) for row in rows]
+ results = [_to_session_contract(row, persons_by_distinct_id, intents_by_session) for row in rows]
+ return contracts.MCPSessionsPage(results=results, has_next=has_next)
def _row_to_session_dict(row: tuple[Any, ...]) -> dict[str, Any]:
diff --git a/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py
index 3f562e3d9182..59e44c35f681 100644
--- a/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py
+++ b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py
@@ -107,9 +107,9 @@ class Command(BaseCommand):
def add_arguments(self, parser: CommandParser) -> None:
parser.add_argument("--team-id", type=int, required=True, help="Team ID to seed events for.")
- parser.add_argument("--sessions", type=int, default=10, help="Number of sessions to create.")
+ parser.add_argument("--sessions", type=int, default=101, help="Number of sessions to create.")
parser.add_argument("--min-calls", type=int, default=4, help="Minimum tool calls per session (inclusive).")
- parser.add_argument("--max-calls", type=int, default=6, help="Maximum tool calls per session (inclusive).")
+ parser.add_argument("--max-calls", type=int, default=50, help="Maximum tool calls per session (inclusive).")
parser.add_argument("--seed", type=int, default=None, help="Optional random seed for reproducible output.")
def handle(self, *args: Any, **options: Any) -> None:
diff --git a/products/mcp_analytics/backend/presentation/serializers.py b/products/mcp_analytics/backend/presentation/serializers.py
index 3ab3cd015092..26298305e6de 100644
--- a/products/mcp_analytics/backend/presentation/serializers.py
+++ b/products/mcp_analytics/backend/presentation/serializers.py
@@ -141,7 +141,7 @@ class MCPToolCallSerializer(serializers.Serializer):
class MCPSessionSerializer(serializers.Serializer):
session_id = serializers.CharField(
- read_only=True, help_text="PostHog $session_id grouping all mcp_tool_call events."
+ read_only=True, help_text="$mcp_session_id grouping all mcp_tool_call events in the session."
)
tool_calls = serializers.IntegerField(
read_only=True, help_text="Total number of mcp_tool_call events in the session."
diff --git a/products/mcp_analytics/backend/presentation/views.py b/products/mcp_analytics/backend/presentation/views.py
index 3923913d762e..51c29f4b2076 100644
--- a/products/mcp_analytics/backend/presentation/views.py
+++ b/products/mcp_analytics/backend/presentation/views.py
@@ -36,6 +36,32 @@ class MCPAnalyticsPagination(LimitOffsetPagination):
max_limit = 500
+class MCPSessionPagination(LimitOffsetPagination):
+ """Returns ``{results, has_next}`` instead of a count-based envelope. The list is an
+ on-the-fly ClickHouse aggregate with no cheap total, so ``has_next`` comes from the
+ logic layer over-fetching one row rather than a count query.
+ """
+
+ default_limit = 100
+ max_limit = 500
+
+ def get_paginated_response(self, data: Any, *, has_next: bool = False) -> Response:
+ return Response({"results": data, "has_next": has_next})
+
+ def get_paginated_response_schema(self, schema: dict) -> dict:
+ return {
+ "type": "object",
+ "required": ["results", "has_next"],
+ "properties": {
+ "results": schema,
+ "has_next": {
+ "type": "boolean",
+ "description": "Whether more results exist beyond this page; the client fetches the next page with a larger offset.",
+ },
+ },
+ }
+
+
@extend_schema(tags=["mcp_analytics"])
class BaseMCPAnalyticsSubmissionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
serializer_class = MCPAnalyticsSubmissionSerializer
@@ -116,16 +142,17 @@ class MCPSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
serializer_class = MCPSessionSerializer
permission_classes = [IsAuthenticated, SingleTenancyOrAdmin]
scope_object = "INTERNAL"
- pagination_class = MCPAnalyticsPagination
+ pagination_class = MCPSessionPagination
def dangerously_get_queryset(self) -> QuerySet:
- # Sessions are aggregated from ClickHouse events, not from a Django model.
- # Returning an empty queryset satisfies DRF's GenericViewSet plumbing.
+ # Sessions live in ClickHouse, not a Django model, but GenericViewSet still needs a
+ # queryset for its plumbing. The model is arbitrary — we borrow MCPAnalyticsSubmission
+ # (a plain manager) so .none() can't trip a team-scoped manager's guard.
return MCPAnalyticsSubmission.objects.none()
@extend_schema(
operation_id="mcp_analytics_sessions_list",
- description="List MCP sessions for the current project, derived by grouping mcp_tool_call events by $mcp_session_id. Ordered by most recent activity first by default.",
+ description="List MCP sessions for the current project, derived by grouping mcp_tool_call events by $mcp_session_id. Ordered by newest session start first by default.",
parameters=[
OpenApiParameter(
name="search",
@@ -142,21 +169,23 @@ class MCPSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
description=(
"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_end'."
+ "Prefix with '-' for descending. Defaults to '-session_start' (newest sessions first)."
),
),
],
responses={200: MCPSessionSerializer(many=True)},
)
def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
- paginator = self.pagination_class()
+ # Instantiate the concrete class (not self.pagination_class()) so the typed
+ # get_paginated_response(has_next=...) is visible to the type checker.
+ paginator = MCPSessionPagination()
limit = paginator.get_limit(request) or paginator.default_limit
offset = paginator.get_offset(request)
search = request.query_params.get("search", "")
order_by = request.query_params.get("order_by", "")
- sessions = api.list_mcp_sessions(self.team, limit=limit, offset=offset, search=search, order_by=order_by)
- serializer = self.get_serializer(sessions, many=True)
- return Response({"results": serializer.data})
+ page = api.list_mcp_sessions(self.team, limit=limit, offset=offset, search=search, order_by=order_by)
+ serializer = self.get_serializer(page.results, many=True)
+ return paginator.get_paginated_response(serializer.data, has_next=page.has_next)
@extend_schema(
operation_id="mcp_analytics_sessions_tool_calls",
@@ -167,7 +196,9 @@ class MCPSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
def tool_calls(self, request: Request, pk: str | None = None, *args: Any, **kwargs: Any) -> Response:
tool_calls = api.list_mcp_tool_calls(self.team, session_id=str(pk or ""))
serializer = MCPToolCallSerializer(tool_calls, many=True)
- return Response({"results": serializer.data})
+ # has_next is always false: this returns the whole (capped) call list, not a page.
+ # The field exists because the viewset's paginator shapes the response schema.
+ return Response({"results": serializer.data, "has_next": False})
@extend_schema(tags=["mcp_analytics"])
diff --git a/products/mcp_analytics/backend/tests/test_api.py b/products/mcp_analytics/backend/tests/test_api.py
index e74441f7bcc2..8c7a6fb1748e 100644
--- a/products/mcp_analytics/backend/tests/test_api.py
+++ b/products/mcp_analytics/backend/tests/test_api.py
@@ -120,11 +120,13 @@ class TestListMCPSessions(ClickhouseTestMixin, APIBaseTest):
)
sessions = [
- s for s in api.list_mcp_sessions(self.team, limit=50, offset=0) if s.session_id in {session_a, session_b}
+ s
+ for s in api.list_mcp_sessions(self.team, limit=50, offset=0).results
+ if s.session_id in {session_a, session_b}
]
assert len(sessions) == 2
- # Newest session_end first
+ # Newest session_start first
assert sessions[0].session_id == session_b
assert sessions[0].mcp_client_name == "Cursor"
assert sorted(sessions[0].tools_used) == ["dashboard_get", "query_run"]
@@ -137,18 +139,18 @@ class TestListMCPSessions(ClickhouseTestMixin, APIBaseTest):
assert sessions[1].tool_calls == 2
def test_returns_empty_list_when_no_sessions(self) -> None:
- assert api.list_mcp_sessions(self.team, limit=50, offset=0) == []
+ assert api.list_mcp_sessions(self.team, limit=50, offset=0).results == []
def test_does_not_cache_empty_responses(self) -> None:
# An empty result must not be cached, so a session created moments later
# shows up immediately instead of being hidden by a cached empty list.
- assert api.list_mcp_sessions(self.team, limit=50, offset=0) == []
+ assert api.list_mcp_sessions(self.team, limit=50, offset=0).results == []
session_id = str(uuid7())
self._seed_session(session_id, ["query_run"])
- sessions = api.list_mcp_sessions(self.team, limit=50, offset=0)
+ page = api.list_mcp_sessions(self.team, limit=50, offset=0)
- assert [s.session_id for s in sessions] == [session_id]
+ assert [s.session_id for s in page.results] == [session_id]
def test_excludes_events_without_mcp_session_id(self) -> None:
# Events with no $mcp_session_id (e.g. the bare-schema producers) must not
@@ -163,9 +165,9 @@ class TestListMCPSessions(ClickhouseTestMixin, APIBaseTest):
properties={"$mcp_tool_name": "query_run"},
)
- sessions = api.list_mcp_sessions(self.team, limit=50, offset=0)
+ page = api.list_mcp_sessions(self.team, limit=50, offset=0)
- assert [s.session_id for s in sessions] == [kept]
+ assert [s.session_id for s in page.results] == [kept]
def test_search_filters_across_multiple_columns(self) -> None:
alice_id = str(uuid7())
@@ -182,7 +184,7 @@ class TestListMCPSessions(ClickhouseTestMixin, APIBaseTest):
self._seed_session(misc_id, ["feature_flag_get"], client_name="Windsurf", distinct_id="anon_dead")
def search(term: str) -> set[str]:
- return {s.session_id for s in api.list_mcp_sessions(self.team, limit=50, offset=0, search=term)}
+ return {s.session_id for s in api.list_mcp_sessions(self.team, limit=50, offset=0, search=term).results}
# distinct_id substring
assert search("hedgehog") == {alice_id}
@@ -217,11 +219,14 @@ class TestListMCPSessions(ClickhouseTestMixin, APIBaseTest):
session_start=now - timedelta(minutes=20),
session_end=now - timedelta(minutes=10),
)
+ # big_id starts in the middle but ends most recently (a long-running session), so
+ # session_start order differs from session_end order — that's what proves the
+ # default sorts by session_start, not session_end.
self._seed_session(
big_id,
["insight_get"] * 5,
session_start=now - timedelta(minutes=60),
- session_end=now - timedelta(minutes=50),
+ session_end=now - timedelta(minutes=10),
)
# Restrict to the three we just created so other rows don't interfere.
@@ -230,16 +235,38 @@ class TestListMCPSessions(ClickhouseTestMixin, APIBaseTest):
def order(value: str) -> list[str]:
return [
s.session_id
- for s in api.list_mcp_sessions(self.team, limit=50, offset=0, order_by=value)
+ for s in api.list_mcp_sessions(self.team, limit=50, offset=0, order_by=value).results
if s.session_id in target
]
- # Default sort: most-recent session_end first
+ # Default sort: newest session_start first (session_end DESC would give [big, new, old]).
assert order("") == [new_id, big_id, old_id]
# Ascending session_end
- assert order("session_end") == [old_id, big_id, new_id]
+ assert order("session_end") == [old_id, new_id, big_id]
# By tool_call_count desc
assert order("-tool_call_count") == [big_id, old_id, new_id]
# Unknown / unsafe column falls back to default
assert order("password") == [new_id, big_id, old_id]
assert order("-DROP TABLE") == [new_id, big_id, old_id]
+
+ def test_has_next_signals_more_pages(self) -> None:
+ # Identical session_end across all three so only the session_id tiebreaker
+ # gives a stable order — the assertion below would flake without it.
+ ts = datetime.now(tz=UTC) - timedelta(minutes=5)
+ ids = [str(uuid7()) for _ in range(3)]
+ for session_id in ids:
+ self._seed_session(session_id, ["query_run"], session_start=ts, session_end=ts)
+
+ # Over-fetch (limit+1) lets the first page know more exists without a count query.
+ first = api.list_mcp_sessions(self.team, limit=2, offset=0)
+ assert len(first.results) == 2
+ assert first.has_next is True
+
+ # Last page returns the remainder and reports no further pages.
+ second = api.list_mcp_sessions(self.team, limit=2, offset=2)
+ assert len(second.results) == 1
+ assert second.has_next is False
+
+ # Total order → the two pages cover every session exactly once (no skips/dupes).
+ paged = [s.session_id for s in first.results] + [s.session_id for s in second.results]
+ assert sorted(paged) == sorted(ids)
diff --git a/products/mcp_analytics/frontend/generated/api.schemas.ts b/products/mcp_analytics/frontend/generated/api.schemas.ts
index 65d02b9b02a8..9ed09b735f21 100644
--- a/products/mcp_analytics/frontend/generated/api.schemas.ts
+++ b/products/mcp_analytics/frontend/generated/api.schemas.ts
@@ -309,7 +309,7 @@ export interface MCPMissingCapabilityCreateApi {
}
export interface MCPSessionApi {
- /** PostHog $session_id grouping all mcp_tool_call events. */
+ /** $mcp_session_id grouping all mcp_tool_call events in the session. */
readonly session_id: string
/** Total number of mcp_tool_call events in the session. */
readonly tool_calls: number
@@ -334,12 +334,9 @@ export interface MCPSessionApi {
}
export interface PaginatedMCPSessionListApi {
- count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
results: MCPSessionApi[]
+ /** Whether more results exist beyond this page; the client fetches the next page with a larger offset. */
+ has_next: boolean
}
export interface MCPToolCallApi {
@@ -363,12 +360,9 @@ export interface MCPToolCallApi {
}
export interface PaginatedMCPToolCallListApi {
- count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
results: MCPToolCallApi[]
+ /** Whether more results exist beyond this page; the client fetches the next page with a larger offset. */
+ has_next: boolean
}
export type McpAnalyticsFeedbackListParams = {
@@ -403,7 +397,7 @@ export type McpAnalyticsSessionsListParams = {
*/
offset?: number
/**
- * 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_end'.
+ * 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
/**
diff --git a/products/mcp_analytics/frontend/generated/api.ts b/products/mcp_analytics/frontend/generated/api.ts
index 005a9fefe576..d169fdc63e92 100644
--- a/products/mcp_analytics/frontend/generated/api.ts
+++ b/products/mcp_analytics/frontend/generated/api.ts
@@ -179,7 +179,7 @@ export const getMcpAnalyticsSessionsListUrl = (projectId: string, params?: McpAn
}
/**
- * List MCP sessions for the current project, derived by grouping mcp_tool_call events by $mcp_session_id. Ordered by most recent activity first by default.
+ * List MCP sessions for the current project, derived by grouping mcp_tool_call events by $mcp_session_id. Ordered by newest session start first by default.
*/
export const mcpAnalyticsSessionsList = async (
projectId: string,
diff --git a/products/mcp_analytics/frontend/sessions/MCPSessionsTable.scss b/products/mcp_analytics/frontend/sessions/MCPSessionsTable.scss
new file mode 100644
index 000000000000..24e32439c59b
--- /dev/null
+++ b/products/mcp_analytics/frontend/sessions/MCPSessionsTable.scss
@@ -0,0 +1,21 @@
+.MCPSessionsTable {
+ // The list scrolls in the wrapping `max-h` / `overflow-y-auto` container. LemonTable nests
+ // several overflow containers (its own root plus base-ui's ScrollArea), each of which would
+ // otherwise capture a sticky <thead> and keep it from pinning to the scroll container. Make
+ // them transparent to sticky positioning so the header pins to the outer wrapper instead.
+ &.LemonTable,
+ .ScrollableShadows,
+ .ScrollableShadows__inner {
+ overflow: visible !important;
+ }
+
+ // Selector mirrors the base `.LemonTable__content > table > thead { position: relative }`
+ // rule and adds the `.MCPSessionsTable` class so it outranks it and the header can pin.
+ .LemonTable__content > table > thead {
+ position: sticky;
+ top: 0;
+
+ // Sit above the body rows (including the highlighted selected row) as they scroll under it.
+ z-index: 2;
+ }
+}
diff --git a/products/mcp_analytics/frontend/sessions/MCPSessionsTable.tsx b/products/mcp_analytics/frontend/sessions/MCPSessionsTable.tsx
index 55cf45ef0597..c166b408ec96 100644
--- a/products/mcp_analytics/frontend/sessions/MCPSessionsTable.tsx
+++ b/products/mcp_analytics/frontend/sessions/MCPSessionsTable.tsx
@@ -1,3 +1,5 @@
+import './MCPSessionsTable.scss'
+
import { useActions, useValues } from 'kea'
import { IconRefresh } from '@posthog/icons'
@@ -12,8 +14,8 @@ import { mcpSessionsLogic, type MCPSessionSortColumn } from './mcpSessionsLogic'
import { formatDuration, sessionDurationMs } from './utils'
export function MCPSessionsTable(): JSX.Element {
- const { setFilters, loadSessions, selectSession, setSorting } = useActions(mcpSessionsLogic)
- const { sessions, sessionsLoading, filters, selectedSessionId, sorting } = useValues(mcpSessionsLogic)
+ const { setFilters, loadSessions, loadMoreSessions, selectSession, setSorting } = useActions(mcpSessionsLogic)
+ const { sessions, sessionsLoading, filters, selectedSessionId, sorting, hasNext } = useValues(mcpSessionsLogic)
const columns: LemonTableColumns<MCPSessionApi> = [
{
@@ -80,37 +82,56 @@ export function MCPSessionsTable(): JSX.Element {
</div>
<div className="flex flex-col gap-3 lg:flex-row lg:items-start">
<div className="flex-1 min-w-0">
- <LemonTable
- data-attr="mcp-sessions-table"
- size="small"
- pagination={{ pageSize: 20 }}
- dataSource={sessions}
- rowKey="session_id"
- columns={columns}
- loading={sessionsLoading}
- sorting={sorting ? { columnKey: sorting.column, order: sorting.order } : null}
- onSort={(newSorting) =>
- setSorting(
- newSorting
- ? {
- column: newSorting.columnKey as MCPSessionSortColumn,
- order: newSorting.order,
- }
- : null
- )
- }
- useURLForSorting={false}
- emptyState="No MCP sessions yet — try the seed_mcp_sessions management command for local data."
- nouns={['session', 'sessions']}
- onRow={(record) => ({
- onClick: () => selectSession(record.session_id),
- })}
- rowClassName={(record) =>
- record.session_id === selectedSessionId
- ? 'cursor-pointer bg-accent-highlight-secondary'
- : 'cursor-pointer'
- }
- />
+ <div className="max-h-[37rem] overflow-y-auto rounded border border-primary bg-surface-primary">
+ <LemonTable
+ data-attr="mcp-sessions-table"
+ className="MCPSessionsTable"
+ size="small"
+ embedded
+ dataSource={sessions}
+ rowKey="session_id"
+ columns={columns}
+ // Only show the full-table loading overlay on the initial/reset load;
+ // "load more" appends and is signalled by the footer button's own spinner.
+ loading={sessionsLoading && sessions.length === 0}
+ sorting={sorting ? { columnKey: sorting.column, order: sorting.order } : null}
+ onSort={(newSorting) =>
+ setSorting(
+ newSorting
+ ? {
+ column: newSorting.columnKey as MCPSessionSortColumn,
+ order: newSorting.order,
+ }
+ : null
+ )
+ }
+ useURLForSorting={false}
+ emptyState="No MCP sessions yet"
+ nouns={['session', 'sessions']}
+ onRow={(record) => ({
+ onClick: () => selectSession(record.session_id),
+ })}
+ rowClassName={(record) =>
+ record.session_id === selectedSessionId
+ ? 'cursor-pointer bg-accent-highlight-secondary'
+ : 'cursor-pointer'
+ }
+ footer={
+ hasNext ? (
+ <div className="flex justify-center py-1">
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={() => loadMoreSessions()}
+ loading={sessionsLoading}
+ >
+ Load more
+ </LemonButton>
+ </div>
+ ) : undefined
+ }
+ />
+ </div>
</div>
<aside className="w-full lg:w-[480px] flex flex-col rounded border border-primary bg-surface-primary overflow-hidden">
<MCPSessionDetail />
diff --git a/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts
index 232e34805bf2..27f83693017b 100644
--- a/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts
+++ b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts
@@ -17,6 +17,9 @@ const DEFAULT_FILTERS: MCPSessionsFilters = {
const SEARCH_DEBOUNCE_MS = 300
+// How many sessions to fetch per request. Each "Load more" appends the next page
+export const SESSIONS_PAGE_SIZE = 50
+
// Must stay aligned with SESSION_SORT_FIELDS on the backend (logic.py).
export type MCPSessionSortColumn =
| 'session_id'
@@ -32,7 +35,11 @@ export interface MCPSessionSorting {
order: 1 | -1
}
-const DEFAULT_SORTING: MCPSessionSorting = { column: 'session_end', order: -1 }
+const DEFAULT_SORTING: MCPSessionSorting = { column: 'session_start', order: -1 }
+
+function orderByParam(sorting: MCPSessionSorting | null): string | undefined {
+ return sorting ? `${sorting.order === -1 ? '-' : ''}${sorting.column}` : undefined
+}
export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
path(['products', 'mcp_analytics', 'frontend', 'sessions', 'mcpSessionsLogic']),
@@ -41,35 +48,61 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
})),
actions({
// Declared explicitly so kea-typegen emits a no-arg signature for the loader
- // action below — without this, the `(_, breakpoint)` loader signature forces
+ // actions below — without this, the `(_, breakpoint)` loader signature forces
// every call site to pass a placeholder argument.
loadSessions: true,
+ loadMoreSessions: true,
setFilters: (filters: Partial<MCPSessionsFilters>) => ({ filters }),
setSorting: (sorting: MCPSessionSorting | null) => ({ sorting }),
+ setHasNext: (hasNext: boolean) => ({ hasNext }),
selectSession: (sessionId: string | null) => ({ sessionId }),
}),
- loaders(({ values }) => ({
+ loaders(({ values, actions }) => ({
sessions: [
[] as MCPSessionApi[],
{
+ // First page / reset (search or sort change). Replaces the list.
loadSessions: async (_, breakpoint) => {
- // Debounce keystroke-driven loads. afterMount fires loadSessions with no
- // payload, in which case we still want the initial fetch to be fast — so
- // only honour the debounce when there is a search term.
if (values.filters.search) {
await breakpoint(SEARCH_DEBOUNCE_MS)
}
if (!values.currentProjectId) {
return []
}
- const sorting = values.sorting
- const orderBy = sorting ? `${sorting.order === -1 ? '-' : ''}${sorting.column}` : undefined
const response = await mcpAnalyticsSessionsList(String(values.currentProjectId), {
search: values.filters.search || undefined,
- order_by: orderBy,
+ order_by: orderByParam(values.sorting),
+ limit: SESSIONS_PAGE_SIZE,
+ offset: 0,
})
+ actions.setHasNext(response.has_next ?? false)
return [...(response.results ?? [])]
},
+ // Load more: append the next page at offset = current length.
+ loadMoreSessions: async () => {
+ if (!values.currentProjectId) {
+ return values.sessions
+ }
+ // Snapshot the list and the query (search + sort) before the await. If a
+ // concurrent loadSessions reset (sort/search change) lands while this page
+ // is in flight, merging against the post-await values.sessions would corrupt
+ // the list — so we both offset and merge from the snapshot, and drop this
+ // page entirely if the query changed underneath us.
+ const baseSessions = values.sessions
+ const search = values.filters.search
+ const orderBy = orderByParam(values.sorting)
+ const response = await mcpAnalyticsSessionsList(String(values.currentProjectId), {
+ search: search || undefined,
+ order_by: orderBy,
+ limit: SESSIONS_PAGE_SIZE,
+ offset: baseSessions.length,
+ })
+ if (search !== values.filters.search || orderBy !== orderByParam(values.sorting)) {
+ return values.sessions
+ }
+ actions.setHasNext(response.has_next ?? false)
+ return [...baseSessions, ...(response.results ?? [])]
+ },
},
],
toolCalls: [
@@ -104,6 +137,15 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
setSorting: (_, { sorting }) => sorting,
},
],
+ hasNext: [
+ false,
+ {
+ setHasNext: (_, { hasNext }) => hasNext,
+ // Hide "Load more" the moment a reset starts so it isn't shown (disabled,
+ // spinning) during the reset; setHasNext restores it when the page resolves.
+ loadSessions: () => false,
+ },
+ ],
}),
selectors({
selectedSession: [
@@ -117,6 +159,7 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
],
}),
listeners(({ actions, values }) => ({
+ // A new filter or sort changes the result set — reload from the first page.
setFilters: () => {
actions.loadSessions()
},
@@ -128,9 +171,9 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
actions.loadToolCalls(sessionId)
}
},
+ // Only fires on a reset load (not on loadMore), so appending more pages doesn't
+ // steal the user's selection. Auto-selects the first row when the set changes.
loadSessionsSuccess: ({ sessions }) => {
- // Auto-select the first session whenever results come back. If the user
- // had a session pinned that is no longer in the filtered set, clear it.
if (sessions.length === 0) {
if (values.selectedSessionId) {
actions.selectSession(null)
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b8b58d2f4ec0..118cf50b1ad4 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -21094,7 +21094,7 @@ export namespace Schemas {
}
export interface MCPSession {
- /** PostHog $session_id grouping all mcp_tool_call events. */
+ /** $mcp_session_id grouping all mcp_tool_call events in the session. */
readonly session_id: string;
/** Total number of mcp_tool_call events in the session. */
readonly tool_calls: number;
@@ -22942,21 +22942,15 @@ export namespace Schemas {
}
export interface PaginatedMCPSessionList {
- count: number;
- /** @nullable */
- next?: string | null;
- /** @nullable */
- previous?: string | null;
results: MCPSession[];
+ /** Whether more results exist beyond this page; the client fetches the next page with a larger offset. */
+ has_next: boolean;
}
export interface PaginatedMCPToolCallList {
- count: number;
- /** @nullable */
- next?: string | null;
- /** @nullable */
- previous?: string | null;
results: MCPToolCall[];
+ /** Whether more results exist beyond this page; the client fetches the next page with a larger offset. */
+ has_next: boolean;
}
export interface PaginatedMaterializedColumnSlotList {
@@ -41263,7 +41257,7 @@ export namespace Schemas {
*/
offset?: number;
/**
- * 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_end'.
+ * 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;
/**