The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Add pagination and sorting to MCP analytics tool calls (#77599)
Sébastiend7a87295dffa
diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpAnalyticsPage.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpAnalyticsPage.tsxindex ef8092c9325..6d9f308a549 100644--- a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpAnalyticsPage.tsx+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpAnalyticsPage.tsx@@ -32,10 +32,10 @@ import { McpEventsTable } from "./McpEventsTable";* filters. Shows a single empty state (no tabs) when the filtered view has no activity.*/export function McpAnalyticsPage({ location, router }: WithRouterProps) {- const [{ date, user, group, tenant, tab }, { patchUrlState }] = useUrlState(- location,- mcpUrlStateConfig,- );+ const [+ { date, user, group, tenant, tab, page, sortColumn, sortDirection },+ { patchUrlState },+ ] = useUrlState(location, mcpUrlStateConfig);const {dateFilter,@@ -67,7 +67,7 @@ export function McpAnalyticsPage({ location, router }: WithRouterProps) {const chartFilters = { dateFilter, userId, groupId, tenantId };- const { isInitialLoading, isRefetching, hasData } = useMcpHasData({+ const { isInitialLoading, isRefetching, hasData, count } = useMcpHasData({...dataSources,...chartFilters,});@@ -104,16 +104,16 @@ export function McpAnalyticsPage({ location, router }: WithRouterProps) {<McpToolCallsFilterdate={date}- onDateChange={(val) => patchUrlState({ date: val })}+ onDateChange={(val) => patchUrlState({ date: val, page: 0 })}user={user}- onUserChange={(val) => patchUrlState({ user: val })}+ onUserChange={(val) => patchUrlState({ user: val, page: 0 })}userOptions={userOptions}group={group}- onGroupChange={(val) => patchUrlState({ group: val })}+ onGroupChange={(val) => patchUrlState({ group: val, page: 0 })}groupOptions={groupOptions}groupNoFilterValue={groupNoFilterValue}tenant={tenant}- onTenantChange={(val) => patchUrlState({ tenant: val })}+ onTenantChange={(val) => patchUrlState({ tenant: val, page: 0 })}tenantOptions={tenantOptions}hasTenants={hasTenants}/>@@ -204,6 +204,20 @@ export function McpAnalyticsPage({ location, router }: WithRouterProps) {{...chartFilters}hasTenants={hasTenants}hasPii={hasPii}+ page={page}+ total={count}+ onPageChange={(newPage) => patchUrlState({ page: newPage })}+ sortingOptions={{+ sort_column: sortColumn,+ sort_direction: sortDirection,+ }}+ onSortingOptionsChange={(newSorting) =>+ patchUrlState({+ sortColumn: newSorting.sort_column,+ sortDirection: newSorting.sort_direction,+ page: 0,+ })+ }/></Tabs.Panel></Tabs>diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpAnalyticsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpAnalyticsPage.unit.spec.tsxindex a8223467742..e037384412b 100644--- a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpAnalyticsPage.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpAnalyticsPage.unit.spec.tsx@@ -33,6 +33,11 @@ registerVisualizations();const MCP_TOOL_CALLS_TABLE_ID = 2001;const GROUP_MEMBERS_TABLE_ID = 2002;+// Field ids are deterministic — `table_id * 100 + field index` (see `buildTable`). Indices below+// match the field order of the `v_mcp_tool_calls` table defined further down.+const TOOL_CALL_ID_FIELD_ID = MCP_TOOL_CALLS_TABLE_ID * 100 + 0;+const CREATED_AT_FIELD_ID = MCP_TOOL_CALLS_TABLE_ID * 100 + 1;+const BASE_TYPE = {text: "type/Text",integer: "type/Integer",@@ -118,6 +123,32 @@ const datasetResponse: Dataset = createMockDataset({running_time: 1,});+// A count/breakout dataset whose scalar count (rows[0][0]) exceeds one page, so the events+// table's pagination controls appear (total > EVENTS_PAGE_SIZE of 25).+const multiPageDatasetResponse: Dataset = createMockDataset({+ data: createMockDatasetData({+ rows: [+ [60, "search_data"],+ [7, "run_query"],+ ],+ cols: [+ createMockColumn({+ source: "aggregation",+ name: "count",+ display_name: "Count",+ }),+ createMockColumn({+ source: "breakout",+ name: "tool_name",+ display_name: "Tool name",+ }),+ ],+ }),+ database_id: AUDIT_DB_ID,+ row_count: 2,+ running_time: 1,+});+// A zero-count aggregation result — what the page's "has any data?" probe gets when the// filtered view is empty.const emptyDatasetResponse: Dataset = createMockDataset({@@ -200,11 +231,104 @@ describe("McpAnalyticsPage", () => {);const eventsPanel = screen.getByRole("tabpanel");+ expect(await within(eventsPanel).findByRole("table")).toBeInTheDocument();+ // curated column header + a cell value from the mocked dataset row+ expect(within(eventsPanel).getByText("Tool")).toBeInTheDocument();expect(- await within(eventsPanel).findByTestId("table-root"),+ await within(eventsPanel).findByText("search_data"),).toBeInTheDocument();});+ it("sorts the events table server-side when a column header is clicked", async () => {+ setup();++ await screen.findByRole("heading", { name: "MCP analytics" });+ await userEvent.click(+ await screen.findByRole("tab", { name: "Tool calls" }),+ );++ // The Tool header is sortable; clicking it re-sorts ascending (it wasn't the active column).+ await userEvent.click(await screen.findByRole("button", { name: "Tool" }));++ await waitFor(() => {+ const sortedAscending = fetchMock.callHistory+ .calls("dataset")+ .some((call) => {+ const body = call.options?.body;+ if (typeof body !== "string") {+ return false;+ }+ const stage = JSON.parse(body).stages?.[0];+ return stage?.page != null && stage["order-by"]?.[0]?.[0] === "asc";+ });+ expect(sortedAscending).toBe(true);+ });+ });++ it("paginates the events table when there are more matching rows than one page", async () => {+ setup({ dataset: multiPageDatasetResponse });++ await screen.findByRole("heading", { name: "MCP analytics" });+ await userEvent.click(+ await screen.findByRole("tab", { name: "Tool calls" }),+ );++ const pagination = await screen.findByRole("navigation", {+ name: "pagination",+ });+ // First page: previous disabled, next enabled (total 60 spans multiple pages of 25).+ expect(within(pagination).getByLabelText("Previous page")).toBeDisabled();+ const nextButton = within(pagination).getByLabelText("Next page");+ expect(nextButton).toBeEnabled();++ await userEvent.click(nextButton);++ // Advancing issues an adhoc dataset query for the second MBQL page (1-indexed).+ await waitFor(() => {+ const requestedPage2 = fetchMock.callHistory+ .calls("dataset")+ .some((call) => {+ const body = call.options?.body;+ if (typeof body !== "string") {+ return false;+ }+ return JSON.parse(body)?.stages?.[0]?.page?.page === 2;+ });+ expect(requestedPage2).toBe(true);+ });+ });++ it("orders the events query by a total order (created_at + tool_call_id) for stable paging", async () => {+ setup();++ await screen.findByRole("heading", { name: "MCP analytics" });+ await userEvent.click(+ await screen.findByRole("tab", { name: "Tool calls" }),+ );++ // The events request is the paginated one (carries a `page` clause); its order-by must be+ // created_at followed by the tool_call_id (PK) tiebreaker, so pages can't skip/duplicate rows+ // on tied timestamps.+ await waitFor(() => {+ const eventsStage = fetchMock.callHistory+ .calls("dataset")+ .map((call) => call.options?.body)+ .filter((body): body is string => typeof body === "string")+ .map((body) => JSON.parse(body).stages?.[0])+ .find((stage) => stage?.page != null);+ // pMBQL order-by clause: [direction, opts, ["field", opts, fieldId]]+ const orderBy = eventsStage?.["order-by"] as [+ string,+ object,+ [string, object, number],+ ][];+ expect(orderBy?.map((clause) => clause[2][2])).toEqual([+ CREATED_AT_FIELD_ID,+ TOOL_CALL_ID_FIELD_ID,+ ]);+ });+ });+it("shows a single empty state (no tabs, no charts) when there is no activity", async () => {setup({ dataset: emptyDatasetResponse });diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpEventsTable.module.css b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpEventsTable.module.cssnew file mode 100644index 00000000000..a20b9bf988d--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpEventsTable.module.css@@ -0,0 +1,40 @@+.scroll {+ overflow: auto;+ /* Cap the body so it scrolls internally and the pagination controls below the card stay in+ view. The offset must clear the chrome above the card (nav, any banner, page header, tabs)+ plus the pager below it; sized generously so the pager stays visible even with a banner. */+ max-height: calc(100vh - 23rem);+ min-height: 15rem;+}++.table {+ width: 100%;+}++/* Keep the sortable headers reachable while the body scrolls. */+.table thead th {+ position: sticky;+ top: 0;+ z-index: 1;+ background-color: var(--mb-color-background_surface-primary);+}++.table thead th,+.table thead th * {+ color: var(--mb-color-core-brand);+ white-space: nowrap;+}++.table td,+.table th {+ padding-block: 0.75em;+ white-space: nowrap;+}++.table td:first-child {+ font-weight: normal;+}++.table tbody tr:not(:last-child) {+ border-bottom: 1px solid var(--mb-color-border-neutral);+}diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpEventsTable.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpEventsTable.tsxindex 150a0fa30c8..2653b011334 100644--- a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpEventsTable.tsx+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpEventsTable.tsx@@ -1,141 +1,141 @@-import { useMemo } from "react";+import cx from "classnames";+import { type ReactNode, useMemo, useRef } from "react";import { t } from "ttag";+import { DateTime } from "metabase/common/components/DateTime";+import { SortableColumnHeader } from "metabase/common/components/ItemsTable/BaseItemsTable";+import { PaginationControls } from "metabase/common/components/PaginationControls";+import AdminS from "metabase/css/admin.module.css";+import { Box, Card, Flex, LoadingOverlay } from "metabase/ui";+import { EMPTY_CELL_PLACEHOLDER } from "metabase/utils/constants";+import { formatNumber } from "metabase/utils/formatting";import type {CardMetadata,MetadataProvider,TableMetadata,} from "metabase-lib";-import type { DatasetQuery, TableColumnOrderSetting } from "metabase-types/api";+import type { RowValue, RowValues, SortingOptions } from "metabase-types/api";-import { BreakoutChartCard } from "../../metabot-analytics/components/ConversationStatsPage/BreakoutChartCard";-import { useAdhocBreakoutQuery } from "../../metabot-analytics/hooks/useAdhocBreakoutQuery";-import type { McpFilters } from "../query-utils";+import { useMcpEventsQuery } from "../hooks/useMcpEventsQuery";+import type { McpEventSortColumn, McpFilters } from "../query-utils";import { buildEventsQuery } from "../query-utils";-const EVENTS_LIMIT = 100;-const TABLE_HEIGHT = 600;--// Columns surfaced in the events table, in display order. Every other view column (raw ids,-// client_name, …) is hidden. `tenant_name` is only included when tenants are enabled, and-// `ip_address` only when PII retention is on (it's null otherwise); `error_type`/`error_message`-// are populated only for failed calls (error_message is gated by analytics-pii-retention-enabled).-function eventColumns(hasTenants: boolean, hasPii: boolean): string[] {- return [- "tool_call_id",- "created_at",- "tool_name",- "client_display_name",- "client_version",- "user_display_name",- ...(hasTenants ? ["tenant_name"] : []),- ...(hasPii ? ["ip_address"] : []),- "status",- "duration_ms",- "error_type",- // error_message is gated PII (the backend only writes it when retention is on), so hide it- // alongside ip_address rather than show a permanently-blank column.- ...(hasPii ? ["error_message"] : []),+import S from "./McpEventsTable.module.css";++export const EVENTS_PAGE_SIZE = 25;++type EventColumn = {+ /** View column name, matched case-insensitively against the result columns. */+ key: string;+ title: string;+ /** Present when the column can be sorted server-side. */+ sort?: McpEventSortColumn;+ align?: "right";+ render?: (value: RowValue) => ReactNode;+};++/**+ * The curated columns surfaced in the events table, in display order. Only these are ever+ * rendered — every other view column (raw ids, client_name, user_agent, …) stays hidden by+ * construction, so nothing sensitive can leak. `tenant_name` shows only when tenants are enabled;+ * `ip_address`/`error_message` only when PII retention is on (they're null otherwise).+ */+export function eventColumns(+ hasTenants: boolean,+ hasPii: boolean,+): EventColumn[] {+ const columns: (EventColumn | false)[] = [+ { key: "tool_call_id", title: t`ID` },+ {+ key: "created_at",+ title: t`Created at`,+ sort: "created_at",+ render: (value) =>+ value == null ? (+ EMPTY_CELL_PLACEHOLDER+ ) : (+ <DateTime value={String(value)} />+ ),+ },+ { key: "tool_name", title: t`Tool`, sort: "tool_name" },+ {+ key: "client_display_name",+ title: t`Client`,+ sort: "client_display_name",+ },+ { key: "client_version", title: t`Client version` },+ { key: "user_display_name", title: t`User`, sort: "user_display_name" },+ hasTenants && { key: "tenant_name", title: t`Tenant` },+ hasPii && { key: "ip_address", title: t`IP address` },+ { key: "status", title: t`Status`, sort: "status" },+ {+ key: "duration_ms",+ title: t`Duration (ms)`,+ sort: "duration_ms",+ align: "right",+ render: (value) =>+ value == null ? EMPTY_CELL_PLACEHOLDER : formatNumber(Number(value)),+ },+ { key: "error_type", title: t`Error type` },+ hasPii && { key: "error_message", title: t`Error message` },];+ return columns.filter((column): column is EventColumn => column !== false);}-/** Sentence-case header overrides for the surfaced columns, keyed by view column name. */-function columnTitles(): Record<string, string> {- return {- tool_call_id: t`ID`,- created_at: t`Created at`,- tool_name: t`Tool`,- client_display_name: t`Client`,- client_version: t`Client version`,- user_display_name: t`User`,- tenant_name: t`Tenant`,- ip_address: t`IP address`,- status: t`Status`,- duration_ms: t`Duration (ms)`,- error_type: t`Error type`,- error_message: t`Error message`,- };+function renderCell(column: EventColumn, value: RowValue): ReactNode {+ if (column.render) {+ return column.render(value);+ }+ return value == null || value === "" ? EMPTY_CELL_PLACEHOLDER : String(value);}-type Props = McpFilters & {- provider: MetadataProvider | null;- table: TableMetadata | CardMetadata | null;- groupMembersTable: TableMetadata | CardMetadata | null;- hasTenants: boolean;- hasPii: boolean;+type PaginationProps = {+ /** Current page, 0-indexed. */+ page: number;+ /** Total number of tool calls matching the filters (across all pages). */+ total: number;+ onPageChange: (page: number) => void;+};++type SortProps = {+ sortingOptions: SortingOptions<McpEventSortColumn>;+ onSortingOptionsChange: (+ sortingOptions: SortingOptions<McpEventSortColumn>,+ ) => void;};-type InnerProps = McpFilters & {+type Nullable<T> = { [K in keyof T]: T[K] | null };++// The audit metadata sources the inner table needs, all resolved.+type MetadataSources = {provider: MetadataProvider;table: TableMetadata | CardMetadata;groupMembersTable: TableMetadata | CardMetadata;- hasTenants: boolean;- hasPii: boolean;};+type BaseProps = McpFilters &+ PaginationProps &+ SortProps & {+ hasTenants: boolean;+ hasPii: boolean;+ };++// Sources are still loading in the outer props (hence nullable); the inner component only renders+// once they're resolved, so it takes them non-null.+type Props = BaseProps & Nullable<MetadataSources>;+type InnerProps = BaseProps & MetadataSources;+/**- * Wrap a row-level dataset as a single-card table rawSeries for `<Visualization>`. Surfaces only- * the {@link eventColumns} present in the result (in display order) with Sentence-case headers,- * and explicitly hides every other view column. Returns null when there's no data yet.+ * Retain the last non-nullish value so a component keeps rendering the previous result while the+ * next one loads. RTK query hooks return `undefined` data mid-fetch; without this a consumer would+ * blank out on every refetch.*/-export function buildEventsRawSeries(- data: ReturnType<typeof useAdhocBreakoutQuery>["data"],- jsQuery: DatasetQuery | null,- hasTenants: boolean,- hasPii: boolean,-) {- if (!data?.data || !jsQuery) {- return null;+function useRetainedValue<T>(value: T | undefined): T | undefined {+ const ref = useRef(value);+ if (value != null) {+ ref.current = value;}- const titles = columnTitles();- const { cols } = data.data;-- // Result column names are upper- or lower-cased depending on the warehouse (the audit DB is- // H2, which upper-cases identifiers; Postgres lower-cases), so match case-insensitively and- // key everything off the real column names.- const normalizedColumnMap = new Map(- cols.map((col) => [col.name.toLowerCase(), col]),- );- const visibleColumns = eventColumns(hasTenants, hasPii)- .map((name) => normalizedColumnMap.get(name)?.name)- .filter((name): name is string => name != null);-- // Override each surfaced column's header. Row data is left untouched so columns stay aligned.- const renamedCols = cols.map((col) => {- const title = titles[col.name.toLowerCase()];- return title ? { ...col, display_name: title } : col;- });-- // Fail closed: if none of the curated columns are present (e.g. an unexpected schema), render- // nothing rather than the default table — the default would surface every column, including- // user_agent, raw ids, and gated PII.- if (visibleColumns.length === 0) {- return null;- }-- // `table.columns` must enumerate EVERY column — the surfaced ones (ordered, enabled) followed- // by the rest (disabled). Columns omitted from this list are otherwise appended to the table.- const visibleColumnNames = new Set<string>(visibleColumns);- const tableColumns: TableColumnOrderSetting[] = [- ...visibleColumns.map((name) => ({ name, enabled: true })),- ...cols- .map((col) => col.name)- .filter((name) => !visibleColumnNames.has(name))- .map((name) => ({ name, enabled: false })),- ];-- return [- {- card: {- display: "table",- dataset_query: jsQuery,- visualization_settings: {- "table.columns": tableColumns,- },- },- data: { ...data.data, cols: renamedCols },- },- ];+ return value ?? ref.current;}/**@@ -146,7 +146,7 @@ export function McpEventsTable({provider,table,groupMembersTable,- ...filters+ ...rest}: Props) {if (!provider || !table || !groupMembersTable) {return null;@@ -156,14 +156,14 @@ export function McpEventsTable({provider={provider}table={table}groupMembersTable={groupMembersTable}- {...filters}+ {...rest}/>);}/**- * Loaded variant of {@link McpEventsTable}: builds the row-level events query, runs it, and- * renders the latest tool calls as a table through the shared chart card.+ * Loaded variant of {@link McpEventsTable}: builds the paginated, sorted row-level query, runs it,+ * and renders the tool calls as a sortable table with pagination controls.*/function McpEventsTableInner({provider,@@ -175,6 +175,11 @@ function McpEventsTableInner({tenantId,hasTenants,hasPii,+ page,+ total,+ onPageChange,+ sortingOptions,+ onSortingOptionsChange,}: InnerProps) {const query = useMemo(() =>@@ -186,25 +191,112 @@ function McpEventsTableInner({userId,groupId,tenantId,- limit: EVENTS_LIMIT,+ sortColumn: sortingOptions.sort_column,+ sortDirection: sortingOptions.sort_direction,}),- [provider, table, groupMembersTable, dateFilter, userId, groupId, tenantId],+ [+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ sortingOptions,+ ],);- const { data, jsQuery, isFetching } = useAdhocBreakoutQuery(query);+ const { data: latestData, isFetching } = useMcpEventsQuery(+ query,+ page,+ EVENTS_PAGE_SIZE,+ );+ // Retain the previous page while the next one loads, so the table doesn't blank out on every+ // page or sort change; we overlay a spinner on the retained rows instead. From here on `data` is+ // simply the warehouse result — the retention is an implementation detail of the hook.+ const data = useRetainedValue(latestData);- const rawSeries = useMemo(- () => buildEventsRawSeries(data, jsQuery, hasTenants, hasPii),- [data, jsQuery, hasTenants, hasPii],+ const columns = useMemo(+ () => eventColumns(hasTenants, hasPii),+ [hasTenants, hasPii],);+ const rows: RowValues[] = data?.data?.rows ?? [];+ // The result columns (`data.data.cols`) are the full, warehouse-ordered set the query returns —+ // not the curated `columns` we render. So we can't reuse the `columns` index; we map each curated+ // column to its position in the result by name. Names are upper- or lower-cased depending on the+ // warehouse (the audit DB is H2, which upper-cases; Postgres lower-cases), so match+ // case-insensitively.+ const columnIndex = useMemo(() => {+ const cols = data?.data?.cols ?? [];+ return new Map(cols.map((col, index) => [col.name.toLowerCase(), index]));+ }, [data]);++ const showEmpty = !isFetching && rows.length === 0;return (- <BreakoutChartCard- rawSeries={rawSeries}- isFetching={isFetching}- display="table"- h={TABLE_HEIGHT}- otherLabel={t`Other`}- />+ <>+ <Card withBorder shadow="none" p={0} pos="relative">+ <LoadingOverlay visible={isFetching} />+ <Box className={S.scroll}>+ <table className={cx(AdminS.ContentTable, S.table)}>+ <thead>+ <tr>+ {columns.map((column) => (+ <SortableColumnHeader+ key={column.key}+ name={column.sort}+ sortingOptions={sortingOptions}+ onSortingOptionsChange={onSortingOptionsChange}+ columnHeaderProps={{ style: { textAlign: column.align } }}+ >+ {column.title}+ </SortableColumnHeader>+ ))}+ </tr>+ </thead>+ <tbody>+ {showEmpty ? (+ <tr>+ <td colSpan={columns.length}>+ <Flex c="text-disabled" justify="center">+ {t`No tool calls found`}+ </Flex>+ </td>+ </tr>+ ) : (+ rows.map((row, rowIndex) => (+ <tr key={rowIndex}>+ {columns.map((column) => {+ const index = columnIndex.get(column.key);+ const value = index != null ? row[index] : null;+ return (+ <td+ key={column.key}+ style={{ textAlign: column.align }}+ >+ {renderCell(column, value)}+ </td>+ );+ })}+ </tr>+ ))+ )}+ </tbody>+ </table>+ </Box>+ </Card>++ <Flex justify="flex-end" mt="md">+ <PaginationControls+ page={page}+ pageSize={EVENTS_PAGE_SIZE}+ itemsLength={rows.length}+ total={total}+ showTotal+ onPreviousPage={() => onPageChange(page - 1)}+ onNextPage={() => onPageChange(page + 1)}+ />+ </Flex>+ </>);}diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpEventsTable.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpEventsTable.unit.spec.tsxindex d48ea27e784..18e626ce9d2 100644--- a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpEventsTable.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpEventsTable.unit.spec.tsx@@ -1,177 +1,62 @@-import type { DatasetQuery } from "metabase-types/api";-import { createMockColumn } from "metabase-types/api/mocks";--import { buildEventsRawSeries } from "./McpEventsTable";--type EventsData = Parameters<typeof buildEventsRawSeries>[0];--const col = (name: string, display_name: string) =>- createMockColumn({ name, display_name });--// Every view column the events query returns, with default humanized headers. Names are-// UPPER-CASE to mirror the H2 audit DB (which upper-cases identifiers) — the curated set is-// matched case-insensitively, so this guards against the all-hidden regression.-const ALL_COLS = [- col("TOOL_CALL_ID", "Tool Call Id"),- col("CREATED_AT", "Created At"),- col("TOOL_NAME", "Tool Name"),- col("STATUS", "Status"),- col("ERROR_TYPE", "Error Type"),- col("ERROR_MESSAGE", "Error Message"),- col("DURATION_MS", "Duration Ms"),- col("MCP_SESSION_ID", "Mcp Session Id"),- col("USER_ID", "User Id"),- col("USER_DISPLAY_NAME", "User Display Name"),- col("GROUP_NAME", "Group Name"),- col("CLIENT_NAME", "Client Name"),- col("CLIENT_DISPLAY_NAME", "Client Display Name"),- col("CLIENT_VERSION", "Client Version"),- col("TENANT_ID", "Tenant Id"),- col("TENANT_NAME", "Tenant Name"),- col("IP_ADDRESS", "Ip Address"),- col("USER_AGENT", "User Agent"),-];--// Unjustified type cast. FIXME-const jsQuery = { database: 1, type: "query", query: {} } as DatasetQuery;--function build(cols = ALL_COLS, hasTenants = true, hasPii = true) {- // Unjustified type cast. FIXME- const data = { data: { cols, rows: [[]] } } as unknown as EventsData;- const series = buildEventsRawSeries(data, jsQuery, hasTenants, hasPii);- if (!series) {- throw new Error("expected a rawSeries");- }- return series[0];-}--/** The card's `table.columns` setting, narrowed past the all-hidden fallback branch. */-function surfacedTableColumns(- cols = ALL_COLS,- hasTenants = true,- hasPii = true,-) {- const { card } = build(cols, hasTenants, hasPii);- if (!("visualization_settings" in card)) {- throw new Error("expected table.columns to be set");- }- // Unjustified type cast. FIXME- return card.visualization_settings["table.columns"] as {- name: string;- enabled: boolean;- }[];-}--const enabledNames = (cols: { name: string; enabled: boolean }[]) =>- cols.filter((c) => c.enabled).map((c) => c.name);--describe("buildEventsRawSeries", () => {- it("returns null without data or query", () => {- expect(buildEventsRawSeries(undefined, jsQuery, true, true)).toBeNull();- expect(- buildEventsRawSeries(- // Unjustified type cast. FIXME- { data: { cols: [], rows: [] } } as unknown as EventsData,- null,- true,- true,- ),- ).toBeNull();- });-- it("fails closed: returns null when no curated column is present (no all-columns leak)", () => {- const foreign = [- col("WEIRD_A", "Weird A"),- col("USER_AGENT", "User Agent"),- ];- // Unjustified type cast. FIXME- const data = {- data: { cols: foreign, rows: [[]] },- } as unknown as EventsData;- expect(buildEventsRawSeries(data, jsQuery, true, true)).toBeNull();- });-- it("surfaces only the curated columns, in order (ID first, Tenant + IP after User)", () => {- expect(enabledNames(surfacedTableColumns())).toEqual([- "TOOL_CALL_ID",- "CREATED_AT",- "TOOL_NAME",- "CLIENT_DISPLAY_NAME",- "CLIENT_VERSION",- "USER_DISPLAY_NAME",- "TENANT_NAME",- "IP_ADDRESS",- "STATUS",- "DURATION_MS",- "ERROR_TYPE",- "ERROR_MESSAGE",+import { eventColumns } from "./McpEventsTable";++const keys = (hasTenants: boolean, hasPii: boolean) =>+ eventColumns(hasTenants, hasPii).map((column) => column.key);++describe("eventColumns", () => {+ it("surfaces the curated columns in display order (ID first, Tenant + IP after User)", () => {+ expect(keys(true, true)).toEqual([+ "tool_call_id",+ "created_at",+ "tool_name",+ "client_display_name",+ "client_version",+ "user_display_name",+ "tenant_name",+ "ip_address",+ "status",+ "duration_ms",+ "error_type",+ "error_message",]);});it("includes the Tenant column only when tenants are enabled", () => {- expect(enabledNames(surfacedTableColumns(ALL_COLS, true, true))).toContain(- "TENANT_NAME",- );- expect(- enabledNames(surfacedTableColumns(ALL_COLS, false, true)),- ).not.toContain("TENANT_NAME");- });-- it("includes the IP column only when PII retention is on", () => {- expect(enabledNames(surfacedTableColumns(ALL_COLS, true, true))).toContain(- "IP_ADDRESS",- );- expect(- enabledNames(surfacedTableColumns(ALL_COLS, true, false)),- ).not.toContain("IP_ADDRESS");+ expect(keys(true, true)).toContain("tenant_name");+ expect(keys(false, true)).not.toContain("tenant_name");});- it("includes the Error message column only when PII retention is on", () => {- // error_message is gated PII (written only when retention is on), like ip_address; error_type- // (non-PII) is always surfaced.- expect(enabledNames(surfacedTableColumns(ALL_COLS, true, true))).toContain(- "ERROR_MESSAGE",+ it("includes the PII columns (IP + error message) only when retention is on", () => {+ expect(keys(true, true)).toEqual(+ expect.arrayContaining(["ip_address", "error_message"]),);- const withoutPii = enabledNames(- surfacedTableColumns(ALL_COLS, true, false),- );- expect(withoutPii).not.toContain("ERROR_MESSAGE");- expect(withoutPii).toContain("ERROR_TYPE");- });-- it("explicitly hides the extraneous columns (incl. raw tenant_id) so they don't leak", () => {- const tableColumns = surfacedTableColumns();- const disabled = tableColumns.filter((c) => !c.enabled).map((c) => c.name);- expect(disabled).toEqual(- expect.arrayContaining([- "MCP_SESSION_ID",- "USER_ID",- "CLIENT_NAME",- "TENANT_ID",- "USER_AGENT",- ]),- );- // every column is accounted for, so nothing is appended unlisted- expect(tableColumns).toHaveLength(ALL_COLS.length);- });-- it("overrides surfaced headers to Sentence case, leaving hidden columns untouched", () => {- const titles = Object.fromEntries(- build().data.cols.map((c) => [c.name, c.display_name]),- );-- expect(titles).toMatchObject({- TOOL_CALL_ID: "ID",- TOOL_NAME: "Tool",- CLIENT_DISPLAY_NAME: "Client",- USER_DISPLAY_NAME: "User",- TENANT_NAME: "Tenant",- IP_ADDRESS: "IP address",- DURATION_MS: "Duration (ms)",- ERROR_TYPE: "Error type",- ERROR_MESSAGE: "Error message",- // an untouched (hidden) column keeps its original header- USER_AGENT: "User Agent",- });+ const withoutPii = keys(true, false);+ expect(withoutPii).not.toContain("ip_address");+ expect(withoutPii).not.toContain("error_message");+ // error_type (non-PII) is always surfaced, unlike error_message+ expect(withoutPii).toContain("error_type");+ });++ it("never surfaces raw/sensitive columns (user_agent, raw ids, client_name)", () => {+ const all = keys(true, true);+ expect(all).not.toContain("user_agent");+ expect(all).not.toContain("client_name");+ expect(all).not.toContain("user_id");+ expect(all).not.toContain("mcp_session_id");+ });++ it("marks the expected columns sortable and leaves the rest static", () => {+ const columns = eventColumns(true, true);+ const sortable = columns.filter((c) => c.sort).map((c) => c.key);+ expect(sortable).toEqual([+ "created_at",+ "tool_name",+ "client_display_name",+ "user_display_name",+ "status",+ "duration_ms",+ ]);+ // the PK and free-text columns are not sortable+ expect(columns.find((c) => c.key === "tool_call_id")?.sort).toBeUndefined();});});diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/hooks/useMcpEventsQuery.ts b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/hooks/useMcpEventsQuery.tsnew file mode 100644index 00000000000..03bd24d071e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/hooks/useMcpEventsQuery.ts@@ -0,0 +1,34 @@+import { useMemo } from "react";++import { skipToken, useGetAdhocQueryQuery } from "metabase/api";+import type { Query } from "metabase-lib";+import * as Lib from "metabase-lib";+import type { Dataset } from "metabase-types/api";++import { paginateEventsQuery } from "../query-utils";++type EventsPageResult = {+ data: Dataset | undefined;+ isFetching: boolean;+};++/**+ * Run the row-level events query for one page. Applies the MBQL `:page` clause (via+ * {@link paginateEventsQuery}) before execution so the backend returns only the requested page.+ * `page` is 0-indexed.+ */+export function useMcpEventsQuery(+ query: Query | null,+ page: number,+ pageSize: number,+): EventsPageResult {+ const jsQuery = useMemo(+ () =>+ query ? Lib.toJsQuery(paginateEventsQuery(query, page, pageSize)) : null,+ [query, page, pageSize],+ );++ const { data, isFetching } = useGetAdhocQueryQuery(jsQuery ?? skipToken);++ return { data, isFetching };+}diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/hooks/useMcpHasData.ts b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/hooks/useMcpHasData.tsindex 7a1570b39cb..4222508bac7 100644--- a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/hooks/useMcpHasData.ts+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/hooks/useMcpHasData.ts@@ -23,6 +23,8 @@ type Result = {isRefetching: boolean;/** Whether the current (resolved) filters match any tool calls. */hasData: boolean;+ /** Total number of tool calls matching the current filters — drives the events pagination. */+ count: number;};/**@@ -83,5 +85,6 @@ export function useMcpHasData({isInitialLoading: !hasLoadedOnce.current,isRefetching: hasLoadedOnce.current && isFetching,hasData: count > 0,+ count,};}diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/query-utils.ts b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/query-utils.tsindex d94634082e4..78386e21c75 100644--- a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/query-utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/query-utils.ts@@ -6,6 +6,7 @@ import type {TableMetadata,} from "metabase-lib";import * as Lib from "metabase-lib";+import type { SortDirection } from "metabase-types/api";import {applyDateFilter,@@ -270,14 +271,41 @@ export function buildTotalCountQuery({return query;}+/** View columns the events table can sort by (server-side). Others render but aren't sortable. */+export const MCP_EVENT_SORT_COLUMNS = [+ "created_at",+ "tool_name",+ "client_display_name",+ "user_display_name",+ "status",+ "duration_ms",+] as const;++export type McpEventSortColumn = (typeof MCP_EVENT_SORT_COLUMNS)[number];++/** Append an order-by on `columnName` in `direction` if it's orderable. No-op if absent. */+function orderByColumn(+ query: Query,+ columnName: string,+ direction: "asc" | "desc",+): Query {+ const col = findColumn(query, columnName, Lib.orderableColumns);+ return col ? Lib.orderBy(query, 0, col, direction) : query;+}+type EventsQueryOpts = McpFilters &McpDataSources & {- limit: number;+ sortColumn?: McpEventSortColumn;+ sortDirection?: SortDirection;};/*** Build the row-level events query for the Events tab: the filtered view with no aggregation,- * ordered by `created_at` descending and capped at `limit` rows.+ * ordered by the chosen sort column (default `created_at` descending), then by the `tool_call_id`+ * primary key as a tiebreaker. The tiebreaker makes the sort a total order — without it,+ * pagination can skip or duplicate rows across page boundaries when the sort column has ties (the+ * DB is free to order ties differently between requests). Pagination is applied separately via+ * {@link paginateEventsQuery}.*/export function buildEventsQuery({provider,@@ -287,7 +315,8 @@ export function buildEventsQuery({userId,groupId,tenantId,- limit,+ sortColumn = "created_at",+ sortDirection = "desc",}: EventsQueryOpts): Query {let query = buildBaseQuery({provider,@@ -299,11 +328,20 @@ export function buildEventsQuery({tenantId,});- const createdAt = findColumn(query, "created_at", Lib.orderableColumns);- if (createdAt) {- query = Lib.orderBy(query, 0, createdAt, "desc");- }+ query = orderByColumn(query, sortColumn, sortDirection);+ query = orderByColumn(query, "tool_call_id", "desc");- query = Lib.limit(query, 0, limit);return query;}++/**+ * Restrict the events query to a single page via the MBQL `:page` clause. `page` is 0-indexed+ * here; metabase-lib's `:page` is 1-indexed, so we add 1.+ */+export function paginateEventsQuery(+ query: Query,+ page: number,+ pageSize: number,+): Query {+ return Lib.withPage(query, 0, { page: page + 1, items: pageSize });+}diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/url-state.ts b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/url-state.tsindex faf9b792208..b355ec8c364 100644--- a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/url-state.ts+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/url-state.ts@@ -3,6 +3,7 @@ import {type UrlStateConfig,getFirstParamValue,} from "metabase/common/hooks/use-url-state";+import type { SortDirection } from "metabase-types/api";import {type FilterUrlState,@@ -10,27 +11,62 @@ import {mergeUrlStateConfig,} from "../metabot-analytics/components/ConversationFilters/url-state";+import { MCP_EVENT_SORT_COLUMNS, type McpEventSortColumn } from "./query-utils";+export type McpTab = "charts" | "events";type McpPageUrlState = {tab: McpTab;+ /** Current page of the row-level events table, 0-indexed. */+ page: number;+ sortColumn: McpEventSortColumn;+ sortDirection: SortDirection;};export type McpUrlState = FilterUrlState & McpPageUrlState;const DEFAULT_TAB: McpTab = "charts";+const DEFAULT_SORT_COLUMN: McpEventSortColumn = "created_at";+const DEFAULT_SORT_DIRECTION: SortDirection = "desc";/** Parse the `tab` query param, defaulting to the charts tab for any unrecognized value. */function parseTab(param: QueryParam): McpTab {return getFirstParamValue(param) === "events" ? "events" : DEFAULT_TAB;}+/** Parse the `page` query param, defaulting to 0 for anything missing or invalid. */+function parsePage(param: QueryParam): number {+ const parsed = parseInt(getFirstParamValue(param) || "0", 10);+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;+}++function parseSortColumn(param: QueryParam): McpEventSortColumn {+ const value = getFirstParamValue(param);+ return (+ MCP_EVENT_SORT_COLUMNS.find((col) => col === value) ?? DEFAULT_SORT_COLUMN+ );+}++function parseSortDirection(param: QueryParam): SortDirection {+ const value = getFirstParamValue(param);+ // we don't want to use `value` directly because it may be an invalid sort direction+ // coming from URL params+ return value === "asc" || value === "desc" ? value : DEFAULT_SORT_DIRECTION;+}+const mcpPageUrlStateConfig: UrlStateConfig<McpPageUrlState> = {parse: (query) => ({tab: parseTab(query.tab),+ page: parsePage(query.page),+ sortColumn: parseSortColumn(query.sortColumn),+ sortDirection: parseSortDirection(query.sortDirection),}),- serialize: ({ tab }) => ({+ serialize: ({ tab, page, sortColumn, sortDirection }) => ({tab: tab === DEFAULT_TAB ? undefined : tab,+ page: page === 0 ? undefined : String(page),+ sortColumn: sortColumn === DEFAULT_SORT_COLUMN ? undefined : sortColumn,+ sortDirection:+ sortDirection === DEFAULT_SORT_DIRECTION ? undefined : sortDirection,}),};diff --git a/frontend/src/metabase-lib/query/index.ts b/frontend/src/metabase-lib/query/index.tsindex edf08ce2b7d..10bb721d190 100644--- a/frontend/src/metabase-lib/query/index.ts+++ b/frontend/src/metabase-lib/query/index.ts@@ -20,6 +20,7 @@ export * from "./measures";export * from "./metrics";export * from "./native";export * from "./order_by";+export * from "./page";export * from "./query";export * from "./segments";export * from "./temporal_bucket";diff --git a/frontend/src/metabase-lib/query/page.ts b/frontend/src/metabase-lib/query/page.tsnew file mode 100644index 00000000000..1ad979c6ebf--- /dev/null+++ b/frontend/src/metabase-lib/query/page.ts@@ -0,0 +1,23 @@+import * as ML from "cljs/metabase.lib.js";++import type { Query } from "./types";++export type Page = {+ /** 1-indexed page number. `{ page: 1, items: 10 }` = rows 1-10. */+ page: number;+ items: number;+};++/** Set (or, with `null`, remove) the `:page` clause on a query stage. Drops `:limit` if present. */+export function withPage(+ query: Query,+ stageIndex: number,+ page: Page | null,+): Query {+ return ML.with_page(query, stageIndex, page);+}++/** Return the `:page` clause on a query stage, or `null` if there is none. */+export function currentPage(query: Query, stageIndex: number): Page | null {+ return ML.current_page(query, stageIndex);+}diff --git a/src/metabase/lib/js.cljs b/src/metabase/lib/js.cljsindex 931bc038a9c..29e1225de90 100644--- a/src/metabase/lib/js.cljs+++ b/src/metabase/lib/js.cljs@@ -441,6 +441,22 @@[a-query stage-number orderable direction](lib.core/order-by a-query stage-number orderable (keyword direction)))+(defn ^:export with-page+ "Set (or, with a nil `a-page`, remove) the `:page` clause on `a-query` at `stage-number`. Returns+ the updated query. `a-page` is a JS object `{page, items}` (`page` is 1-indexed). Drops `:limit`+ if present, since it conflicts with `:page`.++ > **Code health:** Healthy"+ [a-query stage-number a-page]+ (lib.core/with-page a-query stage-number (when a-page (js->clj a-page :keywordize-keys true))))++(defn ^:export current-page+ "Return the `:page` clause on `a-query` at `stage-number` as a JS object, or nil if there is none.++ > **Code health:** Healthy"+ [a-query stage-number]+ (clj->js (lib.core/current-page a-query stage-number)))+(defn ^:export order-bys"Get the `ORDER BY` clauses in `a-query` at `stage-number`, as a JS array of opaque values.