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
MCP Usage Analytics: storage, instrumentation, audit view, and admin page (MVP) (#76403)
Sébastiene78a7c57e64c
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.ednindex 3a86e98f3e9..d145a55bc91 100644--- a/.clj-kondo/config.edn+++ b/.clj-kondo/config.edn@@ -187,10 +187,17 @@metabase.channel.render.pdf.font/load-fonts!metabase.warehouses.models.database/assert-not-h2!metabase.driver.sql-jdbc.execute/execute-prepared-statement!+ metabase.mcp.usage/record-mcp-session!+ metabase.mcp.usage/record-mcp-session-end!+ metabase.mcp.usage/record-mcp-tool-call!metabase.notification.models/create-notification!metabase.oauth-server.core/reset-provider!metabase.pulse.send/send-pulse!metabase-enterprise.transforms-python.python-runner-test/execute!+ ;; MCP usage tests isolate their rows by unique keys (session id / tool name / duration /+ ;; client version) and clean up only those, so these deletes are safe in parallel.+ metabase-enterprise.mcp.usage-test/cleanup!+ metabase-enterprise.mcp.usage-test/cleanup-calls!;; Workspace isolation functions are safe in parallel tests because they operate on;; isolated, test-specific workspaces and databases that don't affect other testsmetabase-enterprise.workspaces.isolation/destroy-workspace-isolation!diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex b841d0833ea..81390422f1e 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -1227,13 +1227,17 @@:api #{metabase.mcp.apimetabase.mcp.callback-apimetabase.mcp.core- metabase.mcp.init}+ metabase.mcp.init+ metabase.mcp.usage}+ :model-exports #{:model/McpSessionLog+ :model/McpToolCallLog}:uses #{agent-apiapiapp-dbconfigllmoauth-server+ premium-featuresrequestserversession@@ -2308,6 +2312,7 @@configliblib-be+ mcppermissionspremium-featuressearch@@ -3254,6 +3259,18 @@premium-features}:model-imports #{:model/Card :model/Collection :model/Table}}+ enterprise/mcp+ {:team "Metabot"+ :api #{metabase-enterprise.mcp.init}+ :uses #{analytics+ mcp+ metabot+ premium-features+ task+ util}+ :model-imports #{:model/McpSessionLog+ :model/McpToolCallLog}}+enterprise/memoize-monitor{:team "Graphy":api #{metabase-enterprise.memoize-monitor.init}diff --git a/e2e/test/scenarios/metabot/mcp-analytics.cy.spec.ts b/e2e/test/scenarios/metabot/mcp-analytics.cy.spec.tsnew file mode 100644index 00000000000..57372994b66--- /dev/null+++ b/e2e/test/scenarios/metabot/mcp-analytics.cy.spec.ts@@ -0,0 +1,108 @@+const { H } = cy;++import { ADMIN_USER_ID } from "e2e/support/cypress_sample_instance_data";++const MCP_ANALYTICS_PATH = "/admin/metabot/usage-auditing/mcp";+const SEED_TOOL_NAME = "e2e_smoke_tool";+const SEED_ERROR_TOOL = "e2e_error_tool";+// error_code -32602 is JSON-RPC "Invalid params", which the view maps to error_type "Invalid params".+const SEED_ERROR_CODE = -32602;+const SEED_ERROR_TYPE = "Invalid params";+const SEED_ERROR_MESSAGE = "missing required argument: query";++type SeedMcpToolCallResponse = { session_id: string; tool_name: string };++type SeedMcpToolCallBody = {+ tool_name?: string;+ status?: string;+ error_code?: number;+ error_message?: string;+};++function seedMcpToolCall(+ body: SeedMcpToolCallBody = {},+): Cypress.Chainable<Cypress.Response<SeedMcpToolCallResponse>> {+ return cy.request<SeedMcpToolCallResponse>(+ "POST",+ "/api/testing/mcp/seed-tool-call",+ { user_id: ADMIN_USER_ID, tool_name: SEED_TOOL_NAME, ...body },+ );+}++function visitMcpAnalyticsPage(): void {+ cy.intercept("GET", "/api/database/13371337/metadata*").as("auditMetadata");+ cy.intercept("POST", "/api/dataset").as("dataset");++ cy.visit(MCP_ANALYTICS_PATH);+ cy.wait("@auditMetadata");+}++describe("scenarios > metabot > mcp analytics", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ });++ it("shows the audit-app nav item and a seeded tool call on the page", () => {+ H.activateToken("pro-self-hosted");+ seedMcpToolCall();++ visitMcpAnalyticsPage();++ cy.log("Nav item lives under the Auditing folder");+ cy.findByRole("link", { name: "MCP analytics" }).should("be.visible");++ cy.log("The page renders with the seeded data (not the empty state)");+ H.main().within(() => {+ cy.findByRole("heading", { name: "MCP analytics" }).should("be.visible");+ cy.findByText("No MCP activity").should("not.exist");+ });++ cy.log("The seeded tool call shows up in the Events table");+ H.main().findByRole("tab", { name: "Tool calls" }).click();+ cy.wait("@dataset");+ H.main().findByText(SEED_TOOL_NAME).should("be.visible");+ });++ it("surfaces a failed tool call's error type and message", () => {+ H.activateToken("pro-self-hosted");+ // error_message is gated PII — the backend only records/shows it when retention is on.+ H.updateSetting("analytics-pii-retention-enabled", true);+ seedMcpToolCall({+ tool_name: SEED_ERROR_TOOL,+ status: "error",+ error_code: SEED_ERROR_CODE,+ error_message: SEED_ERROR_MESSAGE,+ });++ visitMcpAnalyticsPage();++ cy.log(+ "The Usage tab surfaces an Errors section once there are failed calls",+ );+ H.main()+ .findByRole("heading", { name: "Errors" })+ .scrollIntoView()+ .should("be.visible");++ cy.log(+ "The Tool calls table shows the derived error type and gated message",+ );+ H.main().findByRole("tab", { name: "Tool calls" }).click();+ cy.wait("@dataset");+ H.main().within(() => {+ cy.findByText(SEED_ERROR_TOOL).scrollIntoView().should("be.visible");+ cy.findByText(SEED_ERROR_TYPE).scrollIntoView().should("be.visible");+ cy.findByText(SEED_ERROR_MESSAGE).scrollIntoView().should("be.visible");+ });+ });++ it("hides the nav item and the page without the audit-app feature", () => {+ cy.visit(MCP_ANALYTICS_PATH);++ cy.log("The MCP analytics route is not registered without audit_app");+ cy.findByLabelText("error page").should("be.visible");+ cy.findByRole("heading", { name: "MCP analytics" }).should("not.exist");+ cy.findByRole("link", { name: "MCP analytics" }).should("not.exist");+ });+});diff --git a/enterprise/backend/src/metabase_enterprise/audit_app/permissions.clj b/enterprise/backend/src/metabase_enterprise/audit_app/permissions.cljindex 20a8f905497..197eecc4f4c 100644--- a/enterprise/backend/src/metabase_enterprise/audit_app/permissions.clj+++ b/enterprise/backend/src/metabase_enterprise/audit_app/permissions.clj@@ -32,7 +32,8 @@"v_view_log""v_metabot_conversations""v_metabot_messages"- "v_ai_usage_log"})+ "v_ai_usage_log"+ "v_mcp_tool_calls"})(defenterprise check-audit-db-permissions"Performs a number of permission checks to ensure that a query on the Audit database can be run.diff --git a/enterprise/backend/src/metabase_enterprise/audit_app/task/truncate_audit_tables.clj b/enterprise/backend/src/metabase_enterprise/audit_app/task/truncate_audit_tables.cljindex 6804136a540..b9ccc20a107 100644--- a/enterprise/backend/src/metabase_enterprise/audit_app/task/truncate_audit_tables.clj+++ b/enterprise/backend/src/metabase_enterprise/audit_app/task/truncate_audit_tables.clj@@ -4,7 +4,11 @@(defenterprise audit-models-to-truncate"List of models to truncate, as well as the name of the column containing the row's timestamp. EE version adds- `audit_log` and `view_log` truncation"+ `audit_log` and `view_log` truncation.++ Note: the MCP analytics logs are intentionally *not* here — they're collected on every EE instance+ (not just `audit-app`), so their retention runs on every EE instance via the standalone+ `metabase-enterprise.mcp.task.mcp-usage-trimmer` (keyed on `ai-usage-max-retention-days`).":feature :audit-app[][{:model :model/QueryExecution :timestamp-col :started_at}diff --git a/enterprise/backend/src/metabase_enterprise/core/init.clj b/enterprise/backend/src/metabase_enterprise/core/init.cljindex 9e20921e059..48a421ba076 100644--- a/enterprise/backend/src/metabase_enterprise/core/init.clj+++ b/enterprise/backend/src/metabase_enterprise/core/init.clj@@ -16,6 +16,7 @@[metabase-enterprise.dependencies.init][metabase-enterprise.entity-retrieval.init][metabase-enterprise.gsheets.init]+ [metabase-enterprise.mcp.init][metabase-enterprise.memoize-monitor.init][metabase-enterprise.metabot.init][metabase-enterprise.remote-sync.init]diff --git a/enterprise/backend/src/metabase_enterprise/mcp/init.clj b/enterprise/backend/src/metabase_enterprise/mcp/init.cljnew file mode 100644index 00000000000..d3bd3c298ca--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/mcp/init.clj@@ -0,0 +1,5 @@+(ns metabase-enterprise.mcp.init+ "Startup wiring for the enterprise MCP module — loads the scheduled MCP usage trimmer so its+ `task/init!` runs on boot (on every EE instance, matching where MCP usage is collected)."+ (:require+ [metabase-enterprise.mcp.task.mcp-usage-trimmer]))diff --git a/enterprise/backend/src/metabase_enterprise/mcp/task/mcp_usage_trimmer.clj b/enterprise/backend/src/metabase_enterprise/mcp/task/mcp_usage_trimmer.cljnew file mode 100644index 00000000000..7aaab831b86--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/mcp/task/mcp_usage_trimmer.clj@@ -0,0 +1,54 @@+(ns metabase-enterprise.mcp.task.mcp-usage-trimmer+ "Scheduled task to delete `mcp_tool_call_log` / `mcp_session_log` rows older than the configured+ `ai-usage-max-retention-days`. Mirrors the Metabot `ai-usage-trimmer`: MCP usage is collected on+ every EE instance, so its retention runs on every EE instance too — deliberately *not*+ audit-app-gated (which would let data grow unbounded on instances that collect but can't view it)."+ (:require+ [clojurewerkz.quartzite.jobs :as jobs]+ [clojurewerkz.quartzite.schedule.cron :as cron]+ [clojurewerkz.quartzite.triggers :as triggers]+ [java-time.api :as t]+ [metabase.metabot.settings :as metabot.settings]+ [metabase.task.core :as task]+ [metabase.util.log :as log]+ [toucan2.core :as t2])+ (:import+ (org.quartz DisallowConcurrentExecution)))++(set! *warn-on-reflection* true)++(def ^:private trimmer-job-key (jobs/key "metabase.task.mcp.usage-trimmer.job"))+(def ^:private trimmer-trigger-key (triggers/key "metabase.task.mcp.usage-trimmer.trigger"))++(defn- trim-old-mcp-usage-data!+ []+ (let [retention-days (metabot.settings/ai-usage-max-retention-days)]+ (if (nil? retention-days)+ (log/info "Skipping MCP usage log cleanup; ai-usage-max-retention-days is 0 (infinite retention).")+ (let [cutoff (t/minus (t/offset-date-time) (t/days (long retention-days)))]+ (log/infof "Trimming MCP usage log rows older than %d days." (long retention-days))+ ;; Each table is pruned independently by its own created_at. Tool-call rows are+ ;; self-contained (identity is denormalized onto them, no session link), so pruning a+ ;; session row can never orphan a tool call.+ (let [calls (t2/delete! :model/McpToolCallLog {:where [:< :created_at cutoff]})+ sessions (t2/delete! :model/McpSessionLog {:where [:< :created_at cutoff]})]+ (log/infof "MCP usage log cleanup complete. Deleted %d tool-call and %d session rows."+ (or calls 0) (or sessions 0)))))))++(task/defjob ^{DisallowConcurrentExecution true+ :doc "Delete old MCP usage log rows"}+ McpUsageTrimmer [_ctx]+ (trim-old-mcp-usage-data!))++(defmethod task/init! ::McpUsageTrimmer+ [_]+ (let [job (jobs/build+ (jobs/of-type McpUsageTrimmer)+ (jobs/with-identity trimmer-job-key))+ trigger (triggers/build+ (triggers/with-identity trimmer-trigger-key)+ (triggers/start-now)+ (triggers/with-schedule+ ;; daily at 23:19:41 (offset from the ai-usage trimmer's 23:14:37)+ (cron/cron-schedule "41 19 23 * * ?")))]+ (task/schedule-task! job trigger)))diff --git a/enterprise/backend/src/metabase_enterprise/mcp/usage.clj b/enterprise/backend/src/metabase_enterprise/mcp/usage.cljnew file mode 100644index 00000000000..2a2ff43726e--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/mcp/usage.clj@@ -0,0 +1,135 @@+(ns metabase-enterprise.mcp.usage+ "Enterprise implementation of MCP usage logging.++ Writes the session row at `initialize`, stamps `ended_at` at teardown, and writes one+ lean tool-call row per `tools/call`. Collection runs on every EE instance (`:feature+ :none`), mirroring `ai_usage_log`; PII columns are populated only when+ `analytics-pii-retention-enabled` is on (itself `:audit-app`-gated). Every write is+ best-effort: a failure is logged and swallowed so logging never fails the MCP request and+ adds negligible latency."+ (:require+ [metabase.analytics.core :as analytics]+ [metabase.analytics.settings :as analytics.settings]+ [metabase.mcp.usage :as mcp.usage]+ [metabase.premium-features.core :refer [defenterprise]]+ [metabase.util.log :as log]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(def ^:private error-message-max-length+ "Cap on the stored error_message length (gated PII), mirroring query_execution.parameters."+ 1024)++(def ^:private tool-name-max-length+ "Cap on the stored tool_name length, matching the `mcp_tool_call_log.tool_name` column width."+ 255)++(def ^:private client-version-max-length+ "Cap on the stored client_version length, matching the `client_version` column width."+ 255)++(def ^:private unknown-tool-name+ "Recorded when a `tools/call` arrives with no usable tool name (blank/missing — e.g. a malformed+ request that returns \"Unknown tool\"). Keeps the analytics row rather than dropping it to a+ swallowed NOT NULL violation."+ "unknown")++(defn- truncate+ "Truncate string `s` to at most `n` characters; nil-safe."+ [s n]+ (when s+ (let [s (str s)]+ (subs s 0 (min (count s) n)))))++(defenterprise record-mcp-session!+ "EE: upsert the `mcp_session_log` row at `initialize`. Identity + PII are set once — an+ existing row is left untouched (mirrors `metabot_conversation`). PII columns are populated+ only when `analytics-pii-retention-enabled` is on."+ :feature :none+ [{:keys [session-id user-id tenant-id client-info user-agent ip-address]}]+ (try+ (when (and session-id+ ;; mcp-remote fires a throwaway transport-probe handshake; never record it+ (not (mcp.usage/proxy-probe? (:name client-info)))+ (not (t2/exists? :model/McpSessionLog :id session-id)))+ (let [;; `pii-fields-from` returns the gated PII columns only when+ ;; `analytics-pii-retention-enabled` is on (nil otherwise). Allowlist the two columns+ ;; `mcp_session_log` actually has — selecting explicitly (rather than dissoc-ing the+ ;; unwanted ones) means a new field on the shared helper can't silently start+ ;; persisting here without a deliberate change.+ pii (select-keys (analytics/pii-fields-from {:user-agent user-agent+ :ip-address ip-address})+ [:user_agent :ip_address])]+ (t2/insert! :model/McpSessionLog+ (merge {:id session-id+ :user_id user-id+ :tenant_id tenant-id+ :client_name (mcp.usage/detect-client (:name client-info))+ :client_version (truncate (:version client-info) client-version-max-length)}+ pii))))+ (catch Throwable e+ (log/warn e "Failed to record MCP session"))))++(defenterprise record-mcp-session-end!+ "EE: stamp `ended_at` on the session row at teardown. Best-effort; the row may be absent+ (e.g. the session was opened before the feature was enabled)."+ :feature :none+ [session-id]+ (try+ (when session-id+ (t2/update! :model/McpSessionLog :id session-id {:ended_at :%now}))+ (catch Throwable e+ (log/warn e "Failed to record MCP session end"))))++(defn- resolve-client-identity+ "Client identity for a tool-call row, denormalized so `v_mcp_tool_calls` needs no session join.+ Resolved in priority order (matches the upcoming MCP RC, which drops sessions):+ 1. `client-info` from the call's `_meta[\"io.modelcontextprotocol/clientInfo\"]` (RC clients);+ 2. the identity stored on the session row at `initialize` (old-protocol clients);+ 3. nothing.+ Returns `{:client_name <canonical> :client_version <version>}` (either key may be nil)."+ [client-info session-id]+ (cond+ client-info+ {:client_name (mcp.usage/detect-client (:name client-info))+ :client_version (truncate (:version client-info) client-version-max-length)}++ session-id+ (t2/select-one [:model/McpSessionLog :client_name :client_version] :id session-id)++ :else nil))++(defenterprise record-mcp-tool-call!+ "EE: write one `mcp_tool_call_log` row per `tools/call`, with client identity + PII denormalized+ onto the row (resolved at call time via [[resolve-client-identity]]) so `v_mcp_tool_calls` needs+ no join to `mcp_session_log`. `error_code` (JSON-RPC code) is non-PII and always recorded on+ failure; `error_message` and the `ip_address`/`user_agent`/`sanitized_user_agent` columns are+ PII — stored only when `analytics-pii-retention-enabled` is on. `tool-name` is truncated and+ falls back to a sentinel when blank/missing, so a malformed call still records a row."+ :feature :none+ [{:keys [tool-name user-id session-id status duration-ms error-code error-message+ client-info tenant-id user-agent ip-address]}]+ (try+ (let [{:keys [client_name client_version]} (resolve-client-identity client-info session-id)+ ;; `pii-fields-from` returns the gated PII columns only when retention is on (nil+ ;; otherwise). Allowlist the three the tool-call row has, so a new field on the shared+ ;; helper can't silently start persisting here without a deliberate change.+ pii (select-keys (analytics/pii-fields-from {:user-agent user-agent+ :ip-address ip-address})+ [:user_agent :ip_address :sanitized_user_agent])]+ (t2/insert! :model/McpToolCallLog+ (merge {:tool_name (or (not-empty (truncate tool-name tool-name-max-length))+ unknown-tool-name)+ :user_id user-id+ :client_name client_name+ :client_version client_version+ :tenant_id tenant-id+ :status status+ :duration_ms duration-ms+ :error_code error-code+ :error_message (when (analytics.settings/analytics-pii-retention-enabled)+ (truncate error-message error-message-max-length))}+ pii)))+ (catch Throwable e+ (log/warn e "Failed to record MCP tool call"))))diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.cljindex 1713be9c8d7..b7cf3f2d4cd 100644--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj@@ -89,6 +89,8 @@"ImplicitAction""LoginHistory""McpQueryHandle"+ "McpSessionLog"+ "McpToolCallLog""MetabotConversation""MetabotFeedback""MetabotGroupLimit"diff --git a/enterprise/backend/test/metabase_enterprise/mcp/task/mcp_usage_trimmer_test.clj b/enterprise/backend/test/metabase_enterprise/mcp/task/mcp_usage_trimmer_test.cljnew file mode 100644index 00000000000..e41eb9b7de4--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/mcp/task/mcp_usage_trimmer_test.clj@@ -0,0 +1,45 @@+(ns metabase-enterprise.mcp.task.mcp-usage-trimmer-test+ (:require+ [clojure.test :refer :all]+ [java-time.api :as t]+ [metabase-enterprise.mcp.task.mcp-usage-trimmer :as mcp-usage-trimmer]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [toucan2.core :as t2]))++(use-fixtures :once (fixtures/initialize :db))++(set! *warn-on-reflection* true)++;; NOTE: these tests deliberately do NOT wrap in `mt/with-premium-features #{:audit-app}` — MCP usage+;; is collected on every EE instance, so its trimmer must run regardless of the audit-app feature.++(deftest trims-rows-older-than-custom-retention-test+ (testing "with retention set to 30 days, session + tool-call rows older than 30 days are deleted"+ (mt/with-temp+ [:model/McpSessionLog {s-recent :id} {:id "sess-recent" :created_at (t/offset-date-time)}+ :model/McpSessionLog {s-old :id} {:id "sess-old" :created_at (t/minus (t/offset-date-time) (t/days 200))}+ :model/McpToolCallLog {tc-recent :id} {:tool_name "query" :created_at (t/offset-date-time)}+ :model/McpToolCallLog {tc-boundary :id} {:tool_name "query" :created_at (t/minus (t/offset-date-time) (t/days 31))}+ :model/McpToolCallLog {tc-old :id} {:tool_name "query" :created_at (t/minus (t/offset-date-time) (t/days 200))}]+ (mt/with-temp-env-var-value! [mb-ai-usage-max-retention-days 30]+ (#'mcp-usage-trimmer/trim-old-mcp-usage-data!)+ (is (= #{s-recent}+ (t2/select-fn-set :id :model/McpSessionLog {:where [:in :id [s-recent s-old]]}))+ "old session rows are deleted, recent kept")+ (is (= #{tc-recent}+ (t2/select-fn-set :id :model/McpToolCallLog {:where [:in :id [tc-recent tc-boundary tc-old]]}))+ "tool-call rows older than the cutoff are deleted, recent kept")))))++(deftest skips-deletion-when-retention-is-infinite-test+ (testing "when retention is set to 0 (infinite), no rows are deleted"+ (mt/with-temp+ [:model/McpSessionLog {s-recent :id} {:id "sess-recent-inf" :created_at (t/offset-date-time)}+ :model/McpSessionLog {s-old :id} {:id "sess-old-inf" :created_at (t/minus (t/offset-date-time) (t/years 5))}+ :model/McpToolCallLog {tc-old :id} {:tool_name "query" :created_at (t/minus (t/offset-date-time) (t/years 5))}]+ (mt/with-temp-env-var-value! [mb-ai-usage-max-retention-days 0]+ (#'mcp-usage-trimmer/trim-old-mcp-usage-data!)+ (is (= #{s-recent s-old}+ (t2/select-fn-set :id :model/McpSessionLog {:where [:in :id [s-recent s-old]]})))+ (is (= #{tc-old}+ (t2/select-fn-set :id :model/McpToolCallLog {:where [:in :id [tc-old]]})))))))diff --git a/enterprise/backend/test/metabase_enterprise/mcp/usage_test.clj b/enterprise/backend/test/metabase_enterprise/mcp/usage_test.cljnew file mode 100644index 00000000000..4ce44824779--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/mcp/usage_test.clj@@ -0,0 +1,390 @@+(ns metabase-enterprise.mcp.usage-test+ "Tests for the three MCP usage write points (session at `initialize`, `ended_at` at+ teardown, tool-call per `tools/call`). Exercises the `defenterprise` dispatch via the OSS+ entry points in `metabase.mcp.usage`. Collection runs on every EE instance (`:feature+ :none`); PII is gated by `analytics-pii-retention-enabled` (itself `:audit-app`-gated)."+ (:require+ [clojure.test :refer [deftest is testing use-fixtures]]+ [metabase.mcp.tools :as mcp.tools]+ [metabase.mcp.usage :as usage]+ [metabase.test :as mt]+ [metabase.test.data.users :as test.users]+ [metabase.test.fixtures :as fixtures]+ [metabase.test.http-client :as client]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(use-fixtures :once (fixtures/initialize :db :test-users))++(defn- cleanup! [session-id]+ (t2/delete! :model/McpSessionLog :id session-id))++(defn- cleanup-calls!+ "Tool-call rows no longer carry a session id, so tests isolate + clean up their rows by a unique+ column value (tool name / duration / client version). Whitelisted for `^:parallel` use."+ [& conditions]+ (apply t2/delete! :model/McpToolCallLog conditions))++;;; ----------------------------------------- detect-client (pure) ------------------------------------------++(deftest ^:parallel detect-client-test+ (testing "handshake clientInfo.name maps to a canonical client key"+ (is (= "claude" (usage/detect-client "claude-ai")))+ (is (= "claude" (usage/detect-client "Claude")))+ (is (= "chatgpt" (usage/detect-client "ChatGPT")))+ (is (= "chatgpt" (usage/detect-client "openai-mcp")))+ (is (= "cursor-vscode" (usage/detect-client "Cursor")))+ (is (= "vscode" (usage/detect-client "Visual Studio Code")))+ (is (= "vscode" (usage/detect-client "Visual Studio Code - Insiders")))+ (is (= "zed" (usage/detect-client "Zed"))))+ (testing "the mcp-remote wrapper is stripped before classifying"+ (is (= "zed" (usage/detect-client "Zed (via mcp-remote 0.1.37)")))+ (is (= "claude" (usage/detect-client "Claude Code (via mcp-remote 0.1.37)"))))+ (testing "the fuzzy fallback classifies spacing/punctuation variants and generic proxy wrappers"+ (is (= "vscode" (usage/detect-client "VS Code")))+ (is (= "vscode" (usage/detect-client "VSCode")))+ (is (= "chatgpt" (usage/detect-client "chat-gpt")))+ (is (= "chatgpt" (usage/detect-client "chatgpt-5 (via foo proxy v6)")))+ (is (= "claude" (usage/detect-client "Claude (via some-other-proxy 1.0)"))))+ (testing "unknown / missing names fall back to \"other\""+ (is (= "other" (usage/detect-client "Some Random Client")))+ (is (= "other" (usage/detect-client "")))+ (is (= "other" (usage/detect-client nil))))+ (testing "every value produced is a supported key or the \"other\" fallback"+ (doseq [n ["claude-ai" "ChatGPT" "Cursor" "Visual Studio Code" "Zed" "whatever" nil]]+ (is (contains? (conj usage/supported-client-keys "other")+ (usage/detect-client n))))))++(deftest ^:parallel proxy-probe?-test+ (testing "mcp-remote's throwaway transport-probe handshake is recognized (case-insensitive)"+ (is (true? (usage/proxy-probe? "mcp-remote-fallback-test")))+ (is (true? (usage/proxy-probe? "MCP-Remote-Fallback-Test"))))+ (testing "real clients (including mcp-remote-wrapped ones) are not probes"+ (is (not (usage/proxy-probe? "Zed (via mcp-remote 0.1.37)")))+ (is (not (usage/proxy-probe? "claude-ai")))+ (is (not (usage/proxy-probe? nil)))))++;;; ------------------------------------------- record-mcp-session! -----------------------------------------++(deftest record-mcp-session!-writes-row-test+ (mt/with-premium-features #{:audit-app}+ (mt/with-temporary-setting-values [analytics-pii-retention-enabled true]+ (let [sid (str "test-session-" (mt/random-name))]+ (try+ (usage/record-mcp-session!+ {:session-id sid+ :user-id (mt/user->id :rasta)+ :tenant-id nil+ :client-info {:name "claude-ai" :version "1.2.3"}+ :user-agent "Mozilla/5.0 (Macintosh) Chrome/120"+ :ip-address "203.0.113.7"})+ (let [row (t2/select-one :model/McpSessionLog :id sid)]+ (testing "non-PII identity columns"+ (is (= "claude" (:client_name row)))+ (is (= "1.2.3" (:client_version row)))+ (is (= (mt/user->id :rasta) (:user_id row))))+ (testing "PII columns are populated when retention is on"+ (is (= "203.0.113.7" (:ip_address row)))+ (is (some? (:user_agent row))))+ (testing "ended_at is not stamped at initialize"+ (is (nil? (:ended_at row)))))+ (finally (cleanup! sid)))))))++(deftest record-mcp-session!-pii-gate-off-test+ (testing "with retention off, PII columns are null but non-PII fields are kept"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temporary-setting-values [analytics-pii-retention-enabled false]+ (let [sid (str "test-session-" (mt/random-name))]+ (try+ (usage/record-mcp-session!+ {:session-id sid+ :user-id (mt/user->id :rasta)+ :tenant-id 7+ :client-info {:name "chatgpt" :version "9"}+ :user-agent "UA"+ :ip-address "1.2.3.4"})+ (let [row (t2/select-one :model/McpSessionLog :id sid)]+ (is (= "chatgpt" (:client_name row)))+ (is (= (mt/user->id :rasta) (:user_id row)))+ (is (= 7 (:tenant_id row)))+ (testing "gated PII columns are null"+ (is (nil? (:ip_address row)))+ (is (nil? (:user_agent row)))))+ (finally (cleanup! sid))))))))++(deftest ^:parallel record-mcp-session!-identity-set-once-test+ (testing "a second initialize for the same session id never overwrites identity/PII"+ (mt/with-premium-features #{:audit-app}+ (let [sid (str "test-session-" (mt/random-name))]+ (try+ (usage/record-mcp-session!+ {:session-id sid :user-id (mt/user->id :rasta) :client-info {:name "claude-ai" :version "1"}})+ (usage/record-mcp-session!+ {:session-id sid :user-id (mt/user->id :crowberto) :client-info {:name "chatgpt" :version "2"}})+ (let [row (t2/select-one :model/McpSessionLog :id sid)]+ (is (= 1 (t2/count :model/McpSessionLog :id sid)))+ (is (= "claude" (:client_name row)))+ (is (= "1" (:client_version row)))+ (is (= (mt/user->id :rasta) (:user_id row))))+ (finally (cleanup! sid)))))))++(deftest ^:parallel record-mcp-session!-ignores-mcp-remote-probe-test+ (testing "mcp-remote's fallback-probe handshake is never recorded as a session"+ (mt/with-premium-features #{:audit-app}+ (let [sid (str "test-probe-" (mt/random-name))]+ (try+ (usage/record-mcp-session!+ {:session-id sid :user-id (mt/user->id :rasta)+ :client-info {:name "mcp-remote-fallback-test" :version "0.0.0"}})+ (is (nil? (t2/select-one :model/McpSessionLog :id sid)))+ (finally (cleanup! sid)))))))++;;; ----------------------------------------- record-mcp-session-end! ---------------------------------------++(deftest ^:parallel record-mcp-session-end!-stamps-ended-at-test+ (mt/with-premium-features #{:audit-app}+ (let [sid (str "test-session-" (mt/random-name))]+ (try+ (usage/record-mcp-session! {:session-id sid :user-id (mt/user->id :rasta) :client-info {:name "claude"}})+ (is (nil? (:ended_at (t2/select-one :model/McpSessionLog :id sid))))+ (usage/record-mcp-session-end! sid)+ (is (some? (:ended_at (t2/select-one :model/McpSessionLog :id sid))))+ (finally (cleanup! sid)))))+ (testing "stamping a missing session row is a harmless no-op (zero rows updated, no throw)"+ (mt/with-premium-features #{:audit-app}+ (is (= 0 (usage/record-mcp-session-end! (str "absent-" (mt/random-name))))))))++;;; ------------------------------------------ record-mcp-tool-call! ----------------------------------------++(deftest ^:parallel record-mcp-tool-call!-writes-row-test+ (mt/with-premium-features #{:audit-app}+ (let [sid (str "test-session-" (mt/random-name))+ tool (str "query-" (mt/random-name))]+ (try+ (usage/record-mcp-session! {:session-id sid :user-id (mt/user->id :rasta) :client-info {:name "claude"}})+ (usage/record-mcp-tool-call! {:tool-name tool :user-id (mt/user->id :rasta)+ :session-id sid :status "success" :duration-ms 12})+ (let [row (t2/select-one :model/McpToolCallLog :tool_name tool)]+ (is (= tool (:tool_name row)))+ (is (= "success" (:status row)))+ (is (= 12 (:duration_ms row)))+ (is (= (mt/user->id :rasta) (:user_id row)))+ (testing "client identity is denormalized onto the row (here from the session)"+ (is (= "claude" (:client_name row)))))+ (finally (cleanup-calls! :tool_name tool) (cleanup! sid))))))++(deftest ^:parallel record-mcp-tool-call!-client-identity-test+ (testing "client identity is resolved in priority order: _meta clientInfo -> session -> nothing"+ (mt/with-premium-features #{:audit-app}+ (testing "1. _meta clientInfo wins, and its raw name is canonicalized"+ (let [tool (str "meta-" (mt/random-name))]+ (try+ (usage/record-mcp-tool-call! {:tool-name tool :user-id (mt/user->id :rasta)+ :status "success" :duration-ms 1+ :client-info {:name "ChatGPT" :version "5.0"}})+ (let [row (t2/select-one :model/McpToolCallLog :tool_name tool)]+ (is (= "chatgpt" (:client_name row)))+ (is (= "5.0" (:client_version row))))+ (finally (cleanup-calls! :tool_name tool)))))+ (testing "2. falls back to the session's stored identity when the call carries no _meta"+ (let [sid (str "identity-session-" (mt/random-name))+ tool (str "session-" (mt/random-name))]+ (try+ (usage/record-mcp-session! {:session-id sid :user-id (mt/user->id :rasta)+ :client-info {:name "claude-ai" :version "1.2"}})+ (usage/record-mcp-tool-call! {:tool-name tool :user-id (mt/user->id :rasta)+ :session-id sid :status "success" :duration-ms 1})+ (let [row (t2/select-one :model/McpToolCallLog :tool_name tool)]+ (is (= "claude" (:client_name row)))+ (is (= "1.2" (:client_version row))))+ (finally (cleanup-calls! :tool_name tool) (cleanup! sid)))))+ (testing "3. neither _meta nor a session row -> nil client identity (row still logs)"+ (let [tool (str "none-" (mt/random-name))]+ (try+ (usage/record-mcp-tool-call! {:tool-name tool :user-id (mt/user->id :rasta)+ :session-id (str "absent-" (mt/random-name))+ :status "success" :duration-ms 1})+ (let [row (t2/select-one :model/McpToolCallLog :tool_name tool)]+ (is (some? row))+ (is (nil? (:client_name row)))+ (is (nil? (:client_version row))))+ (finally (cleanup-calls! :tool_name tool))))))))++(deftest record-mcp-tool-call!-pii-gate-test+ (testing "ip/user-agent are denormalized onto the row only when retention is on"+ (mt/with-premium-features #{:audit-app}+ (testing "retention on: PII columns populated"+ (mt/with-temporary-setting-values [analytics-pii-retention-enabled true]+ (let [tool (str "pii-on-" (mt/random-name))]+ (try+ (usage/record-mcp-tool-call! {:tool-name tool :user-id (mt/user->id :rasta)+ :status "success" :duration-ms 1+ :ip-address "203.0.113.7"+ :user-agent "Claude/1.0 (macOS)"})+ (let [row (t2/select-one :model/McpToolCallLog :tool_name tool)]+ (is (= "203.0.113.7" (:ip_address row)))+ (is (some? (:user_agent row)))+ (is (some? (:sanitized_user_agent row))))+ (finally (cleanup-calls! :tool_name tool))))))+ (testing "retention off: PII columns stay null"+ (mt/with-temporary-setting-values [analytics-pii-retention-enabled false]+ (let [tool (str "pii-off-" (mt/random-name))]+ (try+ (usage/record-mcp-tool-call! {:tool-name tool :user-id (mt/user->id :rasta)+ :status "success" :duration-ms 1+ :ip-address "203.0.113.7"+ :user-agent "Claude/1.0 (macOS)"})+ (let [row (t2/select-one :model/McpToolCallLog :tool_name tool)]+ (is (nil? (:ip_address row)))+ (is (nil? (:user_agent row)))+ (is (nil? (:sanitized_user_agent row))))+ (finally (cleanup-calls! :tool_name tool)))))))))++(deftest ^:parallel record-mcp-tool-call!-normalizes-tool-name-test+ (testing "a blank or over-long tool_name is normalized so the row is still recorded, rather than+ dropped to a swallowed NOT NULL / length-constraint violation"+ (mt/with-premium-features #{:audit-app}+ (testing "a missing tool name falls back to a sentinel"+ ;; tool_name is the value under test, so isolate the row by a unique duration_ms marker+ (let [marker (+ 5000000 (rand-int 1000000))]+ (try+ (usage/record-mcp-tool-call! {:tool-name nil :user-id (mt/user->id :rasta)+ :status "error" :duration-ms marker})+ (is (= "unknown" (:tool_name (t2/select-one :model/McpToolCallLog :duration_ms marker))))+ (finally (cleanup-calls! :duration_ms marker)))))+ (testing "an over-long tool name is truncated to the column width"+ (let [marker (+ 6000000 (rand-int 1000000))+ long-name (apply str (repeat 300 \x))]+ (try+ (usage/record-mcp-tool-call! {:tool-name long-name :user-id (mt/user->id :rasta)+ :status "success" :duration-ms marker})+ (is (= 255 (count (:tool_name (t2/select-one :model/McpToolCallLog :duration_ms marker)))))+ (finally (cleanup-calls! :duration_ms marker))))))))++;;; ---------------------------------------- call-tool instrumentation --------------------------------------++(deftest ^:parallel call-tool-records-error-when-handler-throws-test+ (testing "a handler that throws (rather than returning error content) still records an error row,+ then the exception is rethrown so the client still sees the failure"+ (mt/with-premium-features #{:audit-app}+ (let [sid (str "throw-session-" (mt/random-name))+ tool (str "boom-" (mt/random-name))]+ (try+ (mt/with-dynamic-fn-redefs [mcp.tools/dispatch-tool-call+ (fn [& _] (throw (ex-info "kaboom" {})))]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"kaboom"+ (mcp.tools/call-tool #{} sid tool {}))))+ (let [row (t2/select-one :model/McpToolCallLog :tool_name tool)]+ (is (some? row) "an error row is recorded even though the handler threw")+ (is (= "error" (:status row))))+ (finally (cleanup-calls! :tool_name tool)))))))++;;; --------------------------------------------- Feature gating --------------------------------------------++(deftest ^:parallel collection-runs-on-ee-without-audit-app-test+ (testing "collection happens on any EE instance (:feature :none), but PII stays null without :audit-app"+ ;; Without :audit-app the `analytics-pii-retention-enabled` setting reads its default (false)+ ;; and cannot be turned on, so PII is never collected — but non-PII rows still are.+ (mt/with-premium-features #{}+ (let [sid (str "test-session-" (mt/random-name))+ tool (str "query-" (mt/random-name))]+ (try+ (usage/record-mcp-session!+ {:session-id sid :user-id (mt/user->id :rasta) :client-info {:name "claude" :version "1"}+ :user-agent "UA" :ip-address "1.2.3.4"})+ (usage/record-mcp-tool-call! {:tool-name tool :user-id (mt/user->id :rasta)+ :session-id sid :status "success" :duration-ms 1})+ (testing "rows are written"+ (is (= 1 (t2/count :model/McpSessionLog :id sid)))+ (is (= 1 (t2/count :model/McpToolCallLog :tool_name tool))))+ (let [row (t2/select-one :model/McpSessionLog :id sid)]+ (testing "non-PII identity is collected"+ (is (= "claude" (:client_name row)))+ (is (= (mt/user->id :rasta) (:user_id row))))+ (testing "PII is null because retention can't be enabled without :audit-app"+ (is (nil? (:ip_address row)))+ (is (nil? (:user_agent row)))))+ (finally (cleanup-calls! :tool_name tool) (cleanup! sid)))))))++;;; ------------------------------------------- Best-effort logging -----------------------------------------++(deftest logging-is-best-effort-test+ (testing "a failed write is swallowed and never propagates"+ (mt/with-premium-features #{:audit-app}+ (mt/with-dynamic-fn-redefs [t2/insert! (fn [& _] (throw (ex-info "boom" {})))]+ (is (nil? (usage/record-mcp-tool-call! {:tool-name "query" :user-id 1 :session-id "x"+ :status "success" :duration-ms 1})))+ (is (nil? (usage/record-mcp-session! {:session-id "y" :user-id 1 :client-info {:name "claude"}})))))))++;;; ------------------------------ Integration: drive the real MCP handler ----------------------------------++(defn- jsonrpc [method params id]+ (cond-> {:jsonrpc "2.0" :method method :params params}+ id (assoc :id id)))++(deftest ^:parallel three-write-points-integration-test+ (testing "initialize -> tools/call -> DELETE records session, tool-call, and ended_at"+ ;; Collection runs on any EE instance (:feature :none), so no premium feature is needed here.+ (let [crowberto (mt/user->id :crowberto)+ ;; Unique per run so parallel tests can't collide: the version rides onto the session and,+ ;; via the denormalized identity, onto every tool-call row — a precise lookup/cleanup key.+ ver (str (random-uuid))+ init-resp (client/client-full-response+ (test.users/username->token :crowberto)+ :post "mcp"+ (jsonrpc "initialize"+ {:clientInfo {:name "claude-ai" :version ver} :capabilities {}}+ 1))+ sid (get-in init-resp [:headers "Mcp-Session-Id"])]+ (try+ (testing "initialize writes exactly one session row with handshake identity"+ (is (some? sid))+ (is (= 1 (t2/count :model/McpSessionLog :id sid)))+ (let [row (t2/select-one :model/McpSessionLog :id sid)]+ (is (= "claude" (:client_name row)))+ (is (= ver (:client_version row)))+ (is (= crowberto (:user_id row)))+ (is (nil? (:ended_at row)))))+ ;; complete the handshake, then call a tool+ (client/client-full-response (test.users/username->token :crowberto)+ :post "mcp"+ {:request-options {:headers {"mcp-session-id" sid}}}+ (jsonrpc "notifications/initialized" {} nil))+ (let [call-resp (client/client-full-response+ (test.users/username->token :crowberto)+ :post "mcp"+ {:request-options {:headers {"mcp-session-id" sid}}}+ (jsonrpc "tools/call" {:name "read_resource"+ :arguments {:uris ["metabase://databases"]}} 2))]+ (testing "successful tools/call writes a success row with identity denormalized on it"+ (is (= 200 (:status call-resp)))+ (is (false? (boolean (get-in call-resp [:body :result :isError]))))+ (let [row (t2/select-one :model/McpToolCallLog :tool_name "read_resource" :client_version ver)]+ (is (some? row))+ (is (= "success" (:status row)))+ (is (= crowberto (:user_id row)))+ (is (nat-int? (:duration_ms row)))+ (testing "client identity is denormalized from the session (the call carried no _meta)"+ (is (= "claude" (:client_name row)))+ (is (= ver (:client_version row)))))))+ (testing "an unknown tool records a status=error row and the error propagates to the client"+ (let [err-resp (client/client-full-response+ (test.users/username->token :crowberto)+ :post "mcp"+ {:request-options {:headers {"mcp-session-id" sid}}}+ (jsonrpc "tools/call" {:name "no_such_tool" :arguments {}} 3))]+ (is (true? (boolean (get-in err-resp [:body :result :isError]))))+ (let [row (t2/select-one :model/McpToolCallLog :tool_name "no_such_tool" :client_version ver)]+ (is (some? row))+ (is (= "error" (:status row)))+ ;; unknown tool -> JSON-RPC "method not found"; error_code is non-PII, always recorded+ (is (= -32601 (:error_code row))))))+ (testing "DELETE stamps ended_at on the session row"+ (client/client-full-response (test.users/username->token :crowberto)+ :delete "mcp"+ {:request-options {:headers {"mcp-session-id" sid}}})+ (is (some? (:ended_at (t2/select-one :model/McpSessionLog :id sid)))))+ (finally+ (cleanup-calls! :client_version ver)+ (cleanup! sid))))))diff --git a/enterprise/backend/test/metabase_enterprise/mcp/v_mcp_tool_calls_test.clj b/enterprise/backend/test/metabase_enterprise/mcp/v_mcp_tool_calls_test.cljnew file mode 100644index 00000000000..3082f5acf45--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/mcp/v_mcp_tool_calls_test.clj@@ -0,0 +1,84 @@+(ns metabase-enterprise.mcp.v-mcp-tool-calls-test+ "Tests for the `v_mcp_tool_calls` SQL view. Identity is denormalized onto each tool-call row+ (no session join), and the view derives `client_display_name` / `error_type` / `user_display_name`+ from it."+ (:require+ [clojure.test :refer [deftest is testing use-fixtures]]+ [java-time.api :as t]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [toucan2.core :as t2]))++(use-fixtures :once (fixtures/initialize :db))++(set! *warn-on-reflection* true)++(defn- query-view+ "Query v_mcp_tool_calls, returning only rows for the given tool-call ids."+ [tool-call-ids]+ (t2/query {:select [:*]+ :from [:v_mcp_tool_calls]+ :where [:in :tool_call_id tool-call-ids]}))++(defn- find-row [rows tool-call-id]+ (some #(when (= (:tool_call_id %) tool-call-id) %) rows))++(deftest joins-and-derived-columns-test+ (testing "the view derives display columns from the identity denormalized on each tool-call row"+ (mt/with-temp+ [:model/User {user-id :id} {:first_name "Ada" :last_name "Lovelace"}+ :model/McpToolCallLog {ok-id :id} {:user_id user-id+ :tool_name "query" :status "success" :duration_ms 42+ :client_name "claude" :client_version "1.4.2"+ :created_at (t/offset-date-time)}+ :model/McpToolCallLog {err-id :id} {:user_id user-id+ :tool_name "query" :status "error" :duration_ms 7+ :client_name "claude" :client_version "1.4.2"+ :error_code -32602 :error_message "bad params"+ :created_at (t/offset-date-time)}]+ (let [rows (query-view [ok-id err-id])+ ok (find-row rows ok-id)+ err (find-row rows err-id)]+ (is (=? {:tool_name "query"+ :status "success"+ :client_name "claude"+ :client_display_name "Claude"+ :client_version "1.4.2"+ :user_display_name "Ada Lovelace"+ :error_type nil}+ ok))+ (is (=? {:status "error"+ :error_type "Invalid params"+ :error_message "bad params"}+ err))))))++(deftest unknown-client-and-user-test+ (testing "a tool call with no denormalized client and no user still appears, with null display columns"+ (mt/with-temp+ [:model/McpToolCallLog {orphan-id :id} {:user_id nil+ :tool_name "query" :status "success" :duration_ms 5+ :created_at (t/offset-date-time)}]+ (let [row (find-row (query-view [orphan-id]) orphan-id)]+ (is (some? row) "the row is not dropped")+ (is (=? {:tool_name "query" :client_name nil :client_display_name nil :user_display_name nil}+ row))))))++;; Guard the hand-maintained error_code -> error_type coupling. These pairs must stay in sync with+;; the CASE in the v_mcp_tool_calls view SQL and the error-code-* constants in metabase.mcp.tools; a+;; drift on either side breaks this test rather than silently mislabeling errors.+(def ^:private error-code->type+ {-32600 "Invalid request"+ -32601 "Method not found"+ -32602 "Invalid params"+ -32603 "Internal error"+ -32000 "Server error"+ -99999 nil})++(deftest error-code-to-type-mapping-test+ (testing "every JSON-RPC error_code maps to the expected error_type (and unknown codes -> nil)"+ (doseq [[code expected] error-code->type]+ (mt/with-temp+ [:model/McpToolCallLog {id :id} {:tool_name "query" :status "error" :duration_ms 1+ :error_code code :created_at (t/offset-date-time)}]+ (is (= expected (:error_type (find-row (query-view [id]) id)))+ (format "error_code %d should map to %s" code (pr-str expected)))))))diff --git a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.cljindex 731f12e2417..39282320c54 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj@@ -64,6 +64,8 @@:model/DashboardCardSeries:model/LoginHistory:model/McpQueryHandle+ :model/McpSessionLog+ :model/McpToolCallLog:model/FieldValues:model/MetabotConversation:model/MetabotFeedbackdiff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/index.js b/enterprise/frontend/src/metabase-enterprise/audit_app/index.jsindex fdcf4883f13..da924826fed 100644--- a/enterprise/frontend/src/metabase-enterprise/audit_app/index.js+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/index.js@@ -12,10 +12,8 @@ import { hasPremiumFeature } from "metabase-enterprise/settings";import { InsightsLink } from "./components/InsightsLink";import { InsightsMenuItem } from "./components/InsightsMenuItem";-import {- getMetabotAnalyticsNavItems,- getMetabotAnalyticsUpsellNavItems,-} from "./metabot-analytics/nav";+import { getMcpAnalyticsRoutes } from "./mcp-analytics/routes";+import { getMetabotAnalyticsNavItems } from "./metabot-analytics/nav";import {getAiAnalyticsRoutes,getAiAnalyticsUpsellRoutes,@@ -50,12 +48,13 @@ export function initializePlugin() {PLUGIN_AUDIT.isAuditDb = isAuditDb;PLUGIN_AUDIT.InsightsLink = InsightsLink;PLUGIN_AUDIT.InsightsMenuItem = InsightsMenuItem;+ PLUGIN_AUDIT.getMcpAnalyticsRoutes = getMcpAnalyticsRoutes;+ // Nav is registered for audit_app and decides Metabot (ai_controls) vs MCP (audit_app)+ // children internally; only the routes split on ai_controls.+ PLUGIN_AUDIT.getMetabotAnalyticsNavItems = getMetabotAnalyticsNavItems;if (hasPremiumFeature("ai_controls")) {- PLUGIN_AUDIT.getMetabotAnalyticsNavItems = getMetabotAnalyticsNavItems;PLUGIN_AUDIT.getAiAnalyticsRoutes = getAiAnalyticsRoutes;} else {- PLUGIN_AUDIT.getMetabotAnalyticsNavItems =- getMetabotAnalyticsUpsellNavItems;PLUGIN_AUDIT.getAiAnalyticsRoutes = getAiAnalyticsUpsellRoutes;}diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpAnalyticsEmptyState.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpAnalyticsEmptyState.tsxnew file mode 100644index 00000000000..6a0e8e781ed--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpAnalyticsEmptyState.tsx@@ -0,0 +1,17 @@+import { t } from "ttag";++import { EmptyState } from "metabase/common/components/EmptyState";+import { Flex } from "metabase/ui";++/** Centered placeholder shown (in place of the tabs/charts) when the filtered view has no tool calls. */+export function McpAnalyticsEmptyState() {+ return (+ <Flex flex={1} mih="60vh" align="center" justify="center">+ <EmptyState+ icon="audit"+ title={t`No MCP activity`}+ message={t`Tool calls from MCP clients will show up here. Try widening the date range or check back once clients start using the server.`}+ />+ </Flex>+ );+}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.tsxnew file mode 100644index 00000000000..95244ce6890--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpAnalyticsPage.tsx@@ -0,0 +1,213 @@+import { useEffect } from "react";+import { match } from "ts-pattern";+import { t } from "ttag";++import { MetabotAdminLayout } from "metabase/admin/ai/MetabotAdminLayout";+import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";+import { useSetting } from "metabase/common/hooks";+import { useUrlState } from "metabase/common/hooks/use-url-state";+import type { WithRouterProps } from "metabase/router";+import { Flex, Loader, SimpleGrid, Stack, Tabs, Title } from "metabase/ui";++import {+ // The shared audit filter bar; aliased since it has nothing to do with MCP "conversations".+ ConversationFilters as McpToolCallsFilter,+ useFilterOptions,+} from "../../metabot-analytics/components/ConversationFilters";+import { useAuditTable } from "../../metabot-analytics/hooks/useAuditTable";+import { VIEW_GROUP_MEMBERS, VIEW_MCP_TOOL_CALLS } from "../constants";+import { useMcpHasData } from "../hooks/useMcpHasData";+import { buildCallsByDayByStatusQuery } from "../query-utils";+import type { McpTab } from "../url-state";+import { mcpUrlStateConfig } from "../url-state";++import { McpAnalyticsEmptyState } from "./McpAnalyticsEmptyState";+import { McpBreakoutChart } from "./McpBreakoutChart";+import { McpCallsTimelineChart } from "./McpCallsTimelineChart";+import { McpEventsTable } from "./McpEventsTable";++/**+ * Admin MCP analytics page. Renders live ad-hoc queries over the `v_mcp_tool_calls` audit view+ * across two tabs (Charts and a row-level Events table), sharing URL-state date/user/group+ * 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 {+ dateFilter,+ userId,+ groupId,+ tenantId,+ groupNoFilterValue,+ userOptions,+ groupOptions,+ tenantOptions,+ hasTenants,+ } = useFilterOptions({ date, user, group, tenant });++ // IP address and error message are PII (null unless retention is on), so only surface those+ // columns when they're collected.+ const hasPii = useSetting("analytics-pii-retention-enabled") === true;+ // The MCP server can be turned off while its historical analytics still exist; when it's off the+ // page is inaccessible (the nav item greys out — this also blocks direct URL access).+ const mcpEnabled = useSetting("mcp-enabled?");++ const toolCallsAudit = useAuditTable(VIEW_MCP_TOOL_CALLS);+ const groupMembersAudit = useAuditTable(VIEW_GROUP_MEMBERS);++ const dataSources = {+ provider: toolCallsAudit.provider,+ table: toolCallsAudit.table,+ groupMembersTable: groupMembersAudit.table,+ };++ const chartFilters = { dateFilter, userId, groupId, tenantId };++ const { isInitialLoading, isRefetching, hasData } = useMcpHasData({+ ...dataSources,+ ...chartFilters,+ });+ // Initial load shows a loader (never the empty state). After the first result, a filter+ // change keeps the charts mounted so they show their own skeletons while refetching; the+ // empty state only appears once a load has resolved to zero rows.+ const showEmpty = !isInitialLoading && !isRefetching && !hasData;++ // Only surface the errors section when the current filters actually match failed calls, so a+ // healthy instance doesn't show a row of empty error charts.+ const { hasData: hasErrors } = useMcpHasData({+ ...dataSources,+ ...chartFilters,+ errorsOnly: true,+ });++ // The MCP server can be off while its historical analytics still exist; when it's off the page+ // is inaccessible — redirect away so it can't be reached by URL (the nav item also greys out).+ useEffect(() => {+ if (!mcpEnabled) {+ router.replace("/admin/metabot/usage-auditing");+ }+ }, [mcpEnabled, router]);++ if (!mcpEnabled) {+ return null;+ }++ return (+ <MetabotAdminLayout fullWidth>+ <SettingsPageWrapper mt="sm">+ <Flex align="center" justify="space-between">+ <Title order={2}>{t`MCP analytics`}</Title>++ <McpToolCallsFilter+ date={date}+ onDateChange={(val) => patchUrlState({ date: val })}+ user={user}+ onUserChange={(val) => patchUrlState({ user: val })}+ userOptions={userOptions}+ group={group}+ onGroupChange={(val) => patchUrlState({ group: val })}+ groupOptions={groupOptions}+ groupNoFilterValue={groupNoFilterValue}+ tenant={tenant}+ onTenantChange={(val) => patchUrlState({ tenant: val })}+ tenantOptions={tenantOptions}+ hasTenants={hasTenants}+ />+ </Flex>++ {match({ isInitialLoading, showEmpty })+ .with({ isInitialLoading: true }, () => (+ <Flex mih="60vh" align="center" justify="center">+ <Loader size="lg" />+ </Flex>+ ))+ .with({ showEmpty: true }, () => <McpAnalyticsEmptyState />)+ .otherwise(() => (+ <Tabs+ value={tab}+ onChange={(val) => patchUrlState({ tab: val as McpTab })}+ keepMounted={false}+ >+ <Tabs.List mb="lg">+ <Tabs.Tab value="charts">{t`Usage`}</Tabs.Tab>+ <Tabs.Tab value="events">{t`Tool calls`}</Tabs.Tab>+ </Tabs.List>++ <Tabs.Panel value="charts">+ <Stack gap="lg">+ <McpCallsTimelineChart+ {...dataSources}+ {...chartFilters}+ title={t`Calls by client over time`}+ />+ <SimpleGrid cols={2} spacing="lg">+ <McpBreakoutChart+ {...dataSources}+ {...chartFilters}+ title={t`Calls by tool`}+ display="pie"+ breakoutColumn="tool_name"+ h={500}+ />+ <McpBreakoutChart+ {...dataSources}+ {...chartFilters}+ title={t`Calls by user`}+ display="row"+ breakoutColumn="user_display_name"+ h={500}+ />+ </SimpleGrid>++ {hasErrors && (+ <>+ <Title order={3} mt="md">{t`Errors`}</Title>+ <McpCallsTimelineChart+ {...dataSources}+ {...chartFilters}+ title={t`Calls by status over time`}+ buildQuery={buildCallsByDayByStatusQuery}+ />+ <SimpleGrid cols={2} spacing="lg">+ <McpBreakoutChart+ {...dataSources}+ {...chartFilters}+ title={t`Errors by type`}+ display="pie"+ breakoutColumn="error_type"+ errorsOnly+ h={500}+ />+ <McpBreakoutChart+ {...dataSources}+ {...chartFilters}+ title={t`Errors by tool`}+ display="row"+ breakoutColumn="tool_name"+ errorsOnly+ h={500}+ />+ </SimpleGrid>+ </>+ )}+ </Stack>+ </Tabs.Panel>++ <Tabs.Panel value="events">+ <McpEventsTable+ {...dataSources}+ {...chartFilters}+ hasTenants={hasTenants}+ hasPii={hasPii}+ />+ </Tabs.Panel>+ </Tabs>+ ))}+ </SettingsPageWrapper>+ </MetabotAdminLayout>+ );+}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.tsxnew file mode 100644index 00000000000..0a26ea0912b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpAnalyticsPage.unit.spec.tsx@@ -0,0 +1,224 @@+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 { renderWithProviders, screen, waitFor, within } from "__support__/ui";+import { createMockState } from "metabase/redux/store/mocks";+import { Route } from "metabase/router";+import registerVisualizations from "metabase/visualizations/register";+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 { AUDIT_DB_ID } from "../constants";++import { McpAnalyticsPage } from "./McpAnalyticsPage";++registerVisualizations();++const MCP_TOOL_CALLS_TABLE_ID = 2001;+const GROUP_MEMBERS_TABLE_ID = 2002;++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 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) {+ fetchMock.get(`path:/api/database/${AUDIT_DB_ID}/metadata`, auditDatabase);+ setupUsersEndpoints([createMockUser({ id: 1, first_name: "Ada" })]);+ setupGroupsEndpoint([createMockGroup({ id: 1, name: "All Users" })]);+ fetchMock.post("path:/api/dataset", dataset, { name: "dataset" });+}++/** Render `McpAnalyticsPage` at its route with EE plugins + `audit_app`, optionally overriding the dataset response. */+function setup({ dataset }: { dataset?: Dataset } = {}) {+ setupEnterprisePlugins();+ setupEndpoints(dataset);++ return renderWithProviders(+ <Route+ path="/admin/metabot/usage-auditing/mcp"+ component={McpAnalyticsPage}+ />,+ {+ initialRoute: "/admin/metabot/usage-auditing/mcp",+ withRouter: true,+ storeInitialState: createMockState({+ settings: mockSettings({+ "token-features": createMockTokenFeatures({ audit_app: true }),+ "mcp-enabled?": true,+ }),+ }),+ },+ );+}++describe("McpAnalyticsPage", () => {+ it("renders the header, filters, and charts tab", 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("tab", { 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("switches to the events tab and renders the row-level table", async () => {+ setup();++ await screen.findByRole("heading", { name: "MCP analytics" });+ await userEvent.click(+ await screen.findByRole("tab", { name: "Tool calls" }),+ );++ const eventsPanel = screen.getByRole("tabpanel");+ expect(+ await within(eventsPanel).findByTestId("table-root"),+ ).toBeInTheDocument();+ });++ it("shows a single empty state (no tabs, no charts) 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();++ // No tabs render when the view is empty — so neither the charts nor the events table can.+ expect(+ screen.queryByRole("tab", { name: "Usage" }),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("tab", { name: "Tool calls" }),+ ).not.toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpBreakoutChart.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpBreakoutChart.tsxnew file mode 100644index 00000000000..390ff3adb79--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpBreakoutChart.tsx@@ -0,0 +1,159 @@+import { useMemo } from "react";+import { t } from "ttag";++import { Skeleton, useMantineTheme } from "metabase/ui";+import type {+ CardMetadata,+ MetadataProvider,+ Query,+ TableMetadata,+} from "metabase-lib";+import type { VisualizationDisplay } from "metabase-types/api";++import { BreakoutChartCard } from "../../metabot-analytics/components/ConversationStatsPage/BreakoutChartCard";+import { mapBreakoutDimension } from "../../metabot-analytics/components/ConversationStatsPage/breakout-raw-series";+import { useAdhocBreakoutQuery } from "../../metabot-analytics/hooks/useAdhocBreakoutQuery";+import type { McpFilters } from "../query-utils";+import {+ buildCountBreakoutQuery,+ buildErrorBreakoutQuery,+} from "../query-utils";+import { toCountBreakoutRawSeries } from "../raw-series";++const DEFAULT_CHART_HEIGHT = 350;+const DEFAULT_MAX_CATEGORIES = 8;++type DataSources = {+ provider: MetadataProvider | null;+ table: TableMetadata | CardMetadata | null;+ groupMembersTable: TableMetadata | CardMetadata | null;+};++type Props = DataSources &+ McpFilters & {+ title: string;+ display: VisualizationDisplay;+ /** Column to break down call counts by (e.g. `tool_name`, `user_display_name`). */+ breakoutColumn: string;+ /** When set, count only failed calls (`status = error`) — for the error breakdown charts. */+ errorsOnly?: boolean;+ labelMapper?: (value: unknown) => unknown;+ maxCategories?: number;+ h?: number;+ };++type InnerProps = McpFilters & {+ provider: MetadataProvider;+ table: TableMetadata | CardMetadata;+ groupMembersTable: TableMetadata | CardMetadata;+ title: string;+ display: VisualizationDisplay;+ breakoutColumn: string;+ errorsOnly: boolean;+ labelMapper?: (value: unknown) => unknown;+ maxCategories: number;+ h: number;+};++/**+ * Single-breakout count chart (e.g. calls by tool as a pie, calls by user as a row chart).+ * Renders a skeleton until the audit metadata is loaded, then delegates to the inner component.+ */+export function McpBreakoutChart({+ provider,+ table,+ groupMembersTable,+ h = DEFAULT_CHART_HEIGHT,+ maxCategories = DEFAULT_MAX_CATEGORIES,+ errorsOnly = false,+ ...rest+}: Props) {+ if (!provider || !table || !groupMembersTable) {+ return <Skeleton h={h} />;+ }+ return (+ <McpBreakoutChartInner+ provider={provider}+ table={table}+ groupMembersTable={groupMembersTable}+ h={h}+ maxCategories={maxCategories}+ errorsOnly={errorsOnly}+ {...rest}+ />+ );+}++/**+ * Loaded variant of {@link McpBreakoutChart}: builds the breakout query, runs it, and renders+ * the result through the shared chart card. Split out so the query hooks only run once metadata+ * (provider/table) is available.+ */+function McpBreakoutChartInner({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ title,+ display,+ breakoutColumn,+ errorsOnly,+ labelMapper,+ maxCategories,+ h,+}: InnerProps) {+ const query = useMemo<Query>(() => {+ const opts = {+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ breakoutColumn,+ };+ return errorsOnly+ ? buildErrorBreakoutQuery(opts)+ : buildCountBreakoutQuery(opts);+ }, [+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ breakoutColumn,+ errorsOnly,+ ]);++ const { data, jsQuery, isFetching } = useAdhocBreakoutQuery(query);+ const { themeColor } = useMantineTheme().fn;++ const rawSeries = useMemo(() => {+ const labeled = labelMapper+ ? mapBreakoutDimension(data, labelMapper)+ : data;+ return toCountBreakoutRawSeries(labeled, jsQuery, {+ display,+ maxCategories,+ otherLabel: t`Other`,+ getColor: themeColor,+ });+ }, [data, jsQuery, labelMapper, display, maxCategories, themeColor]);++ return (+ <BreakoutChartCard+ title={title}+ rawSeries={rawSeries}+ isFetching={isFetching}+ display={display}+ h={h}+ otherLabel={t`Other`}+ />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpCallsTimelineChart.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpCallsTimelineChart.tsxnew file mode 100644index 00000000000..021944b08ef--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpCallsTimelineChart.tsx@@ -0,0 +1,130 @@+import { useMemo } from "react";+import { t } from "ttag";++import { Skeleton } from "metabase/ui";+import type {+ CardMetadata,+ MetadataProvider,+ Query,+ TableMetadata,+} from "metabase-lib";++import { BreakoutChartCard } from "../../metabot-analytics/components/ConversationStatsPage/BreakoutChartCard";+import { useAdhocBreakoutQuery } from "../../metabot-analytics/hooks/useAdhocBreakoutQuery";+import type { McpFilters } from "../query-utils";+import { buildCallsByDayByClientQuery } from "../query-utils";+import { toSeriesByBreakoutRawSeries } from "../raw-series";++const CHART_HEIGHT = 320;++type DataSources = {+ provider: MetadataProvider;+ table: TableMetadata | CardMetadata;+ groupMembersTable: TableMetadata | CardMetadata;+};++type BuildQueryFn = (opts: McpFilters & DataSources) => Query;++type Props = McpFilters & {+ provider: MetadataProvider | null;+ table: TableMetadata | CardMetadata | null;+ groupMembersTable: TableMetadata | CardMetadata | null;+ title: string;+ /** Two-breakout (day × series) query builder. Defaults to the day×client breakdown. */+ buildQuery?: BuildQueryFn;+ h?: number;+};++type InnerProps = McpFilters &+ DataSources & {+ title: string;+ buildQuery: BuildQueryFn;+ h: number;+ };++/**+ * Multi-series line chart of calls per day (one line per series — client or status). Renders a+ * skeleton until the audit metadata is loaded, then delegates to the inner component.+ */+export function McpCallsTimelineChart({+ provider,+ table,+ groupMembersTable,+ title,+ buildQuery = buildCallsByDayByClientQuery,+ h = CHART_HEIGHT,+ ...filters+}: Props) {+ if (!provider || !table || !groupMembersTable) {+ return <Skeleton h={h} />;+ }+ return (+ <McpCallsTimelineChartInner+ provider={provider}+ table={table}+ groupMembersTable={groupMembersTable}+ title={title}+ buildQuery={buildQuery}+ h={h}+ {...filters}+ />+ );+}++/**+ * Loaded variant of {@link McpCallsTimelineChart}: builds the day×series query, runs it, and+ * renders it as a multi-series line chart through the shared chart card.+ */+function McpCallsTimelineChartInner({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ title,+ buildQuery,+ h,+}: InnerProps) {+ const query = useMemo(+ () =>+ buildQuery({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ }),+ [+ buildQuery,+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ ],+ );++ const { data, jsQuery, isFetching } = useAdhocBreakoutQuery(query);++ const rawSeries = useMemo(+ () => toSeriesByBreakoutRawSeries(data, jsQuery),+ [data, jsQuery],+ );++ return (+ <BreakoutChartCard+ title={title}+ rawSeries={rawSeries}+ isFetching={isFetching}+ display="line"+ h={h}+ otherLabel={t`Other`}+ />+ );+}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.tsxnew file mode 100644index 00000000000..150a0fa30c8--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpEventsTable.tsx@@ -0,0 +1,210 @@+import { useMemo } from "react";+import { t } from "ttag";++import type {+ CardMetadata,+ MetadataProvider,+ TableMetadata,+} from "metabase-lib";+import type { DatasetQuery, TableColumnOrderSetting } 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 { 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"] : []),+ ];+}++/** 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`,+ };+}++type Props = McpFilters & {+ provider: MetadataProvider | null;+ table: TableMetadata | CardMetadata | null;+ groupMembersTable: TableMetadata | CardMetadata | null;+ hasTenants: boolean;+ hasPii: boolean;+};++type InnerProps = McpFilters & {+ provider: MetadataProvider;+ table: TableMetadata | CardMetadata;+ groupMembersTable: TableMetadata | CardMetadata;+ hasTenants: boolean;+ hasPii: boolean;+};++/**+ * 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.+ */+export function buildEventsRawSeries(+ data: ReturnType<typeof useAdhocBreakoutQuery>["data"],+ jsQuery: DatasetQuery | null,+ hasTenants: boolean,+ hasPii: boolean,+) {+ if (!data?.data || !jsQuery) {+ return null;+ }+ 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 },+ },+ ];+}++/**+ * Row-level events table for the Events tab. Renders nothing until the audit metadata is+ * loaded, then delegates to the inner component.+ */+export function McpEventsTable({+ provider,+ table,+ groupMembersTable,+ ...filters+}: Props) {+ if (!provider || !table || !groupMembersTable) {+ return null;+ }+ return (+ <McpEventsTableInner+ provider={provider}+ table={table}+ groupMembersTable={groupMembersTable}+ {...filters}+ />+ );+}++/**+ * 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.+ */+function McpEventsTableInner({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ hasTenants,+ hasPii,+}: InnerProps) {+ const query = useMemo(+ () =>+ buildEventsQuery({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ limit: EVENTS_LIMIT,+ }),+ [provider, table, groupMembersTable, dateFilter, userId, groupId, tenantId],+ );++ const { data, jsQuery, isFetching } = useAdhocBreakoutQuery(query);++ const rawSeries = useMemo(+ () => buildEventsRawSeries(data, jsQuery, hasTenants, hasPii),+ [data, jsQuery, hasTenants, hasPii],+ );++ return (+ <BreakoutChartCard+ rawSeries={rawSeries}+ isFetching={isFetching}+ display="table"+ h={TABLE_HEIGHT}+ otherLabel={t`Other`}+ />+ );+}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.tsxnew file mode 100644index 00000000000..c64843de764--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/components/McpEventsTable.unit.spec.tsx@@ -0,0 +1,172 @@+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"),+];++const jsQuery = { database: 1, type: "query", query: {} } as DatasetQuery;++function build(cols = ALL_COLS, hasTenants = true, hasPii = true) {+ 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");+ }+ 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(+ { 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"),+ ];+ 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",+ ]);+ });++ 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");+ });++ 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",+ );+ 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",+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/constants.ts b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/constants.tsnew file mode 100644index 00000000000..6d3dda08a9a--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/constants.ts@@ -0,0 +1,7 @@+export {+ AUDIT_DB_ID,+ VIEW_GROUP_MEMBERS,+} from "../metabot-analytics/constants";++// View name in the audit database for MCP tool-call analytics.+export const VIEW_MCP_TOOL_CALLS = "v_mcp_tool_calls";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.tsnew file mode 100644index 00000000000..7a1570b39cb--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/hooks/useMcpHasData.ts@@ -0,0 +1,87 @@+import { useMemo, useRef } from "react";++import type {+ CardMetadata,+ MetadataProvider,+ TableMetadata,+} from "metabase-lib";++import { useAdhocBreakoutQuery } from "../../metabot-analytics/hooks/useAdhocBreakoutQuery";+import type { McpFilters } from "../query-utils";+import { buildTotalCountQuery } from "../query-utils";++type DataSources = {+ provider: MetadataProvider | null;+ table: TableMetadata | CardMetadata | null;+ groupMembersTable: TableMetadata | CardMetadata | null;+};++type Result = {+ /** First load, before the count has ever resolved — show a loader, never the empty state. */+ isInitialLoading: boolean;+ /** A subsequent load triggered by a filter change — let the charts show their own skeletons. */+ isRefetching: boolean;+ /** Whether the current (resolved) filters match any tool calls. */+ hasData: boolean;+};++/**+ * Runs a single count query over the filtered view to drive the page's load/empty/data states.+ * Distinguishes the initial load (loader) from a filter-change refetch (skeletons) so the page+ * never flashes the empty state before the first result has resolved.+ */+export function useMcpHasData({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ errorsOnly = false,+}: DataSources & McpFilters & { errorsOnly?: boolean }): Result {+ const query = useMemo(+ () =>+ provider && table && groupMembersTable+ ? buildTotalCountQuery({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ errorsOnly,+ })+ : null,+ [+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ errorsOnly,+ ],+ );++ const { data, isFetching } = useAdhocBreakoutQuery(query);++ // Latch once the first count resolves; from then on a fetch is a refetch, not initial load.+ const hasLoadedOnce = useRef(false);+ const resolved = query != null && !isFetching && data != null;+ if (resolved) {+ hasLoadedOnce.current = true;+ }++ // The query is a single count aggregation with no breakout, so the result is exactly one row+ // with one column — the scalar total. `rows[0][0]` is that count.+ const count = Number(data?.data?.rows?.[0]?.[0] ?? 0);++ return {+ isInitialLoading: !hasLoadedOnce.current,+ isRefetching: hasLoadedOnce.current && isFetching,+ hasData: count > 0,+ };+}diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/index.ts b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/index.tsnew file mode 100644index 00000000000..0b349df471f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/index.ts@@ -0,0 +1 @@+export { McpAnalyticsPage } from "./components/McpAnalyticsPage";diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/nav.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/nav.tsxnew file mode 100644index 00000000000..41d4f3dab13--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/nav.tsx@@ -0,0 +1,18 @@+import { t } from "ttag";++import { AdminNavItem } from "metabase/admin/components/AdminNav";++/**+ * The MCP analytics nav item, rendered as a child of the admin "Usage auditing" group+ * (`metabot-analytics/nav`). Lives in EE-only code, so it's absent on OSS. Disabled (greyed) when+ * the MCP server is off — matching the route guard that redirects away from the page.+ */+export function McpAnalyticsNavItem({ mcpEnabled }: { mcpEnabled: boolean }) {+ return (+ <AdminNavItem+ label={t`MCP analytics`}+ path="/admin/metabot/usage-auditing/mcp"+ disabled={!mcpEnabled}+ />+ );+}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.tsnew file mode 100644index 00000000000..d94634082e4--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/query-utils.ts@@ -0,0 +1,309 @@+import type { DateFilterValue } from "metabase/querying/common/types";+import type {+ CardMetadata,+ MetadataProvider,+ Query,+ TableMetadata,+} from "metabase-lib";+import * as Lib from "metabase-lib";++import {+ applyDateFilter,+ applyIdFilter,+ breakoutByColumn,+ findColumn,+ joinGroupMembers,+} from "../metabot-analytics/components/ConversationStatsPage/query-utils";++export type McpFilters = {+ dateFilter: DateFilterValue;+ userId?: number;+ groupId?: number;+ tenantId?: number;+};++type McpDataSources = {+ provider: MetadataProvider;+ table: TableMetadata | CardMetadata;+ groupMembersTable: TableMetadata | CardMetadata;+};++// Name of the count aggregation column produced by `Lib.aggregateByCount`.+const COUNT_COLUMN = "count";++/**+ * Apply the shared user/group/tenant filters to a query. The group filter joins the audit+ * `v_group_members` view and filters by `group_id` (a user can belong to several groups); the+ * user and tenant filters are plain `user_id` / `tenant_id` equalities. Each no-ops when its id+ * is unset.+ */+function applyScopeFilters(+ query: Query,+ {+ userId,+ groupId,+ tenantId,+ }: Pick<McpFilters, "userId" | "groupId" | "tenantId">,+ groupMembersTable: TableMetadata | CardMetadata,+): Query {+ query = applyIdFilter(query, "user_id", userId);+ query = applyIdFilter(query, "tenant_id", tenantId);+ query = groupId != null ? joinGroupMembers(query, groupMembersTable) : query;+ query = groupId != null ? applyIdFilter(query, "group_id", groupId) : query;+ return query;+}++/**+ * The shared prelude every builder starts from: the view query with the date + scope+ * (user/group/tenant) filters applied. Centralizing it keeps the filter handling — notably+ * `tenantId` — in one place so a builder can't silently drop a filter.+ */+function buildBaseQuery({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+}: McpFilters & McpDataSources): Query {+ let query = Lib.queryFromTableOrCardMetadata(provider, table);+ query = applyDateFilter(query, dateFilter);+ query = applyScopeFilters(+ query,+ { userId, groupId, tenantId },+ groupMembersTable,+ );+ return query;+}++/** Order an aggregated query by the count column descending (highest counts first). */+function orderByCountDesc(query: Query): Query {+ const countCol = findColumn(query, COUNT_COLUMN, Lib.orderableColumns);+ return countCol ? Lib.orderBy(query, 0, countCol, "desc") : query;+}++/** Filter a query to rows whose `status` equals `status` (e.g. "error"). No-op if absent. */+function applyStatusFilter(query: Query, status: string): Query {+ const col = findColumn(query, "status", Lib.filterableColumns);+ if (!col) {+ return query;+ }+ return Lib.filter(+ query,+ 0,+ Lib.stringFilterClause({+ operator: "=",+ column: col,+ values: [status],+ options: {},+ }),+ );+}++type CountBreakoutQueryOpts = McpFilters &+ McpDataSources & {+ breakoutColumn: string;+ };++/**+ * Build a "count of tool calls grouped by `breakoutColumn`" query (filtered + ordered by+ * count desc). Used by the single-breakout charts — calls by tool, by user, etc.+ */+export function buildCountBreakoutQuery({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ breakoutColumn,+}: CountBreakoutQueryOpts): Query {+ let query = buildBaseQuery({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ });+ query = Lib.aggregateByCount(query, 0);+ query = breakoutByColumn(query, breakoutColumn);+ query = orderByCountDesc(query);+ return query;+}++/** Add a `created_at` breakout bucketed by day (falls back to the raw column if the day bucket is unavailable). */+function breakoutByCreatedAtDay(query: Query): Query {+ const col = findColumn(query, "created_at", Lib.breakoutableColumns);+ if (!col) {+ return query;+ }+ const dayBucket = Lib.availableTemporalBuckets(query, 0, col).find(+ (bucket) => Lib.displayInfo(query, 0, bucket).shortName === "day",+ );+ const bucketed = dayBucket ? Lib.withTemporalBucket(col, dayBucket) : col;+ return Lib.breakout(query, 0, bucketed);+}++/**+ * Build a "calls per day, broken out by client" query — a multi-series time series. The day+ * breakout is added first so it becomes the x-axis dimension and `client_display_name` becomes+ * the series (one line per client).+ */+export function buildCallsByDayByClientQuery({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+}: McpFilters & McpDataSources): Query {+ let query = buildBaseQuery({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ });+ query = Lib.aggregateByCount(query, 0);+ query = breakoutByCreatedAtDay(query);+ query = breakoutByColumn(query, "client_display_name");+ return query;+}++/**+ * Build a "calls per day, broken out by status" query — a multi-series time series (one line+ * per status) that surfaces the error-vs-success trend over time.+ */+export function buildCallsByDayByStatusQuery({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+}: McpFilters & McpDataSources): Query {+ let query = buildBaseQuery({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ });+ query = Lib.aggregateByCount(query, 0);+ query = breakoutByCreatedAtDay(query);+ query = breakoutByColumn(query, "status");+ return query;+}++type ErrorBreakoutQueryOpts = McpFilters &+ McpDataSources & {+ breakoutColumn: string;+ };++/**+ * Build a "count of failed tool calls grouped by `breakoutColumn`" query (filtered to+ * `status = error`, ordered by count desc). Used by the error breakdown charts — by tool, by+ * error type.+ */+export function buildErrorBreakoutQuery({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ breakoutColumn,+}: ErrorBreakoutQueryOpts): Query {+ let query = buildBaseQuery({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ });+ query = applyStatusFilter(query, "error");+ query = Lib.aggregateByCount(query, 0);+ query = breakoutByColumn(query, breakoutColumn);+ query = orderByCountDesc(query);+ return query;+}++/**+ * Build a single-number count over the filtered view, used to decide whether the page has any+ * data to show (so we can render one empty state instead of a grid of empty charts). When+ * `errorsOnly` is set, counts only failed calls (drives the errors-section visibility).+ */+export function buildTotalCountQuery({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ errorsOnly = false,+}: McpFilters & McpDataSources & { errorsOnly?: boolean }): Query {+ let query = buildBaseQuery({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ });+ query = errorsOnly ? applyStatusFilter(query, "error") : query;+ query = Lib.aggregateByCount(query, 0);+ return query;+}++type EventsQueryOpts = McpFilters &+ McpDataSources & {+ limit: number;+ };++/**+ * 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.+ */+export function buildEventsQuery({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ limit,+}: EventsQueryOpts): Query {+ let query = buildBaseQuery({+ provider,+ table,+ groupMembersTable,+ dateFilter,+ userId,+ groupId,+ tenantId,+ });++ const createdAt = findColumn(query, "created_at", Lib.orderableColumns);+ if (createdAt) {+ query = Lib.orderBy(query, 0, createdAt, "desc");+ }++ query = Lib.limit(query, 0, limit);+ return query;+}diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/raw-series.ts b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/raw-series.tsnew file mode 100644index 00000000000..3bea84b2b6b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/raw-series.ts@@ -0,0 +1,145 @@+import type { ColorName } from "metabase/ui/colors/types";+import type { DatasetQuery, VisualizationDisplay } from "metabase-types/api";++type GetColor = (name: ColorName) => string;++type RawDataCol = { source?: string; name?: string };+type RawData = { cols: RawDataCol[]; rows: unknown[][] };+type AdhocResponse = { data?: RawData } | undefined;++type Opts = {+ display: VisualizationDisplay;+ maxCategories?: number;+ otherLabel: string;+ getColor: GetColor;+};++/**+ * Keep the top `max - 1` rows (already count-ordered) and fold the remaining long tail into a+ * single "Other" row whose metric is the summed overflow. Returns rows unchanged when there's+ * nothing to collapse.+ */+function collapseToTopN(+ rows: unknown[][],+ dimensionIndex: number,+ metricIndex: number,+ max: number | undefined,+ otherLabel: string,+ colCount: number,+): unknown[][] {+ const shouldCollapse =+ max != null && dimensionIndex >= 0 && metricIndex >= 0 && rows.length > max;+ if (!shouldCollapse) {+ return rows;+ }+ const keep = rows.slice(0, max - 1);+ const overflow = rows.slice(max - 1);+ const otherRow: unknown[] = new Array(colCount).fill(null);+ otherRow[dimensionIndex] = otherLabel;+ otherRow[metricIndex] = overflow.reduce(+ (sum, row) => sum + (Number(row[metricIndex]) || 0),+ 0,+ );+ return [...keep, otherRow];+}++/**+ * Build a single-breakout rawSeries (one dimension + the count metric) for `bar`/`row`/`pie`+ * displays. Long tails are collapsed into a single "Other" category.+ */+export function toCountBreakoutRawSeries(+ response: AdhocResponse,+ jsQuery: DatasetQuery | null,+ opts: Opts,+) {+ if (!response?.data || !jsQuery) {+ return null;+ }++ const { display, maxCategories, otherLabel, getColor } = opts;+ const cols = response.data.cols;+ const dimensionIndex = cols.findIndex((c) => c.source === "breakout");+ const metricIndex = cols.findIndex((c) => c.source === "aggregation");+ const dimensionName =+ dimensionIndex >= 0 ? cols[dimensionIndex].name : undefined;+ const countColumnName =+ metricIndex >= 0 ? (cols[metricIndex].name ?? "count") : "count";++ const visualizationSettings =+ display === "pie"+ ? {+ "pie.dimension": dimensionName,+ "pie.metric": countColumnName,+ }+ : {+ "graph.x_axis.title_text": "",+ "graph.y_axis.title_text": "",+ ...(display === "bar" && {+ "graph.x_axis.axis_enabled": "compact" as const,+ }),+ series_settings: {+ [countColumnName]: { color: getColor("accent0") },+ },+ };++ return [+ {+ card: {+ display,+ dataset_query: jsQuery,+ visualization_settings: visualizationSettings,+ },+ data: {+ ...response.data,+ rows: collapseToTopN(+ response.data.rows,+ dimensionIndex,+ metricIndex,+ maxCategories,+ otherLabel,+ cols.length,+ ),+ },+ },+ ];+}++/**+ * Build a multi-series line rawSeries from a two-breakout count query: the first breakout is+ * the x-axis dimension and the second becomes the series (e.g. day x client).+ */+export function toSeriesByBreakoutRawSeries(+ response: AdhocResponse,+ jsQuery: DatasetQuery | null,+) {+ if (!response?.data || !jsQuery) {+ return null;+ }++ const breakoutCols = response.data.cols.filter(+ (col) => col.source === "breakout",+ );+ const metricCol = response.data.cols.find(+ (col) => col.source === "aggregation",+ );+ const [dimensionCol, seriesCol] = breakoutCols;+ if (!dimensionCol?.name || !seriesCol?.name || !metricCol?.name) {+ return null;+ }++ return [+ {+ card: {+ display: "line" as const,+ dataset_query: jsQuery,+ visualization_settings: {+ "graph.dimensions": [dimensionCol.name, seriesCol.name],+ "graph.metrics": [metricCol.name],+ "graph.x_axis.title_text": "",+ "graph.y_axis.title_text": "",+ },+ },+ data: response.data,+ },+ ];+}diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/routes.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/routes.tsxnew file mode 100644index 00000000000..b7bac555987--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/routes.tsx@@ -0,0 +1,19 @@+import { Route } from "metabase/router";++import { McpAnalyticsPage } from "./components/McpAnalyticsPage";++/**+ * The `/admin/metabot/usage-auditing/mcp` route — nested under the `usage-auditing` namespace so+ * the admin nav opens the "Usage auditing" folder (where the link lives) rather than the MCP+ * group. Wired into `PLUGIN_AUDIT` and only registered on EE instances with the `audit_app`+ * feature, so navigating there renders nothing on OSS.+ */+export function getMcpAnalyticsRoutes() {+ return (+ <Route+ key="mcp-analytics"+ path="usage-auditing/mcp"+ component={McpAnalyticsPage}+ />+ );+}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.tsnew file mode 100644index 00000000000..faf9b792208--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/mcp-analytics/url-state.ts@@ -0,0 +1,38 @@+import {+ type QueryParam,+ type UrlStateConfig,+ getFirstParamValue,+} from "metabase/common/hooks/use-url-state";++import {+ type FilterUrlState,+ filterUrlStateConfig,+ mergeUrlStateConfig,+} from "../metabot-analytics/components/ConversationFilters/url-state";++export type McpTab = "charts" | "events";++type McpPageUrlState = {+ tab: McpTab;+};++export type McpUrlState = FilterUrlState & McpPageUrlState;++const DEFAULT_TAB: McpTab = "charts";++/** 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;+}++const mcpPageUrlStateConfig: UrlStateConfig<McpPageUrlState> = {+ parse: (query) => ({+ tab: parseTab(query.tab),+ }),+ serialize: ({ tab }) => ({+ tab: tab === DEFAULT_TAB ? undefined : tab,+ }),+};++export const mcpUrlStateConfig: UrlStateConfig<McpUrlState> =+ mergeUrlStateConfig(filterUrlStateConfig, mcpPageUrlStateConfig);diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationStatsPage/BreakoutChartCard.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationStatsPage/BreakoutChartCard.tsxindex 086f4d7ba4d..f476b8ba776 100644--- a/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationStatsPage/BreakoutChartCard.tsx+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationStatsPage/BreakoutChartCard.tsx@@ -15,7 +15,7 @@ const CLICKABLE_MODE: ClickActionsMode = {};type Props = {- title: string;+ title?: string;rawSeries: any[] | null;isFetching: boolean;display: VisualizationDisplay;@@ -49,9 +49,11 @@ export function BreakoutChartCard({pb={display === "row" ? "md" : "0"}h={h}>- <Text fw="bold" mb="md">- {title}- </Text>+ {title && (+ <Text fw="bold" mb="md">+ {title}+ </Text>+ )}<VisualizationrawSeries={rawSeries}isDashboarddiff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/nav.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/nav.tsxindex 306b6d7475b..5c0d635aebc 100644--- a/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/nav.tsx+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/nav.tsx@@ -3,51 +3,59 @@ import { t } from "ttag";import { AdminNavItem } from "metabase/admin/components/AdminNav";import { UpsellGem } from "metabase/common/components/upsells/components";import { useSetting } from "metabase/common/hooks";+import { hasPremiumFeature } from "metabase-enterprise/settings";++import { McpAnalyticsNavItem } from "../mcp-analytics/nav";export function getMetabotAnalyticsNavItems() {return <MetabotAnalyticsNavItems />;}-export function getMetabotAnalyticsUpsellNavItems() {- return <MetabotAnalyticsUpsellNavItems />;-}-+/**+ * The admin "Auditing" nav folder, registered under `audit_app`, so the folder and its+ * `audit_app`-gated MCP child appear whenever `audit_app` is present. The Metabot "Usage+ * stats"/Conversations children additionally need `ai-features-enabled?` and `ai_controls`;+ * without `ai_controls` an upsell-gem "Usage stats" stub is shown instead. `ai-features-enabled?`+ * gates only the Metabot children — never the folder, the upsell, or the MCP child.+ */function MetabotAnalyticsNavItems() {const isConfigured = useSetting("llm-metabot-configured?");const areAiFeaturesEnabled = useSetting("ai-features-enabled?");+ const mcpEnabled = useSetting("mcp-enabled?");+ const hasAiControls = hasPremiumFeature("ai_controls");- if (!areAiFeaturesEnabled) {- return null;- }+ const showMetabotStats = areAiFeaturesEnabled && hasAiControls;return (<AdminNavItemicon="audit"- label={t`Usage auditing`}+ label={t`Auditing`}folderPattern="usage-auditing"disabled={!isConfigured}>- <AdminNavItem- label={t`Stats`}- path="/admin/metabot/usage-auditing"- disabled={!isConfigured}- />- <AdminNavItem- label={t`Conversations`}- path="/admin/metabot/usage-auditing/conversations"- disabled={!isConfigured}- />+ {showMetabotStats ? (+ <>+ <AdminNavItem+ label={t`Usage stats`}+ path="/admin/metabot/usage-auditing"+ disabled={!isConfigured}+ />+ <AdminNavItem+ label={t`Conversations`}+ path="/admin/metabot/usage-auditing/conversations"+ disabled={!isConfigured}+ />+ </>+ ) : (+ !hasAiControls && (+ <AdminNavItem+ label={t`Usage stats`}+ path="/admin/metabot/usage-auditing"+ rightSection={<UpsellGem.New size={14} />}+ />+ )+ )}+ <McpAnalyticsNavItem mcpEnabled={mcpEnabled} /></AdminNavItem>);}--function MetabotAnalyticsUpsellNavItems() {- return (- <AdminNavItem- icon="audit"- label={t`Usage auditing`}- path="/admin/metabot/usage-auditing"- rightSection={<UpsellGem.New size={14} />}- />- );-}diff --git a/frontend/src/metabase/admin/ai/MetabotNavPane.unit.spec.tsx b/frontend/src/metabase/admin/ai/MetabotNavPane.unit.spec.tsxindex 146ecc2e055..2855d096e3c 100644--- a/frontend/src/metabase/admin/ai/MetabotNavPane.unit.spec.tsx+++ b/frontend/src/metabase/admin/ai/MetabotNavPane.unit.spec.tsx@@ -124,7 +124,7 @@ describe("MetabotNavPane", () => {).toHaveAttribute("href", "/admin/metabot/mcp/authorizations");});- it("displays the usage auditing upsell link when audit app is available and ai controls is unavailable", async () => {+ it("shows usage auditing as a folder with MCP analytics (audit app) and an upsell Stats when ai controls is unavailable", async () => {setup({aiControlsEnabled: false,auditAppEnabled: true,@@ -133,8 +133,62 @@ describe("MetabotNavPane", () => {expect(await screen.findByText("AI Settings")).toBeInTheDocument();+ // Expand "Auditing" to reveal its children+ await userEvent.click(await screen.findByText("Auditing"));++ // MCP analytics is available with audit_app alone (no ai_controls needed)+ expect(+ await screen.findByRole("link", { name: "MCP analytics" }),+ ).toHaveAttribute("href", "/admin/metabot/usage-auditing/mcp");++ // Metabot stats stays an upsell (still links to usage-auditing); Conversations needs ai_controls+ expect(screen.getByRole("link", { name: /Usage stats/ })).toHaveAttribute(+ "href",+ "/admin/metabot/usage-auditing",+ );+ expect(screen.queryByText("Conversations")).not.toBeInTheDocument();+ });++ it("keeps MCP analytics (and the upsell Stats) available when AI features are disabled", async () => {+ // Regression guard: `ai-features-enabled?` must gate only the Metabot children, never the+ // `audit_app`-gated MCP analytics child or the upsell stub.+ setup({+ aiControlsEnabled: false,+ auditAppEnabled: true,+ aiFeaturesEnabled: false,+ });++ await userEvent.click(await screen.findByText("Auditing"));++ expect(+ await screen.findByRole("link", { name: "MCP analytics" }),+ ).toHaveAttribute("href", "/admin/metabot/usage-auditing/mcp");+ expect(screen.getByRole("link", { name: /Usage stats/ })).toHaveAttribute(+ "href",+ "/admin/metabot/usage-auditing",+ );+ expect(screen.queryByText("Conversations")).not.toBeInTheDocument();+ });++ it("shows usage auditing with Stats, Conversations and MCP analytics when ai controls is available", async () => {+ setup({+ aiControlsEnabled: true,+ auditAppEnabled: true,+ aiFeaturesEnabled: true,+ });++ await userEvent.click(await screen.findByText("Auditing"));+expect(- screen.getByRole("link", { name: /Usage auditing/ }),+ await screen.findByRole("link", { name: "Usage stats" }),).toHaveAttribute("href", "/admin/metabot/usage-auditing");+ expect(screen.getByRole("link", { name: "Conversations" })).toHaveAttribute(+ "href",+ "/admin/metabot/usage-auditing/conversations",+ );+ expect(screen.getByRole("link", { name: "MCP analytics" })).toHaveAttribute(+ "href",+ "/admin/metabot/usage-auditing/mcp",+ );});});diff --git a/frontend/src/metabase/admin/routes.tsx b/frontend/src/metabase/admin/routes.tsxindex ff427b94bda..27b097502c6 100644--- a/frontend/src/metabase/admin/routes.tsx+++ b/frontend/src/metabase/admin/routes.tsx@@ -280,6 +280,7 @@ export const getRoutes = ({/* Metabot */}<Route path="metabot" component={createAdminRouteGuard("metabot")}>{PLUGIN_AUDIT.getAiAnalyticsRoutes()}+ {PLUGIN_AUDIT.getMcpAnalyticsRoutes()}<Route key="index-layout" component={MetabotAdminLayout}><IndexRoute key="index" component={AISettingsPage} /><Route key="mcp" path="mcp" component={McpSettingsPage} />diff --git a/frontend/src/metabase/plugins/oss/audit.ts b/frontend/src/metabase/plugins/oss/audit.tsindex 81d1a2284a2..248aa4099bd 100644--- a/frontend/src/metabase/plugins/oss/audit.ts+++ b/frontend/src/metabase/plugins/oss/audit.ts@@ -48,6 +48,7 @@ const getDefaultPluginAudit = () => ({InsightsMenuItem: PluginPlaceholder as ComponentType<InsightsMenuItemProps>,getMetabotAnalyticsNavItems: (): ReactNode => null,getAiAnalyticsRoutes: (): ReactNode => null,+ getMcpAnalyticsRoutes: (): ReactNode => null,handleMetabotSlashCommand: ((_args) => false) as MetabotSlashCommandHandler,});diff --git a/resources/migrations/064/20260623_mcp_usage_analytics.yaml b/resources/migrations/064/20260623_mcp_usage_analytics.yamlnew file mode 100644index 00000000000..3fc5ba01d16--- /dev/null+++ b/resources/migrations/064/20260623_mcp_usage_analytics.yaml@@ -0,0 +1,235 @@+## MCP Usage Analytics storage layer.+##+## Two tables modeled on the Metabot analytics pair:+## - mcp_session_log (one row per MCP session) ~ metabot_conversation+## - mcp_tool_call_log (one row per tools/call) ~ ai_usage_log+##+## `mcp_session_log` records per-session metadata (client identity + PII) for old-protocol+## clients. Client identity + PII are ALSO denormalized onto each `mcp_tool_call_log` row —+## resolved at call time — so `v_mcp_tool_calls` is self-contained (no session join) and keeps+## working under the upcoming MCP RC that drops sessions entirely. Row insertion is handled in+## the instrumentation ticket.++databaseChangeLog:+ - logicalFilePath: migrations/064_update_migrations.yaml++ - changeSet:+ id: v64.2026-06-23T00:00:00+ author: sfragnaud+ comment: Create mcp_session_log table+ changes:+ - createTable:+ tableName: mcp_session_log+ remarks: One row per MCP session; client identity + PII captured once at the initialize handshake (modeled on metabot_conversation)+ columns:+ - column:+ name: id+ type: varchar(254)+ remarks: MCP session id (primary key)+ constraints:+ primaryKey: true+ nullable: false+ - column:+ name: created_at+ type: ${timestamp_type}+ defaultValueComputed: current_timestamp+ remarks: When the session was opened (initialize handshake)+ constraints:+ nullable: false+ - column:+ name: ended_at+ type: ${timestamp_type}+ remarks: When the session was torn down (DELETE); NULL when the client never sent a clean teardown+ constraints:+ nullable: true+ - column:+ name: user_id+ type: int+ remarks: Metabase user behind the session; NULL for system/unauthenticated. Non-PII, always recorded.+ constraints:+ nullable: true+ - column:+ name: tenant_id+ type: int+ remarks: Snapshot of the user's tenant at session time; NULL for non-tenant users. Non-PII, always recorded.+ constraints:+ nullable: true+ - column:+ name: client_name+ type: varchar(255)+ remarks: Client name from the initialize handshake clientInfo (e.g. claude, chatgpt, cursor-vscode). Non-PII.+ constraints:+ nullable: true+ - column:+ name: client_version+ type: varchar(255)+ remarks: Client version from the initialize handshake clientInfo. Non-PII.+ constraints:+ nullable: true+ - column:+ name: ip_address+ type: varchar(45)+ remarks: Client IP captured at initialize, PII (gated by analytics-pii-retention-enabled).+ constraints:+ nullable: true+ - column:+ name: user_agent+ type: varchar(512)+ remarks: Raw User-Agent header captured at initialize, PII (gated).+ constraints:+ nullable: true+ rollback:+ - dropTable:+ tableName: mcp_session_log++ - changeSet:+ id: v64.2026-06-23T00:00:01+ author: sfragnaud+ comment: Index on mcp_session_log.user_id+ changes:+ - createIndex:+ indexName: idx_mcp_session_log_user_id+ tableName: mcp_session_log+ columns:+ - column:+ name: user_id+ rollback: # dropped with table++ - changeSet:+ id: v64.2026-06-23T00:00:02+ author: sfragnaud+ comment: Index on mcp_session_log.created_at+ changes:+ - createIndex:+ indexName: idx_mcp_session_log_created_at+ tableName: mcp_session_log+ columns:+ - column:+ name: created_at+ rollback: # dropped with table++ - changeSet:+ id: v64.2026-06-23T00:00:03+ author: sfragnaud+ comment: Create mcp_tool_call_log table+ changes:+ - createTable:+ tableName: mcp_tool_call_log+ remarks: One row per MCP tools/call; client identity + PII denormalized on so the view needs no session join (modeled on ai_usage_log)+ columns:+ - column:+ name: id+ type: bigint+ autoIncrement: true+ remarks: Autoincrement primary key+ constraints:+ primaryKey: true+ nullable: false+ - column:+ name: created_at+ type: ${timestamp_type}+ defaultValueComputed: current_timestamp+ remarks: When the tool call was made+ constraints:+ nullable: false+ - column:+ name: user_id+ type: int+ remarks: Metabase user who triggered the call; duplicated here for group-by convenience (mirrors ai_usage_log.user_id). Non-PII.+ constraints:+ nullable: true+ - column:+ name: tool_name+ type: varchar(255)+ remarks: Name of the MCP tool that was invoked+ constraints:+ nullable: false+ - column:+ name: status+ type: varchar(20)+ remarks: Outcome of the call, e.g. success or error+ constraints:+ nullable: true+ - column:+ name: duration_ms+ type: int+ remarks: Wall-clock duration of the tool call in milliseconds+ constraints:+ nullable: true+ - column:+ name: error_code+ type: int+ remarks: JSON-RPC error code for a failed tool call (e.g. -32602, -32603); NULL on success. Non-PII, always recorded.+ constraints:+ nullable: true+ - column:+ name: error_message+ type: ${text.type}+ remarks: JSON-RPC error message for a failed tool call, PII (gated by analytics-pii-retention-enabled, truncated); NULL on success or when gating is off.+ constraints:+ nullable: true+ - column:+ name: client_name+ type: varchar(255)+ remarks: Canonical MCP client key (claude/chatgpt/cursor-vscode/vscode/zed/other), resolved at call time from _meta clientInfo or the session's stored identity. Non-PII.+ constraints:+ nullable: true+ - column:+ name: client_version+ type: varchar(255)+ remarks: MCP client version, resolved at call time. Non-PII.+ constraints:+ nullable: true+ - column:+ name: tenant_id+ type: int+ remarks: Snapshot of the calling user's tenant at call time; NULL for non-tenant users. Non-PII.+ constraints:+ nullable: true+ - column:+ name: ip_address+ type: varchar(45)+ remarks: Client IP captured at call time, PII (gated by analytics-pii-retention-enabled).+ constraints:+ nullable: true+ - column:+ name: user_agent+ type: varchar(512)+ remarks: Raw User-Agent captured at call time, PII (gated).+ constraints:+ nullable: true+ - column:+ name: sanitized_user_agent+ type: varchar(512)+ remarks: Sanitized (browser/OS) User-Agent descriptor, PII (gated).+ constraints:+ nullable: true+ rollback:+ - dropTable:+ tableName: mcp_tool_call_log++ - changeSet:+ id: v64.2026-06-23T00:00:04+ author: sfragnaud+ comment: Index on mcp_tool_call_log.user_id+ changes:+ - createIndex:+ indexName: idx_mcp_tool_call_log_user_id+ tableName: mcp_tool_call_log+ columns:+ - column:+ name: user_id+ rollback: # dropped with table++ - changeSet:+ id: v64.2026-06-23T00:00:06+ author: sfragnaud+ comment: Index on mcp_tool_call_log.created_at+ changes:+ - createIndex:+ indexName: idx_mcp_tool_call_log_created_at+ tableName: mcp_tool_call_log+ columns:+ - column:+ name: created_at+ rollback: # dropped with tablediff --git a/resources/migrations/064/20260623_mcp_usage_analytics_view.yaml b/resources/migrations/064/20260623_mcp_usage_analytics_view.yamlnew file mode 100644index 00000000000..8c7a81696b8--- /dev/null+++ b/resources/migrations/064/20260623_mcp_usage_analytics_view.yaml@@ -0,0 +1,33 @@+## Create the v_mcp_tool_calls view for MCP usage analytics.+##+## Filename intentionally sorts after 20260623_mcp_usage_analytics.yaml (the table-creation+## migration) so Liquibase — which processes change-log files alphabetically — creates the+## mcp_tool_call_log / mcp_session_log tables before this view references them.+##+## Client identity + PII are denormalized onto each tool-call row, so v_mcp_tool_calls reads them+## straight off mcp_tool_call_log (no session join) and stays valid once the MCP RC drops sessions.+## It LEFT JOINs core_user (for the display name) and the tenant table (for tenant_name).++databaseChangeLog:+ - logicalFilePath: migrations/064_update_migrations.yaml++ - changeSet:+ id: v64.2026-06-23T00:00:10+ author: sfragnaud+ runOnChange: true+ comment: Create v_mcp_tool_calls view for MCP usage analytics+ changes:+ - sqlFile:+ dbms: postgresql+ path: ../instance_analytics_views/mcp_tool_calls/v1/postgres-mcp_tool_calls.sql+ relativeToChangelogFile: true+ - sqlFile:+ dbms: mysql,mariadb+ path: ../instance_analytics_views/mcp_tool_calls/v1/mysql-mcp_tool_calls.sql+ relativeToChangelogFile: true+ - sqlFile:+ dbms: h2+ path: ../instance_analytics_views/mcp_tool_calls/v1/h2-mcp_tool_calls.sql+ relativeToChangelogFile: true+ rollback:+ - sql: DROP VIEW IF EXISTS v_mcp_tool_callsdiff --git a/resources/migrations/instance_analytics_views/mcp_tool_calls/v1/h2-mcp_tool_calls.sql b/resources/migrations/instance_analytics_views/mcp_tool_calls/v1/h2-mcp_tool_calls.sqlnew file mode 100644index 00000000000..056ff34b52a--- /dev/null+++ b/resources/migrations/instance_analytics_views/mcp_tool_calls/v1/h2-mcp_tool_calls.sql@@ -0,0 +1,52 @@+DROP VIEW IF EXISTS v_mcp_tool_calls;++CREATE OR REPLACE VIEW v_mcp_tool_calls AS+SELECT+ t.id AS tool_call_id,+ t.created_at,+ t.tool_name,+ t.status,+ -- NOTE: keep these CASE branches in sync with the error-code-* constants in+ -- src/metabase/mcp/tools.clj (the enum-<->-CASE sync footgun).+ CASE t.error_code+ WHEN -32600 THEN 'Invalid request'+ WHEN -32601 THEN 'Method not found'+ WHEN -32602 THEN 'Invalid params'+ WHEN -32603 THEN 'Internal error'+ WHEN -32000 THEN 'Server error'+ ELSE NULL+ END AS error_type,+ t.error_message AS error_message,+ t.duration_ms,+ t.user_id,+ COALESCE(u.first_name || ' ' || u.last_name, u.email) AS user_display_name,+ (SELECT pg.name+ FROM permissions_group_membership pgm+ JOIN permissions_group pg ON pg.id = pgm.group_id+ WHERE pgm.user_id = t.user_id+ AND pg.id != 1+ ORDER BY pg.name+ LIMIT 1) AS group_name,+ t.client_name AS client_name,+ -- NOTE: keep these CASE branches in sync with `supported-client-keys` /+ -- `detect-client` in src/metabase/mcp/usage.clj (the enum-<->-CASE sync footgun).+ CASE t.client_name+ WHEN 'claude' THEN 'Claude'+ WHEN 'chatgpt' THEN 'ChatGPT'+ WHEN 'cursor-vscode' THEN 'Cursor'+ WHEN 'vscode' THEN 'VS Code'+ WHEN 'zed' THEN 'Zed'+ WHEN 'other' THEN 'Other'+ ELSE t.client_name+ END AS client_display_name,+ t.client_version AS client_version,+ t.tenant_id AS tenant_id,+ tn.name AS tenant_name,+ t.ip_address AS ip_address,+ t.user_agent AS user_agent,+ t.sanitized_user_agent AS sanitized_user_agent+FROM mcp_tool_call_log t+LEFT JOIN core_user u+ ON u.id = t.user_id+LEFT JOIN tenant tn+ ON tn.id = t.tenant_id;diff --git a/resources/migrations/instance_analytics_views/mcp_tool_calls/v1/mysql-mcp_tool_calls.sql b/resources/migrations/instance_analytics_views/mcp_tool_calls/v1/mysql-mcp_tool_calls.sqlnew file mode 100644index 00000000000..2daa87388c8--- /dev/null+++ b/resources/migrations/instance_analytics_views/mcp_tool_calls/v1/mysql-mcp_tool_calls.sql@@ -0,0 +1,52 @@+DROP VIEW IF EXISTS v_mcp_tool_calls;++CREATE OR REPLACE VIEW v_mcp_tool_calls AS+SELECT+ t.id AS tool_call_id,+ t.created_at,+ t.tool_name,+ t.status,+ -- NOTE: keep these CASE branches in sync with the error-code-* constants in+ -- src/metabase/mcp/tools.clj (the enum-<->-CASE sync footgun).+ CASE t.error_code+ WHEN -32600 THEN 'Invalid request'+ WHEN -32601 THEN 'Method not found'+ WHEN -32602 THEN 'Invalid params'+ WHEN -32603 THEN 'Internal error'+ WHEN -32000 THEN 'Server error'+ ELSE NULL+ END AS error_type,+ t.error_message AS error_message,+ t.duration_ms,+ t.user_id,+ COALESCE(CONCAT(u.first_name, ' ', u.last_name), u.email) AS user_display_name,+ (SELECT pg.name+ FROM permissions_group_membership pgm+ JOIN permissions_group pg ON pg.id = pgm.group_id+ WHERE pgm.user_id = t.user_id+ AND pg.id != 1+ ORDER BY pg.name+ LIMIT 1) AS group_name,+ t.client_name AS client_name,+ -- NOTE: keep these CASE branches in sync with `supported-client-keys` /+ -- `detect-client` in src/metabase/mcp/usage.clj (the enum-<->-CASE sync footgun).+ CASE t.client_name+ WHEN 'claude' THEN 'Claude'+ WHEN 'chatgpt' THEN 'ChatGPT'+ WHEN 'cursor-vscode' THEN 'Cursor'+ WHEN 'vscode' THEN 'VS Code'+ WHEN 'zed' THEN 'Zed'+ WHEN 'other' THEN 'Other'+ ELSE t.client_name+ END AS client_display_name,+ t.client_version AS client_version,+ t.tenant_id AS tenant_id,+ tn.name AS tenant_name,+ t.ip_address AS ip_address,+ t.user_agent AS user_agent,+ t.sanitized_user_agent AS sanitized_user_agent+FROM mcp_tool_call_log t+LEFT JOIN core_user u+ ON u.id = t.user_id+LEFT JOIN tenant tn+ ON tn.id = t.tenant_id;diff --git a/resources/migrations/instance_analytics_views/mcp_tool_calls/v1/postgres-mcp_tool_calls.sql b/resources/migrations/instance_analytics_views/mcp_tool_calls/v1/postgres-mcp_tool_calls.sqlnew file mode 100644index 00000000000..056ff34b52a--- /dev/null+++ b/resources/migrations/instance_analytics_views/mcp_tool_calls/v1/postgres-mcp_tool_calls.sql@@ -0,0 +1,52 @@+DROP VIEW IF EXISTS v_mcp_tool_calls;++CREATE OR REPLACE VIEW v_mcp_tool_calls AS+SELECT+ t.id AS tool_call_id,+ t.created_at,+ t.tool_name,+ t.status,+ -- NOTE: keep these CASE branches in sync with the error-code-* constants in+ -- src/metabase/mcp/tools.clj (the enum-<->-CASE sync footgun).+ CASE t.error_code+ WHEN -32600 THEN 'Invalid request'+ WHEN -32601 THEN 'Method not found'+ WHEN -32602 THEN 'Invalid params'+ WHEN -32603 THEN 'Internal error'+ WHEN -32000 THEN 'Server error'+ ELSE NULL+ END AS error_type,+ t.error_message AS error_message,+ t.duration_ms,+ t.user_id,+ COALESCE(u.first_name || ' ' || u.last_name, u.email) AS user_display_name,+ (SELECT pg.name+ FROM permissions_group_membership pgm+ JOIN permissions_group pg ON pg.id = pgm.group_id+ WHERE pgm.user_id = t.user_id+ AND pg.id != 1+ ORDER BY pg.name+ LIMIT 1) AS group_name,+ t.client_name AS client_name,+ -- NOTE: keep these CASE branches in sync with `supported-client-keys` /+ -- `detect-client` in src/metabase/mcp/usage.clj (the enum-<->-CASE sync footgun).+ CASE t.client_name+ WHEN 'claude' THEN 'Claude'+ WHEN 'chatgpt' THEN 'ChatGPT'+ WHEN 'cursor-vscode' THEN 'Cursor'+ WHEN 'vscode' THEN 'VS Code'+ WHEN 'zed' THEN 'Zed'+ WHEN 'other' THEN 'Other'+ ELSE t.client_name+ END AS client_display_name,+ t.client_version AS client_version,+ t.tenant_id AS tenant_id,+ tn.name AS tenant_name,+ t.ip_address AS ip_address,+ t.user_agent AS user_agent,+ t.sanitized_user_agent AS sanitized_user_agent+FROM mcp_tool_call_log t+LEFT JOIN core_user u+ ON u.id = t.user_id+LEFT JOIN tenant tn+ ON tn.id = t.tenant_id;diff --git a/src/metabase/mcp/api.clj b/src/metabase/mcp/api.cljindex 629cfe34ca3..834447e3860 100644--- a/src/metabase/mcp/api.clj+++ b/src/metabase/mcp/api.clj@@ -12,6 +12,7 @@[metabase.mcp.resources :as mcp.resources][metabase.mcp.session :as mcp.session][metabase.mcp.tools :as mcp.tools]+ [metabase.mcp.usage :as mcp.usage][metabase.mcp.validation :as mcp.validation][metabase.oauth-server.core :as oauth-server][metabase.request.core :as request]@@ -73,16 +74,21 @@(jsonrpc-response id {:tools (mcp.tools/list-tools token-scopes {:supports-mcp-ui?supports-mcp-ui?})})))-(defn- handle-tools-call [id params session-id token-scopes]- (let [tool-name (:name params)- arguments (or (:arguments params) {})+(defn- handle-tools-call [id params session-id token-scopes request-context]+ (let [tool-name (:name params)+ arguments (or (:arguments params) {})+ ;; RC clients carry their identity per-call in `_meta`; the recorder falls back to the+ ;; session's stored identity when it's absent. (`json/decode+kw` preserves the slash in+ ;; the extension key, so it's the namespaced keyword `:io.modelcontextprotocol/clientInfo`.)+ client-info (get-in params [:_meta :io.modelcontextprotocol/clientInfo])supports-mcp-ui? (mcp.session/supports-mcp-ui? session-id)](jsonrpc-response id (mcp.tools/call-tool token-scopessession-idtool-namearguments- {:supports-mcp-ui?- supports-mcp-ui?}))))+ {:supports-mcp-ui? supports-mcp-ui?+ :client-info client-info+ :request-context request-context}))))(defn- handle-resources-list [id _params token-scopes](jsonrpc-response id (mcp.resources/list-resources token-scopes)))@@ -105,12 +111,12 @@(defn- dispatch-request"Dispatch a single JSON-RPC request. Returns a response map or nil for notifications."- [{:keys [id method params] :as _msg} session-id token-scopes]+ [{:keys [id method params] :as _msg} session-id token-scopes request-context](try(case method"notifications/initialized" nil"tools/list" (handle-tools-list id params session-id token-scopes)- "tools/call" (handle-tools-call id params session-id token-scopes)+ "tools/call" (handle-tools-call id params session-id token-scopes request-context)"resources/list" (handle-resources-list id params token-scopes)"resources/read" (handle-resources-read id params session-id token-scopes)"ping" (handle-ping id params)@@ -240,7 +246,16 @@supports-mcp-ui? (mcp-app-ui-capability? params)session-id (mcp.session/create! user-id {:supports-mcp-ui?supports-mcp-ui?})- init-response (handle-initialize (:id body) (:params body))]+ init-response (handle-initialize (:id body) params)]+ ;; Record the session row (EE-only, best-effort). Identity + PII are captured once+ ;; here, from the on-thread request, and never overwritten.+ (mcp.usage/record-mcp-session!+ {:session-id session-id+ :user-id user-id+ :tenant-id (some-> api/*current-user* deref :tenant_id)+ :client-info (:clientInfo params)+ :user-agent (get-in request [:headers "user-agent"])+ :ip-address (request/ip-address request)})(if (accepts-sse? request)(sse-response [init-response] {"Mcp-Session-Id" session-id})(json-response 200 init-response {"Mcp-Session-Id" session-id})))@@ -250,8 +265,12 @@(let [{:keys [error]} (require-valid-session user-id session-id)](if errorerror- (let [messages (if batch? body [body])- responses (into [] (keep #(dispatch-request % session-id (:token-scopes request))) messages)]+ (let [messages (if batch? body [body])+ ;; Captured on-thread from the request so each tool-call row can denormalize IP/UA+ ;; (gated PII) alongside client identity — the view no longer joins the session.+ request-context {:user-agent (get-in request [:headers "user-agent"])+ :ip-address (request/ip-address request)}+ responses (into [] (keep #(dispatch-request % session-id (:token-scopes request) request-context)) messages)](cond(empty? responses){:status 202 :headers {} :body ""}@@ -308,6 +327,8 @@{:keys [session-id error]} (require-valid-session user-id session-id-header)](or error(do (mcp.session/delete! session-id user-id)+ ;; Stamp ended_at on the session row (EE-only, best-effort).+ (mcp.usage/record-mcp-session-end! session-id){:status 200 :headers {"Content-Type" "application/json"} :body ""}))));;; -------------------------------------------------- Throttling --------------------------------------------------diff --git a/src/metabase/mcp/models/mcp_session_log.clj b/src/metabase/mcp/models/mcp_session_log.cljnew file mode 100644index 00000000000..35d9dc0e8fa--- /dev/null+++ b/src/metabase/mcp/models/mcp_session_log.clj@@ -0,0 +1,9 @@+(ns metabase.mcp.models.mcp-session-log+ (:require+ [methodical.core :as methodical]+ [toucan2.core :as t2]))++(methodical/defmethod t2/table-name :model/McpSessionLog [_model] :mcp_session_log)++(doto :model/McpSessionLog+ (derive :metabase/model))diff --git a/src/metabase/mcp/models/mcp_tool_call_log.clj b/src/metabase/mcp/models/mcp_tool_call_log.cljnew file mode 100644index 00000000000..5cd166e27f7--- /dev/null+++ b/src/metabase/mcp/models/mcp_tool_call_log.clj@@ -0,0 +1,9 @@+(ns metabase.mcp.models.mcp-tool-call-log+ (:require+ [methodical.core :as methodical]+ [toucan2.core :as t2]))++(methodical/defmethod t2/table-name :model/McpToolCallLog [_model] :mcp_tool_call_log)++(doto :model/McpToolCallLog+ (derive :metabase/model))diff --git a/src/metabase/mcp/tools.clj b/src/metabase/mcp/tools.cljindex 63f052394fa..bda75b1fdd2 100644--- a/src/metabase/mcp/tools.clj+++ b/src/metabase/mcp/tools.clj@@ -12,6 +12,7 @@[metabase.mcp.resources :as mcp.resources][metabase.mcp.scope :as mcp.scope][metabase.mcp.session :as mcp.session]+ [metabase.mcp.usage :as mcp.usage][metabase.server.streaming-response :as streaming-response][metabase.util :as u][metabase.util.json :as json]@@ -348,10 +349,21 @@(cond-> {:content [{:type "text" :text (if (string? v) v (json/encode v))}]}(or (map? v) (sequential? v)) (assoc :structuredContent v)))+;; JSON-RPC error codes recorded as `mcp_tool_call_log.error_code` for failed tool calls.+;; Kept in sync with the `error_code` -> `error_type` CASE in the v_mcp_tool_calls view SQL. The+;; view also maps -32000 ("Server error") defensively (JSON-RPC reserves -32000..-32099), but the+;; recorder never emits it, so there's no constant for it here.+(def ^:private error-code-invalid-request -32600)+(def ^:private error-code-method-not-found -32601)+(def ^:private error-code-invalid-params -32602)+(def ^:private error-code-internal -32603)+(defn- error-content- "Wrap an error message as MCP error content."- [message]- {:content [{:type "text" :text message}] :isError true})+ "Wrap an error message as MCP error content. The JSON-RPC `code` (default: internal error) is+ carried under a namespaced key for usage logging and stripped from the response before it+ reaches the client (see [[call-tool]])."+ ([message] (error-content message error-code-internal))+ ([message code] {:content [{:type "text" :text message}] :isError true ::error-code code}))(comment streaming-response/keep-me) ; ensure StreamingResponse class is loaded@@ -485,36 +497,78 @@(when arguments(into {} (remove (comp nil? val)) arguments)))+(defn- dispatch-tool-call+ "Resolve and invoke the handler for an MCP `tools/call`, returning MCP content on success+ or error content on failure. The instrumented [[call-tool]] wraps this."+ [token-scopes session-id tool-name arguments options]+ (let [arguments (drop-nil-args arguments)+ supported (supported-extensions options)]+ (if-let [ui-tool (some #(when (= tool-name (:name %)) %) (mcp.resources/list-ui-tools))]+ (if-not (mcp.scope/matches? token-scopes (:scope ui-tool))+ (error-content (str "Insufficient scope to call tool: " tool-name) error-code-invalid-request)+ (if-let [missing-extensions (missing-required-extensions ui-tool supported)]+ (error-content (missing-extensions-error tool-name missing-extensions) error-code-invalid-params)+ ((:response-fn ui-tool) arguments {:session-id session-id})))+ (if-let [tool-def (get (tool-index) tool-name)]+ (if-not (mcp.scope/matches? token-scopes (:scope tool-def))+ (error-content (str "Insufficient scope to call tool: " tool-name) error-code-invalid-request)+ (if-let [missing-extensions (missing-required-extensions tool-def supported)]+ (error-content (missing-extensions-error tool-name missing-extensions) error-code-invalid-params)+ (let [arguments (if (tools-accepting-query-handle tool-name)+ (resolve-query-arg session-id tool-name arguments)+ arguments)]+ (if (= arguments ::handle-not-found)+ (error-content "Query handle not found. The query may have expired — try running construct_query again." error-code-invalid-params)+ (try+ (dispatch-via-agent-api tool-def arguments token-scopes session-id)+ (catch Exception e+ (error-content (or (ex-message e) "Internal error") error-code-internal)))))))+ (error-content (str "Unknown tool: " tool-name) error-code-method-not-found)))))+(defn call-tool"Dispatch an MCP `tools/call` request to the appropriate handler.`token-scopes` from the original MCP session are propagated to the syntheticagent-api request so that scope restrictions are enforced by the agent API's`defendpoint` middleware. UI tool response-fns receive `{:session-id session-id}`as opts in case a tool needs to scope reads to the calling MCP session.- Returns MCP content on success, or error content on failure."+ Returns MCP content on success, or error content on failure.++ Every call — including scope-denied, unknown-tool, and error outcomes — is recorded to+ `mcp_tool_call_log` (EE-only, best-effort) with its timing, success/error status, and on+ error the JSON-RPC `error_code` + `error_message` (the latter gated/truncated by the writer)."([token-scopes session-id tool-name arguments](call-tool token-scopes session-id tool-name arguments {:supports-mcp-ui? true}))([token-scopes session-id tool-name arguments options]- (let [arguments (drop-nil-args arguments)- supported (supported-extensions options)]- (if-let [ui-tool (some #(when (= tool-name (:name %)) %) (mcp.resources/list-ui-tools))]- (if-not (mcp.scope/matches? token-scopes (:scope ui-tool))- (error-content (str "Insufficient scope to call tool: " tool-name))- (if-let [missing-extensions (missing-required-extensions ui-tool supported)]- (error-content (missing-extensions-error tool-name missing-extensions))- ((:response-fn ui-tool) arguments {:session-id session-id})))- (if-let [tool-def (get (tool-index) tool-name)]- (if-not (mcp.scope/matches? token-scopes (:scope tool-def))- (error-content (str "Insufficient scope to call tool: " tool-name))- (if-let [missing-extensions (missing-required-extensions tool-def supported)]- (error-content (missing-extensions-error tool-name missing-extensions))- (let [arguments (if (tools-accepting-query-handle tool-name)- (resolve-query-arg session-id tool-name arguments)- arguments)]- (if (= arguments ::handle-not-found)- (error-content "Query handle not found. The query may have expired — try running construct_query again.")- (try- (dispatch-via-agent-api tool-def arguments token-scopes session-id)- (catch Exception e- (error-content (or (ex-message e) "Internal error"))))))))- (error-content (str "Unknown tool: " tool-name)))))))+ (let [start (System/nanoTime)+ record! (fn [status error-code error-message]+ (mcp.usage/record-mcp-tool-call!+ {:tool-name tool-name+ :user-id api/*current-user-id*+ :session-id session-id+ :status status+ :duration-ms (quot (- (System/nanoTime) start) 1000000)+ :error-code error-code+ :error-message error-message+ ;; Identity + PII are denormalized onto the row (the view no longer joins the+ ;; session): client from the call's `_meta`, tenant from the current user,+ ;; IP/UA from the request. The recorder falls back to the session row's stored+ ;; client when `_meta` carries none, and gates the PII columns.+ :client-info (:client-info options)+ :tenant-id (some-> api/*current-user* deref :tenant_id)+ :user-agent (get-in options [:request-context :user-agent])+ :ip-address (get-in options [:request-context :ip-address])}))]+ (try+ (let [result (dispatch-tool-call token-scopes session-id tool-name arguments options)+ error? (boolean (:isError result))]+ (record! (if error? "error" "success")+ (when error? (or (::error-code result) error-code-internal))+ (when error? (some-> result :content first :text)))+ ;; `::error-code` is an internal classification marker — never expose it to the client.+ (dissoc result ::error-code))+ (catch Throwable e+ ;; A handler that throws instead of returning error content (notably a UI tool+ ;; `:response-fn`, whose path isn't wrapped in `dispatch-tool-call`) would otherwise+ ;; skip instrumentation and under-report errors. Record the failure, then rethrow so the+ ;; transport layer still surfaces it to the client.+ (record! "error" error-code-internal (ex-message e))+ (throw e))))))diff --git a/src/metabase/mcp/usage.clj b/src/metabase/mcp/usage.cljnew file mode 100644index 00000000000..2164ca9e72a--- /dev/null+++ b/src/metabase/mcp/usage.clj@@ -0,0 +1,100 @@+(ns metabase.mcp.usage+ "MCP usage logging.++ Three write points feed the MCP analytics tables: the session row at the `initialize`+ handshake, its `ended_at` stamp at session teardown, and one lean tool-call row per+ `tools/call`. All three are `defenterprise` no-ops in OSS — an OSS instance records+ nothing — with the real inserts in `metabase-enterprise.mcp.usage`. Like `ai_usage_log`,+ collection runs on every EE instance (`:feature :none`); the `:audit-app` feature gates+ the surfaces that read these rows (the audit view + page), not the writing.++ PII columns are populated only when `analytics-pii-retention-enabled` is on — a setting+ that is itself `:audit-app`-gated and defaults off, so PII is never collected without+ `:audit-app`. `client_name` is derived from the `initialize` handshake `clientInfo`+ (authoritative), never from User-Agent parsing."+ (:require+ [clojure.string :as str]+ [metabase.premium-features.core :refer [defenterprise]]+ [metabase.util :as u]))++(def supported-client-keys+ "Canonical MCP client keys [[detect-client]] classifies into for analytics. Keep in sync with+ the `client_name` CASE in the `v_mcp_tool_calls` view SQL (the enum-<->-CASE sync footgun)."+ #{"claude" "chatgpt" "cursor-vscode" "vscode" "zed"})++(def ^:private client-name-matchers+ "Ordered `[substring canonical-key]` pairs matched against the lowercased handshake+ `clientInfo.name` (after stripping any mcp-remote wrapper). First match wins. Both the+ spelled-out and compact forms of multi-word clients are listed so the fuzzy pass can catch+ abbreviations (e.g. `\"VS Code\"`)."+ [["claude" "claude"]+ ["chatgpt" "chatgpt"]+ ["openai" "chatgpt"]+ ["cursor" "cursor-vscode"]+ ["visual studio code" "vscode"]+ ["vscode" "vscode"]+ ["zed" "zed"]])++(def ^:private mcp-remote-wrapper-re+ "`mcp-remote` rewrites the handshake name to `\"<name> (via mcp-remote x.y.z)\"`; the strict+ pass strips that suffix so the real client name is what gets classified."+ #"\s*\(via mcp-remote[^)]*\)\s*$")++(def ^:private proxy-wrapper-re+ "A generic `\"(via <proxy> …)\"` suffix that MCP proxies append to the client name; the fuzzy+ pass strips any such wrapper so an unfamiliar proxy format never hides the client name."+ #"\s*\(via[^)]*\)\s*$")++(defn- normalize-client-name+ "Lowercase and drop everything but letters/digits, so spacing/punctuation variants+ (`\"VS Code\"`, `\"chat-gpt\"`) collapse to one comparable token."+ [s]+ (some-> s u/lower-case-en (str/replace #"[^a-z0-9]+" "")))++(def ^:private proxy-probe-client-name+ "`mcp-remote` opens a throwaway probe connection under this exact name while negotiating+ transports. It is never a real client and must not be recorded as a session."+ "mcp-remote-fallback-test")++(defn proxy-probe?+ "True when the `initialize` handshake is `mcp-remote`'s transport-probe connection, which is+ not a real client session and should be ignored for analytics."+ [client-info-name]+ (= (some-> client-info-name u/lower-case-en) proxy-probe-client-name))++(defn detect-client+ "Classify the `initialize`-handshake `clientInfo` name into a canonical client key (one of+ [[supported-client-keys]]), or `\"other\"` when nothing matches. Runs a strict substring match+ first (mcp-remote wrapper stripped); when that finds nothing, falls back to a fuzzier match+ that ignores spacing/punctuation and strips any generic `(via …)` proxy wrapper, so variant+ spellings and unfamiliar proxy formats still classify. Identity comes from the handshake name,+ never User-Agent parsing."+ [client-info-name]+ (let [strict (some-> client-info-name u/lower-case-en (str/replace mcp-remote-wrapper-re ""))+ fuzzy (some-> client-info-name (str/replace proxy-wrapper-re "") normalize-client-name)]+ (or (when strict+ (some (fn [[needle k]] (when (str/includes? strict needle) k)) client-name-matchers))+ (when fuzzy+ (some (fn [[needle k]]+ (when (str/includes? fuzzy (normalize-client-name needle)) k))+ client-name-matchers))+ "other")))++(defenterprise record-mcp-session!+ "Upsert an `mcp_session_log` row at the MCP `initialize` handshake. Identity + PII are+ written once and never overwritten. OSS no-op."+ metabase-enterprise.mcp.usage+ [_session-info]+ nil)++(defenterprise record-mcp-session-end!+ "Stamp `ended_at` on an `mcp_session_log` row at session teardown. OSS no-op."+ metabase-enterprise.mcp.usage+ [_session-id]+ nil)++(defenterprise record-mcp-tool-call!+ "Write a lean `mcp_tool_call_log` row for a `tools/call`. OSS no-op."+ metabase-enterprise.mcp.usage+ [_tool-call-info]+ nil)diff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.cljindex 1d76661d95e..1e20bc67f8c 100644--- a/src/metabase/models/resolution.clj+++ b/src/metabase/models/resolution.clj@@ -57,6 +57,8 @@:model/ImplicitAction metabase.actions.models:model/LoginHistory metabase.login-history.models.login-history:model/McpQueryHandle metabase.mcp.models.mcp-query-handle+ :model/McpSessionLog metabase.mcp.models.mcp-session-log+ :model/McpToolCallLog metabase.mcp.models.mcp-tool-call-log:model/Measure metabase.measures.models.measure:model/Metabot metabase.metabot.models.metabot:model/MetabotConversation metabase.metabot.models.metabot-conversationdiff --git a/src/metabase/testing_api/api.clj b/src/metabase/testing_api/api.cljindex d863e8b64fc..7a04901d902 100644--- a/src/metabase/testing_api/api.clj+++ b/src/metabase/testing_api/api.clj@@ -15,6 +15,7 @@[metabase.lib.schema :as lib.schema][metabase.lib.schema.id :as lib.schema.id][metabase.lib.schema.test-spec :as lib.schema.test-spec]+ [metabase.mcp.usage :as mcp.usage][metabase.permissions.core :as perms][metabase.premium-features.core :refer [defenterprise]][metabase.search.core :as search]@@ -556,3 +557,40 @@[:tenant_id {:optional true} [:maybe ms/PositiveInt]][:second_tenant_id {:optional true} [:maybe ms/PositiveInt]]]](seed-usage-auditing-data! user_id second_user_id tenant_id second_tenant_id))++(api.macros/defendpoint :post "/mcp/seed-tool-call"+ :- [:map+ [:session_id ms/NonBlankString]+ [:tool_name ms/NonBlankString]]+ "Seed one `mcp_session_log` + one `mcp_tool_call_log` row so the MCP analytics E2E page has a+ visible tool-call row. Routes through the production `metabase.mcp.usage` recording helpers+ (rather than hand-rolled inserts) so the seeded rows can't drift from real MCP writes.+ Intended only for E2E tests."+ [_route-params+ _query-params+ {:keys [user_id tool_name client_name client_version status error_code error_message duration_ms]}+ :- [:map+ [:user_id ms/PositiveInt]+ [:tool_name {:optional true} [:maybe ms/NonBlankString]]+ [:client_name {:optional true} [:maybe ms/NonBlankString]]+ [:client_version {:optional true} [:maybe ms/NonBlankString]]+ [:status {:optional true} [:maybe ms/NonBlankString]]+ [:error_code {:optional true} [:maybe :int]]+ [:error_message {:optional true} [:maybe ms/NonBlankString]]+ [:duration_ms {:optional true} [:maybe ms/IntGreaterThanOrEqualToZero]]]]+ (let [session-id (str "e2e-mcp-" (random-uuid))+ tool-name (or tool_name "execute_query")]+ (mcp.usage/record-mcp-session!+ {:session-id session-id+ :user-id user_id+ :client-info {:name (or client_name "claude")+ :version (or client_version "1.0.0")}})+ (mcp.usage/record-mcp-tool-call!+ {:tool-name tool-name+ :user-id user_id+ :session-id session-id+ :status (or status "success")+ :duration-ms (or duration_ms 42)+ :error-code error_code+ :error-message error_message})+ {:session_id session-id :tool_name tool-name}))diff --git a/test/metabase/cmd/copy_test.clj b/test/metabase/cmd/copy_test.cljindex b05e5e88a70..6704cb3a74d 100644--- a/test/metabase/cmd/copy_test.clj+++ b/test/metabase/cmd/copy_test.clj@@ -39,6 +39,8 @@:model/Dependency:model/DependencyStatus:model/McpQueryHandle+ :model/McpSessionLog+ :model/McpToolCallLog:model/MetabotConversation:model/MetabotGroupLimit:model/MetabotInstanceLimitdiff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.cljindex 463999cc335..b515183a284 100644--- a/test/metabase/mcp/api_test.clj+++ b/test/metabase/mcp/api_test.clj@@ -1315,7 +1315,7 @@(defn- dispatch-initialized-request [msg token-scopes](let [session-id (str (random-uuid))]- (#'mcp.api/dispatch-request msg session-id token-scopes)))+ (#'mcp.api/dispatch-request msg session-id token-scopes nil)))(defn- with-scoped-test-resource! [f](let [registry @#'mcp.resources/registry@@ -1361,7 +1361,8 @@(let [response (#'mcp.api/dispatch-request(jsonrpc-request "resources/list")"session-id"- #{"agent:other"})+ #{"agent:other"}+ nil)uris (set (map :uri (get-in response [:result :resources])))](is (contains? uris construct-query-uri)"public construct-query reference is still listed")@@ -1373,7 +1374,8 @@(let [response (#'mcp.api/dispatch-request(jsonrpc-request "resources/list")"session-id"- #{"agent:search"})+ #{"agent:search"}+ nil)uris (set (map :uri (get-in response [:result :resources])))](is (contains? uris scoped-test-uri)))))))