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
import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
import { setupEnterprisePlugins } from "__support__/enterprise";
import {
setupGroupsEndpoint,
setupUsersEndpoints,
} from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { createMockState } from "__support__/state";
import {
mockGetBoundingClientRect,
renderWithProviders,
screen,
waitFor,
within,
} from "__support__/ui";
import { Route, redirect } from "metabase/router";
import * as Urls from "metabase/urls";
import { registerVisualizations } from "metabase/visualizations/register";
import { AUDIT_DB_ID } from "metabase-enterprise/monitor/ai-auditing/mcp-analytics/constants";
import type { Database, Dataset, Field } from "metabase-types/api";
import {
createMockColumn,
createMockDatabase,
createMockDataset,
createMockDatasetData,
createMockField,
createMockGroup,
createMockTable,
createMockTokenFeatures,
createMockUser,
} from "metabase-types/api/mocks";
import { McpAnalyticsSectionLayout } from "./McpAnalyticsSectionLayout";
import { McpEventsPage } from "./McpEventsPage";
import { McpUsagePage } from "./McpUsagePage";
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 TOOL_NAME_FIELD_ID = MCP_TOOL_CALLS_TABLE_ID * 100 + 2;
const BASE_TYPE = {
text: "type/Text",
integer: "type/Integer",
dateTime: "type/DateTimeWithLocalTZ",
} as const;
type FieldSpec = [
type: keyof typeof BASE_TYPE,
name: string,
semantic_type: Field["semantic_type"],
];
/** Build a mock audit-DB table (in `AUDIT_DB_ID`) with the given fields, for the metadata endpoint. */
const buildTable = (id: number, name: string, fields: FieldSpec[]) =>
createMockTable({
id,
db_id: AUDIT_DB_ID,
schema: "public",
name,
display_name: name,
fields: fields.map(([type, fieldName, semantic_type], i) =>
createMockField({
id: id * 100 + i,
table_id: id,
name: fieldName,
display_name: fieldName,
fingerprint: null,
base_type: BASE_TYPE[type],
effective_type: BASE_TYPE[type],
semantic_type,
}),
),
});
const auditDatabase: Database = createMockDatabase({
id: AUDIT_DB_ID,
name: "Audit DB",
tables: [
buildTable(MCP_TOOL_CALLS_TABLE_ID, "v_mcp_tool_calls", [
["text", "tool_call_id", "type/PK"],
["dateTime", "created_at", "type/CreationTimestamp"],
["text", "tool_name", "type/Category"],
["text", "status", "type/Category"],
["integer", "duration_ms", "type/Quantity"],
["integer", "user_id", "type/FK"],
["text", "user_display_name", "type/Name"],
["text", "client_display_name", "type/Category"],
["text", "client_version", "type/Category"],
]),
buildTable(GROUP_MEMBERS_TABLE_ID, "v_group_members", [
["integer", "user_id", "type/Description"],
["integer", "group_id", "type/PK"],
["text", "group_name", "type/Name"],
]),
],
});
// A breakout/count dataset that satisfies both the chart visualizations
// (breakout + aggregation columns) and the events table (named columns).
// Aggregation column first so the page's no-breakout count probe (reads rows[0][0]) sees a
// positive number; the `source` tags still let the breakout charts find the right columns.
const datasetResponse: Dataset = createMockDataset({
data: createMockDatasetData({
rows: [
[12, "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 count/breakout dataset whose scalar count (rows[0][0]) exceeds one page, so the events
// table's pagination controls appear (total > 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({
data: createMockDatasetData({
rows: [[0]],
cols: [
createMockColumn({
source: "aggregation",
name: "count",
display_name: "Count",
}),
],
}),
database_id: AUDIT_DB_ID,
row_count: 1,
running_time: 1,
});
/** Mock the audit-DB metadata, users/groups, and the `/api/dataset` adhoc endpoint (with the given dataset). */
function setupEndpoints(
dataset: Dataset = datasetResponse,
datasetError = false,
) {
fetchMock.get(`path:/api/database/${AUDIT_DB_ID}/metadata`, auditDatabase);
// useAuditTable pulls the table's fields (and its FK targets') from here.
fetchMock.post("path:/api/dataset/query_metadata", {
databases: [auditDatabase],
tables: auditDatabase.tables ?? [],
fields: (auditDatabase.tables ?? []).flatMap((table) => table.fields ?? []),
});
setupUsersEndpoints([createMockUser({ id: 1, first_name: "Ada" })]);
setupGroupsEndpoint([createMockGroup({ id: 1, name: "All Users" })]);
if (datasetError) {
fetchMock.post("path:/api/dataset", {
status: 500,
body: { message: "Audit query failed" },
});
} else {
fetchMock.post("path:/api/dataset", dataset, { name: "dataset" });
}
}
/** Render the MCP analytics section (layout + usage/events sub-routes) with EE plugins + `audit_app`. */
function setup({
dataset,
datasetError,
initialRoute = Urls.monitorAiAuditingMcpUsage(),
}: {
dataset?: Dataset;
datasetError?: boolean;
initialRoute?: string;
} = {}) {
// TreeTable measures column/row sizes via the DOM; jsdom needs a stubbed rect
// for its virtualized rows to render.
mockGetBoundingClientRect({ width: 100, height: 100 });
setupEnterprisePlugins();
setupEndpoints(dataset, datasetError);
return renderWithProviders(
<Route path={Urls.monitorAiAuditingMcp()}>
<Route index element={redirect("usage")} />
<Route element={<McpAnalyticsSectionLayout />}>
<Route path="usage" element={<McpUsagePage />} />
<Route path="events" element={<McpEventsPage />} />
</Route>
</Route>,
{
initialRoute,
withRouter: true,
storeInitialState: createMockState({
settings: mockSettings({
"token-features": createMockTokenFeatures({ audit_app: true }),
"mcp-enabled?": true,
}),
}),
},
);
}
// MBQL 5 order-by clause: [direction, opts, ["field", opts, fieldId]]
type OrderByClause = [string, unknown, [string, unknown, number]];
type EventsMbqlStage = {
page?: { page: number; items: number };
"order-by"?: OrderByClause[];
};
/**
* The first MBQL stage of every adhoc `dataset` request issued so far. The row-level events query
* is the one that carries a `:page` clause on stage 0 (the chart queries don't), so tests filter
* on `.page`. Non-string bodies are skipped.
*/
const eventsDatasetStages = (): EventsMbqlStage[] =>
fetchMock.callHistory
.calls("dataset")
.map((call) => call.options?.body)
.filter((body): body is string => typeof body === "string")
.map((body) => {
// JSON.parse is untyped (`any`); the request body is an MBQL query, so assert its shape.
const query = JSON.parse(body) as { stages?: EventsMbqlStage[] };
return query.stages?.[0];
})
.filter((stage): stage is EventsMbqlStage => stage != null);
describe("McpAnalyticsSectionLayout", () => {
it("redirects from root route to the /usage sub-route", async () => {
const { router } = setup({ initialRoute: Urls.monitorAiAuditingMcp() });
await waitFor(() => {
expect(router?.location.pathname).toBe(Urls.monitorAiAuditingMcpUsage());
});
expect(
await screen.findByRole("heading", { name: "MCP analytics" }),
).toBeInTheDocument();
});
it("redirects from the root route even when the section has no data", async () => {
const { router } = setup({
dataset: emptyDatasetResponse,
initialRoute: Urls.monitorAiAuditingMcp(),
});
await waitFor(() => {
expect(router?.location.pathname).toBe(Urls.monitorAiAuditingMcpUsage());
});
expect(await screen.findByText("No MCP activity")).toBeInTheDocument();
});
it("renders the header, filters, and /usage route by default", async () => {
setup();
expect(
await screen.findByRole("heading", { name: "MCP analytics" }),
).toBeInTheDocument();
expect(
screen.getByTestId("conversation-filters-date-select"),
).toBeInTheDocument();
// Tabs appear only after the initial count query resolves (the page shows a loader first).
expect(
await screen.findByRole("link", { name: "Usage" }),
).toBeInTheDocument();
// Charts run ad-hoc dataset queries through /api/dataset.
await waitFor(() => {
expect(fetchMock.callHistory.called("dataset")).toBe(true);
});
expect(await screen.findByText("Calls by tool")).toBeInTheDocument();
// The errors section renders because the (mocked) error count is > 0.
expect(await screen.findByText("Errors by type")).toBeInTheDocument();
});
it("navigates to the /events route and renders the row-level table", async () => {
const { router } = setup();
await screen.findByRole("heading", { name: "MCP analytics" });
await userEvent.click(
await screen.findByRole("link", { name: "Tool calls" }),
);
expect(router?.location.pathname).toBe(Urls.monitorAiAuditingMcpEvents());
expect(
await screen.findByRole("treegrid", { name: "Tool calls" }),
).toBeInTheDocument();
// curated column header + a cell value from the mocked dataset row
expect(screen.getByText("Tool")).toBeInTheDocument();
expect(await screen.findByText("search_data")).toBeInTheDocument();
});
it("keeps the shared filters visible after navigating between /usage and /events", async () => {
setup();
await screen.findByRole("heading", { name: "MCP analytics" });
expect(
screen.getByTestId("conversation-filters-date-select"),
).toBeInTheDocument();
await userEvent.click(
await screen.findByRole("link", { name: "Tool calls" }),
);
await screen.findByRole("treegrid", { name: "Tool calls" });
expect(
screen.getByTestId("conversation-filters-date-select"),
).toBeInTheDocument();
});
it("keeps the URL filter params when navigating between /usage and /events", async () => {
const { router } = setup({
initialRoute: `${Urls.monitorAiAuditingMcpUsage()}?date=past7days~&user=1`,
});
await screen.findByRole("heading", { name: "MCP analytics" });
await userEvent.click(
await screen.findByRole("link", { name: "Tool calls" }),
);
await waitFor(() => {
expect(router?.location.pathname).toBe(Urls.monitorAiAuditingMcpEvents());
});
const search = router?.location.search ?? "";
expect(search).toContain("date=past7days~");
expect(search).toContain("user=1");
await userEvent.click(await screen.findByRole("link", { name: "Usage" }));
await waitFor(() => {
expect(router?.location.pathname).toBe(Urls.monitorAiAuditingMcpUsage());
});
const backSearch = router?.location.search ?? "";
expect(backSearch).toContain("date=past7days~");
expect(backSearch).toContain("user=1");
});
it("sorts the events table server-side when a column header is clicked", async () => {
setup({ initialRoute: Urls.monitorAiAuditingMcpEvents() });
await screen.findByRole("treegrid", { 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("columnheader", { name: "Tool" }),
);
await waitFor(() => {
const sortedStage = eventsDatasetStages().find(
(stage) => stage.page != null && stage["order-by"]?.[0]?.[0] === "asc",
);
expect(
sortedStage?.["order-by"]?.map(([direction, , [, , fieldId]]) => [
direction,
fieldId,
]),
).toEqual([
["asc", TOOL_NAME_FIELD_ID],
["desc", TOOL_CALL_ID_FIELD_ID],
]);
});
});
it("paginates the events table when there are more matching rows than one page", async () => {
setup({
dataset: multiPageDatasetResponse,
initialRoute: Urls.monitorAiAuditingMcpEvents(),
});
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 = eventsDatasetStages().some(
(stage) => stage.page?.page === 2,
);
expect(requestedPage2).toBe(true);
});
});
it("updates the page URL param immediately when Next is clicked", async () => {
const { router } = setup({
dataset: multiPageDatasetResponse,
initialRoute: Urls.monitorAiAuditingMcpEvents(),
});
const pagination = await screen.findByRole("navigation", {
name: "pagination",
});
await userEvent.click(within(pagination).getByLabelText("Next page"));
expect(router?.location.search).toContain("page=1");
});
it("issues exactly one events query per page change (no redundant refetch)", async () => {
const { router } = setup({
dataset: multiPageDatasetResponse,
initialRoute: Urls.monitorAiAuditingMcpEvents(),
});
await screen.findByRole("treegrid", { name: "Tool calls" });
// Dataset calls for the events query's second page (MBQL `:page` is 1-indexed, so UI page 1).
const page2EventsCalls = () =>
eventsDatasetStages().filter((stage) => stage.page?.page === 2);
await userEvent.click(await screen.findByLabelText("Next page"));
// Wait for the debounced URL update to land — it's the last re-render trigger around a page
// change, and where the old `sortingOptions`-object dependency used to fire redundant refetches.
await waitFor(() => expect(router?.location.search).toContain("page=1"));
// The query memo depends on the primitive sort values, so it stays referentially stable across
// those re-renders: one page change → exactly one events request, not one per render.
expect(page2EventsCalls()).toHaveLength(1);
});
it("orders the events query by a total order (created_at + tool_call_id) for stable paging", async () => {
setup({ initialRoute: Urls.monitorAiAuditingMcpEvents() });
// 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 = eventsDatasetStages().find(
(stage) => stage.page != null,
);
expect(eventsStage?.["order-by"]?.map((clause) => clause[2][2])).toEqual([
CREATED_AT_FIELD_ID,
TOOL_CALL_ID_FIELD_ID,
]);
});
});
it("keeps the header, tabs, and filters visible and shows an empty state in place of the tab content when there is no activity", async () => {
setup({ dataset: emptyDatasetResponse });
expect(
await screen.findByRole("heading", { name: "MCP analytics" }),
).toBeInTheDocument();
expect(await screen.findByText("No MCP activity")).toBeInTheDocument();
// Tabs and filters stay visible even when the view is empty — only the tab content swaps out.
expect(screen.getByRole("link", { name: "Usage" })).toBeInTheDocument();
expect(
screen.getByRole("link", { name: "Tool calls" }),
).toBeInTheDocument();
expect(
screen.getByTestId("conversation-filters-date-select"),
).toBeInTheDocument();
});
it("shows an error instead of spinning forever when the count query fails", async () => {
setup({ datasetError: true });
expect(
await screen.findByRole("heading", { name: "MCP analytics" }),
).toBeInTheDocument();
// Regression: the count query erroring (e.g. a 500) used to leave isInitialLoading
// stuck true forever, so the page never got past the loader.
expect(await screen.findByText("Audit query failed")).toBeInTheDocument();
expect(screen.queryByText("Calls by tool")).not.toBeInTheDocument();
});
});