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): load-more button for a session's tool calls (#68162)

Georgis Andonis9dcc0a43beaa
diff --git a/products/mcp_analytics/backend/logic.py b/products/mcp_analytics/backend/logic.py
index 7aa1aaabbb70..e1fa6b8c47be 100644
--- a/products/mcp_analytics/backend/logic.py
+++ b/products/mcp_analytics/backend/logic.py
@@ -43,7 +43,7 @@ FROM events
WHERE event = {event}
AND timestamp >= {date_from}
AND $session_id = {session_id}
-ORDER BY timestamp ASC
+ORDER BY timestamp ASC, event_id ASC
LIMIT {limit}
OFFSET {offset}
"""
diff --git a/products/mcp_analytics/backend/tests/test_api.py b/products/mcp_analytics/backend/tests/test_api.py
index c637844f9433..0659cff29d06 100644
--- a/products/mcp_analytics/backend/tests/test_api.py
+++ b/products/mcp_analytics/backend/tests/test_api.py
@@ -551,6 +551,21 @@ class TestListMCPToolCalls(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin
assert [c.tool_name for c in second.results] == ["third"]
assert second.has_next is False
+ def test_pagination_is_stable_across_tied_timestamps(self) -> None:
+ session_id = str(uuid7())
+ ts = datetime.now(tz=UTC) - timedelta(minutes=5)
+ # All four calls share a timestamp (a burst), so only the event_id tiebreaker gives a total
+ # order — without it, the two offset pages could overlap or skip a boundary row.
+ for tool in ["a", "b", "c", "d"]:
+ self._seed_tool_call(session_id, timestamp=ts, tool=tool)
+
+ first = api.list_mcp_tool_calls(self.team, session_id=session_id, limit=2, offset=0, date_from=ts)
+ second = api.list_mcp_tool_calls(self.team, session_id=session_id, limit=2, offset=2, date_from=ts)
+ event_ids = [c.event_id for c in first.results] + [c.event_id for c in second.results]
+
+ # The two pages cover all four calls with no duplicates and no skips.
+ assert len(set(event_ids)) == 4
+
class TestSessionEventsLookbackBound(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):
"""The session-detail queries (tool calls and intents alike) bound their scan to
diff --git a/products/mcp_analytics/frontend/sessions/MCPSessionDetail.tsx b/products/mcp_analytics/frontend/sessions/MCPSessionDetail.tsx
index 585a7250c4c3..8edde6cdd77f 100644
--- a/products/mcp_analytics/frontend/sessions/MCPSessionDetail.tsx
+++ b/products/mcp_analytics/frontend/sessions/MCPSessionDetail.tsx
@@ -2,6 +2,7 @@ import { useActions, useValues } from 'kea'
import { IconBolt, IconClock, IconSparkles, IconUser, IconWarning } from '@posthog/icons'
import { LemonButton, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'
+import { Button, Spinner } from '@posthog/quill-primitives'
import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
@@ -19,9 +20,9 @@ function MetaBadge({ icon, label }: { icon: React.ReactNode; label: React.ReactN
}
export function MCPSessionDetail(): JSX.Element {
- const { selectedSession, toolCalls, toolCallsLoading, selectedSessionIntent, isSelectedSessionGenerating } =
+ const { selectedSession, selectedSessionToolCalls, selectedSessionIntent, isSelectedSessionGenerating } =
useValues(mcpSessionsLogic)
- const { generateIntent } = useActions(mcpSessionsLogic)
+ const { generateIntent, loadMoreToolCalls } = useActions(mcpSessionsLogic)
if (!selectedSession) {
return (
@@ -38,8 +39,9 @@ export function MCPSessionDetail(): JSX.Element {
? selectedSession.person_name || selectedSession.person_email || selectedSession.distinct_id
: selectedSession.distinct_id || 'unknown'
- // While the selected session's tool calls load, animate the whole detail panel
- const loading = toolCallsLoading
+ // The panel's view of the selected session's calls: the list, whether more pages exist, whether
+ // the first page is still loading (skeleton), and whether a "Load more" append is in flight.
+ const { calls: toolCalls, hasNext, loading, loadingMore } = selectedSessionToolCalls
return (
<div className="flex flex-col h-full min-h-0">
@@ -127,56 +129,75 @@ export function MCPSessionDetail(): JSX.Element {
) : toolCalls.length === 0 ? (
<div className="text-sm text-secondary">No tool calls captured for this session.</div>
) : (
- <ol className="flex flex-col gap-2 list-none pl-0">
- {toolCalls.map((toolCall, idx) => (
- <li
- key={toolCall.event_id || `${toolCall.timestamp}-${idx}`}
- className={`relative flex flex-col gap-1 rounded border bg-surface-primary px-2 py-1.5 transition-colors hover:bg-surface-secondary ${
- toolCall.is_error
- ? 'border-danger border-l-2'
- : 'border-primary border-l-2 border-l-accent/60'
- }`}
- >
- <div className="flex items-center justify-between gap-2 text-xs">
- <div className="flex items-center gap-1.5 min-w-0">
- {toolCall.is_error ? (
- <IconWarning className="text-danger shrink-0 text-xs" />
- ) : (
- <IconBolt className="text-accent shrink-0 text-xs" />
- )}
- <span className="font-mono font-semibold truncate">
- {toolCall.tool_name || 'unknown'}
- </span>
- {toolCall.is_error ? (
- <LemonTag type="danger" size="small">
- error
- </LemonTag>
- ) : null}
- </div>
- <div className="flex items-center gap-2 text-secondary whitespace-nowrap font-mono text-[11px]">
- {toolCall.duration_ms != null ? (
- <span>{formatDuration(toolCall.duration_ms)} ·</span>
- ) : null}
- <span>
- {formatRelativeOffset(selectedSession.session_start, toolCall.timestamp)}
- </span>
+ <>
+ <ol className="flex flex-col gap-2 list-none pl-0">
+ {toolCalls.map((toolCall, idx) => (
+ <li
+ key={toolCall.event_id || `${toolCall.timestamp}-${idx}`}
+ className={`relative flex flex-col gap-1 rounded border bg-surface-primary px-2 py-1.5 transition-colors hover:bg-surface-secondary ${
+ toolCall.is_error
+ ? 'border-danger border-l-2'
+ : 'border-primary border-l-2 border-l-accent/60'
+ }`}
+ >
+ <div className="flex items-center justify-between gap-2 text-xs">
+ <div className="flex items-center gap-1.5 min-w-0">
+ {toolCall.is_error ? (
+ <IconWarning className="text-danger shrink-0 text-xs" />
+ ) : (
+ <IconBolt className="text-accent shrink-0 text-xs" />
+ )}
+ <span className="font-mono font-semibold truncate">
+ {toolCall.tool_name || 'unknown'}
+ </span>
+ {toolCall.is_error ? (
+ <LemonTag type="danger" size="small">
+ error
+ </LemonTag>
+ ) : null}
+ </div>
+ <div className="flex items-center gap-2 text-secondary whitespace-nowrap font-mono text-[11px]">
+ {toolCall.duration_ms != null ? (
+ <span>{formatDuration(toolCall.duration_ms)} ·</span>
+ ) : null}
+ <span>
+ {formatRelativeOffset(
+ selectedSession.session_start,
+ toolCall.timestamp
+ )}
+ </span>
+ </div>
</div>
- </div>
-
- <div className="text-xs leading-snug pl-5">
- {toolCall.intent || (
- <span className="text-secondary italic">No intent captured.</span>
- )}
- </div>
- {toolCall.is_error && toolCall.error_message ? (
- <div className="text-xs text-danger font-mono pl-5 break-all">
- {toolCall.error_message}
+ <div className="text-xs leading-snug pl-5">
+ {toolCall.intent || (
+ <span className="text-secondary italic">No intent captured.</span>
+ )}
</div>
- ) : null}
- </li>
- ))}
- </ol>
+
+ {toolCall.is_error && toolCall.error_message ? (
+ <div className="text-xs text-danger font-mono pl-5 break-all">
+ {toolCall.error_message}
+ </div>
+ ) : null}
+ </li>
+ ))}
+ </ol>
+ {hasNext ? (
+ <div className="flex justify-center pt-2" data-quill>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => loadMoreToolCalls()}
+ disabled={loadingMore}
+ data-attr="mcp-session-load-more-tool-calls"
+ >
+ {loadingMore ? <Spinner /> : null}
+ Load more
+ </Button>
+ </div>
+ ) : null}
+ </>
)}
</section>
diff --git a/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.test.ts b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.test.ts
new file mode 100644
index 000000000000..15f157c923da
--- /dev/null
+++ b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.test.ts
@@ -0,0 +1,73 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import { mcpAnalyticsSessionsList, mcpAnalyticsSessionsToolCalls } from '../generated/api'
+import { mcpSessionsLogic } from './mcpSessionsLogic'
+
+jest.mock('../generated/api', () => ({
+ mcpAnalyticsSessionsList: jest.fn(),
+ mcpAnalyticsSessionsToolCalls: jest.fn(),
+ mcpAnalyticsSessionsGenerateIntent: jest.fn(),
+}))
+
+const listMock = mcpAnalyticsSessionsList as jest.Mock
+const toolCallsMock = mcpAnalyticsSessionsToolCalls as jest.Mock
+
+const toolCall = (eventId: string): any => ({
+ event_id: eventId,
+ timestamp: '2026-01-01T00:00:00Z',
+ tool_name: eventId,
+ intent: '',
+ is_error: false,
+ error_message: '',
+ duration_ms: null,
+})
+
+describe('mcpSessionsLogic', () => {
+ let logic: ReturnType<typeof mcpSessionsLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ listMock.mockResolvedValue({ results: [], has_next: false })
+ logic = mcpSessionsLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ jest.clearAllMocks()
+ })
+
+ it('keeps the skeleton on the newly selected session when a prior load-more resolves late', async () => {
+ // Session A: a first page with a further page available.
+ toolCallsMock.mockResolvedValueOnce({ results: [toolCall('a1')], has_next: true })
+ await expectLogic(logic, () => {
+ logic.actions.selectSession('A')
+ }).toDispatchActions(['loadToolCallsSuccess'])
+ expect(logic.values.selectedSessionToolCalls.calls.map((c) => c.event_id)).toEqual(['a1'])
+
+ // "Load more" for A is dispatched but held in flight.
+ let resolveAMore: (value: any) => void = () => {}
+ toolCallsMock.mockImplementationOnce(() => new Promise((resolve) => (resolveAMore = resolve)))
+ await expectLogic(logic, () => {
+ logic.actions.loadMoreToolCalls()
+ }).toDispatchActions(['loadMoreToolCalls'])
+
+ // The user switches to B before A's page returns; B's first page never resolves here.
+ toolCallsMock.mockImplementationOnce(() => new Promise(() => {}))
+ await expectLogic(logic, () => {
+ logic.actions.selectSession('B')
+ }).toDispatchActions(['loadToolCalls'])
+ expect(logic.values.selectedSessionId).toBe('B')
+ expect(logic.values.selectedSessionToolCalls.loading).toBe(true)
+
+ // A's load-more finally resolves. It must neither merge into B's list nor drop B's skeleton.
+ await expectLogic(logic, () => {
+ resolveAMore({ results: [toolCall('a2')], has_next: false })
+ }).toDispatchActions(['loadMoreToolCallsSuccess'])
+
+ expect(logic.values.selectedSessionToolCalls.loading).toBe(true)
+ expect(logic.values.selectedSessionToolCalls.calls.map((c) => c.event_id)).not.toContain('a2')
+ })
+})
diff --git a/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts
index 3f617c08f019..0fa22e6a803f 100644
--- a/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts
+++ b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts
@@ -36,6 +36,10 @@ 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
+// How many of a session's tool calls to fetch per request. Each "Load more" appends the
+// next page; the button appears whenever a session has more calls than one page.
+export const TOOL_CALLS_PAGE_SIZE = 100
+
// Must stay aligned with SESSION_SORT_FIELDS on the backend (logic.py).
export type MCPSessionSortColumn =
| 'session_id'
@@ -59,6 +63,36 @@ export function orderByParam(sorting: MCPSessionSorting | null): MCPSessionOrder
return sorting ? `${sorting.order === -1 ? '-' : ''}${sorting.column}` : undefined
}
+// A session's loaded tool calls, tagged with which session they belong to and whether more pages
+// exist. Carrying the session id in the value lets the panel tell "the selected session is still
+// loading" from "these are a previous session's calls" with a plain comparison — no separate
+// tracking reducer, and no reliance on the shared loader flag that a concurrent load-more can flip.
+export interface SessionToolCalls {
+ sessionId: string | null
+ calls: MCPToolCallApi[]
+ hasNext: boolean
+}
+
+const EMPTY_TOOL_CALLS: SessionToolCalls = { sessionId: null, calls: [], hasNext: false }
+
+// Fetch one page of a session's tool calls, unwrapped into { calls, hasNext }. session_id comes from
+// untrusted event properties, so encode it — path/query delimiters must not redirect the request to
+// another same-origin endpoint. date_from bounds the scan by the session's start so sessions older
+// than the backend's default lookback still return their calls.
+async function fetchToolCallsPage(
+ projectId: string | number,
+ sessionId: string,
+ sessionStart: string | null | undefined,
+ offset: number
+): Promise<{ calls: MCPToolCallApi[]; hasNext: boolean }> {
+ const response = await mcpAnalyticsSessionsToolCalls(String(projectId), encodeURIComponent(sessionId), {
+ date_from: sessionStart || undefined,
+ limit: TOOL_CALLS_PAGE_SIZE,
+ offset,
+ })
+ return { calls: response.results ?? [], hasNext: response.has_next ?? false }
+}
+
export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
path(['products', 'mcp_analytics', 'frontend', 'sessions', 'mcpSessionsLogic']),
connect(() => ({
@@ -70,6 +104,7 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
// every call site to pass a placeholder argument.
loadSessions: true,
loadMoreSessions: true,
+ loadMoreToolCalls: true,
setFilters: (filters: Partial<MCPSessionsFilters>) => ({ filters }),
setDateFilter: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
setSorting: (sorting: MCPSessionSorting | null) => ({ sorting }),
@@ -136,24 +171,41 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
},
],
toolCalls: [
- [] as MCPToolCallApi[],
+ EMPTY_TOOL_CALLS,
{
+ // First page for a session. Replaces the value, tagged with the session it's for.
loadToolCalls: async (sessionId: string, breakpoint) => {
if (!values.currentProjectId || !sessionId) {
- return []
+ return EMPTY_TOOL_CALLS
}
- // session_id comes from untrusted event properties — encode it so path/query
- // delimiters can't redirect this request to another same-origin endpoint.
- // Pass the session's start as the scan bound so sessions older than the
- // backend's default lookback still return their tool calls.
- const session = values.sessions.find((s) => s.session_id === sessionId)
- const response = await mcpAnalyticsSessionsToolCalls(
- String(values.currentProjectId),
- encodeURIComponent(sessionId),
- { date_from: session?.session_start || undefined }
+ const page = await fetchToolCallsPage(
+ values.currentProjectId,
+ sessionId,
+ values.selectedSession?.session_start,
+ 0
)
breakpoint()
- return [...(response.results ?? [])]
+ return { sessionId, ...page }
+ },
+ // Load more: append the next page at offset = current length.
+ loadMoreToolCalls: async () => {
+ const { sessionId, calls } = values.toolCalls
+ if (!values.currentProjectId || !sessionId) {
+ return values.toolCalls
+ }
+ const page = await fetchToolCallsPage(
+ values.currentProjectId,
+ sessionId,
+ values.selectedSession?.session_start,
+ calls.length
+ )
+ // If the user switched sessions while this page was loading, drop it — appending
+ // one session's calls onto another's list would show the wrong data. The backend
+ // orders by (timestamp, event_id), so pages don't overlap and need no dedupe.
+ if (sessionId !== values.selectedSessionId) {
+ return values.toolCalls
+ }
+ return { sessionId, calls: [...calls, ...page.calls], hasNext: page.hasNext }
},
},
],
@@ -167,11 +219,10 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
// session_id comes from untrusted event properties — encode it so path/query
// delimiters can't redirect this POST to another same-origin endpoint. Bound the
// intent scan by the session's start so older sessions resolve, mirroring loadToolCalls.
- const session = values.sessions.find((s) => s.session_id === sessionId)
return await mcpAnalyticsSessionsGenerateIntent(
String(values.currentProjectId),
encodeURIComponent(sessionId),
- { date_from: session?.session_start || undefined }
+ { date_from: values.selectedSession?.session_start || undefined }
)
},
},
@@ -255,6 +306,28 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
(generatedIntentLoading, generatingSessionId, selectedSessionId): boolean =>
generatedIntentLoading && generatingSessionId === selectedSessionId,
],
+ // Everything the detail panel needs about the selected session's calls, derived from the
+ // loaded value (tagged with its session) so a previous session's calls never render under
+ // the new session's header. A plain comparison — no shared loader flag a concurrent load
+ // more could flip.
+ selectedSessionToolCalls: [
+ (s) => [s.toolCalls, s.selectedSessionId, s.toolCallsLoading],
+ (
+ toolCalls,
+ selectedSessionId,
+ toolCallsLoading
+ ): { calls: MCPToolCallApi[]; hasNext: boolean; loading: boolean; loadingMore: boolean } => {
+ const isCurrent = toolCalls.sessionId === selectedSessionId
+ return {
+ calls: isCurrent ? toolCalls.calls : [],
+ hasNext: isCurrent && toolCalls.hasNext,
+ // First page still loading: the loaded value isn't for the selected session yet.
+ loading: selectedSessionId !== null && !isCurrent,
+ // A "Load more" append is in flight for the session already on screen.
+ loadingMore: isCurrent && toolCallsLoading,
+ }
+ },
+ ],
}),
listeners(({ actions, values }) => ({
// A new filter or sort changes the result set — reload from the first page.